/zf/library/Zend/Service/WindowsAzure/Storage.php

http://github.com/eryx/php-framework-benchmark · PHP · 573 lines · 254 code · 67 blank · 252 comment · 36 complexity · 0f2507a9060468ecc43fac09b98d3118 MD5 · raw file

  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Service_WindowsAzure
  17. * @subpackage Storage
  18. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Storage.php 23775 2011-03-01 17:25:24Z ralph $
  21. */
  22. /**
  23. * @see Zend_Service_WindowsAzure_Credentials_CredentialsAbstract
  24. */
  25. require_once 'Zend/Service/WindowsAzure/Credentials/CredentialsAbstract.php';
  26. /**
  27. * @see Zend_Service_WindowsAzure_Credentials_SharedKey
  28. */
  29. require_once 'Zend/Service/WindowsAzure/Credentials/SharedKey.php';
  30. /**
  31. * @see Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract
  32. */
  33. require_once 'Zend/Service/WindowsAzure/RetryPolicy/RetryPolicyAbstract.php';
  34. /**
  35. * @see Zend_Service_WindowsAzure_Exception
  36. */
  37. require_once 'Zend/Service/WindowsAzure/Exception.php';
  38. /**
  39. * @see Zend_Http_Client
  40. */
  41. require_once 'Zend/Http/Client.php';
  42. /**
  43. * @see Zend_Http_Response
  44. */
  45. require_once 'Zend/Http/Response.php';
  46. /**
  47. * @category Zend
  48. * @package Zend_Service_WindowsAzure
  49. * @subpackage Storage
  50. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  51. * @license http://framework.zend.com/license/new-bsd New BSD License
  52. */
  53. class Zend_Service_WindowsAzure_Storage
  54. {
  55. /**
  56. * Development storage URLS
  57. */
  58. const URL_DEV_BLOB = "127.0.0.1:10000";
  59. const URL_DEV_QUEUE = "127.0.0.1:10001";
  60. const URL_DEV_TABLE = "127.0.0.1:10002";
  61. /**
  62. * Live storage URLS
  63. */
  64. const URL_CLOUD_BLOB = "blob.core.windows.net";
  65. const URL_CLOUD_QUEUE = "queue.core.windows.net";
  66. const URL_CLOUD_TABLE = "table.core.windows.net";
  67. /**
  68. * Resource types
  69. */
  70. const RESOURCE_UNKNOWN = "unknown";
  71. const RESOURCE_CONTAINER = "c";
  72. const RESOURCE_BLOB = "b";
  73. const RESOURCE_TABLE = "t";
  74. const RESOURCE_ENTITY = "e";
  75. const RESOURCE_QUEUE = "q";
  76. /**
  77. * HTTP header prefixes
  78. */
  79. const PREFIX_PROPERTIES = "x-ms-prop-";
  80. const PREFIX_METADATA = "x-ms-meta-";
  81. const PREFIX_STORAGE_HEADER = "x-ms-";
  82. /**
  83. * Current API version
  84. *
  85. * @var string
  86. */
  87. protected $_apiVersion = '2009-09-19';
  88. /**
  89. * Storage host name
  90. *
  91. * @var string
  92. */
  93. protected $_host = '';
  94. /**
  95. * Account name for Windows Azure
  96. *
  97. * @var string
  98. */
  99. protected $_accountName = '';
  100. /**
  101. * Account key for Windows Azure
  102. *
  103. * @var string
  104. */
  105. protected $_accountKey = '';
  106. /**
  107. * Use path-style URI's
  108. *
  109. * @var boolean
  110. */
  111. protected $_usePathStyleUri = false;
  112. /**
  113. * Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  114. *
  115. * @var Zend_Service_WindowsAzure_Credentials_CredentialsAbstract
  116. */
  117. protected $_credentials = null;
  118. /**
  119. * Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract instance
  120. *
  121. * @var Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract
  122. */
  123. protected $_retryPolicy = null;
  124. /**
  125. * Zend_Http_Client channel used for communication with REST services
  126. *
  127. * @var Zend_Http_Client
  128. */
  129. protected $_httpClientChannel = null;
  130. /**
  131. * Use proxy?
  132. *
  133. * @var boolean
  134. */
  135. protected $_useProxy = false;
  136. /**
  137. * Proxy url
  138. *
  139. * @var string
  140. */
  141. protected $_proxyUrl = '';
  142. /**
  143. * Proxy port
  144. *
  145. * @var int
  146. */
  147. protected $_proxyPort = 80;
  148. /**
  149. * Proxy credentials
  150. *
  151. * @var string
  152. */
  153. protected $_proxyCredentials = '';
  154. /**
  155. * Creates a new Zend_Service_WindowsAzure_Storage instance
  156. *
  157. * @param string $host Storage host name
  158. * @param string $accountName Account name for Windows Azure
  159. * @param string $accountKey Account key for Windows Azure
  160. * @param boolean $usePathStyleUri Use path-style URI's
  161. * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  162. */
  163. public function __construct(
  164. $host = self::URL_DEV_BLOB,
  165. $accountName = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_ACCOUNT,
  166. $accountKey = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_KEY,
  167. $usePathStyleUri = false,
  168. Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null
  169. ) {
  170. $this->_host = $host;
  171. $this->_accountName = $accountName;
  172. $this->_accountKey = $accountKey;
  173. $this->_usePathStyleUri = $usePathStyleUri;
  174. // Using local storage?
  175. if (!$this->_usePathStyleUri
  176. && ($this->_host == self::URL_DEV_BLOB
  177. || $this->_host == self::URL_DEV_QUEUE
  178. || $this->_host == self::URL_DEV_TABLE)
  179. ) {
  180. // Local storage
  181. $this->_usePathStyleUri = true;
  182. }
  183. if ($this->_credentials === null) {
  184. $this->_credentials = new Zend_Service_WindowsAzure_Credentials_SharedKey(
  185. $this->_accountName, $this->_accountKey, $this->_usePathStyleUri);
  186. }
  187. $this->_retryPolicy = $retryPolicy;
  188. if ($this->_retryPolicy === null) {
  189. $this->_retryPolicy = Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
  190. }
  191. // Setup default Zend_Http_Client channel
  192. $options = array(
  193. 'adapter' => 'Zend_Http_Client_Adapter_Proxy'
  194. );
  195. if (function_exists('curl_init')) {
  196. // Set cURL options if cURL is used afterwards
  197. $options['curloptions'] = array(
  198. CURLOPT_FOLLOWLOCATION => true,
  199. CURLOPT_TIMEOUT => 120,
  200. );
  201. }
  202. $this->_httpClientChannel = new Zend_Http_Client(null, $options);
  203. }
  204. /**
  205. * Set the HTTP client channel to use
  206. *
  207. * @param Zend_Http_Client_Adapter_Interface|string $adapterInstance Adapter instance or adapter class name.
  208. */
  209. public function setHttpClientChannel($adapterInstance = 'Zend_Http_Client_Adapter_Proxy')
  210. {
  211. $this->_httpClientChannel->setAdapter($adapterInstance);
  212. }
  213. /**
  214. * Retrieve HTTP client channel
  215. *
  216. * @return Zend_Http_Client_Adapter_Interface
  217. */
  218. public function getHttpClientChannel()
  219. {
  220. return $this->_httpClientChannel;
  221. }
  222. /**
  223. * Set retry policy to use when making requests
  224. *
  225. * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  226. */
  227. public function setRetryPolicy(Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null)
  228. {
  229. $this->_retryPolicy = $retryPolicy;
  230. if ($this->_retryPolicy === null) {
  231. $this->_retryPolicy = Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
  232. }
  233. }
  234. /**
  235. * Set proxy
  236. *
  237. * @param boolean $useProxy Use proxy?
  238. * @param string $proxyUrl Proxy URL
  239. * @param int $proxyPort Proxy port
  240. * @param string $proxyCredentials Proxy credentials
  241. */
  242. public function setProxy($useProxy = false, $proxyUrl = '', $proxyPort = 80, $proxyCredentials = '')
  243. {
  244. $this->_useProxy = $useProxy;
  245. $this->_proxyUrl = $proxyUrl;
  246. $this->_proxyPort = $proxyPort;
  247. $this->_proxyCredentials = $proxyCredentials;
  248. if ($this->_useProxy) {
  249. $credentials = explode(':', $this->_proxyCredentials);
  250. $this->_httpClientChannel->setConfig(array(
  251. 'proxy_host' => $this->_proxyUrl,
  252. 'proxy_port' => $this->_proxyPort,
  253. 'proxy_user' => $credentials[0],
  254. 'proxy_pass' => $credentials[1],
  255. ));
  256. } else {
  257. $this->_httpClientChannel->setConfig(array(
  258. 'proxy_host' => '',
  259. 'proxy_port' => 8080,
  260. 'proxy_user' => '',
  261. 'proxy_pass' => '',
  262. ));
  263. }
  264. }
  265. /**
  266. * Returns the Windows Azure account name
  267. *
  268. * @return string
  269. */
  270. public function getAccountName()
  271. {
  272. return $this->_accountName;
  273. }
  274. /**
  275. * Get base URL for creating requests
  276. *
  277. * @return string
  278. */
  279. public function getBaseUrl()
  280. {
  281. if ($this->_usePathStyleUri) {
  282. return 'http://' . $this->_host . '/' . $this->_accountName;
  283. } else {
  284. return 'http://' . $this->_accountName . '.' . $this->_host;
  285. }
  286. }
  287. /**
  288. * Set Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  289. *
  290. * @param Zend_Service_WindowsAzure_Credentials_CredentialsAbstract $credentials Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance to use for request signing.
  291. */
  292. public function setCredentials(Zend_Service_WindowsAzure_Credentials_CredentialsAbstract $credentials)
  293. {
  294. $this->_credentials = $credentials;
  295. $this->_credentials->setAccountName($this->_accountName);
  296. $this->_credentials->setAccountkey($this->_accountKey);
  297. $this->_credentials->setUsePathStyleUri($this->_usePathStyleUri);
  298. }
  299. /**
  300. * Get Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  301. *
  302. * @return Zend_Service_WindowsAzure_Credentials_CredentialsAbstract
  303. */
  304. public function getCredentials()
  305. {
  306. return $this->_credentials;
  307. }
  308. /**
  309. * Perform request using Zend_Http_Client channel
  310. *
  311. * @param string $path Path
  312. * @param string $queryString Query string
  313. * @param string $httpVerb HTTP verb the request will use
  314. * @param array $headers x-ms headers to add
  315. * @param boolean $forTableStorage Is the request for table storage?
  316. * @param mixed $rawData Optional RAW HTTP data to be sent over the wire
  317. * @param string $resourceType Resource type
  318. * @param string $requiredPermission Required permission
  319. * @return Zend_Http_Response
  320. */
  321. protected function _performRequest(
  322. $path = '/',
  323. $queryString = '',
  324. $httpVerb = Zend_Http_Client::GET,
  325. $headers = array(),
  326. $forTableStorage = false,
  327. $rawData = null,
  328. $resourceType = Zend_Service_WindowsAzure_Storage::RESOURCE_UNKNOWN,
  329. $requiredPermission = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::PERMISSION_READ
  330. ) {
  331. // Clean path
  332. if (strpos($path, '/') !== 0) {
  333. $path = '/' . $path;
  334. }
  335. // Clean headers
  336. if ($headers === null) {
  337. $headers = array();
  338. }
  339. // Ensure cUrl will also work correctly:
  340. // - disable Content-Type if required
  341. // - disable Expect: 100 Continue
  342. if (!isset($headers["Content-Type"])) {
  343. $headers["Content-Type"] = '';
  344. }
  345. $headers["Expect"]= '';
  346. // Add version header
  347. $headers['x-ms-version'] = $this->_apiVersion;
  348. // URL encoding
  349. $path = self::urlencode($path);
  350. $queryString = self::urlencode($queryString);
  351. // Generate URL and sign request
  352. $requestUrl = $this->_credentials
  353. ->signRequestUrl($this->getBaseUrl() . $path . $queryString, $resourceType, $requiredPermission);
  354. $requestHeaders = $this->_credentials
  355. ->signRequestHeaders($httpVerb, $path, $queryString, $headers, $forTableStorage, $resourceType, $requiredPermission, $rawData);
  356. // Prepare request
  357. $this->_httpClientChannel->resetParameters(true);
  358. $this->_httpClientChannel->setUri($requestUrl);
  359. $this->_httpClientChannel->setHeaders($requestHeaders);
  360. $this->_httpClientChannel->setRawData($rawData);
  361. // Execute request
  362. $response = $this->_retryPolicy->execute(
  363. array($this->_httpClientChannel, 'request'),
  364. array($httpVerb)
  365. );
  366. return $response;
  367. }
  368. /**
  369. * Parse result from Zend_Http_Response
  370. *
  371. * @param Zend_Http_Response $response Response from HTTP call
  372. * @return object
  373. * @throws Zend_Service_WindowsAzure_Exception
  374. */
  375. protected function _parseResponse(Zend_Http_Response $response = null)
  376. {
  377. if ($response === null) {
  378. throw new Zend_Service_WindowsAzure_Exception('Response should not be null.');
  379. }
  380. $xml = @simplexml_load_string($response->getBody());
  381. if ($xml !== false) {
  382. // Fetch all namespaces
  383. $namespaces = array_merge($xml->getNamespaces(true), $xml->getDocNamespaces(true));
  384. // Register all namespace prefixes
  385. foreach ($namespaces as $prefix => $ns) {
  386. if ($prefix != '') {
  387. $xml->registerXPathNamespace($prefix, $ns);
  388. }
  389. }
  390. }
  391. return $xml;
  392. }
  393. /**
  394. * Generate metadata headers
  395. *
  396. * @param array $metadata
  397. * @return HTTP headers containing metadata
  398. */
  399. protected function _generateMetadataHeaders($metadata = array())
  400. {
  401. // Validate
  402. if (!is_array($metadata)) {
  403. return array();
  404. }
  405. // Return headers
  406. $headers = array();
  407. foreach ($metadata as $key => $value) {
  408. if (strpos($value, "\r") !== false || strpos($value, "\n") !== false) {
  409. throw new Zend_Service_WindowsAzure_Exception('Metadata cannot contain newline characters.');
  410. }
  411. if (!self::isValidMetadataName($key)) {
  412. throw new Zend_Service_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.');
  413. }
  414. $headers["x-ms-meta-" . strtolower($key)] = $value;
  415. }
  416. return $headers;
  417. }
  418. /**
  419. * Parse metadata headers
  420. *
  421. * @param array $headers HTTP headers containing metadata
  422. * @return array
  423. */
  424. protected function _parseMetadataHeaders($headers = array())
  425. {
  426. // Validate
  427. if (!is_array($headers)) {
  428. return array();
  429. }
  430. // Return metadata
  431. $metadata = array();
  432. foreach ($headers as $key => $value) {
  433. if (substr(strtolower($key), 0, 10) == "x-ms-meta-") {
  434. $metadata[str_replace("x-ms-meta-", '', strtolower($key))] = $value;
  435. }
  436. }
  437. return $metadata;
  438. }
  439. /**
  440. * Parse metadata XML
  441. *
  442. * @param SimpleXMLElement $parentElement Element containing the Metadata element.
  443. * @return array
  444. */
  445. protected function _parseMetadataElement($element = null)
  446. {
  447. // Metadata present?
  448. if ($element !== null && isset($element->Metadata) && $element->Metadata !== null) {
  449. return get_object_vars($element->Metadata);
  450. }
  451. return array();
  452. }
  453. /**
  454. * Generate ISO 8601 compliant date string in UTC time zone
  455. *
  456. * @param int $timestamp
  457. * @return string
  458. */
  459. public function isoDate($timestamp = null)
  460. {
  461. $tz = @date_default_timezone_get();
  462. @date_default_timezone_set('UTC');
  463. if ($timestamp === null) {
  464. $timestamp = time();
  465. }
  466. $returnValue = str_replace('+00:00', '.0000000Z', @date('c', $timestamp));
  467. @date_default_timezone_set($tz);
  468. return $returnValue;
  469. }
  470. /**
  471. * URL encode function
  472. *
  473. * @param string $value Value to encode
  474. * @return string Encoded value
  475. */
  476. public static function urlencode($value)
  477. {
  478. return str_replace(' ', '%20', $value);
  479. }
  480. /**
  481. * Is valid metadata name?
  482. *
  483. * @param string $metadataName Metadata name
  484. * @return boolean
  485. */
  486. public static function isValidMetadataName($metadataName = '')
  487. {
  488. if (preg_match("/^[a-zA-Z0-9_@][a-zA-Z0-9_]*$/", $metadataName) === 0) {
  489. return false;
  490. }
  491. if ($metadataName == '') {
  492. return false;
  493. }
  494. return true;
  495. }
  496. /**
  497. * Builds a query string from an array of elements
  498. *
  499. * @param array Array of elements
  500. * @return string Assembled query string
  501. */
  502. public static function createQueryStringFromArray($queryString)
  503. {
  504. return count($queryString) > 0 ? '?' . implode('&', $queryString) : '';
  505. }
  506. }