Storage.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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-2012 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_Http_Client
  24. */
  25. require_once 'Zend/Http/Client.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. * @category Zend
  36. * @package Zend_Service_WindowsAzure
  37. * @subpackage Storage
  38. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  39. * @license http://framework.zend.com/license/new-bsd New BSD License
  40. */
  41. class Zend_Service_WindowsAzure_Storage
  42. {
  43. /**
  44. * Development storage URLS
  45. */
  46. const URL_DEV_BLOB = "127.0.0.1:10000";
  47. const URL_DEV_QUEUE = "127.0.0.1:10001";
  48. const URL_DEV_TABLE = "127.0.0.1:10002";
  49. /**
  50. * Live storage URLS
  51. */
  52. const URL_CLOUD_BLOB = "blob.core.windows.net";
  53. const URL_CLOUD_QUEUE = "queue.core.windows.net";
  54. const URL_CLOUD_TABLE = "table.core.windows.net";
  55. /**
  56. * Resource types
  57. */
  58. const RESOURCE_UNKNOWN = "unknown";
  59. const RESOURCE_CONTAINER = "c";
  60. const RESOURCE_BLOB = "b";
  61. const RESOURCE_TABLE = "t";
  62. const RESOURCE_ENTITY = "e";
  63. const RESOURCE_QUEUE = "q";
  64. /**
  65. * HTTP header prefixes
  66. */
  67. const PREFIX_PROPERTIES = "x-ms-prop-";
  68. const PREFIX_METADATA = "x-ms-meta-";
  69. const PREFIX_STORAGE_HEADER = "x-ms-";
  70. /**
  71. * Current API version
  72. *
  73. * @var string
  74. */
  75. protected $_apiVersion = '2009-09-19';
  76. /**
  77. * Storage host name
  78. *
  79. * @var string
  80. */
  81. protected $_host = '';
  82. /**
  83. * Account name for Windows Azure
  84. *
  85. * @var string
  86. */
  87. protected $_accountName = '';
  88. /**
  89. * Account key for Windows Azure
  90. *
  91. * @var string
  92. */
  93. protected $_accountKey = '';
  94. /**
  95. * Use path-style URI's
  96. *
  97. * @var boolean
  98. */
  99. protected $_usePathStyleUri = false;
  100. /**
  101. * Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  102. *
  103. * @var Zend_Service_WindowsAzure_Credentials_CredentialsAbstract
  104. */
  105. protected $_credentials = null;
  106. /**
  107. * Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract instance
  108. *
  109. * @var Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract
  110. */
  111. protected $_retryPolicy = null;
  112. /**
  113. * Zend_Http_Client channel used for communication with REST services
  114. *
  115. * @var Zend_Http_Client
  116. */
  117. protected $_httpClientChannel = null;
  118. /**
  119. * Use proxy?
  120. *
  121. * @var boolean
  122. */
  123. protected $_useProxy = false;
  124. /**
  125. * Proxy url
  126. *
  127. * @var string
  128. */
  129. protected $_proxyUrl = '';
  130. /**
  131. * Proxy port
  132. *
  133. * @var int
  134. */
  135. protected $_proxyPort = 80;
  136. /**
  137. * Proxy credentials
  138. *
  139. * @var string
  140. */
  141. protected $_proxyCredentials = '';
  142. /**
  143. * Creates a new Zend_Service_WindowsAzure_Storage instance
  144. *
  145. * @param string $host Storage host name
  146. * @param string $accountName Account name for Windows Azure
  147. * @param string $accountKey Account key for Windows Azure
  148. * @param boolean $usePathStyleUri Use path-style URI's
  149. * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  150. */
  151. public function __construct(
  152. $host = self::URL_DEV_BLOB,
  153. $accountName = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_ACCOUNT,
  154. $accountKey = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_KEY,
  155. $usePathStyleUri = false,
  156. Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null
  157. ) {
  158. $this->_host = $host;
  159. $this->_accountName = $accountName;
  160. $this->_accountKey = $accountKey;
  161. $this->_usePathStyleUri = $usePathStyleUri;
  162. // Using local storage?
  163. if (!$this->_usePathStyleUri
  164. && ($this->_host == self::URL_DEV_BLOB
  165. || $this->_host == self::URL_DEV_QUEUE
  166. || $this->_host == self::URL_DEV_TABLE)
  167. ) {
  168. // Local storage
  169. $this->_usePathStyleUri = true;
  170. }
  171. if (is_null($this->_credentials)) {
  172. $this->_credentials = new Zend_Service_WindowsAzure_Credentials_SharedKey(
  173. $this->_accountName, $this->_accountKey, $this->_usePathStyleUri);
  174. }
  175. $this->_retryPolicy = $retryPolicy;
  176. if (is_null($this->_retryPolicy)) {
  177. $this->_retryPolicy = Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
  178. }
  179. // Setup default Zend_Http_Client channel
  180. $options = array(
  181. 'adapter' => 'Zend_Http_Client_Adapter_Proxy'
  182. );
  183. if (function_exists('curl_init')) {
  184. // Set cURL options if cURL is used afterwards
  185. $options['curloptions'] = array(
  186. CURLOPT_FOLLOWLOCATION => true,
  187. CURLOPT_TIMEOUT => 120,
  188. );
  189. }
  190. $this->_httpClientChannel = new Zend_Http_Client(null, $options);
  191. }
  192. /**
  193. * Set the HTTP client channel to use
  194. *
  195. * @param Zend_Http_Client_Adapter_Interface|string $adapterInstance Adapter instance or adapter class name.
  196. */
  197. public function setHttpClientChannel($adapterInstance = 'Zend_Http_Client_Adapter_Proxy')
  198. {
  199. $this->_httpClientChannel->setAdapter($adapterInstance);
  200. }
  201. /**
  202. * Retrieve HTTP client channel
  203. *
  204. * @return Zend_Http_Client_Adapter_Interface
  205. */
  206. public function getHttpClientChannel()
  207. {
  208. return $this->_httpClientChannel;
  209. }
  210. /**
  211. * Set retry policy to use when making requests
  212. *
  213. * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  214. */
  215. public function setRetryPolicy(Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null)
  216. {
  217. $this->_retryPolicy = $retryPolicy;
  218. if (is_null($this->_retryPolicy)) {
  219. $this->_retryPolicy = Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
  220. }
  221. }
  222. /**
  223. * Set proxy
  224. *
  225. * @param boolean $useProxy Use proxy?
  226. * @param string $proxyUrl Proxy URL
  227. * @param int $proxyPort Proxy port
  228. * @param string $proxyCredentials Proxy credentials
  229. */
  230. public function setProxy($useProxy = false, $proxyUrl = '', $proxyPort = 80, $proxyCredentials = '')
  231. {
  232. $this->_useProxy = $useProxy;
  233. $this->_proxyUrl = $proxyUrl;
  234. $this->_proxyPort = $proxyPort;
  235. $this->_proxyCredentials = $proxyCredentials;
  236. if ($this->_useProxy) {
  237. $credentials = explode(':', $this->_proxyCredentials);
  238. $this->_httpClientChannel->setConfig(array(
  239. 'proxy_host' => $this->_proxyUrl,
  240. 'proxy_port' => $this->_proxyPort,
  241. 'proxy_user' => $credentials[0],
  242. 'proxy_pass' => $credentials[1],
  243. ));
  244. } else {
  245. $this->_httpClientChannel->setConfig(array(
  246. 'proxy_host' => '',
  247. 'proxy_port' => 8080,
  248. 'proxy_user' => '',
  249. 'proxy_pass' => '',
  250. ));
  251. }
  252. }
  253. /**
  254. * Returns the Windows Azure account name
  255. *
  256. * @return string
  257. */
  258. public function getAccountName()
  259. {
  260. return $this->_accountName;
  261. }
  262. /**
  263. * Get base URL for creating requests
  264. *
  265. * @return string
  266. */
  267. public function getBaseUrl()
  268. {
  269. if ($this->_usePathStyleUri) {
  270. return 'http://' . $this->_host . '/' . $this->_accountName;
  271. } else {
  272. return 'http://' . $this->_accountName . '.' . $this->_host;
  273. }
  274. }
  275. /**
  276. * Set Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  277. *
  278. * @param Zend_Service_WindowsAzure_Credentials_CredentialsAbstract $credentials Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance to use for request signing.
  279. */
  280. public function setCredentials(Zend_Service_WindowsAzure_Credentials_CredentialsAbstract $credentials)
  281. {
  282. $this->_credentials = $credentials;
  283. $this->_credentials->setAccountName($this->_accountName);
  284. $this->_credentials->setAccountkey($this->_accountKey);
  285. $this->_credentials->setUsePathStyleUri($this->_usePathStyleUri);
  286. }
  287. /**
  288. * Get Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  289. *
  290. * @return Zend_Service_WindowsAzure_Credentials_CredentialsAbstract
  291. */
  292. public function getCredentials()
  293. {
  294. return $this->_credentials;
  295. }
  296. /**
  297. * Perform request using Zend_Http_Client channel
  298. *
  299. * @param string $path Path
  300. * @param string $queryString Query string
  301. * @param string $httpVerb HTTP verb the request will use
  302. * @param array $headers x-ms headers to add
  303. * @param boolean $forTableStorage Is the request for table storage?
  304. * @param mixed $rawData Optional RAW HTTP data to be sent over the wire
  305. * @param string $resourceType Resource type
  306. * @param string $requiredPermission Required permission
  307. * @return Zend_Http_Response
  308. */
  309. protected function _performRequest(
  310. $path = '/',
  311. $queryString = '',
  312. $httpVerb = Zend_Http_Client::GET,
  313. $headers = array(),
  314. $forTableStorage = false,
  315. $rawData = null,
  316. $resourceType = Zend_Service_WindowsAzure_Storage::RESOURCE_UNKNOWN,
  317. $requiredPermission = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::PERMISSION_READ
  318. ) {
  319. // Clean path
  320. if (strpos($path, '/') !== 0) {
  321. $path = '/' . $path;
  322. }
  323. // Clean headers
  324. if (is_null($headers)) {
  325. $headers = array();
  326. }
  327. // Ensure cUrl will also work correctly:
  328. // - disable Content-Type if required
  329. // - disable Expect: 100 Continue
  330. if (!isset($headers["Content-Type"])) {
  331. $headers["Content-Type"] = '';
  332. }
  333. $headers["Expect"]= '';
  334. // Add version header
  335. $headers['x-ms-version'] = $this->_apiVersion;
  336. // URL encoding
  337. $path = self::urlencode($path);
  338. $queryString = self::urlencode($queryString);
  339. // Generate URL and sign request
  340. $requestUrl = $this->_credentials
  341. ->signRequestUrl($this->getBaseUrl() . $path . $queryString, $resourceType, $requiredPermission);
  342. $requestHeaders = $this->_credentials
  343. ->signRequestHeaders($httpVerb, $path, $queryString, $headers, $forTableStorage, $resourceType, $requiredPermission, $rawData);
  344. // Prepare request
  345. $this->_httpClientChannel->resetParameters(true);
  346. $this->_httpClientChannel->setUri($requestUrl);
  347. $this->_httpClientChannel->setHeaders($requestHeaders);
  348. $this->_httpClientChannel->setRawData($rawData);
  349. // Execute request
  350. $response = $this->_retryPolicy->execute(
  351. array($this->_httpClientChannel, 'request'),
  352. array($httpVerb)
  353. );
  354. return $response;
  355. }
  356. /**
  357. * Parse result from Zend_Http_Response
  358. *
  359. * @param Zend_Http_Response $response Response from HTTP call
  360. * @return object
  361. * @throws Zend_Service_WindowsAzure_Exception
  362. */
  363. protected function _parseResponse(Zend_Http_Response $response = null)
  364. {
  365. if (is_null($response)) {
  366. require_once 'Zend/Service/WindowsAzure/Exception.php';
  367. throw new Zend_Service_WindowsAzure_Exception('Response should not be null.');
  368. }
  369. $xml = @simplexml_load_string($response->getBody());
  370. if ($xml !== false) {
  371. // Fetch all namespaces
  372. $namespaces = array_merge($xml->getNamespaces(true), $xml->getDocNamespaces(true));
  373. // Register all namespace prefixes
  374. foreach ($namespaces as $prefix => $ns) {
  375. if ($prefix != '') {
  376. $xml->registerXPathNamespace($prefix, $ns);
  377. }
  378. }
  379. }
  380. return $xml;
  381. }
  382. /**
  383. * Generate metadata headers
  384. *
  385. * @param array $metadata
  386. * @return HTTP headers containing metadata
  387. */
  388. protected function _generateMetadataHeaders($metadata = array())
  389. {
  390. // Validate
  391. if (!is_array($metadata)) {
  392. return array();
  393. }
  394. // Return headers
  395. $headers = array();
  396. foreach ($metadata as $key => $value) {
  397. if (strpos($value, "\r") !== false || strpos($value, "\n") !== false) {
  398. require_once 'Zend/Service/WindowsAzure/Exception.php';
  399. throw new Zend_Service_WindowsAzure_Exception('Metadata cannot contain newline characters.');
  400. }
  401. if (!self::isValidMetadataName($key)) {
  402. require_once 'Zend/Service/WindowsAzure/Exception.php';
  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. }