Guest User

vps.net api

a guest
Aug 30th, 2012
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 73.56 KB | None | 0 0
  1. <?php
  2. /**
  3.  * API for vps.net
  4.  *
  5.  * This API provides an interface to vps.net allowing common virtual machine and account management tasks
  6.  * @package VPSNET
  7.  * @version 1.1.6
  8.  *
  9.  * Known Issues:
  10.  * - Your PHP user will need access to /tmp so it can write cookies. Some PHP configurations may not allow this.
  11.  *
  12.  * Changelog:
  13.  * 2012-03-13 Added RAM nodes support
  14.  * 2011=06-06 Tickets
  15.  * 2011-03-11 VirtualMachine->remove($remove_nodes=false)
  16.  * 2011-02-04 fixed template name in loadFully() for disabled clouds
  17.  * 2011-01-31 cloud_label to getVirtualMachines()
  18.  * 2010-12-29 filter to getAllTemplates all/free/paid, default - all
  19.  * 2010-12-21 VirtualMachine->getIpAddresses(),VirtualMachine->deleteIP($ipID);
  20.  * 2010-12-13 Power actions was fixed
  21.  * 2010-12-13 getCpanel()
  22.  * 2010-12-09 loadFully() defines system_template_name
  23.  * 2010-12-02 DNS functionality
  24.  * 2010-11-15 getAvailableClouds return non fusion clouds by default
  25.  * 2010-11-15 API URL to constructor (optional)
  26.  * 2010-11-15 changed getTemplatesGroups to return only groups that has templates (by cloud id)
  27.  * 2010-11-12 getAvailableClouds getTemplatesGroups getAllTemplates
  28.  * 2010-11-03 Solution for Onapp CPUs graphs
  29.  * 2010-11-03 Solution for Onapp bandwidth graphs
  30.  * 2010-11-02 Onapp console support, reinstall
  31.  * 2010-11-01 Storage nodes, Rsync, R1Soft, Control Panels (Cpanel/ISPManager ) support
  32.  * 2009-06-24 Corrected wrong variable virtual_machine_id in removing virtual machines (should just be id) and error in createVirtualMachine
  33.  * 2009-06-10 Corrected error in sendGETRequest and sendPUTRequest
  34.  * 2009-06-09 Added proxy support, fixed incorrect parameters (hostname+domain_name) passed in create virtual machine - now uses fqdn
  35.  * 2009-06-02 Fixed showConsole function
  36.  * 2009-06-02 Fixed graph function
  37.  * 2009-05-31 Fixed CURL_USERAGENT to CURLOPT_USERAGENT
  38.  * 2009-05-29 Added changelog, fixed API resource for available clouds.
  39.  */
  40. require("pData.class.php");
  41. require("pChart.class.php");
  42. class VPSNET
  43. {
  44.     /**
  45.      * This contains the API URL for accessing vps.net. You should not
  46.      * need to change this unless asked to do so by vps.net support.
  47.      * @var string
  48.      *
  49.      * */
  50.     protected $_apiUrl = 'https://api.vps.net';
  51.     /**
  52.      * This contains the API version and is sent as part of server
  53.      * requests.
  54.      * @var string
  55.      */
  56.     protected $_apiVersion = 'api10json';
  57.     protected $_apiUserAgent = "VPSNET_API_10_JSON/PHP";
  58.     protected $_session_cookie;
  59.     protected $_auth_name = '';
  60.     protected $_auth_api_key = '';
  61.     protected $_proxy = '';
  62.     private $ch = null;
  63.     public $last_errors = null;
  64.     protected static $instance;
  65.     private function __construct()
  66.     {
  67.     }
  68.     public function __destruct()
  69.     {
  70.         if (!is_null($this->ch)) {
  71.             curl_close($this->ch);
  72.         }
  73.     }
  74.     /**
  75.      * Returns true if the API instance has authentication information set.
  76.      * If not, you can call getInstance() with credentials.
  77.      * @return boolean
  78.      */
  79.     public function isAuthenticationInfoSet()
  80.     {
  81.         return (strlen($this->_auth_name) > 0 && strlen($this->_auth_api_key) > 0);
  82.     }
  83.     /**
  84.      * Returns the instance of the API.
  85.      * @return VPSNET
  86.      */
  87.     public static function getInstance($username = '', $_auth_api_key = '', $proxy = '', $_apiUrl = NULL)
  88.     {
  89.         if (!isset(self::$instance)) {
  90.             $c                             = __CLASS__;
  91.             self::$instance                = new $c;
  92.             self::$instance->_auth_name    = $username;
  93.             self::$instance->_auth_api_key = $_auth_api_key;
  94.             if ($_apiUrl) {
  95.                 self::$instance->_apiUrl = $_apiUrl;
  96.             }
  97.             if (strlen($proxy) > 0)
  98.                 self::$instance->_proxy = $proxy;
  99.             if ((strlen($username) == 0 || strlen($_auth_api_key) == 0))
  100.                 trigger_error('Singleton has been called for the first time and a username or API Key has not been set.', E_USER_ERROR);
  101.             self::$instance->_initCurl();
  102.         }
  103.         return self::$instance;
  104.     }
  105.     public function __clone()
  106.     {
  107.         trigger_error('Clone is not permitted. This class is a singleton.', E_USER_ERROR);
  108.     }
  109.     protected function _initCurl()
  110.     {
  111.         $this->ch = curl_init();
  112.         if (strlen($this->_proxy) > 0)
  113.             curl_setopt($this->ch, CURLOPT_PROXY, $this->_proxy);
  114.         curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
  115.         curl_setopt($this->ch, CURLOPT_HTTPHEADER, array(
  116.             'Content-Type: application/json',
  117.             'Accept: application/json'
  118.         ));
  119.         curl_setopt($this->ch, CURLOPT_USERAGENT, $this->_apiUserAgent);
  120.         curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
  121.         curl_setopt($this->ch, CURLOPT_USERPWD, $this->_auth_name . ':' . $this->_auth_api_key);
  122.         curl_setopt($this->ch, CURLOPT_COOKIEFILE, '/tmp/.vpsnet.' . $this->_auth_name . '.cookie');
  123.         curl_setopt($this->ch, CURLOPT_COOKIEJAR, '/tmp/.vpsnet.' . $this->_auth_name . '.cookie');
  124.     }
  125.     public function setAPIResource($resource, $append_api_version = true, $queryString = '')
  126.     {
  127.         if ($append_api_version) {
  128.             if ($queryString)
  129.                 curl_setopt($this->ch, CURLOPT_URL, sprintf('%1$s/%2$s.%3$s?%4$s', $this->_apiUrl, $resource, $this->_apiVersion, $queryString));
  130.             else
  131.                 curl_setopt($this->ch, CURLOPT_URL, sprintf('%1$s/%2$s.%3$s', $this->_apiUrl, $resource, $this->_apiVersion));
  132.         } else {
  133.             if ($queryString)
  134.                 curl_setopt($this->ch, CURLOPT_URL, sprintf('%1$s/%2$s?%3$s', $this->_apiUrl, $resource, $queryString));
  135.             else
  136.                 curl_setopt($this->ch, CURLOPT_URL, sprintf('%1$s/%2$s', $this->_apiUrl, $resource));
  137.         }
  138.     }
  139.     public function sendGETRequest()
  140.     {
  141.         curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'GET');
  142.         curl_setopt($this->ch, CURLOPT_HTTPGET, true);
  143.         curl_setopt($this->ch, CURLOPT_HTTPHEADER, array(
  144.             'Content-Type: application/json',
  145.             'Accept: application/json'
  146.         ));
  147.         return $this->sendRequest();
  148.     }
  149.     public function sendPOSTRequest($data = null, $encodeasjson = true)
  150.     {
  151.         curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'POST');
  152.         if ($encodeasjson) {
  153.             curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($data));
  154.         } else {
  155.             curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
  156.         }
  157.         //print_r($data);
  158.         curl_setopt($this->ch, CURLOPT_POST, true);
  159.         $rtn = $this->sendRequest();
  160.         return $rtn;
  161.     }
  162.     public function sendPUTRequest($data)
  163.     {
  164.         curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  165.         $json_data = json_encode($data);
  166.         curl_setopt($this->ch, CURLOPT_POSTFIELDS, $json_data);
  167.         curl_setopt($this->ch, CURLOPT_HTTPHEADER, array(
  168.             'Content-Length: ' . strlen($json_data),
  169.             'Content-Type: application/json',
  170.             'Accept: application/json'
  171.         ));
  172.         return $this->sendRequest();
  173.     }
  174.     public function sendDELETERequest()
  175.     {
  176.         curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
  177.         curl_setopt($this->ch, CURLOPT_HTTPHEADER, array(
  178.             'Content-Type: application/json',
  179.             'Accept: application/json'
  180.         ));
  181.         return $this->sendRequest();
  182.     }
  183.     protected function sendRequest($data = null)
  184.     {
  185.         $rtn                  = array();
  186.         $rtn['response_body'] = curl_exec($this->ch);
  187.         $rtn['info']          = curl_getinfo($this->ch);
  188.         if (isset($rtn['info']['content_type']) && $rtn['info']['content_type'] == 'application/json; charset=utf-8') {
  189.             if ($rtn['info']['http_code'] == 200) {
  190.                 $rtn['response'] = json_decode($rtn['response_body']);
  191.             } else if ($rtn['info']['http_code'] == 422) {
  192.                 $rtn['errors'] = json_decode($rtn['response_body']);
  193.             }
  194.         }
  195.         return $rtn;
  196.     }
  197.     /**
  198.      * Returns Nodes from your account.
  199.      * @param int $consumer_id (Optional) Consumer Id to filter results by
  200.      * @return array An array of Nodes instances
  201.      */
  202.     public function getStorageNodes($consumer_id = 0)
  203.     {
  204.         return $this->getNodes($consumer_id = 0, 'storage');
  205.     }
  206.     public function getNodes($consumer_id = 0, $type = 'vps')
  207.     {
  208.         if ($consumer_id > 0) {
  209.             $this->setAPIResource('nodes', true, 'consumer_id=' . $consumer_id . '&type=' . $type);
  210.         } else {
  211.             $this->setAPIResource('nodes', true, 'type=' . $type);
  212.         }
  213.         $result = $this->sendGETRequest();
  214.         $return = array();
  215.         if ($result['info']['http_code'] == 422) {
  216.         } else if ($result['response']) {
  217.             $response = $result['response'];
  218.             for ($x = 0; $x < count($response); $x++) {
  219.                 if ($response[$x]->slice->id) {
  220.                     $return[$x] = new Node($response[$x]->slice->id, $response[$x]->slice->virtual_machine_id, $response[$x]->slice->consumer_id, 'vps', (bool) $response[$x]->slice->free_node, (bool) $response[$x]->slice->discount_node);
  221.                 } elseif ($response[$x]->storage_node->id) {
  222.                     $return[$x] = new Node($response[$x]->storage_node->id, $response[$x]->storage_node->virtual_machine_id, $response[$x]->storage_node->consumer_id, 'storage', (bool) $response[$x]->slice->free_node, (bool) $response[$x]->slice->discount_node);
  223.                 } elseif ($response[$x]->ram_node->id) {
  224.                     $return[$x] = new Node($response[$x]->ram_node->id, $response[$x]->ram_node->virtual_machine_id, $response[$x]->ram_node->consumer_id, 'ram', (bool) $response[$x]->slice->free_node, (bool) $response[$x]->slice->discount_node);
  225.                 }
  226.             }
  227.         }
  228.         return $return;
  229.     }
  230.     public function getCloud($id)
  231.     {
  232.         $this->setAPIResource('clouds/' . $id);
  233.         $result = $this->sendGETRequest();
  234.         return $result['response'];
  235.     }
  236.     public function getProfile()
  237.     {
  238.         $this->setAPIResource('profile');
  239.         $result = $this->sendGETRequest();
  240.         return $result['response']->user;
  241.     }
  242.     /**
  243.      * Returns IP addresses from your account.
  244.      * @param int $consumer_id (Optional) Consumer Id to filter results by
  245.      * @return array An array of IPAddress instances
  246.      */
  247.     public function getIPAddresses($consumer_id = 0)
  248.     {
  249.         if ($consumer_id > 0) {
  250.             $this->setAPIResource('ips', true, 'consumer_id=' . $consumer_id);
  251.             //$this->setAPIResource('ip_address_assignments', true, 'consumer_id=' . $consumer_id);
  252.         } else {
  253.             $this->setAPIResource('ips');
  254.             //$this->setAPIResource('ip_address_assignments');
  255.         }
  256.         $result = $this->sendGETRequest();
  257.         $return = array();
  258.         if ($result['info']['http_code'] == 422) {
  259.         } else if ($result['response']) {
  260.             $response = $result['response'];
  261.             //                        print_r($result);
  262.             for ($x = 0; $x < count($response); $x++) {
  263.                 $return[$x] = $this->_castObjectToClass('IPAddress', $response[$x]->ip_address);
  264.             }
  265.         }
  266.         return $return;
  267.     }
  268.     /**
  269.      * Returns Virtual Machines from your account.
  270.      * @param int $consumer_id (Optional) Consumer Id to filter results by
  271.      * @return array An array of VirtualMachine instances
  272.      */
  273.     public function getVirtualMachines($consumer_id = 0, $deletedAlso = false)
  274.     {
  275.         if ($consumer_id > 0)
  276.             $this->setAPIResource('virtual_machines', true, 'consumer_id=' . $consumer_id);
  277.         else
  278.             $this->setAPIResource('virtual_machines', true, 'basic');
  279.         $result = $this->sendGETRequest();
  280.         if ($deletedAlso) {
  281.             $this->setAPIResource('virtual_machines/recoverable');
  282.             $dresult = $this->sendGETRequest();
  283.         }
  284.         $return = array();
  285.         $names  = array();
  286.         if ($result['info']['http_code'] == 422) {
  287.         } else if ($result['response']) {
  288.             if ($dresult['response']) {
  289.                 foreach ($dresult['response'] as $k => $vm) {
  290.                     $dresult['response'][$k]->virtual_machine->isDeleted = true;
  291.                 }
  292.             } else {
  293.                 $dresult['response'] = array();
  294.             }
  295.             //$response = array_merge($dresult['response'], $result['response']);
  296.             $response = $result['response'];
  297.             for ($x = 0; $x < count($response); $x++) {
  298.                 $return[$x] = $this->_castObjectToClass('VirtualMachine', $response[$x]->virtual_machine);
  299.             }
  300.         }
  301.         return $return;
  302.     }
  303.     public function getRecoverableVirtualMachines($consumer_id = 0)
  304.     {
  305.         $this->setAPIResource('virtual_machines/recoverable');
  306.         $dresult  = $this->sendGETRequest();
  307.         $names    = array();
  308.         $response = false;
  309.         if ($result['info']['http_code'] == 422) {
  310.         } else if ($result['response']) {
  311.             if ($dresult['response']) {
  312.                 foreach ($dresult['response'] as $k => $vm) {
  313.                     if ($consumer_id > 0) {
  314.                         if ($vm->virtual_machine->consumer_id != $consumer_id)
  315.                             continue;
  316.                     }
  317.                     $dresult['response']->virtual_machine->isDeleted = true;
  318.                     $response[]                                      = $vm;
  319.                 }
  320.             }
  321.             if ($response)
  322.                 for ($x = 0; $x < count($response); $x++) {
  323.                     $return[$x] = $this->_castObjectToClass('VirtualMachine', $response[$x]->virtual_machine);
  324.                 }
  325.         }
  326.         return $return;
  327.     }
  328.     public function getAvailableClouds($fusion = false)
  329.     {
  330.         $this->setAPIResource('available_clouds');
  331.         $result = $this->sendGETRequest();
  332.         $clouds = array();
  333.         if ($result['info']['http_code'] == 422) {
  334.         } else if ($result['response']) {
  335.             $clouds = $result['response'];
  336.         }
  337.         $return = array();
  338.         foreach ($clouds as $cloud) {
  339.             if ($fusion) {
  340.                 if ($cloud->cloud->available) {
  341.                     if (strpos($cloud->cloud->label, 'usion'))
  342.                         $return[] = array(
  343.                             'id' => $cloud->cloud->id,
  344.                             'text' => $cloud->cloud->label
  345.                         );
  346.                 }
  347.             } else {
  348.                 if ($cloud->cloud->available) {
  349.                     if (!strpos($cloud->cloud->label, 'usion'))
  350.                         $return[] = array(
  351.                             'id' => $cloud->cloud->id,
  352.                             'text' => $cloud->cloud->label
  353.                         );
  354.                 }
  355.             }
  356.         }
  357.         return $return;
  358.     }
  359.     public function getTemplatesGroups($cloud_id = 0)
  360.     {
  361.         $this->setAPIResource('available_templates');
  362.         $result                 = $this->sendGETRequest();
  363.         $this->AllTemplatesInfo = array();
  364.         $return                 = array();
  365.         foreach ($result['response']->template_groups as $template_group) {
  366.             if ($cloud_id == 0)
  367.                 $return[] = $template_group->name;
  368.             else {
  369.                 $insert = false;
  370.                 foreach ($template_group->templates as $template) {
  371.                     foreach ($template->clouds as $claud) {
  372.                         if ($claud->id == $cloud_id)
  373.                             $insert = true;
  374.                     }
  375.                 }
  376.                 if ($insert)
  377.                     $return[] = $template_group->name;
  378.             }
  379.         }
  380.         return $return;
  381.     }
  382.     public function getTemplateInfo($cloud_id, $tid)
  383.     {
  384.         $this->setAPIResource('clouds/' . $cloud_id . '/system_templates/' . $tid);
  385.         $result = $this->sendGETRequest();
  386.         return $result['response']->system_template;
  387.     }
  388.     public function getAllTemplates($group = false, $filter = 'all', $cloud = 0)
  389.     {
  390.         $this->setAPIResource('available_templates');
  391.         $result                 = $this->sendGETRequest();
  392.         $this->AllTemplatesInfo = array();
  393.         foreach ($result['response']->template_groups as $template_group) {
  394.             foreach ($template_group->templates as $tempalte) {
  395.                 if ($group) {
  396.                     if ($group == $template_group->name) {
  397.                         if (!isset($this->AllTemplatesInfo[$tempalte->clouds[0]->system_template_id])) {
  398.                             $tinfo = $this->getTemplateInfo($tempalte->clouds[0]->id, $tempalte->clouds[0]->system_template_id);
  399.                             $exist = false;
  400.                             foreach ($tempalte->clouds as $tc) {
  401.                                 if ($tc->id == $cloud)
  402.                                     $exist = true;
  403.                             }
  404.                             if (($exist) || ($cloud == 0))
  405.                                 switch ($filter) {
  406.                                     case 'free':
  407.                                         if ($tinfo->applicable_price->USD == 0)
  408.                                             $this->AllTemplatesInfo[$tempalte->clouds[0]->system_template_id] = $tinfo;
  409.                                         break;
  410.                                     case 'paid':
  411.                                         if ($tinfo->applicable_price->USD > 0)
  412.                                             $this->AllTemplatesInfo[$tempalte->clouds[0]->system_template_id] = $tinfo;
  413.                                         break;
  414.                                     default:
  415.                                         $this->AllTemplatesInfo[$tempalte->clouds[0]->system_template_id] = $tinfo;
  416.                                         break;
  417.                                 }
  418.                         }
  419.                     }
  420.                 } else {
  421.                     if (!isset($this->AllTemplatesInfo[$tempalte->clouds[0]->system_template_id])) {
  422.                         $tinfo = $this->getTemplateInfo($tempalte->clouds[0]->id, $tempalte->clouds[0]->system_template_id);
  423.                         $exist = false;
  424.                         foreach ($tempalte->clouds as $tc) {
  425.                             if ($tc->id == $cloud)
  426.                                 $exist = true;
  427.                         }
  428.                         if (($exist) || ($cloud == 0))
  429.                             switch ($filter) {
  430.                                 case 'free':
  431.                                     if ($tinfo->applicable_price->USD == 0)
  432.                                         $this->AllTemplatesInfo[$tempalte->clouds[0]->system_template_id] = $tinfo;
  433.                                     break;
  434.                                 case 'paid':
  435.                                     if ($tinfo->applicable_price->USD > 0)
  436.                                         $this->AllTemplatesInfo[$tempalte->clouds[0]->system_template_id] = $tinfo;
  437.                                     break;
  438.                                 default:
  439.                                     $this->AllTemplatesInfo[$tempalte->clouds[0]->system_template_id] = $tinfo;
  440.                                     break;
  441.                             }
  442.                      }
  443.                 }
  444.             }
  445.         }
  446.         return $this->AllTemplatesInfo;
  447.     }
  448.     /**
  449.      * Returns available Clouds and Virtual Machine templates.
  450.      * @return array
  451.      */
  452.     public function getAvailableCloudsAndTemplates()
  453.     {
  454.         $this->setAPIResource('available_clouds');
  455.         $result = $this->sendGETRequest();
  456.         $return = null;
  457.         if ($result['info']['http_code'] == 422) {
  458.         } else if ($result['response']) {
  459.             $return = $result['response'];
  460.         }
  461.         return $return;
  462.     }
  463.     /**
  464.      * Adds internal IP addresses to your account.
  465.      * @param int $quantity Number of IPs to add
  466.      * @param int $consumer_id (Optional) Consumer Id to tag the IP Address with
  467.      * @return IPAddress An instance of the IP address that was assigned
  468.      */
  469.     public function addInternalIPAddresses($quantity, $consumer_id = 0)
  470.     {
  471.         if ($quantity < 1) {
  472.             trigger_error("To call VPSNET::addInternalIPAddress() you must provide a quantity greater than 0", E_USER_ERROR);
  473.             return false;
  474.         }
  475.         $this->setAPIResource('ip_address_assignments');
  476.         $json_request['ip_address_assignment']->quantity = $quantity;
  477.         $json_request['ip_address_assignment']->type     = 'internal';
  478.         if ($consumer_id > 0)
  479.             $json_request['ip_address_assignment']->consumer_id = $consumer_id;
  480.         $result = $this->sendPOSTRequest($json_request);
  481.         $return = null;
  482.         if ($result['response']) {
  483.             $return = $result['response'];
  484.         }
  485.         return $return;
  486.     }
  487.     /**
  488.      * Adds external IP addresses to your account.
  489.      * @param int $quantity Number of IPs to add
  490.      * @param int $cloud_id Id of the cluster on which to add the IP Address
  491.      * @param int $consumer_id (Optional) Consumer Id to tag the IP Address with
  492.      * @return IPAddress An instance of the IP address that was assigned
  493.      */
  494.     public function addExternalIPAddresses($quantity, $cloud_id, $consumer_id = 0)
  495.     {
  496.         if ($quantity < 1 || $cloud_id < 1) {
  497.             trigger_error("To call VPSNET::addExternalIPAddresses() you must provide a quantity greater than 0 and a cluster_id", E_USER_ERROR);
  498.             return false;
  499.         }
  500.         $this->setAPIResource('ip_address_assignments');
  501.         $json_request['ip_address_assignment']->quantity = $quantity;
  502.         $json_request['ip_address_assignment']->cloud_id = $cloud_id;
  503.         $json_request['ip_address_assignment']->type     = 'external';
  504.         if ($consumer_id > 0)
  505.             $json_request['ip_address_assignment']->consumer_id = $consumer_id;
  506.         $result = $this->sendPOSTRequest($json_request);
  507.         $return = null;
  508.         if ($result['response']) {
  509.             $return = $result['response'];
  510.         }
  511.         return $return;
  512.     }
  513.     public function deleteIP($id)
  514.     {
  515.         $this->setAPIResource('ips/' . $id);
  516.         $result = $this->sendDELETERequest();
  517.         return $result['response'];
  518.     }
  519.     public function editIP($ipid, $value)
  520.     {
  521.         $this->setAPIResource('ips/' . $ipid);
  522.         $json_request = array(
  523.             'ip_address' => array(
  524.                 'notes' => $value
  525.             )
  526.         );
  527.         $return       = $this->sendPUTRequest($json_request);
  528.         return $return['response'];
  529.     }
  530.     /**
  531.      * Adds IP addresses to your account.
  532.      * @return IPAddress An instance of the IP address that was assigned
  533.      */
  534.     public function addIPAddress($virtual_machine_id, $type)
  535.     {
  536.         $this->setAPIResource('ips');
  537.         $requestdata                       = array();
  538.         $requestdata['type']               = $type;
  539.         $requestdata['quantity']           = 1;
  540.         $requestdata['virtual_machine_id'] = $virtual_machine_id;
  541.         $result                            = $this->sendPOSTRequest($requestdata);
  542.         $ip                                = $result['response'][0]->ip_address;
  543.         $requestdata                       = array();
  544.         if ($ip) {
  545.             $this->setAPIResource('ips/' . $result['response'][0]->ip_address->id);
  546.             $requestdata['ip_address'] = array(
  547.                 'notes' => 'for virtual machine #' . $virtual_machine_id
  548.             );
  549.             $result                    = $this->sendPUTRequest($requestdata);
  550.             return json_encode(array(
  551.                 'message' => array(
  552.                     'responseText' => 'IP successfully added'
  553.                 ),
  554.                 'ip' => $ip
  555.             ));
  556.         }
  557.         return $result['response_body'];
  558.     }
  559.     /**
  560.      * Creates a new Virtual Machine account.
  561.      * @param VirtualMachine $virtualmachine Instance of VirtualMachine containing new virtual machine properties
  562.      * @return VirtualMachine|object An instance of the created VirtualMachine that was assigned or an Object of errors
  563.      */
  564.     public function createVirtualMachine($virtualmachine)
  565.     {
  566.         $this->setAPIResource('virtual_machines');
  567.         $requestdata['label']                   = $virtualmachine->label;
  568.         $requestdata['fqdn']                    = $virtualmachine->hostname;
  569.         $requestdata['slices_required']         = $virtualmachine->slices_required;
  570.         $requestdata['storage_nodes_required']  = $virtualmachine->storage_nodes_required;
  571.         $requestdata['ram_nodes_required']      = $virtualmachine->ram_nodes_required;
  572.         $requestdata['backups_enabled']         = (int) $virtualmachine->backups_enabled;
  573.         $requestdata['rsync_backups_enabled']   = (int) $virtualmachine->rsync_backups_enabled;
  574.         $requestdata['r1_soft_backups_enabled'] = (int) $virtualmachine->r1_soft_backups_enabled;
  575.         $requestdata['system_template_id']      = $virtualmachine->system_template_id;
  576.         $requestdata['cloud_id']                = $virtualmachine->cloud_id;
  577.         $requestdata['consumer_id']             = $virtualmachine->consumer_id;
  578.         if (is_array($virtualmachine->licence))
  579.             $requestdata['licenses'] = $virtualmachine->licence;
  580.         $json_request['virtual_machine'] = $requestdata;
  581.         $result                          = $this->sendPOSTRequest($json_request);
  582.         $return                          = null;
  583.         if (isset($result['response'])) {
  584.             $return = $this->_castObjectToClass('VirtualMachine', $result['response']);
  585.             return $result['response'];
  586.         } else {
  587.             if (isset($result['errors']) && isset($result['errors']->errors) && count($result['errors']->errors) > 0) {
  588.                 $errors = array();
  589.                 foreach ($result['errors']->errors as $error) {
  590.                     $errors[] = "{$error[0]} {$error[1]}";
  591.                 }
  592.                 $errors = implode(", ", $errors);
  593.                 throw new Exception($errors);
  594.             }
  595.             throw new Exception("Unknown error");
  596.         }
  597.     }
  598.     /**
  599.      * Adds Nodes to your account.
  600.      * @param int $quantity Number of Nodes to add
  601.      * @param int $consumer_id (Optional) Consumer Id to tag the IP Address with
  602.      * @return boolean true if nodes were added succesfully, false otherwise
  603.      */
  604.     public function addNodes($quantity, $consumer_id = 0, $type = 'vps')
  605.     {
  606.         $this->setAPIResource('nodes');
  607.         $json_request['quantity'] = $quantity;
  608.         if ($type == 'storage' || $type == 'ram') {
  609.             $json_request['upgrade_option'] = $type;
  610.         }
  611.         if ($consumer_id > 0) {
  612.             $json_request['consumer_id'] = $consumer_id;
  613.         }
  614.         $result = $this->sendPOSTRequest($json_request);
  615.         return ($result['info']['http_code'] == 200);
  616.     }
  617.     public function _castObjectToClass($classname, $object)
  618.     {
  619.         return unserialize(preg_replace('/^O:\d+:"[^"]++"/', 'O:' . strlen($classname) . ':"' . $classname . '"', serialize($object)));
  620.     }
  621.     /**
  622.      * Create domain
  623.      */
  624.     public function createDomain($domain, $ip = '')
  625.     {
  626.         if (!$ip)
  627.             $ip = '127.0.0.1';
  628.         $json_request = array(
  629.             'domain' => array(
  630.                 'name' => $domain,
  631.                 'custom_template' => '',
  632.                 'ip_address' => trim($ip)
  633.             )
  634.         );
  635.         $this->setAPIResource('domains');
  636.         $result = $this->sendPOSTRequest($json_request);
  637.         if ($result['response'] == 'false')
  638.             return false;
  639.         return (int) $result['response']->domain->id;
  640.     }
  641.     public function getDomains()
  642.     {
  643.         $this->setAPIResource('domains');
  644.         $return = $this->sendGETRequest();
  645.         return $return['response'];
  646.     }
  647.     public function getDomainRecords($did)
  648.     {
  649.         $this->setAPIResource('domains/' . $did . '/records');
  650.         $return = $this->sendGETRequest();
  651.         return $return['response'];
  652.     }
  653.     public function getDomainRecord($did, $rid)
  654.     {
  655.         $this->setAPIResource('domains/' . $did . '/records/' . $rid, true, 'new');
  656.         $return = $this->sendGETRequest();
  657.         return $return['response'];
  658.     }
  659.     public function UpdateRecord($did, $rid, $type, $value)
  660.     {
  661.         $this->setAPIResource('domains/' . $did . '/records/' . $rid);
  662.         $json_request = array(
  663.             'domain_record' => array(
  664.                 $type => $value
  665.             )
  666.         );
  667.         $return       = $this->sendPUTRequest($json_request);
  668.         return $return['response'];
  669.     }
  670.     public function addArecord($did, $name, $ip, $ttl)
  671.     {
  672.         $json_request = array(
  673.             'domain_record' => array(
  674.                 'ttl' => $ttl,
  675.                 'data' => $ip,
  676.                 'type' => 'a',
  677.                 'host' => $name
  678.             )
  679.         );
  680.         $this->setAPIResource('domains/' . $did . '/records');
  681.         $return = $this->sendPOSTRequest($json_request);
  682.         return $return['response'];
  683.     }
  684.     public function addNSrecord($did, $name, $ip, $ttl)
  685.     {
  686.         $json_request = array(
  687.             'domain_record' => array(
  688.                 'ttl' => $ttl,
  689.                 'data' => $ip,
  690.                 'type' => 'ns',
  691.                 'host' => $name
  692.             )
  693.         );
  694.         $this->setAPIResource('domains/' . $did . '/records');
  695.         $return = $this->sendPOSTRequest($json_request);
  696.         return $return['response'];
  697.     }
  698.     public function addFailoverrecord($did, $name, $ip, $ips)
  699.     {
  700.         $json_request = array(
  701.             'domain_record' => array(
  702.                 'data' => $ips,
  703.                 'type' => 'failover',
  704.                 'host' => $name,
  705.                 'primary_data' => $ip
  706.             )
  707.         );
  708.         $this->setAPIResource('domains/' . $did . '/records');
  709.         $return = $this->sendPOSTRequest($json_request);
  710.         return $return['response'];
  711.     }
  712.     public function addAAAArecord($did, $name, $ip, $ttl)
  713.     {
  714.         $json_request = array(
  715.             'domain_record' => array(
  716.                 'ttl' => $ttl,
  717.                 'data' => $ip,
  718.                 'type' => 'aaaa',
  719.                 'host' => $name
  720.             )
  721.         );
  722.         $this->setAPIResource('domains/' . $did . '/records');
  723.         $return = $this->sendPOSTRequest($json_request);
  724.         return $return['response'];
  725.     }
  726.     public function addTXTrecord($did, $name, $ip, $ttl)
  727.     {
  728.         $json_request = array(
  729.             'domain_record' => array(
  730.                 'ttl' => $ttl,
  731.                 'data' => $ip,
  732.                 'type' => 'txt',
  733.                 'host' => $name
  734.             )
  735.         );
  736.         $this->setAPIResource('domains/' . $did . '/records');
  737.         $return = $this->sendPOSTRequest($json_request);
  738.         return $return['response'];
  739.     }
  740.     public function addCNAMErecord($did, $name, $ip, $ttl)
  741.     {
  742.         $json_request = array(
  743.             'domain_record' => array(
  744.                 'ttl' => $ttl,
  745.                 'data' => $ip,
  746.                 'type' => 'cname',
  747.                 'host' => $name
  748.             )
  749.         );
  750.         $this->setAPIResource('domains/' . $did . '/records');
  751.         $return = $this->sendPOSTRequest($json_request);
  752.         return $return['response'];
  753.     }
  754.     public function addMXrecord($did, $name, $ip, $ttl, $prior)
  755.     {
  756.         $json_request = array(
  757.             'domain_record' => array(
  758.                 'ttl' => $ttl,
  759.                 'data' => $ip,
  760.                 'type' => 'mx',
  761.                 'host' => $name,
  762.                 'mx_priority' => $prior
  763.             )
  764.         );
  765.         $this->setAPIResource('domains/' . $did . '/records');
  766.         $return = $this->sendPOSTRequest($json_request);
  767.         return $return['response'];
  768.     }
  769.     public function deleteDomainRecord($did, $rid)
  770.     {
  771.         $this->setAPIResource('domains/' . $did . '/records/' . $rid);
  772.         $return = $this->sendDELETERequest();
  773.         return $return['response'];
  774.     }
  775.     public function deleteDomain($did)
  776.     {
  777.         $this->setAPIResource('domains/' . $did);
  778.         $return = $this->sendDELETERequest();
  779.         return $return['response'];
  780.     }
  781.     public function getDomainID($domainname)
  782.     {
  783.         $tld = substr(strstr($domainname, '.'), 1);
  784.         $sld = substr($domainname, 0, strpos($domainname, '.'));
  785.         $this->setAPIResource('domains/' . $sld, true, 'tld=' . $tld);
  786.         $return = $this->sendGETRequest();
  787.         if (isset($return['response']->domain->id))
  788.             return $return['response']->domain->id;
  789.         return 0;
  790.     }
  791.     public function getTickets()
  792.     {
  793.         $this->setAPIResource('tickets');
  794.         $return = $this->sendGETRequest();
  795.         return $return['response'];
  796.     }
  797.     public function getTicket($id)
  798.     {
  799.         $this->setAPIResource('tickets/' . $id);
  800.         $return = $this->sendGETRequest();
  801.         return $return['response'];
  802.     }
  803.     public function openTicket($subject, $body, $department = 1)
  804.     {
  805.         $this->setAPIResource('tickets');
  806.         $json_request = array(
  807.             'subject' => $subject,
  808.             'body' => $body,
  809.             'department' => $department
  810.         );
  811.         $return       = $this->sendPOSTRequest($json_request);
  812.         return $return['response'];
  813.     }
  814.     public function replyTicket($id, $body)
  815.     {
  816.         $this->setAPIResource('tickets/' . $id . '/ticket_replies');
  817.         $json_request = array(
  818.             'body' => $body
  819.         );
  820.         $return       = $this->sendPOSTRequest($json_request);
  821.         return $return['response'];
  822.     }
  823.     public function closeTicket($id)
  824.     {
  825.         $this->setAPIResource('tickets/' . $id);
  826.         $return = $this->sendDELETERequest();
  827.         return $return['response'];
  828.     }
  829. }
  830. /**
  831.  * Node class
  832.  *
  833.  * Allows management of Nodes
  834.  */
  835. class Node
  836. {
  837.     public $virtual_machine_id = 0;
  838.     public $id = 0;
  839.     public $consumer_id = 0;
  840.     public $deleted = 0;
  841.     public $free = false;
  842.     public $discount = false;
  843.     public $type = 'vps';
  844.     public function __construct($id = 0, $virtual_machine_id = 0, $consumer_id = 0, $type = 'vps', $free = false, $discount = false)
  845.     {
  846.         $this->id                 = $id;
  847.         $this->virtual_machine_id = $virtual_machine_id;
  848.         $this->consumer_id        = $consumer_id;
  849.         $this->type               = $type;
  850.         $this->free               = $free;
  851.         $this->discount           = $discount;
  852.     }
  853.     public function update($consumer_id)
  854.     {
  855.         $api = VPSNET::getInstance();
  856.         if ($this->id < 1) {
  857.             trigger_error("To call Node::remove() you must set its id", E_USER_ERROR);
  858.             return false;
  859.         }
  860.         switch ($this->type) {
  861.             case 'storage':
  862.                 $api->setAPIResource('nodes/' . $this->id . '/update_storage_node');
  863.                 break;
  864.             case 'ram':
  865.                 $api->setAPIResource('nodes/' . $this->id . '/update_ram_node');
  866.                 break;
  867.             default:
  868.                 $api->setAPIResource('nodes/' . $this->id);
  869.                 break;
  870.         }
  871.         $json_request['consumer_id'] = $consumer_id;
  872.         $result                      = $api->sendPUTRequest($json_request);
  873.     }
  874.     /**
  875.      * Removes Node from your account
  876.      * @return boolean true if Node was deleted succesfully, false otherwise
  877.      */
  878.     public function remove()
  879.     {
  880.         $api = VPSNET::getInstance();
  881.         if ($this->id < 1) {
  882.             trigger_error("To call Node::remove() you must set its id", E_USER_ERROR);
  883.             return false;
  884.         }
  885.         if ($this->virtual_machine_id > 0) {
  886.             trigger_error("You cannot call Node::remove() with a node assigned to a virtual machine. Instead use VirtualMachine::update()", E_USER_ERROR);
  887.             return false;
  888.         }
  889.         switch ($this->type) {
  890.             case 'storage':
  891.                 $api->setAPIResource('nodes/' . $this->id . '/remove_storage_node');
  892.                 break;
  893.             case 'ram':
  894.                 $api->setAPIResource('nodes/' . $this->id . '/remove_ram_node');
  895.                 break;
  896.             default:
  897.                 $api->setAPIResource('nodes/' . $this->id);
  898.                 break;
  899.         }
  900.         $result        = $api->sendDELETERequest();
  901.         //                print_r($result);
  902.         $this->deleted = ($result['info']['http_code'] == 200);
  903.         return $this->deleted;
  904.     }
  905. }
  906. /**
  907.  * IP Address class
  908.  *
  909.  * Allows management of IP addresses
  910.  */
  911. class IPAddress
  912. {
  913.     public $id = 0;
  914.     public $netmask = '';
  915.     public $network = '';
  916.     public $cloud_id = 0;
  917.     public $ip_address = '';
  918.     public $consumer_id = 0;
  919.     public $deleted = false;
  920.     private function __construct($id)
  921.     {
  922.         $this->id = $id;
  923.     }
  924.     /**
  925.      * Use to find out if an IP address is Internal
  926.      * @return boolean true if IP address is Internal, false otherwise
  927.      */
  928.     public function isInternal()
  929.     {
  930.         return ($cloud_id == 0);
  931.     }
  932.     /**
  933.      * Use to find out if an IP address is External
  934.      * @return boolean true if IP address is External, false otherwise
  935.      */
  936.     public function isExternal()
  937.     {
  938.         return ($cloud_id > 0);
  939.     }
  940.     /**
  941.      * Removes IP address from your account
  942.      * @return boolean true if IP address was deleted succesfully, false otherwise
  943.      */
  944.     public function remove()
  945.     {
  946.         $api = VPSNET::getInstance();
  947.         if ($this->id < 1) {
  948.             trigger_error("To call IPAddress::remove() you must set id", E_USER_ERROR);
  949.             return false;
  950.         }
  951.         $api->setAPIResource('ip_address_assignments/' . $this->id);
  952.         $result        = $api->sendDELETERequest();
  953.         $this->deleted = ($result['info']['http_code'] == 200);
  954.         return $this->deleted;
  955.     }
  956. }
  957. /**
  958.  * Backups class
  959.  *
  960.  * Allows management of Backups
  961.  */
  962. class Backup
  963. {
  964.     public $virtual_machine_id = 0;
  965.     public $id = 0;
  966.     public $label = '';
  967.     public $auto_backup_type;
  968.     public $deleted = false;
  969.     public function __construct($id = 0, $virtual_machine_id = 0)
  970.     {
  971.         $this->id                 = $id;
  972.         $this->virtual_machine_id = $virtual_machine_id;
  973.     }
  974.     /**
  975.      * Restores a backup
  976.      * @return boolean true if backup restore request was succesful, false otherwise
  977.      */
  978.     public function restore()
  979.     {
  980.         $api = VPSNET::getInstance();
  981.         if ($this->id < 1 || $this->virtual_machine_id < 1) {
  982.             trigger_error("To call Backup::restore() you must set id and virtual_machine_id", E_USER_ERROR);
  983.             return false;
  984.         }
  985.         $api->setAPIResource('virtual_machines/' . $this->virtual_machine_id . '/backups/' . $this->id . '/restore');
  986.         $result = $api->sendPOSTRequest();
  987.         return ($result['info']['http_code'] == 200);
  988.     }
  989.     /**
  990.      * Removes a backup
  991.      * @return boolean true if backup was removed, false otherwise
  992.      */
  993.     public function remove()
  994.     {
  995.         $api = VPSNET::getInstance();
  996.         if ($this->id < 1 || $this->virtual_machine_id < 1) {
  997.             trigger_error("To call Backup::remove() you must set id and virtual_machine_id", E_USER_ERROR);
  998.             return false;
  999.         }
  1000.         $api->setAPIResource('virtual_machines/' . $this->virtual_machine_id . '/backups/' . $this->id);
  1001.         $result        = $api->sendDELETERequest();
  1002.         $this->deleted = ($result['info']['http_code'] == 200);
  1003.         return $this->deleted;
  1004.     }
  1005. }
  1006. /**
  1007.  * Upgrade Schedule class
  1008.  *
  1009.  * Allows management of Scheduled Upgrades
  1010.  */
  1011. class UpgradeSchedule
  1012. {
  1013.     public $id = 0;
  1014.     public $label = '';
  1015.     public $extra_slices = 0;
  1016.     public $temporary = false;
  1017.     public $run_at;
  1018.     public $days;
  1019.     public function __construct($label, $extra_slices, $run_at, $days = 0)
  1020.     {
  1021.         $this->temporary    = ($days > 0);
  1022.         $this->label        = $label;
  1023.         $this->extra_slices = $extra_slices;
  1024.         $this->run_at       = date_format('c', $run_at);
  1025.         if ($days > 0)
  1026.             $this->days = $days;
  1027.     }
  1028. }
  1029. /**
  1030.  * Virtual Machines class
  1031.  *
  1032.  * Allows management of Virtual Machines
  1033.  */
  1034. class VirtualMachine
  1035. {
  1036.     public $label = '';
  1037.     public $hostname = '';
  1038.     public $domain_name = '';
  1039.     public $slices_count = 0;
  1040.     public $slices_required = 0;
  1041.     public $ram_nodes_required = 0;
  1042.     public $backups_enabled = 0;
  1043.     public $system_template_id = 0;
  1044.     public $cloud_id = 0;
  1045.     public $id;
  1046.     public $consumer_id = 0;
  1047.     public $created_at = null; // "2009-05-12T09:33:05-04:00"
  1048.     public $updated_at = null; // "2009-05-12T09:33:05-04:00"
  1049.     public $password = '';
  1050.     public $backups = array(); // call fullyLoad() to retrieve this
  1051.     public $upgrade_schedules = array(); // call fullyLoad() to retrieve this
  1052.     public $deleted = false;
  1053.     public function __construct($label = '', $hostname = '', $slices_required = '', $backups_enabled = '', $cloud_id = '', $system_template_id = '', $consumer_id = 0, $storage_nodes_required = 0, $rsync_backups_enabled = '', $r1_soft_backups_enabled = '', $licence = NULL, $ram_nodes_required = 0)
  1054.     {
  1055.         $this->label                   = $label;
  1056.         $this->hostname                = $hostname;
  1057.         $this->slices_required         = $slices_required;
  1058.         $this->storage_nodes_required  = $storage_nodes_required;
  1059.         $this->ram_nodes_required      = $ram_nodes_required;
  1060.         $this->backups_enabled         = $backups_enabled;
  1061.         $this->rsync_backups_enabled   = $rsync_backups_enabled;
  1062.         $this->r1_soft_backups_enabled = $r1_soft_backups_enabled;
  1063.         $this->cloud_id                = $cloud_id;
  1064.         $this->system_template_id      = $system_template_id;
  1065.         $this->consumer_id             = $consumer_id;
  1066.         $this->licence                 = $licence;
  1067.     }
  1068.     private function _doAction($action)
  1069.     {
  1070.         $api = VPSNET::getInstance();
  1071.         $api->setAPIResource('virtual_machines/' . $this->id . '/' . $action);
  1072.         $result = $api->sendPOSTRequest();
  1073.         //      print_r($result);
  1074.         if ($result['info']['http_code'] != 200) {
  1075.             throw new Exception("Error performing action");
  1076.         } else if (isset($result['response'])) {
  1077.             foreach ($result['response']->virtual_machine as $key => $value) {
  1078.                 $this->$key = $value;
  1079.             }
  1080.         }
  1081.         return $this;
  1082.     }
  1083.     /**
  1084.      * Powers on a virtual machine
  1085.      * @return VirtualMachine Virtual Machine instance
  1086.      */
  1087.     public function powerOn()
  1088.     {
  1089.         return $this->_doAction('power_on');
  1090.     }
  1091.     /**
  1092.      * Powers off a virtual machine
  1093.      * @return VirtualMachine Virtual Machine instance
  1094.      */
  1095.     public function powerOff()
  1096.     {
  1097.         return $this->_doAction('power_off');
  1098.     }
  1099.     /**
  1100.      * Gracefully shuts down a virtual machine
  1101.      * @return VirtualMachine Virtual Machine instance
  1102.      */
  1103.     public function shutdown()
  1104.     {
  1105.         return $this->_doAction('shutdown');
  1106.     }
  1107.     /**
  1108.      * Reboots a virtual machine
  1109.      * @return VirtualMachine Virtual Machine instance
  1110.      */
  1111.     public function reboot()
  1112.     {
  1113.         return $this->_doAction('reboot');
  1114.     }
  1115.     /**
  1116.      * Creates a backup
  1117.      * @param string $label Name of backup
  1118.      * @return Backup Backup instance
  1119.      */
  1120.     public function createBackup($label)
  1121.     {
  1122.         if (!is_string($label) || strlen($label) < 0) {
  1123.             trigger_error("To call VirtualMachine::createBackup() you must specify a label", E_USER_ERROR);
  1124.             return false;
  1125.         }
  1126.         $api = VPSNET::getInstance();
  1127.         $api->setAPIResource('virtual_machines/' . $this->id . '/backups');
  1128.         $json_request['backup']->label = $label;
  1129.         $result                        = $api->sendPOSTRequest($json_request);
  1130.         $return                        = null;
  1131.         if ($result['info']['http_code'] == 422) {
  1132.             // Do some error handling
  1133.         } else {
  1134.             $this->backups[] = $api->_castObjectToClass('Backup', $result['response']);
  1135.         }
  1136.         return $result['response_body'];
  1137.     }
  1138.     /**
  1139.      * Creates a temporary upgrade schedule
  1140.      * @param string $label Name of upgrade schedule
  1141.      * @param int $extra_slices Number of new nodes
  1142.      * @param date $run_at Date to run upgrade schedule
  1143.      * @param int $days Number of days to run upgrade schedule for
  1144.      * @return UpgradeSchedule instance
  1145.      */
  1146.     public function createTemporaryUpgradeSchedule($label, $extra_slices, $run_at, $days)
  1147.     {
  1148.         $bInputErrors = false;
  1149.         if (!is_string($label) || strlen($label) < 0) {
  1150.             trigger_error("To call VirtualMachine::createTemporaryUpgradeSchedule() you must specify a label", E_USER_ERROR);
  1151.             $bInputErrors = true;
  1152.         }
  1153.         if (!is_int($extra_slices)) {
  1154.             trigger_error("To call VirtualMachine::createTemporaryUpgradeSchedule() you must specify extra_slices as a number", E_USER_ERROR);
  1155.             $bInputErrors = true;
  1156.         }
  1157.         if (!is_int($days) || $days < 1) {
  1158.             trigger_error("To call VirtualMachine::createTemporaryUpgradeSchedule() you must specify days as a number greater than 0", E_USER_ERROR);
  1159.             $bInputErrors = true;
  1160.         }
  1161.         if ($bInputErrors)
  1162.             return false;
  1163.         $api = VPSNET::getInstance();
  1164.         $api->setAPIResource('virtual_machines/' . $this->id . '/backups');
  1165.         $json_request['backup']->label = $label;
  1166.         $result                        = $api->sendPOSTRequest($json_request);
  1167.         $return                        = null;
  1168.         if ($result['info']['http_code'] == 422) {
  1169.             // Do some error handling
  1170.         } else {
  1171.             $this->backups[] = $api->_castObjectToClass('Backup', $result['response']);
  1172.         }
  1173.         return $result['response'];
  1174.     }
  1175.     /**
  1176.      * Outputs a bandwidth usage graph to output stream
  1177.      * @param string $period Period of usage ('hourly', 'daily', 'weekly', 'monthly')
  1178.      */
  1179.     public function showNetworkGraph($period)
  1180.     {
  1181.         if (!in_array($period, array(
  1182.             'hourly',
  1183.             'daily',
  1184.             'weekly',
  1185.             'monthly'
  1186.         ))) {
  1187.             trigger_error("To call VirtualMachine::getNetworkGraph() you must specify a period of hourly, daily, weekly or monthly", E_USER_ERROR);
  1188.             return false;
  1189.         }
  1190.         if ($this->cloud_info->cloud_version == 2) {
  1191.             $this->composeNetworkGraph($period);
  1192.             header('Content-type: Content-Type: image/png');
  1193.             header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (2 * 3600)) . ' GMT');
  1194.             header('Cache-Control: max-age=3600, public');
  1195.             echo file_get_contents(dirname(__FILE__) . '/charts/' . $this->id . '-' . $period . '_usage.png');
  1196.         } else {
  1197.             return $this->showGraph($period, 'network');
  1198.         }
  1199.     }
  1200.     public function composeNetworkGraph($period = 'hourly')
  1201.     {
  1202.         $iName = $this->id . '-' . $period . '_usage.png';
  1203.         $iPath = dirname(__FILE__) . '/charts/';
  1204.         if (file_exists($iPath . $iName)) {
  1205.             switch ($period) {
  1206.                 default:
  1207.                     if ((time() - filemtime($iPath . $iName)) / 60 <= 5)
  1208.                         return;
  1209.                     break;
  1210.                 case 'daily':
  1211.                     if ((time() - filemtime($iPath . $iName)) / 60 <= 60)
  1212.                         return;
  1213.                     break;
  1214.                 case 'weekly':
  1215.                     if ((time() - filemtime($iPath . $iName)) / 60 <= 12 * 60)
  1216.                         return;
  1217.                     break;
  1218.                 case 'monthly':
  1219.                     if ((time() - filemtime($iPath . $iName)) / 60 <= 24 * 60)
  1220.                         return;
  1221.                     break;
  1222.             }
  1223.         }
  1224.         $nu       = $this->getNetworkUtilisation();
  1225.         $DataSet  = new pData;
  1226.         $received = 0;
  1227.         $sent     = 0;
  1228.         $name     = "";
  1229.         switch ($period) {
  1230.             case 'hourly':
  1231.                 $name  = "Hourly Usage";
  1232.                 $start = count($nu) - 24;
  1233.                 if ($start < 0)
  1234.                     $start = 0;
  1235.                 for ($i = $start; $i < count($nu); $i++) {
  1236.                     $data = $nu[$i];
  1237.                     $dsc  = date('H:i', strtotime($data->created_at));
  1238.                     $DataSet->AddPoint((int) ($data->data_received / 1024), "Serie1", $dsc);
  1239.                     $DataSet->AddPoint((int) ($data->data_sent / 1024), "Serie2", $dsc);
  1240.                     $received += $data->data_received;
  1241.                     $sent += $data->data_sent;
  1242.                 }
  1243.                 break;
  1244.             case 'weekly':
  1245.                 $name = "Weekly Usage";
  1246.                 for ($i = -12; $i <= 0; $i++) {
  1247.                     $start          = mktime(0, 0, 0, date('m'), date('d') + $i, date('Y'));
  1248.                     $end            = mktime(23, 59, 59, date('m'), date('d') + $i, date('Y'));
  1249.                     $dsc            = date('j D', $start);
  1250.                     $total_received = 0;
  1251.                     $total_sent     = 0;
  1252.                     foreach ($nu as $data) {
  1253.                         $cur = strtotime($data->created_at);
  1254.                         if (($cur >= $start) && ($cur <= $end)) {
  1255.                             $total_received = $total_received + $data->data_received;
  1256.                             $total_sent     = $total_sent + $data->data_sent;
  1257.                             $received += $data->data_received;
  1258.                             $sent += $data->data_sent;
  1259.                         }
  1260.                     }
  1261.                     $DataSet->AddPoint((int) ($total_received / 1024), "Serie1", $dsc);
  1262.                     $DataSet->AddPoint((int) ($total_sent / 1024), "Serie2", $dsc);
  1263.                 }
  1264.                 break;
  1265.             case 'daily':
  1266.                 $name = "Daily Usage";
  1267.                 for ($i = -6; $i <= 0; $i++) {
  1268.                     $start          = mktime(0, 0, 0, date('m'), date('d') + $i, date('Y'));
  1269.                     $end            = mktime(23, 59, 59, date('m'), date('d') + $i, date('Y'));
  1270.                     $dsc            = date('j D', $start);
  1271.                     $total_received = 0;
  1272.                     $total_sent     = 0;
  1273.                     foreach ($nu as $data) {
  1274.                         $cur = strtotime($data->created_at);
  1275.                         if (($cur >= $start) && ($cur <= $end)) {
  1276.                             $total_received = $total_received + $data->data_received;
  1277.                             $total_sent     = $total_sent + $data->data_sent;
  1278.                             $received += $data->data_received;
  1279.                             $sent += $data->data_sent;
  1280.                         }
  1281.                     }
  1282.                     $DataSet->AddPoint((int) ($total_received / 1024), "Serie1", $dsc);
  1283.                     $DataSet->AddPoint((int) ($total_sent / 1024), "Serie2", $dsc);
  1284.                 }
  1285.                 break;
  1286.             case 'monthly':
  1287.                 $name = "Monthly Usage";
  1288.                 for ($i = -3; $i <= 0; $i++) {
  1289.                     $start          = mktime(0, 0, 0, date('m') + $i, 1, date('Y'));
  1290.                     $end            = mktime(0, 0, -1, date('m') + $i + 1, 1, date('Y'));
  1291.                     $dsc            = date('M', $start);
  1292.                     $total_received = 0;
  1293.                     $total_sent     = 0;
  1294.                     foreach ($nu as $data) {
  1295.                         $cur = strtotime($data->created_at);
  1296.                         if (($cur >= $start) && ($cur <= $end)) {
  1297.                             $total_received = $total_received + $data->data_received;
  1298.                             $total_sent     = $total_sent + $data->data_sent;
  1299.                             $received += $data->data_received;
  1300.                             $sent += $data->data_sent;
  1301.                         }
  1302.                     }
  1303.                     $DataSet->AddPoint((int) ($total_received / 1024), "Serie1", $dsc);
  1304.                     $DataSet->AddPoint((int) ($total_sent / 1024), "Serie2", $dsc);
  1305.                 }
  1306.                 break;
  1307.         }
  1308.         $DataSet->AddAllSeries();
  1309.         $DataSet->SetAbsciseLabelSerie();
  1310.         $DataSet->SetYAxisUnit(' M');
  1311.         $DataSet->SetSerieName($this->formatBytes($received * 1024) . " received", "Serie1");
  1312.         $DataSet->SetSerieName($this->formatBytes($sent * 1024) . " sent", "Serie2");
  1313.         // Initialise the graph
  1314.         $Test = new pChart(650, 250);
  1315.         $Test->setFontProperties(dirname(__FILE__) . "/assets/fonts/tahoma.ttf", 8);
  1316.         $Test->setGraphArea(55, 30, 540, 200);
  1317.         $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 90, 0);
  1318.         $Test->drawGrid(4, TRUE, 230, 230, 230, 50); //reshotka
  1319.         // Draw the line graph
  1320.         $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription());
  1321.         $Test->drawPlotGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 3, 2, 255, 255, 255);
  1322.         // Finish the graph
  1323.         $Test->setFontProperties(dirname(__FILE__) . "/assets/fonts/tahoma.ttf", 8); // Description
  1324.         $Test->drawLegend(542, 30, $DataSet->GetDataDescription(), 255, 255, 255);
  1325.         $Test->setFontProperties(dirname(__FILE__) . "/assets/fonts/tahoma.ttf", 10);
  1326.         $Test->drawTitle(50, 22, $name, 50, 50, 50, 555);
  1327.         $Test->Render($iPath . $iName);
  1328.     }
  1329.     public function getNetworkUtilisation($from = '', $to = '')
  1330.     {
  1331.         if (isset($this->NetworkUtilisation))
  1332.             return $this->NetworkUtilisation;
  1333.         $gfrom = (!empty($from) ? 'from=' . $from : '');
  1334.         $gto   = (!empty($to) ? '&to=' . $to : '');
  1335.         $api   = VPSNET::getInstance();
  1336.         $api->setAPIResource('virtual_machines/' . $this->id . '/network_utilisation', true, $gfrom . $gto);
  1337.         $result                   = $api->sendGETRequest();
  1338.         $response_body            = $result['response'];
  1339.         $this->NetworkUtilisation = $response_body;
  1340.         return $response_body;
  1341.     }
  1342.     public function getCPUUsage()
  1343.     {
  1344.         if (isset($this->CPUUsage))
  1345.             return $this->CPUUsage;
  1346.         $api = VPSNET::getInstance();
  1347.         if (!empty($from)) {
  1348.         }
  1349.         $gfrom = (!empty($from) ? 'from=' . $from : '');
  1350.         $gto   = (!empty($to) ? '&to=' . $to : '');
  1351.         $api->setAPIResource('virtual_machines/' . $this->id . '/cpu_usage', true, $gfrom . $gto);
  1352.         $result         = $api->sendGETRequest();
  1353.         $response_body  = $result['response'];
  1354.         $this->CPUUsage = $response_body;
  1355.         return $response_body;
  1356.         //         /virtual_machines/xx/network_utilisation.api10json
  1357.     }
  1358.     public function composeCPUUsageGraph($period = 'hourly')
  1359.     {
  1360.         $iPath = dirname(__FILE__) . '/charts/';
  1361.         $iName = $this->id . '-' . $period . '_cpu_usage.png';
  1362.         if (file_exists($iPath . $iName)) {
  1363.             switch ($period) {
  1364.                 default:
  1365.                     if ((time() - filemtime($iPath . $iName)) / 60 <= 5)
  1366.                         return;
  1367.                     break;
  1368.                 case 'daily':
  1369.                     if ((time() - filemtime($iPath . $iName)) / 60 <= 60)
  1370.                         return;
  1371.                     break;
  1372.                 case 'weekly':
  1373.                     if ((time() - filemtime($iPath . $iName)) / 60 <= 12 * 60)
  1374.                         return;
  1375.                     break;
  1376.                 case 'monthly':
  1377.                     if ((time() - filemtime($iPath . $iName)) / 60 <= 24 * 60)
  1378.                         return;
  1379.                     break;
  1380.             }
  1381.         }
  1382.         $cu      = $this->getCPUUsage();
  1383.         $name    = "CPU Usage";
  1384.         $DataSet = new pData;
  1385.         //            foreach ($nu as $data) {
  1386.         switch ($period) {
  1387.             default:
  1388.                 $start      = count($cu) - 24;
  1389.                 $SkipLabels = 1;
  1390.                 break;
  1391.             case 'daily':
  1392.                 $start      = count($cu) - 24 * 4;
  1393.                 $SkipLabels = 4;
  1394.                 break;
  1395.             case 'weekly':
  1396.                 $start      = count($cu) - 24 * 14;
  1397.                 $SkipLabels = 12;
  1398.                 break;
  1399.             case 'monthly':
  1400.                 $start      = count($cu) - 24 * 31 * 3;
  1401.                 $SkipLabels = 24;
  1402.                 break;
  1403.         }
  1404.         //$start=count($cu)-24*7;
  1405.         if ($start < 0)
  1406.             $start = 0;
  1407.         for ($i = $start; $i < count($cu); $i++) {
  1408.             $data = $cu[$i];
  1409.             //print_r($i);
  1410.             $dsc  = date('H:i', strtotime($data->created_at));
  1411.             if (($dsc == '00:00') || ($i == $start)) {
  1412.                 $dsc = date('D H:i', strtotime($data->created_at));
  1413.             }
  1414.             if ($period == 'daily') {
  1415.                 $dsc = date('D H:i', strtotime($data->created_at));
  1416.             }
  1417.             if ($period == 'weekly') {
  1418.                 $dsc = date('d H:i', strtotime($data->created_at));
  1419.             }
  1420.             if ($period == 'monthly') {
  1421.                 $dsc = date('d M', strtotime($data->created_at));
  1422.             }
  1423.             $DataSet->AddPoint((($data->cpu_time / $data->elapsed_time) * 10), "Serie1", $dsc);
  1424.         }
  1425.         $DataSet->AddAllSeries();
  1426.         $DataSet->SetAbsciseLabelSerie();
  1427.         $DataSet->SetYAxisUnit(' %');
  1428.         $DataSet->SetSerieName($this->formatBytes($received * 1024) . " received", "Serie1");
  1429.         // Initialise the graph
  1430.         $Test = new pChart(650, 280);
  1431.         $Test->setFontProperties(dirname(__FILE__) . "/assets/fonts/tahoma.ttf", 8);
  1432.         $Test->setGraphArea(40, 30, 640, 200, TRUE);
  1433.         $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_NORMAL, 150, 150, 150, TRUE, 90, 0, FALSE, $SkipLabels);
  1434.         // Draw the line graph
  1435.         $Test->drawLineGraph($DataSet->GetData(), $DataSet->GetDataDescription());
  1436.         // Finish the graph
  1437.         $Test->setFontProperties(dirname(__FILE__) . "/assets/fonts/tahoma.ttf", 10);
  1438.         $Test->drawTitle(50, 22, $name, 50, 50, 50, 585);
  1439.         $Test->Render(dirname(__FILE__) . '/charts/' . $iName);
  1440.     }
  1441.     /**
  1442.      * Outputs a CPU usage graph to output stream
  1443.      * @param string $period Period of usage ('hourly', 'daily', 'weekly', 'monthly')
  1444.      */
  1445.     public function showCPUGraph($period)
  1446.     {
  1447.         if (!in_array($period, array(
  1448.             'hourly',
  1449.             'daily',
  1450.             'weekly',
  1451.             'monthly'
  1452.         ))) {
  1453.             trigger_error("To call VirtualMachine::getCPUGraph() you must specify a period of hourly, daily, weekly or monthly", E_USER_ERROR);
  1454.             return false;
  1455.         }
  1456.         if ($this->cloud_info->cloud_version == 2) {
  1457.             $ipath = dirname(__FILE__) . '/charts/' . $this->id . '-' . $period . '_cpu_usage.png';
  1458.             //exit;
  1459.             $this->composeCPUUsageGraph($period);
  1460.             header('Content-type: Content-Type: image/png');
  1461.             header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (2 * 3600)) . ' GMT');
  1462.             header('Cache-Control: max-age=3600, public');
  1463.             echo file_get_contents($ipath);
  1464.         } else {
  1465.             return $this->showGraph($period, 'cpu');
  1466.         }
  1467.     }
  1468.     protected function showGraph($period, $type)
  1469.     {
  1470.         $api = VPSNET::getInstance();
  1471.         $api->setAPIResource('virtual_machines/' . $this->id . '/' . $type . '_graph', false, 'period=' . $period);
  1472.         $result        = $api->sendGETRequest();
  1473.         $response_body = $result['response_body'];
  1474.         header('Content-type: ' . $result['info']['content_type']);
  1475.         header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (2 * 3600)) . ' GMT');
  1476.         header('Cache-Control: max-age=3600, public');
  1477.         echo ($result['response_body']);
  1478.         return $result;
  1479.     }
  1480.     public function getVNCConsole($w = 810, $h = 630, $s = 100)
  1481.     {
  1482.         $api = VPSNET::getInstance();
  1483.         $api->setAPIResource('virtual_machines/' . $this->id . '/console');
  1484.         $result  = $api->sendGETRequest();
  1485.         $console = $result['response']->session;
  1486.         echo "
  1487.                    <div class='onapp_console'>
  1488.                      <applet archive='https://www.vps.net/vnc.jar' code='VncViewer.class' codebase=\"https://www.vps.net/vnc/\" height='$h' width='$w'>
  1489.                        <param name='PORT' value='" . $console->port . "' />
  1490.                        <param name='PASSWORD' value='" . $console->password . "' />
  1491.                            <PARAM NAME=\"Scaling factor\" VALUE=$s>
  1492.                      </applet>
  1493.                    </div>";
  1494.     }
  1495.     public function getConsole()
  1496.     {
  1497.         $api = VPSNET::getInstance();
  1498.         $api->setAPIResource('virtual_machines/' . $this->id . '/console');
  1499.         $result = $api->sendGETRequest();
  1500.         if (is_object($result['response']))
  1501.             return $result['response']->session;
  1502.         else
  1503.             return false;
  1504.     }
  1505.     /**
  1506.      * Outputs a Console to output stream
  1507.      */
  1508.     public function showConsole()
  1509.     {
  1510.         $api = VPSNET::getInstance();
  1511.         if ($this->cloud_info->cloud_version == 2) {
  1512.             echo '<html><body>';
  1513.             $this->getVNCConsole();
  1514.             echo '</body></html>';
  1515.             return;
  1516.         }
  1517.         $urlpath = substr($_SERVER['PATH_INFO'], 1);
  1518.         $api->setAPIResource('virtual_machines/' . $this->id . '/console_proxy/' . $urlpath, false);
  1519.         $response_body = $result['response_body'];
  1520.         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  1521.             $requestdata = 'k=' . urlencode($_POST['k']) . '&';
  1522.             $requestdata .= 'w=' . urlencode($_POST['w']) . '&';
  1523.             $requestdata .= 'c=' . urlencode($_POST['c']) . '&';
  1524.             $requestdata .= 'h=' . urlencode($_POST['h']) . '&';
  1525.             $requestdata .= 's=' . urlencode($_POST['s']) . '&';
  1526.             $result = $api->sendPOSTRequest($requestdata, false);
  1527.             header('Content-type: ' . $result['info']['content_type']);
  1528.             echo ($result['response_body']);
  1529.         } else {
  1530.             $result = $api->sendGETRequest();
  1531.             if (strpos($urlpath, '.css'))
  1532.                 header('Content-type: text/css');
  1533.             else
  1534.                 header('Content-type: ' . $result['info']['content_type']);
  1535.             echo ($result['response_body']);
  1536.         }
  1537.         return $result;
  1538.     }
  1539.     /**
  1540.      * Retrieves a list of backups and adds it to backups property of current instance
  1541.      * @return array Array of Backups instances
  1542.      */
  1543.     public function loadBackups()
  1544.     {
  1545.         $api = VPSNET::getInstance();
  1546.         $api->setAPIResource('virtual_machines/' . $this->id . '/backups');
  1547.         $result = $api->sendGETRequest();
  1548.         if ($result['info']['http_code'] == 422) {
  1549.             // Do some error handling
  1550.         } else {
  1551.             $this->backups = array();
  1552.             $response      = $result['response'];
  1553.             for ($x = 0; $x < count($response); $x++) {
  1554.                 $this->backups[$x] = $api->_castObjectToClass('Backup', $response[$x]);
  1555.             }
  1556.         }
  1557.         return $this->backups;
  1558.     }
  1559.     public function loadFully($id = 0)
  1560.     {
  1561.         if ($id) {
  1562.             $this->id = $id;
  1563.         }
  1564.         $api = VPSNET::getInstance();
  1565.         $api->setAPIResource('virtual_machines/' . $this->id);
  1566.         $result = $api->sendGETRequest();
  1567.         if ($result['info']['http_code'] == 422) {
  1568.             // Do some error handling
  1569.         } else {
  1570.             if (is_object($result['response']->virtual_machine))
  1571.                 foreach ($result['response']->virtual_machine as $key => $value) {
  1572.                     $this->$key = $value;
  1573.                 }
  1574.         }
  1575.         if ($this->cloud_id) {
  1576.             $this->cloud_info = $api->getCloud($this->cloud_id);
  1577.         }
  1578.         if (@is_array($this->cloud_info->system_templates))
  1579.             foreach ($this->cloud_info->system_templates as $template) {
  1580.                 if ($template->id == $this->system_template_id)
  1581.                     $this->system_template_name = $template->label;
  1582.             }
  1583.         if (!$this->system_template_name) {
  1584.             $tinfo                      = $api->getTemplateInfo($this->cloud_id, $this->system_template_id);
  1585.             $this->system_template_name = $tinfo->label;
  1586.         }
  1587.         $this->rsync_backups_enabled   = ($this->backup_licenses->rsync_license ? true : false);
  1588.         $this->r1_soft_backups_enabled = ($this->backup_licenses->r1soft_license ? true : false);
  1589.         $this->any_backup_enabled      = $this->backups_enabled || $this->rsync_backups_enabled || $this->r1soft_backups_enabled;
  1590.         return $this;
  1591.     }
  1592.     /**
  1593.      * Updates virtual machine
  1594.      * @return boolean True if update succeeded, false otherwise
  1595.      */
  1596.     public function update()
  1597.     {
  1598.         $api = VPSNET::getInstance();
  1599.         if ($this->id < 1) {
  1600.             throw new Exception("To call VirtualMachine::update() you must set it's id first");
  1601.         }
  1602.         $api->setAPIResource('virtual_machines/' . $this->id);
  1603.         $requestdata['label']                   = $this->label;
  1604.         $requestdata['slices_required']         = $this->slices_required ? $this->slices_required : $this->slices_count;
  1605.         $requestdata['consumer_id']             = $this->consumer_id;
  1606.         $requestdata['backups_enabled']         = (int) $this->backups_enabled;
  1607.         $requestdata['rsync_backups_enabled']   = (int) $this->rsync_backups_enabled;
  1608.         $requestdata['r1_soft_backups_enabled'] = (int) $this->r1_soft_backups_enabled;
  1609.         $requestdata['storage_nodes_required']  = isset($this->storage_nodes_required) ? (int) $this->storage_nodes_required : (int) $this->storage_nodes_count;
  1610.         $requestdata['ram_nodes_required']      = isset($this->ram_nodes_required) ? (int) $this->ram_nodes_required : (int) $this->ram_nodes_count;
  1611.         if (is_array($this->licence))
  1612.             $requestdata['licenses'] = $this->licence;
  1613.         $json_request['virtual_machine'] = $requestdata;
  1614.         $result                          = $api->sendPUTRequest($json_request);
  1615.         if ($result['info']['http_code'] == 200) {
  1616.             return true;
  1617.         }
  1618.         if (isset($result['errors']) && isset($result['errors']->errors) && count($result['errors']->errors) > 0) {
  1619.             $errors = array();
  1620.             foreach ($result['errors']->errors as $error) {
  1621.                 $errors[] = "{$error[0]}: {$error[1]}, ";
  1622.             }
  1623.             $errors = implode(", ", $errors);
  1624.             throw new Exception($errors);
  1625.         }
  1626.         throw new Exception("Unknown error");
  1627.     }
  1628.     /**
  1629.      * Removes a virtual machine
  1630.      * @return boolean true if virtual machine was removed, false otherwise
  1631.      */
  1632.     public function remove($remove_nodes = false)
  1633.     {
  1634.         if ($this->running)
  1635.             $this->powerOff();
  1636.         do {
  1637.             usleep(2000000);
  1638.             $this->loadFully();
  1639.         } while ($this->running);
  1640.         $dellus = array();
  1641.         $api    = VPSNET::getInstance();
  1642.         if ($remove_nodes) {
  1643.             $nodes = $api->getNodes($consumer_id = 0, $type = 'vps');
  1644.             foreach ($nodes as $node) {
  1645.                 if ($node->virtual_machine_id == $this->id)
  1646.                     $dellus[] = $node;
  1647.             }
  1648.             $nodes = $api->getNodes($consumer_id = 0, $type = 'storage');
  1649.             foreach ($nodes as $node) {
  1650.                 if ($node->virtual_machine_id == $this->id)
  1651.                     $dellus[] = $node;
  1652.             }
  1653.             $nodes = $api->getNodes($consumer_id = 0, $type = 'ram');
  1654.             foreach ($nodes as $node) {
  1655.                 if ($node->virtual_machine_id == $this->id)
  1656.                     $dellus[] = $node;
  1657.             }
  1658.         }
  1659.         if ($this->id < 1) {
  1660.             trigger_error("To call VirtualMachine::remove() you must set its id", E_USER_ERROR);
  1661.             return false;
  1662.         }
  1663.         $api->setAPIResource('virtual_machines/' . $this->id);
  1664.         $result        = $api->sendDELETERequest();
  1665.         $this->deleted = ($result['info']['http_code'] == 200);
  1666.         foreach ($dellus as $node) {
  1667.             $node->virtual_machine_id = 0;
  1668.             $node->remove(true);
  1669.         }
  1670.         return $this->deleted;
  1671.     }
  1672.     public function recover()
  1673.     {
  1674.         if ($this->id < 1) {
  1675.             trigger_error("To call VirtualMachine::restore() you must set its id", E_USER_ERROR);
  1676.             return false;
  1677.         }
  1678.         $api = VPSNET::getInstance();
  1679.         $api->setAPIResource('virtual_machines/' . $this->id . '/recover');
  1680.         $result = $api->sendPOSTRequest();
  1681.         return ($result['info']['http_code'] == 200);
  1682.     }
  1683.     public function reinstall($system_template_id)
  1684.     {
  1685.         $api = VPSNET::getInstance();
  1686.         if ($this->id < 1) {
  1687.             throw new Exception("To call VirtualMachine::update() you must set it's id first");
  1688.         }
  1689.         if ($this->running)
  1690.             $this->powerOff();
  1691.         do {
  1692.             usleep(2000000);
  1693.             $this->loadFully();
  1694.         } while ($this->running);
  1695.         $api->setAPIResource('virtual_machines/' . $this->id . '/reinstall');
  1696.         $requestdata['system_template_id'] = $system_template_id;
  1697.         $json_request['virtual_machine']   = $requestdata;
  1698.         $result                            = $api->sendPUTRequest($json_request);
  1699.         return ($result['info']['http_code'] == 200 ? true : false);
  1700.     }
  1701.     public function setConsumer($consumer_id)
  1702.     {
  1703.         $api = VPSNET::getInstance();
  1704.         if ($this->id < 1) {
  1705.             throw new Exception("To call VirtualMachine::update() you must set it's id first");
  1706.         }
  1707.         $this->consumer_id = $consumer_id;
  1708.         foreach ($api->getNodes(0, 'vps') as $node) {
  1709.             if ($node->virtual_machine_id == $this->id) {
  1710.                 $node->update($consumer_id);
  1711.             }
  1712.         }
  1713.         foreach ($api->getNodes(0, 'storage') as $node) {
  1714.             if ($node->virtual_machine_id == $this->id) {
  1715.                 $node->update($consumer_id);
  1716.             }
  1717.         }
  1718.         foreach ($api->getNodes(0, 'ram') as $node) {
  1719.             if ($node->virtual_machine_id == $this->id) {
  1720.                 $node->update($consumer_id);
  1721.             }
  1722.         }
  1723.         return $this->update();
  1724.     }
  1725.     public function getCpanel()
  1726.     {
  1727.         $cpanel = 'none';
  1728.         if (is_array($this->virtual_machine_licenses))
  1729.             foreach ($this->virtual_machine_licenses as $linfo) {
  1730.                 if ($linfo->virtual_machine_license->license_id == 1)
  1731.                     $cpanel = 'cpanel';
  1732.                 if ($linfo->virtual_machine_license->license_id == 6)
  1733.                     $cpanel = 'isp manager';
  1734.             }
  1735.         return $cpanel;
  1736.     }
  1737.     public function getIpAddresses()
  1738.     {
  1739.         $api                = VPSNET::getInstance();
  1740.         $ips                = $api->getIpAddresses();
  1741.         $return             = array();
  1742.         $return['external'] = array();
  1743.         $return['internal'] = array();
  1744.         foreach ($ips as $ip) {
  1745.             if (($ip->virtual_machine_id == $this->id) || ($ip->description == 'for virtual machine #' . $this->id))
  1746.                 if ($ip->cloud_id)
  1747.                     $return['external'][] = $ip;
  1748.                 else
  1749.                     $return['internal'][] = $ip;
  1750.         }
  1751.         return $return;
  1752.     }
  1753.     public function deleteIP($id)
  1754.     {
  1755.         $api = VPSNET::getInstance();
  1756.         $ips = $this->getIpAddresses();
  1757.         $ips = array_merge($ips['external'], $ips['internal']);
  1758.         foreach ($ips as $ip) {
  1759.             if ($id == $ip->id)
  1760.                 return $api->deleteIP($id);
  1761.         }
  1762.     }
  1763.     public function formatBytes($bytes, $precision = 1)
  1764.     {
  1765.         $kilobyte = 1024;
  1766.         $megabyte = $kilobyte * 1024;
  1767.         $gigabyte = $megabyte * 1024;
  1768.         $terabyte = $gigabyte * 1024;
  1769.         if (($bytes >= 0) && ($bytes < $kilobyte)) {
  1770.             return $bytes . ' B';
  1771.         } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
  1772.             return round($bytes / $kilobyte, $precision) . ' KB';
  1773.         } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
  1774.             return round($bytes / $megabyte, $precision) . ' MB';
  1775.         } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
  1776.             return round($bytes / $gigabyte, $precision) . ' GB';
  1777.         } elseif ($bytes >= $terabyte) {
  1778.             return round($bytes / $gigabyte, $precision) . ' TB';
  1779.         } else {
  1780.             return $bytes . ' B';
  1781.         }
  1782.     }
  1783. }
  1784. class CustomTemplate
  1785. {
  1786.     public $template_id;
  1787.     public $label;
  1788.     public $description;
  1789.     public $vmid;
  1790.     public $backup_id;
  1791.     public $user_id;
  1792.     public $reseller;
  1793.     public function __construct($template_id = null, $label = '', $description = '', $vmid = 0)
  1794.     {
  1795.         $this->template_id = $template_id;
  1796.         $this->label       = $label;
  1797.         $this->description = $description;
  1798.         $this->vmid        = $vmid;
  1799.     }
  1800.     public function create()
  1801.     {
  1802.         if ($this->vmid < 1) {
  1803.             throw new Exception("To call CustomTemplate::create() you must set it's id first");
  1804.         }
  1805.         $api = VPSNET::getInstance();
  1806.         $api->setAPIResource('virtual_machines/' . $this->vmid . '/backups/' . $this->backup_id . '/convert');
  1807.         $res = $api->sendPOSTRequest();
  1808.         if ($res['info']['http_code'] === 200) {
  1809.             return true;
  1810.         }
  1811.         return false;
  1812.     }
  1813. }
  1814. ?>
Advertisement
Add Comment
Please, Sign In to add comment