SimpleDb.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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_Amazon
  17. * @subpackage SimpleDb
  18. * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. */
  21. /**
  22. * @see Zend_Service_Amazon_Abstract
  23. */
  24. require_once 'Zend/Service/Amazon/Abstract.php';
  25. /**
  26. * @see Zend_Service_Amazon_SimpleDb_Response
  27. */
  28. require_once 'Zend/Service/Amazon/SimpleDb/Response.php';
  29. /**
  30. * @see Zend_Service_Amazon_SimpleDb_Page
  31. */
  32. require_once 'Zend/Service/Amazon/SimpleDb/Page.php';
  33. /**
  34. * @see Zend_Service_Amazon_SimpleDb_Attribute
  35. */
  36. require_once 'Zend/Service/Amazon/SimpleDb/Attribute.php';
  37. /**
  38. * @see Zend_Service_Amazon_SimpleDb_Exception
  39. */
  40. require_once 'Zend/Service/Amazon/SimpleDb/Exception.php';
  41. /**
  42. * @see Zend_Crypt_Hmac
  43. */
  44. require_once 'Zend/Crypt/Hmac.php';
  45. /**
  46. * @category Zend
  47. * @package Zend_Service_Amazon
  48. * @subpackage SimpleDb
  49. * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
  50. * @license http://framework.zend.com/license/new-bsd New BSD License
  51. */
  52. class Zend_Service_Amazon_SimpleDb extends Zend_Service_Amazon_Abstract
  53. {
  54. /* Notes */
  55. // TODO SSL is required
  56. /**
  57. * The HTTP query server
  58. */
  59. protected $_sdbEndpoint = 'sdb.amazonaws.com/';
  60. /**
  61. * Period after which HTTP request will timeout in seconds
  62. */
  63. protected $_httpTimeout = 10;
  64. /**
  65. * The API version to use
  66. */
  67. protected $_sdbApiVersion = '2009-04-15';
  68. /**
  69. * Signature Version
  70. */
  71. protected $_signatureVersion = '2';
  72. /**
  73. * Signature Encoding Method
  74. */
  75. protected $_signatureMethod = 'HmacSHA256';
  76. /**
  77. * Create Amazon SimpleDB client.
  78. *
  79. * @param string $accessKey Override the default Access Key
  80. * @param string $secretKey Override the default Secret Key
  81. */
  82. public function __construct($accessKey, $secretKey)
  83. {
  84. parent::__construct($accessKey, $secretKey);
  85. $this->setEndpoint("https://" . $this->_sdbEndpoint);
  86. }
  87. /**
  88. * Set SimpleDB endpoint to use
  89. *
  90. * @param string|Zend_Uri_Http $endpoint
  91. * @throws Zend_Service_Amazon_SimpleDb_Exception
  92. * @throws Zend_Uri_Exception
  93. * @return Zend_Service_Amazon_SimpleDb
  94. */
  95. public function setEndpoint($endpoint)
  96. {
  97. if(!($endpoint instanceof Zend_Uri_Http)) {
  98. $endpoint = Zend_Uri::factory($endpoint);
  99. }
  100. if(!$endpoint->valid()) {
  101. require_once 'Zend/Service/Amazon/SimpleDb/Exception.php';
  102. throw new Zend_Service_Amazon_SimpleDb_Exception("Invalid endpoint supplied");
  103. }
  104. $this->_endpoint = $endpoint;
  105. return $this;
  106. }
  107. /**
  108. * Get SimpleDB endpoint
  109. *
  110. * @return Zend_Uri_Http
  111. */
  112. public function getEndpoint()
  113. {
  114. return $this->_endpoint;
  115. }
  116. /**
  117. * Get attributes API method
  118. *
  119. * @param string $domainName Domain name within database
  120. * @param string $itemName
  121. * @param string|null $attributeName
  122. * @throws Zend_Service_Amazon_SimpleDb_Exception
  123. * @return array
  124. */
  125. public function getAttributes(
  126. $domainName, $itemName, $attributeName = null
  127. ) {
  128. $params = array();
  129. $params['Action'] = 'GetAttributes';
  130. $params['DomainName'] = $domainName;
  131. $params['ItemName'] = $itemName;
  132. if (isset($attributeName)) {
  133. $params['AttributeName'] = $attributeName;
  134. }
  135. $response = $this->_sendRequest($params);
  136. $document = $response->getSimpleXMLDocument();
  137. $attributeNodes = $document->GetAttributesResult->Attribute;
  138. // Return an array of arrays
  139. $attributes = array();
  140. foreach($attributeNodes as $attributeNode) {
  141. $name = (string)$attributeNode->Name;
  142. $valueNodes = $attributeNode->Value;
  143. $data = null;
  144. if (is_array($valueNodes) && !empty($valueNodes)) {
  145. $data = array();
  146. foreach($valueNodes as $valueNode) {
  147. $data[] = (string)$valueNode;
  148. }
  149. } elseif (isset($valueNodes)) {
  150. $data = (string)$valueNodes;
  151. }
  152. if (isset($attributes[$name])) {
  153. $attributes[$name]->addValue($data);
  154. } else {
  155. $attributes[$name] = new Zend_Service_Amazon_SimpleDb_Attribute($itemName, $name, $data);
  156. }
  157. }
  158. return $attributes;
  159. }
  160. /**
  161. * Push attributes
  162. *
  163. * @param string $domainName
  164. * @param string $itemName
  165. * @param array|Traversable $attributes
  166. * @param array $replace
  167. * @return void
  168. */
  169. public function putAttributes(
  170. $domainName, $itemName, $attributes, $replace = array()
  171. ) {
  172. $params = array();
  173. $params['Action'] = 'PutAttributes';
  174. $params['DomainName'] = $domainName;
  175. $params['ItemName'] = $itemName;
  176. $index = 0;
  177. foreach ($attributes as $attribute) {
  178. $attributeName = $attribute->getName();
  179. foreach ($attribute->getValues() as $value) {
  180. $params['Attribute.' . $index . '.Name'] = $attributeName;
  181. $params['Attribute.' . $index . '.Value'] = $value;
  182. // Check if it should be replaced
  183. if(array_key_exists($attributeName, $replace) && $replace[$attributeName]) {
  184. $params['Attribute.' . $index . '.Replace'] = 'true';
  185. }
  186. $index++;
  187. }
  188. }
  189. // Exception should get thrown if there's an error
  190. $response = $this->_sendRequest($params);
  191. }
  192. /**
  193. * Add many attributes at once
  194. *
  195. * @param array $items
  196. * @param string $domainName
  197. * @param array $replace
  198. * @return void
  199. */
  200. public function batchPutAttributes($items, $domainName, array $replace = array())
  201. {
  202. $params = array();
  203. $params['Action'] = 'BatchPutAttributes';
  204. $params['DomainName'] = $domainName;
  205. $itemIndex = 0;
  206. foreach ($items as $name => $attributes) {
  207. $params['Item.' . $itemIndex . '.ItemName'] = $name;
  208. $attributeIndex = 0;
  209. foreach ($attributes as $attribute) {
  210. // attribute value cannot be array, so when several items are passed
  211. // they are treated as separate values with the same attribute name
  212. foreach($attribute->getValues() as $value) {
  213. $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Name'] = $attribute->getName();
  214. $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Value'] = $value;
  215. if (isset($replace[$name])
  216. && isset($replace[$name][$attribute->getName()])
  217. && $replace[$name][$attribute->getName()]
  218. ) {
  219. $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Replace'] = 'true';
  220. }
  221. $attributeIndex++;
  222. }
  223. }
  224. $itemIndex++;
  225. }
  226. $response = $this->_sendRequest($params);
  227. }
  228. /**
  229. * Delete attributes
  230. *
  231. * @param string $domainName
  232. * @param string $itemName
  233. * @param array $attributes
  234. * @return void
  235. */
  236. public function deleteAttributes($domainName, $itemName, array $attributes = array())
  237. {
  238. $params = array();
  239. $params['Action'] = 'DeleteAttributes';
  240. $params['DomainName'] = $domainName;
  241. $params['ItemName'] = $itemName;
  242. $attributeIndex = 0;
  243. foreach ($attributes as $attribute) {
  244. foreach ($attribute->getValues() as $value) {
  245. $params['Attribute.' . $attributeIndex . '.Name'] = $attribute->getName();
  246. $params['Attribute.' . $attributeIndex . '.Value'] = $value;
  247. $attributeIndex++;
  248. }
  249. }
  250. $response = $this->_sendRequest($params);
  251. return true;
  252. }
  253. /**
  254. * List domains
  255. *
  256. * @param int $maxNumberOfDomains
  257. * @param int $nextToken
  258. * @return array 0 or more domain names
  259. */
  260. public function listDomains($maxNumberOfDomains = 100, $nextToken = null)
  261. {
  262. $params = array();
  263. $params['Action'] = 'ListDomains';
  264. $params['MaxNumberOfDomains'] = $maxNumberOfDomains;
  265. if (null !== $nextToken) {
  266. $params['NextToken'] = $nextToken;
  267. }
  268. $response = $this->_sendRequest($params);
  269. $domainNodes = $response->getSimpleXMLDocument()->ListDomainsResult->DomainName;
  270. $data = array();
  271. foreach ($domainNodes as $domain) {
  272. $data[] = (string)$domain;
  273. }
  274. $nextTokenNode = $response->getSimpleXMLDocument()->ListDomainsResult->NextToken;
  275. $nextToken = (string)$nextTokenNode;
  276. return new Zend_Service_Amazon_SimpleDb_Page($data, $nextToken);
  277. }
  278. /**
  279. * Retrieve domain metadata
  280. *
  281. * @param string $domainName Name of the domain for which metadata will be requested
  282. * @return array Key/value array of metadatum names and values.
  283. */
  284. public function domainMetadata($domainName)
  285. {
  286. $params = array();
  287. $params['Action'] = 'DomainMetadata';
  288. $params['DomainName'] = $domainName;
  289. $response = $this->_sendRequest($params);
  290. $document = $response->getSimpleXMLDocument();
  291. $metadataNodes = $document->DomainMetadataResult->children();
  292. $metadata = array();
  293. foreach ($metadataNodes as $metadataNode) {
  294. $name = $metadataNode->getName();
  295. $metadata[$name] = (string)$metadataNode;
  296. }
  297. return $metadata;
  298. }
  299. /**
  300. * Create a new domain
  301. *
  302. * @param string $domainName Valid domain name of the domain to create
  303. * @return boolean True if successful, false if not
  304. */
  305. public function createDomain($domainName)
  306. {
  307. $params = array();
  308. $params['Action'] = 'CreateDomain';
  309. $params['DomainName'] = $domainName;
  310. $response = $this->_sendRequest($params);
  311. return $response->getHttpResponse()->isSuccessful();
  312. }
  313. /**
  314. * Delete a domain
  315. *
  316. * @param string $domainName Valid domain name of the domain to delete
  317. * @return boolean True if successful, false if not
  318. */
  319. public function deleteDomain($domainName)
  320. {
  321. $params = array();
  322. $params['Action'] = 'DeleteDomain';
  323. $params['DomainName'] = $domainName;
  324. $response = $this->_sendRequest($params);
  325. return $response->getHttpResponse()->isSuccessful();
  326. }
  327. /**
  328. * Select items from the database
  329. *
  330. * @param string $selectExpression
  331. * @param null|string $nextToken
  332. * @return Zend_Service_Amazon_SimpleDb_Page
  333. */
  334. public function select($selectExpression, $nextToken = null)
  335. {
  336. $params = array();
  337. $params['Action'] = 'Select';
  338. $params['SelectExpression'] = $selectExpression;
  339. if (null !== $nextToken) {
  340. $params['NextToken'] = $nextToken;
  341. }
  342. $response = $this->_sendRequest($params);
  343. $xml = $response->getSimpleXMLDocument();
  344. $attributes = array();
  345. foreach ($xml->SelectResult->Item as $item) {
  346. $itemName = (string)$item->Name;
  347. foreach ($item->Attribute as $attribute) {
  348. $attributeName = (string)$attribute->Name;
  349. $values = array();
  350. foreach ($attribute->Value as $value) {
  351. $values[] = (string)$value;
  352. }
  353. $attributes[$itemName][$attributeName] = new Zend_Service_Amazon_SimpleDb_Attribute($itemName, $attributeName, $values);
  354. }
  355. }
  356. $nextToken = (string)$xml->NextToken;
  357. return new Zend_Service_Amazon_SimpleDb_Page($attributes, $nextToken);
  358. }
  359. /**
  360. * Quote SDB value
  361. *
  362. * Wraps it in ''
  363. *
  364. * @param string $value
  365. * @return string
  366. */
  367. public function quote($value)
  368. {
  369. // wrap in single quotes and convert each ' inside to ''
  370. return "'" . str_replace("'", "''", $value) . "'";
  371. }
  372. /**
  373. * Quote SDB column or table name
  374. *
  375. * Wraps it in ``
  376. *
  377. * @param string $name
  378. * @throws Zend_Service_Amazon_SimpleDb_Exception
  379. * @return string
  380. */
  381. public function quoteName($name)
  382. {
  383. if (preg_match('/^[a-z_$][a-z0-9_$-]*$/i', $name) == false) {
  384. throw new Zend_Service_Amazon_SimpleDb_Exception("Invalid name: can contain only alphanumeric characters, \$ and _");
  385. }
  386. return "`$name`";
  387. }
  388. /**
  389. * Sends a HTTP request to the SimpleDB service using Zend_Http_Client
  390. *
  391. * @param array $params List of parameters to send with the request
  392. * @return Zend_Service_Amazon_SimpleDb_Response
  393. * @throws Zend_Service_Amazon_SimpleDb_Exception
  394. */
  395. protected function _sendRequest(array $params = array())
  396. {
  397. // UTF-8 encode all parameters and replace '+' characters
  398. foreach ($params as $name => $value) {
  399. unset($params[$name]);
  400. $params[utf8_encode($name)] = $value;
  401. }
  402. $params = $this->_addRequiredParameters($params);
  403. try {
  404. /* @var $request Zend_Http_Client */
  405. $request = self::getHttpClient();
  406. $request->resetParameters();
  407. $request->setConfig(array(
  408. 'timeout' => $this->_httpTimeout
  409. ));
  410. $request->setUri($this->getEndpoint());
  411. $request->setMethod(Zend_Http_Client::POST);
  412. foreach ($params as $key => $value) {
  413. $params_out[] = rawurlencode($key)."=".rawurlencode($value);
  414. }
  415. $request->setRawData(join('&', $params_out), Zend_Http_Client::ENC_URLENCODED);
  416. $httpResponse = $request->request();
  417. } catch (Zend_Http_Client_Exception $zhce) {
  418. $message = 'Error in request to AWS service: ' . $zhce->getMessage();
  419. throw new Zend_Service_Amazon_SimpleDb_Exception($message, $zhce->getCode());
  420. }
  421. $response = new Zend_Service_Amazon_SimpleDb_Response($httpResponse);
  422. $this->_checkForErrors($response);
  423. return $response;
  424. }
  425. /**
  426. * Adds required authentication and version parameters to an array of
  427. * parameters
  428. *
  429. * The required parameters are:
  430. * - AWSAccessKey
  431. * - SignatureVersion
  432. * - Timestamp
  433. * - Version and
  434. * - Signature
  435. *
  436. * If a required parameter is already set in the <tt>$parameters</tt> array,
  437. * it is overwritten.
  438. *
  439. * @param array $parameters the array to which to add the required
  440. * parameters.
  441. *
  442. * @return array
  443. */
  444. protected function _addRequiredParameters(array $parameters)
  445. {
  446. $parameters['AWSAccessKeyId'] = $this->_getAccessKey();
  447. $parameters['SignatureVersion'] = $this->_signatureVersion;
  448. $parameters['Timestamp'] = gmdate('c');
  449. $parameters['Version'] = $this->_sdbApiVersion;
  450. $parameters['SignatureMethod'] = $this->_signatureMethod;
  451. $parameters['Signature'] = $this->_signParameters($parameters);
  452. return $parameters;
  453. }
  454. /**
  455. * Computes the RFC 2104-compliant HMAC signature for request parameters
  456. *
  457. * This implements the Amazon Web Services signature, as per the following
  458. * specification:
  459. *
  460. * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  461. * excluding <tt>Signature</tt>, the value of which is being created),
  462. * ignoring case.
  463. *
  464. * 2. Iterate over the sorted list and append the parameter name (in its
  465. * original case) and then its value. Do not URL-encode the parameter
  466. * values before constructing this string. Do not use any separator
  467. * characters when appending strings.
  468. *
  469. * @param array $parameters the parameters for which to get the signature.
  470. * @return string the signed data.
  471. */
  472. protected function _signParameters(array $parameters)
  473. {
  474. $data = "POST\n";
  475. $data .= $this->getEndpoint()->getHost() . "\n";
  476. $data .= "/\n";
  477. uksort($parameters, 'strcmp');
  478. unset($parameters['Signature']);
  479. $arrData = array();
  480. foreach ($parameters as $key => $value) {
  481. $value = urlencode($value);
  482. $value = str_replace("%7E", "~", $value);
  483. $value = str_replace("+", "%20", $value);
  484. $arrData[] = urlencode($key) . '=' . $value;
  485. }
  486. $data .= implode('&', $arrData);
  487. require_once 'Zend/Crypt/Hmac.php';
  488. $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Zend_Crypt_Hmac::BINARY);
  489. return base64_encode($hmac);
  490. }
  491. /**
  492. * Checks for errors responses from Amazon
  493. *
  494. * @param Zend_Service_Amazon_SimpleDb_Response $response the response object to
  495. * check.
  496. * @throws Zend_Service_Amazon_SimpleDb_Exception if one or more errors are
  497. * returned from Amazon.
  498. */
  499. private function _checkForErrors(Zend_Service_Amazon_SimpleDb_Response $response)
  500. {
  501. $xpath = new DOMXPath($response->getDocument());
  502. $list = $xpath->query('//Error');
  503. if ($list->length > 0) {
  504. $node = $list->item(0);
  505. $code = $xpath->evaluate('string(Code/text())', $node);
  506. $message = $xpath->evaluate('string(Message/text())', $node);
  507. throw new Zend_Service_Amazon_SimpleDb_Exception($message, 0, $code);
  508. }
  509. }
  510. }