Compare commits

...

12 Commits

Author SHA1 Message Date
malle-pietje
14f4d58b02 minor bugs removed from two examples 2018-02-01 17:11:05 +01:00
malle-pietje
77972aab55 removed donation section from README (...) 2018-02-01 17:04:13 +01:00
malle-pietje
9629cc909d Merge branch 'master' of github.com:Art-of-WiFi/UniFi-API-client 2018-02-01 16:57:18 +01:00
malle-pietje
f6201ec21c minor changes
added an example to update WLAN settings for recent controllers (5.5.X and higher)
2018-02-01 16:56:17 +01:00
malle-pietje
dcf7d2059c removed some spaces for cosmetic reasons only 2018-01-29 13:36:13 +01:00
malle-pietje
7a5e2b5bbb Merge pull request #7 from JaspervRijbroek/master
Allow for extendibility. Thanks to @JaspervRijbroek
2018-01-29 13:34:06 +01:00
Jasper van Rijbroek
1db9040ea8 Allow for extendibility. 2018-01-20 15:46:04 +01:00
malle-pietje
cab0c1a35d Update README.md 2017-10-26 17:14:39 +02:00
malle-pietje
2b5ed31759 Update README.md 2017-10-26 17:12:51 +02:00
malle-pietje
a13ff36409 Merge branch 'master' of github.com:Art-of-WiFi/UniFi-API-client 2017-10-26 17:07:48 +02:00
malle-pietje
c4bc1243eb - minor code cleanup and input validation/sanitization improvements
- added delete_device() function/method
- added move_device() function/method
- added optional `type` parameter to stat_sessions()
- updated README
2017-10-26 17:06:59 +02:00
malle-pietje
c25f4d1937 Update disable_device.php 2017-10-20 09:25:59 +02:00
6 changed files with 260 additions and 38 deletions

View File

