Compare commits

...

6 Commits

Author SHA1 Message Date
malle-pietje
6fd7e6e598 added new functions for 5-minutes stats and minor code cleanup
- stat_5minutes_site()
- stat_5minutes_aps()
- added optional parameter to list_dashboard() to allow fetching of 5minutes stats
2017-10-10 09:37:29 +02:00
malle-pietje
4611dbb28c applied small formatting change to README 2017-10-06 12:59:20 +02:00
malle-pietje
cc486f652d fixed typo in examples/change_wlan_password.php 2017-10-06 12:55:44 +02:00
malle-pietje
008280e870 minor code cleanup and various changes:
- added a 6th parameter to the constructor to enable SSL cert verification, recommended for production environments
- added examples/change_wlan_password.php to demonstrate WLAN password/PSK change
- updated main README accordingly
2017-10-06 12:46:07 +02:00
malle-pietje
971c77ab5f various tweaks and an addition
- more relaxed handling of $site in set_site(), now we only issue an error message when provided (short) site name is probably incorrect and debug mode is
true
- added test_connection.php, a command line script which can be used to quickly test the connection to your controller with various cURL options which you can
quickly change
2017-09-14 12:15:21 +02:00
malle-pietje
03cb083986 minor changes
- more strict comparisons where possible
- slightly changed error messages
- enabled the CURLOPT_CONNECTTIMEOUT cURL option to timeout a controller connection after 10 seconds
2017-09-11 16:50:24 +02:00
5 changed files with 351 additions and 152 deletions

View File

