PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/branches/v2.1.0/library/Microsoft/WindowsAzure/Storage/Table.php

#
PHP | 919 lines | 508 code | 107 blank | 304 comment | 98 complexity | b11f3e97f21005a6c3e4827196e01362 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Copyright (c) 2009 - 2010, RealDolmen
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * * Neither the name of RealDolmen nor the
  14. * names of its contributors may be used to endorse or promote products
  15. * derived from this software without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY RealDolmen ''AS IS'' AND ANY
  18. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. * DISCLAIMED. IN NO EVENT SHALL RealDolmen BE LIABLE FOR ANY
  21. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. *
  28. * @category Microsoft
  29. * @package Microsoft_WindowsAzure
  30. * @subpackage Storage
  31. * @copyright Copyright (c) 2009 - 2010, RealDolmen (http://www.realdolmen.com)
  32. * @license http://phpazure.codeplex.com/license
  33. * @version $Id: Blob.php 14561 2009-05-07 08:05:12Z unknown $
  34. */
  35. /**
  36. * @see Microsoft_WindowsAzure_Credentials_CredentialsAbstract
  37. */
  38. require_once 'Microsoft/WindowsAzure/Credentials/CredentialsAbstract.php';
  39. /**
  40. * @see Microsoft_WindowsAzure_Credentials_SharedKey
  41. */
  42. require_once 'Microsoft/WindowsAzure/Credentials/SharedKey.php';
  43. /**
  44. * @see Microsoft_WindowsAzure_Credentials_SharedKeyLite
  45. */
  46. require_once 'Microsoft/WindowsAzure/Credentials/SharedKeyLite.php';
  47. /**
  48. * @see Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract
  49. */
  50. require_once 'Microsoft/WindowsAzure/RetryPolicy/RetryPolicyAbstract.php';
  51. /**
  52. * @see Microsoft_Http_Client
  53. */
  54. require_once 'Microsoft/Http/Client.php';
  55. /**
  56. * @see Microsoft_Http_Response
  57. */
  58. require_once 'Microsoft/Http/Response.php';
  59. /**
  60. * @see Microsoft_WindowsAzure_Storage
  61. */
  62. require_once 'Microsoft/WindowsAzure/Storage.php';
  63. /**
  64. * @see Microsoft_WindowsAzure_Storage_BatchStorageAbstract
  65. */
  66. require_once 'Microsoft/WindowsAzure/Storage/BatchStorageAbstract.php';
  67. /**
  68. * @see Microsoft_WindowsAzure_Storage_TableInstance
  69. */
  70. require_once 'Microsoft/WindowsAzure/Storage/TableInstance.php';
  71. /**
  72. * @see Microsoft_WindowsAzure_Storage_TableEntity
  73. */
  74. require_once 'Microsoft/WindowsAzure/Storage/TableEntity.php';
  75. /**
  76. * @see Microsoft_WindowsAzure_Storage_DynamicTableEntity
  77. */
  78. require_once 'Microsoft/WindowsAzure/Storage/DynamicTableEntity.php';
  79. /**
  80. * @see Microsoft_WindowsAzure_Storage_TableEntityQuery
  81. */
  82. require_once 'Microsoft/WindowsAzure/Storage/TableEntityQuery.php';
  83. /**
  84. * @see Microsoft_WindowsAzure_Exception
  85. */
  86. require_once 'Microsoft/WindowsAzure/Exception.php';
  87. /**
  88. * @category Microsoft
  89. * @package Microsoft_WindowsAzure
  90. * @subpackage Storage
  91. * @copyright Copyright (c) 2009 - 2010, RealDolmen (http://www.realdolmen.com)
  92. * @license http://phpazure.codeplex.com/license
  93. */
  94. class Microsoft_WindowsAzure_Storage_Table
  95. extends Microsoft_WindowsAzure_Storage_BatchStorageAbstract
  96. {
  97. /**
  98. * Throw Microsoft_WindowsAzure_Exception when a property is not specified in Windows Azure?
  99. * Defaults to true, making behaviour similar to Windows Azure StorageClient in .NET.
  100. *
  101. * @var boolean
  102. */
  103. protected $_throwExceptionOnMissingData = true;
  104. /**
  105. * Throw Microsoft_WindowsAzure_Exception when a property is not specified in Windows Azure?
  106. * Defaults to true, making behaviour similar to Windows Azure StorageClient in .NET.
  107. *
  108. * @param boolean $value
  109. */
  110. public function setThrowExceptionOnMissingData($value = true)
  111. {
  112. $this->_throwExceptionOnMissingData = $value;
  113. }
  114. /**
  115. * Throw Microsoft_WindowsAzure_Exception when a property is not specified in Windows Azure?
  116. */
  117. public function getThrowExceptionOnMissingData()
  118. {
  119. return $this->_throwExceptionOnMissingData;
  120. }
  121. /**
  122. * Creates a new Microsoft_WindowsAzure_Storage_Table instance
  123. *
  124. * @param string $host Storage host name
  125. * @param string $accountName Account name for Windows Azure
  126. * @param string $accountKey Account key for Windows Azure
  127. * @param boolean $usePathStyleUri Use path-style URI's
  128. * @param Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  129. */
  130. public function __construct($host = Microsoft_WindowsAzure_Storage::URL_DEV_TABLE, $accountName = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_ACCOUNT, $accountKey = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_KEY, $usePathStyleUri = false, Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null)
  131. {
  132. parent::__construct($host, $accountName, $accountKey, $usePathStyleUri, $retryPolicy);
  133. // Always use SharedKeyLite authentication
  134. $this->_credentials = new Microsoft_WindowsAzure_Credentials_SharedKeyLite($accountName, $accountKey, $this->_usePathStyleUri);
  135. // API version
  136. $this->_apiVersion = '2009-09-19';
  137. }
  138. /**
  139. * Check if a table exists
  140. *
  141. * @param string $tableName Table name
  142. * @return boolean
  143. */
  144. public function tableExists($tableName = '')
  145. {
  146. if ($tableName === '') {
  147. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  148. }
  149. // List tables
  150. $tables = $this->listTables(); // 2009-09-19 does not support $this->listTables($tableName); all of a sudden...
  151. foreach ($tables as $table) {
  152. if ($table->Name == $tableName) {
  153. return true;
  154. }
  155. }
  156. return false;
  157. }
  158. /**
  159. * List tables
  160. *
  161. * @param string $nextTableName Next table name, used for listing tables when total amount of tables is > 1000.
  162. * @return array
  163. * @throws Microsoft_WindowsAzure_Exception
  164. */
  165. public function listTables($nextTableName = '')
  166. {
  167. // Build query string
  168. $queryString = array();
  169. if ($nextTableName != '') {
  170. $queryString[] = 'NextTableName=' . $nextTableName;
  171. }
  172. $queryString = self::createQueryStringFromArray($queryString);
  173. // Perform request
  174. $response = $this->_performRequest('Tables', $queryString, Microsoft_Http_Client::GET, null, true);
  175. if ($response->isSuccessful()) {
  176. // Parse result
  177. $result = $this->_parseResponse($response);
  178. if (!$result || !$result->entry) {
  179. return array();
  180. }
  181. $entries = null;
  182. if (count($result->entry) > 1) {
  183. $entries = $result->entry;
  184. } else {
  185. $entries = array($result->entry);
  186. }
  187. // Create return value
  188. $returnValue = array();
  189. foreach ($entries as $entry) {
  190. $tableName = $entry->xpath('.//m:properties/d:TableName');
  191. $tableName = (string)$tableName[0];
  192. $returnValue[] = new Microsoft_WindowsAzure_Storage_TableInstance(
  193. (string)$entry->id,
  194. $tableName,
  195. (string)$entry->link['href'],
  196. (string)$entry->updated
  197. );
  198. }
  199. // More tables?
  200. if (!is_null($response->getHeader('x-ms-continuation-NextTableName'))) {
  201. $returnValue = array_merge($returnValue, $this->listTables($response->getHeader('x-ms-continuation-NextTableName')));
  202. }
  203. return $returnValue;
  204. } else {
  205. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  206. }
  207. }
  208. /**
  209. * Create table
  210. *
  211. * @param string $tableName Table name
  212. * @return Microsoft_WindowsAzure_Storage_TableInstance
  213. * @throws Microsoft_WindowsAzure_Exception
  214. */
  215. public function createTable($tableName = '')
  216. {
  217. if ($tableName === '') {
  218. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  219. }
  220. // Generate request body
  221. $requestBody = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  222. <entry
  223. xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
  224. xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
  225. xmlns="http://www.w3.org/2005/Atom">
  226. <title />
  227. <updated>{tpl:Updated}</updated>
  228. <author>
  229. <name />
  230. </author>
  231. <id />
  232. <content type="application/xml">
  233. <m:properties>
  234. <d:TableName>{tpl:TableName}</d:TableName>
  235. </m:properties>
  236. </content>
  237. </entry>';
  238. $requestBody = $this->_fillTemplate($requestBody, array(
  239. 'BaseUrl' => $this->getBaseUrl(),
  240. 'TableName' => htmlspecialchars($tableName),
  241. 'Updated' => $this->isoDate(),
  242. 'AccountName' => $this->_accountName
  243. ));
  244. // Add header information
  245. $headers = array();
  246. $headers['Content-Type'] = 'application/atom+xml';
  247. $headers['DataServiceVersion'] = '1.0;NetFx';
  248. $headers['MaxDataServiceVersion'] = '1.0;NetFx';
  249. // Perform request
  250. $response = $this->_performRequest('Tables', '', Microsoft_Http_Client::POST, $headers, true, $requestBody);
  251. if ($response->isSuccessful()) {
  252. // Parse response
  253. $entry = $this->_parseResponse($response);
  254. $tableName = $entry->xpath('.//m:properties/d:TableName');
  255. $tableName = (string)$tableName[0];
  256. return new Microsoft_WindowsAzure_Storage_TableInstance(
  257. (string)$entry->id,
  258. $tableName,
  259. (string)$entry->link['href'],
  260. (string)$entry->updated
  261. );
  262. } else {
  263. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  264. }
  265. }
  266. /**
  267. * Create table if it does not exist
  268. *
  269. * @param string $tableName Table name
  270. * @throws Microsoft_WindowsAzure_Exception
  271. */
  272. public function createTableIfNotExists($tableName = '')
  273. {
  274. if (!$this->tableExists($tableName)) {
  275. $this->createTable($tableName);
  276. }
  277. }
  278. /**
  279. * Delete table
  280. *
  281. * @param string $tableName Table name
  282. * @throws Microsoft_WindowsAzure_Exception
  283. */
  284. public function deleteTable($tableName = '')
  285. {
  286. if ($tableName === '') {
  287. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  288. }
  289. // Add header information
  290. $headers = array();
  291. $headers['Content-Type'] = 'application/atom+xml';
  292. // Perform request
  293. $response = $this->_performRequest('Tables(\'' . $tableName . '\')', '', Microsoft_Http_Client::DELETE, $headers, true, null);
  294. if (!$response->isSuccessful()) {
  295. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  296. }
  297. }
  298. /**
  299. * Insert entity into table
  300. *
  301. * @param string $tableName Table name
  302. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to insert
  303. * @return Microsoft_WindowsAzure_Storage_TableEntity
  304. * @throws Microsoft_WindowsAzure_Exception
  305. */
  306. public function insertEntity($tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null)
  307. {
  308. if ($tableName === '') {
  309. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  310. }
  311. if (is_null($entity)) {
  312. throw new Microsoft_WindowsAzure_Exception('Entity is not specified.');
  313. }
  314. // Generate request body
  315. $requestBody = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  316. <entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  317. <title />
  318. <updated>{tpl:Updated}</updated>
  319. <author>
  320. <name />
  321. </author>
  322. <id />
  323. <content type="application/xml">
  324. <m:properties>
  325. {tpl:Properties}
  326. </m:properties>
  327. </content>
  328. </entry>';
  329. $requestBody = $this->_fillTemplate($requestBody, array(
  330. 'Updated' => $this->isoDate(),
  331. 'Properties' => $this->_generateAzureRepresentation($entity)
  332. ));
  333. // Add header information
  334. $headers = array();
  335. $headers['Content-Type'] = 'application/atom+xml';
  336. // Perform request
  337. $response = null;
  338. if ($this->isInBatch()) {
  339. $this->getCurrentBatch()->enlistOperation($tableName, '', Microsoft_Http_Client::POST, $headers, true, $requestBody);
  340. return null;
  341. } else {
  342. $response = $this->_performRequest($tableName, '', Microsoft_Http_Client::POST, $headers, true, $requestBody);
  343. }
  344. if ($response->isSuccessful()) {
  345. // Parse result
  346. $result = $this->_parseResponse($response);
  347. $timestamp = $result->xpath('//m:properties/d:Timestamp');
  348. $timestamp = (string)$timestamp[0];
  349. $etag = $result->attributes('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
  350. $etag = (string)$etag['etag'];
  351. // Update properties
  352. $entity->setTimestamp($timestamp);
  353. $entity->setEtag($etag);
  354. return $entity;
  355. } else {
  356. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  357. }
  358. }
  359. /**
  360. * Delete entity from table
  361. *
  362. * @param string $tableName Table name
  363. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to delete
  364. * @param boolean $verifyEtag Verify etag of the entity (used for concurrency)
  365. * @throws Microsoft_WindowsAzure_Exception
  366. */
  367. public function deleteEntity($tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false)
  368. {
  369. if ($tableName === '') {
  370. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  371. }
  372. if (is_null($entity)) {
  373. throw new Microsoft_WindowsAzure_Exception('Entity is not specified.');
  374. }
  375. // Add header information
  376. $headers = array();
  377. if (!$this->isInBatch()) {
  378. // http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/9e255447-4dc7-458a-99d3-bdc04bdc5474/
  379. $headers['Content-Type'] = 'application/atom+xml';
  380. }
  381. $headers['Content-Length'] = 0;
  382. if (!$verifyEtag) {
  383. $headers['If-Match'] = '*';
  384. } else {
  385. $headers['If-Match'] = $entity->getEtag();
  386. }
  387. // Perform request
  388. $response = null;
  389. if ($this->isInBatch()) {
  390. $this->getCurrentBatch()->enlistOperation($tableName . '(PartitionKey=\'' . $entity->getPartitionKey() . '\', RowKey=\'' . $entity->getRowKey() . '\')', '', Microsoft_Http_Client::DELETE, $headers, true, null);
  391. return null;
  392. } else {
  393. $response = $this->_performRequest($tableName . '(PartitionKey=\'' . $entity->getPartitionKey() . '\', RowKey=\'' . $entity->getRowKey() . '\')', '', Microsoft_Http_Client::DELETE, $headers, true, null);
  394. }
  395. if (!$response->isSuccessful()) {
  396. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  397. }
  398. }
  399. /**
  400. * Retrieve entity from table, by id
  401. *
  402. * @param string $tableName Table name
  403. * @param string $partitionKey Partition key
  404. * @param string $rowKey Row key
  405. * @param string $entityClass Entity class name*
  406. * @return Microsoft_WindowsAzure_Storage_TableEntity
  407. * @throws Microsoft_WindowsAzure_Exception
  408. */
  409. public function retrieveEntityById($tableName = '', $partitionKey = '', $rowKey = '', $entityClass = 'Microsoft_WindowsAzure_Storage_DynamicTableEntity')
  410. {
  411. if ($tableName === '') {
  412. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  413. }
  414. if ($partitionKey === '') {
  415. throw new Microsoft_WindowsAzure_Exception('Partition key is not specified.');
  416. }
  417. if ($rowKey === '') {
  418. throw new Microsoft_WindowsAzure_Exception('Row key is not specified.');
  419. }
  420. if ($entityClass === '') {
  421. throw new Microsoft_WindowsAzure_Exception('Entity class is not specified.');
  422. }
  423. // Check for combined size of partition key and row key
  424. // http://msdn.microsoft.com/en-us/library/dd179421.aspx
  425. if (strlen($partitionKey . $rowKey) >= 256) {
  426. // Start a batch if possible
  427. if ($this->isInBatch()) {
  428. throw new Microsoft_WindowsAzure_Exception('Entity cannot be retrieved. A transaction is required to retrieve the entity, but another transaction is already active.');
  429. }
  430. $this->startBatch();
  431. }
  432. // Fetch entities from Azure
  433. $result = $this->retrieveEntities(
  434. $this->select()
  435. ->from($tableName)
  436. ->wherePartitionKey($partitionKey)
  437. ->whereRowKey($rowKey),
  438. '',
  439. $entityClass
  440. );
  441. // Return
  442. if (count($result) == 1) {
  443. return $result[0];
  444. }
  445. return null;
  446. }
  447. /**
  448. * Create a new Microsoft_WindowsAzure_Storage_TableEntityQuery
  449. *
  450. * @return Microsoft_WindowsAzure_Storage_TableEntityQuery
  451. */
  452. public function select()
  453. {
  454. return new Microsoft_WindowsAzure_Storage_TableEntityQuery();
  455. }
  456. /**
  457. * Retrieve entities from table
  458. *
  459. * @param string $tableName|Microsoft_WindowsAzure_Storage_TableEntityQuery Table name -or- Microsoft_WindowsAzure_Storage_TableEntityQuery instance
  460. * @param string $filter Filter condition (not applied when $tableName is a Microsoft_WindowsAzure_Storage_TableEntityQuery instance)
  461. * @param string $entityClass Entity class name
  462. * @param string $nextPartitionKey Next partition key, used for listing entities when total amount of entities is > 1000.
  463. * @param string $nextRowKey Next row key, used for listing entities when total amount of entities is > 1000.
  464. * @return array Array of Microsoft_WindowsAzure_Storage_TableEntity
  465. * @throws Microsoft_WindowsAzure_Exception
  466. */
  467. public function retrieveEntities($tableName = '', $filter = '', $entityClass = 'Microsoft_WindowsAzure_Storage_DynamicTableEntity', $nextPartitionKey = null, $nextRowKey = null)
  468. {
  469. if ($tableName === '') {
  470. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  471. }
  472. if ($entityClass === '') {
  473. throw new Microsoft_WindowsAzure_Exception('Entity class is not specified.');
  474. }
  475. // Convenience...
  476. if (class_exists($filter)) {
  477. $entityClass = $filter;
  478. $filter = '';
  479. }
  480. // Query string
  481. $queryString = '';
  482. // Determine query
  483. if (is_string($tableName)) {
  484. // Option 1: $tableName is a string
  485. // Append parentheses
  486. $tableName .= '()';
  487. // Build query
  488. $query = array();
  489. // Filter?
  490. if ($filter !== '') {
  491. $query[] = '$filter=' . Microsoft_WindowsAzure_Storage_TableEntityQuery::encodeQuery($filter);
  492. }
  493. // Build queryString
  494. if (count($query) > 0) {
  495. $queryString = '?' . implode('&', $query);
  496. }
  497. } else if (get_class($tableName) == 'Microsoft_WindowsAzure_Storage_TableEntityQuery') {
  498. // Option 2: $tableName is a Microsoft_WindowsAzure_Storage_TableEntityQuery instance
  499. // Build queryString
  500. $queryString = $tableName->assembleQueryString(true);
  501. // Change $tableName
  502. $tableName = $tableName->assembleFrom(true);
  503. } else {
  504. throw new Microsoft_WindowsAzure_Exception('Invalid argument: $tableName');
  505. }
  506. // Add continuation querystring parameters?
  507. if (!is_null($nextPartitionKey) && !is_null($nextRowKey)) {
  508. if ($queryString !== '') {
  509. $queryString .= '&';
  510. }
  511. $queryString .= '&NextPartitionKey=' . rawurlencode($nextPartitionKey) . '&NextRowKey=' . rawurlencode($nextRowKey);
  512. }
  513. // Perform request
  514. $response = null;
  515. if ($this->isInBatch() && $this->getCurrentBatch()->getOperationCount() == 0) {
  516. $this->getCurrentBatch()->enlistOperation($tableName, $queryString, Microsoft_Http_Client::GET, array(), true, null);
  517. $response = $this->getCurrentBatch()->commit();
  518. // Get inner response (multipart)
  519. $innerResponse = $response->getBody();
  520. $innerResponse = substr($innerResponse, strpos($innerResponse, 'HTTP/1.1 200 OK'));
  521. $innerResponse = substr($innerResponse, 0, strpos($innerResponse, '--batchresponse'));
  522. $response = Microsoft_Http_Response::fromString($innerResponse);
  523. } else {
  524. $response = $this->_performRequest($tableName, $queryString, Microsoft_Http_Client::GET, array(), true, null);
  525. }
  526. if ($response->isSuccessful()) {
  527. // Parse result
  528. $result = $this->_parseResponse($response);
  529. if (!$result) {
  530. return array();
  531. }
  532. $entries = null;
  533. if ($result->entry) {
  534. if (count($result->entry) > 1) {
  535. $entries = $result->entry;
  536. } else {
  537. $entries = array($result->entry);
  538. }
  539. } else {
  540. // This one is tricky... If we have properties defined, we have an entity.
  541. $properties = $result->xpath('//m:properties');
  542. if ($properties) {
  543. $entries = array($result);
  544. } else {
  545. return array();
  546. }
  547. }
  548. // Create return value
  549. $returnValue = array();
  550. foreach ($entries as $entry) {
  551. // Parse properties
  552. $properties = $entry->xpath('.//m:properties');
  553. $properties = $properties[0]->children('http://schemas.microsoft.com/ado/2007/08/dataservices');
  554. // Create entity
  555. $entity = new $entityClass('', '');
  556. $entity->setAzureValues((array)$properties, $this->_throwExceptionOnMissingData);
  557. // If we have a Microsoft_WindowsAzure_Storage_DynamicTableEntity, make sure all property types are OK
  558. if ($entity instanceof Microsoft_WindowsAzure_Storage_DynamicTableEntity) {
  559. foreach ($properties as $key => $value) {
  560. $attributes = $value->attributes('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
  561. $type = (string)$attributes['type'];
  562. if ($type !== '') {
  563. $entity->setAzurePropertyType($key, $type);
  564. }
  565. }
  566. }
  567. // Update etag
  568. $etag = $entry->attributes('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
  569. $etag = (string)$etag['etag'];
  570. $entity->setEtag($etag);
  571. // Add to result
  572. $returnValue[] = $entity;
  573. }
  574. // More entities?
  575. if (!is_null($response->getHeader('x-ms-continuation-NextPartitionKey')) && !is_null($response->getHeader('x-ms-continuation-NextRowKey'))) {
  576. if (strpos($queryString, '$top') === false) {
  577. $returnValue = array_merge($returnValue, $this->retrieveEntities($tableName, $filter, $entityClass, $response->getHeader('x-ms-continuation-NextPartitionKey'), $response->getHeader('x-ms-continuation-NextRowKey')));
  578. }
  579. }
  580. // Return
  581. return $returnValue;
  582. } else {
  583. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  584. }
  585. }
  586. /**
  587. * Update entity by replacing it
  588. *
  589. * @param string $tableName Table name
  590. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to update
  591. * @param boolean $verifyEtag Verify etag of the entity (used for concurrency)
  592. * @throws Microsoft_WindowsAzure_Exception
  593. */
  594. public function updateEntity($tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false)
  595. {
  596. return $this->_changeEntity(Microsoft_Http_Client::PUT, $tableName, $entity, $verifyEtag);
  597. }
  598. /**
  599. * Update entity by adding or updating properties
  600. *
  601. * @param string $tableName Table name
  602. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to update
  603. * @param boolean $verifyEtag Verify etag of the entity (used for concurrency)
  604. * @param array $properties Properties to merge. All properties will be used when omitted.
  605. * @throws Microsoft_WindowsAzure_Exception
  606. */
  607. public function mergeEntity($tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false, $properties = array())
  608. {
  609. $mergeEntity = null;
  610. if (is_array($properties) && count($properties) > 0) {
  611. // Build a new object
  612. $mergeEntity = new Microsoft_WindowsAzure_Storage_DynamicTableEntity($entity->getPartitionKey(), $entity->getRowKey());
  613. // Keep only values mentioned in $properties
  614. $azureValues = $entity->getAzureValues();
  615. foreach ($azureValues as $key => $value) {
  616. if (in_array($value->Name, $properties)) {
  617. $mergeEntity->setAzureProperty($value->Name, $value->Value, $value->Type);
  618. }
  619. }
  620. } else {
  621. $mergeEntity = $entity;
  622. }
  623. // Ensure entity timestamp matches updated timestamp
  624. $entity->setTimestamp($this->isoDate());
  625. return $this->_changeEntity(Microsoft_Http_Client::MERGE, $tableName, $mergeEntity, $verifyEtag);
  626. }
  627. /**
  628. * Get error message from Microsoft_Http_Response
  629. *
  630. * @param Microsoft_Http_Response $response Repsonse
  631. * @param string $alternativeError Alternative error message
  632. * @return string
  633. */
  634. protected function _getErrorMessage(Microsoft_Http_Response $response, $alternativeError = 'Unknown error.')
  635. {
  636. $response = $this->_parseResponse($response);
  637. if ($response && $response->message) {
  638. return (string)$response->message;
  639. } else {
  640. return $alternativeError;
  641. }
  642. }
  643. /**
  644. * Update entity / merge entity
  645. *
  646. * @param string $httpVerb HTTP verb to use (PUT = update, MERGE = merge)
  647. * @param string $tableName Table name
  648. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to update
  649. * @param boolean $verifyEtag Verify etag of the entity (used for concurrency)
  650. * @throws Microsoft_WindowsAzure_Exception
  651. */
  652. protected function _changeEntity($httpVerb = Microsoft_Http_Client::PUT, $tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false)
  653. {
  654. if ($tableName === '') {
  655. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  656. }
  657. if (is_null($entity)) {
  658. throw new Microsoft_WindowsAzure_Exception('Entity is not specified.');
  659. }
  660. // Add header information
  661. $headers = array();
  662. $headers['Content-Type'] = 'application/atom+xml';
  663. $headers['Content-Length'] = 0;
  664. if (!$verifyEtag) {
  665. $headers['If-Match'] = '*';
  666. } else {
  667. $headers['If-Match'] = $entity->getEtag();
  668. }
  669. // Generate request body
  670. $requestBody = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  671. <entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  672. <title />
  673. <updated>{tpl:Updated}</updated>
  674. <author>
  675. <name />
  676. </author>
  677. <id />
  678. <content type="application/xml">
  679. <m:properties>
  680. {tpl:Properties}
  681. </m:properties>
  682. </content>
  683. </entry>';
  684. // Attempt to get timestamp from entity
  685. $timestamp = $entity->getTimestamp();
  686. if ($timestamp == Microsoft_WindowsAzure_Storage_TableEntity::DEFAULT_TIMESTAMP) {
  687. $timestamp = $this->isoDate();
  688. }
  689. $requestBody = $this->_fillTemplate($requestBody, array(
  690. 'Updated' => $timestamp,
  691. 'Properties' => $this->_generateAzureRepresentation($entity)
  692. ));
  693. // Add header information
  694. $headers = array();
  695. $headers['Content-Type'] = 'application/atom+xml';
  696. if (!$verifyEtag) {
  697. $headers['If-Match'] = '*';
  698. } else {
  699. $headers['If-Match'] = $entity->getEtag();
  700. }
  701. // Perform request
  702. $response = null;
  703. if ($this->isInBatch()) {
  704. $this->getCurrentBatch()->enlistOperation($tableName . '(PartitionKey=\'' . $entity->getPartitionKey() . '\', RowKey=\'' . $entity->getRowKey() . '\')', '', $httpVerb, $headers, true, $requestBody);
  705. return null;
  706. } else {
  707. $response = $this->_performRequest($tableName . '(PartitionKey=\'' . $entity->getPartitionKey() . '\', RowKey=\'' . $entity->getRowKey() . '\')', '', $httpVerb, $headers, true, $requestBody);
  708. }
  709. if ($response->isSuccessful()) {
  710. // Update properties
  711. $entity->setEtag($response->getHeader('Etag'));
  712. $entity->setTimestamp($response->getHeader('Last-modified'));
  713. return $entity;
  714. } else {
  715. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  716. }
  717. }
  718. /**
  719. * Generate RFC 1123 compliant date string
  720. *
  721. * @return string
  722. */
  723. protected function _rfcDate()
  724. {
  725. return gmdate('D, d M Y H:i:s', time()) . ' GMT'; // RFC 1123
  726. }
  727. /**
  728. * Fill text template with variables from key/value array
  729. *
  730. * @param string $templateText Template text
  731. * @param array $variables Array containing key/value pairs
  732. * @return string
  733. */
  734. protected function _fillTemplate($templateText, $variables = array())
  735. {
  736. foreach ($variables as $key => $value) {
  737. $templateText = str_replace('{tpl:' . $key . '}', $value, $templateText);
  738. }
  739. return $templateText;
  740. }
  741. /**
  742. * Generate Azure representation from entity (creates atompub markup from properties)
  743. *
  744. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity
  745. * @return string
  746. */
  747. protected function _generateAzureRepresentation(Microsoft_WindowsAzure_Storage_TableEntity $entity = null)
  748. {
  749. // Generate Azure representation from entity
  750. $azureRepresentation = array();
  751. $azureValues = $entity->getAzureValues();
  752. foreach ($azureValues as $azureValue) {
  753. $value = array();
  754. $value[] = '<d:' . $azureValue->Name;
  755. if ($azureValue->Type != '') {
  756. $value[] = ' m:type="' . $azureValue->Type . '"';
  757. }
  758. if (is_null($azureValue->Value)) {
  759. $value[] = ' m:null="true"';
  760. }
  761. $value[] = '>';
  762. if (!is_null($azureValue->Value)) {
  763. if (strtolower($azureValue->Type) == 'edm.boolean') {
  764. $value[] = ($azureValue->Value == true ? '1' : '0');
  765. } else {
  766. $value[] = htmlspecialchars($azureValue->Value);
  767. }
  768. }
  769. $value[] = '</d:' . $azureValue->Name . '>';
  770. $azureRepresentation[] = implode('', $value);
  771. }
  772. return implode('', $azureRepresentation);
  773. }
  774. /**
  775. * Perform request using Microsoft_Http_Client channel
  776. *
  777. * @param string $path Path
  778. * @param string $queryString Query string
  779. * @param string $httpVerb HTTP verb the request will use
  780. * @param array $headers x-ms headers to add
  781. * @param boolean $forTableStorage Is the request for table storage?
  782. * @param mixed $rawData Optional RAW HTTP data to be sent over the wire
  783. * @param string $resourceType Resource type
  784. * @param string $requiredPermission Required permission
  785. * @return Microsoft_Http_Response
  786. */
  787. protected function _performRequest(
  788. $path = '/',
  789. $queryString = '',
  790. $httpVerb = Microsoft_Http_Client::GET,
  791. $headers = array(),
  792. $forTableStorage = false,
  793. $rawData = null,
  794. $resourceType = Microsoft_WindowsAzure_Storage::RESOURCE_UNKNOWN,
  795. $requiredPermission = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::PERMISSION_READ
  796. ) {
  797. // Add headers
  798. $headers['DataServiceVersion'] = '1.0;NetFx';
  799. $headers['MaxDataServiceVersion'] = '1.0;NetFx';
  800. // Perform request
  801. return parent::_performRequest(
  802. $path,
  803. $queryString,
  804. $httpVerb,
  805. $headers,
  806. $forTableStorage,
  807. $rawData,
  808. $resourceType,
  809. $requiredPermission
  810. );
  811. }
  812. }