Compare commits

..

15 Commits

Author SHA1 Message Date
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
malle-pietje
8df2fcc522 Merge branch 'master' of github.com:Art-of-WiFi/UniFi-API-client 2017-09-08 12:37:17 +02:00
malle-pietje
eba7819c17 various changes and additions:
IMPORTANT CHANGE: renamed all functions/methods named add_*() to create_*()
improved data validation
modified several existing methods/functions to leverage REST endpoints
added create_network() method/function
added set_networksettings_base() method/function
added delete_network() method/function
added list_radius_profiles() method/function
added create_radius_account() method/function
added set_radius_account_base() method/function
added delete_radius_account() method/function
2017-09-08 12:36:12 +02:00
malle-pietje
462d8a81a1 Update README.md 2017-09-07 17:46:22 +02:00
malle-pietje
0373c8369f updated README 2017-09-07 12:48:14 +02:00
malle-pietje
cf41e75269 updated README 2017-09-07 12:36:12 +02:00
malle-pietje
e235267a8a updated README 2017-09-07 12:34:31 +02:00
malle-pietje
9896f6d85f updated README 2017-09-07 12:33:56 +02:00
malle-pietje
4f84cfc550 updated README 2017-09-07 12:33:09 +02:00
malle-pietje
efa6704c97 minor changes to examples and README for consistency 2017-09-07 12:31:47 +02:00
malle-pietje
5c893c1237 updated README 2017-09-07 12:29:13 +02:00
malle-pietje
ab38e6f7ad updated README 2017-09-07 12:27:20 +02:00
malle-pietje
0ac6653ec0 updated README 2017-09-06 17:16:32 +02:00
14 changed files with 601 additions and 225 deletions

168
README.md
View File

@@ -1,39 +1,48 @@
## 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.
This PHP class 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.5.20 has been confirmed to work). 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).
The class is now also installable through 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
## Methods and functions supported
This class currently supports the following functions/methods to get/set data through the UniFi controller API:
- login()
- logout()
- add_site()
- adopt_device()
- authorize_guest()
- unauthorize_guest()
- block_sta()
- unblock_sta()
- count_alarms()
- create_hotspotop()
- create_network()
- create_radius_account()
- create_site()
- create_usergroup()
- create_voucher()
- create_wlan()
- delete_network()
- delete_radius_account()
- delete_site()
- delete_usergroup()
- delete_wlan()
- disable_ap()
- edit_usergroup()
- extend_guest_validity()
- led_override()
- list_admins()
- list_alarms()
- count_alarms()
- upgrade_device()
- upgrade_device_external()
- spectrum_scan()
- spectrum_scan_state()
- list_devices()
- list_aps() (deprecated but still available as alias)
- list_clients()
- list_current_channels()
- list_dashboard()
- list_devices()
- list_dpi_stats()
- list_dynamicdns()
- list_events()
- list_extension()
@@ -45,6 +54,7 @@ This class currently supports the following functions/methods to get/set data th
- list_portforward_stats()
- list_portforwarding()
- list_radius_accounts() (supported on controller version 5.5.19 and higher)
- list_radius_profiles()
- list_rogueaps()
- list_self()
- list_settings()
@@ -54,38 +64,32 @@ This class currently supports the following functions/methods to get/set data th
- list_users()
- list_wlan_groups()
- list_wlanconf()
- list_current_channels()
- list_dpi_stats()
- locate_ap()
- reconnect_sta()
- rename_ap()
- restart_ap()
- revoke_voucher()
- extend_guest_validity()
- set_ap_radiosettings()
- set_guestlogin_settings()
- locate_ap()
- set_locate_ap() (deprecated but still available as alias)
- unset_locate_ap() (deprecated but still available as alias)
- set_networksettings_base()
- set_radius_account_base()
- set_sta_name()
- set_sta_note()
- set_usergroup()
- edit_usergroup()
- add_usergroup()
- delete_usergroup()
- edit_usergroup()
- add_usergroup()
- delete_usergroup()
- set_wlan_mac_filter()
- set_wlansettings()
- create_wlan()
- delete_wlan()
- set_wlansettings_base()
- site_leds()
- site_ledsoff() (deprecated but still available as alias)
- site_ledson() (deprecated but still available as alias)
- spectrum_scan()
- spectrum_scan_state()
- stat_allusers()
- stat_auths()
- stat_client()
- stat_daily_site()
- stat_daily_aps()
- stat_daily_site()
- stat_hourly_aps()
- stat_hourly_site()
- stat_payment()
@@ -94,10 +98,16 @@ This class currently supports the following functions/methods to get/set data th
- stat_sta_sessions_latest()
- stat_sysinfo()
- stat_voucher()
- unauthorize_guest()
- unblock_sta()
- unset_locate_ap() (deprecated but still available as alias)
- upgrade_device()
- upgrade_device_external()
Internal functions, getters/setters:
- set_debug()
- set_site()
- set_site()
- get_site()
- get_cookie() (renamed from getcookie())
- get_last_results_raw()
@@ -105,56 +115,102 @@ Internal functions, getters/setters:
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
## Requirements
### 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
### Install
Simply execute this command from your project directory:
## Installation ##
```
$ composer require art-of-wifi/unifi-api-client
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 the shell in your project directory:
```sh
composer require art-of-wifi/unifi-api-client
```
### Example usage
Finally, be sure to include the autoloader in your code:
```php
require_once('vendor/autoload.php');
```
### Git
Execute the following `git` command from the shell in your project directory:
```sh
git clone https://github.com/Art-of-WiFi/UniFi-API-client.git
```
When git is done cloning, include the file containing the class like so in your code:
```php
require_once('path/to/src/Client.php');
```
### Download the Release
If you prefer not to use composer or git, you can simply [download the package](https://github.com/Art-of-WiFi/UniFi-API-client/archive/master.zip), uncompress the zip file, then include the file containing the class in your code like so:
```php
require_once('path/to/src/Client.php');
```
## Example usage
A basic example how to use the class:
```php
...
/**
* load the class using the composer autoloader
*/
require "vendor/autoload.php";
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 the alarms in a PHP array
...
$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.
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:**
>
>$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
>```
>
>Here `jl3z2shm` is the value required for $site_id.
### IMPORTANT NOTES:
In the example above, the last parameter (`true`, without quotes) that is passed to the constructor enables validation of the controller's SSL certificate which is *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:
`https://<controller IP address or FQDN>:8443/manage/site/jl3z2shm/dashboard`
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/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://www.ubnt.com/downloads/unifi/5.5.20/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

