diff --git a/MySQL_database.sql b/MySQL_database.sql deleted file mode 100644 index c8b9fda..0000000 --- a/MySQL_database.sql +++ /dev/null @@ -1,106 +0,0 @@ -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET NAMES utf8 */; -/*!50503 SET NAMES utf8mb4 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; - - --- Dumping database structure for bunnycdn -CREATE DATABASE IF NOT EXISTS `bunnycdn` /*!40100 DEFAULT CHARACTER SET latin1 */; -USE `bunnycdn`; - --- Dumping structure for table bunnycdn.actions -CREATE TABLE IF NOT EXISTS `actions` ( - `task` varchar(24) DEFAULT NULL, - `zone_name` varchar(124) DEFAULT NULL, - `file` varchar(124) DEFAULT NULL, - `file_other` varchar(124) DEFAULT NULL, - `datetime` datetime DEFAULT current_timestamp() -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- Data exporting was unselected. --- Dumping structure for table bunnycdn.deleted_files -CREATE TABLE IF NOT EXISTS `deleted_files` ( - `zone_name` varchar(124) DEFAULT NULL, - `file` varchar(124) DEFAULT NULL, - `dir` varchar(124) DEFAULT NULL, - `datetime` datetime DEFAULT current_timestamp() -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- Data exporting was unselected. --- Dumping structure for table bunnycdn.file_history -CREATE TABLE IF NOT EXISTS `file_history` ( - `zone_name` varchar(124) DEFAULT NULL, - `new_name` varchar(124) DEFAULT NULL, - `new_dir` varchar(124) DEFAULT NULL, - `old_name` varchar(124) DEFAULT NULL, - `old_dir` varchar(124) DEFAULT NULL, - `datetime` datetime NOT NULL DEFAULT current_timestamp() -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- Data exporting was unselected. --- Dumping structure for table bunnycdn.log_main -CREATE TABLE IF NOT EXISTS `log_main` ( - `zid` int(11) DEFAULT NULL, - `rid` varchar(64) NOT NULL, - `result` varchar(4) DEFAULT NULL, - `file_url` varchar(224) DEFAULT NULL, - `referer` varchar(224) DEFAULT NULL, - `datetime` datetime DEFAULT NULL, - PRIMARY KEY (`rid`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- Data exporting was unselected. --- Dumping structure for table bunnycdn.log_more -CREATE TABLE IF NOT EXISTS `log_more` ( - `zid` int(11) NOT NULL, - `rid` varchar(124) NOT NULL, - `status` int(11) DEFAULT NULL, - `bytes` int(11) DEFAULT NULL, - `ip` varchar(16) DEFAULT NULL, - `user_agent` varchar(224) DEFAULT NULL, - `cdn_dc` varchar(6) DEFAULT NULL, - `country_code` varchar(6) DEFAULT NULL, - PRIMARY KEY (`rid`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- Data exporting was unselected. --- Dumping structure for table bunnycdn.pullzones -CREATE TABLE IF NOT EXISTS `pullzones` ( - `id` int(11) NOT NULL, - `name` varchar(64) DEFAULT NULL, - `origin_url` varchar(124) DEFAULT NULL, - `enabled` tinyint(1) DEFAULT 1, - `bandwidth_used` int(11) DEFAULT 0, - `bandwidth_limit` int(11) DEFAULT 0, - `monthly_charge` decimal(12,12) DEFAULT 0.000000000000, - `storage_zone_id` int(11) DEFAULT NULL, - `zone_us` tinyint(1) DEFAULT 0, - `zone_eu` tinyint(1) DEFAULT 0, - `zone_asia` tinyint(1) DEFAULT 0, - `zone_sa` tinyint(1) DEFAULT 0, - `zone_af` tinyint(1) DEFAULT 0, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- Data exporting was unselected. --- Dumping structure for table bunnycdn.storagezones -CREATE TABLE IF NOT EXISTS `storagezones` ( - `id` int(11) NOT NULL, - `name` varchar(64) NOT NULL, - `storage_used` int(11) NOT NULL DEFAULT 0, - `files_stored` int(11) NOT NULL DEFAULT 0, - `enabled` tinyint(1) NOT NULL DEFAULT 1, - `date_modified` datetime NOT NULL, - `zone_us` tinyint(1) DEFAULT 0, - `zone_eu` tinyint(1) DEFAULT 0, - `zone_asia` tinyint(1) DEFAULT 0, - `zone_sa` tinyint(1) DEFAULT 0, - `zone_af` tinyint(1) DEFAULT 0, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- Data exporting was unselected. -/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; -/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; diff --git a/README.md b/README.md index 2d25942..a4ac5a8 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,19 @@ # BunnyCDN API Class -The most comprehensive, feature packed and easy to use PHP class for the BunnyCDN pull and storage zones [API](https://bunnycdn.docs.apiary.io/). -This class whilst having a main focus on storage zone interaction includes pull zone features. -Combining API with FTP, managing and using BunnyCDN storage zones just got easier. +The most comprehensive, feature packed and easy to use PHP class for the BunnyCDN pull, video streaming and storage +zones [API](https://bunnycdn.docs.apiary.io/). +This class whilst having a main focus on storage zone interaction includes pull zone features. Combining API with FTP, +managing and using BunnyCDN storage zones just got easier. -[![Generic badge](https://img.shields.io/badge/version-1.2-blue.svg)](https://shields.io/) +[![Generic badge](https://img.shields.io/badge/version-1.4-blue.svg)](https://shields.io/) + +**Note video streaming API is seemingly not finalized and is changing** ### Requires -For Pull zone, billing and statistics API interaction you will need your BunnyCDN API key, this is found in your dashboard in the My Account section. +For Pull zone, billing and statistics API interaction you will need your BunnyCDN API key, this is found in your +dashboard in the My Account section. If you want to interact with storage zones you will need your BunnyCDN API key set and the name of the storage zone. @@ -58,12 +62,15 @@ If you want to interact with storage zones you will need your BunnyCDN API key s * Calculate costs ## Usage + Usage is simple, install with: ``` composer require corbpie/bunny-cdn-api ``` + Use like: + ```php require __DIR__ . '/vendor/autoload.php'; @@ -87,23 +94,29 @@ const API_KEY = 'XXXX-XXXX-XXXX'; **option 2** With ```apiKey()``` (needs setting with each calling of class) + ```php $bunny->apiKey('XXXX-XXXX-XXXX');//Bunny api key ``` + --- -To show PHP errors and max execution time of 300 seconds +To have max execution time of 300 seconds + ```php -$bunny = new bunnyAPI(true, 300); +$bunny = new bunnyAPI(300); ``` + --- Storage zone name and access key for storage zone interaction (**not needed if just using pull zone functions**) Set ```$access_key = ''``` to obtain key automatically (storage name must be accurate) + ```php $bunny->zoneConnect($storagename, $access_key); ``` + `$storagename` name of storage zone `string` `$access_key` key/password to storage zone ```string``` **optional** @@ -111,6 +124,7 @@ $bunny->zoneConnect($storagename, $access_key); --- List storage zones + ```php $bunny->listStorageZones(); ``` @@ -120,22 +134,27 @@ returns `array` --- Add a storage zone + ```php $bunny->addStorageZone($newstoragezone); ``` + `$newstoragezone` name of storage zone to create `string` --- Delete a storage zone + ```php $bunny->deleteStorageZone($id); ``` + `$id` id of storage zone to delete `int` --- Get directory size + ```php $bunny->dirSize($dir); ``` @@ -145,6 +164,7 @@ $bunny->dirSize($dir); --- Return current directory + ```php $bunny->currentDir(); ``` @@ -154,14 +174,17 @@ returns `string` --- Change directory + ```php $bunny->changeDir($dir); ``` + `$dir` directory navigation (FTP rules) `string` --- Move to parent directory + ```php $bunny->moveUpOne(); ``` @@ -169,6 +192,7 @@ $bunny->moveUpOne(); --- Create folder in current directory + ```php $bunny->createFolder($newfolder); ``` @@ -178,6 +202,7 @@ $bunny->createFolder($newfolder); --- Delete folder + ```php $bunny->deleteFolder($name); ``` @@ -187,6 +212,7 @@ $bunny->deleteFolder($name); --- Delete a file + ```php $bunny->deleteFile($name); ``` @@ -196,6 +222,7 @@ $bunny->deleteFile($name); --- Delete all files in a folder + ```php $bunny->deleteAllFiles($dir); ``` @@ -207,6 +234,7 @@ $bunny->deleteAllFiles($dir); Rename a file BunnyCDN does not allow for ftp_rename so file copied to new name and then old file deleted. + ```php $bunny->renameFile($directory, $old_file_name, $new_file_name); ``` @@ -220,6 +248,7 @@ $bunny->renameFile($directory, $old_file_name, $new_file_name); --- Move a file + ```php $bunny->moveFile($file, $move_to); ``` @@ -231,6 +260,7 @@ $bunny->moveFile($file, $move_to); --- Download a file + ```php $bunny->downloadFile($save_as, $get_file, $mode); ``` @@ -244,6 +274,7 @@ $bunny->downloadFile($save_as, $get_file, $mode); --- Download all files in a directory + ```php $bunny->downloadAll($dir_dl_from, $dl_into, $mode); ``` @@ -257,6 +288,7 @@ $bunny->downloadAll($dir_dl_from, $dl_into, $mode); --- Upload a file + ```php $bunny->uploadFile($upload, $upload_as, $mode); ``` @@ -270,6 +302,7 @@ $bunny->uploadFile($upload, $upload_as, $mode); --- Upload all files from a local folder + ```php $bunny->uploadAllFiles($dir, $place, $mode); ``` @@ -283,14 +316,17 @@ $bunny->uploadAllFiles($dir, $place, $mode); --- Return storage zone files and folder data (Original) + ```php $bunny->listAllOG(); ``` + returns `array` --- Return storage zone directory files formatted + ```php $bunny->listFiles($location); ``` @@ -302,6 +338,7 @@ returns `array` --- Return storage zone directory folders formatted + ```php $bunny->listFolders($location); ``` @@ -313,6 +350,7 @@ returns `array` --- Return storage zone directory file and folders formatted + ```php $bunny->listAll($location); ``` @@ -324,14 +362,17 @@ returns `array` --- List all pull zones and data + ```php $bunny->listPullZones(); ``` + returns `array` --- List pull zones data for id + ```php $bunny->pullZoneData($id); ``` @@ -343,6 +384,7 @@ returns `array` --- Purge pull zone data + ```php $bunny->purgePullZone($id); ``` @@ -352,6 +394,7 @@ $bunny->purgePullZone($id); --- Delete pull zone data + ```php $bunny->deletePullZone($id); ``` @@ -361,12 +404,15 @@ $bunny->deletePullZone($id); --- Lists pullzone hostnames and amount + ```php $bunny->pullZoneHostnames($pullzone_id); ``` + --- Add hostname to pull zone + ```php $bunny->addHostnamePullZone($id, $hostname); ``` @@ -378,6 +424,7 @@ $bunny->addHostnamePullZone($id, $hostname); --- Remove a hostname from pull zone + ```php $bunny->removeHostnamePullZone($id, $hostname); ``` @@ -389,6 +436,7 @@ $bunny->removeHostnamePullZone($id, $hostname); --- Change force SSL status for pull zone + ```php $bunny->forceSSLPullZone($id, $hostname, $force_ssl); ``` @@ -402,6 +450,7 @@ $bunny->forceSSLPullZone($id, $hostname, $force_ssl); --- Add ip to block for pullzone + ```php $bunny->addBlockedIpPullZone($pullzone_id, $ip, $db_log = false); ``` @@ -409,6 +458,7 @@ $bunny->addBlockedIpPullZone($pullzone_id, $ip, $db_log = false); --- Un block an ip for pullzone + ```php $bunny->unBlockedIpPullZone($pullzone_id, $ip, $db_log = false); ``` @@ -416,6 +466,7 @@ $bunny->unBlockedIpPullZone($pullzone_id, $ip, $db_log = false); --- List all blocked ip's for pullzone + ```php $bunny->listBlockedIpPullZone($pullzone_id); ``` @@ -423,6 +474,7 @@ $bunny->listBlockedIpPullZone($pullzone_id); --- Purge cache for a URL + ```php $bunny->purgeCache($url); ``` @@ -432,6 +484,7 @@ $bunny->purgeCache($url); --- Pull zone logs as formatted array + ```php $bunny->pullZoneLogs($id, $date); ``` @@ -443,116 +496,321 @@ $bunny->pullZoneLogs($id, $date); --- Get usage statistics + ```php $bunny->getStatistics(); ``` + returns `array` --- Get billing data + ```php $bunny->getBilling(); ``` + returns `array` --- Get account balance + ```php $bunny->balance(); ``` + returns `float` --- Get monthly charge + ```php $bunny->monthCharges(); ``` + returns `float` --- Get monthly charge breakdown for region + ```php $bunny->monthChargeBreakdown(); ``` + returns `array` --- Lists total billing amount and first date time + ```php $bunny->totalBillingAmount(); ``` + returns `array` --- Apply a coupon code + ```php $bunny->applyCoupon($code); ``` + --- Set Json header + ```php $bunny->jsonHeader(); ``` + --- Convert/format bytes to other data types + ```php $bunny->convertBytes($bytes, $convert_to = 'GB', $format = true, $decimals = 2); ``` + --- Convert bool to int value + ```php $bunny->boolToInt($bool); ``` + returns `int` --- Close connection (Optional) + ```php $bunny->closeConnection(); ``` +--- + +## Video streaming + +Set video stream library id + +```php +$bunny->setStreamLibraryId($library_id); +``` + +`$library_id` stream library id `int` + +--- -### MySQL Functions +Set video collection guid -Run `MySQL_database.sql` +```php +$bunny->setStreamCollectionGuid($collection_guid); +``` -Put details in `db_connect();` +`$collection_guid` video collection guid `string` --- -Insert Pull zones into database +Set video guid + ```php -$bunny->insertPullZones(); +$bunny->setStreamVideoGuid($video_guid); ``` + +`$video_guid` video guid `string` + --- -Insert Storage zones into database +Get video collections for library + ```php -$bunny->insertStorageZones(); +$bunny->getStreamCollections($library_id, $page, $items_pp,$order_by); ``` + +`$library_id` library id `int` + +*0 = use set library id from setStreamLibraryId()* + +`$page` page number `int` + +`$items_pp` items to show `int` + +`$order_by` order by `string` + --- -Insert Pull zone logs into database +Get streams for a collection + ```php -$bunny->insertPullZoneLogs($id, $date); +$bunny->getStreamForCollection($library_id, $collection_guid); ``` -`$id` Pull zone id `int` -`$date` Date for logs, only past 3 days (mm-dd-yy) `string` +`$library_id` library id `int` + +*0 = use set library id from setStreamLibraryId()* + +`$collection_guid` video collection guid `string` + +*leave empty to use set collection guid from setStreamCollectionGuid()* + +--- + +Update stream collection + +```php +$bunny->updateCollection($library_id, $collection_guid); +``` + +`$library_id` library id `int` + +`$collection_guid` video collection guid `string` + +--- + +Delete stream collection + +```php +$bunny->deleteCollection($library_id, $collection_guid); +``` + +`$library_id` library id `int` + +`$collection_guid` video collection guid `string` + +--- + +Create stream collection + +```php +$bunny->createCollection($library_id, $collection_guid); +``` + +`$library_id` library id `int` + +`$collection_guid` video collection guid `string` + +--- + +List videos for library + +```php +$bunny->listVideos($library_id, $collection_guid); +``` + +`$library_id` library id `int` + +`$collection_guid` video collection guid `string` + +--- + +Get video information + +```php +$bunny->getVideo($library_id, $collection_guid); +``` + +`$library_id` library id `int` + +`$collection_guid` video collection guid `string` + +--- + +Delete video + +```php +$bunny->deleteVideo($library_id, $collection_guid); +``` + +`$library_id` library id `int` + +`$collection_guid` video collection guid `string` + +--- + +Create video + +```php +$bunny->createVideo($library_id, $video_title, $collection_guid); +``` + +`$library_id` library id `int` + +`$video_title` video title `string` + +`$collection_guid` video collection guid `string` + +--- + +Upload video + +Need to use createVideo() first to get video guid + +```php +$bunny->uploadVideo($library_id, $collection_guid, $video_to_upload); +``` + +`$library_id` library id `int` + +`$collection_guid` video collection guid `string` + +`$video_to_upload` video file `string` + +--- + +Set thumbnail for video + +```php +$bunny->setThumbnail($library_id, $video_guid, $thumbnail_url); +``` + +`$library_id` library id `int` + +`$video_guid` video guid `string` + +`$thumbnail_url` image url `string` + +--- + +Add captions + +```php +$bunny->addCaptions($library_id, $video_guid, $collection_guid, $label, $captions_file); +``` + +`$library_id` library id `int` + +`$video_guid` video guid `string` + +`$srclang` caption srclang `string` + +`$label` label for captions `string` + +`$captions_file` caption file URL `string` + +--- + +Delete captions + +```php +$bunny->deleteCaptions($library_id, $video_guid, $srclang); +``` + +`$library_id` library id `int` + +`$video_guid` video guid `string` + +`$srclang` captions srclang `string` --- ## TODO * Proper exception handling -* Improve action logging diff --git a/src/BunnyAPI.php b/src/BunnyAPI.php index 304d22b..0fb3675 100644 --- a/src/BunnyAPI.php +++ b/src/BunnyAPI.php @@ -4,90 +4,66 @@ /** * Bunny CDN pull & storage zone API class - * @version 1.3 + * @version 1.4 * @author corbpie */ class BunnyAPI { - const API_KEY = 'XXXX-XXXX-XXXX';//BunnyCDN API key - const API_URL = 'https://bunnycdn.com/api/';//URL for BunnyCDN API - const STORAGE_API_URL = 'https://storage.bunnycdn.com/';//URL for storage based API - const HOSTNAME = 'storage.bunnycdn.com';//FTP hostname + private const API_KEY = 'XXXX-XXXX-XXXX';//BunnyCDN API key + private const API_URL = 'https://bunnycdn.com/api/';//URL for BunnyCDN API + private const STORAGE_API_URL = 'https://storage.bunnycdn.com/';//URL for storage zone replication region (LA|NY|SG|SYD) Falkenstein is as default + private const VIDEO_STREAM_URL = 'http://video.bunnycdn.com/';//URL for Bunny video stream API + private const HOSTNAME = 'storage.bunnycdn.com';//FTP hostname + private const STREAM_LIBRARY_ACCESS_KEY = 'XXXX-XXXX-XXXX'; private string $api_key; private string $access_key; private string $storage_name; private $connection; private string $data; + private int $stream_library_id; + private string $stream_collection_guid = ''; + private string $stream_video_guid = ''; - /** - * Option to display notices and errors for debugging and execution time amount - * @param bool $show_errors - * @param int $execution_time - */ - public function __construct($show_errors = false, $execution_time = 240) + public function __construct(int $execution_time = 240, bool $json_header = false) { if ($this->constApiKeySet()) { - $this->api_key = BunnyAPI::API_KEY; + $this->api_key = self::API_KEY; } ini_set('max_execution_time', $execution_time); - if ($show_errors) { - ini_set('display_errors', 1); - ini_set('display_startup_errors', 1); - error_reporting(E_ALL); + if ($json_header) { + header('Content-Type: application/json'); } } - /** - * Sets access key and the storage name, makes FTP connection with this - * @param string $api_key (storage zone password) - * @return string - * @throws Exception - */ - public function apiKey(string $api_key = '') + public function apiKey(string $api_key = ''): string { - if (!isset($api_key) or trim($api_key) == '') { + if (!isset($api_key) || trim($api_key) === '') { throw new Exception("You must provide an API key"); } $this->api_key = $api_key; return json_encode(array('response' => 'success', 'action' => 'apiKey')); } - /** - * Sets and creates auth + FTP connection to a storage zone - * @param string $storage_name - * @param string $access_key - * @return string - * @throws Exception - */ - public function zoneConnect(string $storage_name, string $access_key = '') + public function zoneConnect(string $storage_name, string $access_key = ''): ?string { $this->storage_name = $storage_name; - if (empty($access_key)) { - $this->findStorageZoneAccessKey($storage_name); - } else { - $this->access_key = $access_key; - } - $conn_id = ftp_connect((BunnyAPI::HOSTNAME)); + (empty($access_key)) ? $this->findStorageZoneAccessKey($storage_name) : $this->access_key = $access_key; + $conn_id = ftp_connect((self::HOSTNAME)); $login = ftp_login($conn_id, $storage_name, $this->access_key); ftp_pasv($conn_id, true); if ($conn_id) { $this->connection = $conn_id; return json_encode(array('response' => 'success', 'action' => 'zoneConnect')); } else { - throw new Exception("Could not make FTP connection to " . (BunnyAPI::HOSTNAME) . ""); + throw new Exception("Could not make FTP connection to " . (self::HOSTNAME) . ""); } } - /** - * Finds storage zone password/access key from storage zone name - * @param string $storage_name - * @return bool - */ - protected function findStorageZoneAccessKey(string $storage_name) + protected function findStorageZoneAccessKey(string $storage_name): bool { $data = json_decode($this->listStorageZones(), true); foreach ($data as $zone) { - if ($zone['Name'] == $storage_name) { + if ($zone['Name'] === $storage_name) { $this->access_key = $zone['Password']; return true;//Found access key } @@ -95,108 +71,69 @@ protected function findStorageZoneAccessKey(string $storage_name) return false;//Never found access key for said storage zone } - /** - * Sets the MySQL connection (Optional! Only if using MySQL functions) - * @return object - */ - public function db_connect() - { - $db_user = 'root'; - $db_password = ''; - $db = "mysql:host=127.0.0.1;dbname=bunnycdn;charset=utf8mb4"; - $options = array( - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC); - return new PDO($db, $db_user, $db_password, $options); - } - - /** - * Checks if API key has been hard coded with the constant API_KEY - * @return bool - */ - protected function constApiKeySet() + protected function constApiKeySet(): ?bool { if (!defined("self::API_KEY") || empty(self::API_KEY)) { return false; - } else { - return true; } + return true; } - /** - * cURL execution with headers and parameters - * @param string $method - * @param string $url - * @param string|boolean $params - * @return string - * @throws Exception - */ - private function APIcall(string $method, string $url, $params = false) + private function APIcall(string $method, string $url, array $params = [], bool $storage_call = false, bool $video_stream_call = false): string { - if (!$this->constApiKeySet()) { throw new Exception("apiKey() is not set"); } $curl = curl_init(); - switch ($method) { - case "POST": - curl_setopt($curl, CURLOPT_POST, 1); - if ($params) - curl_setopt($curl, CURLOPT_POSTFIELDS, $params); - break; - case "PUT": - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - if ($params) - curl_setopt($curl, CURLOPT_POSTFIELDS, $params); - break; - case "DELETE": - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - if ($params) - curl_setopt($curl, CURLOPT_POSTFIELDS, $params); - break; - default: - if ($params) - $url = sprintf("%s?%s", $url, http_build_query($params)); + if ($method === "POST") { + curl_setopt($curl, CURLOPT_POST, 1); + if (!empty($params)) + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params)); + } elseif ($method === "PUT") { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_UPLOAD, 1); + $params = json_decode(json_encode($params)); + curl_setopt($curl, CURLOPT_INFILE, fopen($params->file, "r")); + curl_setopt($curl, CURLOPT_INFILESIZE, filesize($params->file)); + } elseif ($method === "DELETE") { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + if (!empty($params)) + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params)); + } else {//GET + if (!empty($params)) + $url = sprintf("%s?%s", $url, http_build_query(json_encode($params))); + } + if (!$storage_call && !$video_stream_call) {//General CDN pullzone + curl_setopt($curl, CURLOPT_URL, self::API_URL . "$url"); + curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "AccessKey: $this->api_key")); + } elseif ($video_stream_call) {//Video stream + curl_setopt($curl, CURLOPT_URL, self::VIDEO_STREAM_URL . "$url"); + curl_setopt($curl, CURLOPT_HTTPHEADER, array("AccessKey: " . self::STREAM_LIBRARY_ACCESS_KEY . "")); + } else {//Storage zone + curl_setopt($curl, CURLOPT_URL, self::STORAGE_API_URL . "$url"); + curl_setopt($curl, CURLOPT_HTTPHEADER, array("AccessKey: $this->access_key")); } - curl_setopt($curl, CURLOPT_URL, "" . (BunnyAPI::API_URL) . "$url"); - curl_setopt($curl, CURLOPT_HTTPHEADER, array( - "Content-Type: application/json", - "AccessKey: {$this->api_key}")); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0); $result = curl_exec($curl); + $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); $this->data = $result; return $result; } - /** - * Returns all pull zones and information - * @return string - */ - public function listPullZones() + public function listPullZones(): string { return $this->APIcall('GET', 'pullzone'); } - /** - * Gets a single pull zone information - * @param int $id - * @return string - */ - public function getPullZone(int $id) + public function getPullZone(int $id): string { return $this->APIcall('GET', "pullzone/$id"); } - /** - * Creates pull zone - * @param string $name - * @param string $origin - * @param array $args - * @return string - */ - public function createPullZone(string $name, string $origin, array $args = array()) + public function createPullZone(string $name, string $origin, array $args = array()): string { $args = array_merge( array( @@ -205,65 +142,30 @@ public function createPullZone(string $name, string $origin, array $args = array ), $args ); - return $this->APIcall('POST', 'pullzone', json_encode($args)); + return $this->APIcall('POST', 'pullzone', $args); } - /** - * Updates pull zone - * @param int $id - * @param array $args - * @return string - */ - public function updatePullZone(int $id, array $args = array()) + public function updatePullZone(int $id, array $args = array()): string { - return $this->APIcall('POST', "pullzone/$id", json_encode($args)); + return $this->APIcall('POST', "pullzone/$id", $args); } - /** - * Returns pull zone information for id - * @param int $id - * @return string - * @throws Exception - */ - public function pullZoneData(int $id) + public function pullZoneData(int $id): string { return $this->APIcall('GET', "pullzone/$id"); } - /** - * Purge the pull zone with id - * @param int $id - * @param bool $db_log - * @return string - */ - public function purgePullZone(int $id, bool $db_log = false) + public function purgePullZone(int $id): string { - if ($db_log) { - $this->actionsLog('PURGE PZ', $id); - } return $this->APIcall('POST', "pullzone/$id/purgeCache"); } - /** - * Delete pull zone for id - * @param int $id - * @param bool $db_log - * @return string - */ - public function deletePullZone(int $id, bool $db_log = false) + public function deletePullZone(int $id): string { - if ($db_log) { - $this->actionsLog('DELETE PZ', $id); - } return $this->APIcall('DELETE', "pullzone/$id"); } - /** - * Returns pull zone hostname count and list - * @param int $id - * @return array - */ - public function pullZoneHostnames(int $id) + public function pullZoneHostnames(int $id): ?array { $data = json_decode($this->pullZoneData($id), true); if (isset($data['Hostnames'])) { @@ -285,64 +187,27 @@ public function pullZoneHostnames(int $id) } } - /** - * Add hostname to pull zone for id - * @param int $id - * @param string $hostname - * @param bool $db_log - * @return string - */ - public function addHostnamePullZone(int $id, string $hostname, bool $db_log = false) + public function addHostnamePullZone(int $id, string $hostname): string { - if ($db_log) { - $this->actionsLog('ADD HN', $id, $hostname); - } - return $this->APIcall('POST', 'pullzone/addHostname', json_encode(array("PullZoneId" => $id, "Hostname" => $hostname))); + return $this->APIcall('POST', 'pullzone/addHostname', array("PullZoneId" => $id, "Hostname" => $hostname)); } - /** - * Remove hostname for pull zone - * @param int $id - * @param string $hostname - * @param bool $db_log - * @return string - */ - public function removeHostnamePullZone(int $id, string $hostname, bool $db_log = false) + public function removeHostnamePullZone(int $id, string $hostname): string { - if ($db_log) { - $this->actionsLog('REMOVE HN', $id, $hostname); - } - return $this->APIcall('DELETE', 'pullzone/deleteHostname', json_encode(array("id" => $id, "hostname" => $hostname))); + return $this->APIcall('DELETE', 'pullzone/deleteHostname', array("id" => $id, "hostname" => $hostname)); } - /** - * Load a free certificate provided by Let’s Encrypt. - * @param string $hostname - * @return string - */ - public function addFreeSSLCertificate(string $hostname) + public function addFreeSSLCertificate(string $hostname): string { return $this->APIcall('GET', 'pullzone/loadFreeCertificate?hostname=' . $hostname); } - /** - * Set Force SSL status for pull zone - * @param int $id - * @param string $hostname - * @param boolean $force_ssl - * @return string - */ - public function forceSSLPullZone(int $id, string $hostname, bool $force_ssl = true) + public function forceSSLPullZone(int $id, string $hostname, bool $force_ssl = true): string { - return $this->APIcall('POST', 'pullzone/setForceSSL', json_encode(array("PullZoneId" => $id, "Hostname" => $hostname, 'ForceSSL' => $force_ssl))); + return $this->APIcall('POST', 'pullzone/setForceSSL', array("PullZoneId" => $id, "Hostname" => $hostname, 'ForceSSL' => $force_ssl)); } - /** - * Returns Blocked ip data for pull zone for id - * @param int $id - * @return array - */ - public function listBlockedIpPullZone(int $id) + public function listBlockedIpPullZone(int $id): ?array { $data = json_decode($this->pullZoneData($id), true); if (isset($data['BlockedIps'])) { @@ -360,43 +225,17 @@ public function listBlockedIpPullZone(int $id) } } - /** - * Block an ip for pull zone for id - * @param int $id - * @param string $ip - * @param bool $db_log - * @return string - */ - public function addBlockedIpPullZone(int $id, string $ip, bool $db_log = false) + public function addBlockedIpPullZone(int $id, string $ip): string { - if ($db_log) { - $this->actionsLog('ADD BLOCKED IP', $id, $ip); - } - return $this->APIcall('POST', 'pullzone/addBlockedIp', json_encode(array("PullZoneId" => $id, "BlockedIp" => $ip))); + return $this->APIcall('POST', 'pullzone/addBlockedIp', array("PullZoneId" => $id, "BlockedIp" => $ip)); } - /** - * Remove a blocked ip for pull zone id - * @param int $id - * @param string $ip - * @param bool $db_log - * @return string - */ - public function unBlockedIpPullZone(int $id, string $ip, bool $db_log = false) + public function unBlockedIpPullZone(int $id, string $ip): string { - if ($db_log) { - $this->actionsLog('UN BLOCKED IP', $id, $ip); - } - return $this->APIcall('POST', 'pullzone/removeBlockedIp', json_encode(array("PullZoneId" => $id, "BlockedIp" => $ip))); + return $this->APIcall('POST', 'pullzone/removeBlockedIp', array("PullZoneId" => $id, "BlockedIp" => $ip)); } - /** - * Returns log data array for pull zone id - * @param int $id - * @param string $date Must be within past 3 days (mm-dd-yy) - * @return array - */ - public function pullZoneLogs(int $id, string $date) + public function pullZoneLogs(int $id, string $date): array { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "https://logging.bunnycdn.com/$date/$id.log"); @@ -426,146 +265,84 @@ public function pullZoneLogs(int $id, string $date) 'zone_id' => intval($log_format[4]), 'country_code' => $log_format[11] ); - array_push($line, $details); + $line[] = $details; } } return $line; } - /** - * Returns all storage zones and information - * @return string - */ - public function listStorageZones() + public function listStorageZones(): string { return $this->APIcall('GET', 'storagezone'); } - /** - * Create storage zone - * @param string $name - * @param bool $db_log - * @return string - */ - public function addStorageZone(string $name, bool $db_log = false) + public function addStorageZone(string $name): string { - if ($db_log) { - $this->actionsLog('ADD SZ', $name); - } - return $this->APIcall('POST', 'storagezone', json_encode(array("Name" => $name))); + return $this->APIcall('POST', 'storagezone', array("Name" => $name)); } - /** - * Delete storage zone - * @param int $id - * @param bool $db_log - * @return string - */ - public function deleteStorageZone(int $id, bool $db_log = false) + public function deleteStorageZone(int $id): string { - if ($db_log) { - $this->actionsLog('DELETE SZ', $id); - } return $this->APIcall('DELETE', "storagezone/$id"); } - /** - * Purge cache for a URL - * @param $url - * @return string - */ - public function purgeCache(string $url) + public function purgeCache(string $url): string { - return $this->APIcall('POST', 'purge', json_encode(array("url" => $url))); + return $this->APIcall('POST', 'purge', array("url" => $url)); } - /** - * Convert and format bytes - * @param int $bytes - * @param string $convert_to - * @param bool $format - * @param int $decimals - * @return float - */ - public function convertBytes(int $bytes, string $convert_to = 'GB', bool $format = true, int $decimals = 2) + public function convertBytes(int $bytes, string $convert_to = 'GB', bool $format = true, int $decimals = 2): float|int|string { - if ($convert_to == 'GB') { + if ($convert_to === 'GB') { $value = ($bytes / 1073741824); - } elseif ($convert_to == 'MB') { + } elseif ($convert_to === 'MB') { $value = ($bytes / 1048576); - } elseif ($convert_to == 'KB') { + } elseif ($convert_to === 'KB') { $value = ($bytes / 1024); } else { $value = $bytes; } if ($format) { return number_format($value, $decimals); - } else { - return $value; } + return $value; } - /** - * Get statistics - * @return string - */ - public function getStatistics() + public function getStatistics(): string { return $this->APIcall('GET', 'statistics'); } - /** - * Get billing information - * @return string - */ - public function getBilling() + public function getBilling(): string { return $this->APIcall('GET', 'billing'); } - /** - * Get current account balance - * @return string - */ - public function balance() + public function balance(): string { return json_decode($this->getBilling(), true)['Balance']; } - /** - * Gets current month charge amount - * @return string - */ - public function monthCharges() + public function monthCharges(): string { return json_decode($this->getBilling(), true)['ThisMonthCharges']; } - /** - * Gets total charge amount and first charge date time - * @param bool $format - * @param int $decimals - * @return array - */ - public function totalBillingAmount(bool $format = false, int $decimals = 2) + public function totalBillingAmount(bool $format = false, int $decimals = 2): ?array { $data = json_decode($this->getBilling(), true); $tally = 0; foreach ($data['BillingRecords'] as $charge) { - $tally = ($tally + $charge['Amount']); + $tally += $charge['Amount']; } if ($format) { - return array('amount' => floatval(number_format($tally, $decimals)), 'since' => str_replace('T', ' ', $charge['Timestamp'])); + return array('amount' => (float)number_format($tally, $decimals), 'since' => str_replace('T', ' ', $charge['Timestamp'])); } else { return array('amount' => $tally, 'since' => str_replace('T', ' ', $charge['Timestamp'])); } } - /** - * Array for month charges per zone - * @return array - */ - public function monthChargeBreakdown() + public function monthChargeBreakdown(): array { $ar = json_decode($this->getBilling(), true); return array('storage' => $ar['MonthlyChargesStorage'], 'EU' => $ar['MonthlyChargesEUTraffic'], @@ -573,96 +350,67 @@ public function monthChargeBreakdown() 'SA' => $ar['MonthlyChargesSATraffic']); } - /** - * Apply a coupon code - * @param string $code - * @return string - */ - public function applyCoupon(string $code) + public function applyCoupon(string $code): string + { + return $this->APIcall('POST', 'applycode', array("couponCode" => $code)); + } + + public function uploadFileHTTP(string $file, string $save_as = 'folder/filename.jpg'): void { - return $this->APIcall('POST', 'applycode', json_encode(array("couponCode" => $code))); + $this->APIcall('PUT', $this->storage_name . "/" . $save_as, array('file' => $file), true); } - /** - * Create a folder - * @param string $name folder name to create - * @param bool $db_log - * @return string - * @throws Exception - */ - public function createFolder(string $name, bool $db_log = false) + public function deleteFileHTTP(string $file): void + { + $this->APIcall('DELETE', $this->storage_name . "/" . $file, array(), true); + } + + public function downloadFileHTTP(string $file): void + { + $this->APIcall('GET', $this->storage_name . "/" . $file, array(), true); + } + + public function createFolder(string $name): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); if (ftp_mkdir($this->connection, $name)) { - if ($db_log) { - $this->actionsLog('CREATE FOLDER', $name); - } return json_encode(array('response' => 'success', 'action' => 'createFolder')); } else { throw new Exception("Could not create folder $name"); } } - /** - * Delete a folder (if empty) - * @param string $name folder name to delete - * @param bool $db_log - * @return string - * @throws Exception - */ - public function deleteFolder(string $name, bool $db_log = false) + public function deleteFolder(string $name): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); if (ftp_rmdir($this->connection, $name)) { - if ($db_log) { - $this->actionsLog('DELETE FOLDER', $name); - } return json_encode(array('response' => 'success', 'action' => 'deleteFolder')); } else { throw new Exception("Could not delete $name"); } } - /** - * Delete a file - * @param string $name file to delete - * @param bool $db_log log action to deleted_files table - * @return string - * @throws Exception - */ - public function deleteFile(string $name, bool $db_log = false) + public function deleteFile(string $name): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); if (ftp_delete($this->connection, $name)) { - if ($db_log) { - $path_data = pathinfo($name); - $db = $this->db_connect(); - $insert = $db->prepare('INSERT INTO `deleted_files` (`zone_name`, `file`, `dir`) VALUES (?, ?, ?)'); - $insert->execute([$this->storage_name, $path_data['basename'], $path_data['dirname']]); - } return json_encode(array('response' => 'success', 'action' => 'deleteFile')); } else { throw new Exception("Could not delete $name"); } } - /** - * Delete all files in a folder - * @param string $dir delete all files in here - * @return string - * @throws Exception - */ - public function deleteAllFiles(string $dir) + public function deleteAllFiles(string $dir): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); - $url = (BunnyAPI::STORAGE_API_URL); + $url = (self::STORAGE_API_URL); $array = json_decode(file_get_contents("$url/$this->storage_name/" . $dir . "/?AccessKey=$this->access_key"), true); foreach ($array as $value) { - if ($value['IsDirectory'] == false) { + if ($value['IsDirectory'] === false) { $file_name = $value['ObjectName']; $full_name = "$dir/$file_name"; if (ftp_delete($this->connection, $full_name)) { @@ -674,16 +422,7 @@ public function deleteAllFiles(string $dir) } } - /** - * Upload all files in a directory to a folder - * @param string $dir upload all files from here - * @param string $place upload the files to this location - * @param int $mode - * @param bool $db_log - * @return string - * @throws Exception - */ - public function uploadAllFiles(string $dir, string $place, $mode = FTP_BINARY, $db_log = false) + public function uploadAllFiles(string $dir, string $place, $mode = FTP_BINARY): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); @@ -691,9 +430,6 @@ public function uploadAllFiles(string $dir, string $place, $mode = FTP_BINARY, $ foreach ($obj as $file) { if (!is_dir($file)) { if (ftp_put($this->connection, "" . $place . "$file", "$dir/$file", $mode)) { - if ($db_log) { - $this->actionsLog('UPLOAD FILE', "" . $place . "$file", "$dir/$file"); - } echo json_encode(array('response' => 'success', 'action' => 'uploadAllFiles')); } else { throw new Exception("Error uploading " . $place . "$file as " . $place . "/" . $file . ""); @@ -702,36 +438,24 @@ public function uploadAllFiles(string $dir, string $place, $mode = FTP_BINARY, $ } } - /** - * Get a files size in bytes - * @param string $file E.g 'pets/fluffy_young.jpg' - * @return int - * @throws Exception - */ - public function getFileSize(string $file) + public function getFileSize(string $file): int { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); return ftp_size($this->connection, $file); } - /** - * Returns array with file count and total size - * @param string $dir directory to do count in - * @return array - * @throws Exception - */ - public function dirSize(string $dir = '') + public function dirSize(string $dir = ''): array { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); - $url = (BunnyAPI::STORAGE_API_URL); + $url = (self::STORAGE_API_URL); $array = json_decode(file_get_contents("$url/$this->storage_name" . $dir . "/?AccessKey=$this->access_key"), true); $size = 0; $files = 0; foreach ($array as $value) { - if ($value['IsDirectory'] == false) { - $size = ($size + $value['Length']); + if ($value['IsDirectory'] === false) { + $size += $value['Length']; $files++; } } @@ -739,25 +463,14 @@ public function dirSize(string $dir = '') 'size_mb' => number_format(($size / 1048576), 3), 'size_gb' => number_format(($size / 1073741824), 3)); } - /** - * Return current directory - * @return string - * @throws Exception - */ - public function currentDir() + public function currentDir(): string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); return ftp_pwd($this->connection); } - /** - * Change working directory - * @param string $moveto movement - * @return string - * @throws Exception - */ - public function changeDir(string $moveto) + public function changeDir(string $moveto): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); @@ -768,12 +481,7 @@ public function changeDir(string $moveto) } } - /** - * Move to parent directory - * @return string - * @throws Exception - */ - public function moveUpOne() + public function moveUpOne(): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); @@ -784,17 +492,7 @@ public function moveUpOne() } } - /** - * Renames a file - * Note: This copies a file to the new name and deletes the old file. - * No longer uses old method of downloading and re-uploading as new name. - * @param string $dir directory inside your storage zone E.g 'pets/' - * @param string $file_name file name that is being renamed E.g 'fluffy.jpg' - * @param string $new_file_name new name for the file E.g 'young_fluffy.jpg' - * @param bool $db_log log rename to MySQL - * @throws Exception - */ - public function renameFile(string $dir, string $file_name, string $new_file_name, bool $db_log = false) + public function renameFile(string $dir, string $file_name, string $new_file_name): void { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); @@ -803,11 +501,6 @@ public function renameFile(string $dir, string $file_name, string $new_file_name if (ftp_get($this->connection, "TEMPFILE.$file_type", "{$dir}$file_name", FTP_BINARY)) { if (ftp_put($this->connection, "{$dir}$new_file_name", "TEMPFILE.$file_type", FTP_BINARY)) { $this->deleteFile("{$dir}$file_name"); - if ($db_log) { - $db = $this->db_connect(); - $insert = $db->prepare('INSERT INTO file_history (new_name, old_name, zone_name, new_dir, old_dir) VALUES (?, ?, ?, ?, ?)'); - $insert->execute(["{$dir}$new_file_name", "{$dir}$file_name", $this->storage_name, $dir, $dir]); - } } else { throw new Exception("ftp_put fail: {$dir}$new_file_name, TEMPFILE.$file_type"); } @@ -816,14 +509,7 @@ public function renameFile(string $dir, string $file_name, string $new_file_name } } - /** - * Move a file - * @param string $dir Directory file is in E.g 'pets/' - * @param string $file_name file to move E.g 'small_fluffy.jpg' - * @param string $move_to Directory to move file to E.g 'pets/puppy_fluffy/' - * @throws Exception - */ - public function moveFile(string $dir, string $file_name, string $move_to) + public function moveFile(string $dir, string $file_name, string $move_to): void { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); @@ -840,77 +526,43 @@ public function moveFile(string $dir, string $file_name, string $move_to) } } - /** - * Download a file - * @param string $save_as Save as when downloaded - * @param string $get_file File to download - * @param int $mode - * @param bool $db_log - * @return string - * @throws Exception - */ - public function downloadFile(string $save_as, string $get_file, int $mode = FTP_BINARY, bool $db_log = false) + public function downloadFile(string $save_as, string $get_file, int $mode = FTP_BINARY): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); if (ftp_get($this->connection, $save_as, $get_file, $mode)) { - if ($db_log) { - $this->actionsLog('DOWNLOAD', $save_as, $get_file); - } return json_encode(array('response' => 'success', 'action' => 'downloadFile')); } else { throw new Exception("Error downloading $get_file as $save_as"); } } - /** - * Download a file with progress percentage written to text file - * @param string $save_as Save file as E.g 'fluffy_trick_1.mp4' - * @param string $get_file File to download E.g 'pets/fluffy/fluffy_trick_1.mp4' - * @param string $progress_file File to write the download progress to - * @param bool $db_log Log download to MySQL - */ - public function downloadFileWithProgress(string $save_as, string $get_file, string $progress_file = 'DOWNLOAD_PERCENT.txt', bool $db_log = false) + public function downloadFileWithProgress(string $save_as, string $get_file, string $progress_file = 'DOWNLOAD_PERCENT.txt'): void { - $ftp_url = "ftp://$this->storage_name:$this->access_key@" . BunnyAPI::HOSTNAME . "/$this->storage_name/$get_file"; + $ftp_url = "ftp://$this->storage_name:$this->access_key@" . self::HOSTNAME . "/$this->storage_name/$get_file"; $size = filesize($ftp_url); $in = fopen($ftp_url, "rb") or die("Cannot open source file"); $out = fopen($save_as, "wb"); while (!feof($in)) { $buf = fread($in, 10240); fwrite($out, $buf); - $file_data = intval(ftell($out) / $size * 100); + $file_data = (int)(ftell($out) / $size * 100); file_put_contents($progress_file, $file_data); } fclose($out); fclose($in); - if ($db_log) { - $this->actionsLog('DOWNLOAD', $save_as, $get_file); - } } - /** - * Download all files in a directory - * @param string $dir_dl_from directory to download all from - * @param string $dl_into local folder to download into - * @param int $mode FTP mode for download - * @param bool $db_log - * @return string - * @throws Exception - */ - public function downloadAll(string $dir_dl_from = '', string $dl_into = '', int $mode = FTP_BINARY, bool $db_log = false) + public function downloadAll(string $dir_dl_from = '', string $dl_into = '', int $mode = FTP_BINARY): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); - $url = (BunnyAPI::STORAGE_API_URL); + $url = (self::STORAGE_API_URL); $array = json_decode(file_get_contents("$url/$this->storage_name" . $dir_dl_from . "/?AccessKey=$this->access_key"), true); foreach ($array as $value) { - if ($value['IsDirectory'] == false) { + if ($value['IsDirectory'] === false) { $file_name = $value['ObjectName']; if (ftp_get($this->connection, "" . $dl_into . "$file_name", $file_name, $mode)) { - if ($db_log) { - $this->actionsLog('DOWNLOAD', "" . $dl_into . "$file_name", $file_name); - } echo json_encode(array('response' => 'success', 'action' => 'downloadAll')); } else { throw new Exception("Error downloading $file_name to " . $dl_into . "$file_name"); @@ -919,105 +571,63 @@ public function downloadAll(string $dir_dl_from = '', string $dl_into = '', int } } - /** - * Upload a file - * @param string $upload File to upload - * @param string $upload_as Save as when uploaded - * @param int $mode - * @param bool $db_log - * @return string - * @throws Exception - */ - public function uploadFile(string $upload, string $upload_as, int $mode = FTP_BINARY, bool $db_log = false) + public function uploadFile(string $upload, string $upload_as, int $mode = FTP_BINARY): ?string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); if (ftp_put($this->connection, $upload_as, $upload, $mode)) { - if ($db_log) { - $this->actionsLog('UPLOAD', $upload, $upload_as); - } return json_encode(array('response' => 'success', 'action' => 'uploadFile')); } else { throw new Exception("Error uploading $upload as $upload_as"); } } - /** - * Upload a file with progress percentage written to text file - * @param string $upload File to upload E.g 'fluffy.mp4' - * @param string $upload_as Save as when uploaded E.g 'pets/fluffy.mp4' - * @param string $progress_file File to write the upload progress to - * @param bool $db_log Log upload to MySQL - */ - public function uploadFileWithProgress(string $upload, string $upload_as, string $progress_file = 'UPLOAD_PERCENT.txt', bool $db_log = false) + public function uploadFileWithProgress(string $upload, string $upload_as, string $progress_file = 'UPLOAD_PERCENT.txt'): void { - $ftp_url = "ftp://$this->storage_name:$this->access_key@" . BunnyAPI::HOSTNAME . "/$this->storage_name/$upload_as"; + $ftp_url = "ftp://$this->storage_name:$this->access_key@" . self::HOSTNAME . "/$this->storage_name/$upload_as"; $size = filesize($upload); $out = fopen($ftp_url, "wb"); $in = fopen($upload, "rb"); while (!feof($in)) { $buffer = fread($in, 10240); fwrite($out, $buffer); - $file_data = intval(ftell($in) / $size * 100); + $file_data = (int)(ftell($in) / $size * 100); file_put_contents($progress_file, $file_data); } fclose($in); fclose($out); - if ($db_log) { - $this->actionsLog('UPLOAD', $upload, $upload_as); - } } - /** - * Returns INT 1 for true and INT 0 for false - * @param bool $bool - * @return int - */ - public function boolToInt(bool $bool) + public function boolToInt(bool $bool): ?int { if ($bool) { return 1; - } else { - return 0; } + return 0; } - /** - * Set Json type header (Pretty print JSON in Firefox) - */ - public function jsonHeader() + public function jsonHeader(): void { header('Content-Type: application/json'); } - /** - * Returns official BunnyCDN data from storage instance - * @return string - * @throws Exception - */ - public function listAllOG() + public function listAllOG(): string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); - $url = (BunnyAPI::STORAGE_API_URL); + $url = (self::STORAGE_API_URL); return file_get_contents("$url/$this->storage_name/?AccessKey=$this->access_key"); } - /** - * Returns formatted Json data about all files in location - * @param string $location - * @return string - * @throws Exception - */ - public function listFiles(string $location = '') + public function listFiles(string $location = ''): string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); - $url = (BunnyAPI::STORAGE_API_URL); + $url = (self::STORAGE_API_URL); $array = json_decode(file_get_contents("$url/$this->storage_name" . $location . "/?AccessKey=$this->access_key"), true); $items = array('storage_name' => "" . $this->storage_name, 'current_dir' => $location, 'data' => array()); foreach ($array as $value) { - if ($value['IsDirectory'] == false) { + if ($value['IsDirectory'] === false) { $created = date('Y-m-d H:i:s', strtotime($value['DateCreated'])); $last_changed = date('Y-m-d H:i:s', strtotime($value['LastChanged'])); if (isset(pathinfo($value['ObjectName'])['extension'])) { @@ -1026,7 +636,7 @@ public function listFiles(string $location = '') $file_type = null; } $file_name = $value['ObjectName']; - $size_kb = floatval(($value['Length'] / 1024)); + $size_kb = (float)($value['Length'] / 1024); $guid = $value['Guid']; $items['data'][] = array('name' => $file_name, 'file_type' => $file_type, 'size' => $size_kb, 'created' => $created, 'last_changed' => $last_changed, 'guid' => $guid); @@ -1035,17 +645,11 @@ public function listFiles(string $location = '') return json_encode($items); } - /** - * Returns formatted Json data about all folders in location - * @param string $location - * @return string - * @throws Exception - */ - public function listFolders(string $location = '') + public function listFolders(string $location = ''): string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); - $url = (BunnyAPI::STORAGE_API_URL); + $url = (self::STORAGE_API_URL); $array = json_decode(file_get_contents("$url/$this->storage_name" . $location . "/?AccessKey=$this->access_key"), true); $items = array('storage_name' => $this->storage_name, 'current_dir' => $location, 'data' => array()); foreach ($array as $value) { @@ -1053,7 +657,7 @@ public function listFolders(string $location = '') $last_changed = date('Y-m-d H:i:s', strtotime($value['LastChanged'])); $foldername = $value['ObjectName']; $guid = $value['Guid']; - if ($value['IsDirectory'] == true) { + if ($value['IsDirectory'] === true) { $items['data'][] = array('name' => $foldername, 'created' => $created, 'last_changed' => $last_changed, 'guid' => $guid); } @@ -1061,17 +665,11 @@ public function listFolders(string $location = '') return json_encode($items); } - /** - * Returns formatted Json data about all files and folders in location - * @param string $location - * @return string - * @throws Exception - */ - function listAll(string $location = '') + public function listAll(string $location = ''): string { if (is_null($this->connection)) throw new Exception("zoneConnect() is not set"); - $url = (BunnyAPI::STORAGE_API_URL); + $url = (self::STORAGE_API_URL); $array = json_decode(file_get_contents("$url/$this->storage_name" . $location . "/?AccessKey=$this->access_key"), true); $items = array('storage_name' => "" . $this->storage_name, 'current_dir' => $location, 'data' => array()); foreach ($array as $value) { @@ -1079,7 +677,7 @@ function listAll(string $location = '') $last_changed = date('Y-m-d H:i:s', strtotime($value['LastChanged'])); $file_name = $value['ObjectName']; $guid = $value['Guid']; - if ($value['IsDirectory'] == true) { + if ($value['IsDirectory'] === true) { $file_type = null; $size_kb = null; } else { @@ -1088,7 +686,7 @@ function listAll(string $location = '') } else { $file_type = null; } - $size_kb = floatval(($value['Length'] / 1024)); + $size_kb = (float)($value['Length'] / 1024); } $items['data'][] = array('name' => $file_name, 'file_type' => $file_type, 'size' => $size_kb, 'is_dir' => $value['IsDirectory'], 'created' => $created, 'last_changed' => $last_changed, 'guid' => $guid); @@ -1096,127 +694,15 @@ function listAll(string $location = '') return json_encode($items); } - /** - * Closes FTP connection (Optional use) - * @return string - * @throws Exception - */ - public function closeConnection() + public function closeConnection(): ?string { if (ftp_close($this->connection)) { return json_encode(array('response' => 'success', 'action' => 'closeConnection')); } else { - throw new Exception("Error closing connection to " . (BunnyAPI::HOSTNAME) . ""); + throw new Exception("Error closing connection to " . (self::HOSTNAME) . ""); } } - /** - * @note Below begins the MySQL database functions - * @note These are completely optional - * @note Please ensure that you have edited db_connect() beginning up at line 56 - * @note Also ran MySQL_database.sql file to your database - */ - - /** - * Inserts pull zones into `pullzones` database table - * @return string - */ - public function insertPullZones() - { - $db = $this->db_connect(); - $data = json_decode($this->listPullZones(), true); - foreach ($data as $aRow) { - $insert = $db->prepare('INSERT INTO `pullzones` (`id`, `name`, `origin_url`,`enabled`, `bandwidth_used`, `bandwidth_limit`,`monthly_charge`, `storage_zone_id`, `zone_us`, `zone_eu`, `zone_asia`, `zone_sa`, `zone_af`) - VALUES (:id, :name, :origin, :enabled, :bwdth_used, :bwdth_limit, :charged, :storage_zone_id, :zus, :zeu, :zasia, :zsa, :zaf) - ON DUPLICATE KEY UPDATE `enabled` = :enabled, `bandwidth_used` = :bwdth_used,`monthly_charge` = :charged, `zone_us` = :zus, `zone_eu` = :zeu,`zone_asia` = :zasia, `zone_sa` = :zsa, `zone_af` = :zaf'); - $insert->execute([ - ':id' => $aRow['Id'], - ':name' => $aRow['Name'], - ':origin' => $aRow['OriginUrl'], - ':enabled' => $this->boolToInt($aRow['Enabled']), - ':bwdth_used' => $aRow['MonthlyBandwidthUsed'], - ':bwdth_limit' => $aRow['MonthlyBandwidthLimit'], - ':charged' => $aRow['MonthlyCharges'], - ':storage_zone_id' => $aRow['StorageZoneId'], - ':zus' => $this->boolToInt($aRow['EnableGeoZoneUS']), - ':zeu' => $this->boolToInt($aRow['EnableGeoZoneEU']), - ':zasia' => $this->boolToInt($aRow['EnableGeoZoneASIA']), - ':zsa' => $this->boolToInt($aRow['EnableGeoZoneSA']), - ':zaf' => $this->boolToInt($aRow['EnableGeoZoneAF']) - ]); - } - return json_encode(array('response' => 'success', 'action' => 'insertPullZoneLogs')); - } - - /** - * Inserts storage zones into `storagezones` database table - * @return string - */ - public function insertStorageZones() - { - $db = $this->db_connect(); - $data = json_decode($this->listStorageZones(), true); - foreach ($data as $aRow) { - if ($aRow['Deleted'] == false) { - $enabled = 1; - } else { - $enabled = 0; - } - $insert = $db->prepare('INSERT INTO `storagezones` (`id`, `name`, `storage_used`, `enabled`, `files_stored`, `date_modified`) - VALUES (:id, :name, :storage_used, :enabled, :files_stored, :date_modified) - ON DUPLICATE KEY UPDATE `storage_used` = :storage_used, `enabled` = :enabled,`files_stored` = :files, `date_modified` = :date_modified'); - $insert->execute([ - ':id' => $aRow['Id'], - ':name' => $aRow['Name'], - 'storage_used' => $aRow['StorageUsed'], - ':enabled' => $enabled, - ':files_stored' => $aRow['FilesStored'], - ':date_modified' => $aRow['DateModified'] - ]); - } - return json_encode(array('response' => 'success', 'action' => 'insertPullZoneLogs')); - } - - /** - * Inserts pull zone logs into `logs` database table - * @param int $id - * @param string $date - * @return string - */ - public function insertPullZoneLogs(int $id, string $date) - { - $db = $this->db_connect(); - $data = $this->pullZoneLogs($id, $date); - foreach ($data as $aRow) { - $insert_overview = $db->prepare('INSERT IGNORE INTO `log_main` (`zid`, `rid`, `result`, `referer`, `file_url`, `datetime`) VALUES (?, ?, ?, ?, ?, ?)'); - $insert_overview->execute([$aRow['zone_id'], $aRow['request_id'], $aRow['cache_result'], $aRow['referer'], - $aRow['file_url'], $aRow['datetime']]); - $insert_main = $db->prepare('INSERT IGNORE INTO `log_more` (`zid`, `rid`, `status`, `bytes`, `ip`, - `user_agent`, `cdn_dc`, `country_code`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'); - $insert_main->execute([$aRow['zone_id'], $aRow['request_id'], $aRow['status'], $aRow['bytes'], $aRow['ip'], - $aRow['user_agent'], $aRow['cdn_dc'], $aRow['country_code']]); - } - return json_encode(array('response' => 'success', 'action' => 'insertPullZoneLogs')); - } - - /** - * Action logger for broader actions - * @param string $task - * @param string $file - * @param string|null $file_other - */ - public function actionsLog(string $task, string $file, string $file_other = NULL) - { - $db = $this->db_connect(); - $insert = $db->prepare('INSERT INTO `actions` (`task`, `zone_name`, `file`, `file_other`) VALUES (?, ?, ?, ?)'); - $insert->execute([$task, $this->storage_name, $file, $file_other]); - } - - /** - * Calculate costs of using BunnyCDN - * @param int $bytes amount of bytes as bandwidth - * @return array - */ public function costCalculator(int $bytes): array { $zone1 = '0.01'; @@ -1227,8 +713,8 @@ public function costCalculator(int $bytes): array $s1pb = '0.004'; $s2pb = '0.003'; $s2pb_plus = '0.0025'; - $gigabytes = floatval(($bytes / 1073741824)); - $terabytes = floatval(($gigabytes / 1024)); + $gigabytes = (float)($bytes / 1073741824); + $terabytes = (float)($gigabytes / 1024); return array( 'bytes' => $bytes, 'gigabytes' => $gigabytes, @@ -1244,4 +730,111 @@ public function costCalculator(int $bytes): array ); } -} + /* + * Bunny net video stream section + * + */ + //Library -> collection -> video + public function setStreamLibraryId(int $library_id): void + { + $this->stream_library_id = $library_id; + } + + public function setStreamCollectionGuid(string $collection_guid): void + { + $this->stream_collection_guid = $collection_guid; + } + + public function setStreamVideoGuid(string $video_guid): void + { + $this->stream_video_guid = $video_guid; + } + + public function getVideoCollections(): string + { + return $this->APIcall('GET', "library/{$this->stream_library_id}/collections", [], false, true); + } + + public function getStreamCollections(int $library_id = 0, int $page = 1, int $items_pp = 100, string $order_by = 'date'): string + { + if ($library_id === 0) { + $library_id = $this->stream_library_id; + } + return $this->APIcall('GET', "library/$library_id/collections?page=$page&itemsPerPage=$items_pp&orderBy=$order_by", [], false, true); + } + + public function getStreamForCollection(int $library_id = 0, string $collection_guid = ''): string + { + if ($library_id === 0) { + $library_id = $this->stream_library_id; + } + if (empty($collection_guid)) { + $collection_guid = $this->stream_collection_guid; + } + return $this->APIcall('GET', "library/$library_id/collections/$collection_guid", [], false, true); + } + + public function updateCollection(int $library_id, string $collection_guid, string $video_library_id, int $video_count, int $total_size): string + { + return $this->APIcall('POST', "library/$library_id/collections/$collection_guid", array("videoLibraryId" => $video_library_id, "videoCount" => $video_count, "totalSize" => $total_size), false, true); + } + + public function deleteCollection(int $library_id, string $collection_id): string + { + return $this->APIcall('DELETE', "library/$library_id/collections/$collection_id", [], false, true); + } + + public function createCollection(int $library_id, string $video_library_id, int $video_count, int $total_size): string + { + return $this->APIcall('POST', "library/$library_id/collections", array("videoLibraryId" => $video_library_id, "videoCount" => $video_count, "totalSize" => $total_size), false, true); + } + + public function listVideos(int $page = 1, int $items_pp = 100, string $order_by = 'date'): string + { + if (!isset($this->stream_library_id)) { + throw new Exception("You must set library id with: setStreamLibraryId()"); + } + return $this->APIcall('GET', "library/{$this->stream_library_id}/videos?page=$page&itemsPerPage=$items_pp&orderBy=$order_by", [], false, true); + } + + public function getVideo(int $library_id, string $video_guid): string + { + return $this->APIcall('GET', "library/$library_id/videos/$video_guid", [], false, true); + } + + public function deleteVideo(int $library_id, string $video_guid): ?string + { + return $this->APIcall('DELETE', "library/$library_id/videos/$video_guid", [], false, true); + } + + public function createVideo(int $library_id, string $video_title, string $collection_guid = ''): ?string + { + if (!empty($collection_guid)) { + return $this->APIcall('POST', "library/$library_id/videos?title=$video_title&collectionId=$collection_guid", [], false, true); + } else { + return $this->APIcall('POST', "library/$library_id/videos?title=$video_title", [], false, true); + } + } + + public function uploadVideo(int $library_id, string $video_guid, string $video_to_upload): string + { + //Need to use createVideo() first to get video guid + return $this->APIcall('PUT', "library/$library_id/videos/$video_guid", array('file' => $video_to_upload), false, true); + } + + public function setThumbnail(int $library_id, string $video_guid, string $thumbnail_url): string + { + return $this->APIcall('POST', "library/$library_id/videos/$video_guid/thumbnail?$thumbnail_url", [], false, true); + } + + public function addCaptions(int $library_id, string $video_guid, string $srclang, string $label, string $captions_file): string + { + return $this->APIcall('POST', "library/$library_id/videos/$video_guid/captions/$srclang?label=$label&captionsFile=$captions_file", [], false, true); + } + + public function deleteCaptions(int $library_id, string $video_guid, string $srclang): string + { + return $this->APIcall('DELETE', "library/$library_id/videos/$video_guid/captions/$srclang", [], false, true); + } + +} \ No newline at end of file diff --git a/updater.sql b/updater.sql deleted file mode 100644 index ff43fe8..0000000 --- a/updater.sql +++ /dev/null @@ -1,13 +0,0 @@ -ALTER TABLE `pullzones` - ADD COLUMN `zone_us` TINYINT(1) NULL DEFAULT '0' AFTER `storage_zone_id`, - ADD COLUMN `zone_eu` TINYINT(1) NULL DEFAULT '0' AFTER `zone_us`, - ADD COLUMN `zone_asia` TINYINT(1) NULL DEFAULT '0' AFTER `zone_eu`, - ADD COLUMN `zone_sa` TINYINT(1) NULL DEFAULT '0' AFTER `zone_asia`, - ADD COLUMN `zone_af` TINYINT(1) NULL DEFAULT '0' AFTER `zone_sa`; - -ALTER TABLE `storagezones` - ADD COLUMN `zone_us` TINYINT(1) NULL DEFAULT '0' AFTER `date_modified`, - ADD COLUMN `zone_eu` TINYINT(1) NULL DEFAULT '0' AFTER `zone_us`, - ADD COLUMN `zone_asia` TINYINT(1) NULL DEFAULT '0' AFTER `zone_eu`, - ADD COLUMN `zone_sa` TINYINT(1) NULL DEFAULT '0' AFTER `zone_asia`, - ADD COLUMN `zone_af` TINYINT(1) NULL DEFAULT '0' AFTER `zone_sa`; \ No newline at end of file