Storage.php 15 KB

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