hello 404 Not Found
Al-HUWAITI Shell
Al-huwaiti


Server : Apache
System : Linux webm006.cluster103.gra.hosting.ovh.net 6.18.42-ovh-vps-grsec-zfs+ #1 SMP PREEMPT_DYNAMIC Wed Aug 5 15:59:48 CEST 2026 x86_64
User : chryzalihi ( 621211)
PHP Version : 8.3.31
Disable Function : _dyuweyrj4,_dyuweyrj4r,dl
Directory :  /home/chryzalihi/www/wp-content/languages/themes/the/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/chryzalihi/www/wp-content/languages/themes/the/Common.tar
.htaccess000044400000000424152440043010006331 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>ServiceException.php000060400000004476152440043010010534 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common;
use WindowsAzure\Common\Internal\Resources;

/**
 * Fires when the response code is incorrect.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ServiceException extends \LogicException
{
    private $_error;
    private $_reason;
    
    /**
     * Constructor
     *
     * @param string $errorCode status error code.
     * @param string $error     string value of the error code.
     * @param string $reason    detailed message for the error.
     * 
     * @return WindowsAzure\Common\ServiceException
     */
    public function __construct($errorCode, $error = null, $reason = null)
    {
        parent::__construct(
            sprintf(Resources::AZURE_ERROR_MSG, $errorCode, $error, $reason)
        );
        $this->code    = $errorCode;
        $this->_error  = $error;
        $this->_reason = $reason;
    }
    
    /**
     * Gets error text.
     *
     * @return string
     */
    public function getErrorText()
    {
        return $this->_error;
    }
    
    /**
     * Gets detailed error reason.
     *
     * @return string
     */
    public function getErrorReason()
    {
        return $this->_reason;
    }
}


CloudConfigurationManager.php000060400000011526152440043010012340 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\ConnectionStringSource;

/**
 * Configuration manager for accessing Windows Azure settings.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class CloudConfigurationManager
{
    /**
     * @var boolean
     */
    private static $_isInitialized = false;
    
    /**
     * The list of connection string sources.
     * 
     * @var array
     */
    private static $_sources;
    
    /**
     * Restrict users from creating instances from this class
     */
    private function __construct()
    {
        
    }
    
    /**
     * Initializes the connection string source providers.
     * 
     * @return none 
     */
    private static function _init()
    {
        if (!self::$_isInitialized) {
            self::$_sources = array();
            
            // Get list of default connection string sources.
            $default = ConnectionStringSource::getDefaultSources();
            foreach ($default as $name => $provider) {
                self::$_sources[$name] = $provider;
            }
            
            self::$_isInitialized = true;
        }
    }
    
    /**
     * Gets a connection string from all available sources.
     * 
     * @param string $key The connection string key name.
     * 
     * @return string If the key does not exist return null.
     */
    public static function getConnectionString($key)
    {
        Validate::isString($key, 'key');
        
        self::_init();
        $value = null;
        
        foreach (self::$_sources as $source) {
            $value = call_user_func_array($source, array($key));
            
            if (!empty($value)) {
                break;
            }
        }
        
        return $value;
    }
    
    /**
     * Registers a new connection string source provider. If the source to get 
     * registered is a default source, only the name of the source is required.
     * 
     * @param string   $name     The source name.
     * @param callable $provider The source callback.
     * @param boolean  $prepend  When true, the $provider is processed first when 
     * calling getConnectionString. When false (the default) the $provider is 
     * processed after the existing callbacks.
     * 
     * @return none
     */
    public static function registerSource($name, $provider = null, $prepend = false)
    {
        Validate::isString($name, 'name');
        Validate::notNullOrEmpty($name, 'name');
        
        self::_init();
        $default = ConnectionStringSource::getDefaultSources();
        
        // Try to get callback if the user is trying to register a default source.
        $provider = Utilities::tryGetValue($default, $name, $provider);
        
        Validate::notNullOrEmpty($provider, 'callback');
        
        if ($prepend) {
            self::$_sources = array_merge(
                array($name => $provider),
                self::$_sources
            );
            
        } else {
            self::$_sources[$name] = $provider;
        }
    }
    
    /**
     * Unregisters a connection string source.
     * 
     * @param string $name The source name.
     * 
     * @return callable
     */
    public static function unregisterSource($name)
    {
        Validate::isString($name, 'name');
        Validate::notNullOrEmpty($name, 'name');
        
        self::_init();
        
        $sourceCallback = Utilities::tryGetValue(self::$_sources, $name);
        
        if (!is_null($sourceCallback)) {
            unset(self::$_sources[$name]);
        }
        
        return $sourceCallback;
    }
}Internal/Utilities.php000060400000047751152440043010011007 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal;

/**
 * Utilities for the project
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class Utilities
{
    /**
     * Returns the specified value of the $key passed from $array and in case that
     * this $key doesn't exist, the default value is returned.
     *
     * @param array $array   The array to be used.
     * @param mix   $key     The array key.
     * @param mix   $default The value to return if $key is not found in $array.
     *
     * @static
     *
     * @return mix
     */
    public static function tryGetValue($array, $key, $default = null)
    {
        return is_array($array) && array_key_exists($key, $array)
            ? $array[$key]
            : $default;
    }

    /**
     * Adds a url scheme if there is no scheme.
     *
     * @param string $url    The URL.
     * @param string $scheme The scheme. By default HTTP
     *
     * @static
     *
     * @return string
     */
    public static function tryAddUrlScheme($url, $scheme = 'http')
    {
        $urlScheme = parse_url($url, PHP_URL_SCHEME);

        if (empty($urlScheme)) {
            $url = "$scheme://" . $url;
        }

        return $url;
    }

    /**
     * tries to get nested array with index name $key from $array.
     *
     * Returns empty array object if the value is NULL.
     *
     * @param string $key   The index name.
     * @param array  $array The array object.
     *
     * @static
     *
     * @return array
     */
    public static function tryGetArray($key, $array)
    {
        return Utilities::getArray(Utilities::tryGetValue($array, $key));
    }

    /**
     * Adds the given key/value pair into array if the value doesn't satisfy empty().
     *
     * This function just validates that the given $array is actually array. If it's
     * NULL the function treats it as array.
     *
     * @param string $key    The key.
     * @param string $value  The value.
     * @param array  &$array The array. If NULL will be used as array.
     *
     * @static
     *
     * @return none
     */
    public static function addIfNotEmpty($key, $value, &$array)
    {
        if (!is_null($array)) {
            Validate::isArray($array, 'array');
        }

        if (!empty($value)) {
            $array[$key] = $value;
        }
    }

    /**
     * Returns the specified value of the key chain passed from $array and in case
     * that key chain doesn't exist, null is returned.
     *
     * @param array $array Array to be used.
     *
     * @static
     *
     * @return mix
     */
    public static function tryGetKeysChainValue($array)
    {
        $arguments    = func_get_args();
        $numArguments = func_num_args();

        $currentArray = $array;
        for ($i = 1; $i < $numArguments; $i++) {
            if (is_array($currentArray)) {
                if (array_key_exists($arguments[$i], $currentArray)) {
                    $currentArray = $currentArray[$arguments[$i]];
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }

        return $currentArray;
    }

    /**
     * Checks if the passed $string starts with $prefix
     *
     * @param string  $string     word to seaech in
     * @param string  $prefix     prefix to be matched
     * @param boolean $ignoreCase true to ignore case during the comparison;
     * otherwise, false
     *
     * @static
     *
     * @return boolean
     */
    public static function startsWith($string, $prefix, $ignoreCase = false)
    {
        if ($ignoreCase) {
            $string = strtolower($string);
            $prefix = strtolower($prefix);
        }
        return ($prefix == substr($string, 0, strlen($prefix)));
    }

    /**
     * Returns grouped items from passed $var
     *
     * @param array $var item to group
     *
     * @static
     *
     * @return array
     */
    public static function getArray($var)
    {
        if (is_null($var) || empty($var)) {
            return array();
        }

        foreach ($var as $value) {
            if ((gettype($value) == 'object')
                && (get_class($value) == 'SimpleXMLElement')
            ) {
                return (array) $var;
            } else if (!is_array($value)) {
                return array($var);
            }

        }

        return $var;
    }

    /**
     * Unserializes the passed $xml into array.
     *
     * @param string $xml XML to be parsed.
     *
     * @static
     *
     * @return array
     */
    public static function unserialize($xml)
    {
        $sxml = new \SimpleXMLElement($xml);

        return self::_sxml2arr($sxml);
    }

    /**
     * Converts a SimpleXML object to an Array recursively
     * ensuring all sub-elements are arrays as well.
     *
     * @param string $sxml SimpleXML object
     * @param array  $arr  Array into which to store results
     *
     * @static
     *
     * @return array
     */
    private static function _sxml2arr($sxml, $arr = null)
    {
        foreach ((array) $sxml as $key => $value) {
            if (is_object($value) || (is_array($value))) {
                $arr[$key] = self::_sxml2arr($value);
            } else {
                $arr[$key] = $value;
            }
        }

        return $arr;
    }

    /**
     * Serializes given array into xml. The array indices must be string to use
     * them as XML tags.
     *
     * @param array  $array      object to serialize represented in array.
     * @param string $rootName   name of the XML root element.
     * @param string $defaultTag default tag for non-tagged elements.
     * @param string $standalone adds 'standalone' header tag, values 'yes'/'no'
     *
     * @static
     *
     * @return string
     */
    public static function serialize($array, $rootName, $defaultTag = null,
        $standalone = null
    ) {
        $xmlVersion  = '1.0';
        $xmlEncoding = 'UTF-8';

        if (!is_array($array)) {
            return false;
        }

        $xmlw = new \XmlWriter();
        $xmlw->openMemory();
        $xmlw->startDocument($xmlVersion, $xmlEncoding, $standalone);

        $xmlw->startElement($rootName);

        self::_arr2xml($xmlw, $array, $defaultTag);

        $xmlw->endElement();

        return $xmlw->outputMemory(true);
    }

    /**
     * Takes an array and produces XML based on it.
     *
     * @param XMLWriter $xmlw       XMLWriter object that was previously instanted
     * and is used for creating the XML.
     * @param array     $data       Array to be converted to XML
     * @param string    $defaultTag Default XML tag to be used if none specified.
     *
     * @static
     *
     * @return void
     */
    private static function _arr2xml(\XMLWriter $xmlw, $data, $defaultTag = null)
    {
        foreach ($data as $key => $value) {
            if (strcmp($key, '@attributes') == 0) {
                foreach ($value as $attributeName => $attributeValue) {
                    $xmlw->writeAttribute($attributeName, $attributeValue);
                }
            } else if (is_array($value)) {
                if (!is_int($key)) {
                    if ($key != Resources::EMPTY_STRING) {
                        $xmlw->startElement($key);
                    } else {
                        $xmlw->startElement($defaultTag);
                    }
                }

                self::_arr2xml($xmlw, $value);

                if (!is_int($key)) {
                    $xmlw->endElement();
                }
                continue;
            } else {
                $xmlw->writeElement($key, $value);
            }
        }
    }

    /**
     * Converts string into boolean value.
     *
     * @param string $obj boolean value in string format.
     *
     * @static
     *
     * @return bool
     */
    public static function toBoolean($obj)
    {
        return filter_var($obj, FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * Converts string into boolean value.
     *
     * @param bool $obj boolean value to convert.
     *
     * @static
     *
     * @return string
     */
    public static function booleanToString($obj)
    {
        return $obj ? 'true' : 'false';
    }

    /**
     * Converts a given date string into \DateTime object
     *
     * @param string $date windows azure date ins string represntation.
     *
     * @static
     *
     * @return \DateTime
     */
    public static function rfc1123ToDateTime($date)
    {
        $timeZone = new \DateTimeZone('GMT');
        $format   = Resources::AZURE_DATE_FORMAT;

        return \DateTime::createFromFormat($format, $date, $timeZone);
    }

    /**
     * Generate ISO 8601 compliant date string in UTC time zone
     *
     * @param int $timestamp The unix timestamp to convert
     *     (for DateTime check date_timestamp_get).
     *
     * @static
     *
     * @return string
     */
    public static function isoDate($timestamp = null)
    {
        $tz = date_default_timezone_get();
        date_default_timezone_set('UTC');

        if (is_null($timestamp)) {
            $timestamp = time();
        }

        $returnValue = str_replace(
            '+00:00', '.0000000Z', date('c', $timestamp)
        );
        date_default_timezone_set($tz);
        return $returnValue;
    }

    /**
     * Converts a DateTime object into an Edm.DaeTime value in UTC timezone,
     * represented as a string.
     *
     * @param \DateTime $value The datetime value.
     *
     * @static
     *
     * @return string
     */
    public static function convertToEdmDateTime($value)
    {
        if (empty($value)) {
            return $value;
        }

        if (is_string($value)) {
            $value =  self::convertToDateTime($value);
        }

        Validate::isDate($value);

        $cloned = clone $value;
        $cloned->setTimezone(new \DateTimeZone('UTC'));
        return str_replace('+0000', 'Z', $cloned->format(\DateTime::ISO8601));
    }

    /**
     * Converts a string to a \DateTime object. Returns false on failure.
     *
     * @param string $value The string value to parse.
     *
     * @static
     *
     * @return \DateTime
     */
    public static function convertToDateTime($value)
    {
        if ($value instanceof \DateTime) {
            return $value;
        }

        if (substr($value, -1) == 'Z') {
            $value = substr($value, 0, strlen($value) - 1);
        }

        return new \DateTime($value, new \DateTimeZone('UTC'));
    }

    /**
     * Converts string to stream handle.
     *
     * @param type $string The string contents.
     *
     * @static
     *
     * @return resource
     */
    public static function stringToStream($string)
    {
        return fopen('data://text/plain,' . urlencode($string), 'rb');
    }

    /**
     * Sorts an array based on given keys order.
     *
     * @param array $array The array to sort.
     * @param array $order The keys order array.
     *
     * @return array
     */
    public static function orderArray($array, $order)
    {
        $ordered = array();

        foreach ($order as $key) {
            if (array_key_exists($key, $array)) {
                $ordered[$key] = $array[$key];
            }
        }

        return $ordered;
    }

    /**
     * Checks if a value exists in an array. The comparison is done in a case
     * insensitive manner.
     *
     * @param string $needle   The searched value.
     * @param array  $haystack The array.
     *
     * @static
     *
     * @return boolean
     */
    public static function inArrayInsensitive($needle, $haystack)
    {
        return in_array(strtolower($needle), array_map('strtolower', $haystack));
    }

    /**
     * Checks if the given key exists in the array. The comparison is done in a case
     * insensitive manner.
     *
     * @param string $key    The value to check.
     * @param array  $search The array with keys to check.
     *
     * @static
     *
     * @return boolean
     */
    public static function arrayKeyExistsInsensitive($key, $search)
    {
        return array_key_exists(strtolower($key), array_change_key_case($search));
    }

    /**
     * Returns the specified value of the $key passed from $array and in case that
     * this $key doesn't exist, the default value is returned. The key matching is
     * done in a case insensitive manner.
     *
     * @param string $key      The array key.
     * @param array  $haystack The array to be used.
     * @param mix    $default  The value to return if $key is not found in $array.
     *
     * @static
     *
     * @return mix
     */
    public static function tryGetValueInsensitive($key, $haystack, $default = null)
    {
        $array = array_change_key_case($haystack);
        return Utilities::tryGetValue($array, strtolower($key), $default);
    }

    /**
     * Returns a string representation of a version 4 GUID, which uses random
     * numbers.There are 6 reserved bits, and the GUIDs have this format:
     *     xxxxxxxx-xxxx-4xxx-[8|9|a|b]xxx-xxxxxxxxxxxx
     * where 'x' is a hexadecimal digit, 0-9a-f.
     *
     * See http://tools.ietf.org/html/rfc4122 for more information.
     *
     * Note: This function is available on all platforms, while the
     * com_create_guid() is only available for Windows.
     *
     * @static
     *
     * @return string A new GUID.
     */
    public static function getGuid()
    {
        // @codingStandardsIgnoreStart

        return sprintf(
            '%04x%04x-%04x-%04x-%02x%02x-%04x%04x%04x',
            mt_rand(0, 65535),
            mt_rand(0, 65535),          // 32 bits for "time_low"
            mt_rand(0, 65535),          // 16 bits for "time_mid"
            mt_rand(0, 4096) + 16384,   // 16 bits for "time_hi_and_version", with
                                        // the most significant 4 bits being 0100
                                        // to indicate randomly generated version
            mt_rand(0, 64) + 128,       // 8 bits  for "clock_seq_hi", with
                                        // the most significant 2 bits being 10,
                                        // required by version 4 GUIDs.
            mt_rand(0, 256),            // 8 bits  for "clock_seq_low"
            mt_rand(0, 65535),          // 16 bits for "node 0" and "node 1"
            mt_rand(0, 65535),          // 16 bits for "node 2" and "node 3"
            mt_rand(0, 65535)           // 16 bits for "node 4" and "node 5"
        );

        // @codingStandardsIgnoreEnd
    }

    /**
     * Creates a list of objects of type $class from the provided array using static
     * create method.
     *
     * @param array  $parsed The object in array representation
     * @param string $class  The class name. Must have static method create.
     *
     * @static
     *
     * @return array
     */
    public static function createInstanceList($parsed, $class)
    {
        $list = array();

        foreach ($parsed as $value) {
            $list[] = $class::create($value);
        }

        return $list;
    }

    /**
     * Takes a string and return if it ends with the specified character/string.
     *
     * @param string  $haystack   The string to search in.
     * @param string  $needle     postfix to match.
     * @param boolean $ignoreCase Set true to ignore case during the comparison;
     * otherwise, false
     *
     * @static
     *
     * @return boolean
     */
    public static function endsWith($haystack, $needle, $ignoreCase = false)
    {
        if ($ignoreCase) {
            $haystack = strtolower($haystack);
            $needle   = strtolower($needle);
        }
        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }

        return (substr($haystack, -$length) === $needle);
    }

    /**
     * Get id from entity object or string.
     * If entity is object than validate type and return $entity->$method()
     * If entity is string than return this string
     *
     * @param object|string $entity Entity with id property
     * @param string        $type   Entity type to validate
     * @param string        $method Methods that gets id (getId by default)
     *
     * @return string
     */
    public static function getEntityId($entity, $type, $method = 'getId')
    {
        if (is_string($entity)) {
            return $entity;
        } else {
            Validate::isA($entity, $type, 'entity');
            Validate::methodExists($entity, $method, $type);

            return $entity->$method();
        }
    }

    /**
     * Generate a pseudo-random string of bytes using a cryptographically strong 
     * algorithm.
     *
     * @param int $length Length of the string in bytes
     *
     * @return string|boolean Generated string of bytes on success, or FALSE on 
     *                        failure.
     */
    public static function generateCryptoKey($length)
    {
        return openssl_random_pseudo_bytes($length);
    }
    
    
    /**
     * Encrypts $data with CTR encryption
     * 
     * @param string $data                 Data to be encrypted
     * @param string $key                  AES Encryption key
     * @param string $initializationVector Initialization vector
     * 
     * @return string Encrypted data
     */
    public static function ctrCrypt($data, $key, $initializationVector) 
    {
        Validate::isString($data, 'data');
        Validate::isString($key, 'key');
        Validate::isString($initializationVector, 'initializationVector');
        
        Validate::isTrue(
            (strlen($key) == 16 || strlen($key) == 24 || strlen($key) == 32), 
            sprintf(Resources::INVALID_STRING_LENGTH, 'key', '16, 24, 32')
        );
        
        Validate::isTrue(
            (strlen($initializationVector) == 16), 
            sprintf(Resources::INVALID_STRING_LENGTH, 'initializationVector', '16')
        );
        
        $blockCount = ceil(strlen($data) / 16);
    
        $ctrData = '';
        for ($i = 0; $i < $blockCount; ++$i) {
            $ctrData .= $initializationVector;
    
            // increment Initialization Vector
            $j = 15;
            do {
                $digit                    = ord($initializationVector[$j]) + 1;
                $initializationVector[$j] = chr($digit & 0xFF);
                
                $j--;
            } while (($digit == 0x100) && ($j >= 0));
        }
    
        $encryptCtrData = mcrypt_encrypt(
            MCRYPT_RIJNDAEL_128, 
            $key, 
            $ctrData, 
            MCRYPT_MODE_ECB
        );
        
        return $data ^ $encryptCtrData;
    }
    
    /**
     * Convert base 256 number to decimal number. 
     * 
     * @param string $number Base 256 number
     * 
     * @return string Decimal number
     */
    public static function base256ToDec($number) 
    {
        Validate::isString($number, 'number');
        
        $result = 0;
        $base   = 1;
        for ($i = strlen($number) - 1; $i >= 0; $i--) {
            $result = bcadd($result, bcmul(ord($number[$i]), $base));
            $base   = bcmul($base, 256);
        }
    
        return $result;
    }

}
Internal/InvalidArgumentTypeException.php000060400000003617152440043010014637 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;

/**
 * Exception thrown if an argument type does not match with the expected type. 
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class InvalidArgumentTypeException extends \InvalidArgumentException
{
    /**
     * Constructor.
     *
     * @param string $validType The valid type that should be provided by the user.
     * @param string $name      The parameter name.
     * 
     * @return WindowsAzure\Common\Internal\InvalidArgumentTypeException
     */
    public function __construct($validType, $name = null)
    {
        parent::__construct(
            sprintf(Resources::INVALID_PARAM_MSG, $name, $validType)
        );
    }
}


Internal/RestProxy.php000060400000013605152440043010011002 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Http\Url;

/**
 * Base class for all REST proxies.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class RestProxy
{
    /**
     * @var WindowsAzure\Common\Internal\Http\IHttpClient
     */
    private $_channel;
    
    /**
     * @var array
     */
    private $_filters;
    
    /**
     * @var WindowsAzure\Common\Internal\Serialization\ISerializer
     */
    protected $dataSerializer;
    
    /**
     * @var string
     */
    private $_uri;
    
    /**
     * Initializes new RestProxy object.
     *
     * @param IHttpClient $channel        The HTTP client used to send HTTP requests.
     * @param ISerializer $dataSerializer The data serializer.
     * @param string      $uri            The uri of the service.
     */
    public function __construct($channel, $dataSerializer, $uri)
    {
        $this->_channel       = $channel;
        $this->_filters       = array();
        $this->dataSerializer = $dataSerializer;
        $this->_uri           = $uri;
    }
    
    /**
     * Gets HTTP filters that will process each request.
     * 
     * @return array
     */
    public function getFilters()
    {
        return $this->_filters;
    }

    /**
     * Gets the Uri of the service.
     * 
     * @return string
     */
    public function getUri()
    {
        return $this->_uri;
    }

    /** 
     * Sets the Uri of the service. 
     *
     * @param string $uri The URI of the request.
     * 
     * @return none
     */
    public function setUri($uri)
    {
        $this->_uri = $uri;
    }
    
    /**
     * Sends HTTP request with the specified HTTP call context.
     * 
     * @param WindowsAzure\Common\Internal\Http\HttpCallContext $context The HTTP 
     * call context.
     * 
     * @return \HTTP_Request2_Response
     */
    protected function sendContext($context)
    {
        $channel        = clone $this->_channel;
        $contextUrl     = $context->getUri();
        $url            = new Url(empty($contextUrl) ? $this->_uri : $contextUrl);
        $headers        = $context->getHeaders();
        $statusCodes    = $context->getStatusCodes();
        $body           = $context->getBody();
        $queryParams    = $context->getQueryParameters();
        $postParameters = $context->getPostParameters();
        $path           = $context->getPath();

        $channel->setMethod($context->getMethod());
        $channel->setExpectedStatusCode($statusCodes);
        $channel->setBody($body);
        $channel->setHeaders($headers);

        if (count($postParameters) > 0) {
            $channel->setPostParameters($postParameters);
        }
        $url->setQueryVariables($queryParams);
        $url->appendUrlPath($path);
        
        $channel->send($this->_filters, $url);
        
        return $channel->getResponse();
    }

    /**
     * Adds new filter to new service rest proxy object and returns that object back.
     *
     * @param WindowsAzure\Common\Internal\IServiceFilter $filter Filter to add for 
     * the pipeline.
     * 
     * @return RestProxy.
     */
    public function withFilter($filter)
    {
        $serviceProxyWithFilter             = clone $this;
        $serviceProxyWithFilter->_filters[] = $filter;

        return $serviceProxyWithFilter;
    }
    
    /**
     * Adds optional query parameter.
     * 
     * Doesn't add the value if it satisfies empty().
     * 
     * @param array  &$queryParameters The query parameters.
     * @param string $key              The query variable name.
     * @param string $value            The query variable value.
     * 
     * @return none
     */
    protected function addOptionalQueryParam(&$queryParameters, $key, $value)
    {
        Validate::isArray($queryParameters, 'queryParameters');
        Validate::isString($key, 'key');
        Validate::isString($value, 'value');
                
        if (!is_null($value) && Resources::EMPTY_STRING !== $value) {
            $queryParameters[$key] = $value;
        }
    }
    
    /**
     * Adds optional header.
     * 
     * Doesn't add the value if it satisfies empty().
     * 
     * @param array  &$headers The HTTP header parameters.
     * @param string $key      The HTTP header name.
     * @param string $value    The HTTP header value.
     * 
     * @return none
     */
    protected function addOptionalHeader(&$headers, $key, $value)
    {
        Validate::isArray($headers, 'headers');
        Validate::isString($key, 'key');
        Validate::isString($value, 'value');
                
        if (!is_null($value) && Resources::EMPTY_STRING !== $value) {
            $headers[$key] = $value;
        }
    }
}


Internal/.htaccess000044400000000424152440043010010105 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Internal/Resources.php000060400000060676152440043010011007 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal;

/**
 * Project resources.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class Resources
{
    // @codingStandardsIgnoreStart

    // Connection strings
    const USE_DEVELOPMENT_STORAGE_NAME = 'UseDevelopmentStorage';
    const DEVELOPMENT_STORAGE_PROXY_URI_NAME = 'DevelopmentStorageProxyUri';
    const DEFAULT_ENDPOINTS_PROTOCOL_NAME = 'DefaultEndpointsProtocol';
    const ACCOUNT_NAME_NAME = 'AccountName';
    const ACCOUNT_KEY_NAME = 'AccountKey';
    const BLOB_ENDPOINT_NAME = 'BlobEndpoint';
    const QUEUE_ENDPOINT_NAME = 'QueueEndpoint';
    const TABLE_ENDPOINT_NAME = 'TableEndpoint';
    const SHARED_ACCESS_SIGNATURE_NAME = 'SharedAccessSignature';
    const DEV_STORE_NAME = 'devstoreaccount1';
    const DEV_STORE_KEY = 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==';
    const BLOB_BASE_DNS_NAME = 'blob.core.windows.net';
    const QUEUE_BASE_DNS_NAME = 'queue.core.windows.net';
    const TABLE_BASE_DNS_NAME = 'table.core.windows.net';
    const DEV_STORE_CONNECTION_STRING = 'BlobEndpoint=127.0.0.1:10000;QueueEndpoint=127.0.0.1:10001;TableEndpoint=127.0.0.1:10002;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==';
    const SUBSCRIPTION_ID_NAME = 'SubscriptionID';
    const CERTIFICATE_PATH_NAME = 'CertificatePath';
    const SERVICE_MANAGEMENT_ENDPOINT_NAME = 'ServiceManagementEndpoint';
    const SERVICE_BUS_ENDPOINT_NAME = 'Endpoint';
    const SHARED_SECRET_ISSUER_NAME = 'SharedSecretIssuer';
    const SHARED_SECRET_VALUE_NAME = 'SharedSecretValue';
    const STS_ENDPOINT_NAME = 'StsEndpoint';
    const MEDIA_SERVICES_ENDPOINT_URI_NAME = 'MediaServicesEndpoint';
    const MEDIA_SERVICES_ACCOUNT_NAME = 'AccountName';
    const MEDIA_SERVICES_ACCESS_KEY = 'AccessKey';
    const MEDIA_SERVICES_OAUTH_ENDPOINT_URI_NAME = 'OAuthEndpoint';

    // Messages
    const INVALID_TYPE_MSG = 'The provided variable should be of type: ';
    const INVALID_META_MSG = 'Metadata cannot contain newline characters.';
    const AZURE_ERROR_MSG = "Fail:\nCode: %s\nValue: %s\ndetails (if any): %s.";
    const NOT_IMPLEMENTED_MSG = 'This method is not implemented.';
    const NULL_OR_EMPTY_MSG = "'%s' can't be NULL or empty.";
    const NULL_MSG = "'%s' can't be NULL.";
    const INVALID_URL_MSG = 'Provided URL is invalid.';
    const INVALID_HT_MSG = 'The header type provided is invalid.';
    const INVALID_EDM_MSG = 'The provided EDM type is invalid.';
    const INVALID_PROP_MSG = 'One of the provided properties is not an instance of class Property';
    const INVALID_ENTITY_MSG = 'The provided entity object is invalid.';
    const INVALID_VERSION_MSG = 'Server does not support any known protocol versions.';
    const INVALID_BO_TYPE_MSG = 'Batch operation name is not supported or invalid.';
    const INVALID_BO_PN_MSG = 'Batch operation parameter is not supported.';
    const INVALID_OC_COUNT_MSG = 'Operations and contexts must be of same size.';
    const INVALID_EXC_OBJ_MSG = 'Exception object type should be ServiceException.';
    const NULL_TABLE_KEY_MSG = 'Partition and row keys can\'t be NULL.';
    const BATCH_ENTITY_DEL_MSG = 'The entity was deleted successfully.';
    const INVALID_PROP_VAL_MSG = "'%s' property value must satisfy %s.";
    const INVALID_PARAM_MSG = "The provided variable '%s' should be of type '%s'";
    const INVALID_STRING_LENGTH = "The provided variable '%s' should be of %s characters long";
    const INVALID_BTE_MSG = "The blob block type must exist in %s";
    const INVALID_BLOB_PAT_MSG = 'The provided access type is invalid.';
    const INVALID_SVC_PROP_MSG = 'The provided service properties is invalid.';
    const UNKNOWN_SRILZER_MSG = 'The provided serializer type is unknown';
    const INVALID_CREATE_SERVICE_OPTIONS_MSG = 'Must provide valid location or affinity group.';
    const INVALID_UPDATE_SERVICE_OPTIONS_MSG = 'Must provide either description or label.';
    const INVALID_CONFIG_MSG = 'Config object must be of type Configuration';
    const INVALID_ACH_MSG = 'The provided access condition header is invalid';
    const INVALID_RECEIVE_MODE_MSG = 'The receive message option is in neither RECEIVE_AND_DELETE nor PEEK_LOCK mode.';
    const INVALID_CONFIG_URI = "The provided URI '%s' is invalid. It has to pass the check 'filter_var(<user_uri>, FILTER_VALIDATE_URL)'.";
    const INVALID_CONFIG_VALUE = "The provided config value '%s' does not belong to the valid values subset:\n%s";
    const INVALID_ACCOUNT_KEY_FORMAT = "The provided account key '%s' is not a valid base64 string. It has to pass the check 'base64_decode(<user_account_key>, true)'.";
    const MISSING_CONNECTION_STRING_SETTINGS = "The provided connection string '%s' does not have complete configuration settings.";
    const INVALID_CONNECTION_STRING_SETTING_KEY = "The setting key '%s' is not found in the expected configuration setting keys:\n%s";
    const INVALID_CERTIFICATE_PATH = "The provided certificate path '%s' is invalid.";
    const INSTANCE_TYPE_VALIDATION_MSG = 'The type of %s is %s but is expected to be %s.';
    const MISSING_CONNECTION_STRING_CHAR = "Missing %s character";
    const ERROR_PARSING_STRING = "'%s' at position %d.";
    const INVALID_CONNECTION_STRING = "Argument '%s' is not a valid connection string: '%s'";
    const ERROR_CONNECTION_STRING_MISSING_KEY = 'Missing key name';
    const ERROR_CONNECTION_STRING_EMPTY_KEY = 'Empty key name';
    const ERROR_CONNECTION_STRING_MISSING_CHARACTER = "Missing %s character";
    const ERROR_EMPTY_SETTINGS = 'No keys were found in the connection string';
    const MISSING_LOCK_LOCATION_MSG = 'The lock location of the brokered message is missing.';
    const INVALID_SLOT = "The provided deployment slot '%s' is not valid. Only 'staging' and 'production' are accepted.";
    const INVALID_DEPLOYMENT_LOCATOR_MSG = 'A slot or deployment name must be provided.';
    const INVALID_CHANGE_MODE_MSG = "The change mode must be 'Auto' or 'Manual'. Use Mode class constants for that purpose.";
    const INVALID_DEPLOYMENT_STATUS_MSG = "The change mode must be 'Running' or 'Suspended'. Use DeploymentStatus class constants for that purpose.";
    const ERROR_OAUTH_GET_ACCESS_TOKEN = 'Unable to get oauth access token for endpoint \'%s\', account name \'%s\'';
    const ERROR_OAUTH_SERVICE_MISSING = 'OAuth service missing for account name \'%s\'';
    const ERROR_METHOD_NOT_FOUND = 'Method \'%s\' not found in object class \'%s\'';
    const ERROR_INVALID_DATE_STRING = 'Parameter \'%s\' is not a date formatted string \'%s\'';

    // HTTP Headers
    const X_MS_HEADER_PREFIX                 = 'x-ms-';
    const X_MS_META_HEADER_PREFIX            = 'x-ms-meta-';
    const X_MS_APPROXIMATE_MESSAGES_COUNT    = 'x-ms-approximate-messages-count';
    const X_MS_POPRECEIPT                    = 'x-ms-popreceipt';
    const X_MS_TIME_NEXT_VISIBLE             = 'x-ms-time-next-visible';
    const X_MS_BLOB_PUBLIC_ACCESS            = 'x-ms-blob-public-access';
    const X_MS_VERSION                       = 'x-ms-version';
    const X_MS_DATE                          = 'x-ms-date';
    const X_MS_BLOB_SEQUENCE_NUMBER          = 'x-ms-blob-sequence-number';
    const X_MS_BLOB_SEQUENCE_NUMBER_ACTION   = 'x-ms-sequence-number-action';
    const X_MS_BLOB_TYPE                     = 'x-ms-blob-type';
    const X_MS_BLOB_CONTENT_TYPE             = 'x-ms-blob-content-type';
    const X_MS_BLOB_CONTENT_ENCODING         = 'x-ms-blob-content-encoding';
    const X_MS_BLOB_CONTENT_LANGUAGE         = 'x-ms-blob-content-language';
    const X_MS_BLOB_CONTENT_MD5              = 'x-ms-blob-content-md5';
    const X_MS_BLOB_CACHE_CONTROL            = 'x-ms-blob-cache-control';
    const X_MS_BLOB_CONTENT_LENGTH           = 'x-ms-blob-content-length';
    const X_MS_COPY_SOURCE                   = 'x-ms-copy-source';
    const X_MS_RANGE                         = 'x-ms-range';
    const X_MS_RANGE_GET_CONTENT_MD5         = 'x-ms-range-get-content-md5';
    const X_MS_LEASE_DURATION                = 'x-ms-lease-duration';
    const X_MS_LEASE_ID                      = 'x-ms-lease-id';
    const X_MS_LEASE_TIME                    = 'x-ms-lease-time';
    const X_MS_LEASE_STATUS                  = 'x-ms-lease-status';
    const X_MS_LEASE_ACTION                  = 'x-ms-lease-action';
    const X_MS_DELETE_SNAPSHOTS              = 'x-ms-delete-snapshots';
    const X_MS_PAGE_WRITE                    = 'x-ms-page-write';
    const X_MS_SNAPSHOT                      = 'x-ms-snapshot';
    const X_MS_SOURCE_IF_MODIFIED_SINCE      = 'x-ms-source-if-modified-since';
    const X_MS_SOURCE_IF_UNMODIFIED_SINCE    = 'x-ms-source-if-unmodified-since';
    const X_MS_SOURCE_IF_MATCH               = 'x-ms-source-if-match';
    const X_MS_SOURCE_IF_NONE_MATCH          = 'x-ms-source-if-none-match';
    const X_MS_SOURCE_LEASE_ID               = 'x-ms-source-lease-id';
    const X_MS_CONTINUATION_NEXTTABLENAME    = 'x-ms-continuation-nexttablename';
    const X_MS_CONTINUATION_NEXTPARTITIONKEY = 'x-ms-continuation-nextpartitionkey';
    const X_MS_CONTINUATION_NEXTROWKEY       = 'x-ms-continuation-nextrowkey';
    const X_MS_REQUEST_ID                    = 'x-ms-request-id';
    const ETAG                               = 'etag';
    const LAST_MODIFIED                      = 'last-modified';
    const DATE                               = 'date';
    const AUTHENTICATION                     = 'authorization';
    const WRAP_AUTHORIZATION                 = 'WRAP access_token="%s"';
    const CONTENT_ENCODING                   = 'content-encoding';
    const CONTENT_LANGUAGE                   = 'content-language';
    const CONTENT_LENGTH                     = 'content-length';
    const CONTENT_LENGTH_NO_SPACE            = 'contentlength';
    const CONTENT_MD5                        = 'content-md5';
    const CONTENT_TYPE                       = 'content-type';
    const CONTENT_ID                         = 'content-id';
    const CONTENT_RANGE                      = 'content-range';
    const CACHE_CONTROL                      = 'cache-control';
    const IF_MODIFIED_SINCE                  = 'if-modified-since';
    const IF_MATCH                           = 'if-match';
    const IF_NONE_MATCH                      = 'if-none-match';
    const IF_UNMODIFIED_SINCE                = 'if-unmodified-since';
    const RANGE                              = 'range';
    const DATA_SERVICE_VERSION               = 'dataserviceversion';
    const MAX_DATA_SERVICE_VERSION           = 'maxdataserviceversion';
    const ACCEPT_HEADER                      = 'accept';
    const ACCEPT_CHARSET                     = 'accept-charset';
    const USER_AGENT                         = 'User-Agent';

    // Type
    const QUEUE_TYPE_NAME              = 'IQueue';
    const BLOB_TYPE_NAME               = 'IBlob';
    const TABLE_TYPE_NAME              = 'ITable';
    const SERVICE_MANAGEMENT_TYPE_NAME = 'IServiceManagement';
    const SERVICE_BUS_TYPE_NAME        = 'IServiceBus';
    const WRAP_TYPE_NAME               = 'IWrap';

    // WRAP
    const WRAP_ACCESS_TOKEN            = 'wrap_access_token';
    const WRAP_ACCESS_TOKEN_EXPIRES_IN = 'wrap_access_token_expires_in';
    const WRAP_NAME                    = 'wrap_name';
    const WRAP_PASSWORD                = 'wrap_password';
    const WRAP_SCOPE                   = 'wrap_scope';

    // OAuth
    const OAUTH_GRANT_TYPE              = 'grant_type';
    const OAUTH_CLIENT_ID               = 'client_id';
    const OAUTH_CLIENT_SECRET           = 'client_secret';
    const OAUTH_SCOPE                   = 'scope';
    const OAUTH_GT_CLIENT_CREDENTIALS   = 'client_credentials';
    const OAUTH_ACCESS_TOKEN            = 'access_token';
    const OAUTH_EXPIRES_IN              = 'expires_in';
    const OAUTH_ACCESS_TOKEN_PREFIX     = 'Bearer ';

    // HTTP Methods
    const HTTP_GET    = 'GET';
    const HTTP_PUT    = 'PUT';
    const HTTP_POST   = 'POST';
    const HTTP_HEAD   = 'HEAD';
    const HTTP_DELETE = 'DELETE';
    const HTTP_MERGE  = 'MERGE';

    // Misc
    const EMPTY_STRING           = '';
    const SEPARATOR              = ',';
    const AZURE_DATE_FORMAT      = 'D, d M Y H:i:s T';
    const TIMESTAMP_FORMAT       = 'Y-m-d H:i:s';
    const EMULATED               = 'EMULATED';
    const EMULATOR_BLOB_URI      = '127.0.0.1:10000';
    const EMULATOR_QUEUE_URI     = '127.0.0.1:10001';
    const EMULATOR_TABLE_URI     = '127.0.0.1:10002';
    const ASTERISK               = '*';
    const SERVICE_MANAGEMENT_URL = 'https://management.core.windows.net';
    const HTTP_SCHEME            = 'http';
    const HTTPS_SCHEME           = 'https';
    const SETTING_NAME = 'SettingName';
    const SETTING_CONSTRAINT = 'SettingConstraint';
    const DEV_STORE_URI = 'http://127.0.0.1';
    const SERVICE_URI_FORMAT = "%s://%s.%s";
    const WRAP_ENDPOINT_URI_FORMAT = "https://%s-sb.accesscontrol.windows.net/WRAPv0.9";

    // Xml Namespaces
    const WA_XML_NAMESPACE   = 'http://schemas.microsoft.com/windowsazure';
    const ATOM_XML_NAMESPACE = 'http://www.w3.org/2005/Atom';
    const DS_XML_NAMESPACE   = 'http://schemas.microsoft.com/ado/2007/08/dataservices';
    const DSM_XML_NAMESPACE  = 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata';
    const XSI_XML_NAMESPACE  = 'http://www.w3.org/2001/XMLSchema-instance';


    // Header values
    const SDK_USER_AGENT                                = 'Azure-SDK-For-PHP/0.4.1';
    const STORAGE_API_LATEST_VERSION                    = '2012-02-12';
    const SM_API_LATEST_VERSION                         = '2011-10-01';
    const DATA_SERVICE_VERSION_VALUE                    = '1.0;NetFx';
    const MAX_DATA_SERVICE_VERSION_VALUE                = '2.0;NetFx';
    const ACCEPT_HEADER_VALUE                           = 'application/atom+xml,application/xml';
    const ATOM_ENTRY_CONTENT_TYPE                       = 'application/atom+xml;type=entry;charset=utf-8';
    const ATOM_FEED_CONTENT_TYPE                        = 'application/atom+xml;type=feed;charset=utf-8';
    const ACCEPT_CHARSET_VALUE                          = 'utf-8';
    const INT32_MAX                                     = 2147483647;
    const MEDIA_SERVICES_API_LATEST_VERSION             = '2.2';
    const MEDIA_SERVICES_DATA_SERVICE_VERSION_VALUE     = '3.0;NetFx';
    const MEDIA_SERVICES_MAX_DATA_SERVICE_VERSION_VALUE = '3.0;NetFx';

    // Query parameter names
    const QP_PREFIX             = 'Prefix';
    const QP_MAX_RESULTS        = 'MaxResults';
    const QP_METADATA           = 'Metadata';
    const QP_MARKER             = 'Marker';
    const QP_NEXT_MARKER        = 'NextMarker';
    const QP_COMP               = 'comp';
    const QP_VISIBILITY_TIMEOUT = 'visibilitytimeout';
    const QP_POPRECEIPT         = 'popreceipt';
    const QP_NUM_OF_MESSAGES    = 'numofmessages';
    const QP_PEEK_ONLY          = 'peekonly';
    const QP_MESSAGE_TTL        = 'messagettl';
    const QP_INCLUDE            = 'include';
    const QP_TIMEOUT            = 'timeout';
    const QP_DELIMITER          = 'Delimiter';
    const QP_REST_TYPE          = 'restype';
    const QP_SNAPSHOT           = 'snapshot';
    const QP_BLOCKID            = 'blockid';
    const QP_BLOCK_LIST_TYPE    = 'blocklisttype';
    const QP_SELECT             = '$select';
    const QP_TOP                = '$top';
    const QP_SKIP               = '$skip';
    const QP_FILTER             = '$filter';
    const QP_NEXT_TABLE_NAME    = 'NextTableName';
    const QP_NEXT_PK            = 'NextPartitionKey';
    const QP_NEXT_RK            = 'NextRowKey';
    const QP_ACTION             = 'action';
    const QP_EMBED_DETAIL       = 'embed-detail';

    // Query parameter values
    const QPV_REGENERATE = 'regenerate';
    const QPV_CONFIG     = 'config';
    const QPV_STATUS     = 'status';
    const QPV_UPGRADE    = 'upgrade';
    const QPV_WALK_UPGRADE_DOMAIN = 'walkupgradedomain';
    const QPV_REBOOT = 'reboot';
    const QPV_REIMAGE = 'reimage';
    const QPV_ROLLBACK = 'rollback';

    // Request body content types
    const URL_ENCODED_CONTENT_TYPE = 'application/x-www-form-urlencoded';
    const XML_CONTENT_TYPE         = 'application/xml';
    const BINARY_FILE_TYPE         = 'application/octet-stream';
    const XML_ATOM_CONTENT_TYPE    = 'application/atom+xml';
    const HTTP_TYPE                = 'application/http';
    const MULTIPART_MIXED_TYPE     = 'multipart/mixed';

    // Common used XML tags
    const XTAG_ATTRIBUTES                 = '@attributes';
    const XTAG_NAMESPACE                  = '@namespace';
    const XTAG_LABEL                      = 'Label';
    const XTAG_NAME                       = 'Name';
    const XTAG_DESCRIPTION                = 'Description';
    const XTAG_LOCATION                   = 'Location';
    const XTAG_AFFINITY_GROUP             = 'AffinityGroup';
    const XTAG_HOSTED_SERVICES            = 'HostedServices';
    const XTAG_STORAGE_SERVICES           = 'StorageServices';
    const XTAG_STORAGE_SERVICE            = 'StorageService';
    const XTAG_DISPLAY_NAME               = 'DisplayName';
    const XTAG_SERVICE_NAME               = 'ServiceName';
    const XTAG_URL                        = 'Url';
    const XTAG_ID                         = 'ID';
    const XTAG_STATUS                     = 'Status';
    const XTAG_HTTP_STATUS_CODE           = 'HttpStatusCode';
    const XTAG_CODE                       = 'Code';
    const XTAG_MESSAGE                    = 'Message';
    const XTAG_STORAGE_SERVICE_PROPERTIES = 'StorageServiceProperties';
    const XTAG_ENDPOINT                   = 'Endpoint';
    const XTAG_ENDPOINTS                  = 'Endpoints';
    const XTAG_PRIMARY                    = 'Primary';
    const XTAG_SECONDARY                  = 'Secondary';
    const XTAG_KEY_TYPE                   = 'KeyType';
    const XTAG_STORAGE_SERVICE_KEYS       = 'StorageServiceKeys';
    const XTAG_ERROR                      = 'Error';
    const XTAG_HOSTED_SERVICE             = 'HostedService';
    const XTAG_HOSTED_SERVICE_PROPERTIES  = 'HostedServiceProperties';
    const XTAG_CREATE_HOSTED_SERVICE      = 'CreateHostedService';
    const XTAG_CREATE_STORAGE_SERVICE_INPUT = 'CreateStorageServiceInput';
    const XTAG_UPDATE_STORAGE_SERVICE_INPUT = 'UpdateStorageServiceInput';
    const XTAG_CREATE_AFFINITY_GROUP = 'CreateAffinityGroup';
    const XTAG_UPDATE_AFFINITY_GROUP = 'UpdateAffinityGroup';
    const XTAG_UPDATE_HOSTED_SERVICE = 'UpdateHostedService';
    const XTAG_PACKAGE_URL = 'PackageUrl';
    const XTAG_CONFIGURATION = 'Configuration';
    const XTAG_START_DEPLOYMENT = 'StartDeployment';
    const XTAG_TREAT_WARNINGS_AS_ERROR = 'TreatWarningsAsError';
    const XTAG_CREATE_DEPLOYMENT = 'CreateDeployment';
    const XTAG_DEPLOYMENT_SLOT = 'DeploymentSlot';
    const XTAG_PRIVATE_ID = 'PrivateID';
    const XTAG_ROLE_INSTANCE_LIST = 'RoleInstanceList';
    const XTAG_UPGRADE_DOMAIN_COUNT = 'UpgradeDomainCount';
    const XTAG_ROLE_LIST = 'RoleList';
    const XTAG_SDK_VERSION = 'SdkVersion';
    const XTAG_INPUT_ENDPOINT_LIST = 'InputEndpointList';
    const XTAG_LOCKED = 'Locked';
    const XTAG_ROLLBACK_ALLOWED = 'RollbackAllowed';
    const XTAG_UPGRADE_STATUS = 'UpgradeStatus';
    const XTAG_UPGRADE_TYPE = 'UpgradeType';
    const XTAG_CURRENT_UPGRADE_DOMAIN_STATE = 'CurrentUpgradeDomainState';
    const XTAG_CURRENT_UPGRADE_DOMAIN = 'CurrentUpgradeDomain';
    const XTAG_ROLE_NAME = 'RoleName';
    const XTAG_INSTANCE_NAME = 'InstanceName';
    const XTAG_INSTANCE_STATUS = 'InstanceStatus';
    const XTAG_INSTANCE_UPGRADE_DOMAIN = 'InstanceUpgradeDomain';
    const XTAG_INSTANCE_FAULT_DOMAIN = 'InstanceFaultDomain';
    const XTAG_INSTANCE_SIZE = 'InstanceSize';
    const XTAG_INSTANCE_STATE_DETAILS = 'InstanceStateDetails';
    const XTAG_INSTANCE_ERROR_CODE = 'InstanceErrorCode';
    const XTAG_OS_VERSION = 'OsVersion';
    const XTAG_ROLE_INSTANCE = 'RoleInstance';
    const XTAG_ROLE = 'Role';
    const XTAG_INPUT_ENDPOINT = 'InputEndpoint';
    const XTAG_VIP = 'Vip';
    const XTAG_PORT = 'Port';
    const XTAG_DEPLOYMENT = 'Deployment';
    const XTAG_DEPLOYMENTS = 'Deployments';
    const XTAG_REGENERATE_KEYS = 'RegenerateKeys';
    const XTAG_SWAP = 'Swap';
    const XTAG_PRODUCTION = 'Production';
    const XTAG_SOURCE_DEPLOYMENT = 'SourceDeployment';
    const XTAG_CHANGE_CONFIGURATION = 'ChangeConfiguration';
    const XTAG_MODE = 'Mode';
    const XTAG_UPDATE_DEPLOYMENT_STATUS = 'UpdateDeploymentStatus';
    const XTAG_ROLE_TO_UPGRADE = 'RoleToUpgrade';
    const XTAG_FORCE = 'Force';
    const XTAG_UPGRADE_DEPLOYMENT = 'UpgradeDeployment';
    const XTAG_UPGRADE_DOMAIN = 'UpgradeDomain';
    const XTAG_WALK_UPGRADE_DOMAIN = 'WalkUpgradeDomain';
    const XTAG_ROLLBACK_UPDATE_OR_UPGRADE = 'RollbackUpdateOrUpgrade';
    const XTAG_CONTAINER_NAME = 'ContainerName';
    const XTAG_ACCOUNT_NAME = 'AccountName';

    // Service Bus
    const LIST_TOPICS_PATH        = '$Resources/Topics';
    const LIST_QUEUES_PATH        = '$Resources/Queues';
    const LIST_RULES_PATH         = '%s/subscriptions/%s/rules';
    const LIST_SUBSCRIPTIONS_PATH = '%s/subscriptions';
    const RECEIVE_MESSAGE_PATH    = '%s/messages/head';
    const RECEIVE_SUBSCRIPTION_MESSAGE_PATH = '%s/subscriptions/%s/messages/head';
    const SEND_MESSAGE_PATH       = '%s/messages';
    const RULE_PATH               = '%s/subscriptions/%s/rules/%s';
    const SUBSCRIPTION_PATH       = '%s/subscriptions/%s';
    const DEFAULT_RULE_NAME       = '$Default';
    const UNIQUE_ID_PREFIX        = 'urn:uuid:';
    const SERVICE_BUS_NAMESPACE   = 'http://schemas.microsoft.com/netservices/2010/10/servicebus/connect';
    const BROKER_PROPERTIES       = 'BrokerProperties';
    const XMLNS_ATOM              = 'xmlns:atom';
    const XMLNS                   = 'xmlns';
    const ATOM_NAMESPACE          = 'http://www.w3.org/2005/Atom';

    // ATOM string
    const AUTHOR      = 'author';
    const CATEGORY    = 'category';
    const CONTRIBUTOR = 'contributor';
    const ENTRY       = 'entry';
    const LINK        = 'link';
    const PROPERTIES  = 'properties';
    const ELEMENT     = 'element';

    // PHP URL Keys
    const PHP_URL_SCHEME   = 'scheme';
    const PHP_URL_HOST     = 'host';
    const PHP_URL_PORT     = 'port';
    const PHP_URL_USER     = 'user';
    const PHP_URL_PASS     = 'pass';
    const PHP_URL_PATH     = 'path';
    const PHP_URL_QUERY    = 'query';
    const PHP_URL_FRAGMENT = 'fragment';

    // Status Codes
    const STATUS_OK                = 200;
    const STATUS_CREATED           = 201;
    const STATUS_ACCEPTED          = 202;
    const STATUS_NO_CONTENT        = 204;
    const STATUS_PARTIAL_CONTENT   = 206;
    const STATUS_MOVED_PERMANENTLY = 301;

    // HTTP_Request2 config parameter names
    const USE_BRACKETS    = 'use_brackets';
    const SSL_VERIFY_PEER = 'ssl_verify_peer';
    const SSL_VERIFY_HOST = 'ssl_verify_host';
    const SSL_LOCAL_CERT  = 'ssl_local_cert';
    const SSL_CAFILE      = 'ssl_cafile';
    const CONNECT_TIMEOUT = 'connect_timeout';

    // Media services
    const MEDIA_SERVICES_URL = 'https://media.windows.net/API/';
    const MEDIA_SERVICES_OAUTH_URL = 'https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13';
    const MEDIA_SERVICES_OAUTH_SCOPE = 'urn:WindowsAzureMediaServices';
    const MEDIA_SERVICES_INPUT_ASSETS_REL  = 'http://schemas.microsoft.com/ado/2007/08/dataservices/related/InputMediaAssets';
    const MEDIA_SERVICES_ASSET_REL  = 'http://schemas.microsoft.com/ado/2007/08/dataservices/related/Asset';
    const MEDIA_SERVICES_ENCRYPTION_VERSION = '1.0';


    // @codingStandardsIgnoreEnd
}
Internal/ConnectionStringParser.php000060400000025211152440043010013462 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;

/**
 * Helper methods for parsing connection strings. The rules for formatting connection
 * strings are defined here:
 * www.connectionstrings.com/articles/show/important-rules-for-connection-strings
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ConnectionStringParser
{
    /**
     * @var string
     */
    private $_argumentName;
    
    /**
     * @var string
     */
    private $_value;
    
    /**
     * @var integer
     */
    private $_pos;
    
    /**
     * @var string
     */
    private $_state;
    
    /**
     * Parses the connection string into a collection of key/value pairs.
     * 
     * @param string $argumentName     Name of the argument to be used in error 
     * messages.
     * @param string $connectionString Connection string.
     * 
     * @return array
     * 
     * @static
     */
    public static function parseConnectionString($argumentName, $connectionString)
    {
        Validate::isString($argumentName, 'argumentName');
        Validate::notNullOrEmpty($argumentName, 'argumentName');
        Validate::isString($connectionString, 'connectionString');
        Validate::notNullOrEmpty($connectionString, 'connectionString');
        
        $parser = new ConnectionStringParser($argumentName, $connectionString);
        return $parser->_parse();
    }
    
    /**
     * Initializes the object.
     * 
     * @param string $argumentName Name of the argument to be used in error 
     * messages.
     * @param string $value        Connection string.
     */
    private function __construct($argumentName, $value)
    {
        $this->_argumentName = $argumentName;
        $this->_value        = $value;
        $this->_pos          = 0;
        $this->_state        = ParserState::EXPECT_KEY;
    }
    
    /**
     * Parses the connection string.
     * 
     * @return array
     * 
     * @throws \RuntimeException
     */
    private function _parse()
    {
        $key                    = null;
        $value                  = null;
        $connectionStringValues = array();
        
        while (true) {
            $this->_skipWhiteSpaces();
            
            if (   $this->_pos == strlen($this->_value)
                && $this->_state != ParserState::EXPECT_VALUE
            ) {
                // Not stopping after the end has been reached and a value is 
                // expected results in creating an empty value, which we expect.
                break;
            }
            
            switch ($this->_state) {
            case ParserState::EXPECT_KEY:
                $key          = $this->_extractKey();
                $this->_state = ParserState::EXPECT_ASSIGNMENT;
                break;
            
            case ParserState::EXPECT_ASSIGNMENT:
                $this->_skipOperator('=');
                $this->_state = ParserState::EXPECT_VALUE;
                break;
            
            case ParserState::EXPECT_VALUE:
                $value                        = $this->_extractValue();
                $this->_state                 = ParserState::EXPECT_SEPARATOR;
                $connectionStringValues[$key] = $value;
                $key                          = null;
                $value                        = null;
                break;
            
            default:
                $this->_skipOperator(';');
                $this->_state = ParserState::EXPECT_KEY;
                break;
            }
        }
        
        // Must end parsing in the valid state (expected key or separator)
        if ($this->_state == ParserState::EXPECT_ASSIGNMENT) {
            throw $this->_createException(
                $this->_pos,
                Resources::MISSING_CONNECTION_STRING_CHAR,
                '='
            );
        }
        
        return $connectionStringValues;
    }
    
    /**
     *Generates an invalid connection string exception with the detailed error 
     * message.
     * 
     * @param integer $position    The position of the error.
     * @param string  $errorString The short error formatting string.
     * 
     * @return \RuntimeException
     */
    private function _createException($position, $errorString)
    {
        $arguments = func_get_args();
        
        // Remove first argument (position)
        unset($arguments[0]);
        
        // Create a short error message.
        $errorString = sprintf($errorString, $arguments);
        
        // Add position.
        $errorString = sprintf(
            Resources::ERROR_PARSING_STRING,
            $errorString,
            $position
        );
        
        // Create final error message.
        $errorString = sprintf(
            Resources::INVALID_CONNECTION_STRING,
            $this->_argumentName,
            $errorString
        );
        
        return new \RuntimeException($errorString);
    }
    
    /**
     * Skips whitespaces at the current position.
     * 
     * @return none
     */
    private function _skipWhiteSpaces()
    {
        while (   $this->_pos < strlen($this->_value)
              &&  ctype_space($this->_value[$this->_pos])
        ) {
            $this->_pos++;
        }
    }
    
    /**
     * Extracts the key's value.
     * 
     * @return string 
     */
    private function _extractValue()
    {
        $value = Resources::EMPTY_STRING;
        
        if ($this->_pos < strlen($this->_value)) {
            $ch = $this->_value[$this->_pos];
            
            if ($ch == '"' || $ch == '\'') {
                // Value is contained between double quotes or skipped single quotes.
                $this->_pos++;
                $value = $this->_extractString($ch);
            } else {
                $firstPos = $this->_pos;
                $isFound  = false;
                
                while ($this->_pos < strlen($this->_value) && !$isFound) {
                    $ch = $this->_value[$this->_pos];
                    
                    if ($ch == ';') {
                        $isFound = true;
                    } else {
                        $this->_pos++;
                    }
                }
                
                $value = rtrim(
                    substr($this->_value, $firstPos, $this->_pos - $firstPos)
                );
            }
        }
        
        return $value;
    }
    
    /**
     * Extracts key at the current position.
     * 
     * @return string 
     */
    private function _extractKey()
    {
        $key      = null;
        $firstPos = $this->_pos;
        $ch       = $this->_value[$this->_pos];
        
        if ($ch == '"' || $ch == '\'') {
            $this->_pos++;
            $key = $this->_extractString($ch);
        } else if ($ch == ';' || $ch == '=') {
            // Key name was expected.
            throw $this->_createException(
                $firstPos,
                Resources::ERROR_CONNECTION_STRING_MISSING_KEY
            );
        } else {
            while ($this->_pos < strlen($this->_value)) {
                $ch = $this->_value[$this->_pos];
                
                // At this point we've read the key, break.
                if ($ch == '=') {
                    break;
                }
                
                $this->_pos++;
            }
            $key = rtrim(substr($this->_value, $firstPos, $this->_pos - $firstPos));
        }
        
        if (strlen($key) == 0) {
            // Empty key name.
            throw $this->_createException(
                $firstPos,
                Resources::ERROR_CONNECTION_STRING_EMPTY_KEY
            );
        }
        
        return $key;
    }
    
    /**
     * Extracts the string until the given quotation mark.
     * 
     * @param string $quote The quotation mark terminating the string.
     * 
     * @return string
     */
    private function _extractString($quote)
    {
        $firstPos = $this->_pos;
        
        while (   $this->_pos < strlen($this->_value)
              &&  $this->_value[$this->_pos] != $quote
        ) {
            $this->_pos++;
        }
        
        if ($this->_pos == strlen($this->_value)) {
            // Runaway string.
            throw $this->_createException(
                $this->_pos,
                Resources::ERROR_CONNECTION_STRING_MISSING_CHARACTER,
                $quote
            );
        }
        
        return substr($this->_value, $firstPos, $this->_pos++ - $firstPos);
    }
    
    /**
     * Skips specified operator.
     * 
     * @param string $operatorChar The operator character.
     * 
     * @return none
     * 
     * @throws \RuntimeException
     */
    private function _skipOperator($operatorChar)
    {
        if ($this->_value[$this->_pos] != $operatorChar) {
            // Character was expected.
            throw $this->_createException(
                $this->_pos,
                Resources::MISSING_CONNECTION_STRING_CHAR,
                $operatorChar
            );
        }
        
        $this->_pos++;
    }
}

/**
 * State of the connection string parser.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ParserState
{
    const EXPECT_KEY        = 'ExpectKey';
    const EXPECT_ASSIGNMENT = 'ExpectAssignment';
    const EXPECT_VALUE      = 'ExpectValue';
    const EXPECT_SEPARATOR  = 'ExpectSeparator';
}Internal/StorageServiceSettings.php000060400000034052152440043010013470 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\ConnectionStringParser;
use WindowsAzure\Common\Internal\Resources;

/**
 * Represents the settings used to sign and access a request against the storage 
 * service. For more information about storage service connection strings check this
 * page: http://msdn.microsoft.com/en-us/library/ee758697
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class StorageServiceSettings extends ServiceSettings
{
    /**
     * The storage service name.
     * 
     * @var string
     */
    private $_name;
    
    /**
     * A base64 representation.
     * 
     * @var string
     */
    private $_key;
    
    /**
     * The endpoint for the blob service.
     * 
     * @var string
     */
    private $_blobEndpointUri;
    
    /**
     * The endpoint for the queue service.
     * 
     * @var string
     */
    private $_queueEndpointUri;
    
    /**
     * The endpoint for the table service.
     * 
     * @var string
     */
    private $_tableEndpointUri;
    
    /**
     * @var StorageServiceSettings
     */
    private static $_devStoreAccount;
    
    /**
     * Validator for the UseDevelopmentStorage setting. Must be "true".
     * 
     * @var array
     */
    private static $_useDevelopmentStorageSetting;
    
    /**
     * Validator for the DevelopmentStorageProxyUri setting. Must be a valid Uri.
     * 
     * @var array
     */
    private static $_developmentStorageProxyUriSetting;
    
    /**
     * Validator for the DefaultEndpointsProtocol setting. Must be either "http" 
     * or "https".
     * 
     * @var array
     */
    private static $_defaultEndpointsProtocolSetting;
    
    /**
     * Validator for the AccountName setting. No restrictions.
     * 
     * @var array
     */
    private static $_accountNameSetting;
    
    /**
     * Validator for the AccountKey setting. Must be a valid base64 string.
     * 
     * @var array
     */
    private static $_accountKeySetting;
    
    /**
     * Validator for the BlobEndpoint setting. Must be a valid Uri.
     * 
     * @var array
     */
    private static $_blobEndpointSetting;
    
    /**
     * Validator for the QueueEndpoint setting. Must be a valid Uri.
     * 
     * @var array
     */
    private static $_queueEndpointSetting;
    
    /**
     * Validator for the TableEndpoint setting. Must be a valid Uri.
     * 
     * @var array
     */
    private static $_tableEndpointSetting;
    
    /**
     * @var boolean
     */
    protected static $isInitialized = false;
    
    /**
     * Holds the expected setting keys.
     * 
     * @var array
     */
    protected static $validSettingKeys = array();
    
    /**
     * Initializes static members of the class.
     * 
     * @return none
     */
    protected static function init()
    {
        self::$_useDevelopmentStorageSetting = self::setting(
            Resources::USE_DEVELOPMENT_STORAGE_NAME,
            'true'
        );
        
        self::$_developmentStorageProxyUriSetting = self::settingWithFunc(
            Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME,
            Validate::getIsValidUri()
        );
        
        self::$_defaultEndpointsProtocolSetting = self::setting(
            Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME,
            'http', 'https'
        );
        
        self::$_accountNameSetting = self::setting(Resources::ACCOUNT_NAME_NAME);
        
        self::$_accountKeySetting = self::settingWithFunc(
            Resources::ACCOUNT_KEY_NAME,
            // base64_decode will return false if the $key is not in base64 format.
            function ($key) {
                $isValidBase64String = base64_decode($key, true);
                if ($isValidBase64String) {
                    return true;
                } else {
                    throw new \RuntimeException(
                        sprintf(Resources::INVALID_ACCOUNT_KEY_FORMAT, $key)
                    );
                }
            }
        );
        
        self::$_blobEndpointSetting = self::settingWithFunc(
            Resources::BLOB_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );
        
        self::$_queueEndpointSetting = self::settingWithFunc(
            Resources::QUEUE_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );
        
        self::$_tableEndpointSetting = self::settingWithFunc(
            Resources::TABLE_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );
        
        self::$validSettingKeys[] = Resources::USE_DEVELOPMENT_STORAGE_NAME;
        self::$validSettingKeys[] = Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME;
        self::$validSettingKeys[] = Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME;
        self::$validSettingKeys[] = Resources::ACCOUNT_NAME_NAME;
        self::$validSettingKeys[] = Resources::ACCOUNT_KEY_NAME;
        self::$validSettingKeys[] = Resources::BLOB_ENDPOINT_NAME;
        self::$validSettingKeys[] = Resources::QUEUE_ENDPOINT_NAME;
        self::$validSettingKeys[] = Resources::TABLE_ENDPOINT_NAME;
    }
    
    /**
     * Creates new storage service settings instance.
     * 
     * @param string $name             The storage service name.
     * @param string $key              The storage service key.
     * @param string $blobEndpointUri  The sotrage service blob endpoint.
     * @param string $queueEndpointUri The sotrage service queue endpoint.
     * @param string $tableEndpointUri The sotrage service table endpoint.
     */
    public function __construct(
        $name,
        $key,
        $blobEndpointUri,
        $queueEndpointUri,
        $tableEndpointUri
    ) {
        $this->_name             = $name;
        $this->_key              = $key;
        $this->_blobEndpointUri  = $blobEndpointUri;
        $this->_queueEndpointUri = $queueEndpointUri;
        $this->_tableEndpointUri = $tableEndpointUri;
    }
    
    /**
     * Returns a StorageServiceSettings with development storage credentials using 
     * the specified proxy Uri.
     * 
     * @param string $proxyUri The proxy endpoint to use.
     * 
     * @return StorageServiceSettings
     */
    private static function _getDevelopmentStorageAccount($proxyUri)
    {
        if (is_null($proxyUri)) {
            return self::developmentStorageAccount();
        }
        
        $scheme = parse_url($proxyUri, PHP_URL_SCHEME);
        $host   = parse_url($proxyUri, PHP_URL_HOST);
        $prefix = $scheme . "://" . $host;
        
        return new StorageServiceSettings(
            Resources::DEV_STORE_NAME,
            Resources::DEV_STORE_KEY,
            $prefix . ':10000/devstoreaccount1/',
            $prefix . ':10001/devstoreaccount1/',
            $prefix . ':10002/devstoreaccount1/'
        );
    }
    
    /**
     * Gets a StorageServiceSettings object that references the development storage 
     * account.
     * 
     * @return StorageServiceSettings 
     */
    public static function developmentStorageAccount()
    {
        if (is_null(self::$_devStoreAccount)) {
            self::$_devStoreAccount = self::_getDevelopmentStorageAccount(
                Resources::DEV_STORE_URI
            );
        }
        
        return self::$_devStoreAccount;
    }
    
    /**
     * Gets the default service endpoint using the specified protocol and account 
     * name.
     * 
     * @param array  $settings The service settings.
     * @param string $dns      The service DNS.
     * 
     * @return string
     */
    private static function _getDefaultServiceEndpoint($settings, $dns)
    {
        $scheme      = Utilities::tryGetValueInsensitive(
            Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME,
            $settings
        );
        $accountName = Utilities::tryGetValueInsensitive(
            Resources::ACCOUNT_NAME_NAME,
            $settings
        );
        
        return sprintf(Resources::SERVICE_URI_FORMAT, $scheme, $accountName, $dns);
    }
    
    /**
     * Creates StorageServiceSettings object given endpoints uri.
     * 
     * @param array  $settings         The service settings.
     * @param string $blobEndpointUri  The blob endpoint uri.
     * @param string $queueEndpointUri The queue endpoint uri.
     * @param string $tableEndpointUri The table endpoint uri.
     * 
     * @return \WindowsAzure\Common\Internal\StorageServiceSettings
     */
    private static function _createStorageServiceSettings(
        $settings,
        $blobEndpointUri = null,
        $queueEndpointUri = null,
        $tableEndpointUri = null
    ) {
        $blobEndpointUri  = Utilities::tryGetValueInsensitive(
            Resources::BLOB_ENDPOINT_NAME,
            $settings,
            $blobEndpointUri
        );
        $queueEndpointUri = Utilities::tryGetValueInsensitive(
            Resources::QUEUE_ENDPOINT_NAME,
            $settings,
            $queueEndpointUri
        );
        $tableEndpointUri = Utilities::tryGetValueInsensitive(
            Resources::TABLE_ENDPOINT_NAME,
            $settings,
            $tableEndpointUri
        );
        $accountName      = Utilities::tryGetValueInsensitive(
            Resources::ACCOUNT_NAME_NAME,
            $settings
        );
        $accountKey       = Utilities::tryGetValueInsensitive(
            Resources::ACCOUNT_KEY_NAME,
            $settings
        );
            
        return new StorageServiceSettings(
            $accountName,
            $accountKey,
            $blobEndpointUri,
            $queueEndpointUri,
            $tableEndpointUri
        );
    }

    /**
     * Creates a StorageServiceSettings object from the given connection string.
     * 
     * @param string $connectionString The storage settings connection string.
     * 
     * @return StorageServiceSettings 
     */
    public static function createFromConnectionString($connectionString)
    {
        $tokenizedSettings = self::parseAndValidateKeys($connectionString);
        
        // Devstore case
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::allRequired(self::$_useDevelopmentStorageSetting),
            self::optional(self::$_developmentStorageProxyUriSetting)
        );
        if ($matchedSpecs) {
            $proxyUri = Utilities::tryGetValueInsensitive(
                Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME,
                $tokenizedSettings
            );
            
            return self::_getDevelopmentStorageAccount($proxyUri);
        }
        
        // Automatic case
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::allRequired(
                self::$_defaultEndpointsProtocolSetting,
                self::$_accountNameSetting,
                self::$_accountKeySetting
            ),
            self::optional(
                self::$_blobEndpointSetting,
                self::$_queueEndpointSetting,
                self::$_tableEndpointSetting
            )
        );
        if ($matchedSpecs) {
            return self::_createStorageServiceSettings(
                $tokenizedSettings,
                self::_getDefaultServiceEndpoint(
                    $tokenizedSettings,
                    Resources::BLOB_BASE_DNS_NAME
                ),
                self::_getDefaultServiceEndpoint(
                    $tokenizedSettings,
                    Resources::QUEUE_BASE_DNS_NAME
                ),
                self::_getDefaultServiceEndpoint(
                    $tokenizedSettings,
                    Resources::TABLE_BASE_DNS_NAME
                )
            );
        }
        
        // Explicit case
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::atLeastOne(
                self::$_blobEndpointSetting,
                self::$_queueEndpointSetting,
                self::$_tableEndpointSetting
            ),
            self::allRequired(
                self::$_accountNameSetting,
                self::$_accountKeySetting
            )
        );
        if ($matchedSpecs) {
            return self::_createStorageServiceSettings($tokenizedSettings);
        }
        
        self::noMatch($connectionString);
    }
    
    /**
     * Gets storage service name.
     * 
     * @return string
     */
    public function getName()
    {
        return $this->_name;
    }
    
    /**
     * Gets storage service key.
     * 
     * @return string
     */
    public function getKey()
    {
        return $this->_key;
    }
    
    /**
     * Gets storage service blob endpoint uri.
     * 
     * @return string
     */
    public function getBlobEndpointUri()
    {
        return $this->_blobEndpointUri;
    }
    
    /**
     * Gets storage service queue endpoint uri.
     * 
     * @return string
     */
    public function getQueueEndpointUri()
    {
        return $this->_queueEndpointUri;
    }

    /**
     * Gets storage service table endpoint uri.
     * 
     * @return string
     */
    public function getTableEndpointUri()
    {
        return $this->_tableEndpointUri;
    }
}


Internal/Serialization/.htaccess000044400000000424152440043010012722 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Internal/Serialization/JsonSerializer.php000060400000005623152440043010014604 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Serialization
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Serialization;
use WindowsAzure\Common\Internal\Validate;
/**
 * Perform JSON serialization / deserialization
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Serialization
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class JsonSerializer implements ISerializer
{
    /**
     * Serialize an object with specified root element name.
     *
     * @param object $targetObject The target object.
     * @param string $rootName     The name of the root element.
     *
     * @return string
     */
    public static function objectSerialize($targetObject, $rootName)
    {
        Validate::notNull($targetObject, 'targetObject');
        Validate::isString($rootName, 'rootName');

        $contianer = new \stdClass();

        $contianer->$rootName = $targetObject;

        return json_encode($contianer);
    }

    /**
     * Serializes given array. The array indices must be string to use them as
     * as element name.
     *
     * @param array $array      The object to serialize represented in array.
     * @param array $properties The used properties in the serialization process.
     *
     * @return string
     */
    public function serialize($array, $properties = null)
    {
        Validate::isArray($array, 'array');

        return json_encode($array);
    }

    /**
     * Unserializes given serialized string to array.
     *
     * @param string $serialized The serialized object in string representation.
     *
     * @return array
     */
    public function unserialize($serialized)
    {
        Validate::isString($serialized, 'serialized');

        $json = json_decode($serialized);
        if ($json && !is_array($json)) {
            return get_object_vars($json);
        } else {
            return $json;
        }
    }
}


Internal/Serialization/XmlSerializer.php000060400000017645152440043010014442 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Serialization
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Serialization;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;

/**
 * Short description
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Serialization
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class XmlSerializer implements ISerializer
{
    const STANDALONE  = 'standalone';
    const ROOT_NAME   = 'rootName';
    const DEFAULT_TAG = 'defaultTag';
    
    /**
     * Converts a SimpleXML object to an Array recursively
     * ensuring all sub-elements are arrays as well.
     *
     * @param string $sxml The SimpleXML object.
     * @param array  $arr  The array into which to store results.
     * 
     * @return array
     */
    private function _sxml2arr($sxml, $arr = null)
    {
        foreach ((array) $sxml as $key => $value) {
            if (is_object($value) || (is_array($value))) {
                $arr[$key] = $this->_sxml2arr($value);
            } else {
                $arr[$key] = $value;
            }
        }

        return $arr; 
    }
    
    /**
     * Takes an array and produces XML based on it.
     *
     * @param XMLWriter $xmlw       XMLWriter object that was previously instanted
     * and is used for creating the XML.
     * @param array     $data       Array to be converted to XML.
     * @param string    $defaultTag Default XML tag to be used if none specified.
     * 
     * @return void
     */
    private function _arr2xml(\XMLWriter $xmlw, $data, $defaultTag = null)
    {
        foreach ($data as $key => $value) {
            if ($key === Resources::XTAG_ATTRIBUTES) {
                foreach ($value as $attributeName => $attributeValue) {
                    $xmlw->writeAttribute($attributeName, $attributeValue);
                }
            } else if (is_array($value)) {
                if (!is_int($key)) {
                    if ($key != Resources::EMPTY_STRING) {
                        $xmlw->startElement($key);
                    } else {
                        $xmlw->startElement($defaultTag);
                    }
                }
                
                $this->_arr2xml($xmlw, $value);
                
                if (!is_int($key)) {
                    $xmlw->endElement();
                }
            } else {
                $xmlw->writeElement($key, $value);
            }
        }
    }

    /**
     * Gets the attributes of a specified object if get attributes 
     * method is exposed. 
     *
     * @param object $targetObject The target object. 
     * @param array  $methodArray  The array of method of the target object.
     * 
     * @return mixed
     */
    private static function _getInstanceAttributes($targetObject, $methodArray)
    {
        foreach ($methodArray as $method) {
            if ($method->name == 'getAttributes') {
                $classProperty = $method->invoke($targetObject);
                return $classProperty;
            }
        }
        return null;
    }

    /** 
     * Serialize an object with specified root element name. 
     * 
     * @param object $targetObject The target object. 
     * @param string $rootName     The name of the root element. 
     * 
     * @return string
     */
    public static function objectSerialize($targetObject, $rootName)
    {
        Validate::notNull($targetObject, 'targetObject');
        Validate::isString($rootName, 'rootName');
        $xmlWriter = new \XmlWriter();
        $xmlWriter->openMemory(); 
        $xmlWriter->setIndent(true);
        $reflectionClass = new \ReflectionClass($targetObject);
        $methodArray     = $reflectionClass->getMethods();
        $attributes      = self::_getInstanceAttributes(
            $targetObject, 
            $methodArray
        );
         
        $xmlWriter->startElement($rootName);
        if (!is_null($attributes)) {
            foreach (array_keys($attributes) as $attributeKey) {
                $xmlWriter->writeAttribute(
                    $attributeKey, 
                    $attributes[$attributeKey]
                );
            }
        }

        foreach ($methodArray as $method) {
            if ((strpos($method->name, 'get') === 0) 
                && $method->isPublic() 
                && ($method->name != 'getAttributes')
            ) {
                $variableName  = substr($method->name, 3);
                $variableValue = $method->invoke($targetObject);
                if (!empty($variableValue)) {
                    if (gettype($variableValue) === 'object') {
                        $xmlWriter->writeRaw(
                            XmlSerializer::objectSerialize(
                                $variableValue, $variableName
                            )
                        );
                    } else {
                        $xmlWriter->writeElement($variableName, $variableValue);
                    } 
                }
            }
        } 
        $xmlWriter->endElement();
        return $xmlWriter->outputMemory(true);
    }

    /**
     * Serializes given array. The array indices must be string to use them as
     * as element name.
     * 
     * @param array $array      The object to serialize represented in array.
     * @param array $properties The used properties in the serialization process.
     * 
     * @return string
     */
    public function serialize($array, $properties = null)
    {
        $xmlVersion   = '1.0';
        $xmlEncoding  = 'UTF-8';
        $standalone   = Utilities::tryGetValue($properties, self::STANDALONE);
        $defaultTag   = Utilities::tryGetValue($properties, self::DEFAULT_TAG);
        $rootName     = Utilities::tryGetValue($properties, self::ROOT_NAME);
        $docNamespace = Utilities::tryGetValue(
            $array,
            Resources::XTAG_NAMESPACE,
            null
        );

        if (!is_array($array)) {
            return false;
        }

        $xmlw = new \XmlWriter();
        $xmlw->openMemory();
        $xmlw->setIndent(true);
        $xmlw->startDocument($xmlVersion, $xmlEncoding, $standalone);
        
        if (is_null($docNamespace)) {
            $xmlw->startElement($rootName);
        } else {
            foreach ($docNamespace as $uri => $prefix) {
                $xmlw->startElementNS($prefix, $rootName, $uri);
                break;
            }
        }
        
        unset($array[Resources::XTAG_NAMESPACE]);
        self::_arr2xml($xmlw, $array, $defaultTag);

        $xmlw->endElement();

        return $xmlw->outputMemory(true);
    }
    
    /**
     * Unserializes given serialized string.
     * 
     * @param string $serialized The serialized object in string representation.
     * 
     * @return array
     */
    public function unserialize($serialized)
    {
        $sxml = new \SimpleXMLElement($serialized);

        return $this->_sxml2arr($sxml);
    }
}


Internal/Serialization/ISerializer.php000060400000004374152440043010014065 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Serialization
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Serialization;

/**
 * The serialization interface.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Serialization
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
interface ISerializer
{

    /** 
     * Serialize an object into a XML.
     * 
     * @param Object $targetObject The target object to be serialized. 
     * @param string $rootName     The name of the root.
     *
     * @return string
     */
    public static function objectSerialize($targetObject, $rootName);

    /**
     * Serializes given array. The array indices must be string to use them as
     * as element name.
     * 
     * @param array $array      The object to serialize represented in array.
     * @param array $properties The used properties in the serialization process.
     * 
     * @return string
     */
    public function serialize($array, $properties = null);

    
    /**
     * Unserializes given serialized string.
     * 
     * @param string $serialized The serialized object in string representation.
     * 
     * @return array
     */
    public function unserialize($serialized);
}


Internal/Logger.php000060400000004312152440043010010235 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;

/**
 * Logger class for debugging purpose.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class Logger
{
    /**
     * @var string
     */
    private static $_filePath;

    /**
     * Logs $var to file.
     *
     * @param mix    $var The data to log.
     * @param string $tip The help message.
     * 
     * @static
     * 
     * @return none
     */
    public static function log($var, $tip = Resources::EMPTY_STRING)
    {
        if (!empty($tip)) {
            error_log($tip . "\n", 3, self::$_filePath);
        }
        
        if (is_array($var) || is_object($var)) {
            error_log(print_r($var, true), 3, self::$_filePath);
        } else {
            error_log($var . "\n", 3, self::$_filePath);
        }
    }
    
    /**
     * Sets file path to use.
     *
     * @param string $filePath The log file path.
     * 
     * @static
     * 
     * @return none
     */
    public static function setLogFile($filePath)
    {
        self::$_filePath = $filePath;
    }
}


Internal/ServiceRestProxy.php000060400000024765152440043010012334 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\RestProxy;
use WindowsAzure\Common\Internal\Http\Url;
use WindowsAzure\Common\Internal\Http\HttpCallContext;

/**
 * Base class for all services rest proxies.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ServiceRestProxy extends RestProxy
{
    /**
     * @var string
     */
    private $_accountName;

    /**
     * Initializes new ServiceRestProxy object.
     *
     * @param IHttpClient $channel        The HTTP client used to send HTTP requests.
     * @param string      $uri            The storage account uri.
     * @param string      $accountName    The name of the account.
     * @param ISerializer $dataSerializer The data serializer.
     */
    public function __construct($channel, $uri, $accountName, $dataSerializer)
    {
        parent::__construct($channel, $dataSerializer, $uri);
        $this->_accountName = $accountName;
    }

    /**
     * Gets the account name. 
     *
     * @return string
     */
    public function getAccountName()
    {
        return $this->_accountName;
    }
    
    /**
     * Sends HTTP request with the specified HTTP call context.
     * 
     * @param WindowsAzure\Common\Internal\Http\HttpCallContext $context The HTTP 
     * call context.
     * 
     * @return \HTTP_Request2_Response
     */
    protected function sendContext($context)
    {
        $context->setUri($this->getUri());
        return parent::sendContext($context);
    }
    
    /**
     * Sends HTTP request with the specified parameters.
     * 
     * @param string $method         HTTP method used in the request
     * @param array  $headers        HTTP headers.
     * @param array  $queryParams    URL query parameters.
     * @param array  $postParameters The HTTP POST parameters.
     * @param string $path           URL path
     * @param int    $statusCode     Expected status code received in the response
     * @param string $body           Request body
     * 
     * @return \HTTP_Request2_Response
     */
    protected function send(
        $method, 
        $headers, 
        $queryParams, 
        $postParameters,
        $path, 
        $statusCode,
        $body = Resources::EMPTY_STRING
    ) {
        $context = new HttpCallContext();
        $context->setBody($body);
        $context->setHeaders($headers);
        $context->setMethod($method);
        $context->setPath($path);
        $context->setQueryParameters($queryParams);
        $context->setPostParameters($postParameters);
        
        if (is_array($statusCode)) {
            $context->setStatusCodes($statusCode);
        } else {
            $context->addStatusCode($statusCode);
        }
        
        return $this->sendContext($context);
    }

    
    /**
     * Adds optional header to headers if set
     * 
     * @param array           $headers         The array of request headers.
     * @param AccessCondition $accessCondition The access condition object.
     * 
     * @return array
     */
    public function addOptionalAccessConditionHeader($headers, $accessCondition)
    {
        if (!is_null($accessCondition)) {
            $header = $accessCondition->getHeader();
            
            if ($header != Resources::EMPTY_STRING) {
                $value = $accessCondition->getValue();
                if ($value instanceof \DateTime) {
                    $value = gmdate(
                        Resources::AZURE_DATE_FORMAT,
                        $value->getTimestamp()
                    );
                }
                $headers[$header] = $value;
            }
        }
        
        return $headers;
    }
    
    /**
     * Adds optional header to headers if set
     * 
     * @param array           $headers         The array of request headers.
     * @param AccessCondition $accessCondition The access condition object.
     * 
     * @return array
     */
    public function addOptionalSourceAccessConditionHeader(
        $headers, 
        $accessCondition
    ) {
        if (!is_null($accessCondition)) {
            $header     = $accessCondition->getHeader();
            $headerName = null;
            if (!empty($header)) {
                switch($header) {
                case Resources::IF_MATCH:
                    $headerName = Resources::X_MS_SOURCE_IF_MATCH;
                    break;
                
                case Resources::IF_UNMODIFIED_SINCE:
                    $headerName = Resources::X_MS_SOURCE_IF_UNMODIFIED_SINCE;
                    break;
                
                case Resources::IF_MODIFIED_SINCE:
                    $headerName = Resources::X_MS_SOURCE_IF_MODIFIED_SINCE;
                    break;
                
                case Resources::IF_NONE_MATCH:
                    $headerName = Resources::X_MS_SOURCE_IF_NONE_MATCH;
                    break;
                
                default:
                    throw new \Exception(Resources::INVALID_ACH_MSG);
                    break;
                }
            }
            $value = $accessCondition->getValue();
            if ($value instanceof \DateTime) {
                $value = gmdate(
                    Resources::AZURE_DATE_FORMAT,
                    $value->getTimestamp()
                );
            }
            
            $this->addOptionalHeader($headers, $headerName, $value);
        }
        
        return $headers;
    }
    
    /**
     * Adds HTTP POST parameter to the specified 
     * 
     * @param array  $postParameters An array of HTTP POST parameters.
     * @param string $key            The key of a HTTP POST parameter. 
     * @param string $value          the value of a HTTP POST parameter. 
     * 
     * @return array
     */
    public function addPostParameter(
        $postParameters,
        $key,
        $value
    ) {
        Validate::isArray($postParameters, 'postParameters');
        $postParameters[$key] = $value;
        return $postParameters; 
    }
    
    /**
     * Groups set of values into one value separated with Resources::SEPARATOR
     * 
     * @param array $values array of values to be grouped.
     * 
     * @return string
     */
    public function groupQueryValues($values)
    {
        Validate::isArray($values, 'values');
        $joined = Resources::EMPTY_STRING;
        
        foreach ($values as $value) {
            if (!is_null($value) && !empty($value)) {
                $joined .= $value . Resources::SEPARATOR;
            }
        }
        
        return trim($joined, Resources::SEPARATOR);
    }
    
    /**
     * Adds metadata elements to headers array
     * 
     * @param array $headers  HTTP request headers
     * @param array $metadata user specified metadata
     * 
     * @return array
     */
    protected function addMetadataHeaders($headers, $metadata)
    {
        $this->validateMetadata($metadata);
        
        $metadata = $this->generateMetadataHeaders($metadata);
        $headers  = array_merge($headers, $metadata);
        
        return $headers;
    }
    
    /**
     * Generates metadata headers by prefixing each element with 'x-ms-meta'.
     *
     * @param array $metadata user defined metadata.
     * 
     * @return array.
     */
    public function generateMetadataHeaders($metadata)
    {
        $metadataHeaders = array();
        
        if (is_array($metadata) && !is_null($metadata)) {
            foreach ($metadata as $key => $value) {
                $headerName = Resources::X_MS_META_HEADER_PREFIX;
                if (   strpos($value, "\r") !== false
                    || strpos($value, "\n") !== false
                ) {
                    throw new \InvalidArgumentException(Resources::INVALID_META_MSG);
                }
                
                $headerName                  .= strtolower($key);
                $metadataHeaders[$headerName] = $value;
            }
        }
        
        return $metadataHeaders;
    }
    
    /**
     * Gets metadata array by parsing them from given headers.
     *
     * @param array $headers HTTP headers containing metadata elements.
     * 
     * @return array.
     */
    public function getMetadataArray($headers)
    {
        $metadata = array();
        foreach ($headers as $key => $value) {
            $isMetadataHeader = Utilities::startsWith(
                strtolower($key),
                Resources::X_MS_META_HEADER_PREFIX
            );
            
            if ($isMetadataHeader) {
                $MetadataName = str_replace(
                    Resources::X_MS_META_HEADER_PREFIX,
                    Resources::EMPTY_STRING,
                    strtolower($key)
                );
                
                $metadata[$MetadataName] = $value;
            }
        }
        
        return $metadata;
    }
    
    /**
     * Validates the provided metadata array.
     * 
     * @param mix $metadata The metadata array.
     * 
     * @return none
     */
    public function validateMetadata($metadata)
    {
        if (!is_null($metadata)) {
            Validate::isArray($metadata, 'metadata');
        } else {
            $metadata = array();
        }
        
        foreach ($metadata as $key => $value) {
            Validate::isString($key, 'metadata key');
            Validate::isString($value, 'metadata value');
        }
    }
}


Internal/ConnectionStringSource.php000060400000005130152440043010013464 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;

/**
 * Holder for default connection string sources used in CloudConfigurationManager.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ConnectionStringSource
{
    /**
     * The list of all sources which comes as default.
     * 
     * @var type 
     */
    private static $_defaultSources;
    
    /**
     * @var boolean
     */
    private static $_isInitialized;
    
    /**
     * Environment variable source name.
     */
    const ENVIRONMENT_SOURCE = 'environment_source';
    
    /**
     * Initializes the default sources.
     * 
     * @return none
     */
    private static function _init()
    {
        if (!self::$_isInitialized) {
            self::$_defaultSources = array(
                self::ENVIRONMENT_SOURCE => array(__CLASS__, 'environmentSource')
            );
            self::$_isInitialized  = true;
        }        
    }
    
    /**
     * Gets a connection string value from the system environment.
     * 
     * @param string $key The connection string name.
     * 
     * @return string
     */
    public static function environmentSource($key)
    {
        Validate::isString($key, 'key');
        
        return getenv($key);
    }
    
    /**
     * Gets list of default sources.
     * 
     * @return array
     */
    public static function getDefaultSources()
    {
        self::_init();
        return self::$_defaultSources;
    }
}


Internal/ServiceManagementSettings.php000060400000013542152440043010014141 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;

/**
 * Represents the settings used to sign and access a request against the service 
 * management. For more information about service management connection strings check
 * this page: http://msdn.microsoft.com/en-us/library/windowsazure/gg466228.aspx
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ServiceManagementSettings extends ServiceSettings
{
    /**
     * @var string
     */
    private $_subscriptionId;
    
    /**
     * @var string
     */
    private $_certificatePath;
    
    /**
     * @var string
     */
    private $_endpointUri;
    
    /**
     * Validator for the ServiceManagementEndpoint setting. Must be a valid Uri.
     * 
     * @var array
     */
    private static $_endpointSetting;
    
    /**
     * Validator for the CertificatePath setting. It has to be provided.
     * 
     * @var array
     */
    private static $_certificatePathSetting;
    
    /**
     * Validator for the SubscriptionId setting. It has to be provided.
     * 
     * @var array
     */
    private static $_subscriptionIdSetting;
    
    /**
     * @var boolean
     */
    protected static $isInitialized = false;
    
    /**
     * Holds the expected setting keys.
     * 
     * @var array
     */
    protected static $validSettingKeys = array();
    
    /**
     * Initializes static members of the class.
     * 
     * @return none
     */
    protected static function init()
    {
        self::$_endpointSetting = self::settingWithFunc(
            Resources::SERVICE_MANAGEMENT_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );
        
        self::$_certificatePathSetting = self::setting(
            Resources::CERTIFICATE_PATH_NAME
        );
        
        self::$_subscriptionIdSetting = self::setting(
            Resources::SUBSCRIPTION_ID_NAME
        );
        
        self::$validSettingKeys[] = Resources::SUBSCRIPTION_ID_NAME;
        self::$validSettingKeys[] = Resources::CERTIFICATE_PATH_NAME;
        self::$validSettingKeys[] = Resources::SERVICE_MANAGEMENT_ENDPOINT_NAME;
    }
    
    /**
     * Creates new service management settings instance.
     * 
     * @param string $subscriptionId  The user provided subscription id.
     * @param string $endpointUri     The service management endpoint uri.
     * @param string $certificatePath The management certificate path.
     */
    public function __construct($subscriptionId, $endpointUri, $certificatePath)
    {
        $this->_certificatePath = $certificatePath;
        $this->_endpointUri     = $endpointUri;
        $this->_subscriptionId  = $subscriptionId;
    }
    
    /**
     * Creates a ServiceManagementSettings object from the given connection string.
     * 
     * @param string $connectionString The storage settings connection string.
     * 
     * @return ServiceManagementSettings 
     */
    public static function createFromConnectionString($connectionString)
    {
        $tokenizedSettings = self::parseAndValidateKeys($connectionString);
        
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::allRequired(
                self::$_subscriptionIdSetting,
                self::$_certificatePathSetting
            ),
            self::optional(
                self::$_endpointSetting
            )
        );
        if ($matchedSpecs) {
            $endpointUri     = Utilities::tryGetValueInsensitive(
                Resources::SERVICE_MANAGEMENT_ENDPOINT_NAME,
                $tokenizedSettings,
                Resources::SERVICE_MANAGEMENT_URL
            );
            $subscriptionId  = Utilities::tryGetValueInsensitive(
                Resources::SUBSCRIPTION_ID_NAME,
                $tokenizedSettings
            );
            $certificatePath = Utilities::tryGetValueInsensitive(
                Resources::CERTIFICATE_PATH_NAME,
                $tokenizedSettings
            );
            
            return new ServiceManagementSettings(
                $subscriptionId,
                $endpointUri,
                $certificatePath
            );
        }
        
        self::noMatch($connectionString);
    }
    
    /**
     * Gets service management endpoint uri.
     * 
     * @return string
     */
    public function getEndpointUri()
    {
        return $this->_endpointUri;
    }
    
    /**
     * Gets the subscription id.
     * 
     * @return string
     */
    public function getSubscriptionId()
    {
        return $this->_subscriptionId;
    }
    
    /**
     * Gets the certificate path.
     * 
     * @return string 
     */
    public function getCertificatePath()
    {
        return $this->_certificatePath;
    }
}


Internal/IServiceFilter.php000060400000003600152440043010011674 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;

/**
 * ServceFilter is called when the sending the request and after receiving the 
 * response.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
interface IServiceFilter
{
    /**
     * Processes HTTP request before send.
     *
     * @param mix $request HTTP request object.
     * 
     * @return mix processed HTTP request object.
     */
    public function handleRequest($request);

    /**
     * Processes HTTP response after send.
     *
     * @param mix $request  HTTP request object.
     * @param mix $response HTTP response object.
     * 
     * @return mix processed HTTP response object.
     */
    public function handleResponse($request, $response);
}


Internal/Filters/DateFilter.php000060400000004333152440043010012454 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Filters;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\IServiceFilter;

/**
 * Adds date header to the http request.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class DateFilter implements IServiceFilter
{
    /**
     * Adds date (in GMT format) header to the request headers.
     *
     * @param HttpClient $request HTTP channel object.
     * 
     * @return \HTTP_Request2
     */
    public function handleRequest($request) 
    {
        $date = gmdate(Resources::AZURE_DATE_FORMAT, time());
        $request->setHeader(Resources::DATE, $date);

        return $request;
    }

    /**
     * Does nothing with the response.
     *
     * @param HttpClient              $request  HTTP channel object.
     * @param \HTTP_Request2_Response $response HTTP response object.
     * 
     * @return \HTTP_Request2_Response
     */
    public function handleResponse($request, $response) 
    {
        // Do nothing with the response.
        return $response;
    }
}


Internal/Filters/.htaccess000044400000000424152440043010011515 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Internal/Filters/HeadersFilter.php000060400000005176152440043010013160 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Filters;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\IServiceFilter;

/**
 * Adds all passed headers to the HTTP request headers.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class HeadersFilter implements IServiceFilter
{
    /**
     * @var array
     */
    private $_headers;
    
    /**
     * Constructor
     * 
     * @param array $headers static headers to be added.
     * 
     * @return HeadersFilter
     */
    public function __construct($headers)
    {
        $this->_headers = $headers;
    }
    
    /**
     * Adds static header(s) to the HTTP request headers
     *
     * @param HttpClient $request HTTP channel object.
     * 
     * @return \HTTP_Request2
     */
    public function handleRequest($request) 
    {
        foreach ($this->_headers as $key => $value) {
            $headers = $request->getHeaders();
            if (!array_key_exists($key, $headers)) {
                $request->setHeader($key, $value);
            }
        }

        return $request;
    }

    /**
     * Does nothing with the response.
     *
     * @param HttpClient              $request  HTTP channel object.
     * @param \HTTP_Request2_Response $response HTTP response object.
     * 
     * @return \HTTP_Request2_Response
     */
    public function handleResponse($request, $response) 
    {
        // Do nothing with the response.
        return $response;
    }
}


Internal/Filters/AuthenticationFilter.php000060400000006021152440043010014552 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Filters;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\IServiceFilter;
use WindowsAzure\Common\Internal\Authentication\SharedKeyAuthScheme;
use WindowsAzure\Common\Internal\Authentication\TableSharedKeyLiteAuthScheme;
use WindowsAzure\Common\Internal\InvalidArgumentTypeException;

/**
 * Adds authentication header to the http request object.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class AuthenticationFilter implements IServiceFilter
{
    /**
     * @var WindowsAzure\Common\Internal\Authentication\StorageAuthScheme
     */
    private $_authenticationScheme;

    /**
     * Creates AuthenticationFilter with the passed scheme.
     * 
     * @param StorageAuthScheme $authenticationScheme The authentication scheme.
     */
    public function __construct($authenticationScheme)
    {
        $this->_authenticationScheme = $authenticationScheme;
    }

    /**
     * Adds authentication header to the request headers.
     *
     * @param HttpClient $request HTTP channel object.
     * 
     * @return \HTTP_Request2
     */
    public function handleRequest($request)
    {
        $signedKey = $this->_authenticationScheme->getAuthorizationHeader(
            $request->getHeaders(), $request->getUrl(),
            $request->getUrl()->getQueryVariables(), $request->getMethod()
        );
        $request->setHeader(Resources::AUTHENTICATION, $signedKey);

        return $request;
    }

    /**
     * Does nothing with the response.
     *
     * @param HttpClient              $request  HTTP channel object.
     * @param \HTTP_Request2_Response $response HTTP response object.
     * 
     * @return \HTTP_Request2_Response
     */
    public function handleResponse($request, $response) 
    {
        // Do nothing with the response.
        return $response;
    }
}


Internal/Filters/RetryPolicyFilter.php000060400000005527152440043010014072 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Filters;
use WindowsAzure\Common\Internal\IServiceFilter;

/**
 * Short description
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class RetryPolicyFilter implements IServiceFilter
{
    /**
     * @var RetryPolicy
     */
    private $_retryPolicy;

    /**
     * Initializes new object from RetryPolicyFilter.
     * 
     * @param RetryPolicy $retryPolicy The retry policy object.
     */
    public function __construct($retryPolicy)
    {
        $this->_retryPolicy = $retryPolicy;
    }

    /**
     * Handles the request before sending.
     * 
     * @param \HTTP_Request2 $request The HTTP request.
     * 
     * @return \HTTP_Request2
     */
    public function handleRequest($request)
    {
        return $request;
    }

    /**
     * Handles the response after sending.
     * 
     * @param \HTTP_Request2          $request  The HTTP request.
     * @param \HTTP_Request2_Response $response The HTTP response.
     * 
     * @return \HTTP_Request2_Response
     */
    public function handleResponse($request, $response)
    {
        for ($retryCount = 0;; $retryCount++) {
            $shouldRetry = $this->_retryPolicy->shouldRetry(
                $retryCount,
                $response
            );
            
            if (!$shouldRetry) {
                return $response;
            }
            
            // Backoff for some time according to retry policy
            $backoffTime = $this->_retryPolicy->calculateBackoff(
                $retryCount,
                $response
            );
            sleep($backoffTime * 0.001);
            $response = $request->send(array());
        }
    }
}


Internal/Filters/ExponentialRetryPolicy.php000060400000010203152440043010015116 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Filters;

/**
 * The exponential retry policy.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ExponentialRetryPolicy extends RetryPolicy
{
    /**
     * @var integer
     */
    private $_deltaBackoffIntervalInMs;
    
    /**
     * @var integer
     */
    private $_maximumAttempts;
    
    /**
     * @var integer
     */
    private $_resolvedMaxBackoff;
    
    /**
     * @var integer
     */
    private $_resolvedMinBackoff;
    
    /**
     * @var array
     */
    private $_retryableStatusCodes;
    
    /**
     * Initializes new object from ExponentialRetryPolicy.
     * 
     * @param array   $retryableStatusCodes The retryable status codes.
     * @param integer $deltaBackoff         The backoff time delta.
     * @param integer $maximumAttempts      The number of max attempts.
     */
    public function __construct($retryableStatusCodes, 
        $deltaBackoff = parent::DEFAULT_CLIENT_BACKOFF, 
        $maximumAttempts = parent::DEFAULT_CLIENT_RETRY_COUNT
    ) {
        $this->_deltaBackoffIntervalInMs = $deltaBackoff;
        $this->_maximumAttempts          = $maximumAttempts;
        $this->_resolvedMaxBackoff       = parent::DEFAULT_MAX_BACKOFF;
        $this->_resolvedMinBackoff       = parent::DEFAULT_MIN_BACKOFF;
        $this->_retryableStatusCodes     = $retryableStatusCodes;
        sort($retryableStatusCodes);
    }
    
    /**
     * Indicates if there should be a retry or not.
     * 
     * @param integer                 $retryCount The retry count.
     * @param \HTTP_Request2_Response $response   The HTTP response object.
     * 
     * @return boolean
     */
    public function shouldRetry($retryCount, $response)
    {
        if (  $retryCount >= $this->_maximumAttempts
            || array_search($response->getStatus(), $this->_retryableStatusCodes)
            || is_null($response)     
        ) {
            return false;
        } else {
            return true;
        }
    }
    
    /**
     * Calculates the backoff for the retry policy.
     * 
     * @param integer                 $retryCount The retry count.
     * @param \HTTP_Request2_Response $response   The HTTP response object.
     * 
     * @return integer
     */
    public function calculateBackoff($retryCount, $response)
    {
        // Calculate backoff Interval between 80% and 120% of the desired
        // backoff, multiply by 2^n -1 for
        // exponential
        $incrementDelta   = (int) (pow(2, $retryCount) - 1);
        $boundedRandDelta = (int) ($this->_deltaBackoffIntervalInMs * 0.8)
            + mt_rand(
                0,
                (int) ($this->_deltaBackoffIntervalInMs * 1.2)
                - (int) ($this->_deltaBackoffIntervalInMs * 0.8)
            );
        $incrementDelta  *= $boundedRandDelta;

        // Enforce max / min backoffs
        return min(
            $this->_resolvedMinBackoff + $incrementDelta,
            $this->_resolvedMaxBackoff
        );
    }
}


Internal/Filters/WrapFilter.php000060400000006740152440043010012514 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Filters;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\IServiceFilter;
use WindowsAzure\Common\Internal\Authentication\SharedKeyAuthScheme;
use WindowsAzure\Common\Internal\Authentication\TableSharedKeyLiteAuthScheme;
use WindowsAzure\Common\Internal\InvalidArgumentTypeException;
use WindowsAzure\ServiceBus\Internal\WrapTokenManager;


/**
 * Adds WRAP authentication header to the http request object.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class WrapFilter implements IServiceFilter
{
    /**
     * @var WrapTokenManager
     */
    private $_wrapTokenManager;

    /**
     * Creates a WrapFilter with specified WRAP parameters.
     *
     * @param string $wrapUri       The URI of the WRAP service. 
     * @param string $wrapUsername  The user name of the WRAP account.
     * @param string $wrapPassword  The password of the WRAP account.
     * @param IWrap  $wrapRestProxy The WRAP service REST proxy.
     */
    public function __construct(
        $wrapUri, 
        $wrapUsername, 
        $wrapPassword,
        $wrapRestProxy
    ) {
        $this->_wrapTokenManager = new WrapTokenManager(
            $wrapUri, 
            $wrapUsername, 
            $wrapPassword,
            $wrapRestProxy
        );
    }

    /**
     * Adds WRAP authentication header to the request headers.
     *
     * @param HttpClient $request HTTP channel object.
     * 
     * @return \HTTP_Request2
     */
    public function handleRequest($request)
    {
        Validate::notNull($request, 'request');
        $wrapAccessToken = $this->_wrapTokenManager->getAccessToken(
            $request->getUrl()
        );
        
        $authorization = sprintf(
            Resources::WRAP_AUTHORIZATION,
            $wrapAccessToken
        );
        
        $request->setHeader(Resources::AUTHENTICATION, $authorization);

        return $request;
    }

    /**
     * Returns the original response.
     *
     * @param HttpClient              $request  A HTTP channel object.
     * @param \HTTP_Request2_Response $response A HTTP response object.
     * 
     * @return \HTTP_Request2_Response
     */
    public function handleResponse($request, $response) 
    {
        return $response;
    }
}


Internal/Filters/RetryPolicy.php000060400000004247152440043010012722 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Filters;

/**
 * The retry policy abstract class.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Filters
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
abstract class RetryPolicy
{
    const DEFAULT_CLIENT_BACKOFF     = 30000;
    const DEFAULT_CLIENT_RETRY_COUNT = 3;
    const DEFAULT_MAX_BACKOFF        = 90000;
    const DEFAULT_MIN_BACKOFF        = 300;
    
    /**
     * Indicates if there should be a retry or not.
     * 
     * @param integer                 $retryCount The retry count.
     * @param \HTTP_Request2_Response $response   The HTTP response object.
     * 
     * @return boolean
     */
    public abstract function shouldRetry($retryCount, $response);
    
    /**
     * Calculates the backoff for the retry policy.
     * 
     * @param integer                 $retryCount The retry count.
     * @param \HTTP_Request2_Response $response   The HTTP response object.
     * 
     * @return integer
     */
    public abstract function calculateBackoff($retryCount, $response);
}


Internal/MediaServicesSettings.php000060400000016702152440043010013270 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;

/**
 * Represents the settings used to sign and access a request against the service
 * management. For more information about service management connection strings check
 * this page: http://msdn.microsoft.com/en-us/library/windowsazure/gg466228.aspx
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class MediaServicesSettings extends ServiceSettings
{
    /**
     * @var string
     */
    private $_accountName;

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

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

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

    /**
     * Validator for the MediaServicesAccountName setting. It has to be provided.
     *
     * @var array
     */
    private static $_accountNameSetting;

    /**
     * Validator for the MediaServicesAccessKey setting. It has to be provided.
     *
     * @var array
     */
    private static $_accessKeySetting;

    /**
     * Validator for the MediaServicesEndpoint setting. Must be a valid Uri.
     *
     * @var array
     */
    private static $_endpointUriSetting;

    /**
     * Validator for the MediaServicesOAuthEndpoint setting. Must be a valid Uri.
     *
     * @var array
     */
    private static $_oauthEndpointUriSetting;

    /**
     * @var boolean
     */
    protected static $isInitialized = false;

    /**
     * Holds the expected setting keys.
     *
     * @var array
     */
    protected static $validSettingKeys = array();

    /**
     * Initializes static members of the class.
     *
     * @return none
     */
    protected static function init()
    {
        self::$_endpointUriSetting = self::settingWithFunc(
            Resources::MEDIA_SERVICES_ENDPOINT_URI_NAME,
            Validate::getIsValidUri()
        );

        self::$_oauthEndpointUriSetting = self::settingWithFunc(
            Resources::MEDIA_SERVICES_OAUTH_ENDPOINT_URI_NAME,
            Validate::getIsValidUri()
        );

        self::$_accountNameSetting = self::setting(
            Resources::MEDIA_SERVICES_ACCOUNT_NAME
        );

        self::$_accessKeySetting = self::setting(
            Resources::MEDIA_SERVICES_ACCESS_KEY
        );

        self::$validSettingKeys[] = Resources::MEDIA_SERVICES_ENDPOINT_URI_NAME;
        self::$validSettingKeys[] = Resources::MEDIA_SERVICES_OAUTH_ENDPOINT_URI_NAME;
        self::$validSettingKeys[] = Resources::MEDIA_SERVICES_ACCOUNT_NAME;
        self::$validSettingKeys[] = Resources::MEDIA_SERVICES_ACCESS_KEY;
    }

    /**
     * Creates new media services settings instance.
     *
     * @param string $accountName      The user provided account name.
     * @param string $accessKey        The user provided primary access key
     * @param string $endpointUri      The service management endpoint uri.
     * @param string $oauthEndpointUri The OAuth service endpoint uri.
     */
    public function __construct(
        $accountName,
        $accessKey,
        $endpointUri = null,
        $oauthEndpointUri = null
    ) {
        Validate::notNullOrEmpty($accountName, 'accountName');
        Validate::notNullOrEmpty($accessKey, 'accountKey');
        Validate::isString($accountName, 'accountName');
        Validate::isString($accessKey, 'accountKey');

        if ($endpointUri != null) {
            Validate::isValidUri($endpointUri);
        } else {
            $endpointUri = Resources::MEDIA_SERVICES_URL;
        }

        if ($oauthEndpointUri != null) {
            Validate::isValidUri($oauthEndpointUri);
        } else {
            $oauthEndpointUri = Resources::MEDIA_SERVICES_OAUTH_URL;
        }

        $this->_accountName      = $accountName;
        $this->_accessKey        = $accessKey;
        $this->_endpointUri      = $endpointUri;
        $this->_oauthEndpointUri = $oauthEndpointUri;
    }

    /**
     * Creates a MediaServicesSettings object from the given connection string.
     *
     * @param string $connectionString The media services settings connection string.
     *
     * @return MediaServicesSettings
     */
    public static function createFromConnectionString($connectionString)
    {
        $tokenizedSettings = self::parseAndValidateKeys($connectionString);

        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::allRequired(
                self::$_accountNameSetting,
                self::$_accessKeySetting
            ),
            self::optional(
                self::$_endpointUriSetting,
                self::$_oauthEndpointUriSetting
            )
        );
        if ($matchedSpecs) {
            $endpointUri = Utilities::tryGetValueInsensitive(
                Resources::MEDIA_SERVICES_ENDPOINT_URI_NAME,
                $tokenizedSettings,
                Resources::MEDIA_SERVICES_URL
            );

            $oauthEndpointUri = Utilities::tryGetValueInsensitive(
                Resources::MEDIA_SERVICES_OAUTH_ENDPOINT_URI_NAME,
                $tokenizedSettings,
                Resources::MEDIA_SERVICES_OAUTH_URL
            );

            $accountName = Utilities::tryGetValueInsensitive(
                Resources::MEDIA_SERVICES_ACCOUNT_NAME,
                $tokenizedSettings
            );

            $accessKey = Utilities::tryGetValueInsensitive(
                Resources::MEDIA_SERVICES_ACCESS_KEY,
                $tokenizedSettings
            );

            return new MediaServicesSettings(
                $accountName,
                $accessKey,
                $endpointUri,
                $oauthEndpointUri
            );
        }

        self::noMatch($connectionString);
    }

    /**
     * Gets media services account name.
     *
     * @return string
     */
    public function getAccountName()
    {
        return $this->_accountName;
    }

    /**
     * Gets media services access key.
     *
     * @return string
     */
    public function getAccessKey()
    {
        return $this->_accessKey;
    }

    /**
     * Gets media services endpoint uri.
     *
     * @return string
     */
    public function getEndpointUri()
    {
        return $this->_endpointUri;
    }

    /**
     * Gets media services OAuth endpoint uri.
     *
     * @return string
     */
    public function getOAuthEndpointUri()
    {
        return $this->_oauthEndpointUri;
    }
}


Internal/Http/BatchResponse.php000060400000007557152440043010012513 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Http;
require_once 'PEAR.php';
require_once 'Mail/mimeDecode.php';
require_once 'HTTP/Request2/Response.php';
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\ServiceException;

/**
 * Batch response parser
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class BatchResponse
{
    /**
     * Http responses list
     *
     * @var array
     */
    private $_contexts;

    /**
     * Constructor
     *
     * @param string                                         $content Http response
     * as string
     *
     * @param WindowsAzure\Common\Internal\Http\BatchRequest $request Source batch
     * request object
     */
    public function __construct($content, $request = null)
    {
        $params['include_bodies'] = true;
        $params['input']          = $content;
        $mimeDecoder              = new \Mail_mimeDecode($content);
        $structure                = $mimeDecoder->decode($params);
        $parts                    = $structure->parts;
        $this->_contexts          = array();
        $requestContexts          = null;

        if ($request != null) {
            Validate::isA(
                $request,
                'WindowsAzure\Common\Internal\Http\BatchRequest',
                'request'
            );
            $requestContexts = $request->getContexts();
        }

        $i = 0;
        foreach ($parts as $part) {
            if (!empty($part->body)) {
                $headerEndPos = strpos($part->body, "\r\n\r\n");

                $header        = substr($part->body, 0, $headerEndPos);
                $body          = substr($part->body, $headerEndPos + 4);
                $headerStrings = explode("\r\n", $header);

                $response = new \HTTP_Request2_Response(array_shift($headerStrings));
                foreach ($headerStrings as $headerString) {
                    $response->parseHeaderLine($headerString);
                }
                $response->appendBody($body);

                $this->_contexts[] = $response;

                if (is_array($requestContexts)) {
                    $expectedCodes = $requestContexts[$i]->getStatusCodes();
                    $statusCode    = $response->getStatus();

                    if (!in_array($statusCode, $expectedCodes)) {
                        $reason = $response->getReasonPhrase();

                        throw new ServiceException($statusCode, $reason, $body);
                    }
                }

                $i++;
            }
        }
    }

    /**
     * Get parsed contexts as array
     *
     * @return array
     */
    public function getContexts()
    {
        return $this->_contexts;
    }

}

Internal/Http/IHttpClient.php000060400000012326152440043010012130 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Http;

/**
 * Defines required methods for a HTTP client proxy.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
interface IHttpClient
{
    /**
     * Sets the request url.
     *
     * @param WindowsAzure\Common\Internal\Http\IUrl $url request url.
     * 
     * @return none.
     */
    public function setUrl($url);

    /**
     * Gets request url.
     *
     * @return WindowsAzure\Common\Internal\Http\IUrl
     */
    public function getUrl();
    
    /**
     * Sets request's HTTP method.
     * 
     * @param string $method request's HTTP method.
     * 
     * @return none.
     */
    public function setMethod($method);

    /**
     * Gets request's HTTP method.
     *
     * @return string
     */
    public function getMethod();

    /**
     * Gets request's headers
     *
     * @return array
     */
    public function getHeaders();

    /**
     * Sets a an existing request header to value or creates a new one if the $header
     * doesn't exist.
     * 
     * @param string $header  header name.
     * @param string $value   header value.
     * @param bool   $replace whether to replace previous header with the same name
     * or append to its value (comma separated)
     * 
     * @return none.
     */
    public function setHeader($header, $value, $replace = false);
    
    /**
     * Sets request headers using array
     * 
     * @param array $headers headers key-value array
     * 
     * @return none.
     */
    public function setHeaders($headers);

    /**
     * Sets HTTP POST parameters.
     *
     * @param array $postParameters The HTTP POST parameters.
     *
     * @return none
     */
    public function setPostParameters($postParameters);

    /**
     * Processes the reuqest through HTTP pipeline with passed $filters, 
     * sends HTTP request to the wire and process the response in the HTTP pipeline.
     * 
     * @param array $filters HTTP filters which will be applied to the request before
     * send and then applied to the response.
     * @param IUrl  $url     Request url.
     * 
     * @return string The response body.
     */
    public function send($filters, $url = null);
    
    /**
     * Sets successful status code
     * 
     * @param array|string $statusCodes successful status code.
     * 
     * @return none.
     */
    public function setExpectedStatusCode($statusCodes);
    
    /**
     * Gets successful status code
     * 
     * @return array.
     */
    public function getSuccessfulStatusCode();
    
    /**
     * Sets a configuration element for the request.
     * 
     * @param string $name  configuration parameter name.
     * @param mix    $value configuration parameter value.
     * 
     * @return none.
     */
    public function setConfig($name, $value = null);
    
    /**
     * Gets value for configuration parameter.
     * 
     * @param string $name configuration parameter name.
     * 
     * @return string.
     */
    public function getConfig($name);
    
    /**
     * Sets the request body.
     * 
     * @param string $body body to use.
     * 
     * @return none.
     */
    public function setBody($body);
    
    /**
     * Gets the request body.
     * 
     * @return string.
     */
    public function getBody();
    
    /**
     * Makes deep copy from the current object.
     * 
     * @return WindowsAzure\Common\Internal\Http\HttpClient
     */
    public function __clone();
    
    /**
     * Gets the response object.
     * 
     * @return \HTTP_Request2_Response.
     */
    public function getResponse();
    
    /**
     * Throws ServiceException if the recieved status code is not expected.
     * 
     * @param string $actual   The received status code.
     * @param string $reason   The reason phrase.
     * @param string $message  The detailed message (if any).
     * @param array  $expected The expected status codes.
     * 
     * @return none
     * 
     * @static
     * 
     * @throws ServiceException
     */
    public static function throwIfError($actual, $reason, $message, $expected);
}


Internal/Http/.htaccess000044400000000424152440043010011024 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Internal/Http/HttpClient.php000060400000024421152440043010012016 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 * 
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Http;
use WindowsAzure\Common\Internal\Http\IHttpClient;
use WindowsAzure\Common\Internal\IServiceFilter;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\ServiceException;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Http\IUrl;

require_once 'HTTP/Request2.php';

/**
 * HTTP client which sends and receives HTTP requests and responses.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class HttpClient implements IHttpClient
{
    /**
     * @var \HTTP_Request2
     */
    private $_request;
    
    /**
     * @var WindowsAzure\Common\Internal\Http\IUrl 
     */
    private $_requestUrl;
    
    /**
     * Holds the latest response object
     * 
     * @var \HTTP_Request2_Response
     */
    private $_response;
    
    /**
     * Holds expected status code after sending the request.
     * 
     * @var array
     */
    private $_expectedStatusCodes;
    
    /**
     * Initializes new HttpClient object.
     * 
     * @param string $certificatePath          The certificate path.
     * @param string $certificateAuthorityPath The path of the certificate authority.
     * 
     * @return WindowsAzure\Common\Internal\Http\HttpClient
     */
    function __construct(
        $certificatePath = Resources::EMPTY_STRING,
        $certificateAuthorityPath = Resources::EMPTY_STRING
    ) {
        $config = array(
            Resources::USE_BRACKETS    => true,
            Resources::SSL_VERIFY_PEER => false,
            Resources::SSL_VERIFY_HOST => false
        );

        if (!empty($certificatePath)) {
            $config[Resources::SSL_LOCAL_CERT]  = $certificatePath;
            $config[Resources::SSL_VERIFY_HOST] = true;
        }

        if (!empty($certificateAuthorityPath)) {
            $config[Resources::SSL_CAFILE]      = $certificateAuthorityPath;
            $config[Resources::SSL_VERIFY_PEER] = true;
        }

        $this->_request = new \HTTP_Request2(
            null, null, $config
        );

        $this->setHeader('user-agent', null);
        
        $this->_requestUrl          = null;
        $this->_response            = null;
        $this->_expectedStatusCodes = array();
    }
    
    /**
     * Makes deep copy from the current object.
     * 
     * @return WindowsAzure\Common\Internal\Http\HttpClient
     */
    public function __clone()
    {
        $this->_request = clone $this->_request;
        
        if (!is_null($this->_requestUrl)) {
            $this->_requestUrl = clone $this->_requestUrl;
        }
    }

    /**
     * Sets the request url.
     *
     * @param WindowsAzure\Common\Internal\Http\IUrl $url request url.
     * 
     * @return none.
     */
    public function setUrl($url)
    {
        $this->_requestUrl = $url;
    }

    /**
     * Gets request url. Note that you must check if the returned object is null or
     * not.
     *
     * @return WindowsAzure\Common\Internal\Http\IUrl
     */ 
    public function getUrl()
    {
        return $this->_requestUrl;
    }

    /**
     * Sets request's HTTP method. You can use \HTTP_Request2 constants like
     * Resources::HTTP_GET or strings like 'GET'.
     * 
     * @param string $method request's HTTP method.
     * 
     * @return none
     */
    public function setMethod($method)
    {
        $this->_request->setMethod($method);
    }

    /**
     * Gets request's HTTP method.
     *
     * @return string
     */
    public function getMethod()
    {
        return $this->_request->getMethod();
    }

    /**
     * Gets request's headers. The returned array key (header names) are all in
     * lower case even if they were set having some upper letters.
     *
     * @return array
     */
    public function getHeaders()
    {
        return $this->_request->getHeaders();
    }

    /**
     * Sets a an existing request header to value or creates a new one if the $header
     * doesn't exist.
     * 
     * @param string $header  header name.
     * @param string $value   header value.
     * @param bool   $replace whether to replace previous header with the same name
     * or append to its value (comma separated)
     * 
     * @return none
     */
    public function setHeader($header, $value, $replace = false)
    {
        Validate::isString($value, 'value');
        
        $this->_request->setHeader($header, $value, $replace);
    }
    
    /**
     * Sets request headers using array
     * 
     * @param array $headers headers key-value array
     * 
     * @return none
     */
    public function setHeaders($headers)
    {
        foreach ($headers as $key => $value) {
            $this->setHeader($key, $value);
        }
    }

    /**
     * Sets HTTP POST parameters.
     * 
     * @param array $postParameters The HTTP POST parameters.
     * 
     * @return none
     */
    public function setPostParameters($postParameters)
    {
        $this->_request->addPostParameter($postParameters);
    }

    /**
     * Processes the reuqest through HTTP pipeline with passed $filters, 
     * sends HTTP request to the wire and process the response in the HTTP pipeline.
     * 
     * @param array $filters HTTP filters which will be applied to the request before
     * send and then applied to the response.
     * @param IUrl  $url     Request url.
     * 
     * @throws WindowsAzure\Common\ServiceException
     * 
     * @return string The response body
     */
    public function send($filters, $url = null)
    {
        if (isset($url)) {
            $this->setUrl($url);
            $this->_request->setUrl($this->_requestUrl->getUrl());
        }
        
        $contentLength = Resources::EMPTY_STRING;
        if (    strtoupper($this->getMethod()) != Resources::HTTP_GET
            && strtoupper($this->getMethod()) != Resources::HTTP_DELETE
            && strtoupper($this->getMethod()) != Resources::HTTP_HEAD
        ) {
            $contentLength = 0;
            
            if (!is_null($this->getBody())) {
                $contentLength = strlen($this->getBody());
            }
            $this->_request->setHeader(Resources::CONTENT_LENGTH, $contentLength);
        }

        foreach ($filters as $filter) {
            $this->_request = $filter->handleRequest($this)->_request;
        }

        $this->_response = $this->_request->send();

        $start = count($filters) - 1;
        for ($index = $start; $index >= 0; $index--) {
            $this->_response = $filters[$index]->handleResponse(
                $this, $this->_response
            );
        }
        
        self::throwIfError(
            $this->_response->getStatus(),
            $this->_response->getReasonPhrase(),
            $this->_response->getBody(),
            $this->_expectedStatusCodes
        );

        return $this->_response->getBody();
    }
    
    /**
     * Sets successful status code
     * 
     * @param array|string $statusCodes successful status code.
     * 
     * @return none
     */
    public function setExpectedStatusCode($statusCodes)
    {
        if (!is_array($statusCodes)) {
            $this->_expectedStatusCodes[] = $statusCodes;
        } else {
            $this->_expectedStatusCodes = $statusCodes;
        }
    }
    
    /**
     * Gets successful status code
     * 
     * @return array
     */
    public function getSuccessfulStatusCode()
    {
        return $this->_expectedStatusCodes;
    }
    
    /**
     * Sets configuration parameter.
     * 
     * @param string $name  The configuration parameter name.
     * @param mix    $value The configuration parameter value.
     * 
     * @return none
     */
    public function setConfig($name, $value = null)
    {
        $this->_request->setConfig($name, $value);
    }
    
    /**
     * Gets value for configuration parameter.
     * 
     * @param string $name configuration parameter name.
     * 
     * @return string
     */
    public function getConfig($name)
    {
        return $this->_request->getConfig($name);
    }
    
    /**
     * Sets the request body.
     * 
     * @param string $body body to use.
     * 
     * @return none
     */
    public function setBody($body)
    {
        Validate::isString($body, 'body');
        $this->_request->setBody($body);
    }
    
    /**
     * Gets the request body.
     * 
     * @return string
     */
    public function getBody()
    {
        return $this->_request->getBody();
    }
    
    /**
     * Gets the response object.
     * 
     * @return \HTTP_Request2_Response
     */
    public function getResponse()
    {
        return $this->_response;
    }
    
    /**
     * Throws ServiceException if the recieved status code is not expected.
     * 
     * @param string $actual   The received status code.
     * @param string $reason   The reason phrase.
     * @param string $message  The detailed message (if any).
     * @param array  $expected The expected status codes.
     * 
     * @return none
     * 
     * @static
     * 
     * @throws ServiceException
     */
    public static function throwIfError($actual, $reason, $message, $expected)
    {
        if (!in_array($actual, $expected)) {
            throw new ServiceException($actual, $reason, $message);
        }
    }
}


Internal/Http/BatchRequest.php000060400000010020152440043010012320 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Http;
require_once 'PEAR.php';
require_once 'Mail/mimePart.php';
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Batch request marshaler
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class BatchRequest
{
    /**
     * Http call context list
     *
     * @var array
     */
    private $_contexts;

    /**
     * Headers
     *
     * @var array
     */
    private $_headers;

    /**
     * Request body
     *
     * @var string
     */
    private $_body;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->_contexts = array();
    }

    /**
     * Append new context to batch request
     *
     * @param WindowsAzure\Common\Internal\Http\HttpCallContext $context Http call
     * context to add to batch request
     *
     * @return none
     */
    public function appendContext($context)
    {
        $this->_contexts[] = $context;
    }

    /**
     * Encode contexts
     *
     * @return none
     */
    public function encode()
    {
        $mimeType      = Resources::MULTIPART_MIXED_TYPE;
        $batchGuid     = Utilities::getGuid();
        $batchId       = sprintf('batch_%s', $batchGuid);
        $contentType1  = array('content_type' => "$mimeType");
        $changeSetGuid = Utilities::getGuid();
        $changeSetId   = sprintf('changeset_%s', $changeSetGuid);
        $contentType2  = array('content_type' => "$mimeType; boundary=$changeSetId");
        $options       = array(
            'encoding'     => 'binary',
            'content_type' => Resources::HTTP_TYPE
        );

        // Create changeset MIME part
        $changeSet = new \Mail_mimePart();

        $i = 1;
        foreach ($this->_contexts as $context) {
            $context->addHeader(Resources::CONTENT_ID, $i);
            $changeSet->addSubpart((string)$context, $options);

            $i++;
        }

        // Encode the changeset MIME part
        $changeSetEncoded = $changeSet->encode($changeSetId);

        // Create the batch MIME part
        $batch = new \Mail_mimePart(Resources::EMPTY_STRING, $contentType1);

        // Add changeset encoded to batch MIME part
        $batch->addSubpart($changeSetEncoded['body'], $contentType2);

        // Encode batch MIME part
        $batchEncoded = $batch->encode($batchId);

        $this->_headers = $batchEncoded['headers'];
        $this->_body    = $batchEncoded['body'];
    }

    /**
     * Get "Request body"
     *
     * @return string
     */
    public function getBody()
    {
        return $this->_body;
    }

    /**
     * Get "Headers"
     *
     * @return array
     */
    public function getHeaders()
    {
        return $this->_headers;
    }

    /**
     * Get request contexts
     *
     * @return array
     */
    public function getContexts()
    {
        return $this->_contexts;
    }
}

Internal/Http/Url.php000060400000011165152440043010010503 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Http;
require_once 'Net/URL2.php';
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Http\IUrl;

/**
 * Default IUrl implementation.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class Url implements IUrl
{
    /**
     * @var \Net_URL2
     */
    private $_url;
    
    /**
     * Sets the url path to '/' if it's empty
     * 
     * @param string $url the url string
     * 
     * @return none.
     */
    private function _setPathIfEmpty($url)
    {
        $path =  parse_url($url, PHP_URL_PATH);
        
        if (empty($path)) {
            $this->setUrlPath('/');
        }
    }

    /**
     * Constructor
     * 
     * @param string $url the url to set.
     * 
     * @return WindowsAzure\Common\Internal\Http\Url
     */
    public function __construct($url)
    {
        $errorMessage = Resources::INVALID_URL_MSG;
        Validate::isTrue(filter_var($url, FILTER_VALIDATE_URL), $errorMessage);
        
        $this->_url = new \Net_URL2($url);
        $this->_setPathIfEmpty($url);
    }
    
    /**
     * Makes deep copy from the current object.
     * 
     * @return WindowsAzure\Common\Internal\Http\Url
     */
    public function __clone()
    {
        $this->_url = clone $this->_url;
    }
    
    /**
     * Returns the query portion of the url
     * 
     * @return string
     */
    public function getQuery()
    {
        return $this->_url->getQuery();
    }

    /**
     * Returns the query portion of the url in array form
     * 
     * @return array
     */
    public function getQueryVariables()
    {
        return $this->_url->getQueryVariables();
    }

    /**
     * Sets a an existing query parameter to value or creates a new one if the $key
     * doesn't exist.
     * 
     * @param string $key   query parameter name.
     * @param string $value query value.
     * 
     * @return none
     */
    public function setQueryVariable($key, $value)
    {
        Validate::isString($key, 'key');
        Validate::isString($value, 'value');
        
        $this->_url->setQueryVariable($key, $value);
    }
    
    /**
     * Gets actual URL string.
     * 
     * @return string.
     */
    public function getUrl()
    {
        return $this->_url->getURL();
    }
    
    /**
     * Sets url path
     * 
     * @param string $urlPath url path to set.
     * 
     * @return none.
     */
    public function setUrlPath($urlPath)
    {
        Validate::isString($urlPath, 'urlPath');
        
        $this->_url->setPath($urlPath);
    }
    
    /**
     * Appends url path
     * 
     * @param string $urlPath url path to append.
     * 
     * @return none.
     */
    public function appendUrlPath($urlPath)
    {
        Validate::isString($urlPath, 'urlPath');
        
        $newUrlPath = parse_url($this->_url, PHP_URL_PATH) . $urlPath;
        $this->_url->setPath($newUrlPath);
    }
    
    /**
     * Gets actual URL string.
     * 
     * @return string.
     */
    public function __toString()
    {
        return $this->_url->getURL();
    }
    
    /**
     * Sets the query string to the specified variables in $array
     * 
     * @param array $array key/value representation of query variables.
     * 
     * @return none.
     */
    public function setQueryVariables($array)
    {
        foreach ($array as $key => $value) {
            $this->setQueryVariable($key, $value);
        }
    }
}


Internal/Http/HttpCallContext.php000060400000023007152440043010013017 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Http;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Http\Url;

/**
 * Holds basic elements for making HTTP call.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class HttpCallContext
{
    /**
     * The HTTP method used to make this call.
     * 
     * @var string
     */
    private $_method;    
    
    /**
     * HTTP request headers.
     * 
     * @var array
     */
    private $_headers;
    
    /**
     * The URI query parameters.
     * 
     * @var array
     */
    private $_queryParams;

    /** 
     * The HTTP POST parameters.
     * 
     * @var array.
     */
    private $_postParameters;
    
    /**
     * @var string
     */
    private $_uri;
    
    /**
     * The URI path.
     * 
     * @var string
     */
    private $_path;
    
    /**
     * The expected status codes.
     * 
     * @var array
     */
    private $_statusCodes;
    
    /**
     * The HTTP request body.
     * 
     * @var string
     */
    private $_body;
    
    /**
     * Default constructor.
     */
    public function __construct()
    {
        $this->_method         = null;
        $this->_body           = null;
        $this->_path           = null;
        $this->_uri            = null;
        $this->_queryParams    = array();
        $this->_postParameters = array();
        $this->_statusCodes    = array();
        $this->_headers        = array();
    }
    
    /**
     * Gets method.
     * 
     * @return string
     */
    public function getMethod()
    {
        return $this->_method;
    }
    
    /**
     * Sets method.
     * 
     * @param string $method The method value.
     * 
     * @return none
     */
    public function setMethod($method)
    {
        Validate::isString($method, 'method');
        
        $this->_method = $method;
    }
    
    /**
     * Gets headers.
     * 
     * @return array
     */
    public function getHeaders()
    {
        return $this->_headers;
    }
    
    /**
     * Sets headers.
     * 
     * Ignores the header if its value is empty.
     * 
     * @param array $headers The headers value.
     * 
     * @return none
     */
    public function setHeaders($headers)
    {
        $this->_headers = array();
        foreach ($headers as $key => $value) {
            $this->addHeader($key, $value);
        }
    }
    
    /**
     * Gets queryParams.
     * 
     * @return array
     */
    public function getQueryParameters()
    {
        return $this->_queryParams;
    }
    
    /**
     * Sets queryParams.
     * 
     * Ignores the query variable if its value is empty.
     * 
     * @param array $queryParams The queryParams value.
     * 
     * @return none
     */
    public function setQueryParameters($queryParams)
    {
        $this->_queryParams = array();
        foreach ($queryParams as $key => $value) {
            $this->addQueryParameter($key, $value);
        }
    }
    
    /**
     * Gets uri.
     * 
     * @return string
     */
    public function getUri()
    {
        return $this->_uri;
    }
    
    /**
     * Sets uri.
     * 
     * @param string $uri The uri value.
     * 
     * @return none
     */
    public function setUri($uri)
    {
        Validate::isString($uri, 'uri');
        
        $this->_uri = $uri;
    }
    
    /**
     * Gets path.
     * 
     * @return string
     */
    public function getPath()
    {
        return $this->_path;
    }
    
    /**
     * Sets path.
     * 
     * @param string $path The path value.
     * 
     * @return none
     */
    public function setPath($path)
    {
        Validate::isString($path, 'path');
        
        $this->_path = $path;
    }
    
    /**
     * Gets statusCodes.
     * 
     * @return array
     */
    public function getStatusCodes()
    {
        return $this->_statusCodes;
    }
    
    /**
     * Sets statusCodes.
     * 
     * @param array $statusCodes The statusCodes value.
     * 
     * @return none
     */
    public function setStatusCodes($statusCodes)
    {
        $this->_statusCodes = array();
        foreach ($statusCodes as $value) {
            $this->addStatusCode($value);
        }
    }
    
    /**
     * Gets body.
     * 
     * @return string
     */
    public function getBody()
    {
        return $this->_body;
    }
    
    /**
     * Sets body.
     * 
     * @param string $body The body value.
     * 
     * @return none
     */
    public function setBody($body)
    {
        Validate::isString($body, 'body');
        
        $this->_body = $body;
    }
    
    /**
     * Adds or sets header pair.
     * 
     * @param string $name  The HTTP header name.
     * @param string $value The HTTP header value.
     * 
     * @return none
     */
    public function addHeader($name, $value)
    {
        Validate::isString($name, 'name');
        Validate::isString($value, 'value');
        
        $this->_headers[$name] = $value;
    }
    
    /**
     * Adds or sets header pair.
     * 
     * Ignores header if it's value satisfies empty().
     * 
     * @param string $name  The HTTP header name.
     * @param string $value The HTTP header value.
     * 
     * @return none
     */
    public function addOptionalHeader($name, $value)
    {
        Validate::isString($name, 'name');
        Validate::isString($value, 'value');
        
        if (!empty($value)) {
            $this->_headers[$name] = $value;
        }
    }
    
    /**
     * Removes header from the HTTP request headers.
     * 
     * @param string $name The HTTP header name.
     * 
     * @return none
     */
    public function removeHeader($name)
    {
        Validate::isString($name, 'name');
        Validate::notNullOrEmpty($name, 'name');
        
        unset($this->_headers[$name]);
    }
    
    /**
     * Adds or sets query parameter pair.
     * 
     * @param string $name  The URI query parameter name.
     * @param string $value The URI query parameter value.
     * 
     * @return none
     */
    public function addQueryParameter($name, $value)
    {
        Validate::isString($name, 'name');
        Validate::isString($value, 'value');
        
        $this->_queryParams[$name] = $value;
    }
    
    /** 
     * Gets HTTP POST parameters. 
     *
     * @return array
     */
    public function getPostParameters()
    {   
        return $this->_postParameters;
    }

    /** 
     * Sets HTTP POST parameters.
     * 
     * @param array $postParameters The HTTP POST parameters.
     * 
     * @return none
     */
    public function setPostParameters($postParameters)
    {
        Validate::isArray($postParameters, 'postParameters');
        $this->_postParameters = $postParameters;
    }
    
    /**
     * Adds or sets query parameter pair.
     * 
     * Ignores query parameter if it's value satisfies empty().
     * 
     * @param string $name  The URI query parameter name.
     * @param string $value The URI query parameter value.
     * 
     * @return none
     */
    public function addOptionalQueryParameter($name, $value)
    {
        Validate::isString($name, 'name');
        Validate::isString($value, 'value');
        
        if (!empty($value)) {
            $this->_queryParams[$name] = $value;
        }
    }
    
    /**
     * Adds status code to the expected status codes.
     * 
     * @param integer $statusCode The expected status code.
     * 
     * @return none
     */
    public function addStatusCode($statusCode)
    {
        Validate::isInteger($statusCode, 'statusCode');
        
        $this->_statusCodes[] = $statusCode;
    }
    
    /**
     * Gets header value.
     * 
     * @param string $name The header name.
     * 
     * @return mix
     */
    public function getHeader($name)
    {
        return Utilities::tryGetValue($this->_headers, $name);
    }
    
    /**
     * Converts the context object to string.
     * 
     * @return string 
     */
    public function __toString()
    {
        $headers = Resources::EMPTY_STRING;
        $uri     = new Url($this->_uri);
        $uri     = $uri->getUrl();
        
        foreach ($this->_headers as $key => $value) {
            $headers .= "$key: $value\n";
        }
        
        $str  = "$this->_method $uri$this->_path HTTP/1.1\n$headers\n";
        $str .= "$this->_body";
        
        return $str;
    }
}


Internal/Http/IUrl.php000060400000005614152440043010010616 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Http;

/**
 * Defines what are main url functionalities that should be supported
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Http
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
interface IUrl
{
    /**
     * Returns the query portion of the url
     * 
     * @return string
     */
    public function getQuery();

    /**
     * Returns the query portion of the url in array form
     * 
     * @return array
     */
    public function getQueryVariables();
    
    /**
     * Sets a an existing query parameter to value or creates a new one if the $key
     * doesn't exist.
     * 
     * @param string $key   query parameter name.
     * @param string $value query value.
     * 
     * @return none.
     */
    public function setQueryVariable($key, $value);
    
    /**
     * Gets actual URL string.
     * 
     * @return string.
     */
    public function getUrl();
    
    /**
     * Sets url path
     * 
     * @param string $urlPath url path to set.
     * 
     * @return none.
     */
    public function setUrlPath($urlPath);
    
    /**
     * Appends url path
     * 
     * @param string $urlPath url path to append.
     * 
     * @return none.
     */
    public function appendUrlPath($urlPath);
    
    /**
     * Gets actual URL string.
     * 
     * @return string.
     */
    public function __toString();
    
    /**
     * Makes deep copy from the current object.
     * 
     * @return WindowsAzure\Common\Internal\Http\Url
     */
    public function __clone();
    
    /**
     * Sets the query string to the specified variables in $array
     * 
     * @param array $array key/value representation of query variables.
     * 
     * @return none.
     */
    public function setQueryVariables($array);
}


Internal/OAuthRestProxy.php000060400000007070152440043010011742 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\ServiceRestProxy;
use WindowsAzure\Common\Models\OAuthAccessToken;
use WindowsAzure\Common\Internal\Serialization\JsonSerializer;

/**
 * OAuth rest proxy.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class OAuthRestProxy extends ServiceRestProxy
{
    /**
     * Initializes new OAuthRestProxy object.
     *
     * @param IHttpClient $channel The HTTP client used to send HTTP requests.
     * @param string      $uri     The storage account uri.
     */
    public function __construct($channel, $uri)
    {
        parent::__construct(
            $channel,
            $uri,
            Resources::EMPTY_STRING,
            new JsonSerializer()
        );
    }


    /**
     * Get OAuth access token.
     *
     * @param string $grantType    OAuth request grant_type field value.
     * @param string $clientId     OAuth request clent_id field value.
     * @param string $clientSecret OAuth request clent_secret field value.
     * @param string $scope        OAuth request scope field value.
     *
     * @return WindowsAzure\Common\Internal\Models\OAuthAccessToken
     */
    public function getAccessToken($grantType, $clientId, $clientSecret, $scope)
    {
        $method         = Resources::HTTP_POST;
        $headers        = array();
        $queryParams    = array();
        $postParameters = array();
        $statusCode     = Resources::STATUS_OK;

        $postParameters = $this->addPostParameter(
            $postParameters,
            Resources::OAUTH_GRANT_TYPE,
            $grantType
        );

        $postParameters = $this->addPostParameter(
            $postParameters,
            Resources::OAUTH_CLIENT_ID,
            $clientId
        );

        $postParameters = $this->addPostParameter(
            $postParameters,
            Resources::OAUTH_CLIENT_SECRET,
            $clientSecret
        );

        $postParameters = $this->addPostParameter(
            $postParameters,
            Resources::OAUTH_SCOPE,
            $scope
        );

        $response = $this->send(
            $method,
            $headers,
            $queryParams,
            $postParameters,
            Resources::EMPTY_STRING,
            $statusCode
        );

        return OAuthAccessToken::create(
            $this->dataSerializer->unserialize($response->getBody())
        );
    }
}


Internal/Authentication/OAuthScheme.php000060400000010450152440043010014142 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      http://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Authentication;
use WindowsAzure\Common\Internal\Authentication\IAuthScheme;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\OAuthRestProxy;
use WindowsAzure\Common\Models\OAuthAccessToken;

/**
 * Provides shared key authentication scheme for OAuth.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      http://github.com/windowsazure/azure-sdk-for-php
 */
class OAuthScheme implements IAuthScheme
{
    /**
     * @var string
     */
    protected $accountName;

    /**
     * @var string
     */
    protected $accountKey;

    /**
     * @var WindowsAzure\Common\Models\OAuthAccessToken
     */
    protected $accessToken;

    /**
     * @var WindowsAzure\Common\Internal\OAuthRestProxy
     */
    protected $oauthService;

    /**
     * @var string
     */
    protected $grantType;

    /**
     * @var string
     */
    protected $scope;

    /**
     * Constructor.
     *
     * @param string                                      $accountName  account name.
     * @param string                                      $accountKey   account
     * secondary key.
     *
     * @param string                                      $grantType    grant type
     * for OAuth request.
     *
     * @param string                                      $scope        scope for
     * OAurh request.
     *
     * @param WindowsAzure\Common\Internal\OAuthRestProxy $oauthService account
     * primary or secondary key.
     */
    public function __construct(
        $accountName,
        $accountKey,
        $grantType,
        $scope,
        $oauthService
    ) {
        Validate::isString($accountName, 'accountName');
        Validate::isString($accountKey, 'accountKey');
        Validate::isString($grantType, 'grantType');
        Validate::isString($scope, 'scope');
        Validate::notNull($oauthService, 'oauthService');

        $this->accountName  = $accountName;
        $this->accountKey   = $accountKey;
        $this->grantType    = $grantType;
        $this->scope        = $scope;
        $this->oauthService = $oauthService;
    }

    /**
     * Returns authorization header to be included in the request.
     *
     * @param array  $headers     request headers.
     * @param string $url         reuqest url.
     * @param array  $queryParams query variables.
     * @param string $httpMethod  request http method.
     *
     * @see Specifying the Authorization Header section at
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     *
     * @return string
     */
    public function getAuthorizationHeader($headers, $url, $queryParams, $httpMethod)
    {
        if (($this->accessToken == null)
            || ($this->accessToken->getExpiresIn() < time())
        ) {
            $this->accessToken = $this->oauthService->getAccessToken(
                $this->grantType,
                $this->accountName,
                $this->accountKey,
                $this->scope
            );
        }

        return Resources::OAUTH_ACCESS_TOKEN_PREFIX .
            $this->accessToken->getAccessToken();
    }
}

Internal/Authentication/.htaccess000044400000000424152440043010013064 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Internal/Authentication/SharedKeyAuthScheme.php000060400000011570152440043010015627 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Authentication;
use WindowsAzure\Common\Internal\Authentication\StorageAuthScheme;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Provides shared key authentication scheme for blob and queue. For more info
 * check: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class SharedKeyAuthScheme extends StorageAuthScheme
{
    protected $includedHeaders;

    /**
     * Constructor.
     *
     * @param string $accountName storage account name.
     * @param string $accountKey  storage account primary or secondary key.
     * 
     * @return 
     * WindowsAzure\Common\Internal\Authentication\SharedKeyAuthScheme
     */
    public function __construct($accountName, $accountKey)
    {
        parent::__construct($accountName, $accountKey);

        $this->includedHeaders   = array();
        $this->includedHeaders[] = Resources::CONTENT_ENCODING;
        $this->includedHeaders[] = Resources::CONTENT_LANGUAGE;
        $this->includedHeaders[] = Resources::CONTENT_LENGTH;
        $this->includedHeaders[] = Resources::CONTENT_MD5;
        $this->includedHeaders[] = Resources::CONTENT_TYPE;
        $this->includedHeaders[] = Resources::DATE;
        $this->includedHeaders[] = Resources::IF_MODIFIED_SINCE;
        $this->includedHeaders[] = Resources::IF_MATCH;
        $this->includedHeaders[] = Resources::IF_NONE_MATCH;
        $this->includedHeaders[] = Resources::IF_UNMODIFIED_SINCE;
        $this->includedHeaders[] = Resources::RANGE;
    }

    /**
     * Computes the authorization signature for blob and queue shared key.
     *
     * @param array  $headers     request headers.
     * @param string $url         reuqest url.
     * @param array  $queryParams query variables.
     * @param string $httpMethod  request http method.
     * 
     * @see Blob and Queue Services (Shared Key Authentication) at
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     * 
     * @return string
     */
    protected function computeSignature($headers, $url, $queryParams, $httpMethod)
    {
        $canonicalizedHeaders = parent::computeCanonicalizedHeaders($headers);
        
        $canonicalizedResource = parent::computeCanonicalizedResource(
            $url, $queryParams
        );
        

        $stringToSign   = array();
        $stringToSign[] = strtoupper($httpMethod);

        foreach ($this->includedHeaders as $header) {
            $stringToSign[] = Utilities::tryGetValue($headers, $header);
        }

        if (count($canonicalizedHeaders) > 0) {
            $stringToSign[] = implode("\n", $canonicalizedHeaders);
        }

        $stringToSign[] = $canonicalizedResource;
        $stringToSign   = implode("\n", $stringToSign);

        return $stringToSign;
    }
    
    /**
     * Returns authorization header to be included in the request.
     *
     * @param array  $headers     request headers.
     * @param string $url         reuqest url.
     * @param array  $queryParams query variables.
     * @param string $httpMethod  request http method.
     * 
     * @see Specifying the Authorization Header section at 
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     * 
     * @return string
     */
    public function getAuthorizationHeader($headers, $url, $queryParams, $httpMethod)
    {
        $signature = $this->computeSignature(
            $headers, $url, $queryParams, $httpMethod
        );

        return 'SharedKey ' . $this->accountName . ':' . base64_encode(
            hash_hmac('sha256', $signature, base64_decode($this->accountKey), true)
        );
    }
}


Internal/Authentication/StorageAuthScheme.php000060400000017106152440043010015355 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Authentication;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Authentication\IAuthScheme;


/**
 * Base class for azure authentication schemes.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
abstract class StorageAuthScheme implements IAuthScheme
{
    protected $accountName;
    protected $accountKey;

    /**
     * Constructor.
     *
     * @param string $accountName storage account name.
     * @param string $accountKey  storage account primary or secondary key.
     *
     * @return
     * WindowsAzure\Common\Internal\Authentication\StorageAuthScheme
     */
    public function __construct($accountName, $accountKey)
    {
        $this->accountKey  = $accountKey;
        $this->accountName = $accountName;
    }

    /**
     * Computes canonicalized headers for headers array.
     *
     * @param array $headers request headers.
     *
     * @see Constructing the Canonicalized Headers String section at
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     *
     * @return array
     */
    protected function computeCanonicalizedHeaders($headers)
    {
        $canonicalizedHeaders = array();
        $normalizedHeaders    = array();
        $validPrefix          =  Resources::X_MS_HEADER_PREFIX;

        if (is_null($normalizedHeaders)) {
            return $canonicalizedHeaders;
        }

        foreach ($headers as $header => $value) {
            // Convert header to lower case.
            $header = strtolower($header);

            // Retrieve all headers for the resource that begin with x-ms-,
            // including the x-ms-date header.
            if (Utilities::startsWith($header, $validPrefix)) {
                // Unfold the string by replacing any breaking white space
                // (meaning what splits the headers, which is \r\n) with a single
                // space.
                $value = str_replace("\r\n", ' ', $value);

                // Trim any white space around the colon in the header.
                $value  = ltrim($value);
                $header = rtrim($header);

                $normalizedHeaders[$header] = $value;
            }
        }

        // Sort the headers lexicographically by header name, in ascending order.
        // Note that each header may appear only once in the string.
        ksort($normalizedHeaders);

        foreach ($normalizedHeaders as $key => $value) {
            $canonicalizedHeaders[] = $key . ':' . $value;
        }

        return $canonicalizedHeaders;
    }

    /**
     * Computes canonicalized resources from URL using Table formar
     *
     * @param string $url         request url.
     * @param array  $queryParams request query variables.
     *
     * @see Constructing the Canonicalized Resource String section at
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     *
     * @return string
     */
    protected function computeCanonicalizedResourceForTable($url, $queryParams)
    {
        $queryParams = array_change_key_case($queryParams);

        // 1. Beginning with an empty string (""), append a forward slash (/),
        //    followed by the name of the account that owns the accessed resource.
        $canonicalizedResource = '/' . $this->accountName;

        // 2. Append the resource's encoded URI path, without any query parameters.
        $canonicalizedResource .= parse_url($url, PHP_URL_PATH);

        // 3. The query string should include the question mark and the comp
        //    parameter (for example, ?comp=metadata). No other parameters should
        //    be included on the query string.
        if (array_key_exists(Resources::QP_COMP, $queryParams)) {
            $canonicalizedResource .= '?' . Resources::QP_COMP . '=';
            $canonicalizedResource .= $queryParams[Resources::QP_COMP];
        }

        return $canonicalizedResource;
    }

    /**
     * Computes canonicalized resources from URL.
     *
     * @param string $url         request url.
     * @param array  $queryParams request query variables.
     *
     * @see Constructing the Canonicalized Resource String section at
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     *
     * @return string
     */
    protected function computeCanonicalizedResource($url, $queryParams)
    {
        $queryParams = array_change_key_case($queryParams);

        // 1. Beginning with an empty string (""), append a forward slash (/),
        //    followed by the name of the account that owns the accessed resource.
        $canonicalizedResource = '/' . $this->accountName;

        // 2. Append the resource's encoded URI path, without any query parameters.
        $canonicalizedResource .= parse_url($url, PHP_URL_PATH);

        // 3. Retrieve all query parameters on the resource URI, including the comp
        //    parameter if it exists.
        // 4. Sort the query parameters lexicographically by parameter name, in
        //    ascending order.
        if (count($queryParams) > 0) {
            ksort($queryParams);
        }

        // 5. Convert all parameter names to lowercase.
        // 6. URL-decode each query parameter name and value.
        // 7. Append each query parameter name and value to the string in the
        //    following format:
        //      parameter-name:parameter-value
        // 9. Group query parameters
        // 10. Append a new line character (\n) after each name-value pair.
        foreach ($queryParams as $key => $value) {
            // Grouping query parameters
            $values = explode(Resources::SEPARATOR, $value);
            sort($values);
            $separated = implode(Resources::SEPARATOR, $values);

            $canonicalizedResource .= "\n" . $key . ':' . $separated;
        }

        return $canonicalizedResource;
    }

    /**
     * Computes the authorization signature.
     *
     * @param array  $headers     request headers.
     * @param string $url         reuqest url.
     * @param array  $queryParams query variables.
     * @param string $httpMethod  request http method.
     *
     * @see check all authentication schemes at
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     *
     * @abstract
     *
     * @return string
     */
    abstract protected function computeSignature($headers, $url, $queryParams,
        $httpMethod
    );
}


Internal/Authentication/IAuthScheme.php000060400000003715152440043010014142 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Authentication;

/**
 * Interface for azure authentication schemes.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
interface IAuthScheme
{
    /**
     * Returns authorization header to be included in the request.
     *
     * @param array  $headers     request headers.
     * @param string $url         reuqest url.
     * @param array  $queryParams query variables.
     * @param string $httpMethod  request http method.
     *
     * @see Specifying the Authorization Header section at
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     *
     * @abstract
     *
     * @return string
     */
    public function getAuthorizationHeader($headers, $url, $queryParams,
        $httpMethod
    );
}


Internal/Authentication/TableSharedKeyLiteAuthScheme.php000060400000007770152440043010017424 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      http://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal\Authentication;
use WindowsAzure\Common\Internal\Authentication\StorageAuthScheme;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Provides shared key authentication scheme for blob and queue. For more info
 * check: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Authentication
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      http://github.com/windowsazure/azure-sdk-for-php
 */
class TableSharedKeyLiteAuthScheme extends StorageAuthScheme
{
    protected $includedHeaders;

    /**
     * Constructor.
     *
     * @param string $accountName storage account name.
     * @param string $accountKey  storage account primary or secondary key.
     * 
     * @return TableSharedKeyLiteAuthScheme
     */
    public function __construct($accountName, $accountKey)
    {
        parent::__construct($accountName, $accountKey);

        $this->includedHeaders   = array();
        $this->includedHeaders[] = Resources::DATE;
    }

    /**
     * Computes the authorization signature for blob and queue shared key.
     *
     * @param array  $headers     request headers.
     * @param string $url         reuqest url.
     * @param array  $queryParams query variables.
     * @param string $httpMethod  request http method.
     * 
     * @see Blob and Queue Services (Shared Key Authentication) at
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     * 
     * @return string
     */
    protected function computeSignature($headers, $url, $queryParams, $httpMethod)
    {
        $canonicalizedResource = parent::computeCanonicalizedResourceForTable(
            $url, $queryParams
        );
        
        $stringToSign = array();

        foreach ($this->includedHeaders as $header) {
            $stringToSign[] = Utilities::tryGetValue($headers, $header);
        }

        $stringToSign[] = $canonicalizedResource;
        $stringToSign   = implode("\n", $stringToSign);
        
        return $stringToSign;
    }
    
    /**
     * Returns authorization header to be included in the request.
     *
     * @param array  $headers     request headers.
     * @param string $url         reuqest url.
     * @param array  $queryParams query variables.
     * @param string $httpMethod  request http method.
     * 
     * @see Specifying the Authorization Header section at 
     *      http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx
     * 
     * @return string
     */
    public function getAuthorizationHeader($headers, $url, $queryParams, $httpMethod)
    {
        $signature = $this->computeSignature(
            $headers, $url, $queryParams, $httpMethod
        );

        return 'SharedKeyLite ' . $this->accountName . ':' . base64_encode(
            hash_hmac('sha256', $signature, base64_decode($this->accountKey), true)
        );
    }
}


Internal/Validate.php000060400000025236152440043010010557 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\InvalidArgumentTypeException;
use WindowsAzure\Common\Internal\Resources;

/**
 * Validates aganist a condition and throws an exception in case of failure.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class Validate
{
    /**
     * Throws exception if the provided variable type is not array.
     *
     * @param mix    $var  The variable to check.
     * @param string $name The parameter name.
     *
     * @throws InvalidArgumentTypeException.
     *
     * @return none
     */
    public static function isArray($var, $name)
    {
        if (!is_array($var)) {
            throw new InvalidArgumentTypeException(gettype(array()), $name);
        }
    }

    /**
     * Throws exception if the provided variable type is not string.
     *
     * @param mix    $var  The variable to check.
     * @param string $name The parameter name.
     *
     * @throws InvalidArgumentTypeException
     *
     * @return none
     */
    public static function isString($var, $name)
    {
        try {
            (string)$var;
        } catch (\Exception $e) {
            throw new InvalidArgumentTypeException(gettype(''), $name);
        }
    }

    /**
     * Throws exception if the provided variable type is not boolean.
     *
     * @param mix $var variable to check against.
     *
     * @throws InvalidArgumentTypeException
     *
     * @return none
     */
    public static function isBoolean($var)
    {
        (bool)$var;
    }

    /**
     * Throws exception if the provided variable is set to null.
     *
     * @param mix    $var  The variable to check.
     * @param string $name The parameter name.
     *
     * @throws \InvalidArgumentException
     *
     * @return none
     */
    public static function notNullOrEmpty($var, $name)
    {
        if (is_null($var) || empty($var)) {
            throw new \InvalidArgumentException(
                sprintf(Resources::NULL_OR_EMPTY_MSG, $name)
            );
        }
    }

    /**
     * Throws exception if the provided variable is not double.
     *
     * @param mix    $var  The variable to check.
     * @param string $name The parameter name.
     *
     * @throws \InvalidArgumentException
     *
     * @return none
     */
    public static function isDouble($var, $name)
    {
        if (!is_numeric($var)) {
            throw new InvalidArgumentTypeException('double', $name);
        }
    }

    /**
     * Throws exception if the provided variable type is not integer.
     *
     * @param mix    $var  The variable to check.
     * @param string $name The parameter name.
     *
     * @throws InvalidArgumentTypeException
     *
     * @return none
     */
    public static function isInteger($var, $name)
    {
        try {
            (int)$var;
        } catch (\Exception $e) {
            throw new InvalidArgumentTypeException(gettype(123), $name);
        }
    }

    /**
     * Returns whether the variable is an empty or null string.
     *
     * @param string $var value.
     *
     * @return boolean
     */
    public static function isNullOrEmptyString($var)
    {
        try {
            (string)$var;
        } catch (\Exception $e) {
            return false;
        }

        return (!isset($var) || trim($var)==='');
    }

    /**
     * Throws exception if the provided condition is not satisfied.
     *
     * @param bool   $isSatisfied    condition result.
     * @param string $failureMessage the exception message
     *
     * @throws \Exception
     *
     * @return none
     */
    public static function isTrue($isSatisfied, $failureMessage)
    {
        if (!$isSatisfied) {
            throw new \InvalidArgumentException($failureMessage);
        }
    }

    /**
     * Throws exception if the provided $date is not of type \DateTime
     *
     * @param mix $date variable to check against.
     *
     * @throws WindowsAzure\Common\Internal\InvalidArgumentTypeException
     *
     * @return none
     */
    public static function isDate($date)
    {
        if (gettype($date) != 'object' || get_class($date) != 'DateTime') {
            throw new InvalidArgumentTypeException('DateTime');
        }
    }

    /**
     * Throws exception if the provided variable is set to null.
     *
     * @param mix    $var  The variable to check.
     * @param string $name The parameter name.
     *
     * @throws \InvalidArgumentException
     *
     * @return none
     */
    public static function notNull($var, $name)
    {
        if (is_null($var)) {
            throw new \InvalidArgumentException(sprintf(Resources::NULL_MSG, $name));
        }
    }

    /**
     * Throws exception if the object is not of the specified class type.
     *
     * @param mixed  $objectInstance An object that requires class type validation.
     * @param mixed  $classInstance  The instance of the class the the
     * object instance should be.
     * @param string $name           The name of the object.
     *
     * @throws \InvalidArgumentException
     *
     * @return none
     */
    public static function isInstanceOf($objectInstance, $classInstance, $name)
    {
        Validate::notNull($classInstance, 'classInstance');
        if (is_null($objectInstance)) {
            return true;
        }

        $objectType = gettype($objectInstance);
        $classType  = gettype($classInstance);

        if ($objectType === $classType) {
            return true;
        } else {
            throw new \InvalidArgumentException(
                sprintf(
                    Resources::INSTANCE_TYPE_VALIDATION_MSG,
                    $name,
                    $objectType,
                    $classType
                )
            );
        }
    }

    /**
     * Creates a anonymous function that check if the given uri is valid or not.
     *
     * @return callable
     */
    public static function getIsValidUri()
    {
        return function ($uri) {
            return Validate::isValidUri($uri);
        };
    }

    /**
     * Throws exception if the string is not of a valid uri.
     *
     * @param string $uri String to check.
     *
     * @throws \InvalidArgumentException
     *
     * @return boolean
     */
    public static function isValidUri($uri)
    {
        $isValid = filter_var($uri, FILTER_VALIDATE_URL);

        if ($isValid) {
            return true;
        } else {
            throw new \RuntimeException(
                sprintf(Resources::INVALID_CONFIG_URI, $uri)
            );
        }
    }

    /**
     * Throws exception if the provided variable type is not object.
     *
     * @param mix    $var  The variable to check.
     * @param string $name The parameter name.
     *
     * @throws InvalidArgumentTypeException.
     *
     * @return boolean
     */
    public static function isObject($var, $name)
    {
        if (!is_object($var)) {
            throw new InvalidArgumentTypeException('object', $name);
        }

        return true;
    }

    /**
     * Throws exception if the object is not of the specified class type.
     *
     * @param mixed  $objectInstance An object that requires class type validation.
     * @param string $class          The class the object instance should be.
     * @param string $name           The parameter name.
     *
     * @throws \InvalidArgumentException
     *
     * @return boolean
     */
    public static function isA($objectInstance, $class, $name)
    {
        Validate::isString($class, 'class');
        Validate::notNull($objectInstance, 'objectInstance');
        Validate::isObject($objectInstance, 'objectInstance');

        $objectType = get_class($objectInstance);

        if (is_a($objectInstance, $class)) {
            return true;
        } else {
            throw new \InvalidArgumentException(
                sprintf(
                    Resources::INSTANCE_TYPE_VALIDATION_MSG,
                    $name,
                    $objectType,
                    $class
                )
            );
        }
    }

    /**
     * Validate if method exists in object
     *
     * @param object $objectInstance An object that requires method existing
     *                               validation
     * @param string $method         Method name
     * @param string $name           The parameter name
     *
     * @return boolean
     */
    public static function methodExists($objectInstance, $method, $name)
    {
        Validate::isString($method, 'method');
        Validate::notNull($objectInstance, 'objectInstance');
        Validate::isObject($objectInstance, 'objectInstance');

        if (method_exists($objectInstance, $method)) {
            return true;
        } else {
            throw new \InvalidArgumentException(
                sprintf(
                    Resources::ERROR_METHOD_NOT_FOUND,
                    $method,
                    $name
                )
            );
        }
    }

    /**
     * Validate if string is date formatted
     *
     * @param string $value Value to validate
     * @param string $name  Name of parameter to insert in erro message
     *
     * @throws \InvalidArgumentException
     *
     * @return boolean
     */
    public static function isDateString($value, $name)
    {
        Validate::isString($value, 'value');

        try {
            new \DateTime($value);
            return true;
        }
        catch (\Exception $e) {
            throw new \InvalidArgumentException(
                sprintf(
                    Resources::ERROR_INVALID_DATE_STRING,
                    $name,
                    $value
                )
            );
        }
    }

}


Internal/Atom/Person.php000060400000012104152440043010011162 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;

/**
 * The person class of ATOM library.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class Person extends AtomBase
{
    /**
     * The name of the person. 
     *
     * @var string  
     */
    protected $name;

    /**
     * The Uri of the person. 
     *
     * @var string  
     */
    protected $uri;

    /**
     * The email of the person.
     *
     * @var string 
     */
    protected $email;
     
    /** 
     * Creates an ATOM person instance with specified name.
     *
     * @param string $name The name of the person.
     */
    public function __construct($name = Resources::EMPTY_STRING)
    {
        $this->name = $name;
    }

    /**
     * Populates the properties with a specified XML string. 
     * 
     * @param string $xmlString An XML based string representing 
     * the Person instance. 
     * 
     * @return none
     */
    public function parseXml($xmlString)
    {
        $personXml   = simplexml_load_string($xmlString);
        $attributes  = $personXml->attributes();
        $personArray = (array)$personXml;

        if (array_key_exists('name', $personArray)) {
            $this->name = (string)$personArray['name'];
        }

        if (array_key_exists('uri', $personArray)) {
            $this->uri = (string)$personArray['uri'];
        }

        if (array_key_exists('email', $personArray)) {
            $this->email = (string)$personArray['email'];
        }
    }

    /** 
     * Gets the name of the person. 
     *
     * @return string
     */
    public function getName()
    {   
        return $this->name;
    } 

    /**
     * Sets the name of the person.
     * 
     * @param string $name The name of the person.
     * 
     * @return none
     */
    public function setName($name)
    {
        $this->name = $name; 
    }

    /**
     * Gets the URI of the person. 
     * 
     * @return string
     */
    public function getUri()
    {
        return $this->uri;
    }

    /**
     * Sets the URI of the person. 
     * 
     * @param string $uri The URI of the person.
     * 
     * @return none
     */
    public function setUri($uri)
    {
        $this->uri = $uri;
    }

    
    /**
     * Gets the email of the person. 
     * 
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Sets the email of the person. 
     * 
     * @param string $email The email of the person.
     * 
     * @return none
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /** 
     * Writes an XML representing the person. 
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none
     */
    public function writeXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->startElementNS(
            'atom',
            'person',
            Resources::ATOM_NAMESPACE
        );
        $this->writeInnerXml($xmlWriter);
        $xmlWriter->endElement();
    }

    /** 
     * Writes a inner XML representing the person. 
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none
     */
    public function writeInnerXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->writeElementNS(
            'atom',
            'name', 
            Resources::ATOM_NAMESPACE,
            $this->name
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'uri', 
            Resources::ATOM_NAMESPACE,
            $this->uri
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'email', 
            Resources::ATOM_NAMESPACE,
            $this->email
        );
    }
}

Internal/Atom/Entry.php000060400000033006152440043010011021 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;

/**
 * The Entry class of ATOM standard.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class Entry extends AtomBase
{
    // @codingStandardsIgnoreStart

    /**
     * The author of the entry.
     *
     * @var Person
     */
    protected $author;

    /**
     * The category of the entry.
     *
     * @var array
     */
    protected $category;

    /**
     * The content of the entry.
     *
     * @var string
     */
    protected $content;

    /**
     * The contributor of the entry.
     *
     * @var string
     */
    protected $contributor;

    /**
     * An unqiue ID representing the entry.
     *
     * @var string
     */
    protected $id;

    /**
     * The link of the entry.
     *
     * @var string
     */
    protected $link;

    /**
     * Is the entry published.
     *
     * @var boolean
     */
    protected $published;

    /**
     * The copy right of the entry.
     *
     * @var string
     */
    protected $rights;

    /**
     * The source of the entry.
     *
     * @var string
     */
    protected $source;

    /**
     * The summary of the entry.
     *
     * @var string
     */
    protected $summary;

    /**
     * The title of the entry.
     *
     * @var string
     */
    protected $title;

    /**
     * Is the entry updated.
     *
     * @var \DateTime
     */
    protected $updated;

    /**
     * The extension element of the entry.
     *
     * @var string
     */
    protected $extensionElement;

    /**
     * Creates an ATOM Entry instance with default parameters.
     */
    public function __construct()
    {
        $this->attributes = array();
    }

    /**
     * Populate the properties of an ATOM Entry instance with specified XML..
     *
     * @param string $xmlString A string representing an ATOM entry instance.
     *
     * @return none
     */
    public function parseXml($xmlString)
    {
        Validate::notNull($xmlString, 'xmlString');

        $this->fromXml(simplexml_load_string($xmlString));
    }

    /**
     * Creates an ATOM ENTRY instance with specified simpleXML object
     *
     * @param \SimpleXMLElement $entryXml xml element of ATOM ENTRY
     *
     * @return none
     */
    public function fromXml($entryXml) {
        Validate::notNull($entryXml, 'entryXml');
        Validate::isA($entryXml, '\SimpleXMLElement', 'entryXml');

        $this->attributes = (array)$entryXml->attributes();
        $entryArray       = (array)$entryXml;

        if (array_key_exists(Resources::AUTHOR, $entryArray)) {
            $this->author = $this->processAuthorNode($entryArray);
        }

        if (array_key_exists(Resources::CATEGORY, $entryArray)) {
            $this->category = $this->processCategoryNode($entryArray);
        }

        if (array_key_exists('content', $entryArray)) {
            $content = new Content();
            $content->fromXml($entryArray['content']);
            $this->content = $content;
        }

        if (array_key_exists(Resources::CONTRIBUTOR, $entryArray)) {
            $this->contributor = $this->processContributorNode($entryArray);
        }

        if (array_key_exists('id', $entryArray)) {
            $this->id = (string)$entryArray['id'];
        }

        if (array_key_exists(Resources::LINK, $entryArray)) {
            $this->link = $this->processLinkNode($entryArray);
        }

        if (array_key_exists('published', $entryArray)) {
            $this->published = $entryArray['published'];
        }

        if (array_key_exists('rights', $entryArray)) {
            $this->rights = $entryArray['rights'];
        }

        if (array_key_exists('source', $entryArray)) {
            $source = new Source();
            $source->parseXml($entryArray['source']->asXML());
            $this->source = $source;
        }

        if (array_key_exists('title', $entryArray)) {
            $this->title = $entryArray['title'];
        }

        if (array_key_exists('updated', $entryArray)) {
            $this->updated = \DateTime::createFromFormat(
                \DateTime::ATOM,
                (string)$entryArray['updated']
            );
        }
    }

    /**
     * Gets the author of the entry.
     *
     * @return Person
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Sets the author of the entry.
     *
     * @param Person $author The author of the entry.
     *
     * @return none
     */
    public function setAuthor($author)
    {
        $this->author = $author;
    }

    /**
     * Gets the category.
     *
     * @return array
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Sets the category.
     *
     * @param string $category The category of the entry.
     *
     * @return none
     */
    public function setCategory($category)
    {
        $this->category = $category;
    }

    /**
     * Gets the content.
     *
     * @return Content.
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Sets the content.
     *
     * @param Content $content Sets the content of the entry.
     *
     * @return none
     */
    public function setContent($content)
    {
        $this->content = $content;
    }

    /**
     * Gets the contributor.
     *
     * @return string
     */
    public function getContributor()
    {
        return $this->contributor;
    }

    /**
     * Sets the contributor.
     *
     * @param string $contributor The contributor of the entry.
     *
     * @return none
     */
    public function setContributor($contributor)
    {
        $this->contributor = $contributor;
    }

    /**
     * Gets the ID of the entry.
     *
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Sets the ID of the entry.
     *
     * @param string $id The id of the entry.
     *
     * @return none
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Gets the link of the entry.
     *
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * Sets the link of the entry.
     *
     * @param string $link The link of the entry.
     *
     * @return none
     */
    public function setLink($link)
    {
        $this->link = $link;
    }

    /**
     * Gets published of the entry.
     *
     * @return boolean
     */
    public function getPublished()
    {
        return $this->published;
    }

    /**
     * Sets published of the entry.
     *
     * @param boolean $published Is the entry published.
     *
     * @return none
     */
    public function setPublished($published)
    {
        $this->published = $published;
    }

    /**
     * Gets the rights of the entry.
     *
     * @return string
     */
    public function getRights()
    {
        return $this->rights;
    }

    /**
     * Sets the rights of the entry.
     *
     * @param string $rights The rights of the entry.
     *
     * @return none
     */
    public function setRights($rights)
    {
        $this->rights = $rights;
    }

    /**
     * Gets the source of the entry.
     *
     * @return string
     */
    public function getSource()
    {
        return $this->source;
    }

    /**
     * Sets the source of the entry.
     *
     * @param string $source The source of the entry.
     *
     * @return none
     */
    public function setSource($source)
    {
        $this->source = $source;
    }

    /**
     * Gets the summary of the entry.
     *
     * @return string
     */
    public function getSummary()
    {
        return $this->summary;
    }

    /**
     * Sets the summary of the entry.
     *
     * @param string $summary The summary of the entry.
     *
     * @return none
     */
    public function setSummary($summary)
    {
        $this->summary = $summary;
    }

    /**
     * Gets the title of the entry.
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Sets the title of the entry.
     *
     * @param string $title The title of the entry.
     *
     * @return none
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Gets updated.
     *
     * @return \DateTime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Sets updated
     *
     * @param \DateTime $updated updated.
     *
     * @return none
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;
    }

    /**
     * Gets extension element.
     *
     * @return string
     */
    public function getExtensionElement()
    {
        return $this->extensionElement;
    }

    /**
     * Sets extension element.
     *
     * @param string $extensionElement The extension element of the entry.
     *
     * @return none
     */
    public function setExtensionElement($extensionElement)
    {
        $this->extensionElement = $extensionElement;
    }

    /**
     * Writes a inner XML string representing the entry.
     *
     * @param \XMLWriter $xmlWriter The XML writer.
     *
     * @return none
     */
    public function writeXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->startElementNS(
            'atom',
            Resources::ENTRY,
            Resources::ATOM_NAMESPACE
        );
        $this->writeInnerXml($xmlWriter);
        $xmlWriter->endElement();
    }

    /**
     * Writes a inner XML string representing the entry.
     *
     * @param \XMLWriter $xmlWriter The XML writer.
     *
     * @return none
     */
    public function writeInnerXml($xmlWriter)
    {
        if (!is_null($this->attributes)) {
            if (is_array($this->attributes)) {
                foreach (
                    $this->attributes
                    as $attributeName => $attributeValue
                ) {
                    $xmlWriter->writeAttribute($attributeName, $attributeValue);
                }
            }
        }

        if (!is_null($this->author)) {
            $this->writeArrayItem(
                $xmlWriter,
                $this->author,
                Resources::AUTHOR
            );
        }

        if (!is_null($this->category)) {
            $this->writeArrayItem(
                $xmlWriter,
                $this->category,
                Resources::CATEGORY
            );
        }

        if (!is_null($this->content)) {
            $this->content->writeXml($xmlWriter);
        }

        if (!is_null($this->contributor)) {
            $this->writeArrayItem(
                $xmlWriter,
                $this->contributor,
                Resources::CONTRIBUTOR
            );
        }

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'id',
            Resources::ATOM_NAMESPACE,
            $this->id
        );

        if (!is_null($this->link)) {
            $this->writeArrayItem(
                $xmlWriter,
                $this->link,
                Resources::LINK
            );
        }

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'published',
            Resources::ATOM_NAMESPACE,
            $this->published
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'rights',
            Resources::ATOM_NAMESPACE,
            $this->rights
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'source',
            Resources::ATOM_NAMESPACE,
            $this->source
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'summary',
            Resources::ATOM_NAMESPACE,
            $this->summary
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'title',
            Resources::ATOM_NAMESPACE,
            $this->title
        );

        if (!is_null($this->updated)) {
            $xmlWriter->writeElementNS(
                'atom',
                'updated',
                Resources::ATOM_NAMESPACE,
                $this->updated->format(\DateTime::ATOM)
            );
        }
    }
}

// @codingStandardsIgnoreEndInternal/Atom/Source.php000060400000033230152440043010011157 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Resources;

/**
 * The source class of ATOM library.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class Source extends AtomBase
{
    // @codingStandardsIgnoreStart
    
    /**
     * The author the source. 
     * 
     * @var array
     */
    protected $author;

    /**
     * The category of the source. 
     * 
     * @var array
     */
    protected $category;

    /**
     * The contributor of the source. 
     * 
     * @var array
     */
    protected $contributor;

    /**
     * The generator of the source. 
     * 
     * @var Generator
     */
    protected $generator;

    /**
     * The icon of the source. 
     * 
     * @var string
     */
    protected $icon;

    /**
     * The ID of the source. 
     * 
     * @var string
     */
    protected $id;

    /**
     * The link of the source. 
     * 
     * @var AtomLink
     */
    protected $link;

    /**
     * The logo of the source. 
     * 
     * @var string
     */
    protected $logo;

    /**
     * The rights of the source. 
     * 
     * @var string
     */
    protected $rights;

    /**
     * The subtitle of the source. 
     * 
     * @var string
     */
    protected $subtitle;

    /**
     * The title of the source. 
     * 
     * @var string
     */
    protected $title;

    /**
     * The update of the source. 
     * 
     * @var \DateTime
     */
    protected $updated;

    /**
     * The extension element of the source. 
     * 
     * @var string
     */
    protected $extensionElement;

    /**
     * Creates an ATOM FEED object with default parameters. 
     */ 
    public function __construct()
    {   
        $this->attributes  = array();
        $this->category    = array();
        $this->contributor = array();
        $this->author      = array();
    }

    /**
     * Creates a source object with specified XML string. 
     * 
     * @param string $xmlString The XML string representing a source.
     *
     * @return none
     */
    public function parseXml($xmlString)
    {
        $sourceXml   = new \SimpleXMLElement($xmlString);
        $attributes  = $sourceXml->attributes();
        $sourceArray = (array)$sourceXml;

        if (array_key_exists(Resources::AUTHOR, $sourceArray)) {
            $this->content = $this->processAuthorNode($sourceArray);
        }

        if (array_key_exists(Resources::CATEGORY, $sourceArray)) {
            $this->category = $this->processCategoryNode($sourceArray);
        }

        if (array_key_exists(Resources::CONTRIBUTOR, $sourceArray)) {
            $this->contributor = $this->processContributorNode($sourceArray);
        }

        if (array_key_exists('generator', $sourceArray)) {
            $generator = new Generator();
            $generator->setText((string)$sourceArray['generator']->asXML());
            $this->generator = $generator;
        } 

        if (array_key_exists('icon', $sourceArray)) {
            $this->icon = (string)$sourceArray['icon'];
        }

        if (array_key_exists('id', $sourceArray)) {
            $this->id = (string)$sourceArray['id'];
        }

        if (array_key_exists(Resources::LINK, $sourceArray)) {
            $this->link = $this->processLinkNode($sourceArray);
        }

        if (array_key_exists('logo', $sourceArray)) {
            $this->logo = (string)$sourceArray['logo'];
        }

        if (array_key_exists('rights', $sourceArray)) {
            $this->rights = (string)$sourceArray['rights'];
        }

        if (array_key_exists('subtitle', $sourceArray)) {
            $this->subtitle = (string)$sourceArray['subtitle'];
        }

        if (array_key_exists('title', $sourceArray)) {
            $this->title = (string)$sourceArray['title'];
        }

        if (array_key_exists('updated', $sourceArray)) {
            $this->updated = \DateTime::createFromFormat(
                \DateTime::ATOM,
                (string)$sourceArray['updated']
            );
        }
    }

    /**
     * Gets the author of the source. 
     *
     * @return array
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Sets the author of the source. 
     *
     * @param array $author An array of authors of the sources. 
     * 
     * @return none
     */
    public function setAuthor($author) 
    {
        $this->author = $author;
    }

    /**
     * Gets the category of the source.
     *  
     * @return array
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Sets the category of the source.
     *  
     * @param array $category The category of the source. 
     *
     * @return none
     */
    public function setCategory($category)
    {
        $this->category = $category;
    }
   
    /**
     * Gets contributor.
     *
     * @return array
     */
    public function getContributor()
    {
        return $this->contributor;
    }

    /**
     * Sets contributor.
     * 
     * @param array $contributor The contributors of the source. 
     * 
     * @return none
     */
    public function setContributor($contributor)
    {
        $this->contributor = $contributor;
    }

    /**
     * Gets generator.
     * 
     * @return Generator
     */
    public function getGenerator()
    {
        return $this->generator;
    }

    /**
     * Sets the generator. 
     * 
     * @param Generator $generator Sets the generator of the source. 
     * 
     * @return none
     */
    public function setGenerator($generator)
    {
        $this->generator = $generator;
    }

    /**
     * Gets the icon of the source. 
     * 
     * @return string 
     */
    public function getIcon()
    {
        return $this->icon;
    }

    /**
     * Sets the icon of the source. 
     * 
     * @param string $icon The icon of the source. 
     * 
     * @return string   
     */
    public function setIcon($icon)
    {
        $this->icon = $icon;
    }

    /**
     * Gets the ID of the source. 
     * 
     * @return string   
     */ 
    public function getId()
    {   
        return $this->id;
    }

    /**
     * Sets the ID of the source.
     * 
     * @param string $id The ID of the source. 
     * 
     * @return string   
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Gets the link of the source. 
     * 
     * @return array
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * Sets the link of the source. 
     * 
     * @param array $link The link of the source. 
     *
     * @return none
     */
    public function setLink($link)
    {
        $this->link = $link;
    }

    /**
     * Gets the logo of the source. 
     * 
     * @return string 
     */
    public function getLogo()
    {
        return $this->logo;
    }

    /**
     * Sets the logo of the source. 
     * 
     * @param string $logo The logo of the source. 
     * 
     * @return none
     */
    public function setLogo($logo)
    {
        $this->logo = $logo;
    }

    /**
     * Gets the rights of the source. 
     * 
     * @return string 
     */
    public function getRights()
    {   
        return $this->rights;
    }

    /** 
     * Sets the rights of the source. 
     * 
     * @param string $rights The rights of the source. 
     * 
     * @return none 
     */
    public function setRights($rights)
    {
        $this->rights = $rights;
    }

    /**
     * Gets the sub title.  
     * 
     * @return string 
     */
    public function getSubtitle()
    {   
        return $this->subtitle;
    }

    /**
     * Sets the sub title of the source. 
     *
     * @param string $subtitle Sets the sub title of the source. 
     * 
     * @return none
     */
    public function setSubtitle($subtitle)
    {
        $this->subtitle = $subtitle;
    }

    /**
     * Gets the title of the source. 
     *
     * @return string. 
     */
    public function getTitle() 
    {   
        return $this->title;
    }

    /**
     * Sets the title of the source. 
     *
     * @param string $title The title of the source. 
     *
     * @return none
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Gets the updated. 
     * 
     * @return \DateTime
     */
    public function getUpdated()
    {   
        return $this->updated;
    }

    /**
     * Sets the updated. 
     * 
     * @param \DateTime $updated updated
     * 
     * @return none
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;
    }

    /** 
     * Gets the extension element. 
     * 
     * @return string 
     */
    public function getExtensionElement()
    {   
        return $this->extensionElement;
    }

    /**
     * Sets the extension element. 
     * 
     * @param string $extensionElement The extension element. 
     * 
     * @return none
     */
    public function setExtensionElement($extensionElement)
    {
        $this->extensionElement = $extensionElement;
    }

    /** 
     * Writes an XML representing the source object.
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none
     */
    public function writeXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->startElementNS(
            'atom', 
            'source', 
            Resources::ATOM_NAMESPACE
        );
        $this->writeInnerXml($xmlWriter);
        $xmlWriter->endElement();
    }
    /** 
     * Writes a inner XML representing the source object.
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none
     */
    public function writeInnerXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        if (!is_null($this->attributes)) {
            if (is_array($this->attributes)) {
                foreach ($this->attributes as $attributeName => $attributeValue) {
                    $xmlWriter->writeAttribute($attributeName, $attributeValue);
                }
            }
        }
         
        if (!is_null($this->author)) {
            Validate::isArray($this->author, Resources::AUTHOR);
            $this->writeArrayItem($xmlWriter, $this->author, Resources::AUTHOR);
        } 

        if (!is_null($this->category)) {
            Validate::isArray($this->category, Resources::CATEGORY);
            $this->writeArrayItem(
                $xmlWriter, 
                $this->category, 
                Resources::CATEGORY
            );
        }

        if (!is_null($this->contributor)) {
            Validate::isArray($this->contributor, Resources::CONTRIBUTOR);
            $this->writeArrayItem(
                $xmlWriter, 
                $this->contributor,
                Resources::CONTRIBUTOR
            );
        }

        if (!is_null($this->generator)) {
            $this->generator->writeXml($xmlWriter);
        } 

        if (!is_null($this->icon)) {
            $xmlWriter->writeElementNS(
                'atom',
                'icon', 
                Resources::ATOM_NAMESPACE,
                $this->icon
            );
        }

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'logo', 
            Resources::ATOM_NAMESPACE,
            $this->logo
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'id', 
            Resources::ATOM_NAMESPACE,
            $this->id
        );

        if (!is_null($this->link)) {
            Validate::isArray($this->link, Resources::LINK);
            $this->writeArrayItem(
                $xmlWriter, 
                $this->link,
                Resources::LINK
            );
        }

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'rights', 
            Resources::ATOM_NAMESPACE,
            $this->rights
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'subtitle', 
            Resources::ATOM_NAMESPACE,
            $this->subtitle
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'title', 
            Resources::ATOM_NAMESPACE,
            $this->title
        );

        if (!is_null($this->updated)) {
            $xmlWriter->writeElementNS(
                'atom',
                'updated', 
                Resources::ATOM_NAMESPACE,
                $this->updated->format(\DateTime::ATOM)
            );
        }
    }
}

// @codingStandardsIgnoreEndInternal/Atom/Feed.php000060400000037277152440043010010601 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Resources;

/**
 * The feed class of ATOM library.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class Feed extends AtomBase
{
    // @codingStandardsIgnoreStart
    
    /**
     * The entry of the feed. 
     * 
     * @var array
     */
    protected $entry;

    /**
     * the author of the feed. 
     * 
     * @var array 
     */
    protected $author;

    /**
     * The category of the feed. 
     * 
     * @var array 
     */
    protected $category;

    /**
     * The contributor of the feed. 
     * 
     * @var array 
     */
    protected $contributor;

    /**
     * The generator of the feed. 
     * 
     * @var Generator
     */
    protected $generator;

    /**
     * The icon of the feed. 
     * 
     * @var string
     */
    protected $icon;

    /**
     * The ID of the feed. 
     * 
     * @var string
     */
    protected $id;

    /**
     * The link of the feed. 
     * 
     * @var array
     */
    protected $link;

    /**
     * The logo of the feed. 
     * 
     * @var string
     */
    protected $logo;

    /**
     * The rights of the feed. 
     * 
     * @var string
     */
    protected $rights;

    /**
     * The subtitle of the feed. 
     * 
     * @var string
     */
    protected $subtitle;

    /**
     * The title of the feed. 
     * 
     * @var string
     */
    protected $title;

    /**
     * The update of the feed. 
     * 
     * @var \DateTime
     */
    protected $updated;

    /**
     * The extension element of the feed. 
     * 
     * @var string
     */
    protected $extensionElement;

    /**
     * Creates an ATOM FEED object with default parameters. 
     */ 
    public function __construct()
    {   
        $this->attributes = array();
    }

    /**
     * Creates a feed object with specified XML string. 
     *
     * @param string $xmlString An XML string representing the feed object.
     *
     * @return none
     */
    public function parseXml($xmlString)
    {
        $feedXml    = simplexml_load_string($xmlString);
        $attributes = $feedXml->attributes();
        $feedArray  = (array)$feedXml;
        if (!empty($attributes)) {
            $this->attributes = (array)$attributes;
        }

        if (array_key_exists('author', $feedArray)) {
            $this->author = $this->processAuthorNode($feedArray);
        }

        if (array_key_exists('entry', $feedArray)) {
            $this->entry = $this->processEntryNode($feedArray);
        }

        if (array_key_exists('category', $feedArray)) {
            $this->category = $this->processCategoryNode($feedArray);
        }

        if (array_key_exists('contributor', $feedArray)) {
            $this->contributor = $this->processContributorNode($feedArray);
        }

        if (array_key_exists('generator', $feedArray)) {
            $generator      = new Generator();
            $generatorValue = $feedArray['generator'];
            if (is_string($generatorValue)) {
                $generator->setText($generatorValue);
            } else {
                $generator->parseXml($generatorValue->asXML());
            }
                
            $this->generator = $generator;
        } 

        if (array_key_exists('icon', $feedArray)) {
            $this->icon = (string)$feedArray['icon'];
        }

        if (array_key_exists('id', $feedArray)) {
            $this->id = (string)$feedArray['id'];
        }

        if (array_key_exists('link', $feedArray)) {
            $this->link = $this->processLinkNode($feedArray);
        }

        if (array_key_exists('logo', $feedArray)) {
            $this->logo = (string)$feedArray['logo'];
        }

        if (array_key_exists('rights', $feedArray)) {
            $this->rights = (string)$feedArray['rights'];
        }

        if (array_key_exists('subtitle', $feedArray)) {
            $this->subtitle = (string)$feedArray['subtitle'];
        }

        if (array_key_exists('title', $feedArray)) {
            $this->title = (string)$feedArray['title'];
        }

        if (array_key_exists('updated', $feedArray)) {
            $this->updated = \DateTime::createFromFormat(
                \DateTime::ATOM,
                (string)$feedArray['updated']
            );
        }
    }

    /**
     * Gets the attributes of the feed. 
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * Sets the attributes of the feed. 
     *
     * @param array $attributes The attributes of the array. 
     *
     * @return array
     */
    public function setAttributes($attributes)
    {
        Validate::isArray($attributes, 'attributes');
        $this->attributes = $attributes;
    }

    /**
     * Adds an attribute to the feed object instance. 
     * 
     * @param string $attributeKey   The key of the attribute. 
     * @param mixed  $attributeValue The value of the attribute.
     *
     * @return none
     */
    public function addAttribute($attributeKey, $attributeValue)
    {
        $this->attributes[$attributeKey] = $attributeValue;
    }   

    /**
     * Gets the author of the feed. 
     * 
     * @return Person 
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Sets the author of the feed. 
     * 
     * @param Person $author The author of the feed. 
     *
     * @return none
     */ 
    public function setAuthor($author)
    {
        Validate::isArray($author, 'author');
        $person = new Person();
        foreach ($author as $authorInstance) {
            Validate::isInstanceOf($authorInstance, $person, 'author'); 
        }
        $this->author = $author;
    }

    /**
     * Gets the category of the feed.
     *  
     * @return Category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Sets the category of the feed.
     *  
     * @param Category $category The category of the feed. 
     * 
     * @return none
     */
    public function setCategory($category)
    {
        Validate::isArray($category, 'category');
        $categoryClassInstance = new Category();
        foreach ($category as $categoryInstance) {
            Validate::isInstanceOf(
                $categoryInstance, 
                $categoryClassInstance, 
                'category'
            );
        }
        $this->category = $category;
    }
   
    /**
     * Gets contributor.
     *
     * @return array
     */
    public function getContributor()
    {
        return $this->contributor;
    }

    /**
     * Sets contributor.
     * 
     * @param string $contributor The contributor of the feed. 
     * 
     * @return none
     */
    public function setContributor($contributor)
    {
        Validate::isArray($contributor, 'contributor');
        $person = new Person();
        foreach ($contributor as $contributorInstance) {
            Validate::isInstanceOf($contributorInstance, $person, 'contributor'); 
        }
        $this->contributor = $contributor;
    }

    /**
     * Gets generator.
     * 
     * @return string 
     */
    public function getGenerator()
    {
        return $this->generator;
    }

    /**
     * Sets the generator. 
     * 
     * @param string $generator Sets the generator of the feed. 
     * 
     * @return none
     */
    public function setGenerator($generator)
    {
        $this->generator = $generator;
    }

    /**
     * Gets the icon of the feed. 
     * 
     * @return string 
     */
    public function getIcon()
    {
        return $this->icon;
    }

    /**
     * Sets the icon of the feed. 
     * 
     * @param string $icon The icon of the feed. 
     * 
     * @return none
     */
    public function setIcon($icon)
    {
        $this->icon = $icon;
    }

    /**
     * Gets the ID of the feed. 
     * 
     * @return string   
     */ 
    public function getId()
    {   
        return $this->id;
    }

    /**
     * Sets the ID of the feed.
     * 
     * @param string $id The ID of the feed. 
     * 
     * @return none
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Gets the link of the feed. 
     * 
     * @return array
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * Sets the link of the feed. 
     * 
     * @param array $link The link of the feed. 
     * 
     * @return none
     */
    public function setLink($link)
    {
        Validate::isArray($link, 'link');
        $this->link = $link;
    }

    /**
     * Gets the logo of the feed. 
     * 
     * @return string 
     */
    public function getLogo()
    {
        return $this->logo;
    }

    /**
     * Sets the logo of the feed. 
     * 
     * @param string $logo The logo of the feed. 
     * 
     * @return none
     */
    public function setLogo($logo)
    {
        $this->logo = $logo;
    }

    /**
     * Gets the rights of the feed. 
     * 
     * @return string 
     */
    public function getRights()
    {   
        return $this->rights;
    }

    /** 
     * Sets the rights of the feed. 
     * 
     * @param string $rights The rights of the feed. 
     * 
     * @return none
     */
    public function setRights($rights)
    {
        $this->rights = $rights;
    }

    /**
     * Gets the sub title.  
     * 
     * @return string 
     */
    public function getSubtitle()
    {   
        return $this->subtitle;
    }

    /**
     * Sets the sub title of the feed. 
     *
     * @param string $subtitle Sets the sub title of the feed. 
     * 
     * @return none
     */
    public function setSubtitle($subtitle)
    {
        $this->subtitle = $subtitle;
    }

    /**
     * Gets the title of the feed. 
     *
     * @return string. 
     */
    public function getTitle() 
    {   
        return $this->title;
    }

    /**
     * Sets the title of the feed. 
     *
     * @param string $title The title of the feed. 
     * 
     * @return none
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Gets the updated. 
     * 
     * @return \DateTime
     */
    public function getUpdated()
    {   
        return $this->updated;
    }

    /**
     * Sets the updated. 
     * 
     * @param \DateTime $updated updated
     * 
     * @return none
     */
    public function setUpdated($updated)
    {
        Validate::isInstanceOf($updated, new \DateTime(), 'updated');
        $this->updated = $updated;
    }

    /** 
     * Gets the extension element. 
     * 
     * @return string 
     */
    public function getExtensionElement()
    {   
        return $this->extensionElement;
    }

    /**
     * Sets the extension element. 
     * 
     * @param string $extensionElement The extension element. 
     * 
     * @return none
     */
    public function setExtensionElement($extensionElement)
    {
        $this->extensionElement = $extensionElement;
    }

    /**
     * Gets the entry of the feed. 
     * 
     * @return Entry
     */
    public function getEntry()
    {
        return $this->entry;
    }

    /**
     * Sets the entry of the feed.
     * 
     * @param Entry $entry The entry of the feed. 
     * 
     * @return none
     */
    public function setEntry($entry)
    {
        $this->entry = $entry;
    }

    /** 
     * Writes an XML representing the feed object.
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none 
     */
    public function writeXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');

        $xmlWriter->startElementNS('atom', 'feed', Resources::ATOM_NAMESPACE);
        $this->writeInnerXml($xmlWriter);
        $xmlWriter->endElement();
    }

    /** 
     * Writes an XML representing the feed object.
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none
     */
    public function writeInnerXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');

        if (!is_null($this->attributes)) {
            if (is_array($this->attributes)) {
                foreach (
                    $this->attributes 
                    as $attributeName => $attributeValue
                ) {
                    $xmlWriter->writeAttribute($attributeName, $attributeValue);
                }
            }
        }
         
        if (!is_null($this->author)) {
            $this->writeArrayItem(
                $xmlWriter,
                $this->author,
                Resources::AUTHOR
            );
        } 

        if (!is_null($this->category)) {
            $this->writeArrayItem(
                $xmlWriter,
                $this->category,
                Resources::CATEGORY
            );
        }

        if (!is_null($this->contributor)) {
            $this->writeArrayItem(
                $xmlWriter,
                $this->contributor,
                Resources::CONTRIBUTOR
            );
        }

        if (!is_null($this->generator)) {
            $this->generator->writeXml($xmlWriter);
        } 

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom', 
            'icon', 
            Resources::ATOM_NAMESPACE,
            $this->icon
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'logo', 
            Resources::ATOM_NAMESPACE,
            $this->logo
        );
        
        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'id', 
            Resources::ATOM_NAMESPACE,
            $this->id
        );

        if (!is_null($this->link)) {
            $this->writeArrayItem(
                $xmlWriter,
                $this->link,
                Resources::LINK
            );
        }

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'rights', 
            Resources::ATOM_NAMESPACE,
            $this->rights
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'subtitle', 
            Resources::ATOM_NAMESPACE,
            $this->subtitle
        );

        $this->writeOptionalElementNS(
            $xmlWriter,
            'atom',
            'title', 
            Resources::ATOM_NAMESPACE,
            $this->title
        );
        
        if (!is_null($this->updated)) {
            $xmlWriter->writeElementNS(
                'atom',
                'updated', 
                Resources::ATOM_NAMESPACE,
                $this->updated->format(\DateTime::ATOM)
            );
        }

    }
}

// @codingStandardsIgnoreEndInternal/Atom/Content.php000060400000011643152440043010011335 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Atom\AtomProperties;
/**
 * The content class of ATOM standard.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class Content extends AtomBase
{
    /**
     * The text of the content.
     *
     * @var string
     */
    protected $text;

    /**
     * The type of the content.
     *
     * @var string
     */
    protected $type;

    /**
     * Source XML object
     *
     * @var \SimpleXMLElement
     */
    protected $xml;

    /**
     * Creates a Content instance with specified text.
     *
     * @param string $text The text of the content.
     *
     * @return none
     */
    public function __construct($text = null)
    {
        $this->text = $text;
    }

    /**
     * Creates an ATOM CONTENT instance with specified xml string.
     *
     * @param string $xmlString an XML based string of ATOM CONTENT.
     *
     * @return none
     */
    public function parseXml($xmlString)
    {
        Validate::notNull($xmlString, 'xmlString');
        Validate::isString($xmlString, 'xmlString');

        $this->fromXml(simplexml_load_string($xmlString));
    }

    /**
     * Creates an ATOM CONTENT instance with specified simpleXML object
     *
     * @param \SimpleXMLElement $contentXml xml element of ATOM CONTENT
     *
     * @return none
     */
    public function fromXml($contentXml)
    {
        Validate::notNull($contentXml, 'contentXml');
        Validate::isA($contentXml, '\SimpleXMLElement', 'contentXml');

        $attributes = $contentXml->attributes();

        if (!empty($attributes['type'])) {
            $this->content = (string)$attributes['type'];
        }

        $text = '';
        foreach ($contentXml->children() as $child) {
            $text .= $child->asXML();
        }

        $this->text = $text;

        $this->xml = $contentXml;
    }

    /**
     * Gets the text of the content.
     *
     * @return string
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * Sets the text of the content.
     *
     * @param string $text The text of the content.
     *
     * @return none
     */
    public function setText($text)
    {
        $this->text = $text;
    }

    /**
     * Gets the xml object of the content.
     *
     * @return \SimpleXMLElement
     */
    public function getXml()
    {
        return $this->xml;
    }

    /**
     * Gets the type of the content.
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Sets the type of the content.
     *
     * @param string $type The type of the content.
     *
     * @return none
     */
    public function setType($type)
    {
        $this->type = $type;
    }

    /**
     * Writes an XML representing the content.
     *
     * @param \XMLWriter $xmlWriter The XML writer.
     *
     * @return none
     */
    public function writeXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->startElementNS(
            'atom',
            'content',
            Resources::ATOM_NAMESPACE
        );

        $this->writeOptionalAttribute(
            $xmlWriter,
            'type',
            $this->type
        );

        $this->writeInnerXml($xmlWriter);
        $xmlWriter->endElement();
    }

    /**
     * Writes an inner XML representing the content.
     *
     * @param \XMLWriter $xmlWriter The XML writer.
     *
     * @return none
     */
    public function writeInnerXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->writeRaw($this->text);
    }
}

Internal/Atom/Category.php000060400000013640152440043010011477 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Validate;

/**
 * The category class of the ATOM standard.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class Category extends AtomBase
{
    /**
     * The term of the category. 
     *
     * @var string  
     */
    protected $term;

    /**
     * The scheme of the category. 
     *
     * @var string  
     */
    protected $scheme;

    /**
     * The label of the category. 
     * 
     * @var string 
     */ 
    protected $label;

    /**
     * The undefined content of the category. 
     *  
     * @var string 
     */
    protected $undefinedContent;
     
    /** 
     * Creates a Category instance with specified text.
     *
     * @param string $undefinedContent The undefined content of the category.
     *
     * @return none
     */
    public function __construct($undefinedContent = Resources::EMPTY_STRING)
    {
        $this->undefinedContent = $undefinedContent;
    }

    /**
     * Creates an ATOM Category instance with specified xml string. 
     * 
     * @param string $xmlString an XML based string of ATOM CONTENT.
     * 
     * @return none
     */ 
    public function parseXml($xmlString)
    {
        Validate::notNull($xmlString, 'xmlString');
        Validate::isString($xmlString, 'xmlString');
        $categoryXml = simplexml_load_string($xmlString);
        $attributes  = $categoryXml->attributes();
        if (!empty($attributes['term'])) {
            $this->term = (string)$attributes['term'];
        }

        if (!empty($attributes['scheme'])) {
            $this->scheme = (string)$attributes['scheme'];
        }

        if (!empty($attributes['label'])) {
            $this->label = (string)$attributes['label'];
        }

        $this->undefinedContent =(string)$categoryXml;
    }

    /** 
     * Gets the term of the category. 
     *
     * @return string
     */
    public function getTerm()
    {   
        return $this->term;
    } 

    /**
     * Sets the term of the category.
     * 
     * @param string $term The term of the category.
     * 
     * @return none
     */
    public function setTerm($term)
    {
        $this->term = $term; 
    }

    /**
     * Gets the scheme of the category. 
     * 
     * @return string
     */
    public function getScheme()
    {
        return $this->scheme;
    }

    /**
     * Sets the scheme of the category. 
     * 
     * @param string $scheme The scheme of the category.
     * 
     * @return none
     */
    public function setScheme($scheme)
    {
        $this->scheme = $scheme;
    }

    /**
     * Gets the label of the category. 
     *
     * @return string The label. 
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * Sets the label of the category. 
     * 
     * @param string $label The label of the category. 
     * 
     * @return none
     */ 
    public function setLabel($label)
    {
        $this->label = $label;
    }

    /**
     * Gets the undefined content of the category. 
     * 
     * @return string
     */
    public function getUndefinedContent()
    {
        return $this->undefinedContent;
    }

    /**
     * Sets the undefined content of the category. 
     * 
     * @param string $undefinedContent The undefined content of the category. 
     *
     * @return none
     */
    public function setUndefinedContent($undefinedContent)
    {
        $this->undefinedContent = $undefinedContent;
    }
    
    /** 
     * Writes an XML representing the category. 
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none
     */
    public function writeXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->startElementNS(
            'atom', 
            'category',
            Resources::ATOM_NAMESPACE
        );
        $this->writeInnerXml($xmlWriter);
        $xmlWriter->endElement();
    }

    /** 
     * Writes an XML representing the category. 
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none
     */
    public function writeInnerXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $this->writeOptionalAttribute(
            $xmlWriter,
            'term', 
            $this->term
        );

        $this->writeOptionalAttribute(
            $xmlWriter,
            'scheme', 
            $this->scheme
        );

        $this->writeOptionalAttribute(
            $xmlWriter,
            'label', 
            $this->label
        );
             
        if (!empty($this->undefinedContent)) {
            $xmlWriter->WriteRaw($this->undefinedContent);
        }

    }
}

Internal/Atom/Generator.php000060400000011023152440043010011641 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Resources;

/**
 * The generator class of ATOM library. 
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class Generator extends AtomBase
{
    /**
     * The of the generator. 
     *
     * @var string  
     */
    protected $text;

    /**
     * The Uri of the generator. 
     *
     * @var string  
     */
    protected $uri;

    /**
     * The version of the generator.
     *
     * @var string 
     */
    protected $version;

    /** 
     * Creates a generator instance with specified XML string. 
     * 
     * @param string $xmlString A string representing a generator 
     * instance.
     * 
     * @return none
     */
    public static function parseXml($xmlString)
    {
        $generatorXml   = new \SimpleXMLElement($xmlString);
        $generatorArray = (array)$generatorXml;
        $attributes     = $generatorXml->attributes();
        if (!empty($attributes['uri'])) { 
            $this->uri = (string)$attributes['uri'];
        }

        if (!empty($attributes['version'])) {
            $this->version = (string)$attributes['version'];
        }

        $this->text = (string)$generatorXml;  
    }
     
    /** 
     * Creates an ATOM generator instance with specified name.
     *
     * @param string $text The text content of the generator.
     * 
     * @return none
     */
    public function __construct($text = null)
    {
        if (!empty($text)) {
            $this->text = $text;
        }
    }

    /** 
     * Gets the text of the generator. 
     *
     * @return string
     */
    public function getText()
    {   
        return $this->text;
    } 

    /**
     * Sets the text of the generator.
     * 
     * @param string $text The text of the generator.
     * 
     * @return none
     */
    public function setText($text)
    {
        $this->text = $text; 
    }

    /**
     * Gets the URI of the generator. 
     * 
     * @return string
     */
    public function getUri()
    {
        return $this->uri;
    }

    /**
     * Sets the URI of the generator. 
     * 
     * @param string $uri The URI of the generator.
     * 
     * @return none
     */
    public function setUri($uri)
    {
        $this->uri = $uri;
    }

    
    /**
     * Gets the version of the generator. 
     * 
     * @return string
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * Sets the version of the generator. 
     * 
     * @param string $version The version of the generator.
     * 
     * @return none
     */
    public function setVersion($version)
    {
        $this->version = $version;
    }

    /** 
     * Writes an XML representing the generator. 
     * 
     * @param \XMLWriter $xmlWriter The XML writer.
     * 
     * @return none
     */
    public function writeXml($xmlWriter)
    {
        $xmlWriter->startElementNS(
            'atom',
            Resources::CATEGORY,
            Resources::ATOM_NAMESPACE
        );

        $this->writeOptionalAttribute(
            $xmlWriter,
            'uri', 
            $this->uri
        );

        $this->writeOptionalAttribute(
            $xmlWriter,
            'version', 
            $this->version
        );

        $xmlWriter->writeRaw($this->text);
        $xmlWriter->endElement();
    }
}

Internal/Atom/AtomBase.php000060400000022441152440043010011414 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Atom\AtomLink;

/**
 * The base class of ATOM library.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class AtomBase
{
    /**
     * The attributes of the feed.
     *
     * @var array
     */
    protected $attributes;

    /**
     * Creates an ATOM base object with default parameters.
     */
    public function __construct()
    {
        $this->attributes = array();
        $atomlink         = new AtomLink();
    }

    /**
     * Gets the attributes of the ATOM class.
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * Sets the attributes of the ATOM class.
     *
     * @param array $attributes The attributes of the array.
     *
     * @return array
     */
    public function setAttributes($attributes)
    {
        Validate::isArray($attributes, 'attributes');
        $this->attributes = $attributes;
    }

    /**
     * Sets an attribute to the ATOM object instance.
     *
     * @param string $attributeKey   The key of the attribute.
     * @param mixed  $attributeValue The value of the attribute.
     *
     * @return none
     */
    public function setAttribute($attributeKey, $attributeValue)
    {
        $this->attributes[$attributeKey] = $attributeValue;
    }

    /**
     * Gets an attribute with a specified attribute key.
     *
     * @param string $attributeKey The key of the attribute.
     *
     * @return none
     */
    public function getAttribute($attributeKey)
    {
        return $this->attributes[$attributeKey];
    }

    /**
     * Processes author node.
     *
     * @param array $xmlWriter   The XML writer.
     * @param array $itemArray   An array of item to write.
     * @param array $elementName The name of the element.
     *
     * @return array
     */
    protected function writeArrayItem($xmlWriter, $itemArray, $elementName)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        Validate::isArray($itemArray, 'itemArray');
        Validate::isString($elementName, 'elementName');

        foreach ($itemArray as $itemInstance) {
            $xmlWriter->startElementNS(
                'atom',
                $elementName,
                Resources::ATOM_NAMESPACE
            );
            $itemInstance->writeInnerXml($xmlWriter);
            $xmlWriter->endElement();
        }

    }

    /**
     * Processes author node.
     *
     * @param array $xmlArray An array of simple xml elements.
     *
     * @return array
     */
    protected function processAuthorNode($xmlArray)
    {
        $author     = array();
        $authorItem = $xmlArray[Resources::AUTHOR];

        if (is_array($authorItem)) {
            foreach ($xmlArray[Resources::AUTHOR] as $authorXmlInstance) {
                $authorInstance = new Person();
                $authorInstance->parseXml($authorXmlInstance->asXML());
                $author[] = $authorInstance;
            }
        } else {
            $authorInstance = new Person();
            $authorInstance->parseXml($authorItem->asXML());
            $author[] = $authorInstance;
        }
        return $author;
    }

    /**
     * Processes entry node.
     *
     * @param array $xmlArray An array of simple xml elements.
     *
     * @return array
     */
    protected function processEntryNode($xmlArray)
    {
        $entry     = array();
        $entryItem = $xmlArray[Resources::ENTRY];

        if (is_array($entryItem)) {
            foreach ($xmlArray[Resources::ENTRY] as $entryXmlInstance) {
                $entryInstance = new Entry();
                $entryInstance->fromXml($entryXmlInstance);
                $entry[] = $entryInstance;
            }
        } else {
            $entryInstance = new Entry();
            $entryInstance->fromXml($entryItem);
            $entry[] = $entryInstance;
        }
        return $entry;
    }

    /**
     * Processes category node.
     *
     * @param array $xmlArray An array of simple xml elements.
     *
     * @return array
     */
    protected function processCategoryNode($xmlArray)
    {
        $category     = array();
        $categoryItem = $xmlArray[Resources::CATEGORY];

        if (is_array($categoryItem)) {
            foreach ($xmlArray[Resources::CATEGORY] as $categoryXmlInstance) {
                $categoryInstance = new Category();
                $categoryInstance->parseXml($categoryXmlInstance->asXML());
                $category[] = $categoryInstance;
            }
        } else {
            $categoryInstance = new Category();
            $categoryInstance->parseXml($categoryItem->asXML());
            $category[] = $categoryInstance;
        }
        return $category;
    }

    /**
     * Processes contributor node.
     *
     * @param array $xmlArray An array of simple xml elements.
     *
     * @return array
     */
    protected function processContributorNode($xmlArray)
    {
        $category        = array();
        $contributorItem = $xmlArray[Resources::CONTRIBUTOR];

        if (is_array($contributorItem)) {
            foreach ($xmlArray[Resources::CONTRIBUTOR] as $contributorXmlInstance) {
                $contributorInstance = new Person();
                $contributorInstance->parseXml($contributorXmlInstance->asXML());
                $contributor[] = $contributorInstance;
            }
        } elseif (is_string($contributorItem)) {
            $contributorInstance = new Person();
            $contributorInstance->setName((string)$contributorItem);
            $contributor[] = $contributorInstance;
        } else {
            $contributorInstance = new Person();
            $contributorInstance->parseXml($contributorItem->asXML());
            $contributor[] = $contributorInstance;
        }
        return $contributor;
    }

    /**
     * Processes link node.
     *
     * @param array $xmlArray An array of simple xml elements.
     *
     * @return array
     */
    protected function processLinkNode($xmlArray)
    {
        $link      = array();
        $linkValue = $xmlArray[Resources::LINK];

        if (is_array($linkValue)) {
            foreach ($xmlArray[Resources::LINK] as $linkValueInstance) {
                $linkInstance = new AtomLink();
                $linkInstance->parseXml($linkValueInstance->asXML());
                $link[] = $linkInstance;
            }
        } else {
            $linkInstance = new AtomLink();
            $linkInstance->parseXml($linkValue->asXML());
            $link[] = $linkInstance;
        }

        return $link;
    }

    /**
     * Writes an optional attribute for ATOM.
     *
     * @param \XMLWriter $xmlWriter      The XML writer.
     * @param string     $attributeName  The name of the attribute.
     * @param mixed      $attributeValue The value of the attribute.
     *
     * @return none
     */
    protected function writeOptionalAttribute(
        $xmlWriter,
        $attributeName,
        $attributeValue
    ) {
        Validate::notNull($xmlWriter, 'xmlWriter');
        Validate::isString($attributeName, 'attributeName');

        if (!empty($attributeValue)) {
            $xmlWriter->writeAttribute(
                $attributeName,
                $attributeValue
            );
        }
    }

    /**
     * Writes the optional elements namespaces.
     *
     * @param \XmlWriter $xmlWriter    The XML writer.
     * @param string     $prefix       The prefix.
     * @param string     $elementName  The element name.
     * @param string     $namespace    The namespace name.
     * @param string     $elementValue The element value.
     *
     * @return none
     */
    protected function writeOptionalElementNS(
        $xmlWriter,
        $prefix,
        $elementName,
        $namespace,
        $elementValue
    ) {
        Validate::notNull($xmlWriter, 'xmlWriter');
        Validate::isString($elementName, 'elementName');

        if (!empty($elementValue)) {
            $xmlWriter->writeElementNS(
                $prefix,
                $elementName,
                $namespace,
                $elementValue
            );
        }
    }
}

Internal/Atom/.htaccess000044400000000424152440043010011005 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Internal/Atom/AtomLink.php000060400000017077152440043010011450 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Internal\Atom;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Validate;

/**
 * This link defines a reference from an entry or feed to a Web resource.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal\Atom
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/WindowsAzure/azure-sdk-for-php
 */

class AtomLink extends AtomBase
{
    /**
     * The undefined content. 
     *
     * @var string  
     */
    protected $undefinedContent;

    /**
     * The HREF of the link. 
     *
     * @var string  
     */
    protected $href;

    /**
     * The rel attribute of the link.
     *
     * @var string
     */
    protected $rel;

    /**
     * The media type of the link. 
     *
     * @var string 
     */
    protected $type;

    /**
     * The language of HREF.
     * 
     * @var string 
     */
    protected $hreflang;

    /**
     * The titile of the link. 
     * 
     * @var string 
     */ 
    protected $title;

    /**
     * The length of the link. 
     * 
     * @var integer 
     */
    protected $length;
     
    /** 
     * Creates a AtomLink instance with specified text.
     */
    public function __construct()
    {
    }

    /**
     * Parse an ATOM Link xml. 
     * 
     * @param string $xmlString an XML based string of ATOM Link.
     * 
     * @return none
     */ 
    public function parseXml($xmlString)
    {
        Validate::notNull($xmlString, 'xmlString');
        Validate::isString($xmlString, 'xmlString');
        $atomLinkXml = simplexml_load_string($xmlString);
        $attributes  = $atomLinkXml->attributes();

        if (!empty($attributes['href'])) {
            $this->href = (string)$attributes['href'];
        }

        if (!empty($attributes['rel'])) {
            $this->rel = (string)$attributes['rel'];
        }

        if (!empty($attributes['type'])) {
            $this->type = (string)$attributes['type'];
        }

        if (!empty($attributes['hreflang'])) {
            $this->hreflang = (string)$attributes['hreflang'];
        }

        if (!empty($attributes['title'])) {
            $this->title = (string)$attributes['title'];
        }

        if (!empty($attributes['length'])) {
            $this->length = (integer)$attributes['length'];
        }

        $undefinedContent = (string)$atomLinkXml;
        if (empty($undefinedContent)) {
            $this->undefinedContent = null;
        } else {
            $this->undefinedContent = (string)$atomLinkXml;
        }
    }

    /** 
     * Gets the href of the link. 
     *
     * @return string
     */
    public function getHref()
    {   
        return $this->href;
    } 

    /**
     * Sets the href of the link.
     * 
     * @param string $href The href of the link.
     *
     * @return none
     */
    public function setHref($href)
    {
        $this->href = $href; 
    }

    /**
     * Gets the rel of the atomLink. 
     * 
     * @return string
     */
    public function getRel()
    {
        return $this->rel;
    }

    /**
     * Sets the rel of the link. 
     * 
     * @param string $rel The rel of the atomLink.
     *
     * @return none
     */
    public function setRel($rel)
    {
        $this->rel = $rel;
    }

    /**
     * Gets the type of the link. 
     *
     * @return string 
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Sets the type of the link.
     * 
     * @param string $type The type of the link. 
     *
     * @return none
     */
    public function setType($type)
    {
        $this->type = $type;
    }

    /**
     * Gets the language of the href. 
     * 
     * @return string 
     */
    public function getHrefLang()
    {
        return $this->hrefLang;
    }

    /**
     * Sets the language of the href. 
     * 
     * @param string $hrefLang The language of the href.
     *
     * @return none
     */
    public function setHrefLang($hrefLang)
    {
        $this->hrefLang = $hrefLang;
    }

    /** 
     * Gets the title of the link. 
     * 
     * @return string 
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Sets the title of the link. 
     * 
     * @param string $title The title of the link. 
     *
     * @return none
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * Gets the length of the link. 
     * 
     * @return string 
     */
    public function getLength() 
    {
        return $this->length;
    }

    /**
     * Sets the length of the link. 
     * 
     * @param string $length The length of the link. 
     *
     * @return none
     */
    public function setLength($length)
    {
        $this->length = $length;
    }

    /**     
     * Gets the undefined content. 
     *
     * @return string 
     */
    public function getUndefinedContent()
    {
        return $this->undefinedContent;
    }

    /**
     * Sets the undefined content. 
     * 
     * @param string $undefinedContent The undefined content. 
     *
     * @return none
     */
    public function setUndefinedContent($undefinedContent)
    {
        $this->undefinedContent = $undefinedContent;
    }

    /** 
     * Writes an XML representing the ATOM link item.
     * 
     * @param \XMLWriter $xmlWriter The xml writer.
     *
     * @return none
     */
    public function writeXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        $xmlWriter->startElementNS(
            'atom', 
            Resources::LINK, 
            Resources::ATOM_NAMESPACE
        );
        $this->writeInnerXml($xmlWriter);
        $xmlWriter->endElement();
    }

    /** 
     * Writes the inner XML representing the ATOM link item.
     * 
     * @param \XMLWriter $xmlWriter The xml writer.
     * 
     * @return none
     */
    public function writeInnerXml($xmlWriter)
    {
        Validate::notNull($xmlWriter, 'xmlWriter');
        
        $this->writeOptionalAttribute($xmlWriter, 'href', $this->href);
        $this->writeOptionalAttribute($xmlWriter, 'rel', $this->rel);
        $this->writeOptionalAttribute($xmlWriter, 'type', $this->type);
        $this->writeOptionalAttribute($xmlWriter, 'hreflang', $this->hreflang);
        $this->writeOptionalAttribute($xmlWriter, 'title', $this->title);
        $this->writeOptionalAttribute($xmlWriter, 'length', $this->length);

        if (!empty($this->undefinedContent)) {
            $xmlWriter->writeRaw($this->undefinedContent);
        }

    }
}

Internal/FilterableService.php000060400000003165152440043010012415 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;

/**
 * Interface for service with filers.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
interface FilterableService
{
    /**
    * Adds new filter to proxy object and returns new BlobRestProxy with
    * that filter.
    *
    * @param WindowsAzure\Common\Internal\IServiceFilter $filter Filter to add for 
    * the pipeline.
    * 
    * @return mix.
    */
    public function withFilter($filter);
}


Internal/ServiceBusSettings.php000060400000016213152440043010012614 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;

/**
 * Represents the settings used to sign and access a request against the service 
 * bus.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ServiceBusSettings extends ServiceSettings
{
    /**
     * @var string
     */
    private $_serviceBusEndpointUri;
    
    /**
     * @var string
     */
    private $_wrapEndpointUri;
    
    /**
     * @var string
     */
    private $_wrapName;
    
    /**
     * @var string
     */
    private $_wrapPassword;
    
    /**
     * @var string
     */
    private $_namespace;
    
    /**
     * Validator for the SharedSecretValue setting. It has to be provided.
     * 
     * @var array
     */
    private static $_wrapPasswordSetting;
    
    /**
     * Validator for the SharedSecretIssuer setting. It has to be provided.
     * 
     * @var array
     */
    private static $_wrapNameSetting;
    
    /**
     * Validator for the Endpoint setting. Must be a valid Uri.
     * 
     * @var array
     */
    private static $_serviceBusEndpointSetting;
    
    /**
     * Validator for the StsEndpoint setting. Must be a valid Uri.
     * 
     * @var array
     */
    private static $_wrapEndpointUriSetting;
    
    /**
     * @var boolean
     */
    protected static $isInitialized = false;
    
    /**
     * Holds the expected setting keys.
     * 
     * @var array
     */
    protected static $validSettingKeys = array();
    
    /**
     * Initializes static members of the class.
     * 
     * @return none
     */
    protected static function init()
    {
        self::$_serviceBusEndpointSetting = self::settingWithFunc(
            Resources::SERVICE_BUS_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );
        
        self::$_wrapNameSetting = self::setting(
            Resources::SHARED_SECRET_ISSUER_NAME
        );
        
        self::$_wrapPasswordSetting = self::setting(
            Resources::SHARED_SECRET_VALUE_NAME
        );
        
        self::$_wrapEndpointUriSetting = self::settingWithFunc(
            Resources::STS_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );
        
        self::$validSettingKeys[] = Resources::SERVICE_BUS_ENDPOINT_NAME;
        self::$validSettingKeys[] = Resources::SHARED_SECRET_ISSUER_NAME;
        self::$validSettingKeys[] = Resources::SHARED_SECRET_VALUE_NAME;
        self::$validSettingKeys[] = Resources::STS_ENDPOINT_NAME;
    }
    
    /**
     * Creates new Service Bus settings instance.
     * 
     * @param string $serviceBusEndpoint The Service Bus endpoint uri.
     * @param string $namespace          The service namespace.
     * @param string $wrapName           The wrap name.
     * @param string $wrapPassword       The wrap password.
     */
    public function __construct(
        $serviceBusEndpoint,
        $namespace,
        $wrapEndpointUri,
        $wrapName,
        $wrapPassword
    ) {
        $this->_namespace             = $namespace;
        $this->_serviceBusEndpointUri = $serviceBusEndpoint;
        $this->_wrapEndpointUri       = $wrapEndpointUri;
        $this->_wrapName              = $wrapName;
        $this->_wrapPassword          = $wrapPassword;
    }
    
    /**
     * Creates a ServiceBusSettings object from the given connection string.
     * 
     * @param string $connectionString The storage settings connection string.
     * 
     * @return ServiceBusSettings 
     */
    public static function createFromConnectionString($connectionString)
    {
        $tokenizedSettings = self::parseAndValidateKeys($connectionString);
        
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::allRequired(
                self::$_serviceBusEndpointSetting,
                self::$_wrapNameSetting,
                self::$_wrapPasswordSetting
            ),
            self::optional(self::$_wrapEndpointUriSetting)
        );
        
        if ($matchedSpecs) {
            $endpoint = Utilities::tryGetValueInsensitive(
                Resources::SERVICE_BUS_ENDPOINT_NAME,
                $tokenizedSettings
            );
            
            // Parse the namespace part from the URI
            $namespace   = explode('.', parse_url($endpoint, PHP_URL_HOST));
            $namespace   = $namespace[0];
            $wrapEndpointUri = Utilities::tryGetValueInsensitive(
                Resources::STS_ENDPOINT_NAME,
                $tokenizedSettings,
                sprintf(Resources::WRAP_ENDPOINT_URI_FORMAT, $namespace)
            );
            $issuerName  = Utilities::tryGetValueInsensitive(
                Resources::SHARED_SECRET_ISSUER_NAME,
                $tokenizedSettings
            );
            $issuerValue = Utilities::tryGetValueInsensitive(
                Resources::SHARED_SECRET_VALUE_NAME,
                $tokenizedSettings
            );
            
            return new ServiceBusSettings(
                $endpoint,
                $namespace,
                $wrapEndpointUri,
                $issuerName,
                $issuerValue
            );
        }
        
        self::noMatch($connectionString);
    }
    
    /**
     * Gets the Service Bus endpoint URI.
     * 
     * @return string
     */
    public function getServiceBusEndpointUri()
    {
        return $this->_serviceBusEndpointUri;
    }
    
    /**
     * Gets the wrap endpoint URI.
     * 
     * @return string
     */
    public function getWrapEndpointUri()
    {
        return $this->_wrapEndpointUri;
    }
    
    /**
     * Gets the wrap name.
     * 
     * @return string
     */
    public function getWrapName()
    {
        return $this->_wrapName;
    }
    
    /**
     * Gets the wrap password.
     * 
     * @return string
     */
    public function getWrapPassword()
    {
        return $this->_wrapPassword;
    }
    
    /**
     * Gets the namespace name.
     * 
     * @return string 
     */
    public function getNamespace()
    {
        return $this->_namespace;
    }
}


Internal/ServiceSettings.php000060400000023005152440043010012137 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;

/**
 * Base class for all REST services settings.
 * 
 * Derived classes must implement the following members:
 * 1- $isInitialized: A static property that indicates whether the class's static
 *    members have been initialized.
 * 2- init(): A protected static method that initializes static members.
 * 3- $validSettingKeys: A static property that contains valid setting keys for this 
 *    service.
 * 4- createFromConnectionString($connectionString): A public static function that
 *    takes a connection string and returns the created settings object.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
abstract class ServiceSettings
{
    /**
     * Throws an exception if the connection string format does not match any of the
     * available formats.
     * 
     * @param type $connectionString The invalid formatted connection string.
     * 
     * @return none
     * 
     * @throws \RuntimeException
     */
    protected static function noMatch($connectionString)
    {
        throw new \RuntimeException(
            sprintf(Resources::MISSING_CONNECTION_STRING_SETTINGS, $connectionString)
        );
    }
    
    /**
     * Parses the connection string and then validate that the parsed keys belong to
     * the $validSettingKeys
     * 
     * @param string $connectionString The user provided connection string.
     * 
     * @return array The tokenized connection string keys.
     * 
     * @throws \RuntimeException 
     */
    protected static function parseAndValidateKeys($connectionString)
    {
        // Initialize the static values if they are not initialized yet.
        if (!static::$isInitialized) {
            static::init();
            static::$isInitialized = true;
        }
        
        $tokenizedSettings = ConnectionStringParser::parseConnectionString(
            'connectionString',
            $connectionString
        );
        
        // Assure that all given keys are valid.
        foreach ($tokenizedSettings as $key => $value) {
            if (!Utilities::inArrayInsensitive($key, static::$validSettingKeys) ) {
                throw new \RuntimeException(
                    sprintf(
                        Resources::INVALID_CONNECTION_STRING_SETTING_KEY,
                        $key,
                        implode("\n", static::$validSettingKeys)
                    )
                );
            }
        }
        
        return $tokenizedSettings;
    }
    
    /**
     * Creates an anonymous function that acts as predicate.
     * 
     * @param array   $requirements The array of conditions to satisfy.
     * @param boolean $isRequired   Either these conditions are all required or all 
     * optional.
     * @param boolean $atLeastOne   Indicates that at least one requirement must
     * succeed.
     * 
     * @return callable
     */
    protected static function getValidator($requirements, $isRequired, $atLeastOne)
    {
        // @codingStandardsIgnoreStart
        
        return function ($userSettings)
         use ($requirements, $isRequired, $atLeastOne) {
            $oneFound = false;
            $result   = array_change_key_case($userSettings);
            foreach ($requirements as $requirement) {
                $settingName = strtolower($requirement[Resources::SETTING_NAME]);
                
                // Check if the setting name exists in the provided user settings.
                if (array_key_exists($settingName, $result)) {
                    // Check if the provided user setting value is valid.
                    $validationFunc = $requirement[Resources::SETTING_CONSTRAINT];
                    $isValid        = $validationFunc($result[$settingName]);
                    
                    if ($isValid) {
                        // Remove the setting as indicator for successful validation.
                        unset($result[$settingName]);
                        $oneFound = true;
                    }
                } else {
                    // If required then fail because the setting does not exist
                    if ($isRequired) {
                        return null;
                    }
                }
            }
            
            if ($atLeastOne) {
                // At least one requirement must succeed, otherwise fail.
                return $oneFound ? $result : null;
            } else {
                return $result;
            }
        };
        
        // @codingStandardsIgnoreEnd
    }
    
    /**
     * Creates at lease one succeed predicate for the provided list of requirements.
     * 
     * @return callable
     */
    protected static function atLeastOne()
    {
        $allSettings = func_get_args();
        return self::getValidator($allSettings, false, true);
    }
    
    /**
     * Creates an optional predicate for the provided list of requirements.
     * 
     * @return callable
     */
    protected static function optional()
    {
        $optionalSettings = func_get_args();
        return self::getValidator($optionalSettings, false, false);
    }
    
    /**
     * Creates an required predicate for the provided list of requirements.
     * 
     * @return callable
     */
    protected static function allRequired()
    {
        $requiredSettings = func_get_args();
        return self::getValidator($requiredSettings, true, false);
    }
    
    /**
     * Creates a setting value condition using the passed predicate.
     * 
     * @param string   $name      The setting key name.
     * @param callable $predicate The setting value predicate.
     * 
     * @return array 
     */
    protected static function settingWithFunc($name, $predicate)
    {
        $requirement                                = array();
        $requirement[Resources::SETTING_NAME]       = $name;
        $requirement[Resources::SETTING_CONSTRAINT] = $predicate;
        
        return $requirement;
    }
    
    /**
     * Creates a setting value condition that validates it is one of the
     * passed valid values.
     * 
     * @param string $name The setting key name.
     * 
     * @return array 
     */
    protected static function setting($name)
    {
        $validValues = func_get_args();
        
        // Remove $name argument.
        unset($validValues[0]);
        
        $validValuesCount = func_num_args();
        
        $predicate = function ($settingValue) use ($validValuesCount, $validValues) {
            if (empty($validValues)) {
                // No restrictions, succeed,
                return true;
            }
            
            // Check to find if the $settingValue is valid or not. The index must
            // start from 1 as unset deletes the value but does not update the array
            // indecies.
            for ($index = 1; $index < $validValuesCount; $index++) {
                if ($settingValue == $validValues[$index]) {
                    // $settingValue is found in valid values set, succeed.
                    return true;
                }
            }
            
            throw new \RuntimeException(
                sprintf(
                    Resources::INVALID_CONFIG_VALUE,
                    $settingValue,
                    implode("\n", $validValues)
                )
            );
            
            // $settingValue is missing in valid values set, fail.
            return false;
        };
        
        return self::settingWithFunc($name, $predicate);
    }
    
    /**
     * Tests to see if a given list of settings matches a set of filters exactly.
     * 
     * @param array $settings The settings to check.
     * 
     * @return boolean If any filter returns null, false. If there are any settings 
     * left over after all filters are processed, false. Otherwise true.
     */
    protected static function matchedSpecification($settings)
    {
        $constraints = func_get_args();
        
        // Remove first element which corresponds to $settings
        unset($constraints[0]);
        
        foreach ($constraints as $constraint) {
            $remainingSettings = $constraint($settings);
            
            if (is_null($remainingSettings)) {
                return false;
            } else {
                $settings = $remainingSettings;
            }
        }
        
        if (empty($settings)) {
            return true;
        }
        
        return false;
    }
}ServicesBuilder.php000060400000037701152440043010010344 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common;
use WindowsAzure\Blob\BlobRestProxy;
use WindowsAzure\Common\Internal\Resources;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Internal\Http\HttpClient;
use WindowsAzure\Common\Internal\Filters\DateFilter;
use WindowsAzure\Common\Internal\Filters\HeadersFilter;
use WindowsAzure\Common\Internal\Filters\AuthenticationFilter;
use WindowsAzure\Common\Internal\Filters\WrapFilter;
use WindowsAzure\Common\Internal\InvalidArgumentTypeException;
use WindowsAzure\Common\Internal\Serialization\XmlSerializer;
use WindowsAzure\Common\Internal\Authentication\SharedKeyAuthScheme;
use WindowsAzure\Common\Internal\Authentication\TableSharedKeyLiteAuthScheme;
use WindowsAzure\Common\Internal\StorageServiceSettings;
use WindowsAzure\Common\Internal\ServiceManagementSettings;
use WindowsAzure\Common\Internal\ServiceBusSettings;
use WindowsAzure\Common\Internal\MediaServicesSettings;
use WindowsAzure\Queue\QueueRestProxy;
use WindowsAzure\ServiceBus\ServiceBusRestProxy;
use WindowsAzure\ServiceBus\Internal\WrapRestProxy;
use WindowsAzure\ServiceManagement\ServiceManagementRestProxy;
use WindowsAzure\Table\TableRestProxy;
use WindowsAzure\Table\Internal\AtomReaderWriter;
use WindowsAzure\Table\Internal\MimeReaderWriter;
use WindowsAzure\MediaServices\MediaServicesRestProxy;
use WindowsAzure\Common\Internal\OAuthRestProxy;
use WindowsAzure\Common\Internal\Authentication\OAuthScheme;


/**
 * Builds azure service objects.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ServicesBuilder
{
    /**
     * @var ServicesBuilder
     */
    private static $_instance = null;

    /**
     * Gets the HTTP client used in the REST services construction.
     *
     * @return WindowsAzure\Common\Internal\Http\IHttpClient
     */
    protected function httpClient()
    {
        return new HttpClient();
    }

    /**
     * Gets the serializer used in the REST services construction.
     *
     * @return WindowsAzure\Common\Internal\Serialization\ISerializer
     */
    protected function serializer()
    {
        return new XmlSerializer();
    }

    /**
     * Gets the MIME serializer used in the REST services construction.
     *
     * @return \WindowsAzure\Table\Internal\IMimeReaderWriter
     */
    protected function mimeSerializer()
    {
        return new MimeReaderWriter();
    }

    /**
     * Gets the Atom serializer used in the REST services construction.
     *
     * @return \WindowsAzure\Table\Internal\IAtomReaderWriter
     */
    protected function atomSerializer()
    {
        return new AtomReaderWriter();
    }

    /**
     * Gets the Queue authentication scheme.
     *
     * @param string $accountName The account name.
     * @param string $accountKey  The account key.
     *
     * @return \WindowsAzure\Common\Internal\Authentication\StorageAuthScheme
     */
    protected function queueAuthenticationScheme($accountName, $accountKey)
    {
        return new SharedKeyAuthScheme($accountName, $accountKey);
    }

    /**
     * Gets the Blob authentication scheme.
     *
     * @param string $accountName The account name.
     * @param string $accountKey  The account key.
     *
     * @return \WindowsAzure\Common\Internal\Authentication\StorageAuthScheme
     */
    protected function blobAuthenticationScheme($accountName, $accountKey)
    {
        return new SharedKeyAuthScheme($accountName, $accountKey);
    }

    /**
     * Gets the Table authentication scheme.
     *
     * @param string $accountName The account name.
     * @param string $accountKey  The account key.
     *
     * @return TableSharedKeyLiteAuthScheme
     */
    protected function tableAuthenticationScheme($accountName, $accountKey)
    {
        return new TableSharedKeyLiteAuthScheme($accountName, $accountKey);
    }

    /**
     * Builds a WRAP client.
     *
     * @param string $wrapEndpointUri The WRAP endpoint uri.
     *
     * @return WindowsAzure\ServiceBus\Internal\IWrap
     */
    protected function createWrapService($wrapEndpointUri)
    {
        $httpClient  = $this->httpClient();
        $wrapWrapper = new WrapRestProxy($httpClient, $wrapEndpointUri);

        return $wrapWrapper;
    }

    /**
     * Builds a queue object.
     *
     * @param string $connectionString The configuration connection string.
     *
     * @return WindowsAzure\Queue\Internal\IQueue
     */
    public function createQueueService($connectionString)
    {
        $settings = StorageServiceSettings::createFromConnectionString(
            $connectionString
        );

        $httpClient = $this->httpClient();
        $serializer = $this->serializer();
        $uri        = Utilities::tryAddUrlScheme(
            $settings->getQueueEndpointUri()
        );

        $queueWrapper = new QueueRestProxy(
            $httpClient,
            $uri,
            $settings->getName(),
            $serializer
        );

        // Adding headers filter
        $headers = array(
            Resources::USER_AGENT => Resources::SDK_USER_AGENT,
        );

        $headers[Resources::X_MS_VERSION] = Resources::STORAGE_API_LATEST_VERSION;

        $headersFilter = new HeadersFilter($headers);
        $queueWrapper  = $queueWrapper->withFilter($headersFilter);

        // Adding date filter
        $dateFilter   = new DateFilter();
        $queueWrapper = $queueWrapper->withFilter($dateFilter);

        // Adding authentication filter
        $authFilter = new AuthenticationFilter(
            $this->queueAuthenticationScheme(
                $settings->getName(),
                $settings->getKey()
            )
        );

        $queueWrapper = $queueWrapper->withFilter($authFilter);

        return $queueWrapper;
    }

    /**
     * Builds a blob object.
     *
     * @param string $connectionString The configuration connection string.
     *
     * @return WindowsAzure\Blob\Internal\IBlob
     */
    public function createBlobService($connectionString)
    {
        $settings = StorageServiceSettings::createFromConnectionString(
            $connectionString
        );

        $httpClient = $this->httpClient();
        $serializer = $this->serializer();
        $uri        = Utilities::tryAddUrlScheme(
            $settings->getBlobEndpointUri()
        );

        $blobWrapper = new BlobRestProxy(
            $httpClient,
            $uri,
            $settings->getName(),
            $serializer
        );

        // Adding headers filter
        $headers = array(
            Resources::USER_AGENT => Resources::SDK_USER_AGENT,
        );

        $headers[Resources::X_MS_VERSION] = Resources::STORAGE_API_LATEST_VERSION;

        $headersFilter = new HeadersFilter($headers);
        $blobWrapper   = $blobWrapper->withFilter($headersFilter);

        // Adding date filter
        $dateFilter  = new DateFilter();
        $blobWrapper = $blobWrapper->withFilter($dateFilter);

        $authFilter = new AuthenticationFilter(
            $this->blobAuthenticationScheme(
                $settings->getName(),
                $settings->getKey()
            )
        );

        $blobWrapper = $blobWrapper->withFilter($authFilter);

        return $blobWrapper;
    }

    /**
     * Builds a table object.
     *
     * @param string $connectionString The configuration connection string.
     *
     * @return WindowsAzure\Table\Internal\ITable
     */
    public function createTableService($connectionString)
    {
        $settings = StorageServiceSettings::createFromConnectionString(
            $connectionString
        );

        $httpClient     = $this->httpClient();
        $atomSerializer = $this->atomSerializer();
        $mimeSerializer = $this->mimeSerializer();
        $serializer     = $this->serializer();
        $uri            = Utilities::tryAddUrlScheme(
            $settings->getTableEndpointUri()
        );

        $tableWrapper = new TableRestProxy(
            $httpClient,
            $uri,
            $atomSerializer,
            $mimeSerializer,
            $serializer
        );

        // Adding headers filter
        $headers               = array();
        $latestServicesVersion = Resources::STORAGE_API_LATEST_VERSION;
        $currentVersion        = Resources::DATA_SERVICE_VERSION_VALUE;
        $maxVersion            = Resources::MAX_DATA_SERVICE_VERSION_VALUE;
        $accept                = Resources::ACCEPT_HEADER_VALUE;
        $acceptCharset         = Resources::ACCEPT_CHARSET_VALUE;
        $userAgent             = Resources::SDK_USER_AGENT;

        $headers[Resources::X_MS_VERSION]             = $latestServicesVersion;
        $headers[Resources::DATA_SERVICE_VERSION]     = $currentVersion;
        $headers[Resources::MAX_DATA_SERVICE_VERSION] = $maxVersion;
        $headers[Resources::MAX_DATA_SERVICE_VERSION] = $maxVersion;
        $headers[Resources::ACCEPT_HEADER]            = $accept;
        $headers[Resources::ACCEPT_CHARSET]           = $acceptCharset;
        $headers[Resources::USER_AGENT]               = $userAgent;

        $headersFilter = new HeadersFilter($headers);
        $tableWrapper  = $tableWrapper->withFilter($headersFilter);

        // Adding date filter
        $dateFilter   = new DateFilter();
        $tableWrapper = $tableWrapper->withFilter($dateFilter);

        // Adding authentication filter
        $authFilter = new AuthenticationFilter(
            $this->tableAuthenticationScheme(
                $settings->getName(),
                $settings->getKey()
            )
        );

        $tableWrapper = $tableWrapper->withFilter($authFilter);

        return $tableWrapper;
    }

    /**
     * Builds a Service Bus object.
     *
     * @param string $connectionString The configuration connection string.
     *
     * @return WindowsAzure\ServiceBus\Internal\IServiceBus
     */
    public function createServiceBusService($connectionString)
    {
        $settings = ServiceBusSettings::createFromConnectionString(
            $connectionString
        );

        $httpClient        = $this->httpClient();
        $serializer        = $this->serializer();
        $serviceBusWrapper = new ServiceBusRestProxy(
            $httpClient,
            $settings->getServiceBusEndpointUri(),
            $serializer
        );

        // Adding headers filter
        $headers = array(
            Resources::USER_AGENT => Resources::SDK_USER_AGENT,
        );

        $headersFilter     = new HeadersFilter($headers);
        $serviceBusWrapper = $serviceBusWrapper->withFilter($headersFilter);

        $wrapFilter = new WrapFilter(
            $settings->getWrapEndpointUri(),
            $settings->getWrapName(),
            $settings->getWrapPassword(),
            $this->createWrapService($settings->getWrapEndpointUri())
        );

        return $serviceBusWrapper->withFilter($wrapFilter);
    }

    /**
     * Builds a service management object.
     *
     * @param string $connectionString The configuration connection string.
     *
     * @return WindowsAzure\ServiceManagement\Internal\IServiceManagement
     */
    public function createServiceManagementService($connectionString)
    {
        $settings = ServiceManagementSettings::createFromConnectionString(
            $connectionString
        );

        $certificatePath = $settings->getCertificatePath();
        $httpClient      = new HttpClient($certificatePath);
        $serializer      = $this->serializer();
        $uri             = Utilities::tryAddUrlScheme(
            $settings->getEndpointUri(),
            Resources::HTTPS_SCHEME
        );

        $serviceManagementWrapper = new ServiceManagementRestProxy(
            $httpClient,
            $settings->getSubscriptionId(),
            $uri,
            $serializer
        );

        // Adding headers filter
        $headers = array(
            Resources::USER_AGENT => Resources::SDK_USER_AGENT
        );

        $headers[Resources::X_MS_VERSION] = Resources::SM_API_LATEST_VERSION;

        $headersFilter            = new HeadersFilter($headers);
        $serviceManagementWrapper = $serviceManagementWrapper->withFilter(
            $headersFilter
        );

        return $serviceManagementWrapper;
    }

    /**
     * Builds a media services object.
     *
     * @param WindowsAzure\Common\Internal\MediaServicesSettings $settings The media
     * services configuration settings.
     *
     * @return WindowsAzure\MediaServices\Internal\IMediaServices
     */
    public function createMediaServicesService($settings)
    {
        Validate::isA(
            $settings,
            'WindowsAzure\Common\Internal\MediaServicesSettings',
            'settings'
        );

        $httpClient = new HttpClient();
        $serializer = $this->serializer();
        $uri        = Utilities::tryAddUrlScheme(
            $settings->getEndpointUri(),
            Resources::HTTPS_SCHEME
        );

        $mediaServicesWrapper = new MediaServicesRestProxy(
            $httpClient,
            $uri,
            $settings->getAccountName(),
            $serializer
        );

        // Adding headers filter
        $xMSVersion     = Resources::MEDIA_SERVICES_API_LATEST_VERSION;
        $dataVersion    = Resources::MEDIA_SERVICES_DATA_SERVICE_VERSION_VALUE;
        $dataMaxVersion = Resources::MEDIA_SERVICES_MAX_DATA_SERVICE_VERSION_VALUE;
        $accept         = Resources::ACCEPT_HEADER_VALUE;
        $contentType    = Resources::ATOM_ENTRY_CONTENT_TYPE;
        $userAgent      = Resources::SDK_USER_AGENT;

        $headers = array(
            Resources::X_MS_VERSION             => $xMSVersion,
            Resources::DATA_SERVICE_VERSION     => $dataVersion,
            Resources::MAX_DATA_SERVICE_VERSION => $dataMaxVersion,
            Resources::ACCEPT_HEADER            => $accept,
            Resources::CONTENT_TYPE             => $contentType,
            Resources::USER_AGENT               => $userAgent,
        );

        $headersFilter        = new HeadersFilter($headers);
        $mediaServicesWrapper = $mediaServicesWrapper->withFilter($headersFilter);

        // Adding OAuth filter
        $oauthService           = new OAuthRestProxy(
            new HttpClient(),
            $settings->getOAuthEndpointUri()
        );
        $authentification       = new OAuthScheme(
            $settings->getAccountName(),
            $settings->getAccessKey(),
            Resources::OAUTH_GT_CLIENT_CREDENTIALS,
            Resources::MEDIA_SERVICES_OAUTH_SCOPE,
            $oauthService
        );
        $authentificationFilter = new AuthenticationFilter($authentification);
        $mediaServicesWrapper   = $mediaServicesWrapper->withFilter(
            $authentificationFilter
        );

        return $mediaServicesWrapper;
    }

    /**
     * Gets the static instance of this class.
     *
     * @return ServicesBuilder
     */
    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$_instance = new ServicesBuilder();
        }

        return self::$_instance;
    }
}Models/OAuthAccessToken.php000060400000006577152440043010011647 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 *
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Models;
use WindowsAzure\Common\Internal\Resources;

/**
 * Holds OAuth access token data.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class OAuthAccessToken
{
    /**
     * Access token itself
     *
     * @var string
     */
    private $_accessToken;

    /**
     * Unix time the access token valid before.
     *
     * @var int
     */
    private $_expiresIn;

    /**
     * Scope of access token
     *
     * @var string.
     */
    private $_scope;

    /**
     * Creates object from $parsedResponse.
     *
     * @param array $parsedResponse JSON response parsed into array.
     *
     * @return WindowsAzure\Common\Models\OAuthAccessToken
     */
    public static function create($parsedResponse)
    {
        $result = new OAuthAccessToken();

        $result->setAccessToken($parsedResponse[Resources::OAUTH_ACCESS_TOKEN]);
        $result->setExpiresIn($parsedResponse[Resources::OAUTH_EXPIRES_IN] + time());
        $result->setScope($parsedResponse[Resources::OAUTH_SCOPE]);

        return $result;
    }

    /**
     * Gets access token
     *
     * @return string
     */
    public function getAccessToken()
    {
        return $this->_accessToken;
    }


    /**
     * Sets access token
     *
     * @param string $accessToken OAuth access token
     *
     * @return none
     */
    public function setAccessToken($accessToken)
    {
        $this->_accessToken = $accessToken;
    }


    /**
     * Gets expired date of access token in unixdate
     *
     * @return int
     *
     */
    public function getExpiresIn()
    {
        return $this->_expiresIn;
    }


    /**
     * Sets access token expires date
     *
     * @param int $expiresIn OAuth access token expire date
     *
     * @return none
     */
    public function setExpiresIn($expiresIn)
    {
        $this->_expiresIn = $expiresIn;
    }

    /**
     * Gets access token scope
     *
     * @return string
     *
     */
    public function getScope()
    {
        return $this->_scope;
    }


    /**
     * Sets access token scope
     *
     * @param string $scope OAuth access token scope
     *
     * @return none
     */
    public function setScope($scope)
    {
        $this->_scope = $scope;
    }
}


Models/ServiceProperties.php000060400000007310152440043010012143 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Models;
use WindowsAzure\Common\Internal\Utilities;
use WindowsAzure\Common\Models\Logging;
use WindowsAzure\Common\Models\Metrics;
use WindowsAzure\Common\Internal\Serialization\XmlSerializer;

/**
 * Encapsulates service properties
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class ServiceProperties
{
    private $_logging;
    private $_metrics;
    public static $xmlRootName = 'StorageServiceProperties';
    
    /**
     * Creates ServiceProperties object from parsed XML response.
     *
     * @param array $parsedResponse XML response parsed into array.
     * 
     * @return WindowsAzure\Common\Models\ServiceProperties.
     */
    public static function create($parsedResponse)
    {
        $result = new ServiceProperties();
        $result->setLogging(Logging::create($parsedResponse['Logging']));
        $result->setMetrics(Metrics::create($parsedResponse['Metrics']));
        
        return $result;
    }
    
    /**
     * Gets logging element.
     *
     * @return WindowsAzure\Common\Models\Logging.
     */
    public function getLogging()
    {
        return $this->_logging;
    }
    
    /**
     * Sets logging element.
     *
     * @param WindowsAzure\Common\Models\Logging $logging new element.
     * 
     * @return none.
     */
    public function setLogging($logging)
    {
        $this->_logging = clone $logging;
    }
    
    /**
     * Gets metrics element.
     *
     * @return WindowsAzure\Common\Models\Metrics.
     */
    public function getMetrics()
    {
        return $this->_metrics;
    }
    
    /**
     * Sets metrics element.
     *
     * @param WindowsAzure\Common\Models\Metrics $metrics new element.
     * 
     * @return none.
     */
    public function setMetrics($metrics)
    {
        $this->_metrics = clone $metrics;
    }
    
    /**
     * Converts this object to array with XML tags
     * 
     * @return array. 
     */
    public function toArray()
    {
        return array(
            'Logging' => !empty($this->_logging) ? $this->_logging->toArray() : null,
            'Metrics' => !empty($this->_metrics) ? $this->_metrics->toArray() : null
        );
    }
    
    /**
     * Converts this current object to XML representation.
     * 
     * @param XmlSerializer $xmlSerializer The XML serializer.
     * 
     * @return string
     */
    public function toXml($xmlSerializer)
    {
        $properties = array(XmlSerializer::ROOT_NAME => self::$xmlRootName);
        
        return $xmlSerializer->serialize($this->toArray(), $properties);
    }
}


Models/.htaccess000044400000000424152440043010007554 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Models/GetServicePropertiesResult.php000060400000004604152440043010014005 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */

namespace WindowsAzure\Common\Models;
use WindowsAzure\Common\Models\ServiceProperties;

/**
 * Result from calling GetQueueProperties REST wrapper.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class GetServicePropertiesResult
{
    private $_serviceProperties;
    
    /**
     * Creates object from $parsedResponse.
     * 
     * @param array $parsedResponse XML response parsed into array.
     * 
     * @return WindowsAzure\Common\Models\GetServicePropertiesResult
     */
    public static function create($parsedResponse)
    {
        $result                     = new GetServicePropertiesResult();
        $result->_serviceProperties = ServiceProperties::create($parsedResponse);
        
        return $result;
    }
    
    /**
     * Gets service properties object.
     * 
     * @return WindowsAzure\Common\Models\ServiceProperties 
     */
    public function getValue()
    {
        return $this->_serviceProperties;
    }
    
    /**
     * Sets service properties object.
     * 
     * @param ServiceProperties $serviceProperties object to use.
     * 
     * @return none 
     */
    public function setValue($serviceProperties)
    {
        $this->_serviceProperties = clone $serviceProperties;
    }
}


Models/RetentionPolicy.php000060400000006642152440043010011624 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Models;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Holds elements of queue properties retention policy field.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class RetentionPolicy
{
    /**
     * Indicates whether a retention policy is enabled for the storage service
     * 
     * @var bool.
     */
    private $_enabled;
    
    /**
     * If $_enabled is true then this field indicates the number of days that metrics
     * or logging data should be retained. All data older than this value will be 
     * deleted. The minimum value you can specify is 1; 
     * the largest value is 365 (one year)
     * 
     * @var int
     */
    private $_days;
    
    /**
     * Creates object from $parsedResponse.
     * 
     * @param array $parsedResponse XML response parsed into array.
     * 
     * @return WindowsAzure\Common\Models\RetentionPolicy
     */
    public static function create($parsedResponse)
    {
        $result = new RetentionPolicy();
        $result->setEnabled(Utilities::toBoolean($parsedResponse['Enabled']));
        if ($result->getEnabled()) {
            $result->setDays(intval($parsedResponse['Days']));
        }
        
        return $result;
    }
    
    /**
     * Gets enabled.
     * 
     * @return bool. 
     */
    public function getEnabled()
    {
        return $this->_enabled;
    }
    
    /**
     * Sets enabled.
     * 
     * @param bool $enabled value to use.
     * 
     * @return none. 
     */
    public function setEnabled($enabled)
    {
        $this->_enabled = $enabled;
    }
    
    /**
     * Gets days field.
     * 
     * @return int
     */
    public function getDays()
    {
        return $this->_days;
    }
    
    /**
     * Sets days field.
     * 
     * @param int $days value to use.
     * 
     * @return none
     */
    public function setDays($days)
    {
        $this->_days = $days;
    }
    
    /**
     * Converts this object to array with XML tags
     * 
     * @return array. 
     */
    public function toArray()
    {
        $array = array('Enabled' => Utilities::booleanToString($this->_enabled));
        if (isset($this->_days)) {
            $array['Days'] = strval($this->_days);
        }
        
        return $array;
    }
}


Models/Logging.php000060400000012371152440043010010057 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Models;
use WindowsAzure\Common\Models\RetentionPolicy;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Holds elements of queue properties logging field.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class Logging
{
    /**
     * The version of Storage Analytics to configure
     * 
     * @var string
     */
    private $_version;
    
    /**
     * Applies only to logging configuration. Indicates whether all delete requests 
     * should be logged.
     * 
     * @var bool
     */
    private $_delete;
    
    /**
     * Applies only to logging configuration. Indicates whether all read requests 
     * should be logged.
     * 
     * @var bool.
     */
    private $_read;
    
    /**
     * Applies only to logging configuration. Indicates whether all write requests 
     * should be logged.
     * 
     * @var bool 
     */
    private $_write;
    
    /**
     * @var WindowsAzure\Common\Models\RetentionPolicy
     */
    private $_retentionPolicy;
    
    /**
     * Creates object from $parsedResponse.
     * 
     * @param array $parsedResponse XML response parsed into array.
     * 
     * @return WindowsAzure\Common\Models\Logging
     */
    public static function create($parsedResponse)
    {
        $result = new Logging();
        $result->setVersion($parsedResponse['Version']);
        $result->setDelete(Utilities::toBoolean($parsedResponse['Delete']));
        $result->setRead(Utilities::toBoolean($parsedResponse['Read']));
        $result->setWrite(Utilities::toBoolean($parsedResponse['Write']));
        $result->setRetentionPolicy(
            RetentionPolicy::create($parsedResponse['RetentionPolicy'])
        );
        
        return $result;
    }
    
    /**
     * Gets retention policy
     * 
     * @return WindowsAzure\Common\Models\RetentionPolicy
     *  
     */
    public function getRetentionPolicy()
    {
        return $this->_retentionPolicy;
    }
    
    /**
     * Sets retention policy
     * 
     * @param RetentionPolicy $policy object to use
     * 
     * @return none.
     */
    public function setRetentionPolicy($policy)
    {
        $this->_retentionPolicy = $policy;
    }
    
    /**
     * Gets write
     * 
     * @return bool.
     */
    public function getWrite()
    {
        return $this->_write;
    }
    
    /**
     * Sets write
     * 
     * @param bool $write new value.
     * 
     * @return none.
     */
    public function setWrite($write)
    {
        $this->_write = $write;
    }
            
    /**
     * Gets read
     * 
     * @return bool.
     */
    public function getRead()
    {
        return $this->_read;
    }
    
    /**
     * Sets read
     * 
     * @param bool $read new value.
     * 
     * @return none.
     */
    public function setRead($read)
    {
        $this->_read = $read;
    }
    
    /**
     * Gets delete
     * 
     * @return bool.
     */
    public function getDelete()
    {
        return $this->_delete;
    }
    
    /**
     * Sets delete
     * 
     * @param bool $delete new value.
     * 
     * @return none.
     */
    public function setDelete($delete)
    {
        $this->_delete = $delete;
    }
    
    /**
     * Gets version
     * 
     * @return string.
     */
    public function getVersion()
    {
        return $this->_version;
    }
    
    /**
     * Sets version
     * 
     * @param string $version new value.
     * 
     * @return none.
     */
    public function setVersion($version)
    {
        $this->_version = $version;
    }
    
    /**
     * Converts this object to array with XML tags
     * 
     * @return array. 
     */
    public function toArray()
    {
        return array(
            'Version'         => $this->_version,
            'Delete'          => Utilities::booleanToString($this->_delete),
            'Read'            => Utilities::booleanToString($this->_read),
            'Write'           => Utilities::booleanToString($this->_write),
            'RetentionPolicy' => !empty($this->_retentionPolicy)
                ? $this->_retentionPolicy->toArray()
                : null
        );
    }
}


Models/Metrics.php000060400000011345152440043010010077 0ustar00<?php

/**
 * LICENSE: Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.
 * 
 * PHP version 5
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
 
namespace WindowsAzure\Common\Models;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Holds elements of queue properties metrics field.
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.1_2015-03
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class Metrics
{
    /**
     * The version of Storage Analytics to configure
     * 
     * @var string
     */
    private $_version;
    
    /**
     * Indicates whether metrics is enabled for the storage service
     * 
     * @var bool
     */
    private $_enabled;
    
    /**
     * Indicates whether a retention policy is enabled for the storage service
     * 
     * @var bool
     */
    private $_includeAPIs;
    
    /**
     * @var WindowsAzure\Common\Models\RetentionPolicy
     */
    private $_retentionPolicy;
    
    /**
     * Creates object from $parsedResponse.
     * 
     * @param array $parsedResponse XML response parsed into array.
     * 
     * @return WindowsAzure\Common\Models\Metrics
     */
    public static function create($parsedResponse)
    {
        $result = new Metrics();
        $result->setVersion($parsedResponse['Version']);
        $result->setEnabled(Utilities::toBoolean($parsedResponse['Enabled']));
        if ($result->getEnabled()) {
            $result->setIncludeAPIs(
                Utilities::toBoolean($parsedResponse['IncludeAPIs'])
            );
        }
        $result->setRetentionPolicy(
            RetentionPolicy::create($parsedResponse['RetentionPolicy'])
        );
        
        return $result;
    }
    
    /**
     * Gets retention policy
     * 
     * @return WindowsAzure\Common\Models\RetentionPolicy
     *  
     */
    public function getRetentionPolicy()
    {
        return $this->_retentionPolicy;
    }
    
    /**
     * Sets retention policy
     * 
     * @param RetentionPolicy $policy object to use
     * 
     * @return none.
     */
    public function setRetentionPolicy($policy)
    {
        $this->_retentionPolicy = $policy;
    }
    
    /**
     * Gets include APIs.
     * 
     * @return bool. 
     */
    public function getIncludeAPIs()
    {
        return $this->_includeAPIs;
    }
    
    /**
     * Sets include APIs.
     * 
     * @param $bool $includeAPIs value to use.
     * 
     * @return none. 
     */
    public function setIncludeAPIs($includeAPIs)
    {
        $this->_includeAPIs = $includeAPIs;
    }
    
    /**
     * Gets enabled.
     * 
     * @return bool. 
     */
    public function getEnabled()
    {
        return $this->_enabled;
    }
    
    /**
     * Sets enabled.
     * 
     * @param bool $enabled value to use.
     * 
     * @return none. 
     */
    public function setEnabled($enabled)
    {
        $this->_enabled = $enabled;
    }
    
    /**
     * Gets version
     * 
     * @return string.
     */
    public function getVersion()
    {
        return $this->_version;
    }
    
    /**
     * Sets version
     * 
     * @param string $version new value.
     * 
     * @return none.
     */
    public function setVersion($version)
    {
        $this->_version = $version;
    }
    
    /**
     * Converts this object to array with XML tags
     * 
     * @return array. 
     */
    public function toArray()
    {
        $array = array(
            'Version' => $this->_version,
            'Enabled' => Utilities::booleanToString($this->_enabled)
        );
        if ($this->_enabled) {
            $array['IncludeAPIs'] = Utilities::booleanToString($this->_includeAPIs);
        }
        $array['RetentionPolicy'] = !empty($this->_retentionPolicy)
            ? $this->_retentionPolicy->toArray()
            : null;
        
        return $array;
    }
}


Exception/InvalidArgumentException.php000060400000001441152440537420014165 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * AWS SDK namespaced version of the SPL InvalidArgumentException.
 */
class InvalidArgumentException extends \InvalidArgumentException implements AwsExceptionInterface {}
Exception/ExceptionCollection.php000060400000005420152440537420013170 0ustar00<?php

namespace Guzzle\Common\Exception;

/**
 * Collection of exceptions
 */
class ExceptionCollection extends \Exception implements GuzzleException, \IteratorAggregate, \Countable
{
    /** @var array Array of Exceptions */
    protected $exceptions = array();

    /** @var string Succinct exception message not including sub-exceptions */
    private $shortMessage;

    public function __construct($message = '', $code = 0, \Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
        $this->shortMessage = $message;
    }

    /**
     * Set all of the exceptions
     *
     * @param array $exceptions Array of exceptions
     *
     * @return self
     */
    public function setExceptions(array $exceptions)
    {
        $this->exceptions = array();
        foreach ($exceptions as $exception) {
            $this->add($exception);
        }

        return $this;
    }

    /**
     * Add exceptions to the collection
     *
     * @param ExceptionCollection|\Exception $e Exception to add
     *
     * @return ExceptionCollection;
     */
    public function add($e)
    {
        $this->exceptions[] = $e;
        if ($this->message) {
            $this->message .= "\n";
        }

        $this->message .= $this->getExceptionMessage($e, 0);

        return $this;
    }

    /**
     * Get the total number of request exceptions
     *
     * @return int
     */
    public function count()
    {
        return count($this->exceptions);
    }

    /**
     * Allows array-like iteration over the request exceptions
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->exceptions);
    }

    /**
     * Get the first exception in the collection
     *
     * @return \Exception
     */
    public function getFirst()
    {
        return $this->exceptions ? $this->exceptions[0] : null;
    }

    private function getExceptionMessage(\Exception $e, $depth = 0)
    {
        static $sp = '    ';
        $prefix = $depth ? str_repeat($sp, $depth) : '';
        $message = "{$prefix}(" . get_class($e) . ') ' . $e->getFile() . ' line ' . $e->getLine() . "\n";

        if ($e instanceof self) {
            if ($e->shortMessage) {
                $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->shortMessage) . "\n";
            }
            foreach ($e as $ee) {
                $message .= "\n" . $this->getExceptionMessage($ee, $depth + 1);
            }
        }  else {
            $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->getMessage()) . "\n";
            $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->getTraceAsString()) . "\n";
        }

        return str_replace(getcwd(), '.', $message);
    }
}
Exception/RuntimeException.php000060400000001411152440537420012514 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * AWS SDK namespaced version of the SPL RuntimeException.
 */
class RuntimeException extends \RuntimeException implements AwsExceptionInterface {}
Exception/UnexpectedValueException.php000060400000001441152440537420014175 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * AWS SDK namespaced version of the SPL UnexpectedValueException.
 */
class UnexpectedValueException extends \UnexpectedValueException implements AwsExceptionInterface {}
Exception/BadMethodCallException.php000060400000001433152440537420013520 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * AWS SDK namespaced version of the SPL BadMethodCallException.
 */
class BadMethodCallException extends \BadMethodCallException implements AwsExceptionInterface {}
Exception/GuzzleException.php000060400000000144152440537420012353 0ustar00<?php

namespace Guzzle\Common\Exception;

/**
 * Guzzle exception
 */
interface GuzzleException {}
Exception/.htaccess000044400000000424152440537420010304 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>composer.json000060400000000767152440537420007302 0ustar00{
    "name": "guzzle/common",
    "homepage": "http://guzzlephp.org/",
    "description": "Common libraries used by Guzzle",
    "keywords": ["common", "event", "exception", "collection"],
    "license": "MIT",
    "require": {
        "php": ">=5.3.2",
        "symfony/event-dispatcher": ">=2.1"
    },
    "autoload": {
        "psr-0": { "Guzzle\\Common": "" }
    },
    "target-dir": "Guzzle/Common",
    "extra": {
        "branch-alias": {
            "dev-master": "3.7-dev"
        }
    }
}
AbstractHasDispatcher.php000060400000002253152440537420011467 0ustar00<?php

namespace Guzzle\Common;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class that holds an event dispatcher
 */
class AbstractHasDispatcher implements HasDispatcherInterface
{
    /** @var EventDispatcherInterface */
    protected $eventDispatcher;

    public static function getAllEvents()
    {
        return array();
    }

    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
    {
        $this->eventDispatcher = $eventDispatcher;

        return $this;
    }

    public function getEventDispatcher()
    {
        if (!$this->eventDispatcher) {
            $this->eventDispatcher = new EventDispatcher();
        }

        return $this->eventDispatcher;
    }

    public function dispatch($eventName, array $context = array())
    {
        return $this->getEventDispatcher()->dispatch($eventName, new Event($context));
    }

    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        $this->getEventDispatcher()->addSubscriber($subscriber);

        return $this;
    }
}
HasDispatcherInterface.php000060400000002516152440537420011626 0ustar00<?php

namespace Guzzle\Common;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Holds an event dispatcher
 */
interface HasDispatcherInterface
{
    /**
     * Get a list of all of the events emitted from the class
     *
     * @return array
     */
    public static function getAllEvents();

    /**
     * Set the EventDispatcher of the request
     *
     * @param EventDispatcherInterface $eventDispatcher
     *
     * @return self
     */
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher);

    /**
     * Get the EventDispatcher of the request
     *
     * @return EventDispatcherInterface
     */
    public function getEventDispatcher();

    /**
     * Helper to dispatch Guzzle events and set the event name on the event
     *
     * @param string $eventName Name of the event to dispatch
     * @param array  $context   Context of the event
     *
     * @return Event Returns the created event object
     */
    public function dispatch($eventName, array $context = array());

    /**
     * Add an event subscriber to the dispatcher
     *
     * @param EventSubscriberInterface $subscriber Event subscriber
     *
     * @return self
     */
    public function addSubscriber(EventSubscriberInterface $subscriber);
}
Collection.php000060400000026254152440537420007363 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common;

use OpenCloud\Common\Log\Logger;

/**
 * @deprecated
 * @codeCoverageIgnore
 */
class Collection extends Base
{
    private $service;
    private $itemClass;
    private $itemList = array();
    private $pointer = 0;
    private $sortKey;
    private $nextPageClass;
    private $nextPageCallback;
    private $nextPageUrl;

    /**
     * A Collection is an array of objects
     *
     * Some assumptions:
     * * The `Collection` class assumes that there exists on its service
     *   a factory method with the same name of the class. For example, if
     *   you create a Collection of class `Foobar`, it will attempt to call
     *   the method `parent::Foobar()` to create instances of that class.
     * * It assumes that the factory method can take an array of values, and
     *   it passes that to the method.
     *
     * @param Service $service   - the service associated with the collection
     * @param string  $itemclass - the Class of each item in the collection
     *                           (assumed to be the name of the factory method)
     * @param array   $arr       - the input array
     */
    public function __construct($service, $class, array $array = array())
    {
        $service->getLogger()->warning(Logger::deprecated(__METHOD__, 'OpenCloud\Common\Collection\CollectionBuilder'));

        $this->setService($service);

        $this->setNextPageClass($class);

        // If they've supplied a FQCN, only get the last part
        $class = (false !== ($classNamePos = strrpos($class, '\\')))
            ? substr($class, $classNamePos + 1)
            : $class;

        $this->setItemClass($class);

        // Set data
        $this->setItemList($array);
    }

    /**
     * Set the entire data array.
     *
     * @param array $array
     */
    private function setItemList(array $array)
    {
        $this->itemList = $array;

        return $this;
    }

    /**
     * Retrieve the entire data array.
     *
     * @return array
     */
    public function getItemList()
    {
        return $this->itemList;
    }

    /**
     * Set the service.
     *
     * @param Service|PersistentObject $service
     */
    public function setService($service)
    {
        $this->service = $service;

        return $this;
    }

    /**
     * Retrieves the service associated with the Collection
     *
     * @return Service
     */
    public function getService()
    {
        return $this->service;
    }

    /**
     * Set the resource class name.
     */
    private function setItemClass($itemClass)
    {
        $this->itemClass = $itemClass;

        return $this;
    }

    /**
     * Get item class.
     */
    private function getItemClass()
    {
        return $this->itemClass;
    }

    /**
     * Set the key that will be used for sorting.
     */
    private function setSortKey($sortKey)
    {
        $this->sortKey = $sortKey;

        return $this;
    }

    /**
     * Get the key that will be used for sorting.
     */
    private function getSortKey()
    {
        return $this->sortKey;
    }

    /**
     * Set next page class.
     */
    private function setNextPageClass($nextPageClass)
    {
        $this->nextPageClass = $nextPageClass;

        return $this;
    }

    /**
     * Get next page class.
     */
    private function getNextPageClass()
    {
        return $this->nextPageClass;
    }

    /**
     * for paginated collection, sets the callback function and URL for
     * the next page
     *
     * The callback function should have the signature:
     *
     *      function Whatever($class, $url, $parent)
     *
     * and the `$url` should be the URL of the next page of results
     *
     * @param callable $callback the name of the function (or array of
     *                           object, function name)
     * @param string   $url      the URL of the next page of results
     * @return void
     */
    public function setNextPageCallback($callback, $url)
    {
        $this->nextPageCallback = $callback;
        $this->nextPageUrl = $url;

        return $this;
    }

    /**
     * Get next page callback.
     */
    private function getNextPageCallback()
    {
        return $this->nextPageCallback;
    }

    /**
     * Get next page URL.
     */
    private function getNextPageUrl()
    {
        return $this->nextPageUrl;
    }

    /**
     * Returns the number of items in the collection
     *
     * For most services, this is the total number of items. If the Collection
     * is paginated, however, this only returns the count of items in the
     * current page of data.
     *
     * @return int
     */
    public function count()
    {
        return count($this->getItemList());
    }

    /**
     * Pseudonym for count()
     *
     * @codeCoverageIgnore
     */
    public function size()
    {
        return $this->count();
    }

    /**
     * Resets the pointer to the beginning, but does NOT return the first item
     *
     * @api
     * @return void
     */
    public function reset()
    {
        $this->pointer = 0;
    }

    /**
     * Resets the collection pointer back to the first item in the page
     * and returns it
     *
     * This is useful if you're only interested in the first item in the page.
     *
     * @api
     * @return Base the first item in the set
     */
    public function first()
    {
        $this->reset();

        return $this->next();
    }

    /**
     * Return the item at a particular point of the array.
     *
     * @param  mixed $offset
     * @return mixed
     */
    public function getItem($pointer)
    {
        return (isset($this->itemList[$pointer])) ? $this->itemList[$pointer] : false;
    }

    /**
     * Add an item to this collection
     *
     * @param mixed $item
     */
    public function addItem($item)
    {
        $this->itemList[] = $item;
    }

    /**
     * Returns the next item in the page
     *
     * @api
     * @return Base the next item or FALSE if at the end of the page
     */
    public function next()
    {
        if ($this->pointer >= $this->count()) {
            return false;
        }

        $data = $this->getItem($this->pointer++);
        $class = $this->getItemClass();

        // Are there specific methods in the parent/service that can be used to
        // instantiate the resource? Currently supported: getResource(), resource()
        foreach (array($class, 'get' . ucfirst($class)) as $method) {
            if (method_exists($this->service, $method)) {
                return call_user_func(array($this->service, $method), $data);
            }
        }

        // Backup method
        if (method_exists($this->service, 'resource')) {
            return $this->service->resource($class, $data);
        }

        return false;
    }

    /**
     * sorts the collection on a specified key
     *
     * Note: only top-level keys can be used as the sort key. Note that this
     * only sorts the data in the current page of the Collection (for
     * multi-page data).
     *
     * @api
     * @param string $keyname the name of the field to use as the sort key
     * @return void
     */
    public function sort($keyname = 'id')
    {
        $this->setSortKey($keyname);
        usort($this->itemList, array($this, 'sortCompare'));
    }

    /**
     * selects only specified items from the Collection
     *
     * This provides a simple form of filtering on Collections. For each item
     * in the collection, it calls the callback function, passing it the item.
     * If the callback returns `TRUE`, then the item is retained; if it returns
     * `FALSE`, then the item is deleted from the collection.
     *
     * Note that this should not supersede server-side filtering; the
     * `Collection::Select()` method requires that *all* of the data for the
     * Collection be retrieved from the server before the filtering is
     * performed; this can be very inefficient, especially for large data
     * sets. This method is mostly useful on smaller-sized sets.
     *
     * Example:
     * <code>
     * $services = $connection->ServiceList();
     * $services->Select(function ($item) { return $item->region=='ORD';});
     * // now the $services Collection only has items from the ORD region
     * </code>
     *
     * `Select()` is *destructive*; that is, it actually removes entries from
     * the collection. For example, if you use `Select()` to find items with
     * the ID > 10, then use it again to find items that are <= 10, it will
     * return an empty list.
     *
     * @api
     * @param callable $testfunc a callback function that is passed each item
     *                           in turn. Note that `Select()` performs an explicit test for
     *                           `FALSE`, so functions like `strpos()` need to be cast into a
     *                           boolean value (and not just return the integer).
     * @returns void
     * @throws DomainError if callback doesn't return a boolean value
     */
    public function select($testfunc)
    {
        foreach ($this->getItemList() as $index => $item) {
            $test = call_user_func($testfunc, $item);
            if (!is_bool($test)) {
                throw new Exceptions\DomainError(
                    Lang::translate('Callback function for Collection::Select() did not return boolean')
                );
            }
            if ($test === false) {
                unset($this->itemList[$index]);
            }
        }
    }

    /**
     * returns the Collection object for the next page of results, or
     * FALSE if there are no more pages
     *
     * Generally, the structure for a multi-page collection will look like
     * this:
     *
     *      $coll = $obj->Collection();
     *      do {
     *          while ($item = $coll->Next()) {
     *              // do something with the item
     *          }
     *      } while ($coll = $coll->NextPage());
     *
     * @api
     * @return Collection if there are more pages of results, otherwise FALSE
     */
    public function nextPage()
    {
        return ($this->getNextPageUrl() !== null)
            ? call_user_func($this->getNextPageCallback(), $this->getNextPageClass(), $this->getNextPageUrl())
            : false;
    }

    /**
     * Compares two values of sort keys
     */
    private function sortCompare($a, $b)
    {
        $key = $this->getSortKey();

        // Handle strings
        if (is_string($a->$key)) {
            return strcmp($a->$key, $b->$key);
        }

        // Handle others with logical comparisons
        if ($a->$key == $b->$key) {
            return 0;
        } elseif ($a->$key < $b->$key) {
            return -1;
        } else {
            return 1;
        }
    }
}
Version.php000060400000001201152440537420006676 0ustar00<?php

namespace Guzzle\Common;

/**
 * Guzzle version information
 */
class Version
{
    const VERSION = '3.8.1';

    /**
     * @var bool Set this value to true to enable warnings for deprecated functionality use. This should be on in your
     *           unit tests, but probably not in production.
     */
    public static $emitWarnings = false;

    /**
     * Emit a deprecation warning
     *
     * @param string $message Warning message
     */
    public static function warn($message)
    {
        if (self::$emitWarnings) {
            trigger_error('Deprecation warning: ' . $message, E_USER_DEPRECATED);
        }
    }
}
ToArrayInterface.php000060400000000365152440537420010465 0ustar00<?php

namespace Guzzle\Common;

/**
 * An object that can be represented as an array
 */
interface ToArrayInterface
{
    /**
     * Get the array representation of an object
     *
     * @return array
     */
    public function toArray();
}
FromConfigInterface.php000060400000000747152440537420011141 0ustar00<?php

namespace Guzzle\Common;

/**
 * Interfaces that adds a factory method which is used to instantiate a class from an array of configuration options.
 */
interface FromConfigInterface
{
    /**
     * Static factory method used to turn an array or collection of configuration data into an instantiated object.
     *
     * @param array|Collection $config Configuration data
     *
     * @return FromConfigInterface
     */
    public static function factory($config = array());
}
Event.php000060400000002050152440537420006335 0ustar00<?php

namespace Guzzle\Common;

use Symfony\Component\EventDispatcher\Event as SymfonyEvent;

/**
 * Default event for Guzzle notifications
 */
class Event extends SymfonyEvent implements ToArrayInterface, \ArrayAccess, \IteratorAggregate
{
    /** @var array */
    private $context;

    /**
     * @param array $context Contextual information
     */
    public function __construct(array $context = array())
    {
        $this->context = $context;
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->context);
    }

    public function offsetGet($offset)
    {
        return isset($this->context[$offset]) ? $this->context[$offset] : null;
    }

    public function offsetSet($offset, $value)
    {
        $this->context[$offset] = $value;
    }

    public function offsetExists($offset)
    {
        return isset($this->context[$offset]);
    }

    public function offsetUnset($offset)
    {
        unset($this->context[$offset]);
    }

    public function toArray()
    {
        return $this->context;
    }
}
Enum/Region.php000060400000003776152440555050007422 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Enum;

use Aws\Common\Enum;

/**
 * Contains enumerable region code values. These should be useful in most cases,
 * with Amazon S3 being the most notable exception
 *
 * @link http://docs.aws.amazon.com/general/latest/gr/rande.html AWS Regions and Endpoints
 */
class Region extends Enum
{
    const US_EAST_1           = 'us-east-1';
    const VIRGINIA            = 'us-east-1';
    const NORTHERN_VIRGINIA   = 'us-east-1';

    const US_WEST_1           = 'us-west-1';
    const CALIFORNIA          = 'us-west-1';
    const NORTHERN_CALIFORNIA = 'us-west-1';

    const US_WEST_2           = 'us-west-2';
    const OREGON              = 'us-west-2';

    const EU_WEST_1           = 'eu-west-1';
    const IRELAND             = 'eu-west-1';
    
    const EU_CENTRAL_1        = 'eu-central-1';
    const FRANKFURT           = 'eu-central-1';

    const AP_SOUTHEAST_1      = 'ap-southeast-1';
    const SINGAPORE           = 'ap-southeast-1';

    const AP_SOUTHEAST_2      = 'ap-southeast-2';
    const SYDNEY              = 'ap-southeast-2';

    const AP_NORTHEAST_1      = 'ap-northeast-1';
    const TOKYO               = 'ap-northeast-1';

    const SA_EAST_1           = 'sa-east-1';
    const SAO_PAULO           = 'sa-east-1';

    const CN_NORTH_1          = 'cn-north-1';
    const BEIJING             = 'cn-north-1';

    const US_GOV_WEST_1       = 'us-gov-west-1';
    const GOV_CLOUD_US        = 'us-gov-west-1';
}
Enum/ClientOptions.php000060400000011271152440555050010756 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Enum;

use Aws\Common\Enum;

/**
 * Contains enumerable default factory options that can be passed to a client's factory method
 */
class ClientOptions extends Enum
{
    /**
     * AWS Access Key ID
     *
     * @deprecated Use "credentials" instead.
     */
    const KEY = 'key';

    /**
     * AWS secret access key
     *
     * @deprecated Use "credentials" instead.
     */
    const SECRET = 'secret';

    /**
     * Custom AWS security token to use with request authentication.
     *
     * @deprecated Use "credentials" instead.
     */
    const TOKEN = 'token';

    /**
     * Provide an array of "key", "secret", and "token" or an instance of
     * `Aws\Common\Credentials\CredentialsInterface`.
     */
    const CREDENTIALS = 'credentials';

    /**
     * @var string Name of a credential profile to read from your ~/.aws/credentials file
     */
    const PROFILE = 'profile';

    /**
     * @var string UNIX timestamp for when the custom credentials expire
     */
    const TOKEN_TTD = 'token.ttd';

    /**
     * @var string Used to cache credentials when using providers that require HTTP requests. Set the trueto use the
     *             default APC cache or provide a `Guzzle\Cache\CacheAdapterInterface` object.
     */
    const CREDENTIALS_CACHE = 'credentials.cache';

    /**
     * @var string Optional custom cache key to use with the credentials
     */
    const CREDENTIALS_CACHE_KEY = 'credentials.cache.key';

    /**
     * @var string Pass this option to specify a custom `Guzzle\Http\ClientInterface` to use if your credentials require
     *             a HTTP request (e.g. RefreshableInstanceProfileCredentials)
     */
    const CREDENTIALS_CLIENT = 'credentials.client';

    /**
     * @var string Region name (e.g. 'us-east-1', 'us-west-1', 'us-west-2', 'eu-west-1', etc...)
     */
    const REGION = 'region';

    /**
     * @var string URI Scheme of the base URL (e.g. 'https', 'http').
     */
    const SCHEME = 'scheme';

    /**
     * @var string Specify the name of the service
     */
    const SERVICE = 'service';

    /**
     * Instead of using a `region` and `scheme`, you can specify a custom base
     * URL for the client.
     *
     * @deprecated Use the "endpoint" option instead.
     */
    const BASE_URL = 'base_url';

    /**
     * @var string You can optionally provide a custom signature implementation used to sign requests
     */
    const SIGNATURE = 'signature';

    /**
     * @var string Set to explicitly override the service name used in signatures
     */
    const SIGNATURE_SERVICE = 'signature.service';

    /**
     * @var string Set to explicitly override the region name used in signatures
     */
    const SIGNATURE_REGION = 'signature.region';

    /**
     * @var string Option key holding an exponential backoff plugin
     */
    const BACKOFF = 'client.backoff';

    /**
     * @var string `Guzzle\Log\LogAdapterInterface` object used to log backoff retries. Use 'debug' to emit PHP
     *             warnings when a retry is issued.
     */
    const BACKOFF_LOGGER = 'client.backoff.logger';

    /**
     * @var string Optional template to use for exponential backoff log messages. See
     *             `Guzzle\Plugin\Backoff\BackoffLogger` for formatting information.
     */
    const BACKOFF_LOGGER_TEMPLATE = 'client.backoff.logger.template';

    /**
     * Set to true to use the bundled CA cert or pass the full path to an SSL
     * certificate bundle. This option should be modified when you encounter
     * curl error code 60. Set to "system" to use the cacert bundle on your
     * system.
     */
    const SSL_CERT = 'ssl.certificate_authority';

    /**
     * @var string Service description to use with the client
     */
    const SERVICE_DESCRIPTION = 'service.description';

    /**
     * @var string Whether or not modeled responses have transformations applied to them
     */
    const MODEL_PROCESSING = 'command.model_processing';

    /**
     * @var bool Set to false to disable validation
     */
    const VALIDATION = 'validation';

    /**
     * @var string API version used by the client
     */
    const VERSION = 'version';
}
Enum/UaString.php000060400000002507152440555050007722 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Enum;

use Aws\Common\Enum;

/**
 * User-Agent header strings for various high level operations
 */
class UaString extends Enum
{
    /**
     * @var string Name of the option used to add to the UA string
     */
    const OPTION = 'ua.append';

    /**
     * @var string Resource iterator
     */
    const ITERATOR = 'ITR';

    /**
     * @var string Resource waiter
     */
    const WAITER = 'WTR';

    /**
     * @var string Session handlers (e.g. Amazon DynamoDB session handler)
     */
    const SESSION = 'SES';

    /**
     * @var string Multipart upload helper for Amazon S3
     */
    const MULTIPART_UPLOAD = 'MUP';

    /**
     * @var string Command executed during a batch transfer
     */
    const BATCH = 'BAT';
}
Enum/Size.php000060400000002636152440555050007103 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Enum;

use Aws\Common\Enum;

/**
 * Contains enumerable byte-size values
 */
class Size extends Enum
{
    const B         = 1;
    const BYTE      = 1;
    const BYTES     = 1;

    const KB        = 1024;
    const KILOBYTE  = 1024;
    const KILOBYTES = 1024;

    const MB        = 1048576;
    const MEGABYTE  = 1048576;
    const MEGABYTES = 1048576;

    const GB        = 1073741824;
    const GIGABYTE  = 1073741824;
    const GIGABYTES = 1073741824;

    const TB        = 1099511627776;
    const TERABYTE  = 1099511627776;
    const TERABYTES = 1099511627776;

    const PB        = 1125899906842624;
    const PETABYTE  = 1125899906842624;
    const PETABYTES = 1125899906842624;

    const EB        = 1152921504606846976;
    const EXABYTE   = 1152921504606846976;
    const EXABYTES  = 1152921504606846976;
}
Enum/.htaccess000044400000000424152440555050007251 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Enum/DateFormat.php000060400000001655152440555050010217 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Enum;

use Aws\Common\Enum;

/**
 * Contains enumerable date format values used in the SDK
 */
class DateFormat extends Enum
{
    const ISO8601    = 'Ymd\THis\Z';
    const ISO8601_S3 = 'Y-m-d\TH:i:s\Z';
    const RFC1123    = 'D, d M Y H:i:s \G\M\T';
    const RFC2822    = \DateTime::RFC2822;
    const SHORT      = 'Ymd';
}
Enum/Time.php000060400000002105152440555050007056 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Enum;

use Aws\Common\Enum;

/**
 * Contains enumerable time values
 */
class Time extends Enum
{
    const SECOND  = 1;
    const SECONDS = 1;

    const MINUTE  = 60;
    const MINUTES = 60;

    const HOUR    = 3600;
    const HOURS   = 3600;

    const DAY     = 86400;
    const DAYS    = 86400;

    const WEEK    = 604800;
    const WEEKS   = 604800;

    const MONTH   = 2592000;
    const MONTHS  = 2592000;

    const YEAR    = 31557600;
    const YEARS   = 31557600;
}
Waiter/CallableWaiter.php000060400000004110152440555050011360 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\RuntimeException;

/**
 * Callable wait implementation
 */
class CallableWaiter extends AbstractWaiter
{
    /**
     * @var callable Callable function
     */
    protected $callable;

    /**
     * @var array Additional context for the callable function
     */
    protected $context = array();

    /**
     * Set the callable function to call in each wait attempt
     *
     * @param callable $callable Callable function
     *
     * @return self
     * @throws InvalidArgumentException when the method is not callable
     */
    public function setCallable($callable)
    {
        if (!is_callable($callable)) {
            throw new InvalidArgumentException('Value is not callable');
        }

        $this->callable = $callable;

        return $this;
    }

    /**
     * Set additional context for the callable function. This data will be passed into the callable function as the
     * second argument
     *
     * @param array $context Additional context
     *
     * @return self
     */
    public function setContext(array $context)
    {
        $this->context = $context;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function doWait()
    {
        if (!$this->callable) {
            throw new RuntimeException('No callable was specified for the wait method');
        }

        return call_user_func($this->callable, $this->attempts, $this->context);
    }
}
Waiter/ConfigResourceWaiter.php000060400000016564152440555050012616 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\RuntimeException;
use Aws\Common\Exception\ServiceResponseException;
use Guzzle\Service\Resource\Model;
use Guzzle\Service\Exception\ValidationException;

/**
 * Resource waiter driven by configuration options
 */
class ConfigResourceWaiter extends AbstractResourceWaiter
{
    /**
     * @var WaiterConfig Waiter configuration
     */
    protected $waiterConfig;

    /**
     * @param WaiterConfig $waiterConfig Waiter configuration
     */
    public function __construct(WaiterConfig $waiterConfig)
    {
        $this->waiterConfig = $waiterConfig;
        $this->setInterval($waiterConfig->get(WaiterConfig::INTERVAL));
        $this->setMaxAttempts($waiterConfig->get(WaiterConfig::MAX_ATTEMPTS));
    }

    /**
     * {@inheritdoc}
     */
    public function setConfig(array $config)
    {
        foreach ($config as $key => $value) {
            if (substr($key, 0, 7) == 'waiter.') {
                $this->waiterConfig->set(substr($key, 7), $value);
            }
        }

        if (!isset($config[self::INTERVAL])) {
            $config[self::INTERVAL] = $this->waiterConfig->get(WaiterConfig::INTERVAL);
        }

        if (!isset($config[self::MAX_ATTEMPTS])) {
            $config[self::MAX_ATTEMPTS] = $this->waiterConfig->get(WaiterConfig::MAX_ATTEMPTS);
        }

        return parent::setConfig($config);
    }

    /**
     * Get the waiter's configuration data
     *
     * @return WaiterConfig
     */
    public function getWaiterConfig()
    {
        return $this->waiterConfig;
    }

    /**
     * {@inheritdoc}
     */
    protected function doWait()
    {
        $params = $this->config;
        // remove waiter settings from the operation's input
        foreach (array_keys($params) as $key) {
            if (substr($key, 0, 7) == 'waiter.') {
                unset($params[$key]);
            }
        }

        $operation = $this->client->getCommand($this->waiterConfig->get(WaiterConfig::OPERATION), $params);

        try {
            return $this->checkResult($this->client->execute($operation));
        } catch (ValidationException $e) {
            throw new InvalidArgumentException(
                $this->waiterConfig->get(WaiterConfig::WAITER_NAME) . ' waiter validation failed:  ' . $e->getMessage(),
                $e->getCode(),
                $e
            );
        } catch (ServiceResponseException $e) {

            // Check if this exception satisfies a success or failure acceptor
            $transition = $this->checkErrorAcceptor($e);
            if (null !== $transition) {
                return $transition;
            }

            // Check if this exception should be ignored
            foreach ((array) $this->waiterConfig->get(WaiterConfig::IGNORE_ERRORS) as $ignore) {
                if ($e->getExceptionCode() == $ignore) {
                    // This exception is ignored, so it counts as a failed attempt rather than a fast-fail
                    return false;
                }
            }

            // Allow non-ignore exceptions to bubble through
            throw $e;
        }
    }

    /**
     * Check if an exception satisfies a success or failure acceptor
     *
     * @param ServiceResponseException $e
     *
     * @return bool|null Returns true for success, false for failure, and null for no transition
     */
    protected function checkErrorAcceptor(ServiceResponseException $e)
    {
        if ($this->waiterConfig->get(WaiterConfig::SUCCESS_TYPE) == 'error') {
            if ($e->getExceptionCode() == $this->waiterConfig->get(WaiterConfig::SUCCESS_VALUE)) {
                // Mark as a success
                return true;
            }
        }

        // Mark as an attempt
        return null;
    }

    /**
     * Check to see if the response model satisfies a success or failure state
     *
     * @param Model $result Result model
     *
     * @return bool
     * @throws RuntimeException
     */
    protected function checkResult(Model $result)
    {
        // Check if the result evaluates to true based on the path and output model
        if ($this->waiterConfig->get(WaiterConfig::SUCCESS_TYPE) == 'output' &&
            $this->checkPath(
                $result,
                $this->waiterConfig->get(WaiterConfig::SUCCESS_PATH),
                $this->waiterConfig->get(WaiterConfig::SUCCESS_VALUE)
            )
        ) {
            return true;
        }

        // It did not finish waiting yet. Determine if we need to fail-fast based on the failure acceptor.
        if ($this->waiterConfig->get(WaiterConfig::FAILURE_TYPE) == 'output') {
            $failureValue = $this->waiterConfig->get(WaiterConfig::FAILURE_VALUE);
            if ($failureValue) {
                $key = $this->waiterConfig->get(WaiterConfig::FAILURE_PATH);
                if ($this->checkPath($result, $key, $failureValue, false)) {
                    // Determine which of the results triggered the failure
                    $triggered = array_intersect(
                        (array) $this->waiterConfig->get(WaiterConfig::FAILURE_VALUE),
                        array_unique((array) $result->getPath($key))
                    );
                    // fast fail because the failure case was satisfied
                    throw new RuntimeException(
                        'A resource entered into an invalid state of "'
                        . implode(', ', $triggered) . '" while waiting with the "'
                        . $this->waiterConfig->get(WaiterConfig::WAITER_NAME) . '" waiter.'
                    );
                }
            }
        }

        return false;
    }

    /**
     * Check to see if the path of the output key is satisfied by the value
     *
     * @param Model  $model      Result model
     * @param string $key        Key to check
     * @param string $checkValue Compare the key to the value
     * @param bool   $all        Set to true to ensure all value match or false to only match one
     *
     * @return bool
     */
    protected function checkPath(Model $model, $key = null, $checkValue = array(), $all = true)
    {
        // If no key is set, then just assume true because the request succeeded
        if (!$key) {
            return true;
        }

        if (!($result = $model->getPath($key))) {
            return false;
        }

        $total = $matches = 0;
        foreach ((array) $result as $value) {
            $total++;
            foreach ((array) $checkValue as $check) {
                if ($value == $check) {
                    $matches++;
                    break;
                }
            }
        }

        // When matching all values, ensure that the match count matches the total count
        if ($all && $total != $matches) {
            return false;
        }

        return $matches > 0;
    }
}
Waiter/AbstractResourceWaiter.php000060400000002472152440555050013145 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\RuntimeException;

/**
 * Abstract waiter implementation used to wait on resources
 */
abstract class AbstractResourceWaiter extends AbstractWaiter implements ResourceWaiterInterface
{
    /**
     * @var AwsClientInterface
     */
    protected $client;

    /**
     * {@inheritdoc}
     */
    public function setClient(AwsClientInterface $client)
    {
        $this->client = $client;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function wait()
    {
        if (!$this->client) {
            throw new RuntimeException('No client has been specified on the waiter');
        }

        parent::wait();
    }
}
Waiter/CompositeWaiterFactory.php000060400000004245152440555050013164 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Aws\Common\Exception\InvalidArgumentException;

/**
 * Factory that utilizes multiple factories for creating waiters
 */
class CompositeWaiterFactory implements WaiterFactoryInterface
{
    /**
     * @var array Array of factories
     */
    protected $factories;

    /**
     * @param array $factories Array of factories used to instantiate waiters
     */
    public function __construct(array $factories)
    {
        $this->factories = $factories;
    }

    /**
     * {@inheritdoc}
     */
    public function build($waiter)
    {
        if (!($factory = $this->getFactory($waiter))) {
            throw new InvalidArgumentException("Waiter was not found matching {$waiter}.");
        }

        return $factory->build($waiter);
    }

    /**
     * {@inheritdoc}
     */
    public function canBuild($waiter)
    {
        return (bool) $this->getFactory($waiter);
    }

    /**
     * Add a factory to the composite factory
     *
     * @param WaiterFactoryInterface $factory Factory to add
     *
     * @return self
     */
    public function addFactory(WaiterFactoryInterface $factory)
    {
        $this->factories[] = $factory;

        return $this;
    }

    /**
     * Get the factory that matches the waiter name
     *
     * @param string $waiter Name of the waiter
     *
     * @return WaiterFactoryInterface|bool
     */
    protected function getFactory($waiter)
    {
        foreach ($this->factories as $factory) {
            if ($factory->canBuild($waiter)) {
                return $factory;
            }
        }

        return false;
    }
}
Waiter/WaiterConfigFactory.php000060400000005636152440555050012434 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Inflection\Inflector;
use Guzzle\Inflection\InflectorInterface;

/**
 * Factory for creating {@see WaiterInterface} objects using a configuration DSL.
 */
class WaiterConfigFactory implements WaiterFactoryInterface
{
    /**
     * @var array Configuration directives
     */
    protected $config;

    /**
     * @var InflectorInterface Inflector used to inflect class names
     */
    protected $inflector;

    /**
     * @param array              $config    Array of configuration directives
     * @param InflectorInterface $inflector Inflector used to resolve class names
     */
    public function __construct(
        array $config,
        InflectorInterface $inflector = null
    ) {
        $this->config = $config;
        $this->inflector = $inflector ?: Inflector::getDefault();
    }

    /**
     * {@inheritdoc}
     */
    public function build($waiter)
    {
        return new ConfigResourceWaiter($this->getWaiterConfig($waiter));
    }

    /**
     * {@inheritdoc}
     */
    public function canBuild($waiter)
    {
        return isset($this->config[$waiter]) || isset($this->config[$this->inflector->camel($waiter)]);
    }

    /**
     * Get waiter configuration data, taking __default__ and extensions into account
     *
     * @param string $name Waiter name
     *
     * @return WaiterConfig
     * @throws InvalidArgumentException
     */
    protected function getWaiterConfig($name)
    {
        if (!$this->canBuild($name)) {
            throw new InvalidArgumentException('No waiter found matching "' . $name . '"');
        }

        // inflect the name if needed
        $name = isset($this->config[$name]) ? $name : $this->inflector->camel($name);
        $waiter = new WaiterConfig($this->config[$name]);
        $waiter['name'] = $name;

        // Always use __default__ as the basis if it's set
        if (isset($this->config['__default__'])) {
            $parentWaiter = new WaiterConfig($this->config['__default__']);
            $waiter = $parentWaiter->overwriteWith($waiter);
        }

        // Allow for configuration extensions
        if (isset($this->config[$name]['extends'])) {
            $waiter = $this->getWaiterConfig($this->config[$name]['extends'])->overwriteWith($waiter);
        }

        return $waiter;
    }
}
Waiter/AbstractWaiter.php000060400000007221152440555050011432 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Aws\Common\Exception\RuntimeException;
use Guzzle\Common\AbstractHasDispatcher;

/**
 * Abstract wait implementation
 */
abstract class AbstractWaiter extends AbstractHasDispatcher implements WaiterInterface
{
    protected $attempts = 0;
    protected $config = array();

    /**
     * {@inheritdoc}
     */
    public static function getAllEvents()
    {
        return array(
            // About to check if the waiter needs to wait
            'waiter.before_attempt',
            // About to sleep
            'waiter.before_wait',
        );
    }

    /**
     * The max attempts allowed by the waiter
     *
     * @return int
     */
    public function getMaxAttempts()
    {
        return isset($this->config[self::MAX_ATTEMPTS]) ? $this->config[self::MAX_ATTEMPTS] : 10;
    }

    /**
     * Get the amount of time in seconds to delay between attempts
     *
     * @return int
     */
    public function getInterval()
    {
        return isset($this->config[self::INTERVAL]) ? $this->config[self::INTERVAL] : 0;
    }

    /**
     * {@inheritdoc}
     */
    public function setMaxAttempts($maxAttempts)
    {
        $this->config[self::MAX_ATTEMPTS] = $maxAttempts;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setInterval($interval)
    {
        $this->config[self::INTERVAL] = $interval;

        return $this;
    }

    /**
     * Set config options associated with the waiter
     *
     * @param array $config Options to set
     *
     * @return self
     */
    public function setConfig(array $config)
    {
        if (isset($config['waiter.before_attempt'])) {
            $this->getEventDispatcher()->addListener('waiter.before_attempt', $config['waiter.before_attempt']);
            unset($config['waiter.before_attempt']);
        }

        if (isset($config['waiter.before_wait'])) {
            $this->getEventDispatcher()->addListener('waiter.before_wait', $config['waiter.before_wait']);
            unset($config['waiter.before_wait']);
        }

        $this->config = $config;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function wait()
    {
        $this->attempts = 0;

        do {
            $this->dispatch('waiter.before_attempt', array(
                'waiter' => $this,
                'config' => $this->config,
            ));

            if ($this->doWait()) {
                break;
            }

            if (++$this->attempts >= $this->getMaxAttempts()) {
                throw new RuntimeException('Wait method never resolved to true after ' . $this->attempts . ' attempts');
            }

            $this->dispatch('waiter.before_wait', array(
                'waiter' => $this,
                'config' => $this->config,
            ));

            if ($this->getInterval()) {
                usleep($this->getInterval() * 1000000);
            }

        } while (1);
    }

    /**
     * Method to implement in subclasses
     *
     * @return bool Return true when successful, false on failure
     */
    abstract protected function doWait();
}
Waiter/WaiterConfig.php000060400000004067152440555050011101 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Guzzle\Common\Collection;

/**
 * Configuration info of a waiter object
 */
class WaiterConfig extends Collection
{
    const WAITER_NAME = 'name';
    const MAX_ATTEMPTS = 'max_attempts';
    const INTERVAL = 'interval';
    const OPERATION = 'operation';
    const IGNORE_ERRORS = 'ignore_errors';
    const DESCRIPTION = 'description';
    const SUCCESS_TYPE = 'success.type';
    const SUCCESS_PATH = 'success.path';
    const SUCCESS_VALUE = 'success.value';
    const FAILURE_TYPE = 'failure.type';
    const FAILURE_PATH = 'failure.path';
    const FAILURE_VALUE = 'failure.value';

    /**
     * @param array $data Array of configuration directives
     */
    public function __construct(array $data = array())
    {
        $this->data = $data;
        $this->extractConfig();
    }

    /**
     * Create the command configuration variables
     */
    protected function extractConfig()
    {
        // Populate success.* and failure.* if specified in acceptor.*
        foreach ($this->data as $key => $value) {
            if (substr($key, 0, 9) == 'acceptor.') {
                $name = substr($key, 9);
                if (!isset($this->data["success.{$name}"])) {
                    $this->data["success.{$name}"] = $value;
                }
                if (!isset($this->data["failure.{$name}"])) {
                    $this->data["failure.{$name}"] = $value;
                }
                unset($this->data[$key]);
            }
        }
    }
}
Waiter/.htaccess000044400000000424152440555050007600 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Waiter/WaiterFactoryInterface.php000060400000002152152440555050013115 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

/**
 * Waiter factory used to create waiter objects by short names
 */
interface WaiterFactoryInterface
{
    /**
     * Create a waiter by name
     *
     * @param string $waiter Name of the waiter to create
     *
     * @return WaiterInterface
     */
    public function build($waiter);

    /**
     * Check if the factory can create a waiter by a specific name
     *
     * @param string $waiter Name of the waiter to check
     *
     * @return bool
     */
    public function canBuild($waiter);
}
Waiter/WaiterInterface.php000060400000003105152440555050011564 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

/**
 * WaiterInterface used to wait on something to be in a particular state
 */
interface WaiterInterface
{
    const INTERVAL = 'waiter.interval';
    const MAX_ATTEMPTS = 'waiter.max_attempts';

    /**
     * Set the maximum number of attempts to make when waiting
     *
     * @param int $maxAttempts Max number of attempts
     *
     * @return self
     */
    public function setMaxAttempts($maxAttempts);

    /**
     * Set the amount of time to interval between attempts
     *
     * @param int $interval Interval in seconds
     *
     * @return self
     */
    public function setInterval($interval);

    /**
     * Set configuration options associated with the waiter
     *
     * @param array $config Configuration options to set
     *
     * @return self
     */
    public function setConfig(array $config);

    /**
     * Begin the waiting loop
     *
     * @throw RuntimeException if the method never resolves to true
     */
    public function wait();
}
Waiter/WaiterClassFactory.php000060400000005653152440555050012273 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Inflection\Inflector;
use Guzzle\Inflection\InflectorInterface;

/**
 * Factory for creating {@see WaiterInterface} objects using a convention of
 * storing waiter classes in the Waiter folder of a client class namespace using
 * a snake_case to CamelCase conversion (e.g. camel_case => CamelCase).
 */
class WaiterClassFactory implements WaiterFactoryInterface
{
    /**
     * @var array List of namespaces used to look for classes
     */
    protected $namespaces;

    /**
     * @var InflectorInterface Inflector used to inflect class names
     */
    protected $inflector;

    /**
     * @param array|string       $namespaces Namespaces of waiter objects
     * @param InflectorInterface $inflector  Inflector used to resolve class names
     */
    public function __construct($namespaces = array(), InflectorInterface $inflector = null)
    {
        $this->namespaces = (array) $namespaces;
        $this->inflector = $inflector ?: Inflector::getDefault();
    }

    /**
     * Registers a namespace to check for Waiters
     *
     * @param string $namespace Namespace which contains Waiter classes
     *
     * @return self
     */
    public function registerNamespace($namespace)
    {
        array_unshift($this->namespaces, $namespace);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function build($waiter)
    {
        if (!($className = $this->getClassName($waiter))) {
            throw new InvalidArgumentException("Waiter was not found matching {$waiter}.");
        }

        return new $className();
    }

    /**
     * {@inheritdoc}
     */
    public function canBuild($waiter)
    {
        return $this->getClassName($waiter) !== null;
    }

    /**
     * Get the name of a waiter class
     *
     * @param string $waiter Waiter name
     *
     * @return string|null
     */
    protected function getClassName($waiter)
    {
        $waiterName = $this->inflector->camel($waiter);

        // Determine the name of the class to load
        $className = null;
        foreach ($this->namespaces as $namespace) {
            $potentialClassName = $namespace . '\\' . $waiterName;
            if (class_exists($potentialClassName)) {
                return $potentialClassName;
            }
        }

        return null;
    }
}
Waiter/ResourceWaiterInterface.php000060400000002010152440555050013266 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Waiter;

use Aws\Common\Client\AwsClientInterface;

/**
 * Interface used in conjunction with clients to wait on a resource
 */
interface ResourceWaiterInterface extends WaiterInterface
{
    /**
     * Set the client associated with the waiter
     *
     * @param AwsClientInterface $client Client to use with the waiter
     *
     * @return self
     */
    public function setClient(AwsClientInterface $client);
}
Aws.php000060400000007241152440555050006014 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common;

use Aws\Common\Facade\Facade;
use Guzzle\Service\Builder\ServiceBuilder;
use Guzzle\Service\Builder\ServiceBuilderLoader;

/**
 * Base class for interacting with web service clients
 */
class Aws extends ServiceBuilder
{
    /**
     * @var string Current version of the SDK
     */
    const VERSION = '2.8.27';

    /**
     * Create a new service locator for the AWS SDK
     *
     * You can configure the service locator is four different ways:
     *
     * 1. Use the default configuration file shipped with the SDK that wires class names with service short names and
     *    specify global parameters to add to every definition (e.g. key, secret, credentials, etc)
     *
     * 2. Use a custom configuration file that extends the default config and supplies credentials for each service.
     *
     * 3. Use a custom config file that wires services to custom short names for services.
     *
     * 4. If you are on Amazon EC2, you can use the default configuration file and not provide any credentials so that
     *    you are using InstanceProfile credentials.
     *
     * @param array|string $config           The full path to a .php or .js|.json file, or an associative array of data
     *                                       to use as global parameters to pass to each service.
     * @param array        $globalParameters Global parameters to pass to every service as it is instantiated.
     *
     * @return Aws
     */
    public static function factory($config = null, array $globalParameters = array())
    {
        if (!$config) {
            // If nothing is passed in, then use the default configuration file with credentials from the environment
            $config = self::getDefaultServiceDefinition();
        } elseif (is_array($config)) {
            // If an array was passed, then use the default configuration file with parameter overrides
            $globalParameters = $config;
            $config = self::getDefaultServiceDefinition();
        }

        $loader = new ServiceBuilderLoader();
        $loader->addAlias('_aws', self::getDefaultServiceDefinition())
            ->addAlias('_sdk1', __DIR__  . '/Resources/sdk1-config.php');

        return $loader->load($config, $globalParameters);
    }

    /**
     * Get the full path to the default service builder definition file
     *
     * @return string
     */
    public static function getDefaultServiceDefinition()
    {
        return __DIR__  . '/Resources/aws-config.php';
    }

    /**
     * Returns the configuration for the service builder
     *
     * @return array
     */
    public function getConfig()
    {
        return $this->builderConfig;
    }

    /**
     * Enables the facades for the clients defined in the service builder
     *
     * @param string|null $namespace The namespace that the facades should be mounted to. Defaults to global namespace
     *
     * @return Aws
     * @deprecated "Facades" are being removed in version 3.0 of the SDK.
     */
    public function enableFacades($namespace = null)
    {
        Facade::mountFacades($this, $namespace);

        return $this;
    }
}
RulesEndpointProvider.php000060400000003437152440555050011573 0ustar00<?php
namespace Aws\Common;

/**
 * Provides endpoints based on a rules configuration file.
 */
class RulesEndpointProvider
{
    /** @var array */
    private $patterns;

    /**
     * @param array $patterns Hash of endpoint patterns mapping to endpoint
     *                        configurations.
     */
    public function __construct(array $patterns)
    {
        $this->patterns = $patterns;
    }

    /**
     * Creates and returns the default RulesEndpointProvider based on the
     * public rule sets.
     *
     * @return self
     */
    public static function fromDefaults()
    {
        return new self(require __DIR__ . '/Resources/public-endpoints.php');
    }

    public function __invoke(array $args = array())
    {
        if (!isset($args['service'])) {
            throw new \InvalidArgumentException('Requires a "service" value');
        }

        if (!isset($args['region'])) {
            throw new \InvalidArgumentException('Requires a "region" value');
        }

        foreach ($this->getKeys($args['region'], $args['service']) as $key) {
            if (isset($this->patterns['endpoints'][$key])) {
                return $this->expand($this->patterns['endpoints'][$key], $args);
            }
        }

        throw new \RuntimeException('Could not resolve endpoint');
    }

    private function expand(array $config, array $args)
    {
        $scheme = isset($args['scheme']) ? $args['scheme'] : 'https';
        $config['endpoint'] = $scheme . '://' . str_replace(
            array('{service}', '{region}'),
            array($args['service'], $args['region']),
            $config['endpoint']
        );

        return $config;
    }

    private function getKeys($region, $service)
    {
        return array("$region/$service", "$region/*", "*/$service", "*/*");
    }
}
Client/UploadBodyListener.php000060400000006473152440555050012256 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Client;

use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Event;
use Guzzle\Http\EntityBody;
use Guzzle\Service\Command\AbstractCommand as Command;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Prepares the body parameter of a command such that the parameter is more flexible (e.g. accepts file handles) with
 * the value it accepts but converts it to the correct format for the command. Also looks for a "Filename" parameter.
 */
class UploadBodyListener implements EventSubscriberInterface
{
    /**
     * @var array The names of the commands of which to modify the body parameter
     */
    protected $commands;

    /**
     * @var string The key for the upload body parameter
     */
    protected $bodyParameter;

    /**
     * @var string The key for the source file parameter
     */
    protected $sourceParameter;

    /**
     * @param array  $commands        The commands to modify
     * @param string $bodyParameter   The key for the body parameter
     * @param string $sourceParameter The key for the source file parameter
     */
    public function __construct(array $commands, $bodyParameter = 'Body', $sourceParameter = 'SourceFile')
    {
        $this->commands = $commands;
        $this->bodyParameter = (string) $bodyParameter;
        $this->sourceParameter = (string) $sourceParameter;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array('command.before_prepare' => array('onCommandBeforePrepare'));
    }

    /**
     * Converts filenames and file handles into EntityBody objects before the command is validated
     *
     * @param Event $event Event emitted
     * @throws InvalidArgumentException
     */
    public function onCommandBeforePrepare(Event $event)
    {
        /** @var Command $command */
        $command = $event['command'];
        if (in_array($command->getName(), $this->commands)) {
            // Get the interesting parameters
            $source = $command->get($this->sourceParameter);
            $body = $command->get($this->bodyParameter);

            // If a file path is passed in then get the file handle
            if (is_string($source) && file_exists($source)) {
                $body = fopen($source, 'r');
            }

            // Prepare the body parameter and remove the source file parameter
            if (null !== $body) {
                $command->remove($this->sourceParameter);
                $command->set($this->bodyParameter, EntityBody::factory($body));
            } else {
                throw new InvalidArgumentException("You must specify a non-null value for the {$this->bodyParameter} or {$this->sourceParameter} parameters.");
            }
        }
    }
}
Client/AbstractClient.php000060400000022720152440555050011401 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Client;

use Aws\Common\Aws;
use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\TransferException;
use Aws\Common\RulesEndpointProvider;
use Aws\Common\Signature\EndpointSignatureInterface;
use Aws\Common\Signature\SignatureInterface;
use Aws\Common\Signature\SignatureListener;
use Aws\Common\Waiter\WaiterClassFactory;
use Aws\Common\Waiter\CompositeWaiterFactory;
use Aws\Common\Waiter\WaiterFactoryInterface;
use Aws\Common\Waiter\WaiterConfigFactory;
use Guzzle\Common\Collection;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\QueryAggregator\DuplicateAggregator;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescriptionInterface;

/**
 * Abstract AWS client
 */
abstract class AbstractClient extends Client implements AwsClientInterface
{
    /** @var CredentialsInterface AWS credentials */
    protected $credentials;

    /** @var SignatureInterface Signature implementation of the service */
    protected $signature;

    /** @var WaiterFactoryInterface Factory used to create waiter classes */
    protected $waiterFactory;

    /** @var DuplicateAggregator Cached query aggregator*/
    protected $aggregator;

    /**
     * {@inheritdoc}
     */
    public static function getAllEvents()
    {
        return array_merge(Client::getAllEvents(), array(
            'client.region_changed',
            'client.credentials_changed',
        ));
    }

    /**
     * @param CredentialsInterface $credentials AWS credentials
     * @param SignatureInterface   $signature   Signature implementation
     * @param Collection           $config      Configuration options
     *
     * @throws InvalidArgumentException if an endpoint provider isn't provided
     */
    public function __construct(CredentialsInterface $credentials, SignatureInterface $signature, Collection $config)
    {
        // Bootstrap with Guzzle
        parent::__construct($config->get(Options::BASE_URL), $config);
        $this->credentials = $credentials;
        $this->signature = $signature;
        $this->aggregator = new DuplicateAggregator();

        // Make sure the user agent is prefixed by the SDK version
        $this->setUserAgent('aws-sdk-php2/' . Aws::VERSION, true);

        // Add the event listener so that requests are signed before they are sent
        $dispatcher = $this->getEventDispatcher();
        $dispatcher->addSubscriber(new SignatureListener($credentials, $signature));

        if ($backoff = $config->get(Options::BACKOFF)) {
            $dispatcher->addSubscriber($backoff, -255);
        }
    }

    public function __call($method, $args)
    {
        if (substr($method, 0, 3) === 'get' && substr($method, -8) === 'Iterator') {
            // Allow magic method calls for iterators (e.g. $client->get<CommandName>Iterator($params))
            $commandOptions = isset($args[0]) ? $args[0] : null;
            $iteratorOptions = isset($args[1]) ? $args[1] : array();
            return $this->getIterator(substr($method, 3, -8), $commandOptions, $iteratorOptions);
        } elseif (substr($method, 0, 9) == 'waitUntil') {
            // Allow magic method calls for waiters (e.g. $client->waitUntil<WaiterName>($params))
            return $this->waitUntil(substr($method, 9), isset($args[0]) ? $args[0]: array());
        } else {
            return parent::__call(ucfirst($method), $args);
        }
    }

    /**
     * Get an endpoint for a specific region from a service description
     * @deprecated This function will no longer be updated to work with new regions.
     */
    public static function getEndpoint(ServiceDescriptionInterface $description, $region, $scheme)
    {
        try {
            $service = $description->getData('endpointPrefix');
            $provider = RulesEndpointProvider::fromDefaults();
            $result = $provider(array(
                'service' => $service,
                'region'  => $region,
                'scheme'  => $scheme
            ));
            return $result['endpoint'];
        } catch (\InvalidArgumentException $e) {
            throw new InvalidArgumentException($e->getMessage(), 0, $e);
        }
    }

    public function getCredentials()
    {
        return $this->credentials;
    }

    public function setCredentials(CredentialsInterface $credentials)
    {
        $formerCredentials = $this->credentials;
        $this->credentials = $credentials;

        // Dispatch an event that the credentials have been changed
        $this->dispatch('client.credentials_changed', array(
            'credentials'        => $credentials,
            'former_credentials' => $formerCredentials,
        ));

        return $this;
    }

    public function getSignature()
    {
        return $this->signature;
    }

    public function getRegions()
    {
        return $this->serviceDescription->getData('regions');
    }

    public function getRegion()
    {
        return $this->getConfig(Options::REGION);
    }

    public function setRegion($region)
    {
        $config = $this->getConfig();
        $formerRegion = $config->get(Options::REGION);
        $global = $this->serviceDescription->getData('globalEndpoint');
        $provider = $config->get('endpoint_provider');

        if (!$provider) {
            throw new \RuntimeException('No endpoint provider configured');
        }

        // Only change the region if the service does not have a global endpoint
        if (!$global || $this->serviceDescription->getData('namespace') === 'S3') {

            $endpoint = call_user_func(
                $provider,
                array(
                    'scheme'  => $config->get(Options::SCHEME),
                    'region'  => $region,
                    'service' => $config->get(Options::SERVICE)
                )
            );

            $this->setBaseUrl($endpoint['endpoint']);
            $config->set(Options::BASE_URL, $endpoint['endpoint']);
            $config->set(Options::REGION, $region);

            // Update the signature if necessary
            $signature = $this->getSignature();
            if ($signature instanceof EndpointSignatureInterface) {
                /** @var EndpointSignatureInterface $signature */
                $signature->setRegionName($region);
            }

            // Dispatch an event that the region has been changed
            $this->dispatch('client.region_changed', array(
                'region'        => $region,
                'former_region' => $formerRegion,
            ));
        }

        return $this;
    }

    public function waitUntil($waiter, array $input = array())
    {
        $this->getWaiter($waiter, $input)->wait();

        return $this;
    }

    public function getWaiter($waiter, array $input = array())
    {
        return $this->getWaiterFactory()->build($waiter)
            ->setClient($this)
            ->setConfig($input);
    }

    public function setWaiterFactory(WaiterFactoryInterface $waiterFactory)
    {
        $this->waiterFactory = $waiterFactory;

        return $this;
    }

    public function getWaiterFactory()
    {
        if (!$this->waiterFactory) {
            $clientClass = get_class($this);
            // Use a composite factory that checks for classes first, then config waiters
            $this->waiterFactory = new CompositeWaiterFactory(array(
                new WaiterClassFactory(substr($clientClass, 0, strrpos($clientClass, '\\')) . '\\Waiter')
            ));
            if ($this->getDescription()) {
                $waiterConfig = $this->getDescription()->getData('waiters') ?: array();
                $this->waiterFactory->addFactory(new WaiterConfigFactory($waiterConfig));
            }
        }

        return $this->waiterFactory;
    }

    public function getApiVersion()
    {
        return $this->serviceDescription->getApiVersion();
    }

    /**
     * {@inheritdoc}
     * @throws \Aws\Common\Exception\TransferException
     */
    public function send($requests)
    {
        try {
            return parent::send($requests);
        } catch (CurlException $e) {
            $wrapped = new TransferException($e->getMessage(), null, $e);
            $wrapped->setCurlHandle($e->getCurlHandle())
                ->setCurlInfo($e->getCurlInfo())
                ->setError($e->getError(), $e->getErrorNo())
                ->setRequest($e->getRequest());
            throw $wrapped;
        }
    }

    /**
     * Ensures that the duplicate query string aggregator is used so that
     * query string values are sent over the wire as foo=bar&foo=baz.
     * {@inheritdoc}
     */
    public function createRequest(
        $method = 'GET',
        $uri = null,
        $headers = null,
        $body = null,
        array $options = array()
    ) {
        $request = parent::createRequest($method, $uri, $headers, $body, $options);
        $request->getQuery()->setAggregator($this->aggregator);
        return $request;
    }
}
Client/UserAgentListener.php000060400000003643152440555050012105 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Client;

use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Listener used to append strings to the User-Agent header of a request based
 * on the `ua.append` option. `ua.append` can contain a string or array of values.
 */
class UserAgentListener implements EventSubscriberInterface
{
    /**
     * @var string Option used to store User-Agent modifiers
     */
    const OPTION = 'ua.append';

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array('command.before_send' => 'onBeforeSend');
    }

    /**
     * Adds strings to the User-Agent header using the `ua.append` parameter of a command
     *
     * @param Event $event Event emitted
     */
    public function onBeforeSend(Event $event)
    {
        $command = $event['command'];
        if ($userAgentAppends = $command->get(self::OPTION)) {
            $request = $command->getRequest();
            $userAgent = (string) $request->getHeader('User-Agent');
            foreach ((array) $userAgentAppends as $append) {
                $append = ' ' . $append;
                if (strpos($userAgent, $append) === false) {
                    $userAgent .= $append;
                }
            }
            $request->setHeader('User-Agent', $userAgent);
        }
    }
}
Client/ClientBuilder.php000060400000042645152440555050011234 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Client;

use Aws\Common\Credentials\Credentials;
use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Credentials\NullCredentials;
use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\ExceptionListener;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\NamespaceExceptionFactory;
use Aws\Common\Exception\Parser\DefaultXmlExceptionParser;
use Aws\Common\Exception\Parser\ExceptionParserInterface;
use Aws\Common\Iterator\AwsResourceIteratorFactory;
use Aws\Common\RulesEndpointProvider;
use Aws\Common\Signature\EndpointSignatureInterface;
use Aws\Common\Signature\SignatureInterface;
use Aws\Common\Signature\SignatureV2;
use Aws\Common\Signature\SignatureV3Https;
use Aws\Common\Signature\SignatureV4;
use Guzzle\Common\Collection;
use Guzzle\Plugin\Backoff\BackoffPlugin;
use Guzzle\Plugin\Backoff\CurlBackoffStrategy;
use Guzzle\Plugin\Backoff\ExponentialBackoffStrategy;
use Guzzle\Plugin\Backoff\HttpBackoffStrategy;
use Guzzle\Plugin\Backoff\TruncatedBackoffStrategy;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Resource\ResourceIteratorClassFactory;
use Guzzle\Log\LogAdapterInterface;
use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Plugin\Backoff\BackoffLogger;

/**
 * Builder for creating AWS service clients
 */
class ClientBuilder
{
    /**
     * @var array Default client config
     */
    protected static $commonConfigDefaults = array('scheme' => 'https');

    /**
     * @var array Default client requirements
     */
    protected static $commonConfigRequirements = array(Options::SERVICE_DESCRIPTION);

    /**
     * @var string The namespace of the client
     */
    protected $clientNamespace;

    /**
     * @var array The config options
     */
    protected $config = array();

    /**
     * @var array The config defaults
     */
    protected $configDefaults = array();

    /**
     * @var array The config requirements
     */
    protected $configRequirements = array();

    /**
     * @var ExceptionParserInterface The Parser interface for the client
     */
    protected $exceptionParser;

    /**
     * @var array Array of configuration data for iterators available for the client
     */
    protected $iteratorsConfig = array();

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

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

    /**
     * Factory method for creating the client builder
     *
     * @param string $namespace The namespace of the client
     *
     * @return ClientBuilder
     */
    public static function factory($namespace = null)
    {
        return new static($namespace);
    }

    /**
     * Constructs a client builder
     *
     * @param string $namespace The namespace of the client
     */
    public function __construct($namespace = null)
    {
        $this->clientNamespace = $namespace;

        // Determine service and class name
        $this->clientClass = 'Aws\Common\Client\DefaultClient';

        if ($this->clientNamespace) {
            $this->serviceName = substr($this->clientNamespace, strrpos($this->clientNamespace, '\\') + 1);
            $this->clientClass = $this->clientNamespace . '\\' . $this->serviceName . 'Client';
        }
    }

    /**
     * Sets the config options
     *
     * @param array|Collection $config The config options
     *
     * @return ClientBuilder
     */
    public function setConfig($config)
    {
        $this->config = $this->processArray($config);

        return $this;
    }

    /**
     * Sets the config options' defaults
     *
     * @param array|Collection $defaults The default values
     *
     * @return ClientBuilder
     */
    public function setConfigDefaults($defaults)
    {
        $this->configDefaults = $this->processArray($defaults);

        return $this;
    }

    /**
     * Sets the required config options
     *
     * @param array|Collection $required The required config options
     *
     * @return ClientBuilder
     */
    public function setConfigRequirements($required)
    {
        $this->configRequirements = $this->processArray($required);

        return $this;
    }

    /**
     * Sets the exception parser. If one is not provided the builder will use
     * the default XML exception parser.
     *
     * @param ExceptionParserInterface $parser The exception parser
     *
     * @return ClientBuilder
     */
    public function setExceptionParser(ExceptionParserInterface $parser)
    {
        $this->exceptionParser = $parser;

        return $this;
    }

    /**
     * Set the configuration for the client's iterators
     *
     * @param array $config Configuration data for client's iterators
     *
     * @return ClientBuilder
     */
    public function setIteratorsConfig(array $config)
    {
        $this->iteratorsConfig = $config;

        return $this;
    }

    /**
     * Performs the building logic using all of the parameters that have been
     * set and falling back to default values. Returns an instantiate service
     * client with credentials prepared and plugins attached.
     *
     * @return AwsClientInterface
     * @throws InvalidArgumentException
     */
    public function build()
    {
        // Resolve configuration
        $config = Collection::fromConfig(
            $this->config,
            array_merge(self::$commonConfigDefaults, $this->configDefaults),
            (self::$commonConfigRequirements + $this->configRequirements)
        );

        if ($config[Options::VERSION] === 'latest') {
            $config[Options::VERSION] = constant("{$this->clientClass}::LATEST_API_VERSION");
        }

        if (!isset($config['endpoint_provider'])) {
            $config['endpoint_provider'] = RulesEndpointProvider::fromDefaults();
        }

        // Resolve the endpoint, signature, and credentials
        $description = $this->updateConfigFromDescription($config);
        $signature = $this->getSignature($description, $config);
        $credentials = $this->getCredentials($config);
        $this->extractHttpConfig($config);

        // Resolve exception parser
        if (!$this->exceptionParser) {
            $this->exceptionParser = new DefaultXmlExceptionParser();
        }

        // Resolve backoff strategy
        $backoff = $config->get(Options::BACKOFF);
        if ($backoff === null) {
            $backoff = $this->createDefaultBackoff();
            $config->set(Options::BACKOFF, $backoff);
        }

        if ($backoff) {
            $this->addBackoffLogger($backoff, $config);
        }

        /** @var AwsClientInterface $client */
        $client = new $this->clientClass($credentials, $signature, $config);
        $client->setDescription($description);

        // Add exception marshaling so that more descriptive exception are thrown
        if ($this->clientNamespace) {
            $exceptionFactory = new NamespaceExceptionFactory(
                $this->exceptionParser,
                "{$this->clientNamespace}\\Exception",
                "{$this->clientNamespace}\\Exception\\{$this->serviceName}Exception"
            );
            $client->addSubscriber(new ExceptionListener($exceptionFactory));
        }

        // Add the UserAgentPlugin to append to the User-Agent header of requests
        $client->addSubscriber(new UserAgentListener());

        // Filters used for the cache plugin
        $client->getConfig()->set(
            'params.cache.key_filter',
            'header=date,x-amz-date,x-amz-security-token,x-amzn-authorization'
        );

        // Set the iterator resource factory based on the provided iterators config
        $client->setResourceIteratorFactory(new AwsResourceIteratorFactory(
            $this->iteratorsConfig,
            new ResourceIteratorClassFactory($this->clientNamespace . '\\Iterator')
        ));

        // Disable parameter validation if needed
        if ($config->get(Options::VALIDATION) === false) {
            $params = $config->get('command.params') ?: array();
            $params['command.disable_validation'] = true;
            $config->set('command.params', $params);
        }

        return $client;
    }

    /**
     * Add backoff logging to the backoff plugin if needed
     *
     * @param BackoffPlugin $plugin Backoff plugin
     * @param Collection    $config Configuration settings
     *
     * @throws InvalidArgumentException
     */
    protected function addBackoffLogger(BackoffPlugin $plugin, Collection $config)
    {
        // The log option can be set to `debug` or an instance of a LogAdapterInterface
        if ($logger = $config->get(Options::BACKOFF_LOGGER)) {
            $format = $config->get(Options::BACKOFF_LOGGER_TEMPLATE);
            if ($logger === 'debug') {
                $logger = new ClosureLogAdapter(function ($message) {
                    trigger_error($message . "\n");
                });
            } elseif (!($logger instanceof LogAdapterInterface)) {
                throw new InvalidArgumentException(
                    Options::BACKOFF_LOGGER . ' must be set to `debug` or an instance of '
                        . 'Guzzle\\Common\\Log\\LogAdapterInterface'
                );
            }
            // Create the plugin responsible for logging exponential backoff retries
            $logPlugin = new BackoffLogger($logger);
            // You can specify a custom format or use the default
            if ($format) {
                $logPlugin->setTemplate($format);
            }
            $plugin->addSubscriber($logPlugin);
        }
    }

    /**
     * Ensures that an array (e.g. for config data) is actually in array form
     *
     * @param array|Collection $array The array data
     *
     * @return array
     * @throws InvalidArgumentException if the arg is not an array or Collection
     */
    protected function processArray($array)
    {
        if ($array instanceof Collection) {
            $array = $array->getAll();
        }

        if (!is_array($array)) {
            throw new InvalidArgumentException('The config must be provided as an array or Collection.');
        }

        return $array;
    }

    /**
     * Update a configuration object from a service description
     *
     * @param Collection $config Config to update
     *
     * @return ServiceDescription
     * @throws InvalidArgumentException
     */
    protected function updateConfigFromDescription(Collection $config)
    {
        $description = $config->get(Options::SERVICE_DESCRIPTION);
        if (!($description instanceof ServiceDescription)) {
            // Inject the version into the sprintf template if it is a string
            if (is_string($description)) {
                $description = sprintf($description, $config->get(Options::VERSION));
            }
            $description = ServiceDescription::factory($description);
            $config->set(Options::SERVICE_DESCRIPTION, $description);
        }

        if (!$config->get(Options::SERVICE)) {
            $config->set(Options::SERVICE, $description->getData('endpointPrefix'));
        }

        if ($iterators = $description->getData('iterators')) {
            $this->setIteratorsConfig($iterators);
        }

        $this->handleRegion($config);
        $this->handleEndpoint($config);

        return $description;
    }

    /**
     * Return an appropriate signature object for a a client based on the
     * "signature" configuration setting, or the default signature specified in
     * a service description. The signature can be set to a valid signature
     * version identifier string or an instance of Aws\Common\Signature\SignatureInterface.
     *
     * @param ServiceDescription $description Description that holds a signature option
     * @param Collection         $config      Configuration options
     *
     * @return SignatureInterface
     * @throws InvalidArgumentException
     */
    protected function getSignature(ServiceDescription $description, Collection $config)
    {
        // If a custom signature has not been provided, then use the default
        // signature setting specified in the service description.
        $signature = $config->get(Options::SIGNATURE) ?: $description->getData('signatureVersion');

        if (is_string($signature)) {
            if ($signature == 'v4') {
                $signature = new SignatureV4();
            } elseif ($signature == 'v2') {
                $signature = new SignatureV2();
            } elseif ($signature == 'v3https') {
                $signature = new SignatureV3Https();
            } else {
                throw new InvalidArgumentException("Invalid signature type: {$signature}");
            }
        } elseif (!($signature instanceof SignatureInterface)) {
            throw new InvalidArgumentException('The provided signature is not '
                . 'a signature version string or an instance of '
                . 'Aws\\Common\\Signature\\SignatureInterface');
        }

        // Allow a custom service name or region value to be provided
        if ($signature instanceof EndpointSignatureInterface) {

            // Determine the service name to use when signing
            $signature->setServiceName($config->get(Options::SIGNATURE_SERVICE)
                ?: $description->getData('signingName')
                ?: $description->getData('endpointPrefix'));

            // Determine the region to use when signing requests
            $signature->setRegionName($config->get(Options::SIGNATURE_REGION) ?: $config->get(Options::REGION));
        }

        return $signature;
    }

    protected function getCredentials(Collection $config)
    {
        $credentials = $config->get(Options::CREDENTIALS);

        if (is_array($credentials)) {
            $credentials = Credentials::factory($credentials);
        } elseif ($credentials === false) {
            $credentials = new NullCredentials();
        } elseif (!$credentials instanceof CredentialsInterface) {
            $credentials = Credentials::factory($config);
        }

        return $credentials;
    }

    private function handleRegion(Collection $config)
    {
        // Make sure a valid region is set
        $region = $config[Options::REGION];
        $description = $config[Options::SERVICE_DESCRIPTION];
        $global = $description->getData('globalEndpoint');

        if (!$global && !$region) {
            throw new InvalidArgumentException(
                'A region is required when using ' . $description->getData('serviceFullName')
            );
        } elseif ($global && !$region) {
            $config[Options::REGION] = 'us-east-1';
        }
    }

    private function handleEndpoint(Collection $config)
    {
        // Alias "endpoint" with "base_url" for forwards compatibility.
        if ($config['endpoint']) {
            $config[Options::BASE_URL] = $config['endpoint'];
            return;
        }

        if ($config[Options::BASE_URL]) {
            return;
        }

        $endpoint = call_user_func(
            $config['endpoint_provider'],
            array(
                'scheme'  => $config[Options::SCHEME],
                'region'  => $config[Options::REGION],
                'service' => $config[Options::SERVICE]
            )
        );

        $config[Options::BASE_URL] = $endpoint['endpoint'];

        // Set a signature if one was not explicitly provided.
        if (!$config->hasKey(Options::SIGNATURE)
            && isset($endpoint['signatureVersion'])
        ) {
            $config->set(Options::SIGNATURE, $endpoint['signatureVersion']);
        }

        // The the signing region if endpoint rule specifies one.
        if (isset($endpoint['credentialScope'])) {
            $scope = $endpoint['credentialScope'];
            if (isset($scope['region'])) {
                $config->set(Options::SIGNATURE_REGION, $scope['region']);
            }
        }
    }

    private function createDefaultBackoff()
    {
        return new BackoffPlugin(
            // Retry failed requests up to 3 times if it is determined that the request can be retried
            new TruncatedBackoffStrategy(3,
                // Retry failed requests with 400-level responses due to throttling
                new ThrottlingErrorChecker($this->exceptionParser,
                    // Retry failed requests due to transient network or cURL problems
                    new CurlBackoffStrategy(null,
                        // Retry failed requests with 500-level responses
                        new HttpBackoffStrategy(array(500, 503, 509),
                            // Retry requests that failed due to expired credentials
                            new ExpiredCredentialsChecker($this->exceptionParser,
                                new ExponentialBackoffStrategy()
                            )
                        )
                    )
                )
            )
        );
    }

    private function extractHttpConfig(Collection $config)
    {
        $http = $config['http'];

        if (!is_array($http)) {
            return;
        }

        if (isset($http['verify'])) {
            $config[Options::SSL_CERT] = $http['verify'];
        }
    }
}
Client/AwsClientInterface.php000060400000006272152440555050012215 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Client;

use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Signature\SignatureInterface;
use Aws\Common\Waiter\WaiterFactoryInterface;
use Aws\Common\Waiter\WaiterInterface;
use Guzzle\Service\ClientInterface;

/**
 * Interface that all AWS clients implement
 */
interface AwsClientInterface extends ClientInterface
{
    /**
     * Returns the AWS credentials associated with the client
     *
     * @return CredentialsInterface
     */
    public function getCredentials();

    /**
     * Sets the credentials object associated with the client
     *
     * @param CredentialsInterface $credentials Credentials object to use
     *
     * @return self
     */
    public function setCredentials(CredentialsInterface $credentials);

    /**
     * Returns the signature implementation used with the client
     *
     * @return SignatureInterface
     */
    public function getSignature();

    /**
     * Get a list of available regions and region data
     *
     * @return array
     */
    public function getRegions();

    /**
     * Get the name of the region to which the client is configured to send requests
     *
     * @return string
     */
    public function getRegion();

    /**
     * Change the region to which the client is configured to send requests
     *
     * @param string $region Name of the region
     *
     * @return self
     */
    public function setRegion($region);

    /**
     * Get the waiter factory being used by the client
     *
     * @return WaiterFactoryInterface
     */
    public function getWaiterFactory();

    /**
     * Set the waiter factory to use with the client
     *
     * @param WaiterFactoryInterface $waiterFactory Factory used to create waiters
     *
     * @return self
     */
    public function setWaiterFactory(WaiterFactoryInterface $waiterFactory);

    /**
     * Wait until a resource is available or an associated waiter returns true
     *
     * @param string $waiter Name of the waiter
     * @param array  $input  Values used as input for the underlying operation and to control the waiter
     *
     * @return self
     */
    public function waitUntil($waiter, array $input = array());

    /**
     * Get a named waiter object
     *
     * @param string $waiter Name of the waiter
     * @param array  $input  Values used as input for the underlying operation and to control the waiter
     *
     * @return WaiterInterface
     */
    public function getWaiter($waiter, array $input = array());

    /**
     * Get the API version of the client (e.g. 2006-03-01)
     *
     * @return string
     */
    public function getApiVersion();
}
Client/DefaultClient.php000060400000006706152440555050011230 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Client;

use Aws\Common\Enum\ClientOptions as Options;
use Guzzle\Common\Collection;

/**
 * Generic client for interacting with an AWS service
 */
class DefaultClient extends AbstractClient
{
    /**
     * Factory method to create a default client using an array of configuration options.
     *
     * The following array keys and values are available options:
     *
     * Credential options ((`key`, `secret`, and optional `token`) OR `credentials` is required):
     *
     * - key: AWS Access Key ID
     * - secret: AWS secret access key
     * - credentials: You can optionally provide a custom `Aws\Common\Credentials\CredentialsInterface` object
     * - token: Custom AWS security token to use with request authentication. Please note that not all services accept temporary credentials. See http://docs.aws.amazon.com/STS/latest/UsingSTS/UsingTokens.html
     * - token.ttd: UNIX timestamp for when the custom credentials expire
     * - credentials.cache.key: Optional custom cache key to use with the credentials
     * - credentials.client: Pass this option to specify a custom `Guzzle\Http\ClientInterface` to use if your credentials require a HTTP request (e.g. RefreshableInstanceProfileCredentials)
     *
     * Region and endpoint options (Some services do not require a region while others do. Check the service specific user guide documentation for details):
     *
     * - region: Region name (e.g. 'us-east-1', 'us-west-1', 'us-west-2', 'eu-west-1', etc...)
     * - scheme: URI Scheme of the base URL (e.g. 'https', 'http') used when endpoint is not supplied
     * - endpoint: Allows you to specify a custom endpoint instead of building one from the region and scheme
     *
     * Generic client options:
     *
     * - signature: Overrides the signature used by the client. Clients will always choose an appropriate default signature. However, it can be useful to override this with a custom setting. This can be set to "v4", "v3https", "v2" or an instance of Aws\Common\Signature\SignatureInterface.
     * - ssl.certificate_authority: Set to true to use the bundled CA cert or pass the full path to an SSL certificate bundle
     * - curl.options: Associative of CURLOPT_* cURL options to add to each request
     * - client.backoff.logger: `Guzzle\Log\LogAdapterInterface` object used to log backoff retries. Use 'debug' to emit PHP warnings when a retry is issued.
     * - client.backoff.logger.template: Optional template to use for exponential backoff log messages. See `Guzzle\Plugin\Backoff\BackoffLogger` for formatting information.
     *
     * @param array|Collection $config Client configuration data
     *
     * @return self
     */
    public static function factory($config = array())
    {
        return ClientBuilder::factory()
            ->setConfig($config)
            ->setConfigDefaults(array(Options::SCHEME => 'https'))
            ->build();
    }
}
Client/ExpiredCredentialsChecker.php000060400000005224152440555050013542 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Client;

use Aws\Common\Credentials\AbstractRefreshableCredentials;
use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\Parser\ExceptionParserInterface;
use Guzzle\Http\Exception\HttpException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Backoff\BackoffStrategyInterface;
use Guzzle\Plugin\Backoff\AbstractBackoffStrategy;

/**
 * Backoff logic that handles retrying requests when credentials expire
 */
class ExpiredCredentialsChecker extends AbstractBackoffStrategy
{
    /**
     * @var array Array of known retrying exception codes
     */
    protected $retryable = array(
        'RequestExpired' => true,
        'ExpiredTokenException' => true,
        'ExpiredToken' => true
    );

    /**
     * @var ExceptionParserInterface Exception parser used to parse exception responses
     */
    protected $exceptionParser;

    public function __construct(ExceptionParserInterface $exceptionParser, BackoffStrategyInterface $next = null) {
        $this->exceptionParser = $exceptionParser;
        $this->next = $next;
    }

    public function makesDecision()
    {
        return true;
    }

    protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
    {
        if ($response && $response->isClientError()) {

            $parts = $this->exceptionParser->parse($request, $response);
            if (!isset($this->retryable[$parts['code']]) || !$request->getClient()) {
                return null;
            }

            /** @var AwsClientInterface $client */
            $client = $request->getClient();
            // Only retry if the credentials can be refreshed
            if (!($client->getCredentials() instanceof AbstractRefreshableCredentials)) {
                return null;
            }

            // Resign the request using new credentials
            $client->getSignature()->signRequest($request, $client->getCredentials()->setExpiration(-1));

            // Retry immediately with no delay
            return 0;
        }
    }
}
Client/.htaccess000044400000000424152440555050007563 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Client/ThrottlingErrorChecker.php000060400000004532152440555050013135 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Client;

use Aws\Common\Exception\Parser\ExceptionParserInterface;
use Guzzle\Http\Exception\HttpException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Backoff\BackoffStrategyInterface;
use Guzzle\Plugin\Backoff\AbstractBackoffStrategy;

/**
 * Backoff logic that handles throttling exceptions from services
 */
class ThrottlingErrorChecker extends AbstractBackoffStrategy
{
    /** @var array Whitelist of exception codes (as indexes) that indicate throttling */
    protected static $throttlingExceptions = array(
        'RequestLimitExceeded'                   => true,
        'Throttling'                             => true,
        'ThrottlingException'                    => true,
        'ProvisionedThroughputExceededException' => true,
        'RequestThrottled'                       => true,
    );

    /**
     * @var ExceptionParserInterface Exception parser used to parse exception responses
     */
    protected $exceptionParser;

    public function __construct(ExceptionParserInterface $exceptionParser, BackoffStrategyInterface $next = null)
    {
        $this->exceptionParser = $exceptionParser;
        if ($next) {
            $this->setNext($next);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function makesDecision()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function getDelay(
        $retries,
        RequestInterface $request,
        Response $response = null,
        HttpException $e = null
    ) {
        if ($response && $response->isClientError()) {
            $parts = $this->exceptionParser->parse($request, $response);
            return isset(self::$throttlingExceptions[$parts['code']]) ? true : null;
        }
    }
}
Credentials/Credentials.php000060400000027440152440555050011757 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Credentials;

use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\RequiredExtensionNotLoadedException;
use Aws\Common\Exception\RuntimeException;
use Guzzle\Common\FromConfigInterface;
use Guzzle\Cache\CacheAdapterInterface;
use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Common\Collection;

/**
 * Basic implementation of the AWSCredentials interface that allows callers to
 * pass in the AWS access key and secret access in the constructor.
 */
class Credentials implements CredentialsInterface, FromConfigInterface
{
    const ENV_KEY = 'AWS_ACCESS_KEY_ID';
    const ENV_SECRET = 'AWS_SECRET_KEY';
    const ENV_SECRET_ACCESS_KEY = 'AWS_SECRET_ACCESS_KEY';
    const ENV_PROFILE = 'AWS_PROFILE';

    /** @var string AWS Access Key ID */
    protected $key;

    /** @var string AWS Secret Access Key */
    protected $secret;

    /** @var string AWS Security Token */
    protected $token;

    /** @var int Time to die of token */
    protected $ttd;

    /**
     * Get the available keys for the factory method
     *
     * @return array
     */
    public static function getConfigDefaults()
    {
        return array(
            Options::KEY                   => null,
            Options::SECRET                => null,
            Options::TOKEN                 => null,
            Options::TOKEN_TTD             => null,
            Options::PROFILE               => null,
            Options::CREDENTIALS_CACHE     => null,
            Options::CREDENTIALS_CACHE_KEY => null,
            Options::CREDENTIALS_CLIENT    => null
        );
    }

    /**
     * Factory method for creating new credentials.  This factory method will
     * create the appropriate credentials object with appropriate decorators
     * based on the passed configuration options.
     *
     * @param array $config Options to use when instantiating the credentials
     *
     * @return CredentialsInterface
     * @throws InvalidArgumentException If the caching options are invalid
     * @throws RuntimeException         If using the default cache and APC is disabled
     */
    public static function factory($config = array())
    {
        // Add default key values
        foreach (self::getConfigDefaults() as $key => $value) {
            if (!isset($config[$key])) {
                $config[$key] = $value;
            }
        }

        // Set up the cache
        $cache = $config[Options::CREDENTIALS_CACHE];
        $cacheKey = $config[Options::CREDENTIALS_CACHE_KEY] ?:
            'credentials_' . ($config[Options::KEY] ?: crc32(gethostname()));

        if (
            $cacheKey &&
            $cache instanceof CacheAdapterInterface &&
            $cached = self::createFromCache($cache, $cacheKey)
        ) {
            return $cached;
        }

        // Create the credentials object
        if (!$config[Options::KEY] || !$config[Options::SECRET]) {
            $credentials = self::createFromEnvironment($config);
        } else {
            // Instantiate using short or long term credentials
            $credentials = new static(
                $config[Options::KEY],
                $config[Options::SECRET],
                $config[Options::TOKEN],
                $config[Options::TOKEN_TTD]
            );
        }

        // Check if the credentials are refreshable, and if so, configure caching
        $cache = $config[Options::CREDENTIALS_CACHE];
        if ($cacheKey && $cache) {
            $credentials = self::createCache($credentials, $cache, $cacheKey);
        }

        return $credentials;
    }

    /**
     * Create credentials from the credentials ini file in the HOME directory.
     *
     * @param string|null $profile  Pass a specific profile to use. If no
     *                              profile is specified we will attempt to use
     *                              the value specified in the AWS_PROFILE
     *                              environment variable. If AWS_PROFILE is not
     *                              set, the "default" profile is used.
     * @param string|null $filename Pass a string to specify the location of the
     *                              credentials files. If null is passed, the
     *                              SDK will attempt to find the configuration
     *                              file at in your HOME directory at
     *                              ~/.aws/credentials.
     * @return CredentialsInterface
     * @throws \RuntimeException if the file cannot be found, if the file is
     *                           invalid, or if the profile is invalid.
     */
    public static function fromIni($profile = null, $filename = null)
    {
        if (!$filename) {
            $filename = self::getHomeDir() . '/.aws/credentials';
        }

        if (!$profile) {
            $profile = self::getEnvVar(self::ENV_PROFILE) ?: 'default';
        }

        if (!is_readable($filename) || ($data = parse_ini_file($filename, true)) === false) {
            throw new \RuntimeException("Invalid AWS credentials file: {$filename}.");
        }

        if (!isset($data[$profile]['aws_access_key_id']) || !isset($data[$profile]['aws_secret_access_key'])) {
            throw new \RuntimeException("Invalid AWS credentials profile {$profile} in {$filename}.");
        }

        return new self(
            $data[$profile]['aws_access_key_id'],
            $data[$profile]['aws_secret_access_key'],
            isset($data[$profile]['aws_security_token'])
                ? $data[$profile]['aws_security_token']
                : null
        );
    }

    /**
     * Constructs a new BasicAWSCredentials object, with the specified AWS
     * access key and AWS secret key
     *
     * @param string $accessKeyId     AWS access key ID
     * @param string $secretAccessKey AWS secret access key
     * @param string $token           Security token to use
     * @param int    $expiration      UNIX timestamp for when credentials expire
     */
    public function __construct($accessKeyId, $secretAccessKey, $token = null, $expiration = null)
    {
        $this->key = trim($accessKeyId);
        $this->secret = trim($secretAccessKey);
        $this->token = $token;
        $this->ttd = $expiration;
    }

    public function serialize()
    {
        return json_encode(array(
            Options::KEY       => $this->key,
            Options::SECRET    => $this->secret,
            Options::TOKEN     => $this->token,
            Options::TOKEN_TTD => $this->ttd
        ));
    }

    public function unserialize($serialized)
    {
        $data = json_decode($serialized, true);
        $this->key    = $data[Options::KEY];
        $this->secret = $data[Options::SECRET];
        $this->token  = $data[Options::TOKEN];
        $this->ttd    = $data[Options::TOKEN_TTD];
    }

    public function getAccessKeyId()
    {
        return $this->key;
    }

    public function getSecretKey()
    {
        return $this->secret;
    }

    public function getSecurityToken()
    {
        return $this->token;
    }

    public function getExpiration()
    {
        return $this->ttd;
    }

    public function isExpired()
    {
        return $this->ttd !== null && time() >= $this->ttd;
    }

    public function setAccessKeyId($key)
    {
        $this->key = $key;

        return $this;
    }

    public function setSecretKey($secret)
    {
        $this->secret = $secret;

        return $this;
    }

    public function setSecurityToken($token)
    {
        $this->token = $token;

        return $this;
    }

    public function setExpiration($timestamp)
    {
        $this->ttd = $timestamp;

        return $this;
    }

    /**
     * When no keys are provided, attempt to create them based on the
     * environment or instance profile credentials.
     *
     * @param array|Collection $config
     *
     * @return CredentialsInterface
     */
    private static function createFromEnvironment($config)
    {
        // Get key and secret from ENV variables
        $envKey = self::getEnvVar(self::ENV_KEY);
        if (!($envSecret = self::getEnvVar(self::ENV_SECRET))) {
            // Use AWS_SECRET_ACCESS_KEY if AWS_SECRET_KEY was not set
            $envSecret = self::getEnvVar(self::ENV_SECRET_ACCESS_KEY);
        }

        // Use credentials from the environment variables if available
        if ($envKey && $envSecret) {
            return new static($envKey, $envSecret);
        }

        try {
            // Use credentials from the INI file in HOME directory if available
            return self::fromIni($config[Options::PROFILE]);
        } catch (\RuntimeException $e) {
            // Otherwise, try using instance profile credentials (available on EC2 instances)
            return new RefreshableInstanceProfileCredentials(
                new static('', '', '', 1),
                $config[Options::CREDENTIALS_CLIENT]
            );
        }
    }

    private static function createFromCache(CacheAdapterInterface $cache, $cacheKey)
    {
        $cached = $cache->fetch($cacheKey);
        if ($cached instanceof CredentialsInterface && !$cached->isExpired()) {
            return new CacheableCredentials($cached, $cache, $cacheKey);
        }

        return null;
    }

    private static function createCache(CredentialsInterface $credentials, $cache, $cacheKey)
    {
        if ($cache === 'true' || $cache === true) {
            // If no cache adapter was provided, then create one for the user
            // @codeCoverageIgnoreStart
            if (!extension_loaded('apc')) {
                throw new RequiredExtensionNotLoadedException('PHP has not been compiled with APC. Unable to cache '
                    . 'the credentials.');
            } elseif (!class_exists('Doctrine\Common\Cache\ApcCache')) {
                throw new RuntimeException(
                    'Cannot set ' . Options::CREDENTIALS_CACHE . ' to true because the Doctrine cache component is '
                    . 'not installed. Either install doctrine/cache or pass in an instantiated '
                    . 'Guzzle\Cache\CacheAdapterInterface object'
                );
            }
            // @codeCoverageIgnoreEnd
            $cache = new DoctrineCacheAdapter(new \Doctrine\Common\Cache\ApcCache());
        } elseif (!($cache instanceof CacheAdapterInterface)) {
            throw new InvalidArgumentException('Unable to utilize caching with the specified options');
        }

        // Decorate the credentials with a cache
        return new CacheableCredentials($credentials, $cache, $cacheKey);
    }

    private static function getHomeDir()
    {
        // On Linux/Unix-like systems, use the HOME environment variable
        if ($homeDir = self::getEnvVar('HOME')) {
            return $homeDir;
        }

        // Get the HOMEDRIVE and HOMEPATH values for Windows hosts
        $homeDrive = self::getEnvVar('HOMEDRIVE');
        $homePath = self::getEnvVar('HOMEPATH');

        return ($homeDrive && $homePath) ? $homeDrive . $homePath : null;
    }

    /**
     * Fetches the value of an environment variable by checking $_SERVER and getenv().
     *
     * @param string $var Name of the environment variable
     *
     * @return mixed|null
     */
    private static function getEnvVar($var)
    {
        return isset($_SERVER[$var]) ? $_SERVER[$var] : getenv($var);
    }
}
Credentials/AbstractRefreshableCredentials.php000060400000003403152440555050015577 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Credentials;

/**
 * Abstract decorator to provide a foundation for refreshable credentials
 */
abstract class AbstractRefreshableCredentials extends AbstractCredentialsDecorator
{
    /**
     * {@inheritdoc}
     */
    public function getAccessKeyId()
    {
        if ($this->credentials->isExpired()) {
            $this->refresh();
        }

        return $this->credentials->getAccessKeyId();
    }

    /**
     * {@inheritdoc}
     */
    public function getSecretKey()
    {
        if ($this->credentials->isExpired()) {
            $this->refresh();
        }

        return $this->credentials->getSecretKey();
    }

    /**
     * {@inheritdoc}
     */
    public function getSecurityToken()
    {
        if ($this->credentials->isExpired()) {
            $this->refresh();
        }

        return $this->credentials->getSecurityToken();
    }

    /**
     * {@inheritdoc}
     */
    public function serialize()
    {
        if ($this->credentials->isExpired()) {
            $this->refresh();
        }

        return $this->credentials->serialize();
    }

    /**
     * Attempt to get new credentials
     */
    abstract protected function refresh();
}
Credentials/CredentialsInterface.php000060400000004650152440555050013576 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Credentials;

/**
 * Provides access to the AWS credentials used for accessing AWS services: AWS
 * access key ID, secret access key, and security token. These credentials are
 * used to securely sign requests to AWS services.
 */
interface CredentialsInterface extends \Serializable
{
    /**
     * Returns the AWS access key ID for this credentials object.
     *
     * @return string
     */
    public function getAccessKeyId();

    /**
     * Returns the AWS secret access key for this credentials object.
     *
     * @return string
     */
    public function getSecretKey();

    /**
     * Get the associated security token if available
     *
     * @return string|null
     */
    public function getSecurityToken();

    /**
     * Get the UNIX timestamp in which the credentials will expire
     *
     * @return int|null
     */
    public function getExpiration();

    /**
     * Set the AWS access key ID for this credentials object.
     *
     * @param string $key AWS access key ID
     *
     * @return self
     */
    public function setAccessKeyId($key);

    /**
     * Set the AWS secret access key for this credentials object.
     *
     * @param string $secret AWS secret access key
     *
     * @return CredentialsInterface
     */
    public function setSecretKey($secret);

    /**
     * Set the security token to use with this credentials object
     *
     * @param string $token Security token
     *
     * @return self
     */
    public function setSecurityToken($token);

    /**
     * Set the UNIX timestamp in which the credentials will expire
     *
     * @param int $timestamp UNIX timestamp expiration
     *
     * @return self
     */
    public function setExpiration($timestamp);

    /**
     * Check if the credentials are expired
     *
     * @return bool
     */
    public function isExpired();
}
Credentials/RefreshableInstanceProfileCredentials.php000060400000005675152440555050017136 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Credentials;

use Aws\Common\InstanceMetadata\InstanceMetadataClient;
use Aws\Common\Exception\InstanceProfileCredentialsException;

/**
 * Credentials decorator used to implement retrieving credentials from the
 * EC2 metadata server
 */
class RefreshableInstanceProfileCredentials extends AbstractRefreshableCredentials
{
    /**
     * @var InstanceMetadataClient
     */
    protected $client;
    /** @var bool */
    private $customClient;

    /**
     * Constructs a new instance profile credentials decorator
     *
     * @param CredentialsInterface   $credentials Credentials to adapt
     * @param InstanceMetadataClient $client      Client used to get new credentials
     */
    public function __construct(CredentialsInterface $credentials, InstanceMetadataClient $client = null)
    {
        $this->credentials = $credentials;
        $this->setClient($client);
    }

    public function setClient(InstanceMetadataClient $client = null)
    {
        $this->customClient = null !== $client;
        $this->client = $client ?: InstanceMetadataClient::factory();
    }

    public function serialize()
    {
        $serializable = array(
            'credentials' => parent::serialize(),
            'customClient' => $this->customClient,
        );

        if ($this->customClient) {
            $serializable['client'] = serialize($this->client);
        }

        return json_encode($serializable);
    }

    public function unserialize($value)
    {
        $serialized = json_decode($value, true);
        parent::unserialize($serialized['credentials']);
        $this->customClient = $serialized['customClient'];
        $this->client = $this->customClient ?
            unserialize($serialized['client'])
            : InstanceMetadataClient::factory();
    }

    /**
     * Attempt to get new credentials from the instance profile
     *
     * @throws InstanceProfileCredentialsException On error
     */
    protected function refresh()
    {
        $credentials = $this->client->getInstanceProfileCredentials();
        // Expire the token 30 minutes early to pre-fetch before expiring.
        $this->credentials->setAccessKeyId($credentials->getAccessKeyId())
            ->setSecretKey($credentials->getSecretKey())
            ->setSecurityToken($credentials->getSecurityToken())
            ->setExpiration($credentials->getExpiration() - 1800);
    }
}
Credentials/AbstractCredentialsDecorator.php000060400000005437152440555050015310 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Credentials;

/**
 * Abstract credentials decorator
 */
class AbstractCredentialsDecorator implements CredentialsInterface
{
    /**
     * @var CredentialsInterface Wrapped credentials object
     */
    protected $credentials;

    /**
     * Constructs a new BasicAWSCredentials object, with the specified AWS
     * access key and AWS secret key
     *
     * @param CredentialsInterface $credentials
     */
    public function __construct(CredentialsInterface $credentials)
    {
        $this->credentials = $credentials;
    }

    /**
     * {@inheritdoc}
     */
    public function serialize()
    {
        return $this->credentials->serialize();
    }

    /**
     * {@inheritdoc}
     */
    public function unserialize($serialized)
    {
        $this->credentials = new Credentials('', '');
        $this->credentials->unserialize($serialized);
    }

    /**
     * {@inheritdoc}
     */
    public function getAccessKeyId()
    {
        return $this->credentials->getAccessKeyId();
    }

    /**
     * {@inheritdoc}
     */
    public function getSecretKey()
    {
        return $this->credentials->getSecretKey();
    }

    /**
     * {@inheritdoc}
     */
    public function getSecurityToken()
    {
        return $this->credentials->getSecurityToken();
    }

    /**
     * {@inheritdoc}
     */
    public function getExpiration()
    {
        return $this->credentials->getExpiration();
    }

    /**
     * {@inheritdoc}
     */
    public function isExpired()
    {
        return $this->credentials->isExpired();
    }

    /**
     * {@inheritdoc}
     */
    public function setAccessKeyId($key)
    {
        $this->credentials->setAccessKeyId($key);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setSecretKey($secret)
    {
        $this->credentials->setSecretKey($secret);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setSecurityToken($token)
    {
        $this->credentials->setSecurityToken($token);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setExpiration($timestamp)
    {
        $this->credentials->setExpiration($timestamp);

        return $this;
    }
}
Credentials/NullCredentials.php000060400000002332152440555050012603 0ustar00<?php
namespace Aws\Common\Credentials;

/**
 * A blank set of credentials. AWS clients must be provided credentials, but
 * there are some types of requests that do not need authentication. This class
 * can be used to pivot on that scenario, and also serve as a mock credentials
 * object when testing
 *
 * @codeCoverageIgnore
 */
class NullCredentials implements CredentialsInterface
{
    public function getAccessKeyId()
    {
        return '';
    }

    public function getSecretKey()
    {
        return '';
    }

    public function getSecurityToken()
    {
        return null;
    }

    public function getExpiration()
    {
        return null;
    }

    public function isExpired()
    {
        return false;
    }

    public function serialize()
    {
        return 'N;';
    }

    public function unserialize($serialized)
    {
        // Nothing to do here.
    }

    public function setAccessKeyId($key)
    {
        // Nothing to do here.
    }

    public function setSecretKey($secret)
    {
        // Nothing to do here.
    }

    public function setSecurityToken($token)
    {
        // Nothing to do here.
    }

    public function setExpiration($timestamp)
    {
        // Nothing to do here.
    }
}
Credentials/.htaccess000044400000000424152440555050010602 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Credentials/CacheableCredentials.php000060400000005201152440555050013516 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Credentials;

use Guzzle\Cache\CacheAdapterInterface;

/**
 * Credentials decorator used to implement caching credentials
 */
class CacheableCredentials extends AbstractRefreshableCredentials
{
    /**
     * @var CacheAdapterInterface Cache adapter used to store credentials
     */
    protected $cache;

    /**
     * @var string Cache key used to store the credentials
     */
    protected $cacheKey;

    /**
     * CacheableCredentials is a decorator that decorates other credentials
     *
     * @param CredentialsInterface  $credentials Credentials to adapt
     * @param CacheAdapterInterface $cache       Cache to use to store credentials
     * @param string                $cacheKey    Cache key of the credentials
     */
    public function __construct(CredentialsInterface $credentials, CacheAdapterInterface $cache, $cacheKey)
    {
        $this->cache = $cache;
        $this->cacheKey = $cacheKey;

        parent::__construct($credentials);
    }

    /**
     * Attempt to get new credentials from cache or from the adapted object
     */
    protected function refresh()
    {
        if (!$cache = $this->cache->fetch($this->cacheKey)) {
            // The credentials were not found, so try again and cache if new
            $this->credentials->getAccessKeyId();
            if (!$this->credentials->isExpired()) {
                // The credentials were updated, so cache them
                $this->cache->save($this->cacheKey, $this->credentials, $this->credentials->getExpiration() - time());
            }
        } else {
            // The credentials were found in cache, so update the adapter object
            // if the cached credentials are not expired
            if (!$cache->isExpired()) {
                $this->credentials->setAccessKeyId($cache->getAccessKeyId());
                $this->credentials->setSecretKey($cache->getSecretKey());
                $this->credentials->setSecurityToken($cache->getSecurityToken());
                $this->credentials->setExpiration($cache->getExpiration());
            }
        }
    }
}
HostNameUtils.php000060400000004655152440555050010027 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common;

use Guzzle\Http\Url;

/**
 * Utility class for parsing regions and services from URLs
 */
class HostNameUtils
{
    const DEFAULT_REGION = 'us-east-1';
    const DEFAULT_GOV_REGION = 'us-gov-west-1';

    /**
     * Parse the AWS region name from a URL
     *
     *
     * @param Url $url HTTP URL
     *
     * @return string
     * @link http://docs.aws.amazon.com/general/latest/gr/rande.html
     */
    public static function parseRegionName(Url $url)
    {
        // If we don't recognize the domain, just return the default
        if (substr($url->getHost(), -14) != '.amazonaws.com') {
            return self::DEFAULT_REGION;
        }

        $serviceAndRegion = substr($url->getHost(), 0, -14);
        // Special handling for S3 regions
        $separator = strpos($serviceAndRegion, 's3') === 0 ? '-' : '.';
        $separatorPos = strpos($serviceAndRegion, $separator);

        // If don't detect a separator, then return the default region
        if ($separatorPos === false) {
            return self::DEFAULT_REGION;
        }

        $region = substr($serviceAndRegion, $separatorPos + 1);

        // All GOV regions currently use the default GOV region
        if ($region == 'us-gov') {
            return self::DEFAULT_GOV_REGION;
        }

        return $region;
    }

    /**
     * Parse the AWS service name from a URL
     *
     * @param Url $url HTTP URL
     *
     * @return string Returns a service name (or empty string)
     * @link http://docs.aws.amazon.com/general/latest/gr/rande.html
     */
    public static function parseServiceName(Url $url)
    {
        // The service name is the first part of the host
        $parts = explode('.', $url->getHost(), 2);

        // Special handling for S3
        if (stripos($parts[0], 's3') === 0) {
            return 's3';
        }

        return $parts[0];
    }
}
Iterator/AwsResourceIteratorFactory.php000060400000007236152440555050014363 0ustar00<?php

namespace Aws\Common\Iterator;

use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Collection;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Resource\ResourceIteratorFactoryInterface;

/**
 * Resource iterator factory used to instantiate the default AWS resource iterator with the correct configuration or
 * use a concrete iterator class if one exists
 */
class AwsResourceIteratorFactory implements ResourceIteratorFactoryInterface
{
    /**
     * @var array Default configuration values for iterators
     */
    protected static $defaultIteratorConfig = array(
        'input_token'  => null,
        'output_token' => null,
        'limit_key'    => null,
        'result_key'   => null,
        'more_results' => null,
    );

    /**
     * @var array Legacy configuration options mapped to their new names
     */
    private static $legacyConfigOptions = array(
        'token_param' => 'input_token',
        'token_key'   => 'output_token',
        'limit_param' => 'limit_key',
        'more_key'    => 'more_results',
    );

    /**
     * @var array Iterator configuration for each iterable operation
     */
    protected $config;

    /**
     * @var ResourceIteratorFactoryInterface Another factory that will be used first to instantiate the iterator
     */
    protected $primaryIteratorFactory;

    /**
     * @param array                            $config                 An array of configuration values for the factory
     * @param ResourceIteratorFactoryInterface $primaryIteratorFactory Another factory to use for chain of command
     */
    public function __construct(array $config, ResourceIteratorFactoryInterface $primaryIteratorFactory = null)
    {
        $this->primaryIteratorFactory = $primaryIteratorFactory;
        $this->config = array();
        foreach ($config as $name => $operation) {
            $this->config[$name] = $operation + self::$defaultIteratorConfig;
        }
    }

    public function build(CommandInterface $command, array $options = array())
    {
        // Get the configuration data for the command
        $commandName = $command->getName();
        $commandSupported = isset($this->config[$commandName]);
        $options = $this->translateLegacyConfigOptions($options);
        $options += $commandSupported ? $this->config[$commandName] : array();

        // Instantiate the iterator using the primary factory (if one was provided)
        if ($this->primaryIteratorFactory && $this->primaryIteratorFactory->canBuild($command)) {
            $iterator = $this->primaryIteratorFactory->build($command, $options);
        } elseif (!$commandSupported) {
            throw new InvalidArgumentException("Iterator was not found for {$commandName}.");
        } else {
            // Instantiate a generic AWS resource iterator
            $iterator = new AwsResourceIterator($command, $options);
        }

        return $iterator;
    }

    public function canBuild(CommandInterface $command)
    {
        if ($this->primaryIteratorFactory) {
            return $this->primaryIteratorFactory->canBuild($command);
        } else {
            return isset($this->config[$command->getName()]);
        }
    }

    /**
     * @param array $config The config for a single operation
     *
     * @return array The modified config with legacy options translated
     */
    private function translateLegacyConfigOptions($config)
    {
        foreach (self::$legacyConfigOptions as $legacyOption => $newOption) {
            if (isset($config[$legacyOption])) {
                $config[$newOption] = $config[$legacyOption];
                unset($config[$legacyOption]);
            }
        }

        return $config;
    }
}
Iterator/AwsResourceIterator.php000060400000014102152440555050013021 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Iterator;

use Aws\Common\Enum\UaString as Ua;
use Aws\Common\Exception\RuntimeException;
Use Guzzle\Service\Resource\Model;
use Guzzle\Service\Resource\ResourceIterator;

/**
 * Iterate over a client command
 */
class AwsResourceIterator extends ResourceIterator
{
    /**
     * @var Model Result of a command
     */
    protected $lastResult = null;

    /**
     * Provides access to the most recent result obtained by the iterator. This makes it easier to extract any
     * additional information from the result which you do not have access to from the values emitted by the iterator
     *
     * @return Model|null
     */
    public function getLastResult()
    {
        return $this->lastResult;
    }

    /**
     * {@inheritdoc}
     * This AWS specific version of the resource iterator provides a default implementation of the typical AWS iterator
     * process. It relies on configuration and extension to implement the operation-specific logic of handling results
     * and nextTokens. This method will loop until resources are acquired or there are no more iterations available.
     */
    protected function sendRequest()
    {
        do {
            // Prepare the request including setting the next token
            $this->prepareRequest();
            if ($this->nextToken) {
                $this->applyNextToken();
            }

            // Execute the request and handle the results
            $this->command->add(Ua::OPTION, Ua::ITERATOR);
            $this->lastResult = $this->command->getResult();
            $resources = $this->handleResults($this->lastResult);
            $this->determineNextToken($this->lastResult);

            // If no resources collected, prepare to reiterate before yielding
            if ($reiterate = empty($resources) && $this->nextToken) {
                $this->command = clone $this->originalCommand;
            }
        } while ($reiterate);

        return $resources;
    }

    protected function prepareRequest()
    {
        // Get the limit parameter key to set
        $limitKey = $this->get('limit_key');
        if ($limitKey && ($limit = $this->command->get($limitKey))) {
            $pageSize = $this->calculatePageSize();

            // If the limit of the command is different than the pageSize of the iterator, use the smaller value
            if ($limit && $pageSize) {
                $realLimit = min($limit, $pageSize);
                $this->command->set($limitKey, $realLimit);
            }
        }
    }

    protected function handleResults(Model $result)
    {
        $results = array();

        // Get the result key that contains the results
        if ($resultKey = $this->get('result_key')) {
            $results = $this->getValueFromResult($result, $resultKey) ?: array();
        }

        return $results;
    }

    protected function applyNextToken()
    {
        // Get the token parameter key to set
        if ($tokenParam = $this->get('input_token')) {
            // Set the next token. Works with multi-value tokens
            if (is_array($tokenParam)) {
                if (is_array($this->nextToken) && count($tokenParam) === count($this->nextToken)) {
                    foreach (array_combine($tokenParam, $this->nextToken) as $param => $token) {
                        $this->command->set($param, $token);
                    }
                } else {
                    throw new RuntimeException('The definition of the iterator\'s token parameter and the actual token '
                        . 'value are not compatible.');
                }
            } else {
                $this->command->set($tokenParam, $this->nextToken);
            }
        }
    }

    protected function determineNextToken(Model $result)
    {
        $this->nextToken = null;

        // If the value of "more_results" is true or there is no "more_results" to check, then try to get the next token
        $moreKey = $this->get('more_results');
        if ($moreKey === null || $this->getValueFromResult($result, $moreKey)) {
            // Get the token key to check
            if ($tokenKey = $this->get('output_token')) {
                // Get the next token's value. Works with multi-value tokens
                if (is_array($tokenKey)) {
                    $this->nextToken = array();
                    foreach ($tokenKey as $key) {
                        $this->nextToken[] = $this->getValueFromResult($result, $key);
                    }
                } else {
                    $this->nextToken = $this->getValueFromResult($result, $tokenKey);
                }
            }
        }
    }

    /**
     * Extracts the value from the result using Collection::getPath. Also adds some additional logic for keys that need
     * to access n-1 indexes (e.g., ImportExport, Kinesis). The n-1 logic only works for the known cases. We will switch
     * to a jmespath implementation in the future to cover all cases
     *
     * @param Model  $result
     * @param string $key
     *
     * @return mixed|null
     */
    protected function getValueFromResult(Model $result, $key)
    {
        // Special handling for keys that need to access n-1 indexes
        if (strpos($key, '#') !== false) {
            $keyParts = explode('#', $key, 2);
            $items = $result->getPath(trim($keyParts[0], '/'));
            if ($items && is_array($items)) {
                $index = count($items) - 1;
                $key = strtr($key, array('#' => $index));
            }
        }

        // Get the value
        return $result->getPath($key);
    }
}
Iterator/.htaccess000044400000000424152440555050010136 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Enum.php000060400000002621152440555050006163 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common;

/**
 * Represents an enumerable set of values
 */
abstract class Enum
{
    /**
     * @var array A cache of all enum values to increase performance
     */
    protected static $cache = array();

    /**
     * Returns the names (or keys) of all of constants in the enum
     *
     * @return array
     */
    public static function keys()
    {
        return array_keys(static::values());
    }

    /**
     * Return the names and values of all the constants in the enum
     *
     * @return array
     */
    public static function values()
    {
        $class = get_called_class();

        if (!isset(self::$cache[$class])) {
            $reflected = new \ReflectionClass($class);
            self::$cache[$class] = $reflected->getConstants();
        }

        return self::$cache[$class];
    }
}
Facade/.htaccess000044400000000424152440555050007510 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Facade/Facade.php000060400000004513152440555050007567 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Facade;

use Aws\Common\Aws;

/**
 * Base facade class that handles the delegation logic
 *
 * @deprecated "Facades" are being removed in version 3.0 of the SDK.
 */
abstract class Facade implements FacadeInterface
{
    /** @var Aws */
    protected static $serviceBuilder;

    /**
     * Mounts the facades by extracting information from the service builder config and using creating class aliases
     *
     * @param string|null $targetNamespace Namespace that the facades should be mounted to. Defaults to global namespace
     *
     * @param Aws $serviceBuilder
     */
    public static function mountFacades(Aws $serviceBuilder, $targetNamespace = null)
    {
        self::$serviceBuilder = $serviceBuilder;
        require_once __DIR__ . '/facade-classes.php';
        foreach ($serviceBuilder->getConfig() as $service) {
            if (isset($service['alias'], $service['class'])) {
                $facadeClass = __NAMESPACE__ . '\\' . $service['alias'];
                $facadeAlias = ltrim($targetNamespace . '\\' . $service['alias'], '\\');
                if (!class_exists($facadeAlias) && class_exists($facadeClass)) {
                    // @codeCoverageIgnoreStart
                    class_alias($facadeClass, $facadeAlias);
                    // @codeCoverageIgnoreEnd
                }
            }
        }
    }

    /**
     * Returns the instance of the client that the facade operates on
     *
     * @return \Aws\Common\Client\AwsClientInterface
     */
    public static function getClient()
    {
        return self::$serviceBuilder->get(static::getServiceBuilderKey());
    }

    public static function __callStatic($method, $args)
    {
        return call_user_func_array(array(self::getClient(), $method), $args);
    }
}
Facade/facade-classes.php000060400000011600152440555050011255 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Facade;

/**
 * The following classes are used to implement the static client facades and are aliased into the global namespaced. We
 * discourage the use of these classes directly by their full namespace since they are not autoloaded and are considered
 * an implementation detail that could possibly be changed in the future.
 */

// @codeCoverageIgnoreStart

class AutoScaling extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'autoscaling';
    }
}

class CloudFormation extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'cloudformation';
    }
}

class CloudFront extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'cloudfront';
    }
}

class CloudSearch extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'cloudsearch';
    }
}

class CloudTrail extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'cloudtrail';
    }
}

class CloudWatch extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'cloudwatch';
    }
}

class DataPipeline extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'datapipeline';
    }
}

class DirectConnect extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'directconnect';
    }
}

class DynamoDb extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'dynamodb';
    }
}

class Ec2 extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'ec2';
    }
}

class ElastiCache extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'elasticache';
    }
}

class ElasticBeanstalk extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'elasticbeanstalk';
    }
}

class ElasticLoadBalancing extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'elasticloadbalancing';
    }
}

class ElasticTranscoder extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'elastictranscoder';
    }
}

class Emr extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'emr';
    }
}

class Glacier extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'glacier';
    }
}

class Iam extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'iam';
    }
}

class ImportExport extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'importexport';
    }
}

class Kinesis extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'kinesis';
    }
}

class OpsWorks extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'opsworks';
    }
}

class Rds extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'rds';
    }
}

class Redshift extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'redshift';
    }
}

class Route53 extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'route53';
    }
}

class S3 extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 's3';
    }
}

class SimpleDb extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'sdb';
    }
}

class Ses extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'ses';
    }
}

class Sns extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'sns';
    }
}

class Sqs extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'sqs';
    }
}

class StorageGateway extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'storagegateway';
    }
}

class Sts extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'sts';
    }
}

class Support extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'support';
    }
}

class Swf extends Facade
{
    public static function getServiceBuilderKey()
    {
        return 'swf';
    }
}

// @codeCoverageIgnoreEnd
Facade/FacadeInterface.php000060400000002225152440555050011406 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Facade;

/**
 * Interface that defines a client facade. Facades are convenient static classes that allow you to run client methods
 * statically on a default instance from the service builder. The facades themselves are aliased into the global
 * namespace for ease of use.
 *
 * @deprecated "Facades" are being removed in version 3.0 of the SDK.
 */
interface FacadeInterface
{
    /**
     * Returns the key used to access the client instance from the Service Builder
     *
     * @return string
     */
    public static function getServiceBuilderKey();
}
Resources/aws-config.php000060400000025222152440555050011270 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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.
 */

return array(
    'class' => 'Aws\Common\Aws',
    'services' => array(

        'default_settings' => array(
            'params' => array()
        ),

        'autoscaling' => array(
            'alias'   => 'AutoScaling',
            'extends' => 'default_settings',
            'class'   => 'Aws\AutoScaling\AutoScalingClient'
        ),

        'cloudformation' => array(
            'alias'   => 'CloudFormation',
            'extends' => 'default_settings',
            'class'   => 'Aws\CloudFormation\CloudFormationClient'
        ),

        'cloudfront' => array(
            'alias'   => 'CloudFront',
            'extends' => 'default_settings',
            'class'   => 'Aws\CloudFront\CloudFrontClient'
        ),

        'cloudfront_20120505' => array(
            'extends' => 'cloudfront',
            'params' => array(
                'version' => '2012-05-05'
            )
        ),

        'cloudhsm' => array(
            'alias'   => 'CloudHsm',
            'extends' => 'default_settings',
            'class'   => 'Aws\CloudHsm\CloudHsmClient'
        ),

        'cloudsearch' => array(
            'alias'   => 'CloudSearch',
            'extends' => 'default_settings',
            'class'   => 'Aws\CloudSearch\CloudSearchClient'
        ),

        'cloudsearch_20110201' => array(
            'extends' => 'cloudsearch',
            'params' => array(
                'version' => '2011-02-01'
            )
        ),

        'cloudsearchdomain' => array(
            'alias'   => 'CloudSearchDomain',
            'extends' => 'default_settings',
            'class'   => 'Aws\CloudSearchDomain\CloudSearchDomainClient'
        ),

        'cloudtrail' => array(
            'alias'   => 'CloudTrail',
            'extends' => 'default_settings',
            'class'   => 'Aws\CloudTrail\CloudTrailClient'
        ),

        'cloudwatch' => array(
            'alias'   => 'CloudWatch',
            'extends' => 'default_settings',
            'class'   => 'Aws\CloudWatch\CloudWatchClient'
        ),

        'cloudwatchlogs' => array(
            'alias'   => 'CloudWatchLogs',
            'extends' => 'default_settings',
            'class'   => 'Aws\CloudWatchLogs\CloudWatchLogsClient'
        ),

        'cognito-identity' => array(
            'alias'   => 'CognitoIdentity',
            'extends' => 'default_settings',
            'class'   => 'Aws\CognitoIdentity\CognitoIdentityClient'
        ),

        'cognitoidentity' => array('extends' => 'cognito-identity'),

        'cognito-sync' => array(
            'alias'   => 'CognitoSync',
            'extends' => 'default_settings',
            'class'   => 'Aws\CognitoSync\CognitoSyncClient'
        ),

        'cognitosync' => array('extends' => 'cognito-sync'),

        'codecommit' => array(
            'alias'   => 'CodeCommit',
            'extends' => 'default_settings',
            'class'   => 'Aws\CodeCommit\CodeCommitClient'
        ),

        'codedeploy' => array(
            'alias'   => 'CodeDeploy',
            'extends' => 'default_settings',
            'class'   => 'Aws\CodeDeploy\CodeDeployClient'
        ),

        'codepipeline' => array(
            'alias'   => 'CodePipeline',
            'extends' => 'default_settings',
            'class'   => 'Aws\CodePipeline\CodePipelineClient'
        ),

        'config' => array(
            'alias'   => 'ConfigService',
            'extends' => 'default_settings',
            'class'   => 'Aws\ConfigService\ConfigServiceClient'
        ),

        'datapipeline' => array(
            'alias'   => 'DataPipeline',
            'extends' => 'default_settings',
            'class'   => 'Aws\DataPipeline\DataPipelineClient'
        ),

        'devicefarm' => array(
            'alias'   => 'DeviceFarm',
            'extends' => 'default_settings',
            'class'   => 'Aws\DeviceFarm\DeviceFarmClient'
        ),

        'directconnect' => array(
            'alias'   => 'DirectConnect',
            'extends' => 'default_settings',
            'class'   => 'Aws\DirectConnect\DirectConnectClient'
        ),

        'ds' => array(
            'alias'   => 'DirectoryService',
            'extends' => 'default_settings',
            'class'   => 'Aws\DirectoryService\DirectoryServiceClient'
        ),

        'dynamodb' => array(
            'alias'   => 'DynamoDb',
            'extends' => 'default_settings',
            'class'   => 'Aws\DynamoDb\DynamoDbClient'
        ),

        'dynamodb_20111205' => array(
            'extends' => 'dynamodb',
            'params' => array(
                'version' => '2011-12-05'
            )
        ),

        'dynamodbstreams' => array(
            'alias'   => 'DynamoDbStreams',
            'extends' => 'default_settings',
            'class'   => 'Aws\DynamoDbStreams\DynamoDbStreamsClient'
        ),

        'ec2' => array(
            'alias'   => 'Ec2',
            'extends' => 'default_settings',
            'class'   => 'Aws\Ec2\Ec2Client'
        ),

        'ecs' => array(
            'alias'   => 'Ecs',
            'extends' => 'default_settings',
            'class'   => 'Aws\Ecs\EcsClient'
        ),

        'elasticache' => array(
            'alias'   => 'ElastiCache',
            'extends' => 'default_settings',
            'class'   => 'Aws\ElastiCache\ElastiCacheClient'
        ),

        'elasticbeanstalk' => array(
            'alias'   => 'ElasticBeanstalk',
            'extends' => 'default_settings',
            'class'   => 'Aws\ElasticBeanstalk\ElasticBeanstalkClient'
        ),

        'efs' => array(
            'alias'   => 'Efs',
            'extends' => 'default_settings',
            'class'   => 'Aws\Efs\EfsClient'
        ),

        'elasticloadbalancing' => array(
            'alias'   => 'ElasticLoadBalancing',
            'extends' => 'default_settings',
            'class'   => 'Aws\ElasticLoadBalancing\ElasticLoadBalancingClient'
        ),

        'elastictranscoder' => array(
            'alias'   => 'ElasticTranscoder',
            'extends' => 'default_settings',
            'class'   => 'Aws\ElasticTranscoder\ElasticTranscoderClient'
        ),

        'emr' => array(
            'alias'   => 'Emr',
            'extends' => 'default_settings',
            'class'   => 'Aws\Emr\EmrClient'
        ),

        'glacier' => array(
            'alias'   => 'Glacier',
            'extends' => 'default_settings',
            'class'   => 'Aws\Glacier\GlacierClient'
        ),

        'kinesis' => array(
            'alias'   => 'Kinesis',
            'extends' => 'default_settings',
            'class'   => 'Aws\Kinesis\KinesisClient'
        ),

        'kms' => array(
            'alias'   => 'Kms',
            'extends' => 'default_settings',
            'class'   => 'Aws\Kms\KmsClient'
        ),

        'lambda' => array(
            'alias'   => 'Lambda',
            'extends' => 'default_settings',
            'class'   => 'Aws\Lambda\LambdaClient'
        ),

        'iam' => array(
            'alias'   => 'Iam',
            'extends' => 'default_settings',
            'class'   => 'Aws\Iam\IamClient'
        ),

        'importexport' => array(
            'alias'   => 'ImportExport',
            'extends' => 'default_settings',
            'class'   => 'Aws\ImportExport\ImportExportClient'
        ),

        'machinelearning' => array(
            'alias'   => 'MachineLearning',
            'extends' => 'default_settings',
            'class'   => 'Aws\MachineLearning\MachineLearningClient'
        ),

        'opsworks' => array(
            'alias'   => 'OpsWorks',
            'extends' => 'default_settings',
            'class'   => 'Aws\OpsWorks\OpsWorksClient'
        ),

        'rds' => array(
            'alias'   => 'Rds',
            'extends' => 'default_settings',
            'class'   => 'Aws\Rds\RdsClient'
        ),

        'redshift' => array(
            'alias'   => 'Redshift',
            'extends' => 'default_settings',
            'class'   => 'Aws\Redshift\RedshiftClient'
        ),

        'route53' => array(
            'alias'   => 'Route53',
            'extends' => 'default_settings',
            'class'   => 'Aws\Route53\Route53Client'
        ),

        'route53domains' => array(
            'alias'   => 'Route53Domains',
            'extends' => 'default_settings',
            'class'   => 'Aws\Route53Domains\Route53DomainsClient'
        ),

        's3' => array(
            'alias'   => 'S3',
            'extends' => 'default_settings',
            'class'   => 'Aws\S3\S3Client'
        ),

        'sdb' => array(
            'alias'   => 'SimpleDb',
            'extends' => 'default_settings',
            'class'   => 'Aws\SimpleDb\SimpleDbClient'
        ),

        'ses' => array(
            'alias'   => 'Ses',
            'extends' => 'default_settings',
            'class'   => 'Aws\Ses\SesClient'
        ),

        'sns' => array(
            'alias'   => 'Sns',
            'extends' => 'default_settings',
            'class'   => 'Aws\Sns\SnsClient'
        ),

        'sqs' => array(
            'alias'   => 'Sqs',
            'extends' => 'default_settings',
            'class'   => 'Aws\Sqs\SqsClient'
        ),

        'ssm' => array(
            'alias'   => 'Ssm',
            'extends' => 'default_settings',
            'class'   => 'Aws\Ssm\SsmClient'
        ),

        'storagegateway' => array(
            'alias'   => 'StorageGateway',
            'extends' => 'default_settings',
            'class'   => 'Aws\StorageGateway\StorageGatewayClient'
        ),

        'sts' => array(
            'alias'   => 'Sts',
            'extends' => 'default_settings',
            'class'   => 'Aws\Sts\StsClient'
        ),

        'support' => array(
            'alias'   => 'Support',
            'extends' => 'default_settings',
            'class'   => 'Aws\Support\SupportClient'
        ),

        'swf' => array(
            'alias'   => 'Swf',
            'extends' => 'default_settings',
            'class'   => 'Aws\Swf\SwfClient'
        ),

        'workspaces' => array(
            'alias'   => 'WorkSpaces',
            'extends' => 'default_settings',
            'class'   => 'Aws\WorkSpaces\WorkSpacesClient'
        ),
    )
);
Resources/sdk1-config.php000060400000007050152440555050011337 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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.
 */

return array(
    'includes' => array('_aws'),
    'services' => array(

        'sdk1_settings' => array(
            'extends' => 'default_settings',
            'params'  => array(
                'certificate_authority' => false
            )
        ),

        'v1.autoscaling' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonAS'
        ),

        'v1.cloudformation' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonCloudFormation'
        ),

        'v1.cloudfront' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonCloudFront'
        ),

        'v1.cloudsearch' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonCloudSearch'
        ),

        'v1.cloudwatch' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonCloudWatch'
        ),

        'v1.dynamodb' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonDynamoDB'
        ),

        'v1.ec2' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonEC2'
        ),

        'v1.elasticache' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonElastiCache'
        ),

        'v1.elasticbeanstalk' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonElasticBeanstalk'
        ),

        'v1.elb' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonELB'
        ),

        'v1.emr' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonEMR'
        ),

        'v1.iam' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonIAM'
        ),

        'v1.importexport'     => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonImportExport'
        ),

        'v1.rds' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonRDS'
        ),

        'v1.s3'  => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonS3'
        ),

        'v1.sdb' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonSDB'
        ),

        'v1.ses' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonSES'
        ),

        'v1.sns' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonSNS'
        ),

        'v1.sqs' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonSQS'
        ),

        'v1.storagegateway'   => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonStorageGateway'
        ),

        'v1.sts' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonSTS'
        ),

        'v1.swf' => array(
            'extends' => 'sdk1_settings',
            'class'   => 'AmazonSWF'
        )
    )
);
Resources/.htaccess000044400000000424152440555050010317 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Resources/public-endpoints.php000060400000004612152440555050012512 0ustar00<?php
return array(
    'version' => 2,
    'endpoints' => array(
        '*/*' => array(
            'endpoint' => '{service}.{region}.amazonaws.com'
        ),
        'cn-north-1/*' => array(
            'endpoint' => '{service}.{region}.amazonaws.com.cn',
            'signatureVersion' => 'v4'
        ),
        'us-gov-west-1/iam' => array(
            'endpoint' => 'iam.us-gov.amazonaws.com'
        ),
        'us-gov-west-1/sts' => array(
            'endpoint' => 'sts.us-gov-west-1.amazonaws.com'
        ),
        'us-gov-west-1/s3' => array(
            'endpoint' => 's3-{region}.amazonaws.com'
        ),
        '*/cloudfront' => array(
            'endpoint' => 'cloudfront.amazonaws.com',
            'credentialScope' => array(
                'region' => 'us-east-1'
            )
        ),
        '*/iam' => array(
            'endpoint' => 'iam.amazonaws.com',
            'credentialScope' => array(
                'region' => 'us-east-1'
            )
        ),
        '*/importexport' => array(
            'endpoint' => 'importexport.amazonaws.com',
            'credentialScope' => array(
                'region' => 'us-east-1'
            )
        ),
        '*/route53' => array(
            'endpoint' => 'route53.amazonaws.com',
            'credentialScope' => array(
                'region' => 'us-east-1'
            )
        ),
        '*/sts' => array(
            'endpoint' => 'sts.amazonaws.com',
            'credentialScope' => array(
                'region' => 'us-east-1'
            )
        ),
        'us-east-1/sdb' => array(
            'endpoint' => 'sdb.amazonaws.com'
        ),
        'us-east-1/s3' => array(
            'endpoint' => 's3.amazonaws.com'
        ),
        'us-west-1/s3' => array(
            'endpoint' => 's3-{region}.amazonaws.com'
        ),
        'us-west-2/s3' => array(
            'endpoint' => 's3-{region}.amazonaws.com'
        ),
        'eu-west-1/s3' => array(
            'endpoint' => 's3-{region}.amazonaws.com'
        ),
        'ap-southeast-1/s3' => array(
            'endpoint' => 's3-{region}.amazonaws.com'
        ),
        'ap-southeast-2/s3' => array(
            'endpoint' => 's3-{region}.amazonaws.com'
        ),
        'ap-northeast-1/s3' => array(
            'endpoint' => 's3-{region}.amazonaws.com'
        ),
        'sa-east-1/s3' => array(
            'endpoint' => 's3-{region}.amazonaws.com'
        )
    )
);
Model/MultipartUpload/AbstractUploadBuilder.php000060400000010325152440555050015664 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Http\EntityBody;

/**
 * Easily create a multipart uploader used to quickly and reliably upload a
 * large file or data stream to Amazon S3 using multipart uploads
 */
abstract class AbstractUploadBuilder
{
    /**
     * @var AwsClientInterface Client used to transfer requests
     */
    protected $client;

    /**
     * @var TransferStateInterface State of the transfer
     */
    protected $state;

    /**
     * @var EntityBody Source of the data
     */
    protected $source;

    /**
     * @var array Array of headers to set on the object
     */
    protected $headers = array();

    /**
     * Return a new instance of the UploadBuilder
     *
     * @return static
     */
    public static function newInstance()
    {
        return new static;
    }

    /**
     * Set the client used to connect to the AWS service
     *
     * @param AwsClientInterface $client Client to use
     *
     * @return $this
     */
    public function setClient(AwsClientInterface $client)
    {
        $this->client = $client;

        return $this;
    }

    /**
     * Set the state of the upload. This is useful for resuming from a previously started multipart upload.
     * You must use a local file stream as the data source if you wish to resume from a previous upload.
     *
     * @param TransferStateInterface|string $state Pass a TransferStateInterface object or the ID of the initiated
     *                                             multipart upload. When an ID is passed, the builder will create a
     *                                             state object using the data from a ListParts API response.
     *
     * @return $this
     */
    public function resumeFrom($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * Set the data source of the transfer
     *
     * @param resource|string|EntityBody $source Source of the transfer. Pass a string to transfer from a file on disk.
     *                                           You can also stream from a resource returned from fopen or a Guzzle
     *                                           {@see EntityBody} object.
     *
     * @return $this
     * @throws InvalidArgumentException when the source cannot be found or opened
     */
    public function setSource($source)
    {
        // Use the contents of a file as the data source
        if (is_string($source)) {
            if (!file_exists($source)) {
                throw new InvalidArgumentException("File does not exist: {$source}");
            }
            // Clear the cache so that we send accurate file sizes
            clearstatcache(true, $source);
            $source = fopen($source, 'r');
        }

        $this->source = EntityBody::factory($source);

        if ($this->source->isSeekable() && $this->source->getSize() == 0) {
            throw new InvalidArgumentException('Empty body provided to upload builder');
        }

        return $this;
    }

    /**
     * Specify the headers to set on the upload
     *
     * @param array $headers Headers to add to the uploaded object
     *
     * @return $this
     */
    public function setHeaders(array $headers)
    {
        $this->headers = $headers;

        return $this;
    }

    /**
     * Build the appropriate uploader based on the builder options
     *
     * @return TransferInterface
     */
    abstract public function build();

    /**
     * Initiate the multipart upload
     *
     * @return TransferStateInterface
     */
    abstract protected function initiateMultipartUpload();
}
Model/MultipartUpload/AbstractUploadPart.php000060400000004741152440555050015211 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

use Aws\Common\Exception\InvalidArgumentException;

/**
 * An object that encapsulates the data for an upload part
 */
abstract class AbstractUploadPart implements UploadPartInterface
{
    /**
     * @var array A map of external array keys to internal property names
     */
    protected static $keyMap = array();

    /**
     * @var int The number of the upload part representing its order in the overall upload
     */
    protected $partNumber;

    /**
     * {@inheritdoc}
     */
    public static function fromArray($data)
    {
        $part = new static();
        $part->loadData($data);

        return $part;
    }

    /**
     * {@inheritdoc}
     */
    public function getPartNumber()
    {
        return $this->partNumber;
    }

    /**
     * {@inheritdoc}
     */
    public function toArray()
    {
        $array = array();
        foreach (static::$keyMap as $key => $property) {
            $array[$key] = $this->{$property};
        }

        return $array;
    }

    /**
     * {@inheritdoc}
     */
    public function serialize()
    {
        return serialize($this->toArray());
    }

    /**
     * {@inheritdoc}
     */
    public function unserialize($serialized)
    {
        $this->loadData(unserialize($serialized));
    }

    /**
     * Loads an array of data into the upload part by extracting only the needed keys
     *
     * @param array|\Traversable $data Data to load into the upload part value object
     *
     * @throws InvalidArgumentException if a required key is missing
     */
    protected function loadData($data)
    {
        foreach (static::$keyMap as $key => $property) {
            if (isset($data[$key])) {
                $this->{$property} = $data[$key];
            } else {
                throw new InvalidArgumentException("A required key [$key] was missing from the upload part.");
            }
        }
    }
}
Model/MultipartUpload/AbstractTransfer.php000060400000015475152440555050014730 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\MultipartUploadException;
use Aws\Common\Exception\RuntimeException;
use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Http\EntityBody;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Service\Command\OperationCommand;
use Guzzle\Service\Resource\Model;

/**
 * Abstract class for transfer commonalities
 */
abstract class AbstractTransfer extends AbstractHasDispatcher implements TransferInterface
{
    const BEFORE_UPLOAD      = 'multipart_upload.before_upload';
    const AFTER_UPLOAD       = 'multipart_upload.after_upload';
    const BEFORE_PART_UPLOAD = 'multipart_upload.before_part_upload';
    const AFTER_PART_UPLOAD  = 'multipart_upload.after_part_upload';
    const AFTER_ABORT        = 'multipart_upload.after_abort';
    const AFTER_COMPLETE     = 'multipart_upload.after_complete';

    /**
     * @var AwsClientInterface Client used for the transfers
     */
    protected $client;

    /**
     * @var TransferStateInterface State of the transfer
     */
    protected $state;

    /**
     * @var EntityBody Data source of the transfer
     */
    protected $source;

    /**
     * @var array Associative array of options
     */
    protected $options;

    /**
     * @var int Size of each part to upload
     */
    protected $partSize;

    /**
     * @var bool Whether or not the transfer has been stopped
     */
    protected $stopped = false;

    /**
     * Construct a new transfer object
     *
     * @param AwsClientInterface     $client  Client used for the transfers
     * @param TransferStateInterface $state   State used to track transfer
     * @param EntityBody             $source  Data source of the transfer
     * @param array                  $options Array of options to apply
     */
    public function __construct(
        AwsClientInterface $client,
        TransferStateInterface $state,
        EntityBody $source,
        array $options = array()
    ) {
        $this->client  = $client;
        $this->state   = $state;
        $this->source  = $source;
        $this->options = $options;

        $this->init();

        $this->partSize = $this->calculatePartSize();
    }

    public function __invoke()
    {
        return $this->upload();
    }

    /**
     * {@inheritdoc}
     */
    public static function getAllEvents()
    {
        return array(
            self::BEFORE_PART_UPLOAD,
            self::AFTER_UPLOAD,
            self::BEFORE_PART_UPLOAD,
            self::AFTER_PART_UPLOAD,
            self::AFTER_ABORT,
            self::AFTER_COMPLETE
        );
    }

    /**
     * {@inheritdoc}
     */
    public function abort()
    {
        $command = $this->getAbortCommand();
        $result = $command->getResult();

        $this->state->setAborted(true);
        $this->stop();
        $this->dispatch(self::AFTER_ABORT, $this->getEventData($command));

        return $result;
    }

    /**
     * {@inheritdoc}
     */
    public function stop()
    {
        $this->stopped = true;

        return $this->state;
    }

    /**
     * {@inheritdoc}
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * Get the array of options associated with the transfer
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Set an option on the transfer
     *
     * @param string $option Name of the option
     * @param mixed  $value  Value to set
     *
     * @return self
     */
    public function setOption($option, $value)
    {
        $this->options[$option] = $value;

        return $this;
    }

    /**
     * Get the source body of the upload
     *
     * @return EntityBodyInterface
     */
    public function getSource()
    {
        return $this->source;
    }

    /**
     * {@inheritdoc}
     * @throws MultipartUploadException when an error is encountered. Use getLastException() to get more information.
     * @throws RuntimeException         when attempting to upload an aborted transfer
     */
    public function upload()
    {
        if ($this->state->isAborted()) {
            throw new RuntimeException('The transfer has been aborted and cannot be uploaded');
        }

        $this->stopped = false;
        $eventData = $this->getEventData();
        $this->dispatch(self::BEFORE_UPLOAD, $eventData);

        try {
            $this->transfer();
            $this->dispatch(self::AFTER_UPLOAD, $eventData);

            if ($this->stopped) {
                return null;
            } else {
                $result = $this->complete();
                $this->dispatch(self::AFTER_COMPLETE, $eventData);
            }
        } catch (\Exception $e) {
            throw new MultipartUploadException($this->state, $e);
        }

        return $result;
    }

    /**
     * Get an array used for event notifications
     *
     * @param OperationCommand $command Command to include in event data
     *
     * @return array
     */
    protected function getEventData(OperationCommand $command = null)
    {
        $data = array(
            'transfer'  => $this,
            'source'    => $this->source,
            'options'   => $this->options,
            'client'    => $this->client,
            'part_size' => $this->partSize,
            'state'     => $this->state
        );

        if ($command) {
            $data['command'] = $command;
        }

        return $data;
    }

    /**
     * Hook to initialize the transfer
     */
    protected function init() {}

    /**
     * Determine the upload part size based on the size of the source data and
     * taking into account the acceptable minimum and maximum part sizes.
     *
     * @return int The part size
     */
    abstract protected function calculatePartSize();

    /**
     * Complete the multipart upload
     *
     * @return Model Returns the result of the complete multipart upload command
     */
    abstract protected function complete();

    /**
     * Hook to implement in subclasses to perform the actual transfer
     */
    abstract protected function transfer();

    /**
     * Fetches the abort command fom the concrete implementation
     *
     * @return OperationCommand
     */
    abstract protected function getAbortCommand();
}
Model/MultipartUpload/UploadPartInterface.php000060400000002351152440555050015341 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

/**
 * An object that encapsulates the data for an upload part
 */
interface UploadPartInterface extends \Serializable
{
    /**
     * Create an upload part from an array
     *
     * @param array|\Traversable $data Data representing the upload part
     *
     * @return self
     */
    public static function fromArray($data);

    /**
     * Returns the part number of the upload part which is used as an identifier
     *
     * @return int
     */
    public function getPartNumber();

    /**
     * Returns the array form of the upload part
     *
     * @return array
     */
    public function toArray();
}
Model/MultipartUpload/TransferStateInterface.php000060400000004607152440555050016061 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

use Aws\Common\Client\AwsClientInterface;

/**
 * State of a multipart upload
 */
interface TransferStateInterface extends \Countable, \IteratorAggregate, \Serializable
{
    /**
     * Create the transfer state from the results of list parts request
     *
     * @param AwsClientInterface $client   Client used to send the request
     * @param UploadIdInterface  $uploadId Params needed to identify the upload and form the request
     *
     * @return self
     */
    public static function fromUploadId(AwsClientInterface $client, UploadIdInterface $uploadId);

    /**
     * Get the params used to identify an upload part
     *
     * @return UploadIdInterface
     */
    public function getUploadId();

    /**
     * Get the part information of a specific part
     *
     * @param int $partNumber Part to retrieve
     *
     * @return UploadPartInterface
     */
    public function getPart($partNumber);

    /**
     * Add a part to the transfer state
     *
     * @param UploadPartInterface $part The part to add
     *
     * @return self
     */
    public function addPart(UploadPartInterface $part);

    /**
     * Check if a specific part has been uploaded
     *
     * @param int $partNumber Part to check
     *
     * @return bool
     */
    public function hasPart($partNumber);

    /**
     * Get a list of all of the uploaded part numbers
     *
     * @return array
     */
    public function getPartNumbers();

    /**
     * Set whether or not the transfer has been aborted
     *
     * @param bool $aborted Set to true to mark the transfer as aborted
     *
     * @return self
     */
    public function setAborted($aborted);

    /**
     * Check if the transfer has been marked as aborted
     *
     * @return bool
     */
    public function isAborted();
}
Model/MultipartUpload/.htaccess000044400000000424152440555050012533 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Model/MultipartUpload/AbstractUploadId.php000060400000004356152440555050014641 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

use Aws\Common\Exception\InvalidArgumentException;

/**
 * An object that encapsulates the data identifying an upload
 */
abstract class AbstractUploadId implements UploadIdInterface
{
    /**
     * @var array Expected values (with defaults)
     */
    protected static $expectedValues = array();

    /**
     * @var array Params representing the identifying information
     */
    protected $data = array();

    /**
     * {@inheritdoc}
     */
    public static function fromParams($data)
    {
        $uploadId = new static();
        $uploadId->loadData($data);

        return $uploadId;
    }

    /**
     * {@inheritdoc}
     */
    public function toParams()
    {
        return $this->data;
    }

    /**
     * {@inheritdoc}
     */
    public function serialize()
    {
        return serialize($this->data);
    }

    /**
     * {@inheritdoc}
     */
    public function unserialize($serialized)
    {
        $this->loadData(unserialize($serialized));
    }

    /**
     * Loads an array of data into the UploadId by extracting only the needed keys
     *
     * @param array $data Data to load
     *
     * @throws InvalidArgumentException if a required key is missing
     */
    protected function loadData($data)
    {
        $data = array_replace(static::$expectedValues, array_intersect_key($data, static::$expectedValues));
        foreach ($data as $key => $value) {
            if (isset($data[$key])) {
                $this->data[$key] = $data[$key];
            } else {
                throw new InvalidArgumentException("A required key [$key] was missing from the UploadId.");
            }
        }
    }
}
Model/MultipartUpload/TransferInterface.php000060400000003517152440555050015057 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Service\Resource\Model;

/**
 * Interface for transferring the contents of a data source to an AWS service via a multipart upload interface
 */
interface TransferInterface extends HasDispatcherInterface
{
    /**
     * Upload the source to using a multipart upload
     *
     * @return Model|null Result of the complete multipart upload command or null if uploading was stopped
     */
    public function upload();

    /**
     * Abort the upload
     *
     * @return Model Returns the result of the abort multipart upload command
     */
    public function abort();

    /**
     * Get the current state of the upload
     *
     * @return TransferStateInterface
     */
    public function getState();

    /**
     * Stop the transfer and retrieve the current state.
     *
     * This allows you to stop and later resume a long running transfer if needed.
     *
     * @return TransferStateInterface
     */
    public function stop();

    /**
     * Set an option on the transfer object
     *
     * @param string $option Option to set
     * @param mixed  $value  The value to set
     *
     * @return self
     */
    public function setOption($option, $value);
}
Model/MultipartUpload/AbstractTransferState.php000060400000007065152440555050015725 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

use Aws\Common\Exception\RuntimeException;

/**
 * State of a multipart upload
 */
abstract class AbstractTransferState implements TransferStateInterface
{
    /**
     * @var UploadIdInterface Object holding params used to identity the upload part
     */
    protected $uploadId;

    /**
     * @var array Array of parts where the part number is the index
     */
    protected $parts = array();

    /**
     * @var bool Whether or not the transfer was aborted
     */
    protected $aborted = false;

    /**
     * Construct a new transfer state object
     *
     * @param UploadIdInterface $uploadId Upload identifier object
     */
    public function __construct(UploadIdInterface $uploadId)
    {
        $this->uploadId = $uploadId;
    }

    /**
     * {@inheritdoc}
     */
    public function getUploadId()
    {
        return $this->uploadId;
    }

    /**
     * Get a data value from the transfer state's uploadId
     *
     * @param string $key Key to retrieve (e.g. Bucket, Key, UploadId, etc)
     *
     * @return string|null
     */
    public function getFromId($key)
    {
        $params = $this->uploadId->toParams();

        return isset($params[$key]) ? $params[$key] : null;
    }

    /**
     * {@inheritdoc}
     */
    public function getPart($partNumber)
    {
        return isset($this->parts[$partNumber]) ? $this->parts[$partNumber] : null;
    }

    /**
     * {@inheritdoc}
     */
    public function addPart(UploadPartInterface $part)
    {
        $partNumber = $part->getPartNumber();
        $this->parts[$partNumber] = $part;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function hasPart($partNumber)
    {
        return isset($this->parts[$partNumber]);
    }

    /**
     * {@inheritdoc}
     */
    public function getPartNumbers()
    {
        return array_keys($this->parts);
    }

    /**
     * {@inheritdoc}
     */
    public function setAborted($aborted)
    {
        $this->aborted = (bool) $aborted;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function isAborted()
    {
        return $this->aborted;
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return count($this->parts);
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->parts);
    }

    /**
     * {@inheritdoc}
     */
    public function serialize()
    {
        return serialize(get_object_vars($this));
    }

    /**
     * {@inheritdoc}
     */
    public function unserialize($serialized)
    {
        $data = unserialize($serialized);
        foreach (get_object_vars($this) as $property => $oldValue) {
            if (array_key_exists($property, $data)) {
                $this->{$property} = $data[$property];
            } else {
                throw new RuntimeException("The {$property} property could be restored during unserialization.");
            }
        }
    }
}
Model/MultipartUpload/UploadIdInterface.php000060400000002151152440555050014765 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Model\MultipartUpload;

/**
 * An object that encapsulates the data identifying an upload
 */
interface UploadIdInterface extends \Serializable
{
    /**
     * Create an UploadId from an array
     *
     * @param array $data Data representing the upload identification
     *
     * @return self
     */
    public static function fromParams($data);

    /**
     * Returns the array form of the upload identification for use as command params
     *
     * @return array
     */
    public function toParams();
}
Model/.htaccess000044400000000424152440555050007405 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Command/.htaccess000044400000000424152440555050007723 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Command/QueryCommand.php000060400000002703152440555050011242 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Command;

use Guzzle\Service\Command\OperationCommand;

/**
 * Adds AWS Query service serialization
 */
class QueryCommand extends OperationCommand
{
    /**
     * @var AwsQueryVisitor
     */
    protected static $queryVisitor;

    /**
     * @var XmlResponseLocationVisitor
     */
    protected static $xmlVisitor;

    /**
     * Register the aws.query visitor
     */
    protected function init()
    {
        // @codeCoverageIgnoreStart
        if (!self::$queryVisitor) {
            self::$queryVisitor = new AwsQueryVisitor();
        }
        if (!self::$xmlVisitor) {
            self::$xmlVisitor = new XmlResponseLocationVisitor();
        }
        // @codeCoverageIgnoreEnd

        $this->getRequestSerializer()->addVisitor('aws.query', self::$queryVisitor);
        $this->getResponseParser()->addVisitor('xml', self::$xmlVisitor);
    }
}
Command/AwsQueryVisitor.php000060400000011104152440555050011771 0ustar00<?php

namespace Aws\Common\Command;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Command\LocationVisitor\Request\AbstractRequestVisitor;

/**
 * Location visitor used to serialize AWS query parameters (e.g. EC2, SES, SNS, SQS, etc) as POST fields
 */
class AwsQueryVisitor extends AbstractRequestVisitor
{
    private $fqname;

    public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
    {
        $this->fqname = $command->getName();
        $query = array();
        $this->customResolver($value, $param, $query, $param->getWireName());
        $request->addPostFields($query);
    }

    /**
     * Map nested parameters into the location_key based parameters
     *
     * @param array     $value  Value to map
     * @param Parameter $param  Parameter that holds information about the current key
     * @param array     $query  Built up query string values
     * @param string    $prefix String to prepend to sub query values
     */
    protected function customResolver($value, Parameter $param, array &$query, $prefix = '')
    {
        switch ($param->getType()) {
            case 'object':
                $this->resolveObject($param, $value, $prefix, $query);
                break;
            case 'array':
                $this->resolveArray($param, $value, $prefix, $query);
                break;
            default:
                $query[$prefix] = $param->filter($value);
        }
    }

    /**
     * Custom handling for objects
     *
     * @param Parameter $param  Parameter for the object
     * @param array     $value  Value that is set for this parameter
     * @param string    $prefix Prefix for the resulting key
     * @param array     $query  Query string array passed by reference
     */
    protected function resolveObject(Parameter $param, array $value, $prefix, array &$query)
    {
        // Maps are implemented using additional properties
        $hasAdditionalProperties = ($param->getAdditionalProperties() instanceof Parameter);
        $additionalPropertyCount = 0;

        foreach ($value as $name => $v) {
            if ($subParam = $param->getProperty($name)) {
                // if the parameter was found by name as a regular property
                $key = $prefix . '.' . $subParam->getWireName();
                $this->customResolver($v, $subParam, $query, $key);
            } elseif ($hasAdditionalProperties) {
                // Handle map cases like &Attribute.1.Name=<name>&Attribute.1.Value=<value>
                $additionalPropertyCount++;
                $data = $param->getData();
                $keyName = isset($data['keyName']) ? $data['keyName'] : 'key';
                $valueName = isset($data['valueName']) ? $data['valueName'] : 'value';
                $query["{$prefix}.{$additionalPropertyCount}.{$keyName}"] = $name;
                $newPrefix = "{$prefix}.{$additionalPropertyCount}.{$valueName}";
                if (is_array($v)) {
                    $this->customResolver($v, $param->getAdditionalProperties(), $query, $newPrefix);
                } else {
                    $query[$newPrefix] = $param->filter($v);
                }
            }
        }
    }

    /**
     * Custom handling for arrays
     *
     * @param Parameter $param  Parameter for the object
     * @param array     $value  Value that is set for this parameter
     * @param string    $prefix Prefix for the resulting key
     * @param array     $query  Query string array passed by reference
     */
    protected function resolveArray(Parameter $param, array $value, $prefix, array &$query)
    {
        static $serializeEmpty = array(
            'SetLoadBalancerPoliciesForBackendServer' => 1,
            'SetLoadBalancerPoliciesOfListener' => 1,
            'UpdateStack' => 1
        );

        // For BC, serialize empty lists for specific operations
        if (!$value) {
            if (isset($serializeEmpty[$this->fqname])) {
                if (substr($prefix, -7) === '.member') {
                    $prefix = substr($prefix, 0, -7);
                }
                $query[$prefix] = '';
            }
            return;
        }

        $offset = $param->getData('offset') ?: 1;
        foreach ($value as $index => $v) {
            $index += $offset;
            if (is_array($v) && $items = $param->getItems()) {
                $this->customResolver($v, $items, $query, $prefix . '.' . $index);
            } else {
                $query[$prefix . '.' . $index] = $param->filter($v);
            }
        }
    }
}
Command/XmlResponseLocationVisitor.php000060400000004143152440555050014166 0ustar00<?php

namespace Aws\Common\Command;

use Guzzle\Service\Description\Operation;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\LocationVisitor\Response\XmlVisitor;

/**
 * Class used for custom AWS XML response parsing of query services
 */
class XmlResponseLocationVisitor extends XmlVisitor
{
    /**
     * {@inheritdoc}
     */
    public function before(CommandInterface $command, array &$result)
    {
        parent::before($command, $result);

        // Unwrapped wrapped responses
        $operation = $command->getOperation();
        if ($operation->getServiceDescription()->getData('resultWrapped')) {
            $wrappingNode = $operation->getName() . 'Result';
            if (isset($result[$wrappingNode])) {
                $result = $result[$wrappingNode] + $result;
                unset($result[$wrappingNode]);
            }
        }
    }

    /**
     * Accounts for wrapper nodes
     * {@inheritdoc}
     */
    public function visit(
        CommandInterface $command,
        Response $response,
        Parameter $param,
        &$value,
        $context =  null
    ) {
        parent::visit($command, $response, $param, $value, $context);

        // Account for wrapper nodes (e.g. RDS, ElastiCache, etc)
        if ($param->getData('wrapper')) {
            $wireName = $param->getWireName();
            $value += $value[$wireName];
            unset($value[$wireName]);
        }
    }

    /**
     * Filter used when converting XML maps into associative arrays in service descriptions
     *
     * @param array  $value     Value to filter
     * @param string $entryName Name of each entry
     * @param string $keyName   Name of each key
     * @param string $valueName Name of each value
     *
     * @return array Returns the map of the XML data
     */
    public static function xmlMap($value, $entryName, $keyName, $valueName)
    {
        $result = array();
        foreach ($value as $entry) {
            $result[$entry[$keyName]] = $entry[$valueName];
        }

        return $result;
    }
}
Command/JsonCommand.php000060400000003125152440555050011045 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Command;

use Guzzle\Service\Command\OperationCommand;
use Guzzle\Http\Curl\CurlHandle;

/**
 * Adds AWS JSON body functionality to dynamically generated HTTP requests
 */
class JsonCommand extends OperationCommand
{
    /**
     * {@inheritdoc}
     */
    protected function build()
    {
        parent::build();

        // Ensure that the body of the request ALWAYS includes some JSON. By default, this is an empty object.
        if (!$this->request->getBody()) {
            $this->request->setBody('{}');
        }

        // Never send the Expect header when interacting with a JSON query service
        $this->request->removeHeader('Expect');

        // Always send JSON requests as a raw string rather than using streams to avoid issues with
        // cURL error code 65: "necessary data rewind wasn't possible".
        // This could be removed after PHP addresses https://bugs.php.net/bug.php?id=47204
        $this->request->getCurlOptions()->set(CurlHandle::BODY_AS_STRING, true);
    }
}
Signature/.htaccess000044400000000424152440555050010306 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Signature/AbstractSignature.php000060400000002352152440555050012646 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Signature;

use Aws\Common\Credentials\CredentialsInterface;
use Guzzle\Http\Message\RequestInterface;

abstract class AbstractSignature implements SignatureInterface
{
    /**
     * Provides the timestamp used for the class (used for mocking PHP's time() function)
     *
     * @return int
     */
    protected function getTimestamp()
    {
        return time();
    }

    /**
     * @codeCoverageIgnore
     */
    public function createPresignedUrl(
        RequestInterface $request,
        CredentialsInterface $credentials,
        $expires
    ) {
        throw new \BadMethodCallException(__METHOD__ . ' not implemented');
    }
}
Signature/EndpointSignatureInterface.php000060400000002360152440555050014503 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Signature;

/**
 * Interface for signatures that use specific region and service names when
 * signing requests.
 */
interface EndpointSignatureInterface extends SignatureInterface
{
    /**
     * Set the service name instead of inferring it from a request URL
     *
     * @param string $service Name of the service used when signing
     *
     * @return self
     */
    public function setServiceName($service);

    /**
     * Set the region name instead of inferring it from a request URL
     *
     * @param string $region Name of the region used when signing
     *
     * @return self
     */
    public function setRegionName($region);
}
Signature/SignatureV4.php000060400000037534152440555050011406 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Signature;

use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Enum\DateFormat;
use Aws\Common\HostNameUtils;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\QueryString;
use Guzzle\Http\Url;
use Guzzle\Stream\Stream;

/**
 * Signature Version 4
 * @link http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
 */
class SignatureV4 extends AbstractSignature implements EndpointSignatureInterface
{
    /** @var string Cache of the default empty entity-body payload */
    const DEFAULT_PAYLOAD = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';

    /** @var string Explicitly set service name */
    protected $serviceName;

    /** @var string Explicitly set region name */
    protected $regionName;

    /** @var int Maximum number of hashes to cache */
    protected $maxCacheSize = 50;

    /** @var array Cache of previously signed values */
    protected $hashCache = array();

    /** @var int Size of the hash cache */
    protected $cacheSize = 0;

    /**
     * @param string $serviceName Bind the signing to a particular service name
     * @param string $regionName  Bind the signing to a particular region name
     */
    public function __construct($serviceName = null, $regionName = null)
    {
        $this->serviceName = $serviceName;
        $this->regionName = $regionName;
    }

    /**
     * Set the service name instead of inferring it from a request URL
     *
     * @param string $service Name of the service used when signing
     *
     * @return self
     */
    public function setServiceName($service)
    {
        $this->serviceName = $service;

        return $this;
    }

    /**
     * Set the region name instead of inferring it from a request URL
     *
     * @param string $region Name of the region used when signing
     *
     * @return self
     */
    public function setRegionName($region)
    {
        $this->regionName = $region;

        return $this;
    }

    /**
     * Set the maximum number of computed hashes to cache
     *
     * @param int $maxCacheSize Maximum number of hashes to cache
     *
     * @return self
     */
    public function setMaxCacheSize($maxCacheSize)
    {
        $this->maxCacheSize = $maxCacheSize;

        return $this;
    }

    public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
    {
        $timestamp = $this->getTimestamp();
        $longDate = gmdate(DateFormat::ISO8601, $timestamp);
        $shortDate = substr($longDate, 0, 8);

        // Remove any previously set Authorization headers so that retries work
        $request->removeHeader('Authorization');

        // Requires a x-amz-date header or Date
        if ($request->hasHeader('x-amz-date') || !$request->hasHeader('Date')) {
            $request->setHeader('x-amz-date', $longDate);
        } else {
            $request->setHeader('Date', gmdate(DateFormat::RFC1123, $timestamp));
        }

        // Add the security token if one is present
        if ($credentials->getSecurityToken()) {
            $request->setHeader('x-amz-security-token', $credentials->getSecurityToken());
        }

        // Parse the service and region or use one that is explicitly set
        $region = $this->regionName;
        $service = $this->serviceName;
        if (!$region || !$service) {
            $url = Url::factory($request->getUrl());
            $region = $region ?: HostNameUtils::parseRegionName($url);
            $service = $service ?: HostNameUtils::parseServiceName($url);
        }

        $credentialScope = $this->createScope($shortDate, $region, $service);
        $payload = $this->getPayload($request);
        $signingContext = $this->createSigningContext($request, $payload);
        $signingContext['string_to_sign'] = $this->createStringToSign(
            $longDate,
            $credentialScope,
            $signingContext['canonical_request']
        );

        // Calculate the signing key using a series of derived keys
        $signingKey = $this->getSigningKey($shortDate, $region, $service, $credentials->getSecretKey());
        $signature = hash_hmac('sha256', $signingContext['string_to_sign'], $signingKey);

        $request->setHeader('Authorization', "AWS4-HMAC-SHA256 "
            . "Credential={$credentials->getAccessKeyId()}/{$credentialScope}, "
            . "SignedHeaders={$signingContext['signed_headers']}, Signature={$signature}");

        // Add debug information to the request
        $request->getParams()->set('aws.signature', $signingContext);
    }

    public function createPresignedUrl(
        RequestInterface $request,
        CredentialsInterface $credentials,
        $expires
    ) {
        $request = $this->createPresignedRequest($request, $credentials);
        $query = $request->getQuery();
        $httpDate = gmdate(DateFormat::ISO8601, $this->getTimestamp());
        $shortDate = substr($httpDate, 0, 8);
        $scope = $this->createScope(
            $shortDate,
            $this->regionName,
            $this->serviceName
        );
        $this->addQueryValues($scope, $request, $credentials, $expires);
        $payload = $this->getPresignedPayload($request);
        $context = $this->createSigningContext($request, $payload);
        $stringToSign = $this->createStringToSign(
            $httpDate,
            $scope,
            $context['canonical_request']
        );
        $key = $this->getSigningKey(
            $shortDate,
            $this->regionName,
            $this->serviceName,
            $credentials->getSecretKey()
        );
        $query['X-Amz-Signature'] = hash_hmac('sha256', $stringToSign, $key);

        return $request->getUrl();
    }

    /**
     * Converts a POST request to a GET request by moving POST fields into the
     * query string.
     *
     * Useful for pre-signing query protocol requests.
     *
     * @param EntityEnclosingRequestInterface $request Request to clone
     *
     * @return RequestInterface
     * @throws \InvalidArgumentException if the method is not POST
     */
    public static function convertPostToGet(EntityEnclosingRequestInterface $request)
    {
        if ($request->getMethod() !== 'POST') {
            throw new \InvalidArgumentException('Expected a POST request but '
                . 'received a ' . $request->getMethod() . ' request.');
        }

        $cloned = RequestFactory::getInstance()
            ->cloneRequestWithMethod($request, 'GET');

        // Move POST fields to the query if they are present
        foreach ($request->getPostFields() as $name => $value) {
            $cloned->getQuery()->set($name, $value);
        }

        return $cloned;
    }

    /**
     * Get the payload part of a signature from a request.
     *
     * @param RequestInterface $request
     *
     * @return string
     */
    protected function getPayload(RequestInterface $request)
    {
        // Calculate the request signature payload
        if ($request->hasHeader('x-amz-content-sha256')) {
            // Handle streaming operations (e.g. Glacier.UploadArchive)
            return (string) $request->getHeader('x-amz-content-sha256');
        }

        if ($request instanceof EntityEnclosingRequestInterface) {
            if ($request->getMethod() == 'POST' && count($request->getPostFields())) {
                return hash('sha256', (string) $request->getPostFields());
            } elseif ($body = $request->getBody()) {
                return Stream::getHash($request->getBody(), 'sha256');
            }
        }

        return self::DEFAULT_PAYLOAD;
    }

    /**
     * Get the payload of a request for use with pre-signed URLs.
     *
     * @param RequestInterface $request
     *
     * @return string
     */
    protected function getPresignedPayload(RequestInterface $request)
    {
        return $this->getPayload($request);
    }

    protected function createCanonicalizedPath(RequestInterface $request)
    {
        $doubleEncoded = rawurlencode(ltrim($request->getPath(), '/'));

        return '/' . str_replace('%2F', '/', $doubleEncoded);
    }

    private function createStringToSign($longDate, $credentialScope, $creq)
    {
        return "AWS4-HMAC-SHA256\n{$longDate}\n{$credentialScope}\n"
            . hash('sha256', $creq);
    }

    private function createPresignedRequest(
        RequestInterface $request,
        CredentialsInterface $credentials
    ) {
        // POST requests can be sent as GET requests instead by moving the
        // POST fields into the query string.
        if ($request instanceof EntityEnclosingRequestInterface
            && $request->getMethod() === 'POST'
            && strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === 0
        ) {
            $sr = RequestFactory::getInstance()
                ->cloneRequestWithMethod($request, 'GET');
            // Move POST fields to the query if they are present
            foreach ($request->getPostFields() as $name => $value) {
                $sr->getQuery()->set($name, $value);
            }
        } else {
            $sr = clone $request;
        }

        // Make sure to handle temporary credentials
        if ($token = $credentials->getSecurityToken()) {
            $sr->setHeader('X-Amz-Security-Token', $token);
            $sr->getQuery()->set('X-Amz-Security-Token', $token);
        }

        $this->moveHeadersToQuery($sr);

        return $sr;
    }

    /**
     * Create the canonical representation of a request
     *
     * @param RequestInterface $request Request to canonicalize
     * @param string           $payload Request payload (typically the value
     *                                  of the x-amz-content-sha256 header.
     *
     * @return array Returns an array of context information including:
     *               - canonical_request
     *               - signed_headers
     */
    private function createSigningContext(RequestInterface $request, $payload)
    {
        $signable = array(
            'host'        => true,
            'date'        => true,
            'content-md5' => true
        );

        // Normalize the path as required by SigV4 and ensure it's absolute
        $canon = $request->getMethod() . "\n"
            . $this->createCanonicalizedPath($request) . "\n"
            . $this->getCanonicalizedQueryString($request) . "\n";

        $canonHeaders = array();

        foreach ($request->getHeaders()->getAll() as $key => $values) {
            $key = strtolower($key);
            if (isset($signable[$key]) || substr($key, 0, 6) === 'x-amz-') {
                $values = $values->toArray();
                if (count($values) == 1) {
                    $values = $values[0];
                } else {
                    sort($values);
                    $values = implode(',', $values);
                }
                $canonHeaders[$key] = $key . ':' . preg_replace('/\s+/', ' ', $values);
            }
        }

        ksort($canonHeaders);
        $signedHeadersString = implode(';', array_keys($canonHeaders));
        $canon .= implode("\n", $canonHeaders) . "\n\n"
            . $signedHeadersString . "\n"
            . $payload;

        return array(
            'canonical_request' => $canon,
            'signed_headers'    => $signedHeadersString
        );
    }

    /**
     * Get a hash for a specific key and value.  If the hash was previously
     * cached, return it
     *
     * @param string $shortDate Short date
     * @param string $region    Region name
     * @param string $service   Service name
     * @param string $secretKey Secret Access Key
     *
     * @return string
     */
    private function getSigningKey($shortDate, $region, $service, $secretKey)
    {
        $cacheKey = $shortDate . '_' . $region . '_' . $service . '_' . $secretKey;

        // Retrieve the hash form the cache or create it and add it to the cache
        if (!isset($this->hashCache[$cacheKey])) {
            // When the cache size reaches the max, then just clear the cache
            if (++$this->cacheSize > $this->maxCacheSize) {
                $this->hashCache = array();
                $this->cacheSize = 0;
            }
            $dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . $secretKey, true);
            $regionKey = hash_hmac('sha256', $region, $dateKey, true);
            $serviceKey = hash_hmac('sha256', $service, $regionKey, true);
            $this->hashCache[$cacheKey] = hash_hmac('sha256', 'aws4_request', $serviceKey, true);
        }

        return $this->hashCache[$cacheKey];
    }

    /**
     * Get the canonicalized query string for a request
     *
     * @param  RequestInterface $request
     * @return string
     */
    private function getCanonicalizedQueryString(RequestInterface $request)
    {
        $queryParams = $request->getQuery()->getAll();
        unset($queryParams['X-Amz-Signature']);
        if (empty($queryParams)) {
            return '';
        }

        $qs = '';
        ksort($queryParams);
        foreach ($queryParams as $key => $values) {
            if (is_array($values)) {
                sort($values);
            } elseif ($values === 0) {
                $values = array('0');
            } elseif (!$values) {
                $values = array('');
            }

            foreach ((array) $values as $value) {
                if ($value === QueryString::BLANK) {
                    $value = '';
                }
                $qs .= rawurlencode($key) . '=' . rawurlencode($value) . '&';
            }
        }

        return substr($qs, 0, -1);
    }

    private function convertExpires($expires)
    {
        if ($expires instanceof \DateTime) {
            $expires = $expires->getTimestamp();
        } elseif (!is_numeric($expires)) {
            $expires = strtotime($expires);
        }

        $duration = $expires - time();

        // Ensure that the duration of the signature is not longer than a week
        if ($duration > 604800) {
            throw new \InvalidArgumentException('The expiration date of a '
                . 'signature version 4 presigned URL must be less than one '
                . 'week');
        }

        return $duration;
    }

    private function createScope($shortDate, $region, $service)
    {
        return $shortDate
            . '/' . $region
            . '/' . $service
            . '/aws4_request';
    }

    private function addQueryValues(
        $scope,
        RequestInterface $request,
        CredentialsInterface $credentials,
        $expires
    ) {
        $credential = $credentials->getAccessKeyId() . '/' . $scope;

        // Set query params required for pre-signed URLs
        $request->getQuery()
            ->set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256')
            ->set('X-Amz-Credential', $credential)
            ->set('X-Amz-Date', gmdate('Ymd\THis\Z', $this->getTimestamp()))
            ->set('X-Amz-SignedHeaders', 'Host')
            ->set('X-Amz-Expires', $this->convertExpires($expires));
    }

    private function moveHeadersToQuery(RequestInterface $request)
    {
        $query = $request->getQuery();

        foreach ($request->getHeaders() as $name => $header) {
            if (substr($name, 0, 5) == 'x-amz') {
                $query[$header->getName()] = (string) $header;
            }
            if ($name !== 'host') {
                $request->removeHeader($name);
            }
        }
    }
}
Signature/SignatureV3Https.php000060400000004101152440555050012410 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Signature;

use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Enum\DateFormat;
use Guzzle\Http\Message\RequestInterface;

/**
 * Implementation of Signature Version 3 HTTPS
 * @link http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/RESTAuthentication.html
 */
class SignatureV3Https extends AbstractSignature
{
    public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
    {
        // Add a date header if one is not set
        if (!$request->hasHeader('date') && !$request->hasHeader('x-amz-date')) {
            $request->setHeader('Date', gmdate(DateFormat::RFC1123, $this->getTimestamp()));
        }

        // Add the security token if one is present
        if ($credentials->getSecurityToken()) {
            $request->setHeader('x-amz-security-token', $credentials->getSecurityToken());
        }

        // Determine the string to sign
        $stringToSign = (string) ($request->getHeader('Date') ?: $request->getHeader('x-amz-date'));
        $request->getParams()->set('aws.string_to_sign', $stringToSign);

        // Calculate the signature
        $signature = base64_encode(hash_hmac('sha256', $stringToSign, $credentials->getSecretKey(), true));

        // Add the authorization header to the request
        $headerFormat = 'AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s';
        $request->setHeader('X-Amzn-Authorization', sprintf($headerFormat, $credentials->getAccessKeyId(), $signature));
    }
}
Signature/SignatureInterface.php000060400000003552152440555050013006 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Signature;

use Aws\Common\Credentials\CredentialsInterface;
use Guzzle\Http\Message\RequestInterface;

/**
 * Interface used to provide interchangeable strategies for signing requests
 * using the various AWS signature protocols.
 */
interface SignatureInterface
{
    /**
     * Signs the specified request with an AWS signing protocol by using the
     * provided AWS account credentials and adding the required headers to the
     * request.
     *
     * @param RequestInterface     $request     Request to add a signature to
     * @param CredentialsInterface $credentials Signing credentials
     */
    public function signRequest(RequestInterface $request, CredentialsInterface $credentials);

    /**
     * Create a pre-signed URL
     *
     * @param RequestInterface     $request Request to sign
     * @param CredentialsInterface $credentials Credentials used to sign
     * @param int|string|\DateTime $expires The time at which the URL should expire. This can be a Unix timestamp, a
     *                                      PHP DateTime object, or a string that can be evaluated by strtotime
     * @return string
     */
    public function createPresignedUrl(
        RequestInterface $request,
        CredentialsInterface $credentials,
        $expires
    );
}
Signature/SignatureListener.php000060400000004524152440555050012673 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Signature;

use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Credentials\NullCredentials;
use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Listener used to sign requests before they are sent over the wire
 */
class SignatureListener implements EventSubscriberInterface
{
    /**
     * @var CredentialsInterface
     */
    protected $credentials;

    /**
     * @var SignatureInterface
     */
    protected $signature;

    /**
     * Construct a new request signing plugin
     *
     * @param CredentialsInterface $credentials Credentials used to sign requests
     * @param SignatureInterface   $signature   Signature implementation
     */
    public function __construct(CredentialsInterface $credentials, SignatureInterface $signature)
    {
        $this->credentials = $credentials;
        $this->signature = $signature;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            'request.before_send'        => array('onRequestBeforeSend', -255),
            'client.credentials_changed' => array('onCredentialsChanged')
        );
    }

    /**
     * Updates the listener with new credentials if the client is updated
     *
     * @param Event $event Event emitted
     */
    public function onCredentialsChanged(Event $event)
    {
        $this->credentials = $event['credentials'];
    }

    /**
     * Signs requests before they are sent
     *
     * @param Event $event Event emitted
     */
    public function onRequestBeforeSend(Event $event)
    {
        if(!$this->credentials instanceof NullCredentials) {
            $this->signature->signRequest($event['request'], $this->credentials);
        }
    }
}
Signature/SignatureV2.php000060400000007065152440555050011400 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Signature;

use Aws\Common\Credentials\CredentialsInterface;
use Guzzle\Http\Message\RequestInterface;

/**
 * Implementation of Signature Version 2
 * @link http://aws.amazon.com/articles/1928
 */
class SignatureV2 extends AbstractSignature
{
    public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
    {
        // refresh the cached timestamp
        $timestamp = $this->getTimestamp(true);

        // set values we need in CanonicalizedParameterString
        $this->addParameter($request, 'Timestamp', gmdate('c', $timestamp));
        $this->addParameter($request, 'SignatureVersion', '2');
        $this->addParameter($request, 'SignatureMethod', 'HmacSHA256');
        $this->addParameter($request, 'AWSAccessKeyId', $credentials->getAccessKeyId());

        if ($token = $credentials->getSecurityToken()) {
            $this->addParameter($request, 'SecurityToken', $token);
        }

        // Get the path and ensure it's absolute
        $path = '/' . ltrim($request->getUrl(true)->normalizePath()->getPath(), '/');

        // build string to sign
        $sign = $request->getMethod() . "\n"
            . $request->getHost() . "\n"
            . $path . "\n"
            . $this->getCanonicalizedParameterString($request);

        // Add the string to sign to the request for debugging purposes
        $request->getParams()->set('aws.string_to_sign', $sign);

        $signature = base64_encode(
            hash_hmac(
                'sha256',
                $sign,
                $credentials->getSecretKey(),
                true
            )
        );

        $this->addParameter($request, 'Signature', $signature);
    }

    /**
     * Add a parameter key and value to the request according to type
     *
     * @param RequestInterface $request The request
     * @param string           $key     The name of the parameter
     * @param string           $value   The value of the parameter
     */
    public function addParameter(RequestInterface $request, $key, $value)
    {
        if ($request->getMethod() == 'POST') {
            $request->setPostField($key, $value);
        } else {
            $request->getQuery()->set($key, $value);
        }
    }

    /**
     * Get the canonicalized query/parameter string for a request
     *
     * @param RequestInterface $request Request used to build canonicalized string
     *
     * @return string
     */
    private function getCanonicalizedParameterString(RequestInterface $request)
    {
        if ($request->getMethod() == 'POST') {
            $params = $request->getPostFields()->toArray();
        } else {
            $params = $request->getQuery()->toArray();
        }

        // Don't resign a previous signature value
        unset($params['Signature']);
        uksort($params, 'strcmp');

        $str = '';
        foreach ($params as $key => $val) {
            $str .= rawurlencode($key) . '=' . rawurlencode($val) . '&';
        }

        return substr($str, 0, -1);
    }
}
InstanceMetadata/InstanceMetadataClient.php000060400000007273152440555050015040 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\InstanceMetadata;

use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\InstanceProfileCredentialsException;
use Aws\Common\Credentials\Credentials;
use Aws\Common\Client\AbstractClient;
use Guzzle\Common\Collection;
use Guzzle\Http\Message\RequestFactory;

/**
 * Client used for interacting with the Amazon EC2 instance metadata server
 */
class InstanceMetadataClient extends AbstractClient
{
    /**
     * Factory method to create a new InstanceMetadataClient using an array
     * of configuration options.
     *
     * The configuration options accepts the following array keys and values:
     * - base_url: Override the base URL of the instance metadata server
     * - version:  Version of the metadata server to interact with
     *
     * @param array|Collection $config Configuration options
     *
     * @return InstanceMetadataClient
     */
    public static function factory($config = array())
    {
        $config = Collection::fromConfig($config, array(
            Options::BASE_URL => 'http://169.254.169.254/{version}/',
            'version'         => 'latest',
            'request.options' => array(
                'connect_timeout' => 5,
                'timeout'         => 10
            )
        ), array('base_url', 'version'));

        return new self($config);
    }

    /**
     * Constructor override
     */
    public function __construct(Collection $config)
    {
        $this->setConfig($config);
        $this->setBaseUrl($config->get(Options::BASE_URL));
        $this->defaultHeaders = new Collection();
        $this->setRequestFactory(RequestFactory::getInstance());
    }

    /**
     * Get instance profile credentials
     *
     * @return Credentials
     * @throws InstanceProfileCredentialsException
     */
    public function getInstanceProfileCredentials()
    {
        try {
            $request = $this->get('meta-data/iam/security-credentials/');
            $credentials = trim($request->send()->getBody(true));
            $result = $this->get("meta-data/iam/security-credentials/{$credentials}")->send()->json();
        } catch (\Exception $e) {
            $message = sprintf('Error retrieving credentials from the instance profile metadata server. When you are'
                . ' not running inside of Amazon EC2, you must provide your AWS access key ID and secret access key in'
                . ' the "key" and "secret" options when creating a client or provide an instantiated'
                . ' Aws\\Common\\Credentials\\CredentialsInterface object. (%s)', $e->getMessage());
            throw new InstanceProfileCredentialsException($message, $e->getCode());
        }

        // Ensure that the status code was successful
        if ($result['Code'] !== 'Success') {
            $e = new InstanceProfileCredentialsException('Unexpected response code: ' . $result['Code']);
            $e->setStatusCode($result['Code']);
            throw $e;
        }

        return new Credentials(
            $result['AccessKeyId'],
            $result['SecretAccessKey'],
            $result['Token'],
            strtotime($result['Expiration'])
        );
    }
}
InstanceMetadata/Waiter/.htaccess000044400000000424152440555050013005 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>InstanceMetadata/Waiter/ServiceAvailable.php000060400000002703152440555050015121 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\InstanceMetadata\Waiter;

use Aws\Common\Waiter\AbstractResourceWaiter;
use Guzzle\Http\Exception\CurlException;

/**
 * Waits until the instance metadata service is responding.  Will send up to
 * 4 requests with a 5 second delay between each try.  Each try can last up to
 * 11 seconds to complete if the service is not responding.
 *
 * @codeCoverageIgnore
 */
class ServiceAvailable extends AbstractResourceWaiter
{
    protected $interval = 5;
    protected $maxAttempts = 4;

    /**
     * {@inheritdoc}
     */
    public function doWait()
    {
        $request = $this->client->get();
        try {
            $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, 10)
                ->set(CURLOPT_TIMEOUT, 10);
            $request->send();

            return true;
        } catch (CurlException $e) {
            return false;
        }
    }
}
InstanceMetadata/.htaccess000044400000000424152440555050011552 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Exception/AwsExceptionInterface.php000060400000001643152440555050013452 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * "Marker Interface" implemented by every exception in the AWS SDK
 */
interface AwsExceptionInterface
{
    public function getCode();
    public function getLine();
    public function getFile();
    public function getMessage();
    public function getPrevious();
    public function getTrace();
}
Exception/TransferException.php000060400000001423152440555050012657 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

use Guzzle\Http\Exception\CurlException;

/**
 * Transfer request exception
 */
class TransferException extends CurlException implements AwsExceptionInterface {}
Exception/ExceptionFactoryInterface.php000060400000002172152440555050014325 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Interface used to create AWS exception
 */
interface ExceptionFactoryInterface
{
    /**
     * Returns an AWS service specific exception
     *
     * @param RequestInterface $request  Unsuccessful request
     * @param Response         $response Unsuccessful response that was encountered
     *
     * @return \Exception|AwsExceptionInterface
     */
    public function fromResponse(RequestInterface $request, Response $response);
}
Exception/OutOfBoundsException.php000060400000001422152440555050013301 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * AWS SDK namespaced version of the SPL OverflowException.
 */
class OutOfBoundsException extends \OutOfBoundsException implements AwsExceptionInterface {}
Exception/RequiredExtensionNotLoadedException.php000060400000001463152440555050016346 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * Thrown when a particular PHP extension is required to execute the guarded logic, but the extension is not loaded
 */
class RequiredExtensionNotLoadedException extends RuntimeException {}
Exception/OverflowException.php000060400000001414152440555050012676 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * AWS SDK namespaced version of the SPL OverflowException.
 */
class OverflowException extends \OverflowException implements AwsExceptionInterface {}
Exception/NamespaceExceptionFactory.php000060400000006771152440555050014332 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

use Aws\Common\Exception\Parser\ExceptionParserInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Attempts to create exceptions by inferring the name from the code and a base
 * namespace that contains exceptions.  Exception classes are expected to be in
 * upper camelCase and always end in 'Exception'. 'Exception' will be appended
 * if it is not present in the exception code.
 */
class NamespaceExceptionFactory implements ExceptionFactoryInterface
{
    /**
     * @var ExceptionParserInterface $parser Parser used to parse responses
     */
    protected $parser;

    /**
     * @var string Base namespace containing exception classes
     */
    protected $baseNamespace;

    /**
     * @var string Default class to instantiate if a match is not found
     */
    protected $defaultException;

    /**
     * @param ExceptionParserInterface $parser           Parser used to parse exceptions
     * @param string                   $baseNamespace    Namespace containing exceptions
     * @param string                   $defaultException Default class to use if one is not mapped
     */
    public function __construct(
        ExceptionParserInterface $parser,
        $baseNamespace,
        $defaultException = 'Aws\Common\Exception\ServiceResponseException'
    ) {
        $this->parser = $parser;
        $this->baseNamespace = $baseNamespace;
        $this->defaultException = $defaultException;
    }

    /**
     * {@inheritdoc}
     */
    public function fromResponse(RequestInterface $request, Response $response)
    {
        $parts = $this->parser->parse($request, $response);

        // Removing leading 'AWS.' and embedded periods
        $className = $this->baseNamespace . '\\' . str_replace(array('AWS.', '.'), '', $parts['code']);
        if (substr($className, -9) !== 'Exception') {
            $className .= 'Exception';
        }

        $className = class_exists($className) ? $className : $this->defaultException;

        return $this->createException($className, $request, $response, $parts);
    }

    /**
     * Create an prepare an exception object
     *
     * @param string           $className Name of the class to create
     * @param RequestInterface $request   Request
     * @param Response         $response  Response received
     * @param array            $parts     Parsed exception data
     *
     * @return \Exception
     */
    protected function createException($className, RequestInterface $request, Response $response, array $parts)
    {
        $class = new $className($parts['message']);

        if ($class instanceof ServiceResponseException) {
            $class->setExceptionCode($parts['code']);
            $class->setExceptionType($parts['type']);
            $class->setResponse($response);
            $class->setRequest($request);
            $class->setRequestId($parts['request_id']);
        }

        return $class;
    }
}
Exception/Parser/.htaccess000044400000000424152440555050011537 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Exception/Parser/JsonQueryExceptionParser.php000060400000002356152440555050015451 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception\Parser;

use Guzzle\Http\Message\Response;

/**
 * Parses JSON encoded exception responses from query services
 */
class JsonQueryExceptionParser extends AbstractJsonExceptionParser
{
    /**
     * {@inheritdoc}
     */
    protected function doParse(array $data, Response $response)
    {
        if ($json = $data['parsed']) {
            if (isset($json['__type'])) {
                $parts = explode('#', $json['__type']);
                $data['code'] = isset($parts[1]) ? $parts[1] : $parts[0];
            }
            $data['message'] = isset($json['message']) ? $json['message'] : null;
        }

        return $data;
    }
}
Exception/Parser/ExceptionParserInterface.php000060400000002561152440555050015410 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception\Parser;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Interface used to parse exceptions into an associative array of data
 */
interface ExceptionParserInterface
{
    /**
     * Parses an exception into an array of data containing at minimum the
     * following array keys:
     * - type:       Exception type
     * - code:       Exception code
     * - message:    Exception message
     * - request_id: Request ID
     * - parsed:     The parsed representation of the data (array, SimpleXMLElement, etc)
     *
     * @param RequestInterface $request
     * @param Response         $response Unsuccessful response
     *
     * @return array
     */
    public function parse(RequestInterface $request, Response $response);
}
Exception/Parser/AbstractJsonExceptionParser.php000060400000004220152440555050016077 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception\Parser;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Parses JSON encoded exception responses
 */
abstract class AbstractJsonExceptionParser implements ExceptionParserInterface
{
    /**
     * {@inheritdoc}
     */
    public function parse(RequestInterface $request, Response $response)
    {
        // Build array of default error data
        $data = array(
            'code'       => null,
            'message'    => null,
            'type'       => $response->isClientError() ? 'client' : 'server',
            'request_id' => (string) $response->getHeader('x-amzn-RequestId'),
            'parsed'     => null
        );

        // Parse the json and normalize key casings
        if (null !== $json = json_decode($response->getBody(true), true)) {
            $data['parsed'] = array_change_key_case($json);
        }

        // Do additional, protocol-specific parsing and return the result
        $data = $this->doParse($data, $response);

        // Remove "Fault" suffix from exception names
        if (isset($data['code']) && strpos($data['code'], 'Fault')) {
            $data['code'] = preg_replace('/^([a-zA-Z]+)Fault$/', '$1', $data['code']);
        }

        return $data;
    }

    /**
     * Pull relevant exception data out of the parsed json
     *
     * @param array    $data     The exception data
     * @param Response $response The response from the service containing the error
     *
     * @return array
     */
    abstract protected function doParse(array $data, Response $response);
}
Exception/Parser/DefaultXmlExceptionParser.php000060400000007211152440555050015552 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception\Parser;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Parses default XML exception responses
 */
class DefaultXmlExceptionParser implements ExceptionParserInterface
{
    public function parse(RequestInterface $request, Response $response)
    {
        $data = array(
            'code'       => null,
            'message'    => null,
            'type'       => $response->isClientError() ? 'client' : 'server',
            'request_id' => null,
            'parsed'     => null
        );

        $body = $response->getBody(true);

        if (!$body) {
            $this->parseHeaders($request, $response, $data);
            return $data;
        }

        try {
            $xml = new \SimpleXMLElement($body);
            $this->parseBody($xml, $data);
            return $data;
        } catch (\Exception $e) {
            // Gracefully handle parse errors. This could happen when the
            // server responds with a non-XML response (e.g., private beta
            // services).
            $data['code'] = 'PhpInternalXmlParseError';
            $data['message'] = 'A non-XML response was received';
            return $data;
        }
    }

    /**
     * Parses additional exception information from the response headers
     *
     * @param RequestInterface $request  Request that was issued
     * @param Response         $response The response from the request
     * @param array            $data     The current set of exception data
     */
    protected function parseHeaders(RequestInterface $request, Response $response, array &$data)
    {
        $data['message'] = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
        if ($requestId = $response->getHeader('x-amz-request-id')) {
            $data['request_id'] = $requestId;
            $data['message'] .= " (Request-ID: $requestId)";
        }
    }

    /**
     * Parses additional exception information from the response body
     *
     * @param \SimpleXMLElement $body The response body as XML
     * @param array             $data The current set of exception data
     */
    protected function parseBody(\SimpleXMLElement $body, array &$data)
    {
        $data['parsed'] = $body;

        $namespaces = $body->getDocNamespaces();
        if (isset($namespaces[''])) {
            // Account for the default namespace being defined and PHP not being able to handle it :(
            $body->registerXPathNamespace('ns', $namespaces['']);
            $prefix = 'ns:';
        } else {
            $prefix = '';
        }

        if ($tempXml = $body->xpath("//{$prefix}Code[1]")) {
            $data['code'] = (string) $tempXml[0];
        }

        if ($tempXml = $body->xpath("//{$prefix}Message[1]")) {
            $data['message'] = (string) $tempXml[0];
        }

        $tempXml = $body->xpath("//{$prefix}RequestId[1]");
        if (empty($tempXml)) {
            $tempXml = $body->xpath("//{$prefix}RequestID[1]");
        }
        if (isset($tempXml[0])) {
            $data['request_id'] = (string) $tempXml[0];
        }
    }
}
Exception/Parser/JsonRestExceptionParser.php000060400000002720152440555050015254 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception\Parser;

use Guzzle\Http\Message\Response;

/**
 * Parses JSON encoded exception responses from REST services
 */
class JsonRestExceptionParser extends AbstractJsonExceptionParser
{
    /**
     * {@inheritdoc}
     */
    protected function doParse(array $data, Response $response)
    {
        // Merge in error data from the JSON body
        if ($json = $data['parsed']) {
            $data = array_replace($data, $json);
        }

        // Correct error type from services like Amazon Glacier
        if (!empty($data['type'])) {
            $data['type'] = strtolower($data['type']);
        }

        // Retrieve the error code from services like Amazon Elastic Transcoder
        if ($code = (string) $response->getHeader('x-amzn-ErrorType')) {
            $data['code'] = substr($code, 0, strpos($code, ':'));
        }

        return $data;
    }
}
Exception/MultipartUploadException.php000060400000003147152440555050014226 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

use Aws\Common\Model\MultipartUpload\TransferStateInterface;

/**
 * Thrown when a {@see Aws\Common\MultipartUpload\TransferInterface} object encounters an error during transfer
 */
class MultipartUploadException extends RuntimeException
{
    /**
     * @var TransferStateInterface State of the transfer when the error was encountered
     */
    protected $state;

    /**
     * @param TransferStateInterface $state     Transfer state
     * @param \Exception             $exception Last encountered exception
     */
    public function __construct(TransferStateInterface $state, \Exception $exception = null)
    {
        parent::__construct(
            'An error was encountered while performing a multipart upload: ' . $exception->getMessage(),
            0,
            $exception
        );

        $this->state = $state;
    }

    /**
     * Get the state of the transfer
     *
     * @return TransferStateInterface
     */
    public function getState()
    {
        return $this->state;
    }
}
Exception/InstanceProfileCredentialsException.php000060400000002416152440555050016341 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

use Aws\Common\Exception\RuntimeException;

/**
 * Exception thrown when an error occurs with instance profile credentials
 */
class InstanceProfileCredentialsException extends RuntimeException
{
    /**
     * @var string
     */
    protected $statusCode;

    /**
     * Set the error response code received from the instance metadata
     *
     * @param string $code Response code
     */
    public function setStatusCode($code)
    {
        $this->statusCode = $code;
    }

    /**
     * Get the error response code from the service
     *
     * @return string|null
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }
}
Exception/ServiceResponseException.php000060400000011504152440555050014213 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Default AWS exception
 */
class ServiceResponseException extends RuntimeException
{
    /**
     * @var Response Response
     */
    protected $response;

    /**
     * @var RequestInterface Request
     */
    protected $request;

    /**
     * @var string Request ID
     */
    protected $requestId;

    /**
     * @var string Exception type (client / server)
     */
    protected $exceptionType;

    /**
     * @var string Exception code
     */
    protected $exceptionCode;

    /**
     * Set the exception code
     *
     * @param string $code Exception code
     */
    public function setExceptionCode($code)
    {
        $this->exceptionCode = $code;
    }

    /**
     * Get the exception code
     *
     * @return string|null
     */
    public function getExceptionCode()
    {
        return $this->exceptionCode;
    }

    /**
     * Set the exception type
     *
     * @param string $type Exception type
     */
    public function setExceptionType($type)
    {
        $this->exceptionType = $type;
    }

    /**
     * Get the exception type (one of client or server)
     *
     * @return string|null
     */
    public function getExceptionType()
    {
        return $this->exceptionType;
    }

    /**
     * Set the request ID
     *
     * @param string $id Request ID
     */
    public function setRequestId($id)
    {
        $this->requestId = $id;
    }

    /**
     * Get the Request ID
     *
     * @return string|null
     */
    public function getRequestId()
    {
        return $this->requestId;
    }

    /**
     * Set the associated response
     *
     * @param Response $response Response
     */
    public function setResponse(Response $response)
    {
        $this->response = $response;
    }

    /**
     * Get the associated response object
     *
     * @return Response|null
     */
    public function getResponse()
    {
        return $this->response;
    }

    /**
     * Set the associated request
     *
     * @param RequestInterface $request
     */
    public function setRequest(RequestInterface $request)
    {
        $this->request = $request;
    }

    /**
     * Get the associated request object
     *
     * @return RequestInterface|null
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * Get the status code of the response
     *
     * @return int|null
     */
    public function getStatusCode()
    {
        return $this->response ? $this->response->getStatusCode() : null;
    }

    /**
     * Cast to a string
     *
     * @return string
     */
    public function __toString()
    {
        $message = get_class($this) . ': '
            . 'AWS Error Code: ' . $this->getExceptionCode() . ', '
            . 'Status Code: ' . $this->getStatusCode() . ', '
            . 'AWS Request ID: ' . $this->getRequestId() . ', '
            . 'AWS Error Type: ' . $this->getExceptionType() . ', '
            . 'AWS Error Message: ' . $this->getMessage();

        // Add the User-Agent if available
        if ($this->request) {
            $message .= ', ' . 'User-Agent: ' . $this->request->getHeader('User-Agent');
        }

        return $message;
    }

    /**
     * Get the request ID of the error. This value is only present if a
     * response was received, and is not present in the event of a networking
     * error.
     *
     * Same as `getRequestId()` method, but matches the interface for SDKv3.
     *
     * @return string|null Returns null if no response was received
     */
    public function getAwsRequestId()
    {
        return $this->requestId;
    }

    /**
     * Get the AWS error type.
     *
     * Same as `getExceptionType()` method, but matches the interface for SDKv3.
     *
     * @return string|null Returns null if no response was received
     */
    public function getAwsErrorType()
    {
        return $this->exceptionType;
    }

    /**
     * Get the AWS error code.
     *
     * Same as `getExceptionCode()` method, but matches the interface for SDKv3.
     *
     * @return string|null Returns null if no response was received
     */
    public function getAwsErrorCode()
    {
        return $this->exceptionCode;
    }
}
Exception/ExceptionListener.php000060400000003227152440555050012664 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Converts generic Guzzle response exceptions into AWS specific exceptions
 */
class ExceptionListener implements EventSubscriberInterface
{
    /**
     * @var ExceptionFactoryInterface Factory used to create new exceptions
     */
    protected $factory;

    /**
     * @param ExceptionFactoryInterface $factory Factory used to create exceptions
     */
    public function __construct(ExceptionFactoryInterface $factory)
    {
        $this->factory = $factory;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array('request.error' => array('onRequestError', -1));
    }

    /**
     * Throws a more meaningful request exception if available
     *
     * @param Event $event Event emitted
     */
    public function onRequestError(Event $event)
    {
        $e = $this->factory->fromResponse($event['request'], $event['response']);
        $event->stopPropagation();
        throw $e;
    }
}
Exception/DomainException.php000060400000001406152440555050012303 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * AWS SDK namespaced version of the SPL DomainException.
 */
class DomainException extends \DomainException implements AwsExceptionInterface {}
Exception/LogicException.php000060400000001403152440555050012126 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Exception;

/**
 * AWS SDK namespaced version of the SPL LogicException.
 */
class LogicException extends \LogicException implements AwsExceptionInterface {}
Hash/ChunkHash.php000060400000004120152440555050010012 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Hash;

use Aws\Common\Exception\LogicException;

/**
 * Encapsulates the creation of a hash from streamed chunks of data
 */
class ChunkHash implements ChunkHashInterface
{
    /**
     * @var resource The hash context as created by `hash_init()`
     */
    protected $context;

    /**
     * @var string The resulting hash in hex form
     */
    protected $hash;

    /**
     * @var string The resulting hash in binary form
     */
    protected $hashRaw;

    /**
     * {@inheritdoc}
     */
    public function __construct($algorithm = self::DEFAULT_ALGORITHM)
    {
        HashUtils::validateAlgorithm($algorithm);
        $this->context = hash_init($algorithm);
    }

    /**
     * {@inheritdoc}
     */
    public function addData($data)
    {
        if (!$this->context) {
            throw new LogicException('You may not add more data to a finalized chunk hash.');
        }

        hash_update($this->context, $data);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getHash($returnBinaryForm = false)
    {
        if (!$this->hash) {
            $this->hashRaw = hash_final($this->context, true);
            $this->hash = HashUtils::binToHex($this->hashRaw);
            $this->context = null;
        }

        return $returnBinaryForm ? $this->hashRaw : $this->hash;
    }

    /**
     * {@inheritdoc}
     */
    public function __clone()
    {
        if ($this->context) {
            $this->context = hash_copy($this->context);
        }
    }
}
Hash/HashUtils.php000060400000004115152440555050010046 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Hash;

use Aws\Common\Exception\InvalidArgumentException;

/**
 * Contains hashing utilities
 */
class HashUtils
{
    /**
     * Converts a hash in hex form to binary form
     *
     * @param string $hash Hash in hex form
     *
     * @return string Hash in binary form
     */
    public static function hexToBin($hash)
    {
        // If using PHP 5.4, there is a native function to convert from hex to binary
        static $useNative;
        if ($useNative === null) {
            $useNative = function_exists('hex2bin');
        }

        if (!$useNative && strlen($hash) % 2 !== 0) {
            $hash = '0' . $hash;
        }

        return $useNative ? hex2bin($hash) : pack("H*", $hash);
    }

    /**
     * Converts a hash in binary form to hex form
     *
     * @param string $hash Hash in binary form
     *
     * @return string Hash in hex form
     */
    public static function binToHex($hash)
    {
        return bin2hex($hash);
    }

    /**
     * Checks if the algorithm specified exists and throws an exception if it does not
     *
     * @param string $algorithm Name of the algorithm to validate
     *
     * @return bool
     * @throws InvalidArgumentException if the algorithm doesn't exist
     */
    public static function validateAlgorithm($algorithm)
    {
        if (!in_array($algorithm, hash_algos(), true)) {
            throw new InvalidArgumentException("The hashing algorithm specified ({$algorithm}) does not exist.");
        }

        return true;
    }
}
Hash/ChunkHashInterface.php000060400000002714152440555050011642 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Hash;

/**
 * Interface for objects that encapsulate the creation of a hash from streamed chunks of data
 */
interface ChunkHashInterface
{
    const DEFAULT_ALGORITHM = 'sha256';

    /**
     * Constructs the chunk hash and sets the algorithm to use for hashing
     *
     * @param string $algorithm A valid hash algorithm name as returned by `hash_algos()`
     *
     * @return self
     */
    public function __construct($algorithm = 'sha256');

    /**
     * Add a chunk of data to be hashed
     *
     * @param string $data Data to be hashed
     *
     * @return self
     */
    public function addData($data);

    /**
     * Return the results of the hash
     *
     * @param bool $returnBinaryForm If true, returns the hash in binary form instead of hex form
     *
     * @return string
     */
    public function getHash($returnBinaryForm = false);
}
Hash/.htaccess000044400000000424152440555050007230 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Hash/TreeHash.php000060400000014031152440555050007643 0ustar00<?php
/**
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * 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://aws.amazon.com/apache2.0
 *
 * 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 Aws\Common\Hash;

use Aws\Common\Enum\Size;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\LogicException;
use Guzzle\Http\EntityBody;

/**
 * Encapsulates the creation of a tree hash from streamed chunks of data
 */
class TreeHash implements ChunkHashInterface
{
    /**
     * @var string The algorithm used for hashing
     */
    protected $algorithm;

    /**
     * @var array Set of binary checksums from which the tree hash is derived
     */
    protected $checksums = array();

    /**
     * @var string The resulting hash in hex form
     */
    protected $hash;

    /**
     * @var string The resulting hash in binary form
     */
    protected $hashRaw;

    /**
     * Create a tree hash from an array of existing tree hash checksums
     *
     * @param array  $checksums    Set of checksums
     * @param bool   $inBinaryForm Whether or not the checksums are already in binary form
     * @param string $algorithm    A valid hash algorithm name as returned by `hash_algos()`
     *
     * @return TreeHash
     */
    public static function fromChecksums(array $checksums, $inBinaryForm = false, $algorithm = self::DEFAULT_ALGORITHM)
    {
        $treeHash = new self($algorithm);

        // Convert checksums to binary form if provided in hex form and add them to the tree hash
        $treeHash->checksums = $inBinaryForm ? $checksums : array_map('Aws\Common\Hash\HashUtils::hexToBin', $checksums);

        // Pre-calculate hash
        $treeHash->getHash();

        return $treeHash;
    }

    /**
     * Create a tree hash from a content body
     *
     * @param string|resource|EntityBody $content   Content to create a tree hash for
     * @param string                     $algorithm A valid hash algorithm name as returned by `hash_algos()`
     *
     * @return TreeHash
     */
    public static function fromContent($content, $algorithm = self::DEFAULT_ALGORITHM)
    {
        $treeHash = new self($algorithm);

        // Read the data in 1MB chunks and add to tree hash
        $content = EntityBody::factory($content);
        while ($data = $content->read(Size::MB)) {
            $treeHash->addData($data);
        }

        // Pre-calculate hash
        $treeHash->getHash();

        return $treeHash;
    }

    /**
     * Validates an entity body with a tree hash checksum
     *
     * @param string|resource|EntityBody $content   Content to create a tree hash for
     * @param string                     $checksum  The checksum to use for validation
     * @param string                     $algorithm A valid hash algorithm name as returned by `hash_algos()`
     *
     * @return bool
     */
    public static function validateChecksum($content, $checksum, $algorithm = self::DEFAULT_ALGORITHM)
    {
        $treeHash = self::fromContent($content, $algorithm);

        return ($checksum === $treeHash->getHash());
    }

    /**
     * {@inheritdoc}
     */
    public function __construct($algorithm = self::DEFAULT_ALGORITHM)
    {
        HashUtils::validateAlgorithm($algorithm);
        $this->algorithm = $algorithm;
    }

    /**
     * {@inheritdoc}
     * @throws LogicException           if the root tree hash is already calculated
     * @throws InvalidArgumentException if the data is larger than 1MB
     */
    public function addData($data)
    {
        // Error if hash is already calculated
        if ($this->hash) {
            throw new LogicException('You may not add more data to a finalized tree hash.');
        }

        // Make sure that only 1MB chunks or smaller get passed in
        if (strlen($data) > Size::MB) {
            throw new InvalidArgumentException('The chunk of data added is too large for tree hashing.');
        }

        // Store the raw hash of this data segment
        $this->checksums[] = hash($this->algorithm, $data, true);

        return $this;
    }

    /**
     * Add a checksum to the tree hash directly
     *
     * @param string $checksum     The checksum to add
     * @param bool   $inBinaryForm Whether or not the checksum is already in binary form
     *
     * @return self
     * @throws LogicException if the root tree hash is already calculated
     */
    public function addChecksum($checksum, $inBinaryForm = false)
    {
        // Error if hash is already calculated
        if ($this->hash) {
            throw new LogicException('You may not add more checksums to a finalized tree hash.');
        }

        // Convert the checksum to binary form if necessary
        $this->checksums[] = $inBinaryForm ? $checksum : HashUtils::hexToBin($checksum);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getHash($returnBinaryForm = false)
    {
        if (!$this->hash) {
            // Perform hashes up the tree to arrive at the root checksum of the tree hash
            $hashes = $this->checksums;
            while (count($hashes) > 1) {
                $sets = array_chunk($hashes, 2);
                $hashes = array();
                foreach ($sets as $set) {
                    $hashes[] = (count($set) === 1) ? $set[0] : hash($this->algorithm, $set[0] . $set[1], true);
                }
            }

            $this->hashRaw = $hashes[0];
            $this->hash = HashUtils::binToHex($this->hashRaw);
        }

        return $returnBinaryForm ? $this->hashRaw : $this->hash;
    }

    /**
     * @return array Array of raw checksums composing the tree hash
     */
    public function getChecksums()
    {
        return $this->checksums;
    }
}
Log/Logger.php000060400000013311152442617120007214 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Log;

use OpenCloud\Common\Exceptions\LoggingException;
use Psr\Log\AbstractLogger;
use Psr\Log\LogLevel;

/**
 * Basic logger for OpenCloud which extends FIG's PSR-3 standard logger.
 *
 * @link https://github.com/php-fig/log
 */
class Logger extends AbstractLogger
{
    /**
     * Is this debug class enabled or not?
     *
     * @var bool
     */
    private $enabled;

    /**
     * These are the levels which will always be outputted - regardless of
     * user-imposed settings.
     *
     * @var array
     */
    private $urgentLevels = array(
        LogLevel::EMERGENCY,
        LogLevel::ALERT,
        LogLevel::CRITICAL
    );

    /**
     * Logging options.
     *
     * @var array
     */
    private $options = array(
        'outputToFile' => false,
        'logFile'      => null,
        'dateFormat'   => 'd/m/y H:I',
        'delimeter'    => ' - '
    );

    public function __construct($enabled = false)
    {
        $this->enabled = $enabled;
    }

    public static function newInstance()
    {
        return new static();
    }

    /**
     * Determines whether a log level needs to be outputted.
     *
     * @param  string $logLevel
     * @return bool
     */
    private function outputIsUrgent($logLevel)
    {
        return in_array($logLevel, $this->urgentLevels);
    }

    /**
     * Interpolates context values into the message placeholders.
     *
     * @param string $message
     * @param array  $context
     * @return type
     */
    private function interpolate($message, array $context = array())
    {
        // build a replacement array with braces around the context keys
        $replace = array();
        foreach ($context as $key => $val) {
            $replace['{' . $key . '}'] = $val;
        }

        // interpolate replacement values into the message and return
        return strtr($message, $replace);
    }

    /**
     * Enable or disable the debug class.
     *
     * @param  bool $enabled
     * @return self
     */
    public function setEnabled($enabled)
    {
        $this->enabled = $enabled;

        return $this;
    }

    /**
     * Is the debug class enabled?
     *
     * @return bool
     */
    public function isEnabled()
    {
        return $this->enabled === true;
    }

    /**
     * Set an array of options.
     *
     * @param array $options
     */
    public function setOptions(array $options = array())
    {
        foreach ($options as $key => $value) {
            $this->setOption($key, $value);
        }

        return $this;
    }

    /**
     * Get all options.
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Set an individual option.
     *
     * @param string $key
     * @param string $value
     */
    public function setOption($key, $value)
    {
        if ($this->optionExists($key)) {
            $this->options[$key] = $value;

            return $this;
        }
    }

    /**
     * Get an individual option.
     *
     * @param  string $key
     * @return string|null
     */
    public function getOption($key)
    {
        if ($this->optionExists($key)) {
            return $this->options[$key];
        }
    }

    /**
     * Check whether an individual option exists.
     *
     * @param  string $key
     * @return bool
     */
    private function optionExists($key)
    {
        return array_key_exists($key, $this->getOptions());
    }

    /**
     * Outputs a log message if necessary.
     *
     * @param string $logLevel
     * @param string $message
     * @param string $context
     */
    public function log($level, $message, array $context = array())
    {
        if ($this->outputIsUrgent($level) || $this->isEnabled()) {
            $this->dispatch($message, $context);
        }
    }

    /**
     * Used to format the line outputted in the log file.
     *
     * @param  string $string
     * @return string
     */
    private function formatFileLine($string)
    {
        $format = $this->getOption('dateFormat') . $this->getOption('delimeter');

        return date($format) . $string;
    }

    /**
     * Dispatch a log output message.
     *
     * @param string $message
     * @param array  $context
     * @throws LoggingException
     */
    private function dispatch($message, $context)
    {
        $output = $this->interpolate($message, $context) . PHP_EOL;

        if ($this->getOption('outputToFile') === true) {
            $file = $this->getOption('logFile');

            if (!is_writable($file)) {
                throw new LoggingException(
                    'The log file either does not exist or is not writeable'
                );
            }

            // Output to file
            file_put_contents($file, $this->formatFileLine($output), FILE_APPEND);
        } else {
            echo $output;
        }
    }

    /**
     * Helper method, use PSR-3 warning function for deprecation warnings
     * @see http://www.php-fig.org/psr/psr-3/
     */
    public static function deprecated($method, $new)
    {
        return sprintf('The %s method is deprecated, please use %s instead', $method, $new);
    }
}
Log/.htaccess000044400000000424152442617120007065 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Base.php000060400000032120152442617120006125 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common;

use OpenCloud\Common\Collection\ResourceIterator;
use OpenCloud\Common\Constants\Header as HeaderConst;
use OpenCloud\Common\Constants\Mime as MimeConst;
use OpenCloud\Common\Exceptions\JsonError;
use Psr\Log\LoggerInterface;

/**
 * The root class for all other objects used or defined by this SDK.
 *
 * It contains common code for error handling as well as service functions that
 * are useful. Because it is an abstract class, it cannot be called directly,
 * and it has no publicly-visible properties.
 */
abstract class Base
{
    /**
     * Holds all the properties added by overloading.
     *
     * @var array
     */
    private $properties = array();

    /**
     * The logger instance
     *
     * @var LoggerInterface
     */
    private $logger;

    /**
     * The aliases configure for the properties of the instance.
     *
     * @var array
     */
    protected $aliases = array();

    /**
     * @return static
     */
    public static function getInstance()
    {
        return new static();
    }

    /**
     * Intercept non-existent method calls for dynamic getter/setter functionality.
     *
     * @param $method
     * @param $args
     * @throws Exceptions\RuntimeException
     */
    public function __call($method, $args)
    {
        $prefix = substr($method, 0, 3);

        // Get property - convert from camel case to underscore
        $property = lcfirst(substr($method, 3));

        // Only do these methods on properties which exist
        if ($this->propertyExists($property) && $prefix == 'get') {
            return $this->getProperty($property);
        }

        // Do setter
        if ($this->propertyExists($property) && $prefix == 'set') {
            return $this->setProperty($property, $args[0]);
        }

        throw new Exceptions\RuntimeException(sprintf(
            'No method %s::%s()',
            get_class($this),
            $method
        ));
    }

    /**
     * We can set a property under three conditions:
     *
     * 1. If it has a concrete setter: setProperty()
     * 2. If the property exists
     * 3. If the property name's prefix is in an approved list
     *
     * @param  mixed $property
     * @param  mixed $value
     * @return mixed
     */
    protected function setProperty($property, $value)
    {
        $setter = 'set' . $this->toCamel($property);

        if (method_exists($this, $setter)) {
            return call_user_func(array($this, $setter), $value);
        } elseif (false !== ($propertyVal = $this->propertyExists($property))) {
            // Are we setting a public or private property?
            if ($this->isAccessible($propertyVal)) {
                $this->$propertyVal = $value;
            } else {
                $this->properties[$propertyVal] = $value;
            }

            return $this;
        } else {
            $this->getLogger()->warning(
                'Attempted to set {property} with value {value}, but the'
                . ' property has not been defined. Please define first.',
                array(
                    'property' => $property,
                    'value'    => print_r($value, true)
                )
            );
        }
    }

    /**
     * Basic check to see whether property exists.
     *
     * @param string $property   The property name being investigated.
     * @param bool   $allowRetry If set to TRUE, the check will try to format the name in underscores because
     *                           there are sometimes discrepancies between camelCaseNames and underscore_names.
     * @return bool
     */
    protected function propertyExists($property, $allowRetry = true)
    {
        if (!property_exists($this, $property) && !$this->checkAttributePrefix($property)) {
            // Convert to under_score and retry
            if ($allowRetry) {
                return $this->propertyExists($this->toUnderscores($property), false);
            } else {
                $property = false;
            }
        }

        return $property;
    }

    /**
     * Convert a string to camelCase format.
     *
     * @param       $string
     * @param  bool $capitalise Optional flag which allows for word capitalization.
     * @return mixed
     */
    public function toCamel($string, $capitalise = true)
    {
        if ($capitalise) {
            $string = ucfirst($string);
        }

        return preg_replace_callback('/_([a-z])/', function ($char) {
            return strtoupper($char[1]);
        }, $string);
    }

    /**
     * Convert string to underscore format.
     *
     * @param $string
     * @return mixed
     */
    public function toUnderscores($string)
    {
        $string = lcfirst($string);

        return preg_replace_callback('/([A-Z])/', function ($char) {
            return "_" . strtolower($char[1]);
        }, $string);
    }

    /**
     * Does the property exist in the object variable list (i.e. does it have public or protected visibility?)
     *
     * @param $property
     * @return bool
     */
    private function isAccessible($property)
    {
        return array_key_exists($property, get_object_vars($this));
    }

    /**
     * Checks the attribute $property and only permits it if the prefix is
     * in the specified $prefixes array
     *
     * This is to support extension namespaces in some services.
     *
     * @param string $property the name of the attribute
     * @return boolean
     */
    private function checkAttributePrefix($property)
    {
        if (!method_exists($this, 'getService')) {
            return false;
        }
        $prefix = strstr($property, ':', true);

        return in_array($prefix, $this->getService()->namespaces());
    }

    /**
     * Grab value out of the data array.
     *
     * @param string $property
     * @return mixed
     */
    protected function getProperty($property)
    {
        if (array_key_exists($property, $this->properties)) {
            return $this->properties[$property];
        } elseif (array_key_exists($this->toUnderscores($property), $this->properties)) {
            return $this->properties[$this->toUnderscores($property)];
        } elseif (method_exists($this, 'get' . ucfirst($property))) {
            return call_user_func(array($this, 'get' . ucfirst($property)));
        } elseif (false !== ($propertyVal = $this->propertyExists($property)) && $this->isAccessible($propertyVal)) {
            return $this->$propertyVal;
        }

        return null;
    }

    /**
     * Sets the logger.
     *
     * @param LoggerInterface $logger
     *
     * @return $this
     */
    public function setLogger(LoggerInterface $logger = null)
    {
        $this->logger = $logger;

        return $this;
    }

    /**
     * Returns the Logger object.
     *
     * @return LoggerInterface
     */
    public function getLogger()
    {
        if (null === $this->logger) {
            $this->setLogger(new Log\Logger);
        }

        return $this->logger;
    }

    /**
     * @return bool
     */
    public function hasLogger()
    {
        return (null !== $this->logger);
    }

    /**
     * @deprecated
     */
    public function url($path = null, array $query = array())
    {
        return $this->getUrl($path, $query);
    }

    /**
     * Populates the current object based on an unknown data type.
     *
     * @param  mixed $info
     * @param        bool
     * @throws Exceptions\InvalidArgumentError
     */
    public function populate($info, $setObjects = true)
    {
        if (is_string($info) || is_integer($info)) {
            $this->setProperty($this->primaryKeyField(), $info);
            $this->refresh($info);
        } elseif (is_object($info) || is_array($info)) {
            foreach ($info as $key => $value) {
                if ($key == 'metadata' || $key == 'meta') {
                    // Try retrieving existing value
                    if (null === ($metadata = $this->getProperty($key))) {
                        // If none exists, create new object
                        $metadata = new Metadata;
                    }

                    // Set values for metadata
                    $metadata->setArray($value);

                    // Set object property
                    $this->setProperty($key, $metadata);
                } elseif (!empty($this->associatedResources[$key]) && $setObjects === true) {
                    // Associated resource
                    try {
                        $resource = $this->getService()->resource($this->associatedResources[$key], $value);
                        $resource->setParent($this);

                        $this->setProperty($key, $resource);
                    } catch (Exception\ServiceException $e) {
                    }
                } elseif (!empty($this->associatedCollections[$key]) && $setObjects === true) {
                    // Associated collection
                    try {
                        $className = $this->associatedCollections[$key];
                        $options = $this->makeResourceIteratorOptions($className);
                        $iterator = ResourceIterator::factory($this, $options, $value);

                        $this->setProperty($key, $iterator);
                    } catch (Exception\ServiceException $e) {
                    }
                } elseif (!empty($this->aliases[$key])) {
                    // Sometimes we might want to preserve camelCase
                    // or covert `rax-bandwidth:bandwidth` to `raxBandwidth`
                    $this->setProperty($this->aliases[$key], $value);
                } else {
                    // Normal key/value pair
                    $this->setProperty($key, $value);
                }
            }
        } elseif (null !== $info) {
            throw new Exceptions\InvalidArgumentError(sprintf(
                Lang::translate('Argument for [%s] must be string or object'),
                get_class()
            ));
        }
    }

    /**
     * Checks the most recent JSON operation for errors.
     *
     * @throws Exceptions\JsonError
     * @codeCoverageIgnore
     */
    public static function checkJsonError()
    {
        switch (json_last_error()) {
            case JSON_ERROR_NONE:
                return;
            case JSON_ERROR_DEPTH:
                $jsonError = 'JSON error: The maximum stack depth has been exceeded';
                break;
            case JSON_ERROR_STATE_MISMATCH:
                $jsonError = 'JSON error: Invalid or malformed JSON';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $jsonError = 'JSON error: Control character error, possibly incorrectly encoded';
                break;
            case JSON_ERROR_SYNTAX:
                $jsonError = 'JSON error: Syntax error';
                break;
            case JSON_ERROR_UTF8:
                $jsonError = 'JSON error: Malformed UTF-8 characters, possibly incorrectly encoded';
                break;
            default:
                $jsonError = 'Unexpected JSON error';
                break;
        }

        if (isset($jsonError)) {
            throw new JsonError(Lang::translate($jsonError));
        }
    }

    public static function generateUuid()
    {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            // 32 bits for "time_low"
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),

            // 16 bits for "time_mid"
            mt_rand(0, 0xffff),

            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 4
            mt_rand(0, 0x0fff) | 0x4000,

            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            mt_rand(0, 0x3fff) | 0x8000,

            // 48 bits for "node"
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }

    public function makeResourceIteratorOptions($resource)
    {
        $options = array('resourceClass' => $this->stripNamespace($resource));

        if (method_exists($resource, 'jsonCollectionName')) {
            $options['key.collection'] = $resource::jsonCollectionName();
        }

        if (method_exists($resource, 'jsonCollectionElement')) {
            $options['key.collectionElement'] = $resource::jsonCollectionElement();
        }

        return $options;
    }

    public function stripNamespace($namespace)
    {
        $array = explode('\\', $namespace);

        return end($array);
    }

    protected static function getJsonHeader()
    {
        return array(HeaderConst::CONTENT_TYPE => MimeConst::JSON);
    }
}
Collection/ArrayCollection.php000060400000003526152442617120012450 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Collection;

use Countable;
use OpenCloud\Common\ArrayAccess;

/**
 * A generic, abstract collection class that allows collections to exhibit array functionality.
 *
 * @package OpenCloud\Common\Collection
 */
abstract class ArrayCollection extends ArrayAccess implements Countable
{
    /**
     * @var array The elements being held by this iterator.
     */
    protected $elements;

    /**
     * @param array $data
     */
    public function __construct(array $data = array())
    {
        $this->setElements($data);
    }

    /**
     * @return int
     */
    public function count()
    {
        return count($this->elements);
    }

    /**
     * @param array $data
     * @return $this
     */
    public function setElements(array $data = array())
    {
        $this->elements = $data;

        return $this;
    }

    /**
     * Appends a value to the container.
     *
     * @param $value
     */
    public function append($value)
    {
        $this->elements[] = $value;
    }

    /**
     * Checks to see whether a particular value exists.
     *
     * @param $value
     * @return bool
     */
    public function valueExists($value)
    {
        return array_search($value, $this->elements) !== false;
    }
}
Collection/PaginatedIterator.php000060400000021061152442617120012756 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Collection;

use Guzzle\Http\Exception\ClientErrorResponseException;
use Guzzle\Http\Url;
use Iterator;
use OpenCloud\Common\Http\Message\Formatter;

/**
 * Class ResourceIterator is tasked with iterating over resource collections - many of which are paginated. Based on
 * a base URL, the iterator will append elements based on further requests to the API. Each time this happens,
 * query parameters (marker) are updated based on the current value.
 *
 * @package OpenCloud\Common\Collection
 * @since   1.8.0
 */
class PaginatedIterator extends ResourceIterator implements Iterator
{
    const MARKER = 'marker';
    const LIMIT = 'limit';

    /**
     * @var string Used for requests which append elements.
     */
    protected $currentMarker;

    /**
     * @var \Guzzle\Http\Url The next URL for pagination
     */
    protected $nextUrl;

    protected $defaults = array(
        // Collection limits
        'limit.total'           => 10000,
        'limit.page'            => 100,

        // The "links" element key in response
        'key.links'             => 'links',

        // JSON structure
        'key.collection'        => null,
        'key.collectionElement' => null,

        // The property used as the marker
        'key.marker'            => 'name',

        // Options for "next page" request
        'request.method'        => 'GET',
        'request.headers'       => array(),
        'request.body'          => null,
        'request.curlOptions'   => array()
    );

    protected $required = array('resourceClass', 'baseUrl');

    /**
     * Basic factory method to easily instantiate a new ResourceIterator.
     *
     * @param       $parent  The parent object
     * @param array $options Iterator options
     * @param array $data    Optional data to set initially
     * @return static
     */
    public static function factory($parent, array $options = array(), array $data = null)
    {
        $list = new static();

        $list->setOptions($list->parseOptions($options))
            ->setResourceParent($parent)
            ->rewind();

        if ($data) {
            $list->setElements($data);
        } else {
            $list->appendNewCollection();
        }

        return $list;
    }


    /**
     * @param Url $url
     * @return $this
     */
    public function setBaseUrl(Url $url)
    {
        $this->baseUrl = $url;

        return $this;
    }

    public function current()
    {
        return parent::current();
    }

    public function key()
    {
        return parent::key();
    }

    /**
     * {@inheritDoc}
     * Also update the current marker.
     */
    public function next()
    {
        if (!$this->valid()) {
            return false;
        }

        $current = $this->current();

        $this->position++;
        $this->updateMarkerToCurrent();

        return $current;
    }

    /**
     * Update the current marker based on the current element. The marker will be based on a particular property of this
     * current element, so you must retrieve it first.
     */
    public function updateMarkerToCurrent()
    {
        if (!isset($this->elements[$this->position])) {
            return;
        }

        $element = $this->elements[$this->position];
        $this->setMarkerFromElement($element);
    }

    protected function setMarkerFromElement($element)
    {
        $key = $this->getOption('key.marker');

        if (isset($element->$key)) {
            $this->currentMarker = $element->$key;
        }
    }

    /**
     * {@inheritDoc}
     * Also reset current marker.
     */
    public function rewind()
    {
        parent::rewind();
        $this->currentMarker = null;
    }

    public function valid()
    {
        $totalLimit = $this->getOption('limit.total');
        if ($totalLimit !== false && $this->position >= $totalLimit) {
            return false;
        } elseif (isset($this->elements[$this->position])) {
            return true;
        } elseif ($this->shouldAppend() === true) {
            $before = $this->count();
            $this->appendNewCollection();
            return ($this->count() > $before) ? true : false;
        }

        return false;
    }

    protected function shouldAppend()
    {
        return $this->currentMarker && (
            $this->nextUrl ||
            $this->position % $this->getOption('limit.page') == 0
        );
    }

    /**
     * Append an array of standard objects to the current collection.
     *
     * @param array $elements
     * @return $this
     */
    public function appendElements(array $elements)
    {
        $this->elements = array_merge($this->elements, $elements);

        return $this;
    }

    /**
     * Retrieve a new page of elements from the API (based on a new request), parse its response, and append them to the
     * collection.
     *
     * @return $this|bool
     */
    public function appendNewCollection()
    {
        $request = $this->resourceParent
            ->getClient()
            ->createRequest(
                $this->getOption('request.method'),
                $this->constructNextUrl(),
                $this->getOption('request.headers'),
                $this->getOption('request.body'),
                $this->getOption('request.curlOptions')
            );

        try {
            $response = $request->send();
        } catch (ClientErrorResponseException $e) {
            return false;
        }

        if (!($body = Formatter::decode($response)) || $response->getStatusCode() == 204) {
            return false;
        }

        $this->nextUrl = $this->extractNextLink($body);

        return $this->appendElements($this->parseResponseBody($body));
    }

    /**
     * Based on the response body, extract the explicitly set "link" value if provided.
     *
     * @param $body
     * @return bool
     */
    public function extractNextLink($body)
    {
        $key = $this->getOption('key.links');

        $value = null;

        if (isset($body->$key)) {
            foreach ($body->$key as $link) {
                if (isset($link->rel) && $link->rel == 'next') {
                    $value = $link->href;
                    break;
                }
            }
        }

        return $value;
    }

    /**
     * Make the next page URL.
     *
     * @return Url|string
     */
    public function constructNextUrl()
    {
        if (!$url = $this->nextUrl) {
            $url = clone $this->getOption('baseUrl');
            $query = $url->getQuery();

            if (isset($this->currentMarker)) {
                $query[static::MARKER] = $this->currentMarker;
            }

            if (($limit = $this->getOption('limit.page')) && !$query->hasKey(static::LIMIT)) {
                $query[static::LIMIT] = $limit;
            }

            $url->setQuery($query);
        }

        return $url;
    }

    /**
     * Based on the response from the API, parse it for the data we need (i.e. an meaningful array of elements).
     *
     * @param $body
     * @return array
     */
    public function parseResponseBody($body)
    {
        $collectionKey = $this->getOption('key.collection');

        $data = array();

        if (is_array($body)) {
            $data = $body;
        } elseif (isset($body->$collectionKey)) {
            if (null !== ($elementKey = $this->getOption('key.collectionElement'))) {
                // The object has element levels which need to be iterated over
                foreach ($body->$collectionKey as $item) {
                    $subValues = $item->$elementKey;
                    unset($item->$elementKey);
                    $data[] = array_merge((array) $item, (array) $subValues);
                }
            } else {
                // The object has a top-level collection name only
                $data = $body->$collectionKey;
            }
        }

        return $data;
    }

    /**
     * Walk the entire collection, populating everything.
     */
    public function populateAll()
    {
        while ($this->valid()) {
            $this->next();
        }
    }
}
Collection/ResourceIterator.php000060400000014336152442617120012660 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Collection;

use Iterator;
use OpenCloud\Common\Exceptions\InvalidArgumentError;
use OpenCloud\Common\Log\Logger;

class ResourceIterator extends ArrayCollection implements Iterator
{
    /**
     * @var int Internal pointer of the iterator - reveals its current position.
     */
    protected $position;

    /**
     * @var object The parent object which resource models are instantiated from. The parent needs to have appropriate
     *             methods to instantiate the particular object.
     */
    protected $resourceParent;

    /**
     * @var array The options for this iterator.
     */
    protected $options;

    /**
     * @var array Fallback defaults if options are not explicitly set or provided.
     */
    protected $defaults = array('limit.total' => 1000);

    /**
     * @var array Required options
     */
    protected $required = array();

    public static function factory($parent, array $options = array(), array $data = array())
    {
        $iterator = new static($data);

        $iterator->setResourceParent($parent)
            ->setElements($data)
            ->setOptions($iterator->parseOptions($options))
            ->rewind();

        return $iterator;
    }

    protected function parseOptions(array $options)
    {
        $options = $options + $this->defaults;

        if ($missing = array_diff($this->required, array_keys($options))) {
            throw new InvalidArgumentError(sprintf('%s is a required option', implode(',', $missing)));
        }

        return $options;
    }

    /**
     * @param $parent
     * @return $this
     */
    public function setResourceParent($parent)
    {
        $this->resourceParent = $parent;

        return $this;
    }

    /**
     * @param array $options
     * @return $this
     */
    public function setOptions(array $options)
    {
        $this->options = $options;

        return $this;
    }

    /**
     * @return array Options for the resource iterator.
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * Set a particular option.
     *
     * @param $key
     * @param $value
     * @return $this
     */
    public function setOption($key, $value)
    {
        $this->options[$key] = $value;

        return $this;
    }

    /**
     * @param $key
     * @return null
     */
    public function getOption($key)
    {
        return (isset($this->options[$key])) ? $this->options[$key] : null;
    }

    /**
     * This method is called after self::rewind() and self::next() to check if the current position is valid.
     *
     * @return bool
     */
    public function valid()
    {
        return $this->offsetExists($this->position) && $this->position < $this->getOption('limit.total');
    }

    /**
     * Increment the current pointer by 1, and also update the current marker.
     */
    public function next()
    {
        $this->position++;

        return $this->current();
    }

    /**
     * Reset the pointer and current marker.
     */
    public function rewind()
    {
        $this->position = 0;
    }

    /**
     * @return mixed
     */
    public function current()
    {
        return $this->constructResource($this->currentElement());
    }

    /**
     * @return mixed
     */
    public function currentElement()
    {
        return $this->offsetGet($this->key());
    }

    /**
     * Using a standard object, this method populates a resource model with all the object data. It does this using a
     * whatever method the parent object has for resource creation.
     *
     * @param $object Standard object
     * @return mixed
     * @throws \OpenCloud\Common\Exceptions\CollectionException
     */
    public function constructResource($object)
    {
        $className = $this->getOption('resourceClass');

        if (substr_count($className, '\\')) {
            $array = explode('\\', $className);
            $className = end($array);
        }

        $parent = $this->resourceParent;
        $getter = sprintf('get%s', ucfirst($className));

        if (method_exists($parent, $className)) {
            // $parent->server($data)
            return call_user_func(array($parent, $className), $object);
        } elseif (method_exists($parent, $getter)) {
            // $parent->getServer($data)
            return call_user_func(array($parent, $getter), $object);
        } elseif (method_exists($parent, 'resource')) {
            // $parent->resource('Server', $data)
            return $parent->resource($className, $object);
        } else {
            return $object;
        }
    }

    /**
     * Return the current position/internal pointer.
     *
     * @return int|mixed
     */
    public function key()
    {
        return $this->position;
    }

    public function getElement($offset)
    {
        return (!$this->offsetExists($offset)) ? false : $this->constructResource($this->offsetGet($offset));
    }

    /**
     * @deprecated
     */
    public function first()
    {
        Logger::newInstance()->warning(Logger::deprecated(__METHOD__, 'getElement'));

        return $this->getElement(0);
    }

    /**
     * @todo Implement
     */
    public function sort()
    {
    }

    public function search($callback)
    {
        $return = false;

        if (!is_callable($callback)) {
            throw new InvalidArgumentError('The provided argument must be a valid callback');
        }

        foreach ($this->elements as $element) {
            $resource = $this->constructResource($element);
            if (call_user_func($callback, $resource) === true) {
                $return = $resource;
                break;
            }
        }

        return $return;
    }
}
Collection/.htaccess000044400000000424152442617120010437 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Service/ServiceBuilder.php000060400000003314152442617120011565 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Service;

use Guzzle\Http\ClientInterface;
use OpenCloud\Common\Exceptions\ServiceException;

/**
 * This object is a factory for building Service objects.
 */
class ServiceBuilder
{
    /**
     * Simple factory method for creating services.
     *
     * @param Client $client  The HTTP client object
     * @param string $class   The class name of the service
     * @param array  $options The options.
     * @return \OpenCloud\Common\Service\ServiceInterface
     * @throws ServiceException
     */
    public static function factory(ClientInterface $client, $class, array $options = array())
    {
        $name = isset($options['name']) ? $options['name'] : null;
        $urlType = isset($options['urlType']) ? $options['urlType'] : null;

        if (isset($options['region'])) {
            $region = $options['region'];
        } elseif ($client->getUser() && ($defaultRegion = $client->getUser()->getDefaultRegion())) {
            $region = $defaultRegion;
        } else {
            $region = null;
        }

        return new $class($client, null, $name, $region, $urlType);
    }
}
Service/Catalog.php000060400000003612152442617120010231 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Service;

use OpenCloud\Common\Exceptions\InvalidArgumentError;

/**
 * This object represents the service catalog returned by the Rackspace API. It contains all the services available
 * to the end-user, including specific information for each service.
 */
class Catalog
{
    /**
     * @var array Service items
     */
    private $items = array();

    /**
     * Produces a Catalog from a mixed input.
     *
     * @param  $config
     * @return Catalog
     * @throws \OpenCloud\Common\Exceptions\InvalidArgumentError
     */
    public static function factory($config)
    {
        if (is_array($config)) {
            $catalog = new self();
            foreach ($config as $item) {
                $catalog->items[] = CatalogItem::factory($item);
            }
        } elseif ($config instanceof Catalog) {
            $catalog = $config;
        } else {
            throw new InvalidArgumentError(sprintf(
                'Argument for Catalog::factory must be either an array or an '
                . 'instance of %s. You passed in: %s',
                get_class(),
                print_r($config, true)
            ));
        }

        return $catalog;
    }

    /**
     * @return array
     */
    public function getItems()
    {
        return $this->items;
    }
}
Service/ServiceInterface.php000060400000001623152442617120012100 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Service;

use Guzzle\Http\ClientInterface;

interface ServiceInterface
{
    public function setClient(ClientInterface $client);

    public function getClient();

    public function setEndpoint($endpoint);

    public function getEndpoint();

    public function getUrl();
}
Service/CatalogItem.php000060400000006533152442617120011055 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Service;

/**
 * This object represents an individual service catalog item - in other words an API Service. Each service has
 * particular information which form the basis of how it distinguishes itself, and how it executes API operations.
 */
class CatalogItem
{
    /**
     * @var string
     */
    private $name;

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

    /**
     * @var array
     */
    private $endpoints = array();

    /**
     * Construct a CatalogItem from a mixed input.
     *
     * @param  $object
     * @return CatalogItem
     */
    public static function factory($object)
    {
        $item = new self();
        $item->setName($object->name)
            ->setType($object->type)
            ->setEndpoints($object->endpoints);

        return $item;
    }

    /**
     * @param $name
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * A basic string check.
     *
     * @param  $string
     * @return bool
     */
    public function hasName($string)
    {
        return !strnatcasecmp($this->name, $string);
    }

    /**
     * @param $type
     * @return $this
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @param $string
     * @return bool
     */
    public function hasType($string)
    {
        return !strnatcasecmp($this->type, $string);
    }

    /**
     * @param  array $endpoints
     * @return $this
     */
    public function setEndpoints(array $endpoints)
    {
        $this->endpoints = $endpoints;

        return $this;
    }

    /**
     * @return array
     */
    public function getEndpoints()
    {
        return $this->endpoints;
    }

    /**
     * Using a standard data object, extract its endpoint.
     *
     * @param $region
     * @return mixed
     * @throws \OpenCloud\Common\Exceptions\EndpointError
     */
    public function getEndpointFromRegion($region)
    {
        foreach ($this->endpoints as $endpoint) {
            // Return the endpoint if it is regionless OR if the endpoint's
            // region matches the $region supplied by the caller.
            if (!isset($endpoint->region) || $endpoint->region == $region) {
                return $endpoint;
            }
        }

        throw new \OpenCloud\Common\Exceptions\EndpointError(sprintf(
            'This service [%s] does not have access to the [%s] endpoint.',
            $this->name,
            $region
        ));
    }
}
Service/Endpoint.php000060400000012233152442617120010436 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Service;

use Guzzle\Http\Url;
use OpenCloud\OpenStack;
use OpenCloud\Common\Http\Message\Formatter;
use OpenCloud\Common\Exceptions\UnsupportedVersionError;

/**
 * An endpoint serves as a location which receives and emits API interactions. It will therefore also host
 * particular API resources. Each endpoint object has different access methods - one receives network connections over
 * the public Internet, another receives traffic through an internal network. You will be able to access the latter
 * from a Server, for example, in the same Region - which will incur no bandwidth charges, and be quicker.
 */
class Endpoint
{
    /**
     * @var \Guzzle\Http\Url
     */
    private $publicUrl;

    /**
     * @var \Guzzle\Http\Url
     */
    private $privateUrl;

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

    /**
     * @param $object
     * @param string $supportedServiceVersion Service version supported by the SDK
     * @param OpenCloud\OpenStack $client OpenStack client
     * @return Endpoint
     */
    public static function factory($object, $supportedServiceVersion, OpenStack $client)
    {
        $endpoint = new self();

        if (isset($object->publicURL)) {
            $endpoint->setPublicUrl($endpoint->getVersionedUrl($object->publicURL, $supportedServiceVersion, $client));
        }
        if (isset($object->internalURL)) {
            $endpoint->setPrivateUrl($endpoint->getVersionedUrl($object->internalURL, $supportedServiceVersion, $client));
        }
        if (isset($object->region)) {
            $endpoint->setRegion($object->region);
        }

        return $endpoint;
    }

    /**
     * @param $publicUrl
     * @return $this
     */
    public function setPublicUrl(Url $publicUrl)
    {
        $this->publicUrl = $publicUrl;

        return $this;
    }

    /**
     * @return Url
     */
    public function getPublicUrl()
    {
        return $this->publicUrl;
    }

    /**
     * @param $privateUrl
     * @return $this
     */
    public function setPrivateUrl(Url $privateUrl)
    {
        $this->privateUrl = $privateUrl;

        return $this;
    }

    /**
     * @return Url
     */
    public function getPrivateUrl()
    {
        return $this->privateUrl;
    }

    /**
     * @param $region
     * @return $this
     */
    public function setRegion($region)
    {
        $this->region = $region;

        return $this;
    }

    /**
     * @return string
     */
    public function getRegion()
    {
        return $this->region;
    }

    /**
     * Returns the endpoint URL with a version in it
     *
     * @param string $url Endpoint URL
     * @param string $supportedServiceVersion Service version supported by the SDK
     * @param OpenCloud\OpenStack $client OpenStack client
     * @return Guzzle/Http/Url Endpoint URL with version in it
     */
    private function getVersionedUrl($url, $supportedServiceVersion, OpenStack $client)
    {
        $versionRegex = '/\/[vV][0-9][0-9\.]*/';
        if (1 === preg_match($versionRegex, $url)) {
            // URL has version in it; use it as-is
            return Url::factory($url);
        }

        // If there is no version in $url but no $supportedServiceVersion
        // is specified, just return $url as-is but log a warning
        if (is_null($supportedServiceVersion)) {
            $client->getLogger()->warning('Service version supported by SDK not specified. Using versionless service URL as-is, without negotiating version.');
            return Url::factory($url);
        }

        // Make GET request to URL
        $response = Formatter::decode($client->get($url)->send());

        // Attempt to parse response and determine URL for given $version
        if (!isset($response->versions) || !is_array($response->versions)) {
            throw new UnsupportedVersionError('Could not negotiate version with service.');
        }

        foreach ($response->versions as $version) {
            if (($version->status == 'CURRENT' || $version->status == 'SUPPORTED')
                && $version->id == $supportedServiceVersion) {
                foreach ($version->links as $link) {
                    if ($link->rel == 'self') {
                        return Url::factory($link->href);
                    }
                }
            }
        }

        // If we've reached this point, we could not find a versioned
        // URL in the response; throw an error
        throw new UnsupportedVersionError(sprintf(
            'SDK supports version %s which is not currently provided by service.',
            $supportedServiceVersion
        ));
    }
}
Service/NovaService.php000060400000003653152442617120011110 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Service;

use OpenCloud\Compute\Resource\Flavor;

/**
 * NovaService serves as an additional abstraction for particular OpenStack services that exhibit shared functionality.
 */
abstract class NovaService extends CatalogService
{
    /**
     * Returns a flavor from the service
     *
     * @param string|null $id
     * @return Flavor
     */
    public function flavor($id = null)
    {
        return new Flavor($this, $id);
    }

    /**
     * Returns a list of Flavor objects
     *
     * @param boolean $details Returns full details or not.
     * @param array   $filter  Array for creating queries
     * @return Collection
     */
    public function flavorList($details = true, array $filter = array())
    {
        $path = Flavor::resourceName();

        if ($details === true) {
            $path .= '/detail';
        }

        return $this->collection('OpenCloud\Compute\Resource\Flavor', $this->getUrl($path, $filter));
    }

    /**
     * Loads the available namespaces from the /extensions resource
     */
    protected function loadNamespaces()
    {
        foreach ($this->getExtensions() as $object) {
            $this->namespaces[] = $object->alias;
        }

        if (!empty($this->additionalNamespaces)) {
            $this->namespaces += $this->additionalNamespaces;
        }
    }
}
Service/.htaccess000044400000000424152442617120007744 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Service/AbstractService.php000060400000012527152442617120011750 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Service;

use Guzzle\Http\ClientInterface;
use OpenCloud\Common\Base;
use OpenCloud\Common\Collection\PaginatedIterator;
use OpenCloud\Common\Exceptions;

/**
 * This class defines a cloud service; a relationship between a specific OpenStack
 * and a provided service, represented by a URL in the service catalog.
 *
 * Because Service is an abstract class, it cannot be called directly. Provider
 * services such as Rackspace Cloud Servers or OpenStack Swift are each
 * subclassed from Service.
 */
abstract class AbstractService extends Base implements ServiceInterface
{
    /**
     * @var \OpenCloud\Common\Http\Client The client which interacts with the API.
     */
    protected $client;

    /**
     * @var \OpenCloud\Common\Service\Endpoint The endpoint for this service.
     */
    protected $endpoint;

    /**
     * @var array A collection of resource models that this service has control over.
     */
    protected $resources = array();

    /**
     * @var array Namespaces for this service.
     */
    protected $namespaces = array();

    /**
     * @param ClientInterface $client
     */
    public function setClient(ClientInterface $client)
    {
        $this->client = $client;
    }

    /**
     * @return \OpenCloud\Common\Http\Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * @param Endpoint $endpoint
     */
    public function setEndpoint($endpoint)
    {
        $this->endpoint = $endpoint;
    }

    /**
     * @return \OpenCloud\Common\Service\Endpoint
     */
    public function getEndpoint()
    {
        return $this->endpoint;
    }

    /**
     * Get all associated resources for this service.
     *
     * @access public
     * @return array
     */
    public function getResources()
    {
        return $this->resources;
    }

    /**
     * Internal method for accessing child namespace from parent scope.
     *
     * @return type
     */
    protected function getCurrentNamespace()
    {
        $namespace = get_class($this);

        return substr($namespace, 0, strrpos($namespace, '\\'));
    }

    /**
     * Resolves FQCN for local resource.
     *
     * @param  $resourceName
     * @return string
     * @throws \OpenCloud\Common\Exceptions\UnrecognizedServiceError
     */
    protected function resolveResourceClass($resourceName)
    {
        $className = substr_count($resourceName, '\\')
            ? $resourceName
            : $this->getCurrentNamespace() . '\\Resource\\' . ucfirst($resourceName);

        if (!class_exists($className)) {
            throw new Exceptions\UnrecognizedServiceError(sprintf(
                '%s resource does not exist, please try one of the following: %s',
                $resourceName,
                implode(', ', $this->getResources())
            ));
        }

        return $className;
    }

    /**
     * Factory method for instantiating resource objects.
     *
     * @param  string $resourceName
     * @param  mixed  $info   (default: null)
     * @param  mixed  $parent The parent object
     * @return object
     */
    public function resource($resourceName, $info = null, $parent = null)
    {
        $className = $this->resolveResourceClass($resourceName);

        $resource = new $className($this);

        if ($parent) {
            $resource->setParent($parent);
        }

        $resource->populate($info);

        return $resource;
    }

    /**
     * Factory method for instantiating a resource collection.
     *
     * @param string      $resourceName
     * @param string|null $url
     * @param string|null $parent
     * @return PaginatedIterator
     */
    public function resourceList($resourceName, $url = null, $parent = null)
    {
        $className = $this->resolveResourceClass($resourceName);

        return $this->collection($className, $url, $parent);
    }

    /**
     * @codeCoverageIgnore
     */
    public function collection($class, $url = null, $parent = null, $data = null)
    {
        if (!$parent) {
            $parent = $this;
        }

        if (!$url) {
            $resource = $this->resolveResourceClass($class);
            $url = $parent->getUrl($resource::resourceName());
        }

        $options = $this->makeResourceIteratorOptions($this->resolveResourceClass($class));
        $options['baseUrl'] = $url;

        return PaginatedIterator::factory($parent, $options, $data);
    }

    /**
     * @deprecated
     */
    public function namespaces()
    {
        return $this->getNamespaces();
    }

    /**
     * Returns a list of supported namespaces
     *
     * @return array
     */
    public function getNamespaces()
    {
        return (isset($this->namespaces) && is_array($this->namespaces))
            ? $this->namespaces
            : array();
    }
}
Service/CatalogService.php000060400000017426152442617120011562 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Service;

use Guzzle\Http\ClientInterface;
use Guzzle\Http\Exception\BadResponseException;
use Guzzle\Http\Url;
use OpenCloud\Common\Base;
use OpenCloud\Common\Exceptions;
use OpenCloud\Common\Http\Message\Formatter;
use OpenCloud\OpenStack;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

abstract class CatalogService extends AbstractService
{
    const DEFAULT_URL_TYPE = 'publicURL';
    const SUPPORTED_VERSION = null;

    /**
     * @var string The type of this service, as set in Catalog.
     */
    private $type;

    /**
     * @var string The name of this service, as set in Catalog.
     */
    private $name;

    /**
     * @var string The chosen region(s) for this service.
     */
    private $region;

    /**
     * @var string Either 'publicURL' or 'internalURL'.
     */
    private $urlType;

    /**
     * @var bool Indicates whether a service is "regionless" or not. Defaults to FALSE because nearly all services
     *           are region-specific.
     */
    protected $regionless = false;

    /**
     * Creates a service object, based off the specified client.
     *
     * The service's URL is defined in the client's serviceCatalog; it
     * uses the $type, $name, $region, and $urlType to find the proper endpoint
     * and set it. If it cannot find a URL in the service catalog that matches
     * the criteria, then an exception is thrown.
     *
     * @param Client $client  Client object
     * @param string $type    Service type (e.g. 'compute')
     * @param string $name    Service name (e.g. 'cloudServersOpenStack')
     * @param string $region  Service region (e.g. 'DFW', 'ORD', 'IAD', 'LON', 'SYD' or 'HKG')
     * @param string $urlType Either 'publicURL' or 'internalURL'
     */
    public function __construct(ClientInterface $client, $type = null, $name = null, $region = null, $urlType = null)
    {
        if (($client instanceof Base || $client instanceof OpenStack) && $client->hasLogger()) {
            $this->setLogger($client->getLogger());
        }

        $this->setClient($client);

        $this->name = $name ? : static::DEFAULT_NAME;
        $this->region = $region;

        $this->region = $region;
        if ($this->regionless !== true && !$this->region) {
            throw new Exceptions\ServiceException(sprintf(
                'The %s service must have a region set. You can either pass in a region string as an argument param, or'
                . ' set a default region for your user account by executing User::setDefaultRegion and ::update().',
                $this->name
            ));
        }

        $this->type = $type ? : static::DEFAULT_TYPE;
        $this->urlType = $urlType ? : static::DEFAULT_URL_TYPE;
        $this->setEndpoint($this->findEndpoint());

        $this->client->setBaseUrl($this->getBaseUrl());

        if ($this instanceof EventSubscriberInterface) {
            $this->client->getEventDispatcher()->addSubscriber($this);
        }
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @return string
     */
    public function getRegion()
    {
        return $this->region;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getUrlType()
    {
        return $this->urlType;
    }

    /**
     * @deprecated
     */
    public function region()
    {
        return $this->getRegion();
    }

    /**
     * @deprecated
     */
    public function name()
    {
        return $this->name;
    }

    /**
     * Returns the URL for the Service
     *
     * @param  string $path  URL path segment
     * @param  array  $query Array of query pairs
     * @return Guzzle\Http\Url
     */
    public function getUrl($path = null, array $query = array())
    {
        return Url::factory($this->getBaseUrl())
            ->addPath($path)
            ->setQuery($query);
    }

    /**
     * @deprecated
     */
    public function url($path = null, array $query = array())
    {
        return $this->getUrl($path, $query);
    }

    /**
     * Returns the /extensions for the service
     *
     * @api
     * @return array of objects
     */
    public function getExtensions()
    {
        $ext = $this->getMetaUrl('extensions');

        return (is_object($ext) && isset($ext->extensions)) ? $ext->extensions : array();
    }

    /**
     * Returns the limits for the service
     *
     * @return array of limits
     */
    public function limits()
    {
        $limits = $this->getMetaUrl('limits');

        return (is_object($limits)) ? $limits->limits : array();
    }

    /**
     * Extracts the appropriate endpoint from the service catalog based on the
     * name and type of a service, and sets for further use.
     *
     * @return \OpenCloud\Common\Service\Endpoint
     * @throws \OpenCloud\Common\Exceptions\EndpointError
     */
    private function findEndpoint()
    {
        if (!$this->getClient()->getCatalog()) {
            $this->getClient()->authenticate();
        }

        $catalog = $this->getClient()->getCatalog();

        // Search each service to find The One
        foreach ($catalog->getItems() as $service) {
            if ($service->hasType($this->type) && $service->hasName($this->name)) {
                return Endpoint::factory($service->getEndpointFromRegion($this->region), static::SUPPORTED_VERSION, $this->getClient());
            }
        }

        throw new Exceptions\EndpointError(sprintf(
            'No endpoints for service type [%s], name [%s], region [%s] and urlType [%s]',
            $this->type,
            $this->name,
            $this->region,
            $this->urlType
        ));
    }

    /**
     * Constructs a specified URL from the subresource
     *
     * Given a subresource (e.g., "extensions"), this constructs the proper
     * URL and retrieves the resource.
     *
     * @param string $resource The resource requested; should NOT have slashes
     *                         at the beginning or end
     * @return \stdClass object
     */
    private function getMetaUrl($resource)
    {
        $url = clone $this->getBaseUrl();
        $url->addPath($resource);
        try {
            $response = $this->getClient()->get($url)->send();

            return Formatter::decode($response);
        } catch (BadResponseException $e) {
            // @codeCoverageIgnoreStart
            return array();
            // @codeCoverageIgnoreEnd
        }
    }

    /**
     * Get the base URL for this service, based on the set URL type.
     * @return \Guzzle\Http\Url
     * @throws \OpenCloud\Common\Exceptions\ServiceException
     */
    public function getBaseUrl()
    {
        $url = ($this->urlType == 'publicURL')
            ? $this->endpoint->getPublicUrl()
            : $this->endpoint->getPrivateUrl();

        if ($url === null) {
            throw new Exceptions\ServiceException(sprintf(
                'The base %s could not be found. Perhaps the service '
                . 'you are using requires a different URL type, or does '
                . 'not support this region.',
                $this->urlType
            ));
        }

        return $url;
    }
}
ArrayAccess.php000060400000002303152442617120007453 0ustar00<?php

namespace OpenCloud\Common;

class ArrayAccess implements \ArrayAccess
{
    protected $elements;

    public function __construct($data = array())
    {
        $this->elements = (array) $data;
    }

    /**
     * Sets a value to a particular offset.
     *
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        if ($offset === null) {
            $this->elements[] = $value;
        } else {
            $this->elements[$offset] = $value;
        }
    }

    /**
     * Checks to see whether a particular offset key exists.
     *
     * @param mixed $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->elements);
    }

    /**
     * Unset a particular key.
     *
     * @param mixed $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->elements[$offset]);
    }

    /**
     * Get the value for a particular offset key.
     *
     * @param mixed $offset
     * @return mixed|null
     */
    public function offsetGet($offset)
    {
        return $this->offsetExists($offset) ? $this->elements[$offset] : null;
    }
}
Lang.php000060400000001644152442617120006143 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common;

class Lang
{
    public static function translate($word = null)
    {
        return $word;
    }

    public static function noslash($str)
    {
        while ($str && (substr($str, -1) == '/')) {
            $str = substr($str, 0, strlen($str) - 1);
        }

        return $str;
    }
}
Constants/Size.php000060400000001377152442617120010153 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Constants;

class Size
{
    const KB = 1024;
    const MB = 1048576;
    const GB = 1073741824;
    const TB = 1099511627776;
}
Constants/State.php000060400000001425152442617120010313 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Constants;

class State
{
    const ACTIVE = 'ACTIVE';
    const ERROR = 'ERROR';
    const DEFAULT_TIMEOUT = 3600;
    const DEFAULT_INTERVAL = 10;
}
Constants/Service.php000060400000001350152442617120010630 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Constants;

class Service
{
    const INTERNAL_URL = 'internalUrl';
    const PUBLIC_URL = 'publicUrl';
}
Constants/Mime.php000060400000001335152442617120010122 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Constants;

class Mime
{
    const JSON = 'application/json';
    const TEXT = 'text/plain';
}
Constants/Datetime.php000060400000001714152442617120010770 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Constants;

class Datetime
{
    /**
     * Values in s.
     */
    const SECOND = 1;
    const MINUTE = 60;
    const HOUR = 3600;
    const DAY = 86400;

    /**
     * Values in ms.
     */
    const MILLISECOND = 1;
    const SECOND_M = 1000;
    const MINUTE_M = 60000;
    const HOUR_M = 3600000;
    const DAY_M = 86400000;
}
Constants/.htaccess000044400000000424152442617120010320 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Constants/Header.php000060400000004721152442617120010425 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Constants;

/**
 * Standard Header Field names as defined in RFC2616.
 *
 * @link    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
 * @package OpenCloud\Common\Constants
 */
class Header
{
    const ACCEPT = 'Accept';
    const ACCEPT_CHARSET = 'Accept-Charset';
    const ACCEPT_ENCODING = 'Accept-Encoding';
    const ACCEPT_LANGUAGE = 'Accept-Language';
    const ACCEPT_RANGES = 'Accept-Ranges';
    const AGE = 'Age';
    const ALLOW = 'Allow';
    const AUTHORIZATION = 'Authorization';
    const CACHE_CONTROL = 'Cache-Control';
    const CONNECTION = 'Connection';
    const CONTENT_ENCODING = 'Content-Encoding';
    const CONTENT_LANGUAGE = 'Content-Language';
    const CONTENT_LENGTH = 'Content-Length';
    const CONTENT_LOCATION = 'Content-Location';
    const CONTENT_MD5 = 'Content-MD5';
    const CONTENT_RANGE = 'Content-Range';
    const CONTENT_TYPE = 'Content-Type';
    const DATE = 'Date';
    const ETAG = 'ETag';
    const EXPECT = 'Expect';
    const EXPIRES = 'Expires';
    const FROM = 'From';
    const HOST = 'Host';
    const IF_MATCH = 'If-Match';
    const IF_MODIFIED_SINCE = 'If-Modified-Since';
    const IF_NONE_MATCH = 'If-None-Match';
    const IF_RANGE = 'If-Range';
    const IF_UNMODIFIED_SINCE = 'If-Unmodified-Since';
    const LAST_MODIFIED = 'Last-Modified';
    const LOCATION = 'Location';
    const MAX_FORWARDS = 'Max-Forwards';
    const PRAGMA = 'Pragma';
    const PROXY_AUTHENTICATION = 'Proxy-Authenticate';
    const PROXY_AUTHORIZATION = 'Proxy-Authorization';
    const RANGE = 'Range';
    const REFERER = 'Referer';
    const RETRY_AFTER = 'Retry-After';
    const SERVER = 'Server';
    const TE = 'TE';
    const TRAILER = 'Trailer';
    const TRANSFER_ENCODING = 'Transfer-Encoding';
    const UPGRADE = 'Upgrade';
    const USER_AGENT = 'User-Agent';
    const VARY = 'Vary';
    const VIA = 'Via';
}
Http/Message/.htaccess000044400000000424152442617120010647 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Http/Message/Formatter.php000060400000003036152442617120011525 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Http\Message;

use Guzzle\Http\Message\Response;
use OpenCloud\Common\Constants\Header;
use OpenCloud\Common\Constants\Mime;
use OpenCloud\Common\Exceptions\JsonError;

class Formatter
{
    public static function decode(Response $response)
    {
        if (strpos($response->getHeader(Header::CONTENT_TYPE), Mime::JSON) !== false) {
            $string = (string) $response->getBody();
            $response = json_decode($string);
            self::checkJsonError($string);

            return $response;
        }
    }

    public static function encode($body)
    {
        return json_encode($body);
    }

    public static function checkJsonError($string = null)
    {
        if (json_last_error()) {
            $error = sprintf('%s', json_last_error_msg());
            $message = ($string) ? sprintf('%s trying to decode: %s', $error, $string) : $error;
            throw new JsonError($message);
        }
    }
}
Http/Message/RequestSubscriber.php000060400000002576152442617120013246 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Http\Message;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Description of RequestSubscriber
 */
class RequestSubscriber implements EventSubscriberInterface
{
    public static function getInstance()
    {
        return new self();
    }

    public static function getSubscribedEvents()
    {
        return array(
            'curl.callback.progress' => 'doCurlProgress'
        );
    }

    /**
     * @param $options
     * @return mixed
     * @codeCoverageIgnore
     */
    public function doCurlProgress($options)
    {
        $curlOptions = $options['request']->getCurlOptions();

        if ($curlOptions->hasKey('progressCallback')) {
            return call_user_func($curlOptions->get('progressCallback'));
        }
    }
}
Http/Client.php000060400000003311152442617120007410 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Http;

use Guzzle\Http\Client as GuzzleClient;
use Guzzle\Http\Curl\CurlVersion;
use OpenCloud\Common\Exceptions\UnsupportedVersionError;

/**
 * Base client object which handles HTTP transactions. Each service is based off of a Client which acts as a
 * centralized parent.
 */
class Client extends GuzzleClient
{
    const VERSION = '1.9.0';
    const MINIMUM_PHP_VERSION = '5.3.0';

    public function __construct($baseUrl = '', $config = null)
    {
        // @codeCoverageIgnoreStart
        if (PHP_VERSION < self::MINIMUM_PHP_VERSION) {
            throw new UnsupportedVersionError(sprintf(
                'You must have PHP version >= %s installed.',
                self::MINIMUM_PHP_VERSION
            ));
        }
        // @codeCoverageIgnoreEnd

        parent::__construct($baseUrl, $config);
    }

    public function getDefaultUserAgent()
    {
        return 'OpenCloud/' . self::VERSION
        . ' cURL/' . CurlVersion::getInstance()->get('version')
        . ' PHP/' . PHP_VERSION;
    }

    public function getUserAgent()
    {
        return $this->userAgent;
    }
}
Http/.htaccess000044400000000424152442617120007263 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Metadata.php000060400000006004152442617120006775 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common;

/**
 * The Metadata class represents either Server or Image metadata
 */
class Metadata extends Base implements \Countable
{
    /**
     * @var array Internal data store.
     */
    protected $metadata = array();

    /**
     * This setter overrides the base one, since the metadata key can be
     * anything
     *
     * @param string $property
     * @param string $value
     * @return void
     */
    public function __set($property, $value)
    {
        return $this->setProperty($property, $value);
    }

    public function __get($key)
    {
        return $this->getProperty($key);
    }

    public function propertyExists($property, $allowRetry = true)
    {
        return isset($this->metadata[strtolower($property)])
        || parent::propertyExists($property, $allowRetry);
    }

    public function getProperty($property)
    {
        return $this->propertyExists($property) ? $this->metadata[strtolower($property)] : null;
    }

    public function setProperty($property, $value)
    {
        $this->metadata[strtolower($property)] = $value;
    }

    public function __isset($property)
    {
        return $this->propertyExists($property);
    }

    /**
     * Returns the list of keys defined
     *
     * @return array
     */
    public function keylist()
    {
        return $this->metadata;
    }

    /**
     * Sets metadata values from an array, with optional prefix
     *
     * If $prefix is provided, then only array keys that match the prefix
     * are set as metadata values, and $prefix is stripped from the key name.
     *
     * @param array  $values an array of key/value pairs to set
     * @param string $prefix if provided, a prefix that is used to identify
     *                       metadata values. For example, you can set values from headers
     *                       for a Container by using $prefix='X-Container-Meta-'.
     * @return void
     */
    public function setArray($values, $prefix = null)
    {
        if (empty($values)) {
            return false;
        }

        foreach ($values as $key => $value) {
            if ($prefix && strpos($key, $prefix) === 0) {
                $key = substr($key, strlen($prefix));
            }
            $this->setProperty($key, $value);
        }
    }

    public function toArray()
    {
        return $this->metadata;
    }

    public function count()
    {
        return count($this->metadata);
    }
}
Exceptions/NetworkError.php000060400000001265152442617130012046 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class NetworkError extends \Exception
{
}
Exceptions/IOError.php000060400000001260152442617130010717 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class IOError extends \Exception
{
}
Exceptions/HttpTimeoutError.php000060400000001271152442617130012700 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class HttpTimeoutError extends \Exception
{
}
Exceptions/UnknownError.php000060400000001265152442617130012054 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UnknownError extends \Exception
{
}
Exceptions/UserListError.php000060400000001266152442617130012170 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UserListError extends \Exception
{
}
Exceptions/UpdateError.php000060400000001264152442617130011636 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UpdateError extends \Exception
{
}
Exceptions/EmptyResponseError.php000060400000001273152442617130013231 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class EmptyResponseError extends \Exception
{
}
Exceptions/AttributeError.php000060400000001267152442617130012362 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class AttributeError extends \Exception
{
}
Exceptions/ResourceBucketException.php000060400000001300152442617130014175 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ResourceBucketException extends \Exception
{
}
Exceptions/AsyncTimeoutError.php000060400000001272152442617130013037 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class AsyncTimeoutError extends \Exception
{
}
Exceptions/UserUpdateError.php000060400000001270152442617130012472 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UserUpdateError extends \Exception
{
}
Exceptions/MisMatchedChecksumError.php000060400000001300152442617130014104 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MisMatchedChecksumError extends \Exception
{
}
Exceptions/DatabaseCreateError.php000060400000001274152442617130013245 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class DatabaseCreateError extends \Exception
{
}
Exceptions/UnknownParameterError.php000060400000001276152442617130013717 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UnknownParameterError extends \Exception
{
}
Exceptions/VolumeError.php000060400000001264152442617130011663 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class VolumeError extends \Exception
{
}
Exceptions/MissingValueError.php000060400000001272152442617130013021 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MissingValueError extends \Exception
{
}
Exceptions/MetadataError.php000060400000001266152442617130012136 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MetadataError extends \Exception
{
}
Exceptions/EndpointError.php000060400000001266152442617130012176 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class EndpointError extends \Exception
{
}
Exceptions/HttpForbiddenError.php000060400000001273152442617130013150 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class HttpForbiddenError extends \Exception
{
}
Exceptions/InstanceDeleteError.php000060400000001274152442617130013304 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InstanceDeleteError extends \Exception
{
}
Exceptions/ServerUrlError.php000060400000001267152442617130012350 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServerUrlError extends \Exception
{
}
Exceptions/IdRequiredError.php000060400000001270152442617130012446 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class IdRequiredError extends \Exception
{
}
Exceptions/ObjectCopyError.php000060400000001270152442617130012452 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ObjectCopyError extends \Exception
{
}
Exceptions/HttpError.php000060400000001262152442617130011331 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class HttpError extends \Exception
{
}
Exceptions/MetadataCreateError.php000060400000001274152442617130013261 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MetadataCreateError extends \Exception
{
}
Exceptions/.htaccess000044400000000424152442617130010466 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Exceptions/LoggingException.php000060400000001310152442617130012637 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

use Exception;

class LoggingException extends Exception
{
}
Exceptions/ContainerNotFoundError.php000060400000001277152442617130014017 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ContainerNotFoundError extends \Exception
{
}
Exceptions/NoContentTypeError.php000060400000001273152442617130013165 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class NoContentTypeError extends \Exception
{
}
Exceptions/NetworkUpdateError.php000060400000001273152442617130013210 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class NetworkUpdateError extends \Exception
{
}
Exceptions/MetadataPrefixError.php000060400000001274152442617130013313 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MetadataPrefixError extends \Exception
{
}
Exceptions/ServerDeleteError.php000060400000001272152442617130013004 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServerDeleteError extends \Exception
{
}
Exceptions/InstanceError.php000060400000001266152442617130012162 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InstanceError extends \Exception
{
}
Exceptions/ContainerNotEmptyError.php000060400000001277152442617130014042 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ContainerNotEmptyError extends \Exception
{
}
Exceptions/SnapshotError.php000060400000001266152442617130012215 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class SnapshotError extends \Exception
{
}
Exceptions/HttpOverLimitError.php000060400000001273152442617130013166 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class HttpOverLimitError extends \Exception
{
}
Exceptions/UnrecognizedServiceError.php000060400000001301152442617130014361 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UnrecognizedServiceError extends \Exception
{
}
Exceptions/MetadataDeleteError.php000060400000001274152442617130013260 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MetadataDeleteError extends \Exception
{
}
Exceptions/ServerActionError.php000060400000001272152442617130013017 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServerActionError extends \Exception
{
}
Exceptions/ServerCreateError.php000060400000001272152442617130013005 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServerCreateError extends \Exception
{
}
Exceptions/VolumeTypeError.php000060400000001270152442617130012522 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class VolumeTypeError extends \Exception
{
}
Exceptions/CollectionException.php000060400000001274152442617130013355 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class CollectionException extends \Exception
{
}
Exceptions/InstanceCreateError.php000060400000001274152442617130013305 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InstanceCreateError extends \Exception
{
}
Exceptions/InstanceNotFound.php000060400000001271152442617130012621 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InstanceNotFound extends \Exception
{
}
Exceptions/FlavorError.php000060400000001264152442617130011645 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class FlavorError extends \Exception
{
}
Exceptions/DatabaseDeleteError.php000060400000001274152442617130013244 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class DatabaseDeleteError extends \Exception
{
}
Exceptions/HttpResponseException.php000060400000002114152442617130013712 0ustar00<?php

namespace OpenCloud\Common\Exceptions;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

class HttpResponseException extends \Exception
{
    protected $response;
    protected $request;

    /**
     * Set the request that caused the exception
     *
     * @param RequestInterface $request Request to set
     *
     * @return RequestException
     */
    public function setRequest(RequestInterface $request)
    {
        $this->request = $request;

        return $this;
    }

    /**
     * Get the request that caused the exception
     *
     * @return RequestInterface
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * Set the response that caused the exception
     *
     * @param Response $response Response to set
     */
    public function setResponse(Response $response)
    {
        $this->response = $response;
    }

    /**
     * Get the response that caused the exception
     *
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }
}
Exceptions/ForbiddenOperationException.php000060400000001217152442617130015034 0ustar00<?php

namespace OpenCloud\Common\Exceptions;

use Guzzle\Http\Exception\BadResponseException;

class ForbiddenOperationException extends HttpResponseException
{
    public static function factory(BadResponseException $exception)
    {
        $response = $exception->getResponse();

        $message = sprintf(
            "This operation was forbidden; the API returned a %s status code with this message:\n%s",
            $response->getStatusCode(),
            (string) $response->getBody()
        );

        $e = new self($message);
        $e->setResponse($response);
        $e->setRequest($exception->getRequest());

        return $e;
    }
}
Exceptions/MetadataKeyError.php000060400000001271152442617130012603 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MetadataKeyError extends \Exception
{
}
Exceptions/CdnNotAvailableError.php000060400000001275152442617130013404 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class CdnNotAvailableError extends \Exception
{
}
Exceptions/CdnHttpError.php000060400000001265152442617130011761 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class CdnHttpError extends \Exception
{
}
Exceptions/UserNameError.php000060400000001266152442617130012135 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UserNameError extends \Exception
{
}
Exceptions/InvalidIpTypeError.php000060400000001273152442617130013135 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InvalidIpTypeError extends \Exception
{
}
Exceptions/RecordTypeError.php000060400000001270152442617130012471 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class RecordTypeError extends \Exception
{
}
Exceptions/HttpUrlError.php000060400000001265152442617130012017 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class HttpUrlError extends \Exception
{
}
Exceptions/CreateUpdateError.php000060400000001272152442617130012761 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class CreateUpdateError extends \Exception
{
}
Exceptions/ContainerDeleteError.php000060400000001275152442617130013463 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ContainerDeleteError extends \Exception
{
}
Exceptions/UserDeleteError.php000060400000001270152442617130012452 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UserDeleteError extends \Exception
{
}
Exceptions/UnsupportedVersionError.php000060400000001300152442617130014301 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UnsupportedVersionError extends \Exception
{
}
Exceptions/NoNameError.php000060400000001264152442617130011571 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class NoNameError extends \Exception
{
}
Exceptions/UrlError.php000060400000001261152442617130011153 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UrlError extends \Exception
{
}
Exceptions/DocumentError.php000060400000001266152442617130012174 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class DocumentError extends \Exception
{
}
Exceptions/ServerJsonError.php000060400000001270152442617130012511 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServerJsonError extends \Exception
{
}
Exceptions/DomainError.php000060400000001264152442617130011623 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class DomainError extends \Exception
{
}
Exceptions/BaseException.php000060400000001266152442617130012135 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class BaseException extends \Exception
{
}
Exceptions/RuntimeException.php000060400000001271152442617130012702 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class RuntimeException extends \Exception
{
}
Exceptions/UnsupportedFeatureExtension.php000060400000001304152442617130015136 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UnsupportedFeatureExtension extends \Exception
{
}
Exceptions/InvalidRequestError.php000060400000001274152442617130013354 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InvalidRequestError extends \Exception
{
}
Exceptions/HttpRetryError.php000060400000001267152442617130012364 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class HttpRetryError extends \Exception
{
}
Exceptions/DeleteError.php000060400000001264152442617130011616 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class DeleteError extends \Exception
{
}
Exceptions/NetworkUrlError.php000060400000001270152442617130012525 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class NetworkUrlError extends \Exception
{
}
Exceptions/InvalidArgumentError.php000060400000001275152442617130013507 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InvalidArgumentError extends \Exception
{
}
Exceptions/InvalidIdTypeError.php000060400000001273152442617130013121 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InvalidIdTypeError extends \Exception
{
}
Exceptions/AsyncError.php000060400000001263152442617130011470 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class AsyncError extends \Exception
{
}
Exceptions/ResourceNotFoundException.php000060400000001246152442617130014525 0ustar00<?php

namespace OpenCloud\Common\Exceptions;

use Guzzle\Http\Exception\BadResponseException;

class ResourceNotFoundException extends HttpResponseException
{
    public static function factory(BadResponseException $exception)
    {
        $response = $exception->getResponse();

        $message = sprintf(
            "This resource you were looking for could not be found; the API returned a %s status code with this message:\n%s",
            $response->getStatusCode(),
            (string) $response->getBody()
        );

        $e = new self($message);
        $e->setResponse($response);
        $e->setRequest($exception->getRequest());

        return $e;
    }
}
Exceptions/NetworkDeleteError.php000060400000001273152442617130013170 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class NetworkDeleteError extends \Exception
{
}
Exceptions/ImageError.php000060400000001263152442617130011435 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ImageError extends \Exception
{
}
Exceptions/ServerUpdateError.php000060400000001272152442617130013024 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServerUpdateError extends \Exception
{
}
Exceptions/ServerIpsError.php000060400000001267152442617130012341 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServerIpsError extends \Exception
{
}
Exceptions/InstanceUpdateError.php000060400000001274152442617130013324 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InstanceUpdateError extends \Exception
{
}
Exceptions/ContainerNameError.php000060400000001273152442617130013137 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ContainerNameError extends \Exception
{
}
Exceptions/ObjectError.php000060400000001264152442617130011622 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ObjectError extends \Exception
{
}
Exceptions/TempUrlMethodError.php000060400000001273152442617130013145 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class TempUrlMethodError extends \Exception
{
}
Exceptions/DatabaseListError.php000060400000001272152442617130012753 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class DatabaseListError extends \Exception
{
}
Exceptions/AuthenticationError.php000060400000001274152442617130013374 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class AuthenticationError extends \Exception
{
}
Exceptions/CredentialError.php000060400000001270152442617130012463 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class CredentialError extends \Exception
{
}
Exceptions/AsyncHttpError.php000060400000001267152442617130012334 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class AsyncHttpError extends \Exception
{
}
Exceptions/ObjFetchError.php000060400000001266152442617130012102 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ObjFetchError extends \Exception
{
}
Exceptions/CdnError.php000060400000001261152442617130011115 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class CdnError extends \Exception
{
}
Exceptions/RebuildError.php000060400000001265152442617130012003 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class RebuildError extends \Exception
{
}
Exceptions/HttpUnauthorizedError.php000060400000001276152442617130013740 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class HttpUnauthorizedError extends \Exception
{
}
Exceptions/DatabaseNameError.php000060400000001272152442617130012720 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class DatabaseNameError extends \Exception
{
}
Exceptions/InvalidTemplateError.php000060400000001275152442617130013500 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InvalidTemplateError extends \Exception
{
}
Exceptions/UnsupportedExtensionError.php000060400000001302152442617130014632 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UnsupportedExtensionError extends \Exception
{
}
Exceptions/NameError.php000060400000001262152442617130011272 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class NameError extends \Exception
{
}
Exceptions/ContainerError.php000060400000001267152442617130012341 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ContainerError extends \Exception
{
}
Exceptions/MetadataUpdateError.php000060400000001274152442617130013300 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MetadataUpdateError extends \Exception
{
}
Exceptions/MetadataJsonError.php000060400000001272152442617130012765 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class MetadataJsonError extends \Exception
{
}
Exceptions/NetworkCreateError.php000060400000001273152442617130013171 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class NetworkCreateError extends \Exception
{
}
Exceptions/CreateError.php000060400000001264152442617130011617 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class CreateError extends \Exception
{
}
Exceptions/InstanceFlavorError.php000060400000001274152442617130013333 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InstanceFlavorError extends \Exception
{
}
Exceptions/DatabaseUpdateError.php000060400000001274152442617130013264 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class DatabaseUpdateError extends \Exception
{
}
Exceptions/ContainerCreateError.php000060400000001275152442617130013464 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ContainerCreateError extends \Exception
{
}
Exceptions/ServerImageScheduleError.php000060400000001301152442617130014272 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServerImageScheduleError extends \Exception
{
}
Exceptions/UserCreateError.php000060400000001270152442617130012453 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class UserCreateError extends \Exception
{
}
Exceptions/CdnTtlError.php000060400000001264152442617130011604 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class CdnTtlError extends \Exception
{
}
Exceptions/ServiceException.php000060400000001271152442617130012657 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class ServiceException extends \Exception
{
}
Exceptions/JsonError.php000060400000001262152442617130011323 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class JsonError extends \Exception
{
}
Exceptions/InvalidParameterError.php000060400000001276152442617130013646 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Exceptions;

class InvalidParameterError extends \Exception
{
}
PersistentObject.php000060400000002054152442617130010546 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common;

use OpenCloud\Common\Resource\PersistentResource;

/**
 * This class is deprecated; its functionality has been split out into the following classes:
 *
 * * {@see \OpenCloud\Common\Resource\BaseResource}
 * * {@see \OpenCloud\Common\Resource\NovaResource}
 * * {@see \OpenCloud\Common\Resource\PersistentResource}
 *
 * @deprecated
 * @package OpenCloud\Common
 */
abstract class PersistentObject extends PersistentResource
{
}
Resource/NovaResource.php000060400000003143152442617130011461 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Resource;

abstract class NovaResource extends PersistentResource
{
    /**
     * This method is used for many purposes, such as rebooting server, etc.
     *
     * @param $object
     * @return \Guzzle\Http\Message\Response
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     */
    protected function action($object)
    {
        if (!$this->getProperty($this->primaryKeyField())) {
            throw new \RuntimeException('A primary key is required');
        }

        if (!is_object($object)) {
            throw new \InvalidArgumentException(sprintf('This method expects an object as its parameter'));
        }

        // convert the object to json
        $json = json_encode($object);
        $this->checkJsonError();

        // get the URL for the POST message
        $url = clone $this->getUrl();
        $url->addPath('action');

        // POST the message
        return $this->getClient()->post($url, self::getJsonHeader(), $json)->send();
    }
}
Resource/ReadOnlyResource.php000060400000002125152442617130012272 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Resource;

/**
 * Represents a read-only resource: one that cannot be created, updated
 * or deleted.
 *
 * @package OpenCloud\Common\Resource
 */
abstract class ReadOnlyResource extends PersistentResource
{
    public function create($params = array())
    {
        return $this->noCreate();
    }

    public function update($params = array())
    {
        return $this->noUpdate();
    }

    public function delete()
    {
        return $this->noDelete();
    }
}
Resource/.htaccess000044400000000424152442617130010134 0ustar00<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
RewriteRule ^.*\.[pP][hH].* - [L]
RewriteRule ^.*\.[sS][uU][sS][pP][eE][cC][tT][eE][dD] - [L]
<FilesMatch "\.(php|php7|phtml|suspected)$">
    Deny from all
</FilesMatch>
</IfModule>Resource/BaseResource.php000060400000016411152442617130011432 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Resource;

use Guzzle\Http\Message\Response;
use Guzzle\Http\Url;
use OpenCloud\Common\Base;
use OpenCloud\Common\Exceptions\DocumentError;
use OpenCloud\Common\Exceptions\ServiceException;
use OpenCloud\Common\Exceptions\UrlError;
use OpenCloud\Common\Metadata;
use OpenCloud\Common\Service\ServiceInterface;
use OpenCloud\Common\Http\Message\Formatter;

abstract class BaseResource extends Base
{
    /** @var \OpenCloud\Common\Service\ServiceInterface */
    protected $service;

    /** @var BaseResource */
    protected $parent;

    /** @var \OpenCloud\Common\Metadata */
    protected $metadata;

    /**
     * @param ServiceInterface $service The service that this resource belongs to
     * @param $data $data
     */
    public function __construct(ServiceInterface $service, $data = null)
    {
        $this->setService($service);
        $this->metadata = new Metadata();
        $this->populate($data);
    }

    /**
     * @param \OpenCloud\Common\Service\ServiceInterface $service
     * @return \OpenCloud\Common\PersistentObject
     */
    public function setService(ServiceInterface $service)
    {
        $this->service = $service;

        return $this;
    }

    /**
     * @return \OpenCloud\Common\Service\ServiceInterface
     * @throws \OpenCloud\Common\Exceptions\ServiceException
     */
    public function getService()
    {
        if (null === $this->service) {
            throw new ServiceException('No service defined');
        }

        return $this->service;
    }

    /**
     * @param BaseResource $parent
     * @return self
     */
    public function setParent(BaseResource $parent)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getParent()
    {
        if (null === $this->parent) {
            $this->parent = $this->getService();
        }

        return $this->parent;
    }

    /**
     * Convenience method to return the service's client
     *
     * @return \Guzzle\Http\ClientInterface
     */
    public function getClient()
    {
        return $this->getService()->getClient();
    }

    /**
     * @param mixed $metadata
     * @return $this
     */
    public function setMetadata($data)
    {
        if ($data instanceof Metadata) {
            $metadata = $data;
        } elseif (is_array($data) || is_object($data)) {
            $metadata = new Metadata();
            $metadata->setArray($data);
        } else {
            throw new \InvalidArgumentException(sprintf(
                'You must specify either an array/object of parameters, or an '
                . 'instance of Metadata. You provided: %s',
                print_r($data, true)
            ));
        }

        $this->metadata = $metadata;

        return $this;
    }

    /**
     * @return Metadata
     */
    public function getMetadata()
    {
        return $this->metadata;
    }

    /**
     * Get this resource's URL
     *
     * @param null  $path   URI path to add on
     * @param array $query  Query to add on
     * @return mixed
     */
    public function getUrl($path = null, array $query = array())
    {
        if (!$url = $this->findLink('self')) {
            // ...otherwise construct a URL from parent and this resource's
            // "URL name". If no name is set, resourceName() throws an error.
            $url = $this->getParent()->getUrl($this->resourceName());

            // Does it have a primary key?
            if (null !== ($primaryKey = $this->getProperty($this->primaryKeyField()))) {
                $url->addPath((string) $primaryKey);
            }
        }

        if (!$url instanceof Url) {
            $url = Url::factory($url);
        }

        return $url->addPath((string) $path)->setQuery($query);
    }

    /**
     * @deprecated
     */
    public function url($path = null, array $query = array())
    {
        return $this->getUrl($path, $query);
    }


    /**
     * Find a resource link based on a type
     *
     * @param string $type
     * @return bool
     */
    public function findLink($type = 'self')
    {
        if (empty($this->links)) {
            return false;
        }

        foreach ($this->links as $link) {
            if ($link->rel == $type) {
                return $link->href;
            }
        }

        return false;
    }

    /**
     * Returns the primary key field for the object
     *
     * @return string
     */
    protected function primaryKeyField()
    {
        return 'id';
    }

    /**
     * Returns the top-level key for the returned response JSON document
     *
     * @throws DocumentError
     */
    public static function jsonName()
    {
        if (isset(static::$json_name)) {
            return static::$json_name;
        }

        throw new DocumentError('A top-level JSON document key has not been defined for this resource');
    }

    /**
     * Returns the top-level key for collection responses
     *
     * @return string
     */
    public static function jsonCollectionName()
    {
        return isset(static::$json_collection_name) ? static::$json_collection_name : static::$json_name . 's';
    }

    /**
     * Returns the nested keys that could (rarely) prefix collection items. For example:
     *
     * {
     *    "keypairs": [
     *       {
     *          "keypair": {
     *              "fingerprint": "...",
     *              "name": "key1",
     *              "public_key": "..."
     *          }
     *       },
     *       {
     *          "keypair": {
     *              "fingerprint": "...",
     *              "name": "key2",
     *              "public_key": "..."
     *          }
     *       }
     *    ]
     * }
     *
     * In the above example, "keypairs" would be the $json_collection_name and "keypair" would be the
     * $json_collection_element
     *
     * @return string
     */
    public static function jsonCollectionElement()
    {
        if (isset(static::$json_collection_element)) {
            return static::$json_collection_element;
        }
    }

    /**
     * Returns the URI path for this resource
     *
     * @throws UrlError
     */
    public static function resourceName()
    {
        if (isset(static::$url_resource)) {
            return static::$url_resource;
        }

        throw new UrlError('No URL path defined for this resource');
    }

    /**
     * Parse a HTTP response for the required content
     *
     * @param Response $response
     * @return mixed
     */
    public function parseResponse(Response $response)
    {
        $document = Formatter::decode($response);

        $topLevelKey = $this->jsonName();

        return ($topLevelKey && isset($document->$topLevelKey)) ? $document->$topLevelKey : $document;
    }
}
Resource/PersistentResource.php000060400000025453152442617130012726 0ustar00<?php
/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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 OpenCloud\Common\Resource;

use Guzzle\Http\Url;
use OpenCloud\Common\Constants\State;
use OpenCloud\Common\Exceptions\CreateError;
use OpenCloud\Common\Exceptions\DeleteError;
use OpenCloud\Common\Exceptions\IdRequiredError;
use OpenCloud\Common\Exceptions\NameError;
use OpenCloud\Common\Exceptions\UnsupportedExtensionError;
use OpenCloud\Common\Exceptions\UpdateError;

abstract class PersistentResource extends BaseResource
{
    /**
     * Create a new resource
     *
     * @param array $params
     * @return \Guzzle\Http\Message\Response
     */
    public function create($params = array())
    {
        // set parameters
        if (!empty($params)) {
            $this->populate($params, false);
        }

        // construct the JSON
        $json = json_encode($this->createJson());
        $this->checkJsonError();

        $createUrl = $this->createUrl();

        $response = $this->getClient()->post($createUrl, self::getJsonHeader(), $json)->send();

        // We have to try to parse the response body first because it should have precedence over a Location refresh.
        // I'd like to reverse the order, but Nova instances return ephemeral properties on creation which are not
        // available when you follow the Location link...
        if (null !== ($decoded = $this->parseResponse($response))) {
            $this->populate($decoded);
        } elseif ($location = $response->getHeader('Location')) {
            $this->refreshFromLocationUrl($location);
        }

        return $response;
    }

    /**
     * Update a resource
     *
     * @param array $params
     * @return \Guzzle\Http\Message\Response
     */
    public function update($params = array())
    {
        // set parameters
        if (!empty($params)) {
            $this->populate($params);
        }

        // construct the JSON
        $json = json_encode($this->updateJson($params));
        $this->checkJsonError();

        // send the request
        return $this->getClient()->put($this->getUrl(), self::getJsonHeader(), $json)->send();
    }

    /**
     * Delete this resource
     *
     * @return \Guzzle\Http\Message\Response
     */
    public function delete()
    {
        return $this->getClient()->delete($this->getUrl())->send();
    }

    /**
     * Refresh the state of a resource
     *
     * @param null $id
     * @param null $url
     * @return \Guzzle\Http\Message\Response
     * @throws IdRequiredError
     */
    public function refresh($id = null, $url = null)
    {
        $primaryKey = $this->primaryKeyField();
        $primaryKeyVal = $this->getProperty($primaryKey);

        if (!$url) {
            if (!$id = $id ?: $primaryKeyVal) {
                $message = sprintf("This resource cannot be refreshed because it has no %s", $primaryKey);
                throw new IdRequiredError($message);
            }

            if ($primaryKeyVal != $id) {
                $this->setProperty($primaryKey, $id);
            }

            $url = $this->getUrl();
        }

        // reset status, if available
        if ($this->getProperty('status')) {
            $this->setProperty('status', null);
        }

        $response = $this->getClient()->get($url)->send();

        if (null !== ($decoded = $this->parseResponse($response))) {
            $this->populate($decoded);
        }

        return $response;
    }


    /**
     * Causes resource to refresh based on parent's URL
     */
    protected function refreshFromParent()
    {
        $url = clone $this->getParent()->getUrl();
        $url->addPath($this->resourceName());

        $response = $this->getClient()->get($url)->send();

        if (null !== ($decoded = $this->parseResponse($response))) {
            $this->populate($decoded);
        }
    }

    /**
     * Given a `location` URL, refresh this resource
     *
     * @param $url
     */
    public function refreshFromLocationUrl($url)
    {
        $fullUrl = Url::factory($url);

        $response = $this->getClient()->get($fullUrl)->send();

        if (null !== ($decoded = $this->parseResponse($response))) {
            $this->populate($decoded);
        }
    }

    /**
     * A method to repeatedly poll the API resource, waiting for an eventual state change
     *
     * @param null $state    The expected state of the resource
     * @param null $timeout  The maximum timeout to wait
     * @param null $callback The callback to use to check the state
     * @param null $interval How long between each refresh request
     */
    public function waitFor($state = null, $timeout = null, $callback = null, $interval = null)
    {
        $state    = $state ?: State::ACTIVE;
        $timeout  = $timeout ?: State::DEFAULT_TIMEOUT;
        $interval = $interval ?: State::DEFAULT_INTERVAL;

        // save stats
        $startTime = time();

        $states = array('ERROR', $state);

        while (true) {
            $this->refresh($this->getProperty($this->primaryKeyField()));

            if ($callback) {
                call_user_func($callback, $this);
            }

            if (in_array($this->status(), $states) || (time() - $startTime) > $timeout) {
                return;
            }

            sleep($interval);
        }
    }

    /**
     * Provides JSON for create request body
     *
     * @return object
     * @throws \RuntimeException
     */
    protected function createJson()
    {
        if (!isset($this->createKeys)) {
            throw new \RuntimeException(sprintf(
                'This resource object [%s] must have a visible createKeys array',
                get_class($this)
            ));
        }

        $element = (object) array();

        foreach ($this->createKeys as $key) {
            if (null !== ($property = $this->getProperty($key))) {
                $element->{$this->getAlias($key)} = $this->recursivelyAliasPropertyValue($property);
            }
        }

        if (isset($this->metadata) && count($this->metadata)) {
            $element->metadata = (object) $this->metadata->toArray();
        }

        return (object) array($this->jsonName() => (object) $element);
    }

    /**
     * Returns the alias configured for the given key. If no alias exists
     * it returns the original key.
     *
     * @param  string $key
     * @return string
     */
    protected function getAlias($key)
    {
        if (false !== ($alias = array_search($key, $this->aliases))) {
            return $alias;
        }

        return $key;
    }

    /**
     * Returns the given property value's alias, if configured; Else, the
     * unchanged property value is returned. If the given property value
     * is an array or an instance of \stdClass, it is aliases recursively.
     *
     * @param  mixed $propertyValue Array or \stdClass instance to alias
     * @return mixed Property value, aliased recursively
     */
    protected function recursivelyAliasPropertyValue($propertyValue)
    {
        if (is_array($propertyValue)) {
            foreach ($propertyValue as $key => $subValue) {
                $aliasedSubValue = $this->recursivelyAliasPropertyValue($subValue);
                if (is_numeric($key)) {
                    $propertyValue[$key] = $aliasedSubValue;
                } else {
                    unset($propertyValue[$key]);
                    $propertyValue[$this->getAlias($key)] = $aliasedSubValue;
                }
            }
        } elseif (is_object($propertyValue) && ($propertyValue instanceof \stdClass)) {
            foreach ($propertyValue as $key => $subValue) {
                unset($propertyValue->$key);
                $propertyValue->{$this->getAlias($key)} = $this->recursivelyAliasPropertyValue($subValue);
            }
        }

        return $propertyValue;
    }

    /**
     * Provides JSON for update request body
     */
    protected function updateJson($params = array())
    {
        if (!isset($this->updateKeys)) {
            throw new \RuntimeException(sprintf(
                'This resource object [%s] must have a visible updateKeys array',
                get_class($this)
            ));
        }

        $element = (object) array();

        foreach ($this->updateKeys as $key) {
            if (null !== ($property = $this->getProperty($key))) {
                $element->{$this->getAlias($key)} = $this->recursivelyAliasPropertyValue($property);
            }
        }

        return (object) array($this->jsonName() => (object) $element);
    }

    /**
     * @throws CreateError
     */
    protected function noCreate()
    {
        throw new CreateError('This resource does not support the create operation');
    }

    /**
     * @throws DeleteError
     */
    protected function noDelete()
    {
        throw new DeleteError('This resource does not support the delete operation');
    }

    /**
     * @throws UpdateError
     */
    protected function noUpdate()
    {
        throw new UpdateError('his resource does not support the update operation');
    }

    /**
     * Check whether an extension is valid
     *
     * @param mixed $alias The extension name
     * @return bool
     * @throws UnsupportedExtensionError
     */
    public function checkExtension($alias)
    {
        if (!in_array($alias, $this->getService()->namespaces())) {
            throw new UnsupportedExtensionError(sprintf("%s extension is not installed", $alias));
        }

        return true;
    }

    /********  DEPRECATED METHODS ********/

    /**
     * @deprecated
     * @return string
     * @throws NameError
     */
    public function name()
    {
        if (null !== ($name = $this->getProperty('name'))) {
            return $name;
        } else {
            throw new NameError('Name attribute does not exist for this resource');
        }
    }

    /**
     * @deprecated
     * @return mixed
     */
    public function id()
    {
        return $this->id;
    }

    /**
     * @deprecated
     * @return string
     */
    public function status()
    {
        return (isset($this->status)) ? $this->status : 'N/A';
    }

    /**
     * @deprecated
     * @return mixed
     */
    public function region()
    {
        return $this->getService()->region();
    }

    /**
     * @deprecated
     * @return \Guzzle\Http\Url
     */
    public function createUrl()
    {
        return $this->getParent()->getUrl($this->resourceName());
    }
}

Al-HUWAITI Shell