Storage.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  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-2010 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 (is_null($this->_credentials)) {
  184. $this->_credentials = new Zend_Service_WindowsAzure_Credentials_SharedKey(
  185. $this->_accountName, $this->_accountKey, $this->_usePathStyleUri);
  186. }
  187. $this->_retryPolicy = $retryPolicy;
  188. if (is_null($this->_retryPolicy)) {
  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. * Set retry policy to use when making requests
  215. *
  216. * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  217. */
  218. public function setRetryPolicy(Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null)
  219. {
  220. $this->_retryPolicy = $retryPolicy;
  221. if (is_null($this->_retryPolicy)) {
  222. $this->_retryPolicy = Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
  223. }
  224. }
  225. /**
  226. * Set proxy
  227. *
  228. * @param boolean $useProxy Use proxy?
  229. * @param string $proxyUrl Proxy URL
  230. * @param int $proxyPort Proxy port
  231. * @param string $proxyCredentials Proxy credentials
  232. */
  233. public function setProxy($useProxy = false, $proxyUrl = '', $proxyPort = 80, $proxyCredentials = '')
  234. {
  235. $this->_useProxy = $useProxy;
  236. $this->_proxyUrl = $proxyUrl;
  237. $this->_proxyPort = $proxyPort;
  238. $this->_proxyCredentials = $proxyCredentials;
  239. if ($this->_useProxy) {
  240. $credentials = explode(':', $this->_proxyCredentials);
  241. $this->_httpClientChannel->setConfig(array(
  242. 'proxy_host' => $this->_proxyUrl,
  243. 'proxy_port' => $this->_proxyPort,
  244. 'proxy_user' => $credentials[0],
  245. 'proxy_pass' => $credentials[1],
  246. ));
  247. } else {
  248. $this->_httpClientChannel->setConfig(array(
  249. 'proxy_host' => '',
  250. 'proxy_port' => 8080,
  251. 'proxy_user' => '',
  252. 'proxy_pass' => '',
  253. ));
  254. }
  255. }
  256. /**
  257. * Returns the Windows Azure account name
  258. *
  259. * @return string
  260. */
  261. public function getAccountName()
  262. {
  263. return $this->_accountName;
  264. }
  265. /**
  266. * Get base URL for creating requests
  267. *
  268. * @return string
  269. */
  270. public function getBaseUrl()
  271. {
  272. if ($this->_usePathStyleUri) {
  273. return 'http://' . $this->_host . '/' . $this->_accountName;
  274. } else {
  275. return 'http://' . $this->_accountName . '.' . $this->_host;
  276. }
  277. }
  278. /**
  279. * Set Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  280. *
  281. * @param Zend_Service_WindowsAzure_Credentials_CredentialsAbstract $credentials Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance to use for request signing.
  282. */
  283. public function setCredentials(Zend_Service_WindowsAzure_Credentials_CredentialsAbstract $credentials)
  284. {
  285. $this->_credentials = $credentials;
  286. $this->_credentials->setAccountName($this->_accountName);
  287. $this->_credentials->setAccountkey($this->_accountKey);
  288. $this->_credentials->setUsePathStyleUri($this->_usePathStyleUri);
  289. }
  290. /**
  291. * Get Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  292. *
  293. * @return Zend_Service_WindowsAzure_Credentials_CredentialsAbstract
  294. */
  295. public function getCredentials()
  296. {
  297. return $this->_credentials;
  298. }
  299. /**
  300. * Perform request using Zend_Http_Client channel
  301. *
  302. * @param string $path Path
  303. * @param string $queryString Query string
  304. * @param string $httpVerb HTTP verb the request will use
  305. * @param array $headers x-ms headers to add
  306. * @param boolean $forTableStorage Is the request for table storage?
  307. * @param mixed $rawData Optional RAW HTTP data to be sent over the wire
  308. * @param string $resourceType Resource type
  309. * @param string $requiredPermission Required permission
  310. * @return Zend_Http_Response
  311. */
  312. protected function _performRequest(
  313. $path = '/',
  314. $queryString = '',
  315. $httpVerb = Zend_Http_Client::GET,
  316. $headers = array(),
  317. $forTableStorage = false,
  318. $rawData = null,
  319. $resourceType = Zend_Service_WindowsAzure_Storage::RESOURCE_UNKNOWN,
  320. $requiredPermission = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::PERMISSION_READ
  321. ) {
  322. // Clean path
  323. if (strpos($path, '/') !== 0) {
  324. $path = '/' . $path;
  325. }
  326. // Clean headers
  327. if (is_null($headers)) {
  328. $headers = array();
  329. }
  330. // Ensure cUrl will also work correctly:
  331. // - disable Content-Type if required
  332. // - disable Expect: 100 Continue
  333. if (!isset($headers["Content-Type"])) {
  334. $headers["Content-Type"] = '';
  335. }
  336. $headers["Expect"]= '';
  337. // Add version header
  338. $headers['x-ms-version'] = $this->_apiVersion;
  339. // URL encoding
  340. $path = self::urlencode($path);
  341. $queryString = self::urlencode($queryString);
  342. // Generate URL and sign request
  343. $requestUrl = $this->_credentials
  344. ->signRequestUrl($this->getBaseUrl() . $path . $queryString, $resourceType, $requiredPermission);
  345. $requestHeaders = $this->_credentials
  346. ->signRequestHeaders($httpVerb, $path, $queryString, $headers, $forTableStorage, $resourceType, $requiredPermission, $rawData);
  347. // Prepare request
  348. $this->_httpClientChannel->resetParameters(true);
  349. $this->_httpClientChannel->setUri($requestUrl);
  350. $this->_httpClientChannel->setHeaders($requestHeaders);
  351. $this->_httpClientChannel->setRawData($rawData);
  352. // Execute request
  353. $response = $this->_retryPolicy->execute(
  354. array($this->_httpClientChannel, 'request'),
  355. array($httpVerb)
  356. );
  357. return $response;
  358. }
  359. /**
  360. * Parse result from Zend_Http_Response
  361. *
  362. * @param Zend_Http_Response $response Response from HTTP call
  363. * @return object
  364. * @throws Zend_Service_WindowsAzure_Exception
  365. */
  366. protected function _parseResponse(Zend_Http_Response $response = null)
  367. {
  368. if (is_null($response)) {
  369. throw new Zend_Service_WindowsAzure_Exception('Response should not be null.');
  370. }
  371. $xml = @simplexml_load_string($response->getBody());
  372. if ($xml !== false) {
  373. // Fetch all namespaces
  374. $namespaces = array_merge($xml->getNamespaces(true), $xml->getDocNamespaces(true));
  375. // Register all namespace prefixes
  376. foreach ($namespaces as $prefix => $ns) {
  377. if ($prefix != '') {
  378. $xml->registerXPathNamespace($prefix, $ns);
  379. }
  380. }
  381. }
  382. return $xml;
  383. }
  384. /**
  385. * Generate metadata headers
  386. *
  387. * @param array $metadata
  388. * @return HTTP headers containing metadata
  389. */
  390. protected function _generateMetadataHeaders($metadata = array())
  391. {
  392. // Validate
  393. if (!is_array($metadata)) {
  394. return array();
  395. }
  396. // Return headers
  397. $headers = array();
  398. foreach ($metadata as $key => $value) {
  399. if (strpos($value, "\r") !== false || strpos($value, "\n") !== false) {
  400. throw new Zend_Service_WindowsAzure_Exception('Metadata cannot contain newline characters.');
  401. }
  402. if (!self::isValidMetadataName($key)) {
  403. 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.');
  404. }
  405. $headers["x-ms-meta-" . strtolower($key)] = $value;
  406. }
  407. return $headers;
  408. }
  409. /**
  410. * Parse metadata headers
  411. *
  412. * @param array $headers HTTP headers containing metadata
  413. * @return array
  414. */
  415. protected function _parseMetadataHeaders($headers = array())
  416. {
  417. // Validate
  418. if (!is_array($headers)) {
  419. return array();
  420. }
  421. // Return metadata
  422. $metadata = array();
  423. foreach ($headers as $key => $value) {
  424. if (substr(strtolower($key), 0, 10) == "x-ms-meta-") {
  425. $metadata[str_replace("x-ms-meta-", '', strtolower($key))] = $value;
  426. }
  427. }
  428. return $metadata;
  429. }
  430. /**
  431. * Parse metadata XML
  432. *
  433. * @param SimpleXMLElement $parentElement Element containing the Metadata element.
  434. * @return array
  435. */
  436. protected function _parseMetadataElement($element = null)
  437. {
  438. // Metadata present?
  439. if (!is_null($element) && isset($element->Metadata) && !is_null($element->Metadata)) {
  440. return get_object_vars($element->Metadata);
  441. }
  442. return array();
  443. }
  444. /**
  445. * Generate ISO 8601 compliant date string in UTC time zone
  446. *
  447. * @param int $timestamp
  448. * @return string
  449. */
  450. public function isoDate($timestamp = null)
  451. {
  452. $tz = @date_default_timezone_get();
  453. @date_default_timezone_set('UTC');
  454. if (is_null($timestamp)) {
  455. $timestamp = time();
  456. }
  457. $returnValue = str_replace('+00:00', '.0000000Z', @date('c', $timestamp));
  458. @date_default_timezone_set($tz);
  459. return $returnValue;
  460. }
  461. /**
  462. * URL encode function
  463. *
  464. * @param string $value Value to encode
  465. * @return string Encoded value
  466. */
  467. public static function urlencode($value)
  468. {
  469. return str_replace(' ', '%20', $value);
  470. }
  471. /**
  472. * Is valid metadata name?
  473. *
  474. * @param string $metadataName Metadata name
  475. * @return boolean
  476. */
  477. public static function isValidMetadataName($metadataName = '')
  478. {
  479. if (preg_match("/^[a-zA-Z0-9_@][a-zA-Z0-9_]*$/", $metadataName) === 0) {
  480. return false;
  481. }
  482. if ($metadataName == '') {
  483. return false;
  484. }
  485. return true;
  486. }
  487. /**
  488. * Builds a query string from an array of elements
  489. *
  490. * @param array Array of elements
  491. * @return string Assembled query string
  492. */
  493. public static function createQueryStringFromArray($queryString)
  494. {
  495. return count($queryString) > 0 ? '?' . implode('&', $queryString) : '';
  496. }
  497. }