Storage.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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: Storage.php 36457 2010-01-04 07:36:33Z unknown $
  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. * Current API version
  78. *
  79. * @var string
  80. */
  81. protected $_apiVersion = '2009-04-14';
  82. /**
  83. * Storage host name
  84. *
  85. * @var string
  86. */
  87. protected $_host = '';
  88. /**
  89. * Account name for Windows Azure
  90. *
  91. * @var string
  92. */
  93. protected $_accountName = '';
  94. /**
  95. * Account key for Windows Azure
  96. *
  97. * @var string
  98. */
  99. protected $_accountKey = '';
  100. /**
  101. * Use path-style URI's
  102. *
  103. * @var boolean
  104. */
  105. protected $_usePathStyleUri = false;
  106. /**
  107. * Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  108. *
  109. * @var Zend_Service_WindowsAzure_Credentials_CredentialsAbstract
  110. */
  111. protected $_credentials = null;
  112. /**
  113. * Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract instance
  114. *
  115. * @var Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract
  116. */
  117. protected $_retryPolicy = null;
  118. /**
  119. * Zend_Http_Client channel used for communication with REST services
  120. *
  121. * @var Zend_Http_Client
  122. */
  123. protected $_httpClientChannel = null;
  124. /**
  125. * Use proxy?
  126. *
  127. * @var boolean
  128. */
  129. protected $_useProxy = false;
  130. /**
  131. * Proxy url
  132. *
  133. * @var string
  134. */
  135. protected $_proxyUrl = '';
  136. /**
  137. * Proxy port
  138. *
  139. * @var int
  140. */
  141. protected $_proxyPort = 80;
  142. /**
  143. * Proxy credentials
  144. *
  145. * @var string
  146. */
  147. protected $_proxyCredentials = '';
  148. /**
  149. * Creates a new Zend_Service_WindowsAzure_Storage instance
  150. *
  151. * @param string $host Storage host name
  152. * @param string $accountName Account name for Windows Azure
  153. * @param string $accountKey Account key for Windows Azure
  154. * @param boolean $usePathStyleUri Use path-style URI's
  155. * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  156. */
  157. public function __construct(
  158. $host = self::URL_DEV_BLOB,
  159. $accountName = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_ACCOUNT,
  160. $accountKey = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_KEY,
  161. $usePathStyleUri = false,
  162. Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null
  163. ) {
  164. $this->_host = $host;
  165. $this->_accountName = $accountName;
  166. $this->_accountKey = $accountKey;
  167. $this->_usePathStyleUri = $usePathStyleUri;
  168. // Using local storage?
  169. if (!$this->_usePathStyleUri
  170. && ($this->_host == self::URL_DEV_BLOB
  171. || $this->_host == self::URL_DEV_QUEUE
  172. || $this->_host == self::URL_DEV_TABLE)
  173. ) {
  174. // Local storage
  175. $this->_usePathStyleUri = true;
  176. }
  177. if (is_null($this->_credentials)) {
  178. $this->_credentials = new Zend_Service_WindowsAzure_Credentials_SharedKey(
  179. $this->_accountName, $this->_accountKey, $this->_usePathStyleUri);
  180. }
  181. $this->_retryPolicy = $retryPolicy;
  182. if (is_null($this->_retryPolicy)) {
  183. $this->_retryPolicy = Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
  184. }
  185. // Setup default Zend_Http_Client channel
  186. $this->_httpClientChannel = new Zend_Http_Client(
  187. null,
  188. array(
  189. 'adapter' => 'Zend_Http_Client_Adapter_Proxy',
  190. 'curloptions' => array(
  191. CURLOPT_FOLLOWLOCATION => true,
  192. CURLOPT_TIMEOUT => 120,
  193. )
  194. )
  195. );
  196. }
  197. /**
  198. * Set the HTTP client channel to use
  199. *
  200. * @param Zend_Http_Client_Adapter_Interface|string $adapterInstance Adapter instance or adapter class name.
  201. */
  202. public function setHttpClientChannel($adapterInstance = 'Zend_Http_Client_Adapter_Proxy')
  203. {
  204. $this->_httpClientChannel->setAdapter($adapterInstance);
  205. }
  206. /**
  207. * Set retry policy to use when making requests
  208. *
  209. * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  210. */
  211. public function setRetryPolicy(Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null)
  212. {
  213. $this->_retryPolicy = $retryPolicy;
  214. if (is_null($this->_retryPolicy)) {
  215. $this->_retryPolicy = Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
  216. }
  217. }
  218. /**
  219. * Set proxy
  220. *
  221. * @param boolean $useProxy Use proxy?
  222. * @param string $proxyUrl Proxy URL
  223. * @param int $proxyPort Proxy port
  224. * @param string $proxyCredentials Proxy credentials
  225. */
  226. public function setProxy($useProxy = false, $proxyUrl = '', $proxyPort = 80, $proxyCredentials = '')
  227. {
  228. $this->_useProxy = $useProxy;
  229. $this->_proxyUrl = $proxyUrl;
  230. $this->_proxyPort = $proxyPort;
  231. $this->_proxyCredentials = $proxyCredentials;
  232. if ($this->_useProxy) {
  233. $credentials = explode(':', $this->_proxyCredentials);
  234. $this->_httpClientChannel->setConfig(array(
  235. 'proxy_host' => $this->_proxyUrl,
  236. 'proxy_port' => $this->_proxyPort,
  237. 'proxy_user' => $credentials[0],
  238. 'proxy_pass' => $credentials[1],
  239. ));
  240. } else {
  241. $this->_httpClientChannel->setConfig(array(
  242. 'proxy_host' => '',
  243. 'proxy_port' => 8080,
  244. 'proxy_user' => '',
  245. 'proxy_pass' => '',
  246. ));
  247. }
  248. }
  249. /**
  250. * Returns the Windows Azure account name
  251. *
  252. * @return string
  253. */
  254. public function getAccountName()
  255. {
  256. return $this->_accountName;
  257. }
  258. /**
  259. * Get base URL for creating requests
  260. *
  261. * @return string
  262. */
  263. public function getBaseUrl()
  264. {
  265. if ($this->_usePathStyleUri) {
  266. return 'http://' . $this->_host . '/' . $this->_accountName;
  267. } else {
  268. return 'http://' . $this->_accountName . '.' . $this->_host;
  269. }
  270. }
  271. /**
  272. * Set Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  273. *
  274. * @param Zend_Service_WindowsAzure_Credentials_CredentialsAbstract $credentials Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance to use for request signing.
  275. */
  276. public function setCredentials(Zend_Service_WindowsAzure_Credentials_CredentialsAbstract $credentials)
  277. {
  278. $this->_credentials = $credentials;
  279. $this->_credentials->setAccountName($this->_accountName);
  280. $this->_credentials->setAccountkey($this->_accountKey);
  281. $this->_credentials->setUsePathStyleUri($this->_usePathStyleUri);
  282. }
  283. /**
  284. * Get Zend_Service_WindowsAzure_Credentials_CredentialsAbstract instance
  285. *
  286. * @return Zend_Service_WindowsAzure_Credentials_CredentialsAbstract
  287. */
  288. public function getCredentials()
  289. {
  290. return $this->_credentials;
  291. }
  292. /**
  293. * Perform request using Zend_Http_Client channel
  294. *
  295. * @param string $path Path
  296. * @param string $queryString Query string
  297. * @param string $httpVerb HTTP verb the request will use
  298. * @param array $headers x-ms headers to add
  299. * @param boolean $forTableStorage Is the request for table storage?
  300. * @param mixed $rawData Optional RAW HTTP data to be sent over the wire
  301. * @param string $resourceType Resource type
  302. * @param string $requiredPermission Required permission
  303. * @return Zend_Http_Response
  304. */
  305. protected function _performRequest(
  306. $path = '/',
  307. $queryString = '',
  308. $httpVerb = Zend_Http_Client::GET,
  309. $headers = array(),
  310. $forTableStorage = false,
  311. $rawData = null,
  312. $resourceType = Zend_Service_WindowsAzure_Storage::RESOURCE_UNKNOWN,
  313. $requiredPermission = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::PERMISSION_READ
  314. ) {
  315. // Clean path
  316. if (strpos($path, '/') !== 0) {
  317. $path = '/' . $path;
  318. }
  319. // Clean headers
  320. if (is_null($headers)) {
  321. $headers = array();
  322. }
  323. // Ensure cUrl will also work correctly:
  324. // - disable Content-Type if required
  325. // - disable Expect: 100 Continue
  326. if (!isset($headers["Content-Type"])) {
  327. $headers["Content-Type"] = '';
  328. }
  329. $headers["Expect"]= '';
  330. // Add version header
  331. $headers['x-ms-version'] = $this->_apiVersion;
  332. // URL encoding
  333. $path = self::urlencode($path);
  334. $queryString = self::urlencode($queryString);
  335. // Generate URL and sign request
  336. $requestUrl = $this->_credentials
  337. ->signRequestUrl($this->getBaseUrl() . $path . $queryString, $resourceType, $requiredPermission);
  338. $requestHeaders = $this->_credentials
  339. ->signRequestHeaders($httpVerb, $path, $queryString, $headers, $forTableStorage, $resourceType, $requiredPermission);
  340. // Prepare request
  341. $this->_httpClientChannel->resetParameters(true);
  342. $this->_httpClientChannel->setUri($requestUrl);
  343. $this->_httpClientChannel->setHeaders($requestHeaders);
  344. $this->_httpClientChannel->setRawData($rawData);
  345. // Execute request
  346. $response = $this->_retryPolicy->execute(
  347. array($this->_httpClientChannel, 'request'),
  348. array($httpVerb)
  349. );
  350. return $response;
  351. }
  352. /**
  353. * Parse result from Zend_Http_Response
  354. *
  355. * @param Zend_Http_Response $response Response from HTTP call
  356. * @return object
  357. * @throws Zend_Service_WindowsAzure_Exception
  358. */
  359. protected function _parseResponse(Zend_Http_Response $response = null)
  360. {
  361. if (is_null($response)) {
  362. throw new Zend_Service_WindowsAzure_Exception('Response should not be null.');
  363. }
  364. $xml = @simplexml_load_string($response->getBody());
  365. if ($xml !== false) {
  366. // Fetch all namespaces
  367. $namespaces = array_merge($xml->getNamespaces(true), $xml->getDocNamespaces(true));
  368. // Register all namespace prefixes
  369. foreach ($namespaces as $prefix => $ns) {
  370. if ($prefix != '') {
  371. $xml->registerXPathNamespace($prefix, $ns);
  372. }
  373. }
  374. }
  375. return $xml;
  376. }
  377. /**
  378. * Generate metadata headers
  379. *
  380. * @param array $metadata
  381. * @return HTTP headers containing metadata
  382. */
  383. protected function _generateMetadataHeaders($metadata = array())
  384. {
  385. // Validate
  386. if (!is_array($metadata)) {
  387. return array();
  388. }
  389. // Return headers
  390. $headers = array();
  391. foreach ($metadata as $key => $value) {
  392. if (strpos($value, "\r") !== false || strpos($value, "\n") !== false) {
  393. throw new Zend_Service_WindowsAzure_Exception('Metadata cannot contain newline characters.');
  394. }
  395. $headers["x-ms-meta-" . strtolower($key)] = $value;
  396. }
  397. return $headers;
  398. }
  399. /**
  400. * Parse metadata errors
  401. *
  402. * @param array $headers HTTP headers containing metadata
  403. * @return array
  404. */
  405. protected function _parseMetadataHeaders($headers = array())
  406. {
  407. // Validate
  408. if (!is_array($headers)) {
  409. return array();
  410. }
  411. // Return metadata
  412. $metadata = array();
  413. foreach ($headers as $key => $value) {
  414. if (substr(strtolower($key), 0, 10) == "x-ms-meta-") {
  415. $metadata[str_replace("x-ms-meta-", '', strtolower($key))] = $value;
  416. }
  417. }
  418. return $metadata;
  419. }
  420. /**
  421. * Generate ISO 8601 compliant date string in UTC time zone
  422. *
  423. * @param int $timestamp
  424. * @return string
  425. */
  426. public function isoDate($timestamp = null)
  427. {
  428. $tz = @date_default_timezone_get();
  429. @date_default_timezone_set('UTC');
  430. if (is_null($timestamp)) {
  431. $timestamp = time();
  432. }
  433. $returnValue = str_replace('+00:00', '.0000000Z', @date('c', $timestamp));
  434. @date_default_timezone_set($tz);
  435. return $returnValue;
  436. }
  437. /**
  438. * URL encode function
  439. *
  440. * @param string $value Value to encode
  441. * @return string Encoded value
  442. */
  443. public static function urlencode($value)
  444. {
  445. return str_replace(' ', '%20', $value);
  446. }
  447. }