@@ -1,18 +1,13 @@
## UniFi Controller API client class
A PHP class which provides access to Ubiquiti's **UniFi Controller API**, versions 4.x.x and 5.x.x of the UniFi Controller software are supported (version 5.6.18 has been confirmed to work). It's a standalone version of the class which is used in our API browser tool [here](https://github.com/Art-of-WiFi/UniFi-API-browser).
A PHP class which provides access to Ubiquiti's **UniFi Controller API**, versions 4.x.x and 5.x.x of the UniFi Controller software are supported (version 5.6.29 has been confirmed to work). It's a standalone version of the class which is used in our API browser tool which can be found [here](https://github.com/Art-of-WiFi/UniFi-API-browser).
This class can be installed using composer/[packagist](https://packagist.org/packages/art-of-wifi/unifi-api-client) for easy inclusion in your projects.
### Donations
If you find this PHP API client class useful and wish to support it's further development, please use the PayPal donate button below. All donations go to the project maintainer.
[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=M7TVNVX3Z44VN)
## Methods and functions supported
The class currently supports the following functions/methods to get/post/put/delete data through the UniFi Controller API:
- login()
- logout()
- adopt_device()
@@ -27,6 +22,7 @@ The class currently supports the following functions/methods to get/post/put/del
- create_usergroup()
- create_voucher()
- create_wlan()
- delete_device()
- delete_network()
- delete_radius_account()
- delete_site()
@@ -37,6 +33,7 @@ The class currently supports the following functions/methods to get/post/put/del
- extend_guest_validity()
- led_override()
- list_admins()
- list_all_admins()
- list_alarms()
- list_aps() (deprecated but still available as alias)
- list_clients()
@@ -67,6 +64,7 @@ The class currently supports the following functions/methods to get/post/put/del
- list_wlan_groups()
- list_wlanconf()
- locate_ap()
- move_device()
- power_cycle_switch_port()
- reconnect_sta()
- rename_ap()
@@ -112,8 +110,9 @@ The class currently supports the following functions/methods to get/post/put/del
- upgrade_device_external()
Internal functions, getters/setters:
- set_debug()
- set_site()
- get_debug()
- set_site()
- get_site()
- get_cookie() (renamed from getcookie())
@@ -129,7 +128,7 @@ Please refer to the source code for more details on the functions/methods and th
## Installation ##
You can use **Composer**, **Git** or simply **Download the Release** to install the API client class.
You can use [Composer](#composer), [Git](#git) or simply [Download the Release](#download-the-release) to install the API client class.
### Composer
@@ -200,18 +199,15 @@ $results = $unifi_connection->list_alarms(); // returns a PHP array con
Please refer to the `examples/` directory for some more detailed examples which you can use as a starting point for your own PHP code.
### IMPORTANT NOTES:
#### IMPORTANT NOTES:
In the example above, the last parameter (`true`) that is passed to the constructor, enables validation of the controller's SSL certificate which is otherwise **disabled** by default.
It is highly recommended to enable this feature in production environments where you have a valid SSL cert installed on the UniFi Controller, and which is associated with the FQDN of the server as used in the `controller_url` parameter. This option was added with API client version 1.1.16.
1. The last parameter (`true`) that is passed to the constructor, enables validation of the controller's SSL certificate which is otherwise **disabled** by default. It is highly recommended to enable this feature in production environments where you have a valid SSL cert installed on the UniFi Controller, and which is associated with the FQDN of the server as used in the `controller_url` parameter. This option was added with API client version 1.1.16.
---
2. In the example above, `$site_id` is the 8 character short site "name" which is visible in the URL when managing the site in the UniFi Controller:
In the example above, `$site_id` is the 8 character short site "name" which is visible in the URL when managing the site in the UniFi Controller:
`https://<controller IP address or FQDN>:8443/manage/site/jl3z2shm/dashboard`
`https://<controller IP address or FQDN>:8443/manage/site/jl3z2shm/dashboard`
In this case, `jl3z2shm` is the value required for $site_id.
In this case, `jl3z2shm` is the value required for $site_id.
## Need help or have suggestions?
@@ -223,7 +219,7 @@ If you would like to contribute code (improvements), please open an issue and in
## Credits
This class is largely based on the work done by the following developers:
This class is based on the work done by the following developers:
- domwo: http://community.ubnt.com/t5/UniFi-Wireless/little-php-class-for-unifi-api/m-p/603051
- fbagnol: https://github.com/fbagnol/class.unifi.php
- and the API as published by Ubiquiti: https://dl.ubnt.com/unifi/5.6.18-8261dc5066/unifi_sh_api

40
examples/create_site.php Executable file
View File

@@ -0,0 +1,40 @@
<?php
/**
* PHP API usage example
*
* contributed by: Art of WiFi
* description: example basic PHP script to create a new site, returns true upon success
*/
/**
* using the composer autoloader
*/
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)
* see the config.template.php file for an example
*/
require_once('config.php');
/**
* the site to use to log in to the controller
*/
$site_id = '<short site name of a site the credentials used have access to>';
/**
* description of the new site
*/
$description = 'new site';
/**
* initialize the UniFi API connection class and log in to the controller and do our thing
*/
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
$loginresults = $unifi_connection->login();
$results = $unifi_connection->create_site($description);
/**
* provide feedback in json format
*/
echo json_encode($results, JSON_PRETTY_PRINT);

41
examples/delete_site.php Executable file
View File

@@ -0,0 +1,41 @@
<?php
/**
* PHP API usage example
*
* contributed by: Art of WiFi
* description: example basic PHP script to delete a site, returns true upon success
*/
/**
* using the composer autoloader
*/
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)
* see the config.template.php file for an example
*/
require_once('config.php');
/**
* the site to use to log in to the controller
*/
$site_id = '<short site name of a site the credentials used have access to>';
/**
* the site to delete, must not be the same site as referenced by $site_id
*/
$site_to_delete = '<_id value of the site>';
/**
* initialize the UniFi API connection class and log in to the controller and do our thing
*/
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
$loginresults = $unifi_connection->login();
$results = $unifi_connection->delete_site($site_to_delete);
/**
* provide feedback in json format
*/
echo json_encode($results, JSON_PRETTY_PRINT);

View File

@@ -45,6 +45,6 @@ $disable_result = $unifi_connection->disable_ap($device_id, true);
//$disable_result = $unifi_connection->disable_ap($device_id, false);
/**
* provide feedback (the newly created voucher code, without the dash) in json format
* provide feedback in json format
*/
echo json_encode($disable_result, JSON_PRETTY_PRINT);

View File

@@ -0,0 +1,83 @@
<?php
/**
* PHP API usage example
*
* contributed by: Art of WiFi
* description: example basic PHP script to update WLAN settings when using a controller version 5.5.X or higher
* where set_ap_radiosettings() throws an error
*/
/**
* using the composer autoloader
*/
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)
* see the config.template.php file for an example
*/
require_once('config.php');
/**
* the site to use to log in to the controller
*/
$site_id = '<short site name of a site the credentials used have access to>';
/**
* the MAC address of the access point to modify
*/
$ap_mac = '<enter MAC address>';
/**
* power level for 2.4GHz
*/
$ng_tx_power_mode = 'low';
/**
* channel for 2.4GHz
*/
$ng_channel = 6;
/**
* power level for 5GHz
*/
$na_tx_power_mode = 'medium';
/**
* channel for 5GHz
*/
$na_channel = 44;
/**
* initialize the UniFi API connection class and log in to the controller and do our thing
*/
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion, false);
$set_debug_mode = $unifi_connection->set_debug(false);
$loginresults = $unifi_connection->login();
$data = $unifi_connection->list_devices($ap_mac);
$radio_table = $data[0]->radio_table;
$device_id = $data[0]->device_id;
foreach($radio_table as $radio){
if($radio->radio === 'ng'){
$radio->tx_power_mode = $ng_tx_power_mode;
$radio->channel = $ng_channel;
}
if($radio->radio === 'na'){
$radio->tx_power_mode = $na_tx_power_mode;
$radio->channel = $na_channel;
}
}
$update_device = $unifi_connection->set_device_settings_base($device_id, ['radio_table' => $radio_table]);
if(!$update_device){
$error = $unifi_connection->get_last_results_raw();
echo json_encode($error, JSON_PRETTY_PRINT);
}
/**
* provide feedback in json format
*/
echo json_encode($update_device, JSON_PRETTY_PRINT);

