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