PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/src/application/libraries/Zend/Cloud/DocumentService/Adapter/WindowsAzure.php

https://bitbucket.org/masnug/grc276-blog-laravel
PHP | 628 lines | 350 code | 61 blank | 217 comment | 47 complexity | 4ad9b4af27b5df023d15558810fbef6d MD5 | raw file
  1. <?php
  2. /**
  3. * LICENSE
  4. *
  5. * This source file is subject to the new BSD license that is bundled
  6. * with this package in the file LICENSE.txt.
  7. * It is also available through the world-wide-web at this URL:
  8. * http://framework.zend.com/license/new-bsd
  9. * If you did not receive a copy of the license and are unable to
  10. * obtain it through the world-wide-web, please send an email
  11. * to license@zend.com so we can send you a copy immediately.
  12. *
  13. * @category Zend
  14. * @package Zend_Cloud
  15. * @subpackage DocumentService
  16. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  17. * @license http://framework.zend.com/license/new-bsd New BSD License
  18. */
  19. require_once 'Zend/Cloud/DocumentService/Adapter/AbstractAdapter.php';
  20. require_once 'Zend/Cloud/DocumentService/Adapter/WindowsAzure/Query.php';
  21. require_once 'Zend/Cloud/DocumentService/Exception.php';
  22. require_once 'Zend/Service/WindowsAzure/Storage/DynamicTableEntity.php';
  23. require_once 'Zend/Service/WindowsAzure/Storage/Table.php';
  24. /**
  25. * SimpleDB adapter for document service.
  26. *
  27. * @category Zend
  28. * @package Zend_Cloud
  29. * @subpackage DocumentService
  30. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  31. * @license http://framework.zend.com/license/new-bsd New BSD License
  32. */
  33. class Zend_Cloud_DocumentService_Adapter_WindowsAzure
  34. extends Zend_Cloud_DocumentService_Adapter_AbstractAdapter
  35. {
  36. /*
  37. * Options array keys for the Azure adapter.
  38. */
  39. const ACCOUNT_NAME = 'storage_accountname';
  40. const ACCOUNT_KEY = 'storage_accountkey';
  41. const HOST = "storage_host";
  42. const PROXY_HOST = "storage_proxy_host";
  43. const PROXY_PORT = "storage_proxy_port";
  44. const PROXY_CREDENTIALS = "storage_proxy_credentials";
  45. const DEFAULT_PARTITION_KEY = "default_partition_key";
  46. const PARTITION_KEY = 'PartitionKey';
  47. const ROW_KEY = 'RowKey';
  48. const VERIFY_ETAG = "verify_etag";
  49. const TIMESTAMP_KEY = "Timestamp";
  50. const DEFAULT_HOST = Zend_Service_WindowsAzure_Storage::URL_CLOUD_TABLE;
  51. const DEFAULT_QUERY_CLASS = 'Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query';
  52. /**
  53. * Azure service instance.
  54. *
  55. * @var Zend_Service_WindowsAzure_Storage_Table
  56. */
  57. protected $_storageClient;
  58. /**
  59. * Class to utilize for new query objects
  60. *
  61. * @var string
  62. */
  63. protected $_queryClass = 'Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query';
  64. /**
  65. * Partition key to use by default when constructing document identifiers
  66. * @var string
  67. */
  68. protected $_defaultPartitionKey;
  69. /**
  70. * Constructor
  71. *
  72. * @param array $options
  73. * @return void
  74. */
  75. public function __construct($options = array())
  76. {
  77. if ($options instanceof Zend_Config) {
  78. $options = $options->toArray();
  79. }
  80. if (empty($options)) {
  81. $options = array();
  82. }
  83. if (!is_array($options)) {
  84. throw new Zend_Cloud_DocumentService_Exception('Invalid options provided');
  85. }
  86. if (isset($options[self::DOCUMENT_CLASS])) {
  87. $this->setDocumentClass($options[self::DOCUMENT_CLASS]);
  88. }
  89. if (isset($options[self::DOCUMENTSET_CLASS])) {
  90. $this->setDocumentSetClass($options[self::DOCUMENTSET_CLASS]);
  91. }
  92. if (isset($options[self::QUERY_CLASS])) {
  93. $this->setQueryClass($options[self::QUERY_CLASS]);
  94. }
  95. // Build Zend_Service_WindowsAzure_Storage_Blob instance
  96. if (!isset($options[self::HOST])) {
  97. $host = self::DEFAULT_HOST;
  98. } else {
  99. $host = $options[self::HOST];
  100. }
  101. if (! isset($options[self::ACCOUNT_NAME])) {
  102. throw new Zend_Cloud_DocumentService_Exception('No Windows Azure account name provided.');
  103. }
  104. if (! isset($options[self::ACCOUNT_KEY])) {
  105. throw new Zend_Cloud_DocumentService_Exception('No Windows Azure account key provided.');
  106. }
  107. // TODO: support $usePathStyleUri and $retryPolicy
  108. try {
  109. $this->_storageClient = new Zend_Service_WindowsAzure_Storage_Table(
  110. $host, $options[self::ACCOUNT_NAME], $options[self::ACCOUNT_KEY]);
  111. // Parse other options
  112. if (! empty($options[self::PROXY_HOST])) {
  113. $proxyHost = $options[self::PROXY_HOST];
  114. $proxyPort = isset($options[self::PROXY_PORT]) ? $options[self::PROXY_PORT] : 8080;
  115. $proxyCredentials = isset($options[self::PROXY_CREDENTIALS]) ? $options[self::PROXY_CREDENTIALS] : '';
  116. $this->_storageClient->setProxy(true, $proxyHost, $proxyPort, $proxyCredentials);
  117. }
  118. if (isset($options[self::HTTP_ADAPTER])) {
  119. $this->_storageClient->setHttpClientChannel($options[self::HTTP_ADAPTER]);
  120. }
  121. } catch(Zend_Service_WindowsAzure_Exception $e) {
  122. throw new Zend_Cloud_DocumentService_Exception('Error on document service creation: '.$e->getMessage(), $e->getCode(), $e);
  123. }
  124. }
  125. /**
  126. * Set the default partition key
  127. *
  128. * @param string $key
  129. * @return Zend_Cloud_DocumentService_Adapter_WindowsAzure
  130. */
  131. public function setDefaultPartitionKey($key)
  132. {
  133. $this->_validateKey($key);
  134. $this->_defaultPartitionKey = $key;
  135. return $this;
  136. }
  137. /**
  138. * Retrieve default partition key
  139. *
  140. * @return null|string
  141. */
  142. public function getDefaultPartitionKey()
  143. {
  144. return $this->_defaultPartitionKey;
  145. }
  146. /**
  147. * Create collection.
  148. *
  149. * @param string $name
  150. * @param array $options
  151. * @return boolean
  152. */
  153. public function createCollection($name, $options = null)
  154. {
  155. if (!preg_match('/^[A-Za-z][A-Za-z0-9]{2,}$/', $name)) {
  156. throw new Zend_Cloud_DocumentService_Exception('Invalid collection name; Windows Azure collection names must consist of alphanumeric characters only, and be at least 3 characters long');
  157. }
  158. try {
  159. $this->_storageClient->createTable($name);
  160. } catch(Zend_Service_WindowsAzure_Exception $e) {
  161. if (strpos($e->getMessage(), "table specified already exists") === false) {
  162. throw new Zend_Cloud_DocumentService_Exception('Error on collection creation: '.$e->getMessage(), $e->getCode(), $e);
  163. }
  164. }
  165. return true;
  166. }
  167. /**
  168. * Delete collection.
  169. *
  170. * @param string $name
  171. * @param array $options
  172. * @return boolean
  173. */
  174. public function deleteCollection($name, $options = null)
  175. {
  176. try {
  177. $this->_storageClient->deleteTable($name);
  178. } catch(Zend_Service_WindowsAzure_Exception $e) {
  179. if (strpos($e->getMessage(), "does not exist") === false) {
  180. throw new Zend_Cloud_DocumentService_Exception('Error on collection deletion: '.$e->getMessage(), $e->getCode(), $e);
  181. }
  182. }
  183. return true;
  184. }
  185. /**
  186. * List collections.
  187. *
  188. * @param array $options
  189. * @return array
  190. */
  191. public function listCollections($options = null)
  192. {
  193. try {
  194. $tables = $this->_storageClient->listTables();
  195. $restables = array();
  196. foreach ($tables as $table) {
  197. $restables[] = $table->name;
  198. }
  199. return $restables;
  200. } catch(Zend_Service_WindowsAzure_Exception $e) {
  201. throw new Zend_Cloud_DocumentService_Exception('Error on collection list: '.$e->getMessage(), $e->getCode(), $e);
  202. }
  203. return $tables;
  204. }
  205. /**
  206. * Create suitable document from array of fields
  207. *
  208. * @param array $document
  209. * @param null|string $collectionName Collection to which this document belongs
  210. * @return Zend_Cloud_DocumentService_Document
  211. */
  212. protected function _getDocumentFromArray($document, $collectionName = null)
  213. {
  214. $key = null;
  215. if (!isset($document[Zend_Cloud_DocumentService_Document::KEY_FIELD])) {
  216. if (isset($document[self::ROW_KEY])) {
  217. $rowKey = $document[self::ROW_KEY];
  218. unset($document[self::ROW_KEY]);
  219. if (isset($document[self::PARTITION_KEY])) {
  220. $key = array($document[self::PARTITION_KEY], $rowKey);
  221. unset($document[self::PARTITION_KEY]);
  222. } elseif (null !== ($partitionKey = $this->getDefaultPartitionKey())) {
  223. $key = array($partitionKey, $rowKey);
  224. } elseif (null !== $collectionName) {
  225. $key = array($collectionName, $rowKey);
  226. }
  227. }
  228. } else {
  229. $key = $document[Zend_Cloud_DocumentService_Document::KEY_FIELD];
  230. unset($document[Zend_Cloud_DocumentService_Document::KEY_FIELD]);
  231. }
  232. $documentClass = $this->getDocumentClass();
  233. return new $documentClass($document, $key);
  234. }
  235. /**
  236. * List all documents in a collection
  237. *
  238. * @param string $collectionName
  239. * @param null|array $options
  240. * @return Zend_Cloud_DocumentService_DocumentSet
  241. */
  242. public function listDocuments($collectionName, array $options = null)
  243. {
  244. $select = $this->select()->from($collectionName);
  245. return $this->query($collectionName, $select);
  246. }
  247. /**
  248. * Insert document
  249. *
  250. * @param array|Zend_Cloud_DocumentService_Document $document
  251. * @param array $options
  252. * @return boolean
  253. */
  254. public function insertDocument($collectionName, $document, $options = null)
  255. {
  256. if (is_array($document)) {
  257. $document = $this->_getDocumentFromArray($document, $collectionName);
  258. }
  259. if (!$document instanceof Zend_Cloud_DocumentService_Document) {
  260. throw new Zend_Cloud_DocumentService_Exception('Invalid document supplied');
  261. }
  262. $key = $this->_validateDocumentId($document->getId(), $collectionName);
  263. $document->setId($key);
  264. $this->_validateCompositeKey($key);
  265. $this->_validateFields($document);
  266. try {
  267. $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($key[0], $key[1]);
  268. $entity->setAzureValues($document->getFields(), true);
  269. $this->_storageClient->insertEntity($collectionName, $entity);
  270. } catch(Zend_Service_WindowsAzure_Exception $e) {
  271. throw new Zend_Cloud_DocumentService_Exception('Error on document insertion: '.$e->getMessage(), $e->getCode(), $e);
  272. }
  273. }
  274. /**
  275. * Replace document.
  276. *
  277. * The new document replaces the existing document.
  278. *
  279. * @param Zend_Cloud_DocumentService_Document $document
  280. * @param array $options
  281. * @return boolean
  282. */
  283. public function replaceDocument($collectionName, $document, $options = null)
  284. {
  285. if (is_array($document)) {
  286. $document = $this->_getDocumentFromArray($document, $collectionName);
  287. }
  288. if (!$document instanceof Zend_Cloud_DocumentService_Document) {
  289. throw new Zend_Cloud_DocumentService_Exception('Invalid document supplied');
  290. }
  291. $key = $this->_validateDocumentId($document->getId(), $collectionName);
  292. $this->_validateFields($document);
  293. try {
  294. $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($key[0], $key[1]);
  295. $entity->setAzureValues($document->getFields(), true);
  296. if (isset($options[self::VERIFY_ETAG])) {
  297. $entity->setEtag($options[self::VERIFY_ETAG]);
  298. }
  299. $this->_storageClient->updateEntity($collectionName, $entity, isset($options[self::VERIFY_ETAG]));
  300. } catch(Zend_Service_WindowsAzure_Exception $e) {
  301. throw new Zend_Cloud_DocumentService_Exception('Error on document replace: '.$e->getMessage(), $e->getCode(), $e);
  302. }
  303. }
  304. /**
  305. * Update document.
  306. *
  307. * The new document is merged the existing document.
  308. *
  309. * @param string $collectionName
  310. * @param mixed|Zend_Cloud_DocumentService_Document $documentId Document identifier or document contaiing updates
  311. * @param null|array|Zend_Cloud_DocumentService_Document Fields to update (or new fields))
  312. * @param array $options
  313. * @return boolean
  314. */
  315. public function updateDocument($collectionName, $documentId, $fieldset = null, $options = null)
  316. {
  317. if (null === $fieldset && $documentId instanceof Zend_Cloud_DocumentService_Document) {
  318. $fieldset = $documentId->getFields();
  319. $documentId = $documentId->getId();
  320. } elseif ($fieldset instanceof Zend_Cloud_DocumentService_Document) {
  321. if ($documentId == null) {
  322. $documentId = $fieldset->getId();
  323. }
  324. $fieldset = $fieldset->getFields();
  325. }
  326. $this->_validateCompositeKey($documentId, $collectionName);
  327. $this->_validateFields($fieldset);
  328. try {
  329. $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($documentId[0], $documentId[1]);
  330. // Ensure timestamp is set correctly
  331. if (isset($fieldset[self::TIMESTAMP_KEY])) {
  332. $entity->setTimestamp($fieldset[self::TIMESTAMP_KEY]);
  333. unset($fieldset[self::TIMESTAMP_KEY]);
  334. }
  335. $entity->setAzureValues($fieldset, true);
  336. if (isset($options[self::VERIFY_ETAG])) {
  337. $entity->setEtag($options[self::VERIFY_ETAG]);
  338. }
  339. $this->_storageClient->mergeEntity($collectionName, $entity, isset($options[self::VERIFY_ETAG]));
  340. } catch(Zend_Service_WindowsAzure_Exception $e) {
  341. throw new Zend_Cloud_DocumentService_Exception('Error on document update: '.$e->getMessage(), $e->getCode(), $e);
  342. }
  343. }
  344. /**
  345. * Delete document.
  346. *
  347. * @param mixed $document Document ID or Document object.
  348. * @param array $options
  349. * @return void
  350. */
  351. public function deleteDocument($collectionName, $documentId, $options = null)
  352. {
  353. if ($documentId instanceof Zend_Cloud_DocumentService_Document) {
  354. $documentId = $documentId->getId();
  355. }
  356. $documentId = $this->_validateDocumentId($documentId, $collectionName);
  357. try {
  358. $entity = new Zend_Service_WindowsAzure_Storage_DynamicTableEntity($documentId[0], $documentId[1]);
  359. if (isset($options[self::VERIFY_ETAG])) {
  360. $entity->setEtag($options[self::VERIFY_ETAG]);
  361. }
  362. $this->_storageClient->deleteEntity($collectionName, $entity, isset($options[self::VERIFY_ETAG]));
  363. } catch(Zend_Service_WindowsAzure_Exception $e) {
  364. if (strpos($e->getMessage(), "does not exist") === false) {
  365. throw new Zend_Cloud_DocumentService_Exception('Error on document deletion: '.$e->getMessage(), $e->getCode(), $e);
  366. }
  367. }
  368. }
  369. /**
  370. * Fetch single document by ID
  371. *
  372. * @param string $collectionName Collection name
  373. * @param mixed $documentId Document ID, adapter-dependent
  374. * @param array $options
  375. * @return Zend_Cloud_DocumentService_Document
  376. */
  377. public function fetchDocument($collectionName, $documentId, $options = null)
  378. {
  379. $documentId = $this->_validateDocumentId($documentId, $collectionName);
  380. try {
  381. $entity = $this->_storageClient->retrieveEntityById($collectionName, $documentId[0], $documentId[1]);
  382. $documentClass = $this->getDocumentClass();
  383. return new $documentClass($this->_resolveAttributes($entity), array($entity->getPartitionKey(), $entity->getRowKey()));
  384. } catch (Zend_Service_WindowsAzure_Exception $e) {
  385. if (strpos($e->getMessage(), "does not exist") !== false) {
  386. return false;
  387. }
  388. throw new Zend_Cloud_DocumentService_Exception('Error on document fetch: '.$e->getMessage(), $e->getCode(), $e);
  389. }
  390. }
  391. /**
  392. * Query for documents stored in the document service. If a string is passed in
  393. * $query, the query string will be passed directly to the service.
  394. *
  395. * @param string $collectionName Collection name
  396. * @param string|Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query $query
  397. * @param array $options
  398. * @return array Zend_Cloud_DocumentService_DocumentSet
  399. */
  400. public function query($collectionName, $query, $options = null)
  401. {
  402. try {
  403. if ($query instanceof Zend_Cloud_DocumentService_Adapter_WindowsAzure_Query) {
  404. $entities = $this->_storageClient->retrieveEntities($query->assemble());
  405. } else {
  406. $entities = $this->_storageClient->retrieveEntities($collectionName, $query);
  407. }
  408. $documentClass = $this->getDocumentClass();
  409. $resultSet = array();
  410. foreach ($entities as $entity) {
  411. $resultSet[] = new $documentClass(
  412. $this->_resolveAttributes($entity),
  413. array($entity->getPartitionKey(), $entity->getRowKey())
  414. );
  415. }
  416. } catch(Zend_Service_WindowsAzure_Exception $e) {
  417. throw new Zend_Cloud_DocumentService_Exception('Error on document query: '.$e->getMessage(), $e->getCode(), $e);
  418. }
  419. $setClass = $this->getDocumentSetClass();
  420. return new $setClass($resultSet);
  421. }
  422. /**
  423. * Create query statement
  424. *
  425. * @return Zend_Cloud_DocumentService_Query
  426. */
  427. public function select($fields = null)
  428. {
  429. $queryClass = $this->getQueryClass();
  430. if (!class_exists($queryClass)) {
  431. require_once 'Zend/Loader.php';
  432. Zend_Loader::loadClass($queryClass);
  433. }
  434. $query = new $queryClass();
  435. $defaultClass = self::DEFAULT_QUERY_CLASS;
  436. if (!$query instanceof $defaultClass) {
  437. throw new Zend_Cloud_DocumentService_Exception('Query class must extend ' . self::DEFAULT_QUERY_CLASS);
  438. }
  439. $query->select($fields);
  440. return $query;
  441. }
  442. /**
  443. * Get the concrete service client
  444. *
  445. * @return Zend_Service_WindowsAzure_Storage_Table
  446. */
  447. public function getClient()
  448. {
  449. return $this->_storageClient;
  450. }
  451. /**
  452. * Resolve table values to attributes
  453. *
  454. * @param Zend_Service_WindowsAzure_Storage_TableEntity $entity
  455. * @return array
  456. */
  457. protected function _resolveAttributes(Zend_Service_WindowsAzure_Storage_TableEntity $entity)
  458. {
  459. $result = array();
  460. foreach ($entity->getAzureValues() as $attr) {
  461. $result[$attr->Name] = $attr->Value;
  462. }
  463. return $result;
  464. }
  465. /**
  466. * Validate a partition or row key
  467. *
  468. * @param string $key
  469. * @return void
  470. * @throws Zend_Cloud_DocumentService_Exception
  471. */
  472. protected function _validateKey($key)
  473. {
  474. if (preg_match('@[/#?' . preg_quote('\\') . ']@', $key)) {
  475. throw new Zend_Cloud_DocumentService_Exception('Invalid partition or row key provided; must not contain /, \\, #, or ? characters');
  476. }
  477. }
  478. /**
  479. * Validate a composite key
  480. *
  481. * @param array $key
  482. * @return throws Zend_Cloud_DocumentService_Exception
  483. */
  484. protected function _validateCompositeKey(array $key)
  485. {
  486. if (2 != count($key)) {
  487. throw new Zend_Cloud_DocumentService_Exception('Invalid document key provided; must contain exactly two elements: a PartitionKey and a RowKey');
  488. }
  489. foreach ($key as $k) {
  490. $this->_validateKey($k);
  491. }
  492. }
  493. /**
  494. * Validate a document identifier
  495. *
  496. * If the identifier is an array containing a valid partition and row key,
  497. * returns it. If the identifier is a string:
  498. * - if a default partition key is present, it creates an identifier using
  499. * that and the provided document ID
  500. * - if a collection name is provided, it will use that for the partition key
  501. * - otherwise, it's invalid
  502. *
  503. * @param array|string $documentId
  504. * @param null|string $collectionName
  505. * @return array
  506. * @throws Zend_Cloud_DocumentService_Exception
  507. */
  508. protected function _validateDocumentId($documentId, $collectionName = false)
  509. {
  510. if (is_array($documentId)) {
  511. $this->_validateCompositeKey($documentId);
  512. return $documentId;
  513. }
  514. if (!is_string($documentId)) {
  515. throw new Zend_Cloud_DocumentService_Exception('Invalid document identifier; must be a string or an array');
  516. }
  517. $this->_validateKey($documentId);
  518. if (null !== ($partitionKey = $this->getDefaultPartitionKey())) {
  519. return array($partitionKey, $documentId);
  520. }
  521. if (null !== $collectionName) {
  522. return array($collectionName, $documentId);
  523. }
  524. throw new Zend_Cloud_DocumentService_Exception('Cannot determine partition name; invalid document identifier');
  525. }
  526. /**
  527. * Validate a document's fields for well-formedness
  528. *
  529. * Since Azure uses Atom, and fieldnames are included as part of XML
  530. * element tag names, the field names must be valid XML names.
  531. *
  532. * @param Zend_Cloud_DocumentService_Document|array $document
  533. * @return void
  534. * @throws Zend_Cloud_DocumentService_Exception
  535. */
  536. public function _validateFields($document)
  537. {
  538. if ($document instanceof Zend_Cloud_DocumentService_Document) {
  539. $document = $document->getFields();
  540. } elseif (!is_array($document)) {
  541. throw new Zend_Cloud_DocumentService_Exception('Cannot inspect fields; invalid type provided');
  542. }
  543. foreach (array_keys($document) as $key) {
  544. $this->_validateFieldKey($key);
  545. }
  546. }
  547. /**
  548. * Validate an individual field name for well-formedness
  549. *
  550. * Since Azure uses Atom, and fieldnames are included as part of XML
  551. * element tag names, the field names must be valid XML names.
  552. *
  553. * While we could potentially normalize names, this could also lead to
  554. * conflict with other field names -- which we should avoid. As such,
  555. * invalid field names will raise an exception.
  556. *
  557. * @param string $key
  558. * @return void
  559. * @throws Zend_Cloud_DocumentService_Exception
  560. */
  561. public function _validateFieldKey($key)
  562. {
  563. if (!preg_match('/^[_A-Za-z][-._A-Za-z0-9]*$/', $key)) {
  564. throw new Zend_Cloud_DocumentService_Exception('Field keys must conform to XML names (^[_A-Za-z][-._A-Za-z0-9]*$); key "' . $key . '" does not match');
  565. }
  566. }
  567. }