PageRenderTime 68ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

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

#
PHP | 897 lines | 497 code | 104 blank | 296 comment | 95 complexity | 1424e45c74d45ca15c35e393d1543731 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. * Delete table
  268. *
  269. * @param string $tableName Table name
  270. * @throws Microsoft_WindowsAzure_Exception
  271. */
  272. public function deleteTable($tableName = '')
  273. {
  274. if ($tableName === '') {
  275. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  276. }
  277. // Add header information
  278. $headers = array();
  279. $headers['Content-Type'] = 'application/atom+xml';
  280. // Perform request
  281. $response = $this->_performRequest('Tables(\'' . $tableName . '\')', '', Microsoft_Http_Client::DELETE, $headers, true, null);
  282. if (!$response->isSuccessful()) {
  283. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  284. }
  285. }
  286. /**
  287. * Insert entity into table
  288. *
  289. * @param string $tableName Table name
  290. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to insert
  291. * @return Microsoft_WindowsAzure_Storage_TableEntity
  292. * @throws Microsoft_WindowsAzure_Exception
  293. */
  294. public function insertEntity($tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null)
  295. {
  296. if ($tableName === '') {
  297. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  298. }
  299. if (is_null($entity)) {
  300. throw new Microsoft_WindowsAzure_Exception('Entity is not specified.');
  301. }
  302. // Generate request body
  303. $requestBody = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  304. <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">
  305. <title />
  306. <updated>{tpl:Updated}</updated>
  307. <author>
  308. <name />
  309. </author>
  310. <id />
  311. <content type="application/xml">
  312. <m:properties>
  313. {tpl:Properties}
  314. </m:properties>
  315. </content>
  316. </entry>';
  317. $requestBody = $this->_fillTemplate($requestBody, array(
  318. 'Updated' => $this->isoDate(),
  319. 'Properties' => $this->_generateAzureRepresentation($entity)
  320. ));
  321. // Add header information
  322. $headers = array();
  323. $headers['Content-Type'] = 'application/atom+xml';
  324. // Perform request
  325. $response = null;
  326. if ($this->isInBatch()) {
  327. $this->getCurrentBatch()->enlistOperation($tableName, '', Microsoft_Http_Client::POST, $headers, true, $requestBody);
  328. return null;
  329. } else {
  330. $response = $this->_performRequest($tableName, '', Microsoft_Http_Client::POST, $headers, true, $requestBody);
  331. }
  332. if ($response->isSuccessful()) {
  333. // Parse result
  334. $result = $this->_parseResponse($response);
  335. $timestamp = $result->xpath('//m:properties/d:Timestamp');
  336. $timestamp = (string)$timestamp[0];
  337. $etag = $result->attributes('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
  338. $etag = (string)$etag['etag'];
  339. // Update properties
  340. $entity->setTimestamp($timestamp);
  341. $entity->setEtag($etag);
  342. return $entity;
  343. } else {
  344. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  345. }
  346. }
  347. /**
  348. * Delete entity from table
  349. *
  350. * @param string $tableName Table name
  351. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to delete
  352. * @param boolean $verifyEtag Verify etag of the entity (used for concurrency)
  353. * @throws Microsoft_WindowsAzure_Exception
  354. */
  355. public function deleteEntity($tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false)
  356. {
  357. if ($tableName === '') {
  358. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  359. }
  360. if (is_null($entity)) {
  361. throw new Microsoft_WindowsAzure_Exception('Entity is not specified.');
  362. }
  363. // Add header information
  364. $headers = array();
  365. if (!$this->isInBatch()) {
  366. // http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/9e255447-4dc7-458a-99d3-bdc04bdc5474/
  367. $headers['Content-Type'] = 'application/atom+xml';
  368. }
  369. $headers['Content-Length'] = 0;
  370. if (!$verifyEtag) {
  371. $headers['If-Match'] = '*';
  372. } else {
  373. $headers['If-Match'] = $entity->getEtag();
  374. }
  375. // Perform request
  376. $response = null;
  377. if ($this->isInBatch()) {
  378. $this->getCurrentBatch()->enlistOperation($tableName . '(PartitionKey=\'' . $entity->getPartitionKey() . '\', RowKey=\'' . $entity->getRowKey() . '\')', '', Microsoft_Http_Client::DELETE, $headers, true, null);
  379. return null;
  380. } else {
  381. $response = $this->_performRequest($tableName . '(PartitionKey=\'' . $entity->getPartitionKey() . '\', RowKey=\'' . $entity->getRowKey() . '\')', '', Microsoft_Http_Client::DELETE, $headers, true, null);
  382. }
  383. if (!$response->isSuccessful()) {
  384. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  385. }
  386. }
  387. /**
  388. * Retrieve entity from table, by id
  389. *
  390. * @param string $tableName Table name
  391. * @param string $partitionKey Partition key
  392. * @param string $rowKey Row key
  393. * @param string $entityClass Entity class name*
  394. * @return Microsoft_WindowsAzure_Storage_TableEntity
  395. * @throws Microsoft_WindowsAzure_Exception
  396. */
  397. public function retrieveEntityById($tableName = '', $partitionKey = '', $rowKey = '', $entityClass = 'Microsoft_WindowsAzure_Storage_DynamicTableEntity')
  398. {
  399. if ($tableName === '') {
  400. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  401. }
  402. if ($partitionKey === '') {
  403. throw new Microsoft_WindowsAzure_Exception('Partition key is not specified.');
  404. }
  405. if ($rowKey === '') {
  406. throw new Microsoft_WindowsAzure_Exception('Row key is not specified.');
  407. }
  408. if ($entityClass === '') {
  409. throw new Microsoft_WindowsAzure_Exception('Entity class is not specified.');
  410. }
  411. // Check for combined size of partition key and row key
  412. // http://msdn.microsoft.com/en-us/library/dd179421.aspx
  413. if (strlen($partitionKey . $rowKey) >= 256) {
  414. // Start a batch if possible
  415. if ($this->isInBatch()) {
  416. throw new Microsoft_WindowsAzure_Exception('Entity cannot be retrieved. A transaction is required to retrieve the entity, but another transaction is already active.');
  417. }
  418. $this->startBatch();
  419. }
  420. // Fetch entities from Azure
  421. $result = $this->retrieveEntities(
  422. $this->select()
  423. ->from($tableName)
  424. ->wherePartitionKey($partitionKey)
  425. ->whereRowKey($rowKey),
  426. '',
  427. $entityClass
  428. );
  429. // Return
  430. if (count($result) == 1) {
  431. return $result[0];
  432. }
  433. return null;
  434. }
  435. /**
  436. * Create a new Microsoft_WindowsAzure_Storage_TableEntityQuery
  437. *
  438. * @return Microsoft_WindowsAzure_Storage_TableEntityQuery
  439. */
  440. public function select()
  441. {
  442. return new Microsoft_WindowsAzure_Storage_TableEntityQuery();
  443. }
  444. /**
  445. * Retrieve entities from table
  446. *
  447. * @param string $tableName|Microsoft_WindowsAzure_Storage_TableEntityQuery Table name -or- Microsoft_WindowsAzure_Storage_TableEntityQuery instance
  448. * @param string $filter Filter condition (not applied when $tableName is a Microsoft_WindowsAzure_Storage_TableEntityQuery instance)
  449. * @param string $entityClass Entity class name
  450. * @param string $nextPartitionKey Next partition key, used for listing entities when total amount of entities is > 1000.
  451. * @param string $nextRowKey Next row key, used for listing entities when total amount of entities is > 1000.
  452. * @return array Array of Microsoft_WindowsAzure_Storage_TableEntity
  453. * @throws Microsoft_WindowsAzure_Exception
  454. */
  455. public function retrieveEntities($tableName = '', $filter = '', $entityClass = 'Microsoft_WindowsAzure_Storage_DynamicTableEntity', $nextPartitionKey = null, $nextRowKey = null)
  456. {
  457. if ($tableName === '') {
  458. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  459. }
  460. if ($entityClass === '') {
  461. throw new Microsoft_WindowsAzure_Exception('Entity class is not specified.');
  462. }
  463. // Convenience...
  464. if (class_exists($filter)) {
  465. $entityClass = $filter;
  466. $filter = '';
  467. }
  468. // Query string
  469. $queryString = '';
  470. // Determine query
  471. if (is_string($tableName)) {
  472. // Option 1: $tableName is a string
  473. // Append parentheses
  474. $tableName .= '()';
  475. // Build query
  476. $query = array();
  477. // Filter?
  478. if ($filter !== '') {
  479. $query[] = '$filter=' . Microsoft_WindowsAzure_Storage_TableEntityQuery::encodeQuery($filter);
  480. }
  481. // Build queryString
  482. if (count($query) > 0) {
  483. $queryString = '?' . implode('&', $query);
  484. }
  485. } else if (get_class($tableName) == 'Microsoft_WindowsAzure_Storage_TableEntityQuery') {
  486. // Option 2: $tableName is a Microsoft_WindowsAzure_Storage_TableEntityQuery instance
  487. // Build queryString
  488. $queryString = $tableName->assembleQueryString(true);
  489. // Change $tableName
  490. $tableName = $tableName->assembleFrom(true);
  491. } else {
  492. throw new Microsoft_WindowsAzure_Exception('Invalid argument: $tableName');
  493. }
  494. // Add continuation querystring parameters?
  495. if (!is_null($nextPartitionKey) && !is_null($nextRowKey)) {
  496. if ($queryString !== '') {
  497. $queryString .= '&';
  498. }
  499. $queryString .= '&NextPartitionKey=' . rawurlencode($nextPartitionKey) . '&NextRowKey=' . rawurlencode($nextRowKey);
  500. }
  501. // Perform request
  502. $response = null;
  503. if ($this->isInBatch() && $this->getCurrentBatch()->getOperationCount() == 0) {
  504. $this->getCurrentBatch()->enlistOperation($tableName, $queryString, Microsoft_Http_Client::GET, array(), true, null);
  505. $response = $this->getCurrentBatch()->commit();
  506. // Get inner response (multipart)
  507. $innerResponse = $response->getBody();
  508. $innerResponse = substr($innerResponse, strpos($innerResponse, 'HTTP/1.1 200 OK'));
  509. $innerResponse = substr($innerResponse, 0, strpos($innerResponse, '--batchresponse'));
  510. $response = Microsoft_Http_Response::fromString($innerResponse);
  511. } else {
  512. $response = $this->_performRequest($tableName, $queryString, Microsoft_Http_Client::GET, array(), true, null);
  513. }
  514. if ($response->isSuccessful()) {
  515. // Parse result
  516. $result = $this->_parseResponse($response);
  517. if (!$result) {
  518. return array();
  519. }
  520. $entries = null;
  521. if ($result->entry) {
  522. if (count($result->entry) > 1) {
  523. $entries = $result->entry;
  524. } else {
  525. $entries = array($result->entry);
  526. }
  527. } else {
  528. // This one is tricky... If we have properties defined, we have an entity.
  529. $properties = $result->xpath('//m:properties');
  530. if ($properties) {
  531. $entries = array($result);
  532. } else {
  533. return array();
  534. }
  535. }
  536. // Create return value
  537. $returnValue = array();
  538. foreach ($entries as $entry) {
  539. // Parse properties
  540. $properties = $entry->xpath('.//m:properties');
  541. $properties = $properties[0]->children('http://schemas.microsoft.com/ado/2007/08/dataservices');
  542. // Create entity
  543. $entity = new $entityClass('', '');
  544. $entity->setAzureValues((array)$properties, $this->_throwExceptionOnMissingData);
  545. // If we have a Microsoft_WindowsAzure_Storage_DynamicTableEntity, make sure all property types are OK
  546. if ($entity instanceof Microsoft_WindowsAzure_Storage_DynamicTableEntity) {
  547. foreach ($properties as $key => $value) {
  548. $attributes = $value->attributes('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
  549. $type = (string)$attributes['type'];
  550. if ($type !== '') {
  551. $entity->setAzurePropertyType($key, $type);
  552. }
  553. }
  554. }
  555. // Update etag
  556. $etag = $entry->attributes('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
  557. $etag = (string)$etag['etag'];
  558. $entity->setEtag($etag);
  559. // Add to result
  560. $returnValue[] = $entity;
  561. }
  562. // More entities?
  563. if (!is_null($response->getHeader('x-ms-continuation-NextPartitionKey')) && !is_null($response->getHeader('x-ms-continuation-NextRowKey'))) {
  564. if (strpos($queryString, '$top') === false) {
  565. $returnValue = array_merge($returnValue, $this->retrieveEntities($tableName, $filter, $entityClass, $response->getHeader('x-ms-continuation-NextPartitionKey'), $response->getHeader('x-ms-continuation-NextRowKey')));
  566. }
  567. }
  568. // Return
  569. return $returnValue;
  570. } else {
  571. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  572. }
  573. }
  574. /**
  575. * Update entity by replacing it
  576. *
  577. * @param string $tableName Table name
  578. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to update
  579. * @param boolean $verifyEtag Verify etag of the entity (used for concurrency)
  580. * @throws Microsoft_WindowsAzure_Exception
  581. */
  582. public function updateEntity($tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false)
  583. {
  584. return $this->_changeEntity(Microsoft_Http_Client::PUT, $tableName, $entity, $verifyEtag);
  585. }
  586. /**
  587. * Update entity by adding or updating properties
  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. * @param array $properties Properties to merge. All properties will be used when omitted.
  593. * @throws Microsoft_WindowsAzure_Exception
  594. */
  595. public function mergeEntity($tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false, $properties = array())
  596. {
  597. $mergeEntity = null;
  598. if (is_array($properties) && count($properties) > 0) {
  599. // Build a new object
  600. $mergeEntity = new Microsoft_WindowsAzure_Storage_DynamicTableEntity($entity->getPartitionKey(), $entity->getRowKey());
  601. // Keep only values mentioned in $properties
  602. $azureValues = $entity->getAzureValues();
  603. foreach ($azureValues as $key => $value) {
  604. if (in_array($value->Name, $properties)) {
  605. $mergeEntity->setAzureProperty($value->Name, $value->Value, $value->Type);
  606. }
  607. }
  608. } else {
  609. $mergeEntity = $entity;
  610. }
  611. return $this->_changeEntity(Microsoft_Http_Client::MERGE, $tableName, $mergeEntity, $verifyEtag);
  612. }
  613. /**
  614. * Get error message from Microsoft_Http_Response
  615. *
  616. * @param Microsoft_Http_Response $response Repsonse
  617. * @param string $alternativeError Alternative error message
  618. * @return string
  619. */
  620. protected function _getErrorMessage(Microsoft_Http_Response $response, $alternativeError = 'Unknown error.')
  621. {
  622. $response = $this->_parseResponse($response);
  623. if ($response && $response->message) {
  624. return (string)$response->message;
  625. } else {
  626. return $alternativeError;
  627. }
  628. }
  629. /**
  630. * Update entity / merge entity
  631. *
  632. * @param string $httpVerb HTTP verb to use (PUT = update, MERGE = merge)
  633. * @param string $tableName Table name
  634. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity Entity to update
  635. * @param boolean $verifyEtag Verify etag of the entity (used for concurrency)
  636. * @throws Microsoft_WindowsAzure_Exception
  637. */
  638. protected function _changeEntity($httpVerb = Microsoft_Http_Client::PUT, $tableName = '', Microsoft_WindowsAzure_Storage_TableEntity $entity = null, $verifyEtag = false)
  639. {
  640. if ($tableName === '') {
  641. throw new Microsoft_WindowsAzure_Exception('Table name is not specified.');
  642. }
  643. if (is_null($entity)) {
  644. throw new Microsoft_WindowsAzure_Exception('Entity is not specified.');
  645. }
  646. // Add header information
  647. $headers = array();
  648. $headers['Content-Type'] = 'application/atom+xml';
  649. $headers['Content-Length'] = 0;
  650. if (!$verifyEtag) {
  651. $headers['If-Match'] = '*';
  652. } else {
  653. $headers['If-Match'] = $entity->getEtag();
  654. }
  655. // Generate request body
  656. $requestBody = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  657. <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">
  658. <title />
  659. <updated>{tpl:Updated}</updated>
  660. <author>
  661. <name />
  662. </author>
  663. <id />
  664. <content type="application/xml">
  665. <m:properties>
  666. {tpl:Properties}
  667. </m:properties>
  668. </content>
  669. </entry>';
  670. $requestBody = $this->_fillTemplate($requestBody, array(
  671. 'Updated' => $this->isoDate(),
  672. 'Properties' => $this->_generateAzureRepresentation($entity)
  673. ));
  674. // Add header information
  675. $headers = array();
  676. $headers['Content-Type'] = 'application/atom+xml';
  677. if (!$verifyEtag) {
  678. $headers['If-Match'] = '*';
  679. } else {
  680. $headers['If-Match'] = $entity->getEtag();
  681. }
  682. // Perform request
  683. $response = null;
  684. if ($this->isInBatch()) {
  685. $this->getCurrentBatch()->enlistOperation($tableName . '(PartitionKey=\'' . $entity->getPartitionKey() . '\', RowKey=\'' . $entity->getRowKey() . '\')', '', $httpVerb, $headers, true, $requestBody);
  686. return null;
  687. } else {
  688. $response = $this->_performRequest($tableName . '(PartitionKey=\'' . $entity->getPartitionKey() . '\', RowKey=\'' . $entity->getRowKey() . '\')', '', $httpVerb, $headers, true, $requestBody);
  689. }
  690. if ($response->isSuccessful()) {
  691. // Update properties
  692. $entity->setEtag($response->getHeader('Etag'));
  693. $entity->setTimestamp($response->getHeader('Last-modified'));
  694. return $entity;
  695. } else {
  696. throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
  697. }
  698. }
  699. /**
  700. * Generate RFC 1123 compliant date string
  701. *
  702. * @return string
  703. */
  704. protected function _rfcDate()
  705. {
  706. return gmdate('D, d M Y H:i:s', time()) . ' GMT'; // RFC 1123
  707. }
  708. /**
  709. * Fill text template with variables from key/value array
  710. *
  711. * @param string $templateText Template text
  712. * @param array $variables Array containing key/value pairs
  713. * @return string
  714. */
  715. protected function _fillTemplate($templateText, $variables = array())
  716. {
  717. foreach ($variables as $key => $value) {
  718. $templateText = str_replace('{tpl:' . $key . '}', $value, $templateText);
  719. }
  720. return $templateText;
  721. }
  722. /**
  723. * Generate Azure representation from entity (creates atompub markup from properties)
  724. *
  725. * @param Microsoft_WindowsAzure_Storage_TableEntity $entity
  726. * @return string
  727. */
  728. protected function _generateAzureRepresentation(Microsoft_WindowsAzure_Storage_TableEntity $entity = null)
  729. {
  730. // Generate Azure representation from entity
  731. $azureRepresentation = array();
  732. $azureValues = $entity->getAzureValues();
  733. foreach ($azureValues as $azureValue) {
  734. $value = array();
  735. $value[] = '<d:' . $azureValue->Name;
  736. if ($azureValue->Type != '') {
  737. $value[] = ' m:type="' . $azureValue->Type . '"';
  738. }
  739. if (is_null($azureValue->Value)) {
  740. $value[] = ' m:null="true"';
  741. }
  742. $value[] = '>';
  743. if (!is_null($azureValue->Value)) {
  744. if (strtolower($azureValue->Type) == 'edm.boolean') {
  745. $value[] = ($azureValue->Value == true ? '1' : '0');
  746. } else {
  747. $value[] = htmlspecialchars($azureValue->Value);
  748. }
  749. }
  750. $value[] = '</d:' . $azureValue->Name . '>';
  751. $azureRepresentation[] = implode('', $value);
  752. }
  753. return implode('', $azureRepresentation);
  754. }
  755. /**
  756. * Perform request using Microsoft_Http_Client channel
  757. *
  758. * @param string $path Path
  759. * @param string $queryString Query string
  760. * @param string $httpVerb HTTP verb the request will use
  761. * @param array $headers x-ms headers to add
  762. * @param boolean $forTableStorage Is the request for table storage?
  763. * @param mixed $rawData Optional RAW HTTP data to be sent over the wire
  764. * @param string $resourceType Resource type
  765. * @param string $requiredPermission Required permission
  766. * @return Microsoft_Http_Response
  767. */
  768. protected function _performRequest(
  769. $path = '/',
  770. $queryString = '',
  771. $httpVerb = Microsoft_Http_Client::GET,
  772. $headers = array(),
  773. $forTableStorage = false,
  774. $rawData = null,
  775. $resourceType = Microsoft_WindowsAzure_Storage::RESOURCE_UNKNOWN,
  776. $requiredPermission = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::PERMISSION_READ
  777. ) {
  778. // Add headers
  779. $headers['DataServiceVersion'] = '1.0;NetFx';
  780. $headers['MaxDataServiceVersion'] = '1.0;NetFx';
  781. // Perform request
  782. return parent::_performRequest(
  783. $path,
  784. $queryString,
  785. $httpVerb,
  786. $headers,
  787. $forTableStorage,
  788. $rawData,
  789. $resourceType,
  790. $requiredPermission
  791. );
  792. }
  793. }