3
* Copyright (c) 2009 - 2010, RealDolmen
6
* Redistribution and use in source and binary forms, with or without
7
* modification, are permitted provided that the following conditions are met:
8
* * Redistributions of source code must retain the above copyright
9
* notice, this list of conditions and the following disclaimer.
10
* * Redistributions in binary form must reproduce the above copyright
11
* notice, this list of conditions and the following disclaimer in the
12
* documentation and/or other materials provided with the distribution.
13
* * Neither the name of RealDolmen nor the
14
* names of its contributors may be used to endorse or promote products
15
* derived from this software without specific prior written permission.
17
* THIS SOFTWARE IS PROVIDED BY RealDolmen ''AS IS'' AND ANY
18
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20
* DISCLAIMED. IN NO EVENT SHALL RealDolmen BE LIABLE FOR ANY
21
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
* @package Microsoft_WindowsAzure
31
* @copyright Copyright (c) 2009 - 2010, RealDolmen (http://www.realdolmen.com)
32
* @license http://phpazure.codeplex.com/license
33
* @version $Id: Storage.php 51671 2010-09-30 08:33:45Z unknown $
35
if (!defined('W3TC')) {
40
* @see Microsoft_WindowsAzure_Credentials_CredentialsAbstract
42
require_once 'Microsoft/WindowsAzure/Credentials/CredentialsAbstract.php';
45
* @see Microsoft_WindowsAzure_Credentials_SharedKey
47
require_once 'Microsoft/WindowsAzure/Credentials/SharedKey.php';
50
* @see Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract
52
require_once 'Microsoft/WindowsAzure/RetryPolicy/RetryPolicyAbstract.php';
55
* @see Microsoft_WindowsAzure_Exception
57
require_once 'Microsoft/WindowsAzure/Exception.php';
60
* @see Microsoft_Http_Client
62
require_once 'Microsoft/Http/Client.php';
65
* @see Microsoft_Http_Response
67
require_once 'Microsoft/Http/Response.php';
71
* @package Microsoft_WindowsAzure
73
* @copyright Copyright (c) 2009 - 2010, RealDolmen (http://www.realdolmen.com)
74
* @license http://phpazure.codeplex.com/license
76
class Microsoft_WindowsAzure_Storage
79
* Development storage URLS
81
const URL_DEV_BLOB = "127.0.0.1:10000";
82
const URL_DEV_QUEUE = "127.0.0.1:10001";
83
const URL_DEV_TABLE = "127.0.0.1:10002";
88
const URL_CLOUD_BLOB = "blob.core.windows.net";
89
const URL_CLOUD_QUEUE = "queue.core.windows.net";
90
const URL_CLOUD_TABLE = "table.core.windows.net";
95
const RESOURCE_UNKNOWN = "unknown";
96
const RESOURCE_CONTAINER = "c";
97
const RESOURCE_BLOB = "b";
98
const RESOURCE_TABLE = "t";
99
const RESOURCE_ENTITY = "e";
100
const RESOURCE_QUEUE = "q";
103
* HTTP header prefixes
105
const PREFIX_PROPERTIES = "x-ms-prop-";
106
const PREFIX_METADATA = "x-ms-meta-";
107
const PREFIX_STORAGE_HEADER = "x-ms-";
110
* Current API version
114
protected $_apiVersion = '2009-09-19';
121
protected $_host = '';
124
* Account name for Windows Azure
128
protected $_accountName = '';
131
* Account key for Windows Azure
135
protected $_accountKey = '';
138
* Use path-style URI's
142
protected $_usePathStyleUri = false;
145
* Microsoft_WindowsAzure_Credentials_CredentialsAbstract instance
147
* @var Microsoft_WindowsAzure_Credentials_CredentialsAbstract
149
protected $_credentials = null;
152
* Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract instance
154
* @var Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract
156
protected $_retryPolicy = null;
159
* Microsoft_Http_Client channel used for communication with REST services
161
* @var Microsoft_Http_Client
163
protected $_httpClientChannel = null;
170
protected $_useProxy = false;
177
protected $_proxyUrl = '';
184
protected $_proxyPort = 80;
191
protected $_proxyCredentials = '';
194
* Creates a new Microsoft_WindowsAzure_Storage instance
196
* @param string $host Storage host name
197
* @param string $accountName Account name for Windows Azure
198
* @param string $accountKey Account key for Windows Azure
199
* @param boolean $usePathStyleUri Use path-style URI's
200
* @param Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
202
public function __construct(
203
$host = self::URL_DEV_BLOB,
204
$accountName = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_ACCOUNT,
205
$accountKey = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_KEY,
206
$usePathStyleUri = false,
207
Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null
209
$this->_host = $host;
210
$this->_accountName = $accountName;
211
$this->_accountKey = $accountKey;
212
$this->_usePathStyleUri = $usePathStyleUri;
214
// Using local storage?
215
if (!$this->_usePathStyleUri
216
&& ($this->_host == self::URL_DEV_BLOB
217
|| $this->_host == self::URL_DEV_QUEUE
218
|| $this->_host == self::URL_DEV_TABLE)
221
$this->_usePathStyleUri = true;
224
if (is_null($this->_credentials)) {
225
$this->_credentials = new Microsoft_WindowsAzure_Credentials_SharedKey(
226
$this->_accountName, $this->_accountKey, $this->_usePathStyleUri);
229
$this->_retryPolicy = $retryPolicy;
230
if (is_null($this->_retryPolicy)) {
231
$this->_retryPolicy = Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
234
// Setup default Microsoft_Http_Client channel
236
'adapter' => 'Microsoft_Http_Client_Adapter_Proxy'
238
if (function_exists('curl_init')) {
239
// Set cURL options if cURL is used afterwards
240
$options['curloptions'] = array(
241
CURLOPT_FOLLOWLOCATION => true,
242
CURLOPT_TIMEOUT => 120,
245
$this->_httpClientChannel = new Microsoft_Http_Client(null, $options);
249
* Set the HTTP client channel to use
251
* @param Microsoft_Http_Client_Adapter_Interface|string $adapterInstance Adapter instance or adapter class name.
253
public function setHttpClientChannel($adapterInstance = 'Microsoft_Http_Client_Adapter_Proxy')
255
$this->_httpClientChannel->setAdapter($adapterInstance);
259
* Retrieve HTTP client channel
261
* @return Microsoft_Http_Client_Adapter_Interface
263
public function getHttpClientChannel()
265
return $this->_httpClientChannel;
269
* Set retry policy to use when making requests
271
* @param Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
273
public function setRetryPolicy(Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null)
275
$this->_retryPolicy = $retryPolicy;
276
if (is_null($this->_retryPolicy)) {
277
$this->_retryPolicy = Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
284
* @param boolean $useProxy Use proxy?
285
* @param string $proxyUrl Proxy URL
286
* @param int $proxyPort Proxy port
287
* @param string $proxyCredentials Proxy credentials
289
public function setProxy($useProxy = false, $proxyUrl = '', $proxyPort = 80, $proxyCredentials = '')
291
$this->_useProxy = $useProxy;
292
$this->_proxyUrl = $proxyUrl;
293
$this->_proxyPort = $proxyPort;
294
$this->_proxyCredentials = $proxyCredentials;
296
if ($this->_useProxy) {
297
$credentials = explode(':', $this->_proxyCredentials);
299
$this->_httpClientChannel->setConfig(array(
300
'proxy_host' => $this->_proxyUrl,
301
'proxy_port' => $this->_proxyPort,
302
'proxy_user' => $credentials[0],
303
'proxy_pass' => $credentials[1],
306
$this->_httpClientChannel->setConfig(array(
308
'proxy_port' => 8080,
316
* Returns the Windows Azure account name
320
public function getAccountName()
322
return $this->_accountName;
326
* Get base URL for creating requests
330
public function getBaseUrl()
332
if ($this->_usePathStyleUri) {
333
return 'http://' . $this->_host . '/' . $this->_accountName;
335
return 'http://' . $this->_accountName . '.' . $this->_host;
340
* Set Microsoft_WindowsAzure_Credentials_CredentialsAbstract instance
342
* @param Microsoft_WindowsAzure_Credentials_CredentialsAbstract $credentials Microsoft_WindowsAzure_Credentials_CredentialsAbstract instance to use for request signing.
344
public function setCredentials(Microsoft_WindowsAzure_Credentials_CredentialsAbstract $credentials)
346
$this->_credentials = $credentials;
347
$this->_credentials->setAccountName($this->_accountName);
348
$this->_credentials->setAccountkey($this->_accountKey);
349
$this->_credentials->setUsePathStyleUri($this->_usePathStyleUri);
353
* Get Microsoft_WindowsAzure_Credentials_CredentialsAbstract instance
355
* @return Microsoft_WindowsAzure_Credentials_CredentialsAbstract
357
public function getCredentials()
359
return $this->_credentials;
363
* Perform request using Microsoft_Http_Client channel
365
* @param string $path Path
366
* @param string $queryString Query string
367
* @param string $httpVerb HTTP verb the request will use
368
* @param array $headers x-ms headers to add
369
* @param boolean $forTableStorage Is the request for table storage?
370
* @param mixed $rawData Optional RAW HTTP data to be sent over the wire
371
* @param string $resourceType Resource type
372
* @param string $requiredPermission Required permission
373
* @return Microsoft_Http_Response
375
protected function _performRequest(
378
$httpVerb = Microsoft_Http_Client::GET,
380
$forTableStorage = false,
382
$resourceType = Microsoft_WindowsAzure_Storage::RESOURCE_UNKNOWN,
383
$requiredPermission = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::PERMISSION_READ
386
if (strpos($path, '/') !== 0) {
391
if (is_null($headers)) {
395
// Ensure cUrl will also work correctly:
396
// - disable Content-Type if required
397
// - disable Expect: 100 Continue
398
if (!isset($headers["Content-Type"])) {
399
$headers["Content-Type"] = '';
401
$headers["Expect"]= '';
403
// Add version header
404
$headers['x-ms-version'] = $this->_apiVersion;
407
$path = self::urlencode($path);
408
$queryString = self::urlencode($queryString);
410
// Generate URL and sign request
411
$requestUrl = $this->_credentials
412
->signRequestUrl($this->getBaseUrl() . $path . $queryString, $resourceType, $requiredPermission);
413
$requestHeaders = $this->_credentials
414
->signRequestHeaders($httpVerb, $path, $queryString, $headers, $forTableStorage, $resourceType, $requiredPermission, $rawData);
417
$this->_httpClientChannel->resetParameters(true);
418
$this->_httpClientChannel->setUri($requestUrl);
419
$this->_httpClientChannel->setHeaders($requestHeaders);
420
$this->_httpClientChannel->setRawData($rawData);
423
$response = $this->_retryPolicy->execute(
424
array($this->_httpClientChannel, 'request'),
432
* Parse result from Microsoft_Http_Response
434
* @param Microsoft_Http_Response $response Response from HTTP call
436
* @throws Microsoft_WindowsAzure_Exception
438
protected function _parseResponse(Microsoft_Http_Response $response = null)
440
if (is_null($response)) {
441
throw new Microsoft_WindowsAzure_Exception('Response should not be null.');
444
$xml = @simplexml_load_string($response->getBody());
446
if ($xml !== false) {
447
// Fetch all namespaces
448
$namespaces = array_merge($xml->getNamespaces(true), $xml->getDocNamespaces(true));
450
// Register all namespace prefixes
451
foreach ($namespaces as $prefix => $ns) {
453
$xml->registerXPathNamespace($prefix, $ns);
462
* Generate metadata headers
464
* @param array $metadata
465
* @return HTTP headers containing metadata
467
protected function _generateMetadataHeaders($metadata = array())
470
if (!is_array($metadata)) {
476
foreach ($metadata as $key => $value) {
477
if (strpos($value, "\r") !== false || strpos($value, "\n") !== false) {
478
throw new Microsoft_WindowsAzure_Exception('Metadata cannot contain newline characters.');
481
if (!self::isValidMetadataName($key)) {
482
throw new Microsoft_WindowsAzure_Exception('Metadata name does not adhere to metadata naming conventions. See http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx for more information.');
485
$headers["x-ms-meta-" . strtolower($key)] = $value;
491
* Parse metadata headers
493
* @param array $headers HTTP headers containing metadata
496
protected function _parseMetadataHeaders($headers = array())
499
if (!is_array($headers)) {
505
foreach ($headers as $key => $value) {
506
if (substr(strtolower($key), 0, 10) == "x-ms-meta-") {
507
$metadata[str_replace("x-ms-meta-", '', strtolower($key))] = $value;
516
* @param SimpleXMLElement $parentElement Element containing the Metadata element.
519
protected function _parseMetadataElement($element = null)
522
if (!is_null($element) && isset($element->Metadata) && !is_null($element->Metadata)) {
523
return get_object_vars($element->Metadata);
530
* Generate ISO 8601 compliant date string in UTC time zone
532
* @param int $timestamp
535
public function isoDate($timestamp = null)
537
$tz = @date_default_timezone_get();
538
@date_default_timezone_set('UTC');
540
if (is_null($timestamp)) {
544
$returnValue = str_replace('+00:00', '.0000000Z', @date('c', $timestamp));
545
@date_default_timezone_set($tz);
550
* URL encode function
552
* @param string $value Value to encode
553
* @return string Encoded value
555
public static function urlencode($value)
557
return str_replace(' ', '%20', $value);
561
* Is valid metadata name?
563
* @param string $metadataName Metadata name
566
public static function isValidMetadataName($metadataName = '')
568
if (preg_match("/^[a-zA-Z0-9_@][a-zA-Z0-9_]*$/", $metadataName) === 0) {
572
if ($metadataName == '') {
580
* Builds a query string from an array of elements
582
* @param array Array of elements
583
* @return string Assembled query string
585
public static function createQueryStringFromArray($queryString)
587
return count($queryString) > 0 ? '?' . implode('&', $queryString) : '';