<?php
/**
 * Copyright 2013 Stéphane Depierrepont (aka Toorop)
 *
 * Authors :
 *  - Stéphane Depierrepont (aka Toorop)
 *  - Florian Jensen (aka flosoft) : https://github.com/flosoft
 *  - Gillardeau Thibaut (aka Thibautg16)
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 * http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * cloned from vRack code - 2014-06-30
 */

namespace Ovh\Dedicated\Nasha;

use Guzzle\Http\Message\Response;
use Ovh\Common\AbstractClient;
use Ovh\Common\Exception\BadMethodCallException;
use Ovh\Dedicated\Nasha\Exception\NashaException;

class NashaClient extends AbstractClient
{
    /**
     * Get properties
     *
     * @param string $nasha
     * @return string Json
     * @throws Exception\ServerException
     * @throws Exception\ServerNotFoundException
     */
    public function getnashaProperties($nasha)
    {
        try {
            $r = $this->get('dedicated/nasha/' . $nasha)->send();
        } catch (\Exception $e) {
            throw new NashaException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

/*
{get}	/dedicated/nasha/{serviceName}
{put}	/dedicated/nasha/{serviceName}
{get}	/dedicated/nasha/{serviceName}/partition
{post}	/dedicated/nasha/{serviceName}/partition
{get}	/dedicated/nasha/{serviceName}/partition/{partitionName}
{put}	/dedicated/nasha/{serviceName}/partition/{partitionName}
{delete}/dedicated/nasha/{serviceName}/partition/{partitionName}
{get}	/dedicated/nasha/{serviceName}/partition/{partitionName}/access
{post}	/dedicated/nasha/{serviceName}/partition/{partitionName}/access
{get}	/dedicated/nasha/{serviceName}/partition/{partitionName}/access/{ip}
{delete}/dedicated/nasha/{serviceName}/partition/{partitionName}/access/{ip}
{get}	/dedicated/nasha/{serviceName}/partition/{partitionName}/authorizableBlocks
{get}	/dedicated/nasha/{serviceName}/partition/{partitionName}/authorizableIps
{get}	/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot
{post}	/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot
{get}	/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot/{snapshotType}
{delete}/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot/{snapshotType}
{get}	/dedicated/nasha/{serviceName}/serviceInfos
{put}	/dedicated/nasha/{serviceName}/serviceInfos
{get}	/dedicated/nasha/{serviceName}/task
{get}	/dedicated/nasha/{serviceName}/task/{taskId}
*/
}


<?php
/**
 * User: toorop
 * Date: 22/04/13
 * Time: 15:37
 */

namespace Ovh\Cloud;

use Ovh\Cloud\CloudClient;
use Ovh\Common\Exception\BadConstructorCallException;

class Pca
{
    private $pp = null; // Cloud passport
    private $sn = null; // PCA service name
    private static $CloudClient = null;

    public function __construct($pp, $pcaName)
    {
        if (!$pp) {
            throw new BadConstructorCallException('$pp (OVH cloud passport) parameter is missing', 1);
        }
        $this->pp = $pp;
        if (!$pcaName) {
            throw new BadConstructorCallException(' $pcaName (PCA service name) parameter is missing', 1);
        }
        $this->sn = $pcaName;
    }

    /**
     * Return Cloud client
     *
     * @return object cloudClient
     */
    private static function getClient()
    {
        if (!self::$CloudClient instanceof CloudClient) {
            self::$CloudClient = new CloudClient();
        }
        return self::$CloudClient;
    }

    /**
     * Get PCA properties
     *
     * @return string (json encoded object)
     */
    public function getProperties()
    {
        return json_decode(self::getClient()->getPcaProperties($this->pp, $this->sn));
    }

    /**
     * Return SSH key assoiciated with this PCA
     *
     * @return string key
     */
    public function getSshKey()
    {
        return $this->getProperties()->sshkey;
    }

    /**
     * Set SSH key
     *
     * @param string $key
     */
    public function setSshKey($key)
    {
        self::getClient()->setSshKey($this->pp, $this->sn, $key);
    }

    /**
     * Set Password
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        self::getClient()->setPassword($this->pp, $this->sn, $password);
    }

    /**
     * Return PCA login
     *
     * @return string Login
     */
    public function getLogin()
    {
        return $this->getProperties()->login;
    }

    /**
     * Return PCA host
     *
     * @return string host
     */
    public function getHost()
    {
        return $this->getProperties()->host;
    }

    /**
     * Get info about this PCA
     *
     * @return object info
     */
    public function getInfo()
    {
        return json_decode(self::getClient()->getPcaInfo($this->pp, $this->sn));
    }

    /**
     * Get PCA sessions
     *
     * @return array of string session
     */
    public function getSessions()
    {
        return json_decode(self::getClient()->getPcaSessions($this->pp, $this->sn));
    }

    /**
     * Get session properties
     *
     * @param string $sessId
     * @return object props
     */
    public function getSessionProperties($sessId)
    {
        return json_decode(self::getClient()->getPcaSessionProperties($this->pp, $this->sn, $sessId));
    }

    /**
     * Get files associated with sessionId
     *
     * @param string $sessId
     * @return array of files id
     */
    public function getSessionFiles($sessId)
    {
        return json_decode(self::getClient()->getPcaSessionFiles($this->pp, $this->sn, $sessId));
    }

    /**
     * Get files properties
     *
     * @param string $sessId
     * @param string $fileId
     * @return object file properties
     */
    public function getSessionFilesProperties($sessId, $fileId)
    {
        return json_decode(self::getClient()->getPcaSessionFilesProperties($this->pp, $this->sn, $sessId, $fileId));
    }

    /**
     * Return tasks associated with this PAC
     *
     * @return array of task id
     */
    public function getTasks()
    {
        return json_decode(self::getClient()->getPcaTasks($this->pp, $this->sn));
    }

    /**
     * Return properties of task $taskId
     *
     * @param string $taskId
     * @return object task
     */
    public function getTaskProperties($taskId)
    {
        return json_decode(self::getClient()->getPcaTaskProperties($this->pp, $this->sn, $taskId));

    }

    /**
     * Add a new task (restore, delete)
     *
     * @param  array $task. Keys : string sessionId, string taskFunction (restore|delete), array of string fileIds.
     * @return object task
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @deprecated Use addDeleteTask or addRestoreTask
     */
    public function addTask(array $task)
    {
        if (!array_key_exists('sessionId', $task))
            throw new BadMethodCallException("Parameter $task must have the key 'sessionId'");
        if (!array_key_exists('taskFunction', $task))
            throw new BadMethodCallException("Parameter $task must have the key 'taskFunction'");

        if ($task['taskFunction'] == 'restore') {
            return json_decode(self::getClient()->createPcaRestoreTask($this->pp, $this->sn,$task['sessionId']));
        } elseif ($task['taskFunction'] == 'delete') {
            return json_decode(self::getClient()->createPcaDeleteTask($this->pp, $this->sn,$task['sessionId']));
        }
        throw new BadMethodCallException("Task function available are 'delete' or 'restore'");
    }

    /**
     * Add a new delete task
     *
     * @param string $sessionId The session id to delete.
     * @param object task
     */
    public function addDeleteTask($sessionId)
    {
        return json_decode(self::getClient()->createPcaDeleteTask($this->pp, $this->sn, $sessionId));
    }

    /**
     * Add a new restore task
     *
     * @param string $sessionId The session id to restore.
     * @param object task
     */
    public function addRestoreTask($sessionId)
    {
        return json_decode(self::getClient()->createPcaRestoreTask($this->pp, $this->sn, $sessionId));
    }

    /**
     * Get PCA usage
     *
     * @return object task
     */
    public function getUsage(){
        return json_decode(self::getClient()->getPcaUsage($this->pp, $this->sn));
    }

}


<?php
/**
 * Copyright 2013 Stéphane Depierrepont (aka Toorop)
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 * http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

namespace Ovh\Vps;

use Guzzle\Http\Exception\ClientErrorResponseException;
#use Guzzle\Http\Exception\BadResponseException;
#use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\Message\Response;

use Ovh\Common\AbstractClient;
use Ovh\Common\Exception\BadMethodCallException;
use Ovh\Common\Exception\NotImplementedYetException;
use Ovh\Vps\Exception\VpsNotFoundException;
use Ovh\Vps\Exception\VpsException;

class VpsClient extends AbstractClient
{

    /**
     * Get properties
     *
     * @param string $domain
     * @return string Json
     * @throws Exception\VpsException
     * @throws Exception\VpsNotFoundException
     */
    public function getProperties($domain)
    {
        try {
            $r = $this->get('vps/' . $domain)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Get VPS status
     *
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getStatus($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/status')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $domain
     * @param string $period "lastday" or "lastmonth" or "lastweek" or "lastyear" or "today"
     * @param string $type "cpu:max" or "cpu:used" or "mem:max" or "mem:used" or "net:rx" or "net:tx"
     * @return json encoded propertie
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getMonitoring($domain, $period, $type)
    {
        $period = strtolower($period);
        $type = strtolower($type);
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        if (!in_array($period, array('lastday', 'lastmonth', 'lastweek', 'lastyear', 'today')))
            throw new BadMethodCallException('Parameter $period must be "lastday" or "lastmonth" or "lastweek" or "lastyear" or "today". "' . $period . '" given.');
        if (!in_array($type, array('cpu:max', 'cpu:used', 'mem:max', 'mem:used', 'net:rx', 'net:tx')))
            throw new BadMethodCallException('Parameter $type must be "cpu:max" or "cpu:used" or "mem:max" or "mem:used" or "net:rx" or "net:tx". "' . $type . '" given.');
        try {
            $r = $this->get('vps/' . $domain . '/monitoring?period=' . $period . '&type=' . $type)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(),$e);
        }
        return $r->getBody();
    }

    /**
     * Get current monitoring
     *
     * @param string $domain
     * @param string $type "cpu:max" or "cpu:used" or "mem:max" or "mem:used" or "net:rx" or "net:tx"
     * @return string json encoded
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getCurrentMonitoring($domain, $type)
    {
        $type = strtolower($type);
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        if (!in_array($type, array('cpu:max', 'cpu:used', 'mem:max', 'mem:used', 'net:rx', 'net:tx')))
            throw new BadMethodCallException('Parameter $type must be "cpu:max" or "cpu:used" or "mem:max" or "mem:used" or "net:rx" or "net:tx". "' . $type . '" given.');
        try {
            $r = $this->get('vps/' . $domain . '/use?type=' . $type)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(),$e);
        }
        return $r->getBody(true);
    }

    /**
     * Start VPS
     *
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function start($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->post('vps/' . $domain . '/start')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Stop VPS
     *
     * @param string $domain
     * @return mixed
     * @throws Exception\VpsException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsNotFoundException
     */
    public function stop($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->post('vps/' . $domain . '/stop')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Reboot VPS
     *
     * @param string $domain
     * @return mixed
     * @throws Exception\VpsException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsNotFoundException
     */
    public function reboot($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->post('vps/' . $domain . '/reboot')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    # @todo
    public function setRootPassword($domain, $passwd)
    {
        throw new NotImplementedYetException();
        $domain = (string)$domain;
        if (!$domain)
            throw new \BadMethodCallException('Parameter $domain is missing.');
        $passwd = (string)$passwd;
        if (!$passwd)
            throw new \BadMethodCallException('Parameter $passwd is missing.');

        return false;
    }

    /**
     * Get available upgrade for VPS
     *
     * @param string $domain
     * @return mixed
     * @throws Exception\VpsException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsNotFoundException
     */
    public function getAvailableUpgrades($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/availableUpgrade')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Get available Options
     *
     * @param string $domain
     * @return mixed
     * @throws Exception\VpsException
     * @throws BadMethodCallException
     * @throws Exception\VpsNotFoundException
     */
    public function getAvailableOptions($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/availableOptions')->send();
        } catch (ClientErrorResponseException $e) {
            if ($e->getResponse()->getStatusCode() == '404' && json_decode($e->getResponse()->getBody())->message == "No options found")
                return "[]";
            else
                throw new VpsException($e->getMessage(), $e->getCode(), $e);
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Return all models for the range of the virtual server
     *
     * @param string $domain
     * @return mixed
     * @throws Exception\VpsException
     * @throws BadMethodCallException
     * @throws Exception\VpsNotFoundException
     */
    public function getModels($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/models')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function orderCpanelLicense($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->post('vps/' . $domain . '/orderCpanelLicense')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r;
    }

    /**
     * @param string $domain
     * @param $qty
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function orderPleskLicense($domain, $qty)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        $qty = (string)$qty;
        if (!in_array($qty, array('1', '5', '10', '100', '300', 'unlimited')))
            throw new BadMethodCallException('Parameter $qty must be "1","5","10","100","300","unlimited". ' . $qty . ' given');
        $payload = array('item' => (string)$qty);
        try {
            $r = $this->post('vps/' . $domain . '/orderPleskLicense', null, $payload)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r;
    }

    #

    /**
     * @param string $domain
     * @return mixed
     * @throws \BadMethodCallException
     * @throws Exception\VpsException
     */
    public function orderFtpBackup($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new \BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->post('vps/' . $domain . '/orderFtpBackup')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r;
    }

    /**
     * Disks associated to this VPS
     *
     * @param $domain
     * @return mixed
     * @throws BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getDisks($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/disks')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param $domain
     * @param $diskId
     * @return mixed
     * @throws BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getDiskProperties($domain, $diskId)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        $diskId = (string)$diskId;
        if (!$diskId)
            throw new BadMethodCallException('Parameter $diskId is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/disks/' . $diskId)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Return many statistics about the disk at that time
     *
     * @param string $domain
     * @param int/string $diskId
     * @param $type
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getDiskUsage($domain, $diskId, $type)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        $diskId = (string)$diskId;
        if (!$diskId)
            throw new BadMethodCallException('Parameter $diskId is missing.');
        $type = strtolower($type);
        if (!$type)
            throw new BadMethodCallException('Parameter $type is missing.');
        if (!in_array($type, array('max', 'used')))
            throw new BadMethodCallException('Parameter $type must be "max" or "used". ' . $type . ' given.');
        try {
            $r = $this->get('vps/' . $domain . '/disks/' . $diskId . '/use?type=' . $type)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $domain
     * @param int | string $diskId
     * @param string $period
     * @param string $type
     * @return mixed
     * @throws BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getDiskMonitoring($domain, $diskId, $period, $type)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        $diskId = (string)$diskId;
        if (!$diskId)
            throw new BadMethodCallException('Parameter $diskId is missing.');
        $period = strtolower($period);
        if (!in_array($period, array('lastday', 'lastmonth', 'lastweek', 'lastyear', 'today')))
            throw new BadMethodCallException('Parameter $period must be "lastday" or "lastmonth" or "lastweek" or "lastyear" or "today". ' . $period . ' given.');
        $type = strtolower($type);
        if (!$type)
            throw new BadMethodCallException('Parameter $type is missing.');
        if (!in_array($type, array('max', 'used')))
            throw new BadMethodCallException('Parameter $type must be "max" or "used". ' . $type . ' given.');
        try {
            $r = $this->get('vps/' . $domain . '/disks/' . $diskId . '/monitoring?type=' . $type . '&period=' . $period)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Tasks associated to this virtual server
     *
     * @param string $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getTasks($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/tasks')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Get task properties
     *
     * @param $domain
     * @param $taskId
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getTaskProperties($domain, $taskId)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        $taskId = (string)$taskId;
        if (!$taskId)
            throw new BadMethodCallException('Parameter $taskId is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/tasks/' . $taskId)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(),$e);
        }
        return $r->getBody(true);
    }

    /**
     * Get Ips associated to VPS $domain
     *
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getIps($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/ips')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode());
        }
        return $r->getBody(true);
    }

    /**
     * Get IP properties
     *
     * @param $domain
     * @param $ip
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getIpProperties($domain, $ip)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        $ip = (string)$ip;
        if (!$ip)
            throw new BadMethodCallException('Parameter $ip is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/ips/' . $ip)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(),$e);
        }
        return $r->getBody(true);
    }

    /**
     * @param $domain
     * @param $ip
     * @param $properties
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function setIpProperties($domain, $ip, $properties)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        $ip = (string)$ip;
        if (!$ip)
            throw new BadMethodCallException('Parameter $ip is missing.');
        if (!$properties)
            throw new BadMethodCallException('Parameter $properties is missing.');
        try {
            $r = $this->put('vps/' . $domain . '/ips/' . $ip, array('Content-Type' => 'application/json;charset=UTF-8'), json_encode($properties))->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r;
    }

    /**
     * @param  string $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getSnapshotProperties($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/snapshot')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Set properties of a snapshot
     *
     * @param $domain
     * @param array $properties
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function setSnapshotProperties($domain, array $properties)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        if (!$properties || !is_array($properties) || count($properties) == 0)
            throw new BadMethodCallException('Parameter $properties must be a non empty array.');
        $qr = '';
        foreach ($properties as $k => $v) {
            $qr .= $k . '=' . $v . '&';
        }
        $qr = substr($qr, 0, strlen($qr) - 1);
        try {
            $r = $this->put('vps/' . $domain . '/snapshot/?' . $qr)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(),$e);
        }
        return $r;
    }

    /**
     * Delete snapshot of this VPS
     *
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function deleteSnapshot($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->delete('vps/' . $domain . '/snapshot')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(),$e);
        }
        return $r;
    }

    /**
     * Revert to last snapshot
     *
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function revertToLastSnapshot($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->post('vps/' . $domain . '/snapshot')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(),$e);
        }
        return $r;
    }

    /**
     * Order a snapshot
     *
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function orderSnapshot($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->post('vps/' . $domain . '/orderSnapshot')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r;
    }

    /**
     * Create a snapshot
     *
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function createSnapshot($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->post('vps/' . $domain . '/createSnapshot')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode());
        }
        return $r;
    }

    /**
     * get available templates
     *
     * @param $domain
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getAvailableTemplates($domain)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        try {
            $r = $this->get('vps/' . $domain . '/templates')->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Get template properties
     *
     * @param $domain
     * @param $templateId
     * @return mixed
     * @throws \Ovh\Common\Exception\BadMethodCallException
     * @throws Exception\VpsException
     */
    public function getTemplateProperties($domain, $templateId)
    {
        $domain = (string)$domain;
        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');
        $templateId = (string)$templateId;
        if (!$templateId)
            throw new BadMethodCallException("Parameter $templateId is missing");
        try {
            $r = $this->get('vps/' . $domain . '/templates/' . $templateId)->send();
        } catch (\Exception $e) {
            throw new VpsException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody();
    }

	/**
    * Get Distribution Properties
	* GET /vps/{serviceName}/distribution
	* Information sur le systéme d'exploitation
	*
    * Ajout by @Thibautg16 le 12/06/2014
    *
	* @param string $domain
	*
	* @return Object
	*
    * @throws Exception\ServerException
    * @throws \Ovh\Common\Exception\BadMethodCallException
    */
    public function getDistribution($domain){
        $domain = (string)$domain;

        if (!$domain)
            throw new BadMethodCallException('Parameter $domain is missing.');

        try {
            $r = $this->get('vps/' . $domain . '/distribution')->send();
        } catch (\Exception $e) {
            throw new ServerException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }
}


<?php
/**
 * Copyright 2013 Stéphane Depierrepont (aka Toorop)
 *
 * Authors :
 *  - Stéphane Depierrepont (aka Toorop)
 *  - Florian Jensen (aka flosoft) : https://github.com/flosoft
 *  - Gillardeau Thibaut (aka Thibautg16)
 *  - Scott Brown (aka Slartibardfast)
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 * http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * 2014-06-30 - Slartibardfast - extend for /dedicated/nasha and /ip
 * 2015-05-22 - Thibautg16 - ajout "new" /cloud : http://www.ovh.com/fr/cloud/
 */

namespace Ovh\Common;

use Guzzle\Http\Client;

use Ovh\Dedicated\Server\Server;		// extended with 0.1.2
use Ovh\Cdn\Cdn;
use Ovh\Common\Auth\Keyring;
use Ovh\Common\OvhClient;
use Ovh\Sms\Sms;
use Ovh\Telephony\Telephony;
use Ovh\Vps\Vps;
use Ovh\Vrack\Vrack;
use Ovh\Xdsl\Xdsl;
use Ovh\Cloud\Cloud;

// New with 0.1.2 -- tentative numbering
use Ovh\Ip\Ip;
use Ovh\Dedicated\Nasha\Nasha;
use Ovh\License\Cpanel;
use Ovh\License\Directadmin;
use Ovh\License\Plesk;
use Ovh\License\Virtuozzo;
use Ovh\License\Windows;
Use Ovh\License\Worklight;

class Ovh
{
    // Version
    const VERSION = '0.1.2';

    // Client
    private static $ovhClient = null;

    /**
     * Constructor
     *
     * @param array $config
     */
    public function __construct(array $config = array())
    {
        // Populate keyring
        Keyring::setAppKey($config['AK']); // Application Key
        Keyring::setAppSecret($config['AS']); // Application Secret
        Keyring::setConsumerKey($config['CK']); // Consumer Key
        // Backward compatibility
        if (array_key_exists('RG', $config)) {
            keyring::setAppUrlRegion($config['RG']); // Region
        } else {
            keyring::setAppUrlRegion("FR");
        }
    }

    /**
     *
     *          Common
     *
     */

    /**
     * Common client (for no specific task)
     *
     * @return null|OvhClient
     */
    private static function getOvhClient()
    {
        if (!self::$ovhClient instanceof OvhClient) {
            self::$ovhClient = new OvhClient();
        };
        return self::$ovhClient;
    }

    /**
     *
     *          Dedicated Server
     *
     */

    /**
     * Return list of Dedicated Servers owned by user
     *
     * @return mixed
     */
    public function getDedicatedServerList()
    {
        return json_decode(self::getOvhClient()->getDedicatedServerList());
    }

    /**
     * Return a Dedicated Server object
     *
     * @param $domain
     * @return \Ovh\Dedicated\Server\Server
     */
    public function getDedicatedServer($domain)
    {
        return new Server($domain);
    }

    /**
     * Return list of Vrack owned by user
     *
     * @return mixed
     */
    public function getVrackList()
    {
        return json_decode(self::getOvhClient()->getVrackList());
    }

    /**
     * Return a Vrack object
     *
     * @param $domain
     * @return \Ovh\Vrack\Vrack
     */
    public function getVrack($domain)
    {
        return new Vrack($domain);
    }

    /**
     *
     *          VPS
     *
     */

    /**
     * Return list of VPS owned by user
     *
     * @return mixed
     */
    public function getVpsList()
    {
        return json_decode(self::getOvhClient()->getVpsList());
    }

    /**
     * Return a VPS object
     *
     * @param $domain
     * @return \Ovh\Vps\Vps
     */
    public function getVps($domain)
    {
        return new Vps($domain);
    }

    /**
     *
     *          XDSL
     *
     */

    /**
     * Return xdsl subscription/service
     *
     * @return array
     */
    public function getXdslServices()
    {
        return json_decode(self::getOvhClient()->getXdslServices());
    }

    /**
     * @param $serviceId
     * @return \Ovh\Xdsl\Xdsl
     */
    public function getXdsl($serviceId)
    {
        return new Xdsl($serviceId);
    }

    /**
     *
     *      SMS
     *
     */
    /**
     * Return SMS subscriptions/Service (list of 'domains')
     * @return array
     */
    public function getSmsServices()
    {
        return json_decode(self::getOvhClient()->getSmsServices());
    }

    /**
     * Get new SMS object
     *
     * @param $domain
     * @return Sms
     */
    public function getSms($domain)
    {
        return new Sms($domain);
    }

    /**
     *
     *      Telephony
     *
     */
    /**
     * Return Tekphony subscriptions/Service (list of 'domains')
     * @return array
     */
    public function getTelephonyServices()
    {
        return json_decode(self::getOvhClient()->getTelephonyServices());
    }

    /**
     * Get new Telephony object
     * @param  $domain
     * @return Telephony
     */
    public function getTelephony($domain)
    {
        return new Telephony($domain);
    }

    /**
     *
     *      CDN
     *
     */

    /**
     * Get CDN services
     *
     * @return array
     */
    public function getCdnServices()
    {
        return json_decode(self::getOvhClient()->getCdnServices());
    }

    /**
     * Get available POPs
     *
     * @return array
     */
    public function getCdnPops()
    {
        return json_decode(self::getOvhClient()->getCdnPops());
    }

    /**
     * get CDN pop details
     *
     * @param string $pop (as returned by getCdnPops)
     * @return object
     */
    public function getCdnPopDetails($pop)
    {
        return json_decode(self::getOvhClient()->getCdnPopDetails($pop));
    }

    /**
     * Return a CDN object
     *
     * @param $serviceName
     * @return object Cdn
     */
    public function getCdn($serviceName)
    {
        return new Cdn($serviceName);
    }

    /**
     *
     *      CLOUD
     * PCA : public cloud archive : http://www.ovh.com/fr/cloud/archives/
     * PCS : Public cloud storage : http://www.ovh.com/fr/cloud/stockage/
     *
     */

    /**
     * Return Cloud Services (cloud passport)
     *
     * @return array of services (passport)
     */
    public function getCloudPassports()
    {
        return json_decode(self::getOvhClient()->getCloudPassports());
    }

    /**
     * Return Cloud Services (cloud project)
     * OVH Cloud : http://www.ovh.com/fr/cloud/
     *
     * @return array of services (project)
     */
    public function getCloudProjects()
    {
        return json_decode(self::getOvhClient()->getCloudProjects());
    }

    /**
     * Return a cloud instance
     *
     * @param string $passport (OVH cloud passport)
     * @return Cloud instance
     */
    public function getCloud($passport)
    {
        return new Cloud($passport);
    }

// IP heirarchy
	/*
     * Return list of IP blocks owned by user
	 * Optional Args (positional)
	 * 1. specific server
	 * 2. specific ipblock
	 * 3. specific type of IP (type validated inside client)
     *
     * @return mixed
     */
    public function getIPsList($domain="", $ipblock="", $type="")
    {
        return json_decode(self::getOvhClient()->getIPsList($domain, $ipblock, $type));
    }

	/*
     * Instaniate new IP Client, and Return structure of IP block owned by user
     *
     * @return mixed
     */
	public function getIp($domain)
    {
        return new Ip($domain);
    }

// Dedicated/Nasha heirarchy
	/*
     * Return list of high availability NAS owned by user
     *
     * @return mixed
     */
    public function getNashaList()
    {
        return json_decode(self::getOvhClient()->getnashaList());
    }

	/*
     * Instantiate new nasha object and return structure of specific hanas owned by user
     *
     * @return mixed
     */
	public function getnasha($domain)
    {
        return new Nasha($domain);
    }

// License/Cpanel heirarchy

	/*
	 * returns list of Cpanel licenses associatd with user account
	 *
	 * @return json string[]
	*/
	public function getCpanelList()
	{
		return json_decode(self::getOvhClient()->getCpanelList());
	}

	/*
	 * Instantiates a mew cPanel licence object and returns an object of the specific id
	 *
	 * returns Object
	*/
	public function getCpanelLicence($domain)
	{
		return new Cpanel($domain);
	}

	// License/Directadmin heirarchy

	/*
	 * returns list of Directadmin licenses associatd with user account
	 *
	 * @return json string[]
	*/
	public function getDirectadminList()
	{
		return json_decode(self::getOvhClient()->getDirectadminList());
	}

	/*
	 * Instantiates a new DirectAdmin licence object and returns an object of the specific id
	 *
	 * returns Object
	*/
	public function getDirectadminLicence($domain)
	{
		return new Cpanel($domain);
	}

	// License/Plesk heirarchy

	/*
	 * returns list of Plesk licenses associatd with user account
	 *
	 * @return json string[]
	*/
	public function getPleskList()
	{
		return json_decode(self::getOvhClient()->getPleskList());
	}

	/*
	 * Instantiates a new Plesk licence object and returns an object of the specific id
	 *
	 * returns Object
	*/
	public function getPleskLicence($domain)
	{
		return new Plesk($domain);
	}

	// License/Virtuozzo heirarchy

	/*
	 * returns list of Virtuozzo licenses associatd with user account
	 *
	 * @return json string[]
	*/
	public function getVirtuozzoList()
	{
		return json_decode(self::getOvhClient()->getVirtuozzoList());
	}

	/*
	 * Instantiates a new Virtuozzo licence object and returns an object of the specific id
	 *
	 * returns Object
	*/
	public function getVirtuozzoLicence($domain)
	{
		return new Virtuozzo($domain);
	}

	// License/Windows heirarchy

	/*
	 * returns list of Windows licenses associatd with user account
	 *
	 * @return json string[]
	*/
	public function getWindowsList()
	{
		return json_decode(self::getOvhClient()->getWindowsList());
	}

	/*
	 * Instantiates a new Windows licence object and returns an object of the specific id
	 *
	 * returns Object
	*/
	public function getWindowsLicence($domain)
	{
		return new Windows($domain);
	}

	// License/Worklight heirarchy

	/*
	 * returns list of Worklight licenses associatd with user account
	 *
	 * @return json string[]
	*/
	public function getWorklightList()
	{
		return json_decode(self::getOvhClient()->getWorklightList());
	}

	/*
	 * Instantiates a new Worklight licence object and returns an object of the specific id
	 *
	 * returns Object
	*/
	public function getWorklightLicence($domain)
	{
		return new Worklight($domain);
	}

}


<?php
/**
 * Copyright 2013 Stéphane Depierrepont (aka Toorop)
 *
 * Authors :
 *  - Stéphane Depierrepont (aka Toorop)
 *  - Gillardeau Thibaut (aka Thibautg16)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 * http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * 2015-05-22 - Thibautg16 - ajout "new" /cloud : http://www.ovh.com/fr/cloud/
 */

namespace Ovh\Cloud;

use Ovh\Common\AbstractClient;
use Ovh\Common\Exception\BadMethodCallException;
use Ovh\Cloud\Exception\CloudException;

class CloudClient extends AbstractClient
{

    /**
     * Get PCA services associated with this cloud passport
     *
     * @param string $pp OVH cloud passport
     * @return string (json encoded array)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaServices($pp)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (passport).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca')->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Return properties of PCA $pca service name
     *
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @return string (Json encode object)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaProperties($pp, $pca)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCAS erviceName).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca)->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * Set a SSH public key to PCA
     *
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @param string $key
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function setSshKey($pp, $pca, $key)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        if (!$key)
            throw new BadMethodCallException('Missing parameter $key (Public key for this pca).');
        $payload = array('sshkey' => $key);
        try {
            $this->put('cloud/' . $pp . '/pca/' . $pca, array('Content-Type' => 'application/json;charset=UTF-8'), json_encode($payload))->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * Set password to PCA
     *
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @param string $passwd
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function setPassword($pp, $pca, $passwd)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        if (!$passwd)
            throw new BadMethodCallException('Missing parameter $passwd (Password for this pca).');
        $payload = array('password' => $passwd);
        try {
            $this->put('cloud/' . $pp . '/pca/' . $pca, array('Content-Type' => 'application/json;charset=UTF-8'), json_encode($payload))->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @return string (json encoded object)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaInfo($pp, $pca)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca . '/serviceInfos')->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @return string (json encoded array)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaSessions($pp, $pca)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca . '/sessions')->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @param string $sessId PCA service name
     * @return string (json encoded object)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaSessionProperties($pp, $pca, $sessId)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        if (!$sessId)
            throw new BadMethodCallException('Missing parameter $sessId (PCA Session ID).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca . '/sessions/' . $sessId)->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @param string $sessId PCA service name
     * @return string (json encoded array)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaSessionFiles($pp, $pca, $sessId)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        if (!$sessId)
            throw new BadMethodCallException('Missing parameter $sessId (PCA Session ID).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca . '/sessions/' . $sessId . '/files')->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @param string $sessId PCA service name
     * @param string $fileId PCA service name
     * @return string (json encoded array)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaSessionFilesProperties($pp, $pca, $sessId, $fileId)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        if (!$sessId)
            throw new BadMethodCallException('Missing parameter $sessId (PCA Session ID).');
        if (!$fileId)
            throw new BadMethodCallException('Missing parameter $fileId (file ID).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca . '/sessions/' . $sessId . '/files/' . $fileId)->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @return string json encoded array)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaTasks($pp, $pca)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca . '/tasks')->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @param string $sessionId session id to delete
     * @return string json encoded array
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function createPcaDeleteTask($pp, $pca, $sessionId)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        if (!$sessionId)
             throw new BadMethodCallException('Missing parameter $sessionId (string).');
        try {
            $r = $this->delete('cloud/' . $pp . '/pca/' . $pca . '/sessions/' . $sessionId)->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @param string $sessionId session id to restore
     * @return string json encoded array
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function createPcaRestoreTask($pp, $pca, $sessionId)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        if (!$sessionId)
             throw new BadMethodCallException('Missing parameter $sessionId (string).');
        try {
            $r = $this->post('cloud/' . $pp . '/pca/' . $pca . '/sessions/' . $sessionId . '/restore')->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @param string $taskId task ID
     * @return string json encoded array)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaTaskProperties($pp, $pca, $taskId)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        if (!$taskId)
            throw new BadMethodCallException('Missing parameter $taskId (ID of the tasks).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca . '/tasks/' . $taskId)->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
     * @param string $pp OVH cloud passport
     * @param string $pca PCA service name
     * @return string json encoded array)
     * @throws \Ovh\Cloud\Exception\CloudException
     * @throws \Ovh\Common\Exception\BadMethodCallException
     */
    public function getPcaUsage($pp, $pca)
    {
        if (!$pp)
            throw new BadMethodCallException('Missing parameter $pp (OVH cloud passport).');
        if (!$pca)
            throw new BadMethodCallException('Missing parameter $pca (PCA ServiceName).');
        try {
            $r = $this->get('cloud/' . $pp . '/pca/' . $pca . '/usage')->send();
        } catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /***** OVH Cloud *****/
    /**
    * Get Project Properties
    * GET /cloud/project/{serviceName}
    *
    * @return
    * @throws \Ovh\Cloud\Exception\CloudException
    * @throws \Ovh\Common\Exception\BadMethodCallException
    */
    public function getProjectProperties($serviceName){
        if (!$serviceName)
            throw new BadMethodCallException('Missing parameter $serviceName (OVH Cloud Project).');
        try {
            $r = $this->get('cloud/project/'.$serviceName)->send();
        }
        catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
    * Delete Instances of Project Cloud Public
    * DELETE /cloud/project/{serviceName}/instance/{instanceId}
    *
    * @return
    * @throws \Ovh\Cloud\Exception\CloudException
    * @throws \Ovh\Common\Exception\BadMethodCallException
    */
    public function deleteInstance($serviceName, $idInstance){
        if (!$serviceName)
            throw new BadMethodCallException('Missing parameter $serviceName (OVH Cloud Project).');
        if (!$idInstance)
            throw new BadMethodCallException('Missing parameter $idInstance (OVH Cloud Project Instance ID).');

       try {
            $r = $this->delete('cloud/project/'.$serviceName.'/instance/'.$idInstance)->send();
        }
        catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
    * POST Reboot Instance
    * POST /cloud/project/{serviceName}/instance/{instanceId}/reboot
    *
    * @return null
    * @throws \Ovh\Cloud\Exception\CloudException
    * @throws \Ovh\Common\Exception\BadMethodCallException
    */
    public function postInstanceReboot($serviceName, $idInstance, $type='soft'){
        if (!$serviceName)
            throw new BadMethodCallException('Missing parameter $serviceName (OVH Cloud Project).');
        if (!$idInstance)
            throw new BadMethodCallException('Missing parameter $idInstance (OVH Cloud Instance ID).');

        $post = array(
            'type' => $type
		);

        try {
            $r = $this->post('cloud/project/'.$serviceName.'/instance/'.$idInstance.'/reboot', array('Content-Type' => 'application/json;charset=UTF-8'), json_encode($post))->send();
        }
        catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
    * POST Snapshot Instance
    * POST /cloud/project/{serviceName}/instance/{instanceId}/snapshot
    *
    * @return null
    * @throws \Ovh\Cloud\Exception\CloudException
    * @throws \Ovh\Common\Exception\BadMethodCallException
    */
    public function postInstanceSnapshot($serviceName, $idInstance, $snapshotName){
        if (!$serviceName)
            throw new BadMethodCallException('Missing parameter $serviceName (OVH Cloud Project).');
        if (!$idInstance)
            throw new BadMethodCallException('Missing parameter $idInstance (OVH Cloud Instance ID).');
        if (!$snapshotName)
            throw new BadMethodCallException('Missing parameter $snapshotName (OVH Cloud Instance Snapshot Name).');
        $post = array(
            'snapshotName' => $snapshotName
		);

        try {
            $r = $this->post('cloud/project/'.$serviceName.'/instance/'.$idInstance.'/snapshot', array('Content-Type' => 'application/json;charset=UTF-8'), json_encode($post))->send();
        }
        catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
    * Get Project Balance
    * GET /cloud/project/{serviceName}/balance
    *
    * @return
    * @throws \Ovh\Cloud\Exception\CloudException
    * @throws \Ovh\Common\Exception\BadMethodCallException
    */
    public function getProjectBalance($serviceName){
        if (!$serviceName)
            throw new BadMethodCallException('Missing parameter $serviceName (OVH Cloud Project).');
        try {
            $r = $this->get('cloud/project/'.$serviceName.'/balance')->send();
        }
        catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
    * Get Project Quota
    * GET /cloud/project/{serviceName}/quota
    *
    * @return
    * @throws \Ovh\Cloud\Exception\CloudException
    * @throws \Ovh\Common\Exception\BadMethodCallException
    */
    public function getProjectQuota($serviceName){
        if (!$serviceName)
            throw new BadMethodCallException('Missing parameter $serviceName (OVH Cloud Project).');
        try {
            $r = $this->get('cloud/project/'.$serviceName.'/quota')->send();
        }
        catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }

    /**
    * Get Instances of Project Cloud Public
    * GET /cloud/project/{serviceName}/instance
    *
    * @return
    * @throws \Ovh\Cloud\Exception\CloudException
    * @throws \Ovh\Common\Exception\BadMethodCallException
    */
    public function getProjectInstance($serviceName){
        if (!$serviceName)
            throw new BadMethodCallException('Missing parameter $serviceName (OVH Cloud Project).');
        try {
            $r = $this->get('cloud/project/'.$serviceName.'/instance')->send();
        }
        catch (\Exception $e) {
            throw new CloudException($e->getMessage(), $e->getCode(), $e);
        }
        return $r->getBody(true);
    }
}


<?php
/**
 * Copyright 2013 Stéphane Depierrepont (aka Toorop)
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 * http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

namespace Ovh\Vps;

use Ovh\Common\Exception\NotImplementedYetException;
use Ovh\Common\Exception\NotImplementedYetByOvhException;

use Ovh\Common\Ovh;
use Ovh\Vps\VpsClient;
use Ovh\Common\Task;

class Vps
{
    private $domain = null;
    private static $vpsClient = null;

    /**
     * @param string $domain
     */
    public function __construct($domain)
    {
        $this->setDomain($domain);
    }

    /**
     * Return VPS client
     *
     * @return null|VpsClient
     */
    private static function getClient()
    {
        if (!self::$vpsClient instanceof VpsClient){
            self::$vpsClient=new VpsClient();
        };
        return self::$vpsClient;
    }

    /**
     * Set domain
     *
     * @param string $domain
     */
    public function setDomain($domain)
    {
        $this->domain = $domain;
    }

    /**
     * Get domain
     *
     * @return null | string domain
     */
    public function getDomain()
    {
        return $this->domain;
    }

     ###
     # Mains methods from OVH Rest API
     ##

    /**
     *  Get VPS properties
     *
     *  @return object
     *
     */
    public function  getProperties()
    {
        return json_decode(self::getClient()->getProperties($this->getDomain()));
    }

    /**
     * Get VPS status
     *
     * @return object
     */
    public function getStatus()
    {
        return json_decode(self::getClient()->getStatus($this->getDomain()));
    }

    /**
     *  Get monitoring
     *
     * @param string $period "lastday" or "lastmonth" or "lastweek" or "lastyear" or "today"
     * @param string $type "cpu:max" or "cpu:used" or "mem:max" or "mem:used" or "net:rx" or "net:tx"
     * @return object
     */
    public function getMonitoring($period, $type)
    {
        return json_decode(self::getClient()->getMonitoring($this->getDomain(), $period, $type));
    }

    /**
     * @param $type
     * @return mixed
     */
    public function getCurrentMonitoring($type)
    {
        return json_decode(self::getClient()->getCurrentMonitoring($this->getDomain(), $type));
    }

    /**
     * Start VPS
     *
     * @return Task
     */
    public function start()
    {
        return new Task(self::getClient()->start($this->getDomain()));
    }

    /**
     * Stop VPS
     *
     * @return Task
     */
    public function stop()
    {
        return new Task(self::getClient()->stop($this->getDomain()));
    }

    /**
     * Reboot VPS
     *
     * @return Task
     */
    public function reboot()
    {
        return new Task(self::getClient()->reboot($this->getDomain()));
    }

    /**
     * @param $password
     * @throws \Ovh\Common\Exception\NotImplementedYetException
     */
    public function setRootPassword($password)
    {
        throw new NotImplementedYetException;
        #$r = self::getClient()->setRootPassword($this->getDomain(), $password);
        #return;
    }

    /**
     * Get availables Upgrades
     *
     * @return array
     */
    public function getAvailableUpgrades()
    {
        return json_decode(self::getClient()->getAvailableUpgrades($this->getDomain()));
    }

    /**
     * Get available options
     *
     * @return array
     */
    public function getAvailableOptions()
    {
        return json_decode(self::getClient()->getAvailableOptions($this->getDomain()));
    }

    /**
     * Get available models
     *
     * @return array
     */
    public function getModels()
    {
        return json_decode(self::getClient()->getModels($this->getDomain()));
    }

    /**
     * @todo : Waiting for OVH  : 500 ftpbackup option is not orderable
     *
     * @return mixed
     */
    public function orderCpanelLicense()
    {
        throw new NotImplementedYetByOvhException;
        return self::getClient()->orderCpanelLicense($this->getDomain());
    }

    /**
     * @todo : Waiting for OVH
     *
     * @param $qte
     * @return mixed
     */
    public function orderPleskLicence($qte)
    {
        throw new NotImplementedYetByOvhException;
        return  self::getClient()->orderPleskLicense($this->getDomain(), $qte);
    }

    /**
     * @todo : Only Cloud model are able to order a snapshot
     * @return mixed
     */
    public function orderFtpBackup()
    {
        throw new NotImplementedYetException;
        return self::getClient()->orderFtpBackup($this->getDomain());
    }

    # Disk methods

    /**
     * Return disks ID
     *
     * @return array  of disk id
     */
    public function getDisks()
    {
        return json_decode(self::getClient()->getDisks($this->getDomain()));

    }

    /**
     * Return disk properties
     *
     * @param $diskId
     * @return object disk (@todo object disk)
     */
    public function getDiskProperties($diskId)
    {
       return json_decode(self::getClient()->getDiskProperties($this->getDomain(), $diskId));
    }

    /**
     * Get disk usage
     *
     * @param $diskId
     * @param $type
     * @return object
     */
    public function getDiskUsage($diskId, $type)
    {
        return json_decode(self::getClient()->getDiskUsage($this->getDomain(), $diskId, $type));
    }

    /**
     * @param $diskId
     * @param $period
     * @param $type
     * @return mixed
     */
    public function getDiskMonitoring($diskId, $period, $type)
    {
        return json_decode(self::getClient()->getDiskMonitoring($this->getDomain(), $diskId, $period, $type));
    }

    #Task
    /**
     * Return tasks associated with this VPS (current and past)
     *
     * @return array of int
     */
    public function getTasks()
    {
        return json_decode(self::getClient()->getTasks($this->getDomain()));
    }

    /**
     * @param $taskId
     * @return Task
     */
    public function getTaskProperties($taskId)
    {
        return new Task(self::getClient()->getTaskProperties($this->getDomain(), $taskId));
    }

    # IP
    /**
     * Get availables IP of this VPS
     *
     * @return array(IPV4,IPV6)
     */
    public function getIps()
    {
        return json_decode(self::getClient()->getIps($this->getDomain()));

    }

    /**
     * @param $ip
     * @return object (@todo object IP)
     */
    public function getIpProperties($ip)
    {
        return json_decode(self::getClient()->getIpProperties($this->getDomain(), $ip));
    }

    /**
     * @todo : error handling & bad reponse (nullNULL)
     * Set IP properties
     * @param string $ip
     * @param array $properties
     * @return mixed
     */
    public function setIpProperties($ip, $properties)
    {
        return json_decode(self::getClient()->setIpProperties($this->getDomain(), $ip, $properties));
    }

    # Snapshots

    /**
     *
     *
     * @return array
     * @throw VpsSnapshotNotExistsException
     */
    public function getSnapshotProperties()
    {
        return  json_decode(self::getClient()->getSnapshotProperties($this->getDomain()));
    }

    /**
     *
     * @todo no snapshot available yet
     * @param array $properties
     * @throws \Ovh\Common\Exception\NotImplementedYetException
     */
    public function setSnapshotProperties(array $properties)
    {
        throw new NotImplementedYetException;
        self::getClient()->setSnapshotProperties($this->getDomain(),$properties);

    }

    /**
     * @todo no snapshot available yet
     * @throws \Ovh\Common\Exception\NotImplementedYetException
     */
    public function deleteSnapshot()
    {
        throw new NotImplementedYetException;
        return self::getClient()->deleteSnapshot($this->getDomain());
    }

    /**
     *  @todo no snapshot available yet
     * @throws \Ovh\Common\Exception\NotImplementedYetException
     */
    public function revertToLastSnapshot()
    {
        throw new NotImplementedYetException;
        return self::getClient()->revertToLastSnapshot($this->getDomain());
    }

    /**
     * @todo need a cloud VPS
     * @return mixed
     * @throws \Ovh\Common\Exception\NotImplementedYetException
     */
    public function orderSnapshot()
    {
        throw new NotImplementedYetException;
        return self::getClient()->orderSnapshot($this->getDomain());
    }

    /**
     * @todo need a cloud
     * @return mixed
     * @throws \Ovh\Common\Exception\NotImplementedYetException
     */
    public function createSnapshot()
    {
        throw new NotImplementedYetException;
        return self::getClient()->createSnapshot($this->getDomain());
    }

    # Templates
    /**
     * Get available template
     *
     * @return array of int
     */
    public function getAvailableTemplates()
    {
        return json_decode(self::getClient()->getAvailableTemplates($this->getDomain()));
    }

    /**
     * @param $templateId
     * @return object template (@todo object template)
     */
    public function getTemplateProperties($templateId)
    {
        return json_decode(self::getClient()->getTemplateProperties($this->getDomain(),$templateId));
    }

    /**
     *
     *
     *  @todo : Sub methods
     *  Ex : getMemoryLimit from getProperties
     *
     *
     *
     */

    public function setIpReverse($ip, $reverse)
    {
        $r = self::getClient()->setIpProperties($this->getDomain(), $ip, $reverse);
        return;
    }

	/**
    * Get Distribution Properties
	* Ajout by @Thibautg16 le 12/06/2014
    *
    * @throws Exception\ServerException
    * @throws \Ovh\Common\Exception\BadMethodCallException
	*
    * @return Object
    */
	public function getDistribution(){
        return json_decode(self::getClient()->getDistribution($this->getDomain()));
    }
}


<?php
/**
 * Copyright 2013 Stéphane Depierrepont (aka Toorop)
 *
 * Authors :
 *  - Stéphane Depierrepont (aka Toorop)
 *  - Florian Jensen (aka flosoft) : https://github.com/flosoft
 *  - Gillardeau Thibaut (aka Thibautg16)
 *  - Scott Brown (aka Slartibardfast)
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 * http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * 2014-06-30 - Slartibardfast - extend for /dedicated/nasha and /ip
 * 2015-05-22 - Thibautg16 - ajout "new" /cloud : http://www.ovh.com/fr/cloud/
 */

namespace Ovh\Common;

use Ovh\Common\AbstractClient;
use Ovh\Common\Exception\BadMethodCallException;

class OvhClient extends AbstractClient {

	/**
	 * Return Dedicated Server list
	 *
	 * @return mixed
	 */
	public function getDedicatedServerList(){
		$request = $this->get('dedicated/server');
		$response=$request->send();
		return $response->getBody(true);
	}

	/**
	 * Return Vrack list
	 *
	 * @return mixed
	 */
	public function getVrackList(){
		return $this->get('vrack')->send()->getBody(true);
	}

    /**
     * Return VPS list
     *
     * @return mixed
     */
    public function getVpsList(){
        $request = $this->get('vps');
        $response=$request->send();
        return $response->getBody(true);
    }

    /**
     * Get XDSL Services
     *
     * @return json encoded string
     */
    public function getXdslServices(){
        return $this->get('xdsl')->send()->getBody(true);
    }

    /**
     * Get SMS Services
     *
     * @return string (json encoded)
     */
    public function getSmsServices(){
        return $this->get('sms')->send()->getBody(true);
    }

    /**
     * Get Telephony Services
     *
     * @return string (json encoded)
     */
    public function getTelephonyServices(){
        return $this->get('telephony')->send()->getBody(true);
    }

    /**
     * Get CDN services
     *
     * @return string (json encoded)
     */
    public function getCdnServices(){
        return $this->get('cdn')->send()->getBody(true);
    }

    /**
     * Get available POP
     * @return string (json econded)
     */
    public function getCdnPops(){
        return $this->get('cdn/pops')->send()->getBody(true);
    }

    /**
     * Get POP details/info
     *
     * @param string $pop : pop name
     * @return string (json encoded)
     * @throws Exception\BadMethodCallException
     */
    public function getCdnPopDetails($pop){
        if (!$pop)
            throw new BadMethodCallException('Parameter $pop is missing.');
        return $this->get('cdn/pops/'.$pop)->send()->getBody(true);
    }

    /**
     * Get Cloud passports
     *
     * @return string passports (json encoded)
     */
    public function getCloudPassports()
    {
       return $this->get('cloud')->send()->getBody(true);
    }

    /**
     * Get Cloud projects
     *
     * @return string projects (json encoded)
     */
    public function getCloudProjects()
    {
       return $this->get('cloud/project')->send()->getBody(true);
    }

	/*
	* Get list of nasha devices
	*
	* returns list of nasha assoc with the account
	*/
	public function getNashaList()
	{
		return $this->get('dedicated/nasha')->send()->getBody(true);
	}

	/*
	 * get list of IPs, subject to restricitons
	 * 1. associated with specific server
	 * 2. a specific IPblock
	 * 3. a specific type of IP.
	 *
	 * arguments are positional, but cumulatie
	 *
	 * returns list of IPs meeting criteria
	*/
	public function getIPsList($serverdomain="", $ipblock="", $type="")
	{
		if ($type!= "") {
			switch ($type) {
				case "cdn":
				case "dedicated":
				case "failover":
				case "hosted_ssl":
				case "loadBalancing":
				case "mail":
				case "pcc":
				case "pci":
				case "private":
				case "vpn":
				case "vps":
				case "vrack":
				case "xdsl":
					break;
				default:
					throw new InvalidArgumentException('Parameter $type is invalid.');
			}
		}

		$qualifier = "";
		if ($serverdomain!="") {
			$qualifier="routedTo.serviceName=$serverdomain";
		}
		if ($ipblock!="") {
			if (isset($qualifier)) {
				$qualifier .= "&";
			}
			$qualifier .= "ip=".urlencode($ipblock);
		}
		if ($type!="")
		{
			if (isset($qualifier)) {
				$qualifier .= "&";
			}
			$qualifier .= "type=$type";
		}
		if ($qualifier != "") {
			$qualifier = "?$qualifier";
		}

		return $this->get("ip$qualifier")->send()->getBody(true);
	}

	/*
	 * GetCpanelList - retrieves list of CPanel licenses
	 *
	 * @return json string[]
	*/
	public function getCpanelList()
	{
		return $this->get('license/cpanel')->send()->getBody(true);
	}

	/*
	 * getPleskList - retrieves list of Plesk licenses
	 *
	 * @return json string[]
	*/
	public function getPleskList()
	{
		return $this->get('license/plesk')->send()->getBody(true);
	}

	/*
	 * getDirectadminList - retrieves list of DirectAdmin licenses
	 *
	 * @return json string[]
	*/
	public function getDirectadminList()
	{
		return $this->get('license/directadmin')->send()->getBody(true);
	}

	/*
	 * getVirtuozzoList - retrieves list of Virtuozzo licenses
	 *
	 * @return json string[]
	*/
	public function getVirtuozzoList()
	{
		return $this->get('license/virtuozzo')->send()->getBody(true);
	}

	/*
	 * GetWindowsList - retrieves list of Windows licenses
	 *
	 * @return json string[]
	*/
	public function getWindowsList()
	{
		return $this->get('license/windows')->send()->getBody(true);
	}

	/*
	 * GetWorklightList - retrieves list of Worklight licenses
	 *
	 * @return json string[]
	*/
	public function GetWorklightList()
	{
		return $this->get('license/worklight')->send()->getBody(true);
	}
}


<?php

declare(strict_types=1);

/*
 * This file is part of the Geocoder package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @license    MIT License
 */

namespace Geocoder\Provider\Geonames;

use Geocoder\Collection;
use Geocoder\Exception\InvalidCredentials;
use Geocoder\Exception\InvalidServerResponse;
use Geocoder\Exception\UnsupportedOperation;
use Geocoder\Model\AddressBuilder;
use Geocoder\Model\AddressCollection;
use Geocoder\Model\AdminLevelCollection;
use Geocoder\Provider\Geonames\Model\CountryInfo;
use Geocoder\Provider\Geonames\Model\GeonamesAddress;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Geocoder\Http\Provider\AbstractHttpProvider;
use Geocoder\Provider\Provider;
use Http\Client\HttpClient;

/**
 * @author Giovanni Pirrotta <giovanni.pirrotta@gmail.com>
 */
final class Geonames extends AbstractHttpProvider implements Provider
{
    /**
     * @var string
     */
    const GEOCODE_ENDPOINT_URL = 'http://api.geonames.org/searchJSON?q=%s&maxRows=%d&style=full&username=%s';

    /**
     * @var string
     */
    const REVERSE_ENDPOINT_URL = 'http://api.geonames.org/findNearbyPlaceNameJSON?lat=%F&lng=%F&style=full&maxRows=%d&username=%s';

    /**
     * @var string
     */
    const BASE_ENDPOINT_URL = 'http://api.geonames.org/%s?username=%s';

    /**
     * @var string
     */
    private $username;

    /**
     * @param HttpClient $client   An HTTP adapter
     * @param string     $username Username login (Free registration at http://www.geonames.org/login)
     */
    public function __construct(HttpClient $client, string $username)
    {
        if (empty($username)) {
            throw new InvalidCredentials('No username provided.');
        }

        $this->username = $username;
        parent::__construct($client);
    }

    /**
     * {@inheritdoc}
     */
    public function geocodeQuery(GeocodeQuery $query): Collection
    {
        $address = $query->getText();

        // This API doesn't handle IPs
        if (filter_var($address, FILTER_VALIDATE_IP)) {
            throw new UnsupportedOperation('The Geonames provider does not support IP addresses.');
        }

        $url = sprintf(self::GEOCODE_ENDPOINT_URL, urlencode($address), $query->getLimit(), $this->username);

        return $this->executeQuery($url, $query->getLocale());
    }

    /**
     * {@inheritdoc}
     */
    public function reverseQuery(ReverseQuery $query): Collection
    {
        $coordinates = $query->getCoordinates();
        $longitude = $coordinates->getLongitude();
        $latitude = $coordinates->getLatitude();

        $url = sprintf(self::REVERSE_ENDPOINT_URL, $latitude, $longitude, $query->getLimit(), $this->username);

        return $this->executeQuery($url, $query->getLocale());
    }

    /**
     * @param string|null $country
     * @param string|null $locale
     *
     * @return array
     *
     * @throws \Geocoder\Exception\Exception
     */
    public function getCountryInfo(string $country = null, string $locale = null): array
    {
        $url = sprintf(self::BASE_ENDPOINT_URL, 'countryInfoJSON', $this->username);

        if (isset($country)) {
            $url = sprintf('%s&country=%s', $url, $country);
        }

        $url = sprintf('%s&style=FULL', $url);

        if (null !== $locale) {
            // Locale code transformation: for example from it_IT to it
            $url = sprintf('%s&lang=%s', $url, substr($locale, 0, 2));
        }

        $content = $this->getUrlContents($url);
        if (null === $json = json_decode($content)) {
            throw InvalidServerResponse::create($url);
        }

        if (!isset($json->geonames)) {
            return [];
        }

        $data = $json->geonames;

        if (empty($data)) {
            return [];
        }

        $results = [];

        foreach ($data as $item) {
            $countryInfo = new CountryInfo();

            $results[] = $countryInfo
                ->setBounds($item->south, $item->west, $item->north, $item->east)
                ->withContinent($item->continent ?? null)
                ->withCapital($item->capital ?? null)
                ->withLanguages($item->langesuages ?? '')
                ->withGeonameId($item->geonameId ?? null)
                ->withIsoAlpha3($item->isoAlpha3 ?? null)
                ->withFipsCode($item->fipsCode ?? null)
                ->withPopulation($item->population ?? null)
                ->withIsoNumeric($item->isoNumeric ?? null)
                ->withAreaInSqKm($item->areaInSqKm ?? null)
                ->withCountryCode($item->countryCode ?? null)
                ->withCountryName($item->countryName ?? null)
                ->withContinentName($item->continentName ?? null)
                ->withCurrencyCode($item->currencyCode ?? null);
        }

        return $results;
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return 'geonames';
    }

    /**
     * @param string      $url
     * @param string|null $locale
     *
     * @return AddressCollection
     */
    private function executeQuery(string $url, string $locale = null): AddressCollection
    {
        if (null !== $locale) {
            // Locale code transformation: for example from it_IT to it
            $url = sprintf('%s&lang=%s', $url, substr($locale, 0, 2));
        }

        $content = $this->getUrlContents($url);
        if (null === $json = json_decode($content)) {
            throw InvalidServerResponse::create($url);
        }

        if (isset($json->totalResultsCount) && empty($json->totalResultsCount)) {
            return new AddressCollection([]);
        }

        $data = $json->geonames;

        if (empty($data)) {
            return new AddressCollection([]);
        }

        $results = [];
        foreach ($data as $item) {
            $builder = new AddressBuilder($this->getName());

            if (isset($item->bbox)) {
                $builder->setBounds($item->bbox->south, $item->bbox->west, $item->bbox->north, $item->bbox->east);
            }

            for ($level = 1; $level <= AdminLevelCollection::MAX_LEVEL_DEPTH; ++$level) {
                $adminNameProp = 'adminName'.$level;
                $adminCodeProp = 'adminCode'.$level;
                if (!empty($item->$adminNameProp)) {
                    $builder->addAdminLevel($level, $item->$adminNameProp, $item->$adminCodeProp ?? null);
                }
            }

            $builder->setCoordinates($item->lat ?? null, $item->lng ?? null);
            $builder->setLocality($item->name ?? null);
            $builder->setCountry($item->countryName ?? null);
            $builder->setCountryCode($item->countryCode ?? null);
            $builder->setTimezone($item->timezone->timeZoneId ?? null);

            /** @var GeonamesAddress $address */
            $address = $builder->build(GeonamesAddress::class);
            $address = $address->withName($item->name ?? null);
            $address = $address->withAsciiName($item->asciiName ?? null);
            $address = $address->withFclName($item->fclName ?? null);
            $address = $address->withAlternateNames($item->alternateNames ?? []);
            $address = $address->withPopulation($item->population ?? null);
            $address = $address->withGeonameId($item->geonameId ?? null);
            $address = $address->withFcode($item->fcode ?? null);

            $results[] = $address;
        }

        return new AddressCollection($results);
    }
}


<?php

declare(strict_types=1);

/*
 * This file is part of the Geocoder package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @license    MIT License
 */

namespace Geocoder\Provider\Geonames\Model;

use Geocoder\Exception\InvalidArgument;
use Geocoder\Model\Bounds;

/**
 * @author Srihari Thalla <thallasrihari@gmail.com>
 */
final class CountryInfo
{
    /**
     * @var Bounds|null
     */
    private $bounds;

    /**
     * @var string|null
     */
    private $continent;

    /**
     * @var string|null
     */
    private $capital;

    /**
     * @var array
     */
    private $languages = [];

    /**
     * @var int|null
     */
    private $geonameId;

    /**
     * @var string|null
     */
    private $isoAlpha3;

    /**
     * @var string|null
     */
    private $fipsCode;

    /**
     * @var int|null
     */
    private $population;

    /**
     * @var int|null
     */
    private $isoNumeric;

    /**
     * @var float|null
     */
    private $areaInSqKm;

    /**
     * @var string|null
     */
    private $countryCode;

    /**
     * @var string|null
     */
    private $countryName;

    /**
     * @var string|null
     */
    private $continentName;

    /**
     * @var string|null
     */
    private $currencyCode;

    /**
     * @return Bounds|null
     */
    public function getBounds()
    {
        return $this->bounds;
    }

    /**
     * @param float $south
     * @param float $west
     * @param float $north
     * @param float $east
     *
     * @return CountryInfo
     */
    public function setBounds(float $south, float $west, float $north, float $east): self
    {
        $new = clone $this;

        try {
            $new->bounds = new Bounds($south, $west, $north, $east);
        } catch (InvalidArgument $e) {
            $new->bounds = null;
        }

        return $new;
    }

    /**
     * @return null|string
     */
    public function getContinent()
    {
        return $this->continent;
    }

    /**
     * @param null|string $continent
     *
     * @return CountryInfo
     */
    public function withContinent(string $continent = null): self
    {
        $new = clone $this;
        $new->continent = $continent;

        return $new;
    }

    /**
     * @return null|string
     */
    public function getCapital()
    {
        return $this->capital;
    }

    /**
     * @param null|string $capital
     *
     * @return CountryInfo
     */
    public function withCapital(string $capital = null): self
    {
        $new = clone $this;
        $new->capital = $capital;

        return $new;
    }

    /**
     * @return array
     */
    public function getLanguages(): array
    {
        return $this->languages;
    }

    /**
     * @param string $languages
     *
     * @return CountryInfo
     */
    public function withLanguages(string $languages = ''): self
    {
        $new = clone $this;
        $new->languages = explode(',', $languages);

        return $new;
    }

    /**
     * @return int|null
     */
    public function getGeonameId()
    {
        return $this->geonameId;
    }

    /**
     * @param int|null $geonameId
     *
     * @return CountryInfo
     */
    public function withGeonameId(int $geonameId = null): self
    {
        $new = clone $this;
        $new->geonameId = null === $geonameId ? null : (int) $geonameId;

        return $new;
    }

    /**
     * @return null|string
     */
    public function getIsoAlpha3()
    {
        return $this->isoAlpha3;
    }

    /**
     * @param null|string $isoAlpha3
     *
     * @return CountryInfo
     */
    public function withIsoAlpha3(string $isoAlpha3 = null): self
    {
        $new = clone $this;
        $new->isoAlpha3 = $isoAlpha3;

        return $new;
    }

    /**
     * @return null|string
     */
    public function getFipsCode()
    {
        return $this->fipsCode;
    }

    /**
     * @param null|string $fipsCode
     *
     * @return CountryInfo
     */
    public function withFipsCode(string $fipsCode = null): self
    {
        $new = clone $this;
        $new->fipsCode = $fipsCode;

        return $new;
    }

    /**
     * @return int|null
     */
    public function getPopulation()
    {
        return $this->population;
    }

    /**
     * @param int|null $population
     *
     * @return CountryInfo
     */
    public function withPopulation(string $population = null): self
    {
        $new = clone $this;
        $new->population = null === $population ? null : (int) $population;

        return $new;
    }

    /**
     * @return null|int
     */
    public function getIsoNumeric()
    {
        return $this->isoNumeric;
    }

    /**
     * @param string|null $isoNumeric
     *
     * @return CountryInfo
     */
    public function withIsoNumeric(string $isoNumeric = null): self
    {
        $new = clone $this;
        $new->isoNumeric = null === $isoNumeric ? null : (int) $isoNumeric;

        return $new;
    }

    /**
     * @return null|float
     */
    public function getAreaInSqKm()
    {
        return $this->areaInSqKm;
    }

    /**
     * @param string|null $areaInSqKm
     *
     * @return CountryInfo
     */
    public function withAreaInSqKm(string $areaInSqKm = null): self
    {
        $new = clone $this;
        $new->areaInSqKm = null === $areaInSqKm ? null : (float) $areaInSqKm;

        return $new;
    }

    /**
     * @return null|string
     */
    public function getCountryCode()
    {
        return $this->countryCode;
    }

    /**
     * @param string|null $countryCode
     *
     * @return CountryInfo
     */
    public function withCountryCode(string $countryCode = null): self
    {
        $new = clone $this;
        $new->countryCode = $countryCode;

        return $new;
    }

    /**
     * @return null|string
     */
    public function getCountryName()
    {
        return $this->countryName;
    }

    /**
     * @param string|null $countryName
     *
     * @return CountryInfo
     */
    public function withCountryName(string $countryName = null): self
    {
        $new = clone $this;
        $new->countryName = $countryName;

        return $new;
    }

    /**
     * @return null|string
     */
    public function getContinentName()
    {
        return $this->continentName;
    }

    /**
     * @param null|string $continentName
     *
     * @return CountryInfo
     */
    public function withContinentName(string $continentName = null): self
    {
        $new = clone $this;
        $new->continentName = $continentName;

        return $new;
    }

    /**
     * @return null|string
     */
    public function getCurrencyCode()
    {
        return $this->currencyCode;
    }

    /**
     * @param null|string $currencyCode
     *
     * @return CountryInfo
     */
    public function withCurrencyCode(string $currencyCode = null): self
    {
        $new = clone $this;
        $new->currencyCode = $currencyCode;

        return $new;
    }
}


<?php
/**
 * Robin NTLM
 *
 * @copyright 2019 Robin Powered, Inc.
 * @link https://robinpowered.com/
 */

declare(strict_types=1);

namespace Robin\Ntlm\Crypt\Hasher;

use HashContext;
use InvalidArgumentException;

/**
 * A cryptographic hasher implemented using PHP's built-in hashing mechanisms as
 * part of the "hash" extension (`ext-hash`).
 *
 * @link http://php.net/manual/en/ref.hash.php
 */
abstract class AbstractHasher implements HasherInterface
{

    /**
     * Constants
     */

    /**
     * The "resource" type of a PHP hash context.
     *
     * @type string
     */

    const HASH_CONTEXT_RESOURCE_TYPE = 'Hash Context';

    /**
     * Properties
     */

    /**
     * The incremental hashing context.
     *
     * @link http://php.net/manual/en/hash.resources.php
     * @type resource|HashContext
     */
    private $context;

    /**
     * Methods
     */

    /**
     * Constructor
     *
     * @param resource|HashContext $context The incremental hashing context.
     */
    protected function __construct($context)
    {
        $this->context = $this->validateHashContext($context);
    }

    /**
     * {@inheritDoc}
     */
    public function update(string $data): HasherInterface
    {
        hash_update($this->context, $data);

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function digest(): string
    {
        // Copy the context so we can keep using the hasher
        $context_copy = hash_copy($this->context);

        // Calculate the digest
        $digest = hash_final($this->context, true);

        // Set our context to the copied one, since the old one is now finalized
        $this->context = $context_copy;

        return $digest;
    }

    /**
     * Validates a given incremental hashing context.
     *
     * @link http://php.net/manual/en/hash.resources.php
     * @param mixed $context The context to validate.
     * @return resource|HashContext The incremental hashing context.
     * @throws InvalidArgumentException If the hash context isn't valid.
     */
    protected function validateHashContext($context)
    {
        if (!($context instanceof HashContext) && (false === $context
            || !is_resource($context)
            || (is_resource($context) && static::HASH_CONTEXT_RESOURCE_TYPE !== get_resource_type($context)))) {
            throw new InvalidArgumentException(
                'Unable to initialize hashing context. Your system might not support the supplied algorithm.'
            );
        }

        return $context;
    }
}


<?php
/**
 * Robin NTLM
 *
 * @copyright 2019 Robin Powered, Inc.
 * @link https://robinpowered.com/
 */

namespace Robin\Ntlm\Crypt\Des;

use InvalidArgumentException;
use Robin\Ntlm\Crypt\CipherMode;
use Robin\Ntlm\Crypt\Exception\CryptographicFailureException;

/**
 * @deprecated Mcrypt has been deprecated from the core PHP library. Use
 * {@see OpenSslDesEncrypter} as an alternative.
 * @link https://php.net/manual/en/migration72.other-changes.php#migration72.other-changes.mcrypt
 *
 * An engine used to encrypt data using the DES standard algorithm and
 * implemented using the PHP "mcrypt" extension.
 *
 * @link http://php.net/mcrypt
 */
class McryptDesEncrypter extends AbstractDesEncrypter implements DesEncrypterInterface
{

    /**
     * Properties
     */

    /**
     * A map of {@link CipherMode}s to the "mcrypt" extension equivalents.
     */
    private static $cipher_mode_map = [
        CipherMode::CBC => MCRYPT_MODE_CBC,
        CipherMode::CFB => MCRYPT_MODE_CFB,
        CipherMode::ECB => MCRYPT_MODE_ECB,
        CipherMode::OFB => MCRYPT_MODE_OFB,
    ];

    /**
     * Methods
     */

    /**
     * {@inheritDoc}
     */
    public function encrypt($key, $data, $mode, $initialization_vector)
    {
        if (isset(self::$cipher_mode_map[$mode])) {
            $mode = self::$cipher_mode_map[$mode];
        } else {
            throw new InvalidArgumentException('Unknown cipher mode "'. $mode .'"');
        }

        $key = $this->processKey($key);

        $encrypted = mcrypt_encrypt(MCRYPT_DES, $key, $data, $mode, $initialization_vector);

        if (false === $encrypted) {
            throw CryptographicFailureException::forReasonCode(
                CryptographicFailureException::CODE_FOR_ENCRYPTION_FAILURE
            );
        }

        return $encrypted;
    }
}