View File

@@ -24,11 +24,11 @@ class Client
/**
* private properties
*/
private $baseurl = 'https://127.0.0.1:8443';
private $site = 'default';
private $version = '5.4.16';
private $debug = false;
private $is_loggedin = false;
protected $baseurl = 'https://127.0.0.1:8443';
protected $site = 'default';
protected $version = '5.4.16';
protected $debug = false;
protected $is_loggedin = false;
private $cookies = '';
private $request_type = 'POST';
private $connect_timeout = 10;
@@ -46,9 +46,9 @@ class Client
* optional parameter <baseurl> = string; base URL of the UniFi controller, must include "https://" prefix and port suffix (:8443)
* optional parameter <site> = string; short site name to access, defaults to "default"
* optional parameter <version> = string; the version number of the controller, defaults to "5.4.16"
* optional parameter <ssl_verify> = boolean; whether to validate the controller's SSL certificate or not, true is recommended for
* production environments to prevent potential MitM attacks, default is to not validate the
* controller certificate
* optional parameter <ssl_verify> = boolean; whether to validate the controller's SSL certificate or not, a value of true is
* recommended for production environments to prevent potential MitM attacks, default (false) is to
* not validate the controller certificate
*/
function __construct($user, $password, $baseurl = '', $site = '', $version = '', $ssl_verify = false)
{
@@ -178,8 +178,8 @@ class Client
*/
public function set_site($site)
{
$this->check_site($site);
$this->site = trim($site);
$this->check_site($this->site);
return $this->site;
}
@@ -210,6 +210,16 @@ class Client
return false;
}
/**
* Get debug mode
* --------------
* get the value of private property debug, returns the current boolean value for debug
*/
public function get_debug()
{
return $this->debug;
}
/**
* Get last raw results
* --------------------
@@ -242,6 +252,12 @@ class Client
* Get Cookie from UniFi Controller
* --------------------------------
* returns the UniFi controller cookie
*
* NOTES:
* - when the results from this method are stored in $_SESSION['unificookie'], the class will initially not
* log in to the controller when a subsequent request is made using a new instance. This speeds up the
* overall request considerably. If that subsequent request fails (e.g. cookies have expired), a new login
* is executed automatically and the value of $_SESSION['unificookie'] is updated.
*/
public function get_cookie()
{
@@ -467,7 +483,7 @@ class Client
$end = is_null($end) ? ((time())*1000) : intval($end);
$start = is_null($start) ? $end-(12*3600*1000) : intval($start);
$json = ['attrs' => ['bytes', 'num_sta', 'time'], 'start' => $start, 'end' => $end];
if (!is_null($mac)) $json['mac'] = $mac;
if (!is_null($mac)) $json['mac'] = strtolower($mac);
$json = json_encode($json);
$response = $this->exec_curl('/api/s/'.$this->site.'/stat/report/5minutes.ap', 'json='.$json);
return $this->process_response($response);
@@ -491,7 +507,7 @@ class Client
$end = is_null($end) ? ((time())*1000) : intval($end);
$start = is_null($start) ? $end-(7*24*3600*1000) : intval($start);
$json = ['attrs' => ['bytes', 'num_sta', 'time'], 'start' => $start, 'end' => $end];
if (!is_null($mac)) $json['mac'] = $mac;
if (!is_null($mac)) $json['mac'] = strtolower($mac);
$json = json_encode($json);
$response = $this->exec_curl('/api/s/'.$this->site.'/stat/report/hourly.ap', 'json='.$json);
return $this->process_response($response);
@@ -515,7 +531,7 @@ class Client
$end = is_null($end) ? ((time())*1000) : intval($end);
$start = is_null($start) ? $end-(7*24*3600*1000) : intval($start);
$json = ['attrs' => ['bytes', 'num_sta', 'time'], 'start' => $start, 'end' => $end];
if (!is_null($mac)) $json['mac'] = $mac;
if (!is_null($mac)) $json['mac'] = strtolower($mac);
$json = json_encode($json);
$response = $this->exec_curl('/api/s/'.$this->site.'/stat/report/daily.ap', 'json='.$json);
return $this->process_response($response);
@@ -528,17 +544,19 @@ class Client
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
* optional parameter <mac> = client MAC address to return sessions for (can only be used when start and end are also provided)
* optional parameter <type> = client type to return sessions for, can be 'all', 'guest' or 'user'; default value is 'all'
*
* NOTES:
* - defaults to the past 7*24 hours
*/
public function stat_sessions($start = null, $end = null, $mac = null)
public function stat_sessions($start = null, $end = null, $mac = null, $type = 'all')
{
if (!$this->is_loggedin) return false;
if (!in_array($type, ['all', 'guest', 'user'])) return false;
$end = is_null($end) ? time() : intval($end);
$start = is_null($start) ? $end-(7*24*3600) : intval($start);
$json = ['type'=> 'all', 'start' => $start, 'end' => $end];
if (!is_null($mac)) $json['mac'] = $mac;
$json = ['type'=> $type, 'start' => $start, 'end' => $end];
if (!is_null($mac)) $json['mac'] = strtolower($mac);
$json = json_encode($json);
$response = $this->exec_curl('/api/s/'.$this->site.'/stat/session', 'json='.$json);
return $this->process_response($response);
@@ -876,6 +894,18 @@ class Client
return $this->process_response($response);
}
/**
* List all admins
* ---------------
* returns an array containing administrator objects for all sites
*/
public function list_all_admins()
{
if (!$this->is_loggedin) return false;
$response = $this->exec_curl('/api/stat/admin');
return $this->process_response($response);
}
/**
* List wlan_groups
* ----------------
@@ -1253,6 +1283,9 @@ class Client
* required parameter <ht>(default=20)
* required parameter <tx_power_mode>
* required parameter <tx_power>(default=0)
*
* NOTES:
* - only supported on pre-5.X.X controller versions
*/
public function set_ap_radiosettings($ap_id, $radio, $channel, $ht, $tx_power_mode, $tx_power)
{
@@ -1338,6 +1371,35 @@ class Client
return $this->process_response_boolean($response);
}
/**
* Move a device to another site
* -----------------------------
* return true on success
* required parameter <mac> = string; MAC address of the device to move
* required parameter <site_id> = 24 char string; _id of the site to move the device to
*/
public function move_device($mac, $site_id)
{
if (!$this->is_loggedin) return false;
$json = json_encode(['site' => $site_id, 'mac' => $mac, 'cmd' => 'move-device']);
$response = $this->exec_curl('/api/s/'.$this->site.'/cmd/sitemgr', 'json='.$json);
return $this->process_response_boolean($response);
}
/**
* Delete a device from the current site
* -------------------------------------
* return true on success
* required parameter <mac> = string; MAC address of the device to delete
*/
public function delete_device($mac)
{
if (!$this->is_loggedin) return false;
$json = json_encode(['mac' => $mac, 'cmd' => 'delete-device']);
$response = $this->exec_curl('/api/s/'.$this->site.'/cmd/sitemgr', 'json='.$json);
return $this->process_response_boolean($response);
}
/**
* List network settings (using REST)
* ----------------------------------
@@ -1544,7 +1606,7 @@ class Client
* required parameter <wlan_id>
* required parameter <mac_filter_policy> = string, "allow" or "deny"; default MAC policy to apply
* required parameter <mac_filter_enabled> = boolean; true enables the policy, false disables it
* required parameter <macs> = array; must contain MAC strings to be placed in the MAC filter list,
* required parameter <macs> = array; must contain valid MAC strings to be placed in the MAC filter list,
* replacing existing values. Existing MAC filter list can be obtained
* through list_wlanconf().
*/
@@ -1941,7 +2003,7 @@ class Client
/**
* Process regular responses where output is the content of the data array
*/
private function process_response($response_json)
protected function process_response($response_json)
{
$response = json_decode($response_json);
$this->catch_json_last_error();
@@ -1967,7 +2029,7 @@ class Client
/**
* Process responses where output should be boolean (true/false)
*/
private function process_response_boolean($response_json)
protected function process_response_boolean($response_json)
{
$response = json_decode($response_json);
$this->catch_json_last_error();
@@ -2091,7 +2153,7 @@ class Client
/**
* Execute the cURL request
*/
private function exec_curl($path, $data = '')
protected function exec_curl($path, $data = '')
{
$url = $this->baseurl.$path;