Compare commits

..

5 Commits

Author SHA1 Message Date
malle-pietje
a3fc0732e2 API client class v1.1.46
- applied patches to update_switch_poe-mode.php as suggested by scrutinizer-ci.com
- placed warning that UniFI OS is not (yet) supported
2020-01-31 12:14:52 +01:00
malle-pietje
ca25c8ab52 re-added PHP_EOL in several places 2020-01-30 10:14:55 +01:00
malle-pietje
6754eb5041 API client class v1.1.45
- added function/method force_provision(), contributed by @VWT-Dan
- added example update_switch_poe-mode.php, contributed by @Kaltt
2020-01-30 10:09:34 +01:00
malle-pietje
2ac791a353 API client class v1.1.44
- added example script reconnect_client.php
- fixed typo in URL linking to UniFi section on the UI.com site
- add function/method reboot_cloudkey(), contributed by @leonardogyn
2020-01-27 13:19:49 +01:00
malle-pietje
3fd8e69b4a API client class v1.1.43
- updated code and instructions for `set_guestlogin_settings()`, thanks to @stoehrmark for reporting the issue
- added list_connected_users.php example contributed by @gahujipo
- added restart_device() which replaces restart_ap(), contributed by @leonardogyn
- code styling cleanup across `Client.php`
2019-12-13 09:15:10 +01:00
6 changed files with 317 additions and 43 deletions

View File