@@ -1,16 +1,18 @@
## UniFi controller API client class
This PHP class provides access to Ubiquiti's **UniFi Controller API**. Versions 4.x.x and 5.x.x of the UniFi Controller software (version 5.5.20 has been confirmed to work) are supported. It is an independent version of the class which is used in the 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.18 has been confirmed to work). It's a standalone version of the class which is used in the API browser tool [here](https://github.com/Art-of-WiFi/UniFi-API-browser).
This class can now also be installed using composer/[packagist](https://packagist.org/packages/art-of-wifi/unifi-api-client) for easy inclusion in your projects.
### Donations
If you'd like to support further development of this PHP API client class, please use the PayPal donate button below. All donations go to the project maintainer.
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=M7TVNVX3Z44VN)
[![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
This class currently supports the following functions/methods to get/set data through the UniFi controller API:
The class currently supports the following functions/methods to get/post/put/delete data through the UniFi controller API:
- login()
- logout()
- adopt_device()
@@ -86,10 +88,12 @@ This class currently supports the following functions/methods to get/set data th
- stat_allusers()
- stat_auths()
- stat_client()
- stat_daily_aps()
- stat_daily_site()
- stat_5minutes_aps() (supported on controller version 5.5.* and higher)
- stat_hourly_aps()
- stat_daily_aps()
- stat_5minutes_site() (supported on controller version 5.5.* and higher)
- stat_hourly_site()
- stat_daily_site()
- stat_payment()
- stat_sessions()
- stat_sites()
@@ -111,29 +115,22 @@ Internal functions, getters/setters:
- get_last_results_raw()
- get_last_error_message()
Please refer to the source code for more details on each function/method and it's parameters.
## Credits
This class is largely 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://www.ubnt.com/downloads/unifi/5.5.20/unifi_sh_api
Please refer to the source code for more details on each function/method and their parameters.
## Requirements
- a web server with PHP and cURL modules installed (tested on apache2 with PHP Version 5.6.1 and cURL 7.42.1)
- network connectivity between this web server and the server and port (normally port 8443) where the UniFi controller is running
- network connectivity between this web server and the server and port (normally TCP port 8443) where the UniFi controller is running
## Installation ##
You can use **Composer**, **Git** or simply **Download the Release**
You can use **Composer**, **Git** or simply **Download the Release** to install the API client class.
### Composer
The preferred method is via [composer](https://getcomposer.org). Follow the [installation instructions](https://getcomposer.org/doc/00-intro.md) if you do not already have composer installed.
Once composer is installed, simply execute this command from your project directory:
Once composer is installed, simply execute this command from the shell in your project directory:
```sh
composer require art-of-wifi/unifi-api-client
@@ -181,14 +178,19 @@ require_once('vendor/autoload.php');
* initialize the Unifi API connection class, log in to the controller and request the alarms collection
* (this example assumes you have already assigned the correct values to the variables used)
*/
$unifi_connection = new UniFi_API\Client($controller_user, $controller_password, $controller_url, $site_id, $controller_version);
$unifi_connection = new UniFi_API\Client($controller_user, $controller_password, $controller_url, $site_id, $controller_version, true);
$login = $unifi_connection->login();
$results = $unifi_connection->list_alarms(); // returns an PHP array containing alarm objects
$results = $unifi_connection->list_alarms(); // returns a PHP array containing alarm objects
```
Please refer to the `examples/` directory for some more detailed examples which you can use as a starting point for your own PHP code.
### NOTE:
### 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.
---
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:
@@ -198,12 +200,19 @@ In this case, `jl3z2shm` is the value required for $site_id.
## Need help or have suggestions?
There is still work to be done to add functionality and improve the usability of this class, so all suggestions/comments are welcome. Please use the github [issue](https://github.com/Art-of-WiFi/UniFi-API-client/issues) list or the Ubiquiti Community forums (https://community.ubnt.com/t5/UniFi-Wireless/PHP-class-to-access-the-UniFi-controller-API-updates-and/td-p/1512870) to share your ideas.
There is still work to be done to add functionality and improve the usability of this class, so all suggestions/comments are welcome. Please use the github [issue](https://github.com/Art-of-WiFi/UniFi-API-client/issues) list or the Ubiquiti Community forums (https://community.ubnt.com/t5/UniFi-Wireless/PHP-class-to-access-the-UniFi-controller-API-updates-and/td-p/1512870) to share your ideas/questions.
## Contribute
If you would like to contribute code (improvements), please open an issue and include your code there or else create a pull request.
## Credits
This class is largely 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
## Important Disclaimer
Many of these functions are not officially supported by UBNT and as such, may not be supported in future versions of the UniFi controller API.
Many of the functions in this API client class are not officially supported by UBNT and as such, may not be supported in future versions of the UniFi controller API.

View File

@@ -0,0 +1,46 @@
<?php
/**
* PHP API usage example
*
* contributed by: Art of WiFi
* description: example basic PHP script to change the WPA2 password/PSK of a WLAN, returns true on 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 which the WLAN you want to modify belongs
*/
$site_id = '<enter your (short) site name here>';
/**
* the id of the WLAN you wish to modify
*/
$wlan_id = '<the value of _id for the WLAN you wish to change>';
/**
* the new WPA2 password/PSK to apply to the above WLAN
*/
$new_password = '<new password goes here>';
/**
* initialize the UniFi API connection class and log in to the controller
*/
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
$set_debug_mode = $unifi_connection->set_debug($debug);
$loginresults = $unifi_connection->login();
$results = $unifi_connection->set_wlansettings($wlan_id, $new_password);
/**
* provide feedback in json format
*/
echo json_encode($results, JSON_PRETTY_PRINT);

View File

@@ -3,7 +3,7 @@
* PHP API usage example
*
* contributed by: Art of WiFi
* description: example basic PHP script to create a set of vouchers
* description: example basic PHP script to create a set of vouchers, returns an array containing the newly created vouchers
*/
/**
@@ -18,9 +18,9 @@ require_once('vendor/autoload.php');
require_once('config.php');
/**
* the voucher duration in minutes
* minutes the voucher is valid after activation (expiration time)
*/
$voucher_duration = 2000;
$voucher_expiration = 2000;
/**
* the number of vouchers to create
@@ -40,11 +40,16 @@ $set_debug_mode = $unifi_connection->set_debug($debug);
$loginresults = $unifi_connection->login();
/**
* then we create the required number of vouchers for the requested duration
* then we create the required number of vouchers with the requested expiration value
*/
$voucher_result = $unifi_connection->create_voucher($voucher_duration, $voucher_count);
$voucher_result = $unifi_connection->create_voucher($voucher_expiration, $voucher_count);
/**
* provide feedback (the newly created voucher code, without the dash) in json format
* we then fetch the newly created vouchers by the create_time returned
*/
echo json_encode($voucher_result, JSON_PRETTY_PRINT);
$vouchers = $unifi_connection->stat_voucher($voucher_result[0]->create_time);
/**
* provide feedback (the newly created vouchers) in json format
*/
echo json_encode($vouchers, JSON_PRETTY_PRINT);

68
examples/test_connection.php Executable file
View File

@@ -0,0 +1,68 @@
<?php
/**
* Test the connection to your UniFi controller
*
* contributed by: Art of WiFi
* description: PHP script to check/debug the connection to your controller using PHP and cURL
*/
/**
* Include the config file (place your credentials etc. there if not already present),
* see the config.template.php file for an example.
* (will only be used here to get the URL to the controller)
*/
require_once('config.php');
/**
* Check whether the cURL module supports SSL
*/
if (!curl_version()['features'] & CURL_VERSION_SSL) {
print 'SSL is not supported with this cURL installation!' . PHP_EOL;
}
/**
* create cURL resource
*/
$ch = curl_init();
/**
* Set the required cURL options
*/
curl_setopt($ch, CURLOPT_URL, $controllerurl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
/**
* This cURL option can have a value of 0-6
* see this URL for more details:
* http://php.net/manual/en/function.curl-setopt.php
* 0 is the default value and is used by the PHP API client class
*/
curl_setopt($ch, CURLOPT_SSLVERSION, 0);
/**
* Be more verbose
*/
curl_setopt($ch, CURLOPT_VERBOSE, true);
/**
* $results contains the output as returned by the cURL request,
* returns true when successful, else returns false
*/
print 'verbose output from the cURL request:' . PHP_EOL;
$results = curl_exec($ch);
print PHP_EOL . 'curl_getinfo output:' . PHP_EOL;
print_r(curl_getinfo($ch));
/**
* If we receive a cURL error, output it before the results
*/
if (curl_errno($ch)) {
print PHP_EOL . 'cURL error: ' . curl_error($ch) . PHP_EOL;
}
print PHP_EOL . '$results:' . PHP_EOL;
print_r($results);
print PHP_EOL;

View File

@@ -24,19 +24,33 @@ class Client
/**
* private properties
*/
private $user;
private $password;
private $baseurl = 'https://127.0.0.1:8443';
private $site = 'default';
private $version = '5.4.16';
private $debug = false;
private $is_loggedin = false;
private $cookies = '';
private $request_type = 'POST';
private $last_results_raw;
private $last_error_message;
private $baseurl = 'https://127.0.0.1:8443';
private $site = 'default';
private $version = '5.4.16';
private $debug = false;
private $is_loggedin = false;
private $cookies = '';
private $request_type = 'POST';
private $connect_timeout = 10;
private $last_results_raw = null;
private $last_error_message = null;
private $curl_ssl_verify_peer = false;
private $curl_ssl_verify_host = false;
function __construct($user, $password, $baseurl = '', $site = '', $version = '')
/**
* Construct an instance of the UniFi API client class
* ---------------------------------------------------
* return a new class instance
* required parameter <user> = string; user name to use when connecting to the UniFi controller
* required parameter <password> = string; password to use when connecting to the UniFi controller
* 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
*/
function __construct($user, $password, $baseurl = '', $site = '', $version = '', $ssl_verify = false)
{
if (!extension_loaded('curl')) {
trigger_error('The PHP curl extension is not loaded. Please correct this before proceeding!');
@@ -48,20 +62,14 @@ class Client
if (!empty($baseurl)) $this->baseurl = trim($baseurl);
if (!empty($site)) $this->site = trim($site);
if (!empty($version)) $this->version = trim($version);
if (isset($_SESSION['unificookie'])) {
$this->cookies = $_SESSION['unificookie'];
if ($ssl_verify === true) {
$this->curl_ssl_verify_peer = true;
$this->curl_ssl_verify_host = 2;
}
$base_url_components = parse_url($this->baseurl);
if (empty($base_url_components['scheme']) || empty($base_url_components['host']) || empty($base_url_components['port'])) {
trigger_error('The URL provided is incomplete!');
}
if (strlen($this->site) !== 8 && $this->site !== 'default' && $this->debug) {
error_log('The provided short site name is probably incorrect');
}
$this->check_base_url();
$this->check_site($this->site);
$this->update_unificookie();
}
function __destruct()
@@ -83,12 +91,9 @@ class Client
public function login()
{
/**
* if user has $_SESSION['unificookie'] set, skip the login ;)
* if user has $_SESSION['unificookie'] set, skip the login
*/
if (isset($_SESSION['unificookie'])) {
$this->is_loggedin = true;
return $this->is_loggedin;
}
if (isset($_SESSION['unificookie'])) return $this->is_loggedin = true;
$ch = $this->get_curl_obj();
@@ -97,9 +102,12 @@ class Client
curl_setopt($ch, CURLOPT_URL, $this->baseurl.'/api/login');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['username' => $this->user, 'password' => $this->password]));
if (($content = curl_exec($ch)) === false) {
trigger_error('cURL error: '.curl_error($ch));
}
/**
* execute the cURL request
*/
$content = curl_exec($ch);
if (curl_errno($ch)) trigger_error('cURL error: '.curl_error($ch));
if ($this->debug) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
@@ -120,13 +128,12 @@ class Client
curl_close ($ch);
preg_match_all('|Set-Cookie: (.*);|U', substr($content, 0, $header_size), $results);
if (isset($results[1])) {
$this->cookies = implode(';', $results[1]);
if (!empty($body)) {
if (($code >= 200) && ($code < 400)) {
if (strpos($this->cookies, 'unifises') !== false) {
$this->is_loggedin = true;
}
if (strpos($this->cookies, 'unifises') !== false) return $this->is_loggedin = true;
}
if ($code === 400) {
@@ -136,7 +143,7 @@ class Client
}
}
return $this->is_loggedin;
return false;
}
/**
@@ -159,7 +166,6 @@ class Client
* Set site
* --------
* modify the private property site, returns the new (short) site name
* returns the new short name, or false if string length is incorrect or not 'default'
* required parameter <site> = string; must be the short site name of a site to which the
* provided credentials have access
*
@@ -168,13 +174,9 @@ class Client
*/
public function set_site($site)
{
if (strlen($site) === 8 || $site === 'default') {
$this->site = $site;
return $this->site;
} else {
return false;
}
$this->site = $site;
$this->check_site($this->site);
return $this->site;
}
/**
@@ -209,19 +211,14 @@ class Client
/**
* Get last raw results
* --------------------
* returns the raw results of the last method called in PHP stdClass Object format by default, returns false if not set
* optional parameter <return_json> = boolean; true will return the results in "pretty printed" json format
*
* NOTE:
* this method can be used to get the full error as returned by the controller
* returns the raw results of the last method called, returns false if unavailable
* optional parameter <return_json> = boolean; true will return the results in "pretty printed" json format,
* PHP stdClass Object format is returned by default
*/
public function get_last_results_raw($return_json = false)
{
if ($this->last_results_raw != null) {
if ($return_json) {
return json_encode($this->last_results_raw, JSON_PRETTY_PRINT);
}
if ($this->last_results_raw !== null) {
if ($return_json) return json_encode($this->last_results_raw, JSON_PRETTY_PRINT);
return $this->last_results_raw;
}
@@ -231,14 +228,11 @@ class Client
/**
* Get last error message
* ----------------------
* returns the error message of the last method called in PHP stdClass Object format, returns false if not set
* returns the error message of the last method called in PHP stdClass Object format, returns false if unavailable
*/
public function get_last_error_message()
{
if (isset($this->last_error_message)) {
return $this->last_error_message;
}
if ($this->last_error_message !== null) return $this->last_error_message;
return false;
}
@@ -275,7 +269,7 @@ class Client
$json = ['cmd' => 'authorize-guest', 'mac' => $mac, 'minutes' => $minutes];
/**
* if we have received values for up/down/MBytes we append them to the payload array to be submitted
* if we have received values for up/down/MBytes/ap_mac we append them to the payload array to be submitted
*/
if (isset($up)) $json['up'] = $up;
if (isset($down)) $json['down'] = $down;
@@ -347,8 +341,8 @@ class Client
}
/**
* Add/modify a client device note
* -------------------------------
* Add/modify/remove a client device note
* --------------------------------------
* return true on success
* required parameter <user_id> = id of the user device to be modified
* optional parameter <note> = note to be applied to the user device
@@ -366,14 +360,14 @@ class Client
}
/**
* Add/modify a client device name
* -------------------------------
* Add/modify/remove a client device name
* --------------------------------------
* return true on success
* required parameter <user_id> = id of the user device to be modified
* optional parameter <name> = name to be applied to the user device
* required parameter <user_id> = id of the client device to be modified
* optional parameter <name> = name to be applied to the client device
*
* NOTES:
* - when name is empty or not set, the existing name for the user will be removed
* - when name is empty or not set, the existing name for the client device will be removed
*/
public function set_sta_name($user_id, $name = null)
{
@@ -383,6 +377,52 @@ class Client
return $this->process_response_boolean($content_decoded);
}
/**
* 5 minutes site stats method
* ---------------------------
* returns an array of 5 minutes stats objects for the current site
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
*
* NOTES:
* - defaults to the past 12 hours
* - this function/method is only supported on controller versions 5.5.* and later
* - make sure that the retention policy for 5 minutes stats is set to the correct value in
* the controller settings
*/
public function stat_5minutes_site($start = null, $end = null)
{
if (!$this->is_loggedin) return false;
$end = is_null($end) ? ((time())*1000) : $end;
$start = is_null($start) ? $end-(12*3600*1000) : $start;
$attributes = ['bytes', 'wan-tx_bytes', 'wan-rx_bytes', 'wlan_bytes', 'num_sta', 'lan-num_sta', 'wlan-num_sta', 'time'];
$json = json_encode(['attrs' => $attributes, 'start' => $start, 'end' => $end]);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/report/5minutes.site', 'json='.$json));
return $this->process_response($content_decoded);
}
/**
* Hourly site stats method
* ------------------------
* returns an array of hourly stats objects for the current site
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
*
* NOTES:
* - defaults to the past 7*24 hours
* - "bytes" are no longer returned with controller version 4.9.1 and later
*/
public function stat_hourly_site($start = null, $end = null)
{
if (!$this->is_loggedin) return false;
$end = is_null($end) ? ((time())*1000) : $end;
$start = is_null($start) ? $end-(7*24*3600*1000) : $start;
$attributes = ['bytes', 'wan-tx_bytes', 'wan-rx_bytes', 'wlan_bytes', 'num_sta', 'lan-num_sta', 'wlan-num_sta', 'time'];
$json = json_encode(['attrs' => $attributes, 'start' => $start, 'end' => $end]);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/report/hourly.site', 'json='.$json));
return $this->process_response($content_decoded);
}
/**
* Daily site stats method
* ------------------------
@@ -406,24 +446,28 @@ class Client
}
/**
* Hourly site stats method
* ------------------------
* returns an array of hourly stats objects for the current site
* 5 minutes stats method for a single access point or all access points
* ---------------------------------------------------------------------
* returns an array of 5 minutes stats objects
* optional parameter <start> = Unix timestamp in seconds
* optional parameter <end> = Unix timestamp in seconds
* optional parameter <mac> = AP MAC address to return stats for
*
* NOTES:
* - defaults to the past 7*24 hours
* - "bytes" are no longer returned with controller version 4.9.1 and later
* - defaults to the past 12 hours
* - this function/method is only supported on controller versions 5.5.* and later
* - make sure that the retention policy for 5 minutes stats is set to the correct value in
* the controller settings
*/
public function stat_hourly_site($start = null, $end = null)
public function stat_5minutes_aps($start = null, $end = null, $mac = null)
{
if (!$this->is_loggedin) return false;
$end = is_null($end) ? ((time())*1000) : $end;
$start = is_null($start) ? $end-(7*24*3600*1000) : $start;
$attributes = ['bytes', 'wan-tx_bytes', 'wan-rx_bytes', 'wlan_bytes', 'num_sta', 'lan-num_sta', 'wlan-num_sta', 'time'];
$json = json_encode(['attrs' => $attributes, 'start' => $start, 'end' => $end]);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/report/hourly.site', 'json='.$json));
$start = is_null($start) ? $end-(12*3600*1000) : $start;
$json = ['attrs' => ['bytes', 'num_sta', 'time'], 'start' => $start, 'end' => $end];
if (!is_null($mac)) $json['mac'] = $mac;
$json = json_encode($json);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/report/5minutes.ap', 'json='.$json));
return $this->process_response($content_decoded);
}
@@ -478,7 +522,7 @@ class Client
/**
* Show all login sessions
* -----------------------
* returns an array of login session objects for all devices
* returns an array of login session objects for all devices or a single device
* 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)
@@ -605,8 +649,8 @@ class Client
}
/**
* Assign user device to another group
* -----------------------------------
* Assign client device to another group
* -------------------------------------
* return true on success
* required parameter <user_id> = id of the user device to be modified
* required parameter <group_id> = id of the user group to assign user to
@@ -685,18 +729,21 @@ class Client
* List dashboard metrics
* ----------------------
* returns an array of dashboard metric objects (available since controller version 4.9.1.alpha)
* optional parameter <five_minutes> = boolean; if true, return stats based on 5 minute intervals,
* returns hourly stats by default (supported on controller versions 5.5.* and higher)
*/
public function list_dashboard()
public function list_dashboard($five_minutes = false)
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/dashboard'));
$url_suffix = $five_minutes ? '?scale=5minutes' : null;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/dashboard'.$url_suffix));
return $this->process_response($content_decoded);
}
/**
* List user devices
* -----------------
* returns an array of known user device objects
* List client devices
* -------------------
* returns an array of known client device objects
*/
public function list_users()
{
@@ -924,7 +971,7 @@ class Client
/**
* Create voucher(s)
* -----------------
* returns an array of voucher codes (without the dash "-" in the middle) by calling the stat_voucher method
* returns an array containing a single object which contains the create_time(stamp) of the voucher(s) created
* required parameter <minutes> = minutes the voucher is valid after activation (expiration time)
* optional parameter <count> = number of vouchers to create, default value is 1
* optional parameter <quota> = single-use or multi-use vouchers, string value '0' is for multi-use, '1' is for single-use,
@@ -933,6 +980,8 @@ class Client
* optional parameter <up> = upload speed limit in kbps
* optional parameter <down> = download speed limit in kbps
* optional parameter <MBytes> = data transfer limit in MB
*
* NOTES: please use the stat_voucher() method/function to retrieve the newly created voucher(s) by create_time
*/
public function create_voucher($minutes, $count = 1, $quota = '0', $note = null, $up = null, $down = null, $MBytes = null)
{
@@ -1730,6 +1779,11 @@ class Client
*/
public function list_aps($device_mac = null)
{
trigger_error(
'Function list_aps() has been deprecated, use list_devices() instead.',
E_USER_DEPRECATED
);
return $this->list_devices($device_mac);
}
@@ -1808,23 +1862,15 @@ class Client
if (isset($response->meta->rc)) {
if ($response->meta->rc === 'ok') {
$this->last_error_message = null;
if (is_array($response->data)) {
return $response->data;
}
if (is_array($response->data)) return $response->data;
return true;
} elseif ($response->meta->rc === 'error') {
/**
* we have an error:
* set $this->set last_error_message if the returned error message is available
*/
if (isset($response->meta->msg)) {
$this->last_error_message = $response->meta->msg;
}
if ($this->debug) {
trigger_error('Debug: Last error message: '.$this->last_error_message);
}
if (isset($response->meta->msg)) $this->last_error_message = $response->meta->msg;
if ($this->debug) trigger_error('Debug: Last error message: '.$this->last_error_message);
}
}
@@ -1846,19 +1892,44 @@ class Client
* we have an error:
* set $this->last_error_message if the returned error message is available
*/
if (isset($response->meta->msg)) {
$this->last_error_message = $response->meta->msg;
}
if ($this->debug) {
trigger_error('Debug: Last error message: '.$this->last_error_message);
}
if (isset($response->meta->msg)) $this->last_error_message = $response->meta->msg;
if ($this->debug) trigger_error('Debug: Last error message: '.$this->last_error_message);
}
}
return false;
}
/**
* Check the submitted base URL
*/
private function check_base_url()
{
$base_url_components = parse_url($this->baseurl);
if (empty($base_url_components['scheme']) || empty($base_url_components['host']) || empty($base_url_components['port'])) {
trigger_error('The URL provided is incomplete!');
}
}
/**
* Check the (short) site name
*/
private function check_site($site)
{
if ($this->debug && strlen($site) !== 8 && $site !== 'default') {
error_log('The provided (short) site name is probably incorrect');
}
}
/**
* Update the unificookie
*/
private function update_unificookie()
{
if (isset($_SESSION['unificookie'])) $this->cookies = $_SESSION['unificookie'];
}
/**
* Execute the cURL request
*/
@@ -1876,35 +1947,36 @@ class Client
} else {
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
}
} else {
curl_setopt($ch, CURLOPT_POST, false);
if ($this->request_type === 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
if ($this->request_type === 'DELETE') curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
if (($content = curl_exec($ch)) === false) {
/**
* execute the cURL request
*/
$content = curl_exec($ch);
if (curl_errno($ch)) {
trigger_error('cURL error: '.curl_error($ch));
}
/**
* has the session timed out?
*/
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$strerr = '{ "data" : [ ] , "meta" : { "msg" : "api.err.LoginRequired" , "rc" : "error"}}';
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode == 401 && strcmp($content, $strerr) == 0) {
if ($this->debug) {
error_log('cURL debug: Needed reconnect to UniFi Controller');
}
$json_decoded_content = json_decode($content, true);
if ($http_code == 401 && isset($json_decoded_content['meta']['msg']) && $json_decoded_content['meta']['msg'] === 'api.err.LoginRequired') {
if ($this->debug) error_log('cURL debug: Needed to reconnect to UniFi Controller');
/**
* explicitly unset the old cookie now
*/
if (isset($_SESSION['unificookie'])) {
unset($_SESSION['unificookie']);
$have_cookie_in_use = 1;
$no_cookie_in_use = 1;
}
$this->login();
@@ -1918,9 +1990,9 @@ class Client
/**
* setup the cookie for the user within $_SESSION
*/
if (isset($have_cookie_in_use) && session_status() != PHP_SESSION_DISABLED) {
if (isset($no_cookie_in_use) && session_status() != PHP_SESSION_DISABLED) {
$_SESSION['unificookie'] = $this->cookies;
unset($have_cookie_in_use);
unset($no_cookie_in_use);
}
return $this->exec_curl($url, $data);
@@ -1951,19 +2023,18 @@ class Client
}
/**
* get the cURL object
* Get the cURL object
*/
private function get_curl_obj()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verify_peer);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->curl_ssl_verify_host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connect_timeout);
if ($this->debug) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
}
if ($this->debug) curl_setopt($ch, CURLOPT_VERBOSE, true);
if ($this->cookies != '') {
curl_setopt($ch, CURLOPT_COOKIESESSION, true);