@@ -9,7 +9,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)

View File

@@ -9,7 +9,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)

View File

@@ -9,7 +9,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)

View File

@@ -0,0 +1,45 @@
<?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->set_wlansettings($wlan_id, $new_password);
/**
* provide feedback in json format
*/
echo json_encode($loginresults, JSON_PRETTY_PRINT);

View File

@@ -3,13 +3,13 @@
* 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
*/
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)
@@ -18,9 +18,9 @@ require "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);

View File

@@ -9,7 +9,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)

View File

@@ -9,7 +9,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)

View File

@@ -10,7 +10,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc there if not already present)

View File

@@ -10,7 +10,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)

View File

@@ -10,7 +10,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)

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

@@ -10,7 +10,7 @@
/**
* using the composer autoloader
*/
require "vendor/autoload.php";
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)

View File

@@ -13,29 +13,47 @@
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.md
*/
namespace UniFi_API;
/**
* the UniFi API client class
*/
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!');
trigger_error('The PHP curl extension is not loaded. Please correct this before proceeding!');
}
$this->user = trim($user);
@@ -44,16 +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!');
}
$this->check_base_url();
$this->check_site($this->site);
$this->update_unificookie();
}
function __destruct()
@@ -75,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();
@@ -89,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);
@@ -112,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) {
@@ -128,7 +143,7 @@ class Client
}
}
return $this->is_loggedin;
return false;
}
/**
@@ -160,7 +175,7 @@ class Client
public function set_site($site)
{
$this->site = $site;
$this->check_site($this->site);
return $this->site;
}
@@ -182,10 +197,12 @@ class Client
*/
public function set_debug($enable)
{
if ($enable) {
if ($enable === true) {
$this->debug = true;
return true;
} elseif ($enable === false) {
$this->debug = false;
return true;
}
return false;
@@ -194,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;
}
@@ -216,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;
}
@@ -573,7 +582,7 @@ class Client
public function stat_client($client_mac)
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/user/'.trim($client_mac)));
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/stat/user/'.trim($client_mac)));
return $this->process_response($content_decoded);
}
@@ -600,7 +609,7 @@ class Client
{
if (!$this->is_loggedin) return false;
$json = json_encode(['usergroup_id' => $group_id]);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/upd/user/'.trim($user_id), 'json='.$json));
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/upd/user/'.trim($user_id), 'json='.$json));
return $this->process_response_boolean($content_decoded);
}
@@ -625,14 +634,14 @@ class Client
}
/**
* Add user group (using REST)
* Create user group (using REST)
* ---------------------------
* returns an array containing a single object with attributes of the new usergroup ("_id", "name", "qos_rate_max_down", "qos_rate_max_up", "site_id") on success
* required parameter <group_name> = name of the user group
* optional parameter <group_dn> = limit download bandwidth in Kbps (default = -1, which sets bandwidth to unlimited)
* optional parameter <group_up> = limit upload bandwidth in Kbps (default = -1, which sets bandwidth to unlimited)
*/
public function add_usergroup($group_name, $group_dn = -1, $group_up = -1)
public function create_usergroup($group_name, $group_dn = -1, $group_up = -1)
{
if (!$this->is_loggedin) return false;
$json = json_encode(['name' => $group_name, 'qos_rate_max_down' => $group_dn, 'qos_rate_max_up' => $group_up]);
@@ -758,14 +767,14 @@ class Client
}
/**
* Add a site
* ----------
* Create a site
* -------------
* returns an array containing a single object with attributes of the new site ("_id", "desc", "name") on success
* required parameter <description> = the long name for the new site
*
* NOTES: immediately after being added, the new site will be available in the output of the "list_sites" function
*/
public function add_site($description)
public function create_site($description)
{
if (!$this->is_loggedin) return false;
$json = json_encode(['desc' => $description, 'cmd' => 'add-site']);
@@ -836,18 +845,6 @@ class Client
return $this->process_response($content_decoded);
}
/**
* List networkconf
* ----------------
* returns an array of network configuration data
*/
public function list_networkconf()
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/list/networkconf'));
return $this->process_response($content_decoded);
}
/**
* List vouchers
* -------------
@@ -907,21 +904,21 @@ class Client
}
/**
* List hotspot operators
* ----------------------
* List hotspot operators (using REST)
* -----------------------------------
* returns an array of hotspot operators
*/
public function list_hotspotop()
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/list/hotspotop'));
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/hotspotop'));
return $this->process_response($content_decoded);
}
/**
* 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,
@@ -930,6 +927,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)
{
@@ -1184,8 +1183,8 @@ class Client
}
/**
* Set access point radio settings
* -------------------------------
* Update access point radio settings
* ----------------------------------
* return true on success
* required parameter <ap_id>
* required parameter <radio>(default=ng)
@@ -1203,8 +1202,8 @@ class Client
}
/**
* Set guest login settings
* ------------------------
* Update guest login settings
* ---------------------------
* return true on success
* required parameter <portal_enabled>
* required parameter <portal_customized>
@@ -1260,8 +1259,82 @@ class Client
}
/**
* Add a wlan
* ----------
* List network settings (using REST)
* ----------------------------------
* returns an array of (non-wireless) networks and their settings
*/
public function list_networkconf()
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/networkconf'));
return $this->process_response($content_decoded);
}
/**
* Create a network (using REST)
* -----------------------------
* return an array with a single object containing details of the new network on success, else return false
* required parameter <network_settings> = stdClass object or associative array containing the configuration to apply to the network, must be a (partial)
* object structured in the same manner as is returned by list_networkconf() for the specific network type.
* Do not include the _id property, it will be assigned by the controller and returned upon success.
*/
public function create_network($network_settings)
{
if (!$this->is_loggedin) return false;
$this->request_type = 'POST';
$json = json_encode($network_settings);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/networkconf/', 'json='.$json));
return $this->process_response($content_decoded);
}
/**
* Update network settings, base (using REST)
* ------------------------------------------
* return true on success
* required parameter <network_id>
* required parameter <network_settings> = stdClass object or associative array containing the configuration to apply to the network, must be a (partial)
* object/array structured in the same manner as is returned by list_networkconf() for the network.
*/
public function set_networksettings_base($network_id, $network_settings)
{
if (!$this->is_loggedin) return false;
$this->request_type = 'PUT';
$json = json_encode($network_settings);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/networkconf/'.trim($network_id), 'json='.$json));
return $this->process_response_boolean($content_decoded);
}
/**
* Delete a network (using REST)
* -----------------------------
* return true on success
* required parameter <network_id> = 24 char string; _id of the network which can be found with the list_networkconf() function
*/
public function delete_network($network_id)
{
if (!$this->is_loggedin) return false;
$this->request_type = 'DELETE';
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/networkconf/'.trim($network_id)));
return $this->process_response_boolean($content_decoded);
}
/**
* List wlan settings (using REST)
* -------------------------------
* returns an array of wireless networks and their settings, or an array containing a single wireless network when using
* the <wlan_id> parameter
* optional parameter <wlan_id> = 24 char string; _id of the wlan to fetch the settings for
*/
public function list_wlanconf($wlan_id = null)
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/wlanconf/'.trim($wlan_id)));
return $this->process_response($content_decoded);
}
/**
* Create a wlan
* -------------
* return true on success
* required parameter <name> = string; SSID
* required parameter <x_passphrase> = string; new pre-shared key, minimal length is 8 characters, maximum length is 63
@@ -1322,40 +1395,12 @@ class Client
}
/**
* List wlan settings (using REST)
* -------------------------------
* returns an array of wireless networks and their settings, or an array containing a single wireless network when using
* the <wlan_id> parameter
* optional parameter <wlan_id> = 24 char string; _id of the wlan to fetch the settings for
*/
public function list_wlanconf($wlan_id = null)
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/wlanconf/'.trim($wlan_id)));
return $this->process_response($content_decoded);
}
/**
* Delete a wlan (using REST)
* --------------------------
* return true on success
* required parameter <wlan_id> = 24 char string; _id of the wlan that can be found with the list_wlanconf() function
*/
public function delete_wlan($wlan_id)
{
if (!$this->is_loggedin) return false;
$this->request_type = 'DELETE';
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/wlanconf/'.trim($wlan_id)));
return $this->process_response_boolean($content_decoded);
}
/**
* Set wlan settings, base (using REST)
* ------------------------------------
* Update wlan settings, base (using REST)
* ---------------------------------------
* return true on success
* required parameter <wlan_id>
* required parameter <wlan_settings> = stdClass object containing the configuration of the wlan to apply, must be a (partial) object structured
* in the same manner as is returned by list_wlanconf() for a specific wlan)
* required parameter <wlan_settings> = stdClass object or associative array containing the configuration to apply to the wlan, must be a
* (partial) object/array structured in the same manner as is returned by list_wlanconf() for the wlan.
*/
public function set_wlansettings_base($wlan_id, $wlan_settings)
{
@@ -1367,8 +1412,8 @@ class Client
}
/**
* Set basic wlan settings
* -----------------------
* Update basic wlan settings
* --------------------------
* return true on success
* required parameter <wlan_id>
* required parameter <x_passphrase> = new pre-shared key, minimal length is 8 characters, maximum length is 63,
@@ -1399,7 +1444,21 @@ class Client
}
/**
* Set MAC filter for a wlan
* Delete a wlan (using REST)
* --------------------------
* return true on success
* required parameter <wlan_id> = 24 char string; _id of the wlan which can be found with the list_wlanconf() function
*/
public function delete_wlan($wlan_id)
{
if (!$this->is_loggedin) return false;
$this->request_type = 'DELETE';
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/wlanconf/'.trim($wlan_id)));
return $this->process_response_boolean($content_decoded);
}
/**
* Update MAC filter for a wlan
* ----------------------------
* return true on success
* required parameter <wlan_id>
@@ -1527,11 +1586,26 @@ class Client
return $this->process_response($content_decoded);
}
/**
* List Radius profiles (using REST)
* --------------------------------------
* returns an array of objects containing all Radius profiles for the current site
*
* NOTES:
* - this function/method is only supported on controller versions 5.5.19 and later
*/
public function list_radius_profiles()
{
if (!$this->is_loggedin) return false;
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/radiusprofile'));
return $this->process_response($content_decoded);
}
/**
* List Radius user accounts (using REST)
* --------------------------------------
* returns an array of objects containing all Radius accounts for the current site
*
*
* NOTES:
* - this function/method is only supported on controller versions 5.5.19 and later
*/
@@ -1542,6 +1616,100 @@ class Client
return $this->process_response($content_decoded);
}
/**
* Create a Radius user account (using REST)
* -----------------------------------------
* returns an array containing a single object for the newly created account upon success, else returns false
* required parameter <name> = string; name for the new account
* required parameter <x_password> = string; password for the new account
* required parameter <tunnel_type> = integer; must be one of the following values:
* 1 Point-to-Point Tunneling Protocol (PPTP)
* 2 Layer Two Forwarding (L2F)
* 3 Layer Two Tunneling Protocol (L2TP)
* 4 Ascend Tunnel Management Protocol (ATMP)
* 5 Virtual Tunneling Protocol (VTP)
* 6 IP Authentication Header in the Tunnel-mode (AH)
* 7 IP-in-IP Encapsulation (IP-IP)
* 8 Minimal IP-in-IP Encapsulation (MIN-IP-IP)
* 9 IP Encapsulating Security Payload in the Tunnel-mode (ESP)
* 10 Generic Route Encapsulation (GRE)
* 11 Bay Dial Virtual Services (DVS)
* 12 IP-in-IP Tunneling
* 13 Virtual LANs (VLAN)
* required parameter <tunnel_medium_type> = integer; must be one of the following values:
* 1 IPv4 (IP version 4)
* 2 IPv6 (IP version 6)
* 3 NSAP
* 4 HDLC (8-bit multidrop)
* 5 BBN 1822
* 6 802 (includes all 802 media plus Ethernet "canonical format")
* 7 E.163 (POTS)
* 8 E.164 (SMDS, Frame Relay, ATM)
* 9 F.69 (Telex)
* 10 X.121 (X.25, Frame Relay)
* 11 IPX
* 12 Appletalk
* 13 Decnet IV
* 14 Banyan Vines
* 15 E.164 with NSAP format subaddress
* optional parameter <vlan> = integer; VLAN to assign to the account
*
* NOTES:
* - this function/method is only supported on controller versions 5.5.19 and later
*/
public function create_radius_account($name, $x_password, $tunnel_type, $tunnel_medium_type, $vlan = null)
{
if (!$this->is_loggedin) return false;
$this->request_type = 'POST';
$account_details = [
'name' => $name,
'x_password' => $x_password,
'tunnel_type' => (int) $tunnel_type,
'tunnel_medium_type' => (int) $tunnel_medium_type
];
if (isset($vlan)) $account_details['vlan'] = (int) $vlan;
$json = json_encode($account_details);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/account', 'json='.$json));
return $this->process_response($content_decoded);
}
/**
* Update Radius account, base (using REST)
* ----------------------------------------
* return true on success
* required parameter <account_id> = 24 char string; _id of the account which can be found with the list_radius_accounts() function
* required parameter <account_details> = stdClass object or associative array containing the new profile to apply to the account, must be a (partial)
* object/array structured in the same manner as is returned by list_radius_accounts() for the account.
*
* NOTES:
* - this function/method is only supported on controller versions 5.5.19 and later
*/
public function set_radius_account_base($account_id, $account_details)
{
if (!$this->is_loggedin) return false;
$this->request_type = 'PUT';
$json = json_encode($account_details);
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/account/'.trim($account_id), 'json='.$json));
return $this->process_response_boolean($content_decoded);
}
/**
* Delete a Radius account (using REST)
* ------------------------------------
* return true on success
* required parameter <account_id> = 24 char string; _id of the account which can be found with the list_radius_accounts() function
*
* NOTES:
* - this function/method is only supported on controller versions 5.5.19 and later
*/
public function delete_radius_account($account_id)
{
if (!$this->is_loggedin) return false;
$this->request_type = 'DELETE';
$content_decoded = json_decode($this->exec_curl($this->baseurl.'/api/s/'.$this->site.'/rest/account/'.trim($account_id)));
return $this->process_response_boolean($content_decoded);
}
/****************************************************************
* "Aliases" for deprecated functions from here, to support
* backward compatibility:
@@ -1558,6 +1726,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);
}
@@ -1573,6 +1746,7 @@ class Client
'Function set_locate_ap() has been deprecated, use locate_ap() instead.',
E_USER_DEPRECATED
);
return $this->locate_ap($mac, true);
}
@@ -1588,6 +1762,7 @@ class Client
'Function unset_locate_ap() has been deprecated, use locate_ap() instead.',
E_USER_DEPRECATED
);
return $this->locate_ap($mac, false);
}
@@ -1602,6 +1777,7 @@ class Client
'Function site_ledson() has been deprecated, use site_leds() instead.',
E_USER_DEPRECATED
);
return $this->site_leds(true);
}
@@ -1616,6 +1792,7 @@ class Client
'Function site_ledsoff() has been deprecated, use site_leds() instead.',
E_USER_DEPRECATED
);
return $this->site_leds(false);
}
@@ -1632,23 +1809,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);
}
}
@@ -1670,19 +1839,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
*/
@@ -1690,6 +1884,7 @@ class Client
{
$ch = $this->get_curl_obj();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
if (trim($data) != '') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
@@ -1702,32 +1897,34 @@ class Client
} 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 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();
@@ -1741,9 +1938,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);
@@ -1764,23 +1961,28 @@ class Client
}
curl_close($ch);
/**
* set request_type value back to default, just in case
*/
$this->request_type = 'POST';
return $content;
}
/**
* 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);