@@ -1,15 +1,19 @@
## UniFi Controller API client class
A PHP class which provides access to Ubiquiti's [**UniFi SDN Controller API**](https://unifi-sdn.ui.com/), versions 4.X.X and 5.X.X of the UniFi SDN Controller software are supported (version 5.11.39 has been confirmed to work). It's a standalone version of the class which is used in our API browser tool which can be found [here](https://github.com/Art-of-WiFi/UniFi-API-browser).
A PHP class which provides access to Ubiquiti's [**UniFi SDN Controller**](https://unifi-sdn.ui.com/) API, versions 4.X.X and 5.X.X of the UniFi SDN Controller software are supported (version 5.12.35 has been confirmed to work). It's a standalone version of the class which is used in our API browser tool which can be found [here](https://github.com/Art-of-WiFi/UniFi-API-browser).
This class can be installed manually or using composer/[packagist](https://packagist.org/packages/art-of-wifi/unifi-api-client) for easy inclusion in your projects.
## Requirements
- a web server with PHP and cURL modules installed (tested on Apache 2.4 with PHP Version 5.6.1 and cURL 7.42.1 and with PHP 7.2.10 and cURL 7.58.0)
- a web server with PHP and cURL modules installed (tested on Apache 2.4 with PHP Version 5.6.1 and cURL 7.42.1 and with PHP 7.2.24 and cURL 7.58.0)
- network connectivity between this web server and the server and port (normally TCP port 8443) where the UniFi Controller is running
## Installation ##
## UniFi OS Support
Currently, UniFi OS-based controllers (UniFi Dream Machine Pro) are **not supported** due to several breaking changes to the API.
## Installation
You can use [Composer](#composer), [Git](#git) or simply [Download the Release](#download-the-release) to install the API client class.
@@ -169,7 +173,9 @@ The class currently supports the following functions/methods to GET/POST/PUT/DEL
- power_cycle_switch_port()
- reconnect_sta()
- rename_ap()
- restart_ap()
- restart_ap() (deprecated but still available as alias)
- restart_device()
- reboot_cloudkey()
- revoke_voucher()
- set_ap_radiosettings()
- set_device_settings_base()
@@ -261,7 +267,7 @@ This class is based on the initial work by the following developers:
and the API as published by Ubiquiti:
- https://dl.ubnt.com/unifi/5.10.19/unifi_sh_api
- https://dl.ui.com/unifi/5.12.35/unifi_sh_api
## Important Disclaimer

View File

@@ -3,7 +3,7 @@
* PHP API usage example
*
* contributed by: @4oo4
* description: example script to check and upgrade device firmware (can be scheduled with systemd/cron)
* description: example script to upgrade device firmware (can be scheduled with systemd/cron)
* to the most current version
*/
require_once('vendor/autoload.php');

View File

@@ -0,0 +1,37 @@
<?php
/**
* PHP API usage example
*
* contributed by: @gahujipo
* description: example to pull connected users and their details from the UniFi controller and output the results
* in JSON format
*/
/**
* 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 short name of the site which you wish to query
*/
$site_id = '<enter your site id here>';
/**
* initialize the UniFi API connection class and log in to the controller and pull the requested data
*/
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
$set_debug_mode = $unifi_connection->set_debug($debug);
$loginresults = $unifi_connection->login();
$clients_array = $unifi_connection->list_clients();
/**
* output the results in JSON format
*/
header('Content-Type: application/json; charset=utf-8');
echo json_encode($clients_array);

45
examples/reconnect_client.php Executable file
View File

@@ -0,0 +1,45 @@
<?php
/**
* PHP API usage example
*
* contributed by: Art of WiFi
* description: example basic PHP script to force a client device to reconnect
*/
/**
* 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 MAC address to reconnect
*/
$mac_to_reconnect = '<MAC address>';
/**
* site where the above MAC address is connected
*/
$site_id = '<enter your site id 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();
/**
* then we force the device to reconnect
*/
$reconnect_result = $unifi_connection->reconnect_sta($mac_to_reconnect);
/**
* provide feedback in json format
*/
echo json_encode($reconnect_result, JSON_PRETTY_PRINT);

View File

@@ -0,0 +1,94 @@
<?php
/**
* PHP API usage example to turn the PoE of the selected switch ports to "off" or "auto"
*
* contributed by: @Kaltt
* description: A use case for this script is to turn off the PoE of the port where a camera is connected in order to turn off the camera
*
* usage: If the file is called via a web URL, it should be called like: update_switch_poe-mode.php?poe_mode=off
* If the file is called via the command line, it should be called like: php update_switch_poe-mode.php off
* The values can be "off" or "auto"
*/
/**
* using the composer autoloader
*/
require_once('vendor/autoload.php');
/**
* include the config file (place your credentials etc. there if not already present)
* see the config.template.php file for an example
*/
require_once('config.php');
/**
* the site to use to log in to the controller
*/
$site_id = '<short site name of a site the credentials used have access to>';
/**
* the MAC address of the AC-IW device to re-configure
*/
$device_mac = '<enter MAC address>';
/**
* $lanports is an array that defines which ports should be changed
*/
$lanports = [6];
/**
* This is the function that reads out the current port configuration and changes the value for the poe_mode for the ports defined in $lanports
*/
function update_ports($running_config, $ports, $poe_mode){
/**
* Update already non-default ports
*/
$running_config_count = count($running_config);
for($i = 0; $i < $running_config_count; $i++){
if(in_array($running_config[$i]->port_idx, $ports)){
$running_config[$i]->poe_mode = $poe_mode;
unset($ports[array_search($running_config[$i]->port_idx, $ports)]);
}
}
$add_conf = [];
foreach($ports as $port){
$add_conf[] = [
'port_idx' => $port,
'poe_mode' => $poe_mode
];
}
return array_merge($running_config, $add_conf);
}
$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion, false);
$set_debug_mode = $unifi_connection->set_debug(false);
$loginresults = $unifi_connection->login();
$data = $unifi_connection->list_devices($device_mac);
$device_id = $data[0]->device_id;
$current_conf = $data[0]->port_overrides;
/**
* This reads in the values provided via URL or in the command line, if nothing is set than it will poe_mode will be set to "auto"
*/
if (isset($_GET[$poe_mode])) {
$poe_mode = $_GET[poe_mode];
} elseif (isset($argv[1])) {
$poe_mode = $argv[1];
} else {
$poe_mode = 'auto';
}
$new_ports_config = [
'port_overrides' => update_ports($current_conf, $lanports, $poe_mode)
];
$update_device = $unifi_connection->set_device_settings_base($device_id, $new_ports_config);
if (!$update_device) {
$error = $unifi_connection->get_last_results_raw();
echo json_encode($error, JSON_PRETTY_PRINT);
}
echo json_encode($update_device, JSON_PRETTY_PRINT);

View File

@@ -73,7 +73,7 @@ class Client
$this->version = trim($version);
}
if ($ssl_verify === true) {
if ((boolean)$ssl_verify === true) {
$this->curl_ssl_verify_peer = true;
$this->curl_ssl_verify_host = 2;
}
@@ -134,13 +134,13 @@ class Client
if ($this->debug) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
print '<pre>';
print PHP_EOL . '<pre>';
print PHP_EOL . '-----------LOGIN-------------' . PHP_EOL;
print_r(curl_getinfo($ch));
print PHP_EOL . '----------RESPONSE-----------' . PHP_EOL;
print $content;
print PHP_EOL . '-----------------------------' . PHP_EOL;
print '</pre>';
print '</pre>' . PHP_EOL;
}
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
@@ -537,9 +537,10 @@ class Client
return false;
}
$end = is_null($end) ? (time() * 1000) : intval($end);
$start = is_null($start) ? $end - (12 * 3600 * 1000) : intval($start);
$payload = ['attrs' => ['bytes', 'num_sta', 'time'], 'start' => $start, 'end' => $end];
$end = is_null($end) ? (time() * 1000) : intval($end);
$start = is_null($start) ? $end - (12 * 3600 * 1000) : intval($start);
$attributes = ['bytes', 'num_sta', 'time'];
$payload = ['attrs' => $attributes, 'start' => $start, 'end' => $end];
if (!is_null($mac)) {
$payload['mac'] = strtolower($mac);
}
@@ -567,9 +568,10 @@ class Client
return false;
}
$end = is_null($end) ? (time() * 1000) : intval($end);
$start = is_null($start) ? $end - (7 * 24 * 3600 * 1000) : intval($start);
$payload = ['attrs' => ['bytes', 'num_sta', 'time'], 'start' => $start, 'end' => $end];
$end = is_null($end) ? (time() * 1000) : intval($end);
$start = is_null($start) ? $end - (7 * 24 * 3600 * 1000) : intval($start);
$attributes = ['bytes', 'num_sta', 'time'];
$payload = ['attrs' => $attributes, 'start' => $start, 'end' => $end];
if (!is_null($mac)) {
$payload['mac'] = strtolower($mac);
}
@@ -597,9 +599,10 @@ class Client
return false;
}
$end = is_null($end) ? (time() * 1000) : intval($end);
$start = is_null($start) ? $end - (7 * 24 * 3600 * 1000) : intval($start);
$payload = ['attrs' => ['bytes', 'num_sta', 'time'], 'start' => $start, 'end' => $end];
$end = is_null($end) ? (time() * 1000) : intval($end);
$start = is_null($start) ? $end - (7 * 24 * 3600 * 1000) : intval($start);
$attributes = ['bytes', 'num_sta', 'time'];
$payload = ['attrs' => $attributes, 'start' => $start, 'end' => $end];
if (!is_null($mac)) {
$payload['mac'] = strtolower($mac);
}
@@ -1378,6 +1381,27 @@ class Client
return $this->process_response($response);
}
/**
* Generate backup
* ---------------------------
* returns a URL from where the backup file can be downloaded once generated
*
* NOTES:
* this is an experimental function, please do not use unless you know exactly
* what you're doing
*/
public function generate_backup()
{
if (!$this->is_loggedin) {
return false;
}
$payload = ['cmd' => 'backup'];
$response = $this->exec_curl('/api/s/' . $this->site . '/cmd/backup', $payload);
return $this->process_response($response);
}
/**
* List auto backups
* ---------------------------
@@ -2190,23 +2214,70 @@ class Client
}
/**
* Reboot an access point
* Reboot a device
* ----------------------
* return true on success
* required parameter <mac> = device MAC address
* required parameter <mac> = device MAC address
* optional parameter <type> = string; two options: 'soft' or 'hard', defaults to soft
* soft can be used for all devices, requests a plain restart of that device
* hard is special for PoE switches and besides the restart also requests a
* power cycle on all PoE capable ports. Keep in mind that a 'hard' reboot
* does *NOT* trigger a factory-reset, as it somehow could suggest.
*/
public function restart_ap($mac)
public function restart_device($mac, $type = 'soft')
{
if (!$this->is_loggedin) {
return false;
}
$payload = ['cmd' => 'restart', 'mac' => strtolower($mac)];
$payload = ['cmd' => 'restart', 'mac' => strtolower($mac)];
if (!is_null($type) && in_array($type, ['soft', 'hard'])) {
$payload['type'] = strtolower($type);
}
$response = $this->exec_curl('/api/s/' . $this->site . '/cmd/devmgr', $payload);
return $this->process_response_boolean($response);
}
/**
* Force provision of a device
* ---------------------------
* return true on success
* required parameter <mac> = device MAC address
*/
public function force_provision($mac)
{
if (!$this->is_loggedin) {
return false;
}
$payload = ['mac' => strtolower($mac), 'cmd' => 'force-provision'];
$response = $this->exec_curl('/api/s/' . $this->site . '/cmd/devmgr', $payload);
return $this->process_response_boolean($response);
}
/**
* Reboot a UniFi CloudKey
* -----------------------
* return true on success
*
* This API call does nothing on UniFi controllers *not* running on a UniFi CloudKey device
*/
public function reboot_cloudkey()
{
if (!$this->is_loggedin) {
return false;
}
$payload = ['cmd' => 'reboot'];
$response = $this->exec_curl('/api/s/' . $this->site . '/cmd/system', $payload);
return $this->process_response_boolean($response);
}
/**
* Disable/enable an access point (using REST)
* -------------------------------------------
@@ -2356,9 +2427,6 @@ class Client
* required parameter <wlantype_id> = string; WLAN type, can be either 'ng' (for WLANs 2G (11n/b/g)) or 'na' (WLANs 5G (11n/a/ac))
* required parameter <device_id> = string; _id value of the access point to be modified
* required parameter <wlangroup_id> = string; _id value of the WLAN group to assign device to
*
* NOTES:
* - can for example be used to turn WiFi off
*/
public function set_ap_wlangroup($wlantype_id, $device_id, $wlangroup_id)
{
@@ -2370,7 +2438,11 @@ class Client
return false;
}
$payload = ['wlan_overrides' => [], 'wlangroup_id_' . $wlantype_id => $wlangroup_id];
$payload = [
'wlan_overrides' => [],
'wlangroup_id_' . $wlantype_id => $wlangroup_id
];
$response = $this->exec_curl('/api/s/' . $this->site . '/upd/device/' . trim($device_id), $payload);
return $this->process_response_boolean($response);
@@ -2380,14 +2452,15 @@ class Client
* Update guest login settings
* ---------------------------
* return true on success
* required parameter <portal_enabled>
* required parameter <portal_customized>
* required parameter <redirect_enabled>
* required parameter <redirect_url>
* required parameter <x_password>
* required parameter <expire_number>
* required parameter <expire_unit>
* required parameter <site_id>
* required parameter <portal_enabled> = boolean; enable/disable the captive portal
* required parameter <portal_customized> = boolean; enable/disable captive portal customizations
* required parameter <redirect_enabled> = boolean; enable/disable captive portal redirect
* required parameter <redirect_url> = string; url to redirect to, must include the http/https prefix, no trailing slashes
* required parameter <x_password> = string; the captive portal (simple) password
* required parameter <expire_number> = numeric; number of units for the authorization expiry
* required parameter <expire_unit> = numeric; number of minutes within a unit (a value 60 is required for hours)
* required parameter <section_id> = 24 char string; value of _id for the site settings section where key = "guest_access", settings can be obtained
* using the list_settings() function
*
* NOTES:
* - both portal parameters are set to the same value!
@@ -2400,7 +2473,7 @@ class Client
$x_password,
$expire_number,
$expire_unit,
$site_id
$section_id
) {
if (!$this->is_loggedin) {
return false;
@@ -2414,7 +2487,7 @@ class Client
'x_password' => $x_password,
'expire_number' => $expire_number,
'expire_unit' => $expire_unit,
'site_id' => $site_id
'_id' => $section_id
];
$response = $this->exec_curl('/api/s/' . $this->site . '/set/setting/guest_access', $payload);
@@ -3248,14 +3321,11 @@ class Client
}
/**
* Execute specific command
* ------------------------
* Execute specific stats command
* ------------------------------
* return true on success
* required parameter <command> = string; command to execute, known valid values
* 'reset-dpi': reset all DPI counters for the current site
*
* NOTE:
* the provided <command> parameter isn't validated so make sure you're using a correct value
*/
public function cmd_stat($command)
{
@@ -3263,6 +3333,10 @@ class Client
return false;
}
if (!in_array($command, ['reset-dpi'])) {
return false;
}
$payload = ['cmd' => trim($command)];
$response = $this->exec_curl('/api/s/' . $this->site . '/cmd/stat', $payload);
@@ -3355,6 +3429,23 @@ class Client
return $this->site_leds(false);
}
/**
* Reboot an access point
* ----------------------
* return true on success
* required parameter <mac> = device MAC address
*/
public function restart_ap($mac)
{
trigger_error(
'Function restart_ap() has been deprecated, use restart_device() instead.',
E_USER_DEPRECATED
);
return $this->restart_device($mac);
}
/**
* Custom API request
* ------------------
@@ -3718,8 +3809,8 @@ class Client
*/
private function check_site($site)
{
if ($this->debug && strlen($site) !== 8 && $site !== 'default') {
error_log('The provided (short) site name is probably incorrect');
if ($this->debug && preg_match("/\s/", $site)) {
error_log('The provided (short) site name may not contain spaces');
}
}
@@ -3743,6 +3834,7 @@ class Client
} else {
$json_payload = '';
$url = $this->baseurl . $path;
curl_setopt($ch, CURLOPT_URL, $url);
if (!empty($payload)) {