2
0

SimpleDb.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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-2010 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-2010 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. $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Name'] = $attribute->getName();
  208. if (isset($replace[$itemIndex])
  209. && isset($replace[$itemIndex][$attributeIndex])
  210. && $replace[$itemIndex][$attributeIndex]
  211. ) {
  212. $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Replace'] = 'true';
  213. }
  214. foreach($attribute->getValues() as $value) {
  215. $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Value'] = $value;
  216. }
  217. $attributeIndex++;
  218. }
  219. $itemIndex++;
  220. }
  221. $response = $this->_sendRequest($params);
  222. }
  223. /**
  224. * Delete attributes
  225. *
  226. * @param string $domainName
  227. * @param string $itemName
  228. * @param array $attributes
  229. * @return void
  230. */
  231. public function deleteAttributes($domainName, $itemName, array $attributes = array())
  232. {
  233. $params = array();
  234. $params['Action'] = 'DeleteAttributes';
  235. $params['DomainName'] = $domainName;
  236. $params['ItemName'] = $itemName;
  237. $attributeIndex = 0;
  238. foreach ($attributes as $attribute) {
  239. foreach ($attribute->getValues() as $value) {
  240. $params['Attribute.' . $attributeIndex . '.Name'] = $attribute->getName();
  241. $params['Attribute.' . $attributeIndex . '.Value'] = $value;
  242. $attributeIndex++;
  243. }
  244. }
  245. $response = $this->_sendRequest($params);
  246. return true;
  247. }
  248. /**
  249. * List domains
  250. *
  251. * @param $maxNumberOfDomains int
  252. * @param $nextToken int
  253. * @return array 0 or more domain names
  254. */
  255. public function listDomains($maxNumberOfDomains = 100, $nextToken = null)
  256. {
  257. $params = array();
  258. $params['Action'] = 'ListDomains';
  259. $params['MaxNumberOfDomains'] = $maxNumberOfDomains;
  260. if (null !== $nextToken) {
  261. $params['NextToken'] = $nextToken;
  262. }
  263. $response = $this->_sendRequest($params);
  264. $domainNodes = $response->getSimpleXMLDocument()->ListDomainsResult->DomainName;
  265. $data = array();
  266. foreach ($domainNodes as $domain) {
  267. $data[] = (string)$domain;
  268. }
  269. $nextTokenNode = $response->getSimpleXMLDocument()->ListDomainsResult->NextToken;
  270. $nextToken = (string)$nextTokenNode;
  271. $nextToken = (trim($nextToken) === '') ? null : $nextToken;
  272. return new Zend_Service_Amazon_SimpleDb_Page($data, $nextToken);
  273. }
  274. /**
  275. * Retrieve domain metadata
  276. *
  277. * @param $domainName string Name of the domain for which metadata will be requested
  278. * @return array Key/value array of metadatum names and values.
  279. */
  280. public function domainMetadata($domainName)
  281. {
  282. $params = array();
  283. $params['Action'] = 'DomainMetadata';
  284. $params['DomainName'] = $domainName;
  285. $response = $this->_sendRequest($params);
  286. $document = $response->getSimpleXMLDocument();
  287. $metadataNodes = $document->DomainMetadataResult->children();
  288. $metadata = array();
  289. foreach ($metadataNodes as $metadataNode) {
  290. $name = $metadataNode->getName();
  291. $metadata[$name] = (string)$metadataNode;
  292. }
  293. return $metadata;
  294. }
  295. /**
  296. * Create a new domain
  297. *
  298. * @param $domainName string Valid domain name of the domain to create
  299. * @return boolean True if successful, false if not
  300. */
  301. public function createDomain($domainName)
  302. {
  303. $params = array();
  304. $params['Action'] = 'CreateDomain';
  305. $params['DomainName'] = $domainName;
  306. $response = $this->_sendRequest($params);
  307. return $response->getHttpResponse()->isSuccessful();
  308. }
  309. /**
  310. * Delete a domain
  311. *
  312. * @param $domainName string Valid domain name of the domain to delete
  313. * @return boolean True if successful, false if not
  314. */
  315. public function deleteDomain($domainName)
  316. {
  317. $params = array();
  318. $params['Action'] = 'DeleteDomain';
  319. $params['DomainName'] = $domainName;
  320. $response = $this->_sendRequest($params);
  321. return $response->getHttpResponse()->isSuccessful();
  322. }
  323. /**
  324. * Select items from the database
  325. *
  326. * @param string $selectExpression
  327. * @param null|string $nextToken
  328. * @return Zend_Service_Amazon_SimpleDb_Page
  329. */
  330. public function select($selectExpression, $nextToken = null)
  331. {
  332. $params = array();
  333. $params['Action'] = 'Select';
  334. $params['SelectExpression'] = $selectExpression;
  335. if (null !== $nextToken) {
  336. $params['NextToken'] = $nextToken;
  337. }
  338. $response = $this->_sendRequest($params);
  339. $xml = $response->getSimpleXMLDocument();
  340. $attributes = array();
  341. foreach ($xml->SelectResult->Item as $item) {
  342. $itemName = (string)$item->Name;
  343. foreach ($item->Attribute as $attribute) {
  344. $attributeName = (string)$attribute->Name;
  345. $values = array();
  346. foreach ($attribute->Value as $value) {
  347. $values[] = (string)$value;
  348. }
  349. $attributes[$itemName][$attributeName] = new Zend_Service_Amazon_SimpleDb_Attribute($itemName, $attributeName, $values);
  350. }
  351. }
  352. $nextToken = (string)$xml->NextToken;
  353. return new Zend_Service_Amazon_SimpleDb_Page($attributes, $nextToken);
  354. }
  355. /**
  356. * Quote SDB value
  357. *
  358. * Wraps it in ''
  359. *
  360. * @param string $value
  361. * @return string
  362. */
  363. public function quote($value)
  364. {
  365. // wrap in single quotes and convert each ' inside to ''
  366. return "'" . str_replace("'", "''", $value) . "'";
  367. }
  368. /**
  369. * Quote SDB column or table name
  370. *
  371. * Wraps it in ``
  372. * @param string $name
  373. * @return string
  374. */
  375. public function quoteName($name)
  376. {
  377. if (preg_match('/^[a-z_$][a-z0-9_$-]*$/i', $name) == false) {
  378. throw new Zend_Service_Amazon_SimpleDb_Exception("Invalid name: can contain only alphanumeric characters, \$ and _");
  379. }
  380. return "`$name`";
  381. }
  382. /**
  383. * Sends a HTTP request to the SimpleDB service using Zend_Http_Client
  384. *
  385. * @param array $params List of parameters to send with the request
  386. * @return Zend_Service_Amazon_SimpleDb_Response
  387. * @throws Zend_Service_Amazon_SimpleDb_Exception
  388. */
  389. protected function _sendRequest(array $params = array())
  390. {
  391. // UTF-8 encode all parameters and replace '+' characters
  392. foreach ($params as $name => $value) {
  393. unset($params[$name]);
  394. $params[utf8_encode($name)] = $value;
  395. }
  396. $params = $this->_addRequiredParameters($params);
  397. try {
  398. /* @var $request Zend_Http_Client */
  399. $request = self::getHttpClient();
  400. $request->resetParameters();
  401. $request->setConfig(array(
  402. 'timeout' => $this->_httpTimeout
  403. ));
  404. $request->setUri($this->getEndpoint());
  405. $request->setMethod(Zend_Http_Client::POST);
  406. foreach ($params as $key => $value) {
  407. $params_out[] = rawurlencode($key)."=".rawurlencode($value);
  408. }
  409. $request->setRawData(join('&', $params_out), Zend_Http_Client::ENC_URLENCODED);
  410. $httpResponse = $request->request();
  411. } catch (Zend_Http_Client_Exception $zhce) {
  412. $message = 'Error in request to AWS service: ' . $zhce->getMessage();
  413. throw new Zend_Service_Amazon_SimpleDb_Exception($message, $zhce->getCode());
  414. }
  415. $response = new Zend_Service_Amazon_SimpleDb_Response($httpResponse);
  416. $this->_checkForErrors($response);
  417. return $response;
  418. }
  419. /**
  420. * Adds required authentication and version parameters to an array of
  421. * parameters
  422. *
  423. * The required parameters are:
  424. * - AWSAccessKey
  425. * - SignatureVersion
  426. * - Timestamp
  427. * - Version and
  428. * - Signature
  429. *
  430. * If a required parameter is already set in the <tt>$parameters</tt> array,
  431. * it is overwritten.
  432. *
  433. * @param array $parameters the array to which to add the required
  434. * parameters.
  435. *
  436. * @return array
  437. */
  438. protected function _addRequiredParameters(array $parameters)
  439. {
  440. $parameters['AWSAccessKeyId'] = $this->_getAccessKey();
  441. $parameters['SignatureVersion'] = $this->_signatureVersion;
  442. $parameters['Timestamp'] = gmdate('c');
  443. $parameters['Version'] = $this->_sdbApiVersion;
  444. $parameters['SignatureMethod'] = $this->_signatureMethod;
  445. $parameters['Signature'] = $this->_signParameters($parameters);
  446. return $parameters;
  447. }
  448. /**
  449. * Computes the RFC 2104-compliant HMAC signature for request parameters
  450. *
  451. * This implements the Amazon Web Services signature, as per the following
  452. * specification:
  453. *
  454. * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  455. * excluding <tt>Signature</tt>, the value of which is being created),
  456. * ignoring case.
  457. *
  458. * 2. Iterate over the sorted list and append the parameter name (in its
  459. * original case) and then its value. Do not URL-encode the parameter
  460. * values before constructing this string. Do not use any separator
  461. * characters when appending strings.
  462. *
  463. * @param array $parameters the parameters for which to get the signature.
  464. * @param string $secretKey the secret key to use to sign the parameters.
  465. *
  466. * @return string the signed data.
  467. */
  468. protected function _signParameters(array $paramaters)
  469. {
  470. $data = "POST\n";
  471. $data .= $this->getEndpoint()->getHost() . "\n";
  472. $data .= "/\n";
  473. uksort($paramaters, 'strcmp');
  474. unset($paramaters['Signature']);
  475. $arrData = array();
  476. foreach ($paramaters as $key => $value) {
  477. $value = urlencode($value);
  478. $value = str_replace("%7E", "~", $value);
  479. $value = str_replace("+", "%20", $value);
  480. $arrData[] = urlencode($key) . '=' . $value;
  481. }
  482. $data .= implode('&', $arrData);
  483. require_once 'Zend/Crypt/Hmac.php';
  484. $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Zend_Crypt_Hmac::BINARY);
  485. return base64_encode($hmac);
  486. }
  487. /**
  488. * Checks for errors responses from Amazon
  489. *
  490. * @param Zend_Service_Amazon_SimpleDb_Response $response the response object to
  491. * check.
  492. *
  493. * @return void
  494. *
  495. * @throws Zend_Service_Amazon_SimpleDb_Exception if one or more errors are
  496. * returned from Amazon.
  497. */
  498. private function _checkForErrors(Zend_Service_Amazon_SimpleDb_Response $response)
  499. {
  500. $xpath = new DOMXPath($response->getDocument());
  501. $list = $xpath->query('//Error');
  502. if ($list->length > 0) {
  503. $node = $list->item(0);
  504. $code = $xpath->evaluate('string(Code/text())', $node);
  505. $message = $xpath->evaluate('string(Message/text())', $node);
  506. throw new Zend_Service_Amazon_SimpleDb_Exception($message, 0, $code);
  507. }
  508. }
  509. }