diff --git a/README.md b/README.md index e682434..c124b4c 100755 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ ## 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). +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 @@ -116,11 +118,11 @@ Please refer to the source code for more details on each function/method and it' ## 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 @@ -174,14 +176,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 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`, 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: @@ -206,4 +213,4 @@ This class is largely based on the work done by the following developers: ## 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. diff --git a/examples/change_wlan_password.php b/examples/change_wlan_password.php new file mode 100755 index 0000000..40ee269 --- /dev/null +++ b/examples/change_wlan_password.php @@ -0,0 +1,45 @@ +'; + +/** + * the id of the WLAN you wish to modify + */ +$wlan_id = ''; + +/** + * the new WPA2 password/PSK to apply to the above WLAN + */ +$new_password = ''; + +/** + * 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); diff --git a/examples/create_voucher.php b/examples/create_voucher.php index b5d1a6e..509d980 100755 --- a/examples/create_voucher.php +++ b/examples/create_voucher.php @@ -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('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 @@ $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); diff --git a/examples/test_connection.php b/examples/test_connection.php index 98c878b..cae8268 100755 --- a/examples/test_connection.php +++ b/examples/test_connection.php @@ -34,7 +34,8 @@ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); /** - * This cURL option can have a value of 0-6 see this URL for more details: + * 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 */ @@ -64,4 +65,4 @@ print PHP_EOL . '$results:' . PHP_EOL; print_r($results); -print PHP_EOL; +print PHP_EOL; \ No newline at end of file diff --git a/src/Client.php b/src/Client.php index 9be8b89..98382ae 100755 --- a/src/Client.php +++ b/src/Client.php @@ -24,18 +24,33 @@ 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; - private $cookies = ''; - private $request_type = 'POST'; - private $connect_timeout = 10; - private $last_results_raw = null; - private $last_error_message = null; - - function __construct($user, $password, $baseurl = '', $site = '', $version = '') + 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; + + /** + * Construct an instance of the UniFi API client class + * --------------------------------------------------- + * return a new class instance + * required parameter = string; user name to use when connecting to the UniFi controller + * required parameter = string; password to use when connecting to the UniFi controller + * optional parameter = string; base URL of the UniFi controller, must include "https://" prefix and port suffix (:8443) + * optional parameter = string; short site name to access, defaults to "default" + * optional parameter = string; the version number of the controller, defaults to "5.4.16" + * optional parameter = 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!'); @@ -47,20 +62,14 @@ function __construct($user, $password, $baseurl = '', $site = '', $version = '') 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']; - } - - $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 ($ssl_verify === true) { + $this->curl_ssl_verify_peer = true; + $this->curl_ssl_verify_host = 2; } - 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() @@ -82,12 +91,9 @@ function __destruct() 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(); @@ -101,9 +107,7 @@ public function login() */ $content = curl_exec($ch); - if (curl_errno($ch)) { - trigger_error('cURL error: '.curl_error($ch)); - } + if (curl_errno($ch)) trigger_error('cURL error: '.curl_error($ch)); if ($this->debug) { curl_setopt($ch, CURLOPT_VERBOSE, true); @@ -124,13 +128,12 @@ public function login() 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) { @@ -140,7 +143,7 @@ public function login() } } - return $this->is_loggedin; + return false; } /** @@ -171,11 +174,8 @@ public function logout() */ public function set_site($site) { - if (strlen($site) !== 8 && $site !== 'default' && $this->debug) { - error_log('The provided (short) site name is probably incorrect'); - } - $this->site = $site; + $this->check_site($this->site); return $this->site; } @@ -218,10 +218,7 @@ public function set_debug($enable) 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 ($return_json) return json_encode($this->last_results_raw, JSON_PRETTY_PRINT); return $this->last_results_raw; } @@ -235,10 +232,7 @@ public function get_last_results_raw($return_json = false) */ public function get_last_error_message() { - if ($this->last_error_message !== null) { - return $this->last_error_message; - } - + if ($this->last_error_message !== null) return $this->last_error_message; return false; } @@ -924,7 +918,7 @@ public function list_hotspotop() /** * 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 the voucher is valid after activation (expiration time) * optional parameter = number of vouchers to create, default value is 1 * optional parameter = single-use or multi-use vouchers, string value '0' is for multi-use, '1' is for single-use, @@ -933,6 +927,8 @@ public function list_hotspotop() * optional parameter = upload speed limit in kbps * optional parameter = download speed limit in kbps * optional parameter = 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 +1726,11 @@ public function delete_radius_account($account_id) */ 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 +1809,15 @@ private function process_response($response) 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 +1839,44 @@ private function process_response_boolean($response) * 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 */ @@ -1879,9 +1897,7 @@ private function exec_curl($url, $data = '') } 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'); } /** @@ -1896,21 +1912,19 @@ private function exec_curl($url, $data = '') /** * has the session timed out? */ - $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $json_decoded_content = json_decode($content, true); - if ($httpcode == 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'); - } + 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(); @@ -1924,9 +1938,9 @@ private function exec_curl($url, $data = '') /** * 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); @@ -1957,20 +1971,18 @@ private function exec_curl($url, $data = '') } /** - * 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);