PageRenderTime 38ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/src/frapi/library/Zend/Service/Amazon/Sqs.php

http://github.com/frapi/frapi
PHP | 436 lines | 184 code | 62 blank | 190 comment | 26 complexity | 696aa9ffbc0f9d6bda8ab9c588340f00 MD5 | raw file
Possible License(s): BSD-2-Clause
  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
  17. * @subpackage Amazon_Sqs
  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. * @version $Id: Sqs.php 20096 2010-01-06 02:05:09Z bkarwin $
  21. */
  22. /**
  23. * @see Zend_Service_Amazon_Abstract
  24. */
  25. // require_once 'Zend/Service/Amazon/Abstract.php';
  26. /**
  27. * @see Zend_Crypt_Hmac
  28. */
  29. // require_once 'Zend/Crypt/Hmac.php';
  30. /**
  31. * Class for connecting to the Amazon Simple Queue Service (SQS)
  32. *
  33. * @category Zend
  34. * @package Zend_Service
  35. * @subpackage Amazon_Sqs
  36. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  37. * @license http://framework.zend.com/license/new-bsd New BSD License
  38. * @see http://aws.amazon.com/sqs/ Amazon Simple Queue Service
  39. */
  40. class Zend_Service_Amazon_Sqs extends Zend_Service_Amazon_Abstract
  41. {
  42. /**
  43. * Default timeout for createQueue() function
  44. */
  45. const CREATE_TIMEOUT_DEFAULT = 30;
  46. /**
  47. * HTTP end point for the Amazon SQS service
  48. */
  49. protected $_sqsEndpoint = 'queue.amazonaws.com';
  50. /**
  51. * The API version to use
  52. */
  53. protected $_sqsApiVersion = '2009-02-01';
  54. /**
  55. * Signature Version
  56. */
  57. protected $_sqsSignatureVersion = '2';
  58. /**
  59. * Signature Encoding Method
  60. */
  61. protected $_sqsSignatureMethod = 'HmacSHA256';
  62. /**
  63. * Constructor
  64. *
  65. * @param string $accessKey
  66. * @param string $secretKey
  67. * @param string $region
  68. */
  69. public function __construct($accessKey = null, $secretKey = null, $region = null)
  70. {
  71. parent::__construct($accessKey, $secretKey, $region);
  72. }
  73. /**
  74. * Create a new queue
  75. *
  76. * Visibility timeout is how long a message is left in the queue "invisible"
  77. * to other readers. If the message is acknowleged (deleted) before the
  78. * timeout, then the message is deleted. However, if the timeout expires
  79. * then the message will be made available to other queue readers.
  80. *
  81. * @param string $queue_name queue name
  82. * @param integer $timeout default visibility timeout
  83. * @return string|boolean
  84. * @throws Zend_Service_Amazon_Sqs_Exception
  85. */
  86. public function create($queue_name, $timeout = null)
  87. {
  88. $params = array();
  89. $params['QueueName'] = $queue_name;
  90. $timeout = ($timeout === null) ? self::CREATE_TIMEOUT_DEFAULT : (int)$timeout;
  91. $params['DefaultVisibilityTimeout'] = $timeout;
  92. $retry_count = 0;
  93. do {
  94. $retry = false;
  95. $result = $this->_makeRequest(null, 'CreateQueue', $params);
  96. if ($result->CreateQueueResult->QueueUrl === null) {
  97. if ($result->Error->Code == 'AWS.SimpleQueueService.QueueNameExists') {
  98. return false;
  99. } elseif ($result->Error->Code == 'AWS.SimpleQueueService.QueueDeletedRecently') {
  100. // Must sleep for 60 seconds, then try re-creating the queue
  101. sleep(60);
  102. $retry = true;
  103. $retry_count++;
  104. } else {
  105. // require_once 'Zend/Service/Amazon/Sqs/Exception.php';
  106. throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code);
  107. }
  108. } else {
  109. return (string) $result->CreateQueueResult->QueueUrl;
  110. }
  111. } while ($retry);
  112. return false;
  113. }
  114. /**
  115. * Delete a queue and all of it's messages
  116. *
  117. * Returns false if the queue is not found, true if the queue exists
  118. *
  119. * @param string $queue_url queue URL
  120. * @return boolean
  121. * @throws Zend_Service_Amazon_Sqs_Exception
  122. */
  123. public function delete($queue_url)
  124. {
  125. $result = $this->_makeRequest($queue_url, 'DeleteQueue');
  126. if ($result->Error->Code !== null) {
  127. // require_once 'Zend/Service/Amazon/Sqs/Exception.php';
  128. throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code);
  129. }
  130. return true;
  131. }
  132. /**
  133. * Get an array of all available queues
  134. *
  135. * @return array
  136. * @throws Zend_Service_Amazon_Sqs_Exception
  137. */
  138. public function getQueues()
  139. {
  140. $result = $this->_makeRequest(null, 'ListQueues');
  141. if ($result->ListQueuesResult->QueueUrl === null) {
  142. // require_once 'Zend/Service/Amazon/Sqs/Exception.php';
  143. throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code);
  144. }
  145. $queues = array();
  146. foreach ($result->ListQueuesResult->QueueUrl as $queue_url) {
  147. $queues[] = (string)$queue_url;
  148. }
  149. return $queues;
  150. }
  151. /**
  152. * Return the approximate number of messages in the queue
  153. *
  154. * @param string $queue_url Queue URL
  155. * @return integer
  156. * @throws Zend_Service_Amazon_Sqs_Exception
  157. */
  158. public function count($queue_url)
  159. {
  160. return (int)$this->getAttribute($queue_url, 'ApproximateNumberOfMessages');
  161. }
  162. /**
  163. * Send a message to the queue
  164. *
  165. * @param string $queue_url Queue URL
  166. * @param string $message Message to send to the queue
  167. * @return string Message ID
  168. * @throws Zend_Service_Amazon_Sqs_Exception
  169. */
  170. public function send($queue_url, $message)
  171. {
  172. $params = array();
  173. $params['MessageBody'] = urlencode($message);
  174. $checksum = md5($params['MessageBody']);
  175. $result = $this->_makeRequest($queue_url, 'SendMessage', $params);
  176. if ($result->SendMessageResult->MessageId === null) {
  177. // require_once 'Zend/Service/Amazon/Sqs/Exception.php';
  178. throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code);
  179. } else if ((string) $result->SendMessageResult->MD5OfMessageBody != $checksum) {
  180. // require_once 'Zend/Service/Amazon/Sqs/Exception.php';
  181. throw new Zend_Service_Amazon_Sqs_Exception('MD5 of body does not match message sent');
  182. }
  183. return (string) $result->SendMessageResult->MessageId;
  184. }
  185. /**
  186. * Get messages in the queue
  187. *
  188. * @param string $queue_url Queue name
  189. * @param integer $max_messages Maximum number of messages to return
  190. * @param integer $timeout Visibility timeout for these messages
  191. * @return array
  192. * @throws Zend_Service_Amazon_Sqs_Exception
  193. */
  194. public function receive($queue_url, $max_messages = null, $timeout = null)
  195. {
  196. $params = array();
  197. // If not set, the visibility timeout on the queue is used
  198. if ($timeout !== null) {
  199. $params['VisibilityTimeout'] = (int)$timeout;
  200. }
  201. // SQS will default to only returning one message
  202. if ($max_messages !== null) {
  203. $params['MaxNumberOfMessages'] = (int)$max_messages;
  204. }
  205. $result = $this->_makeRequest($queue_url, 'ReceiveMessage', $params);
  206. if ($result->ReceiveMessageResult->Message === null) {
  207. // require_once 'Zend/Service/Amazon/Sqs/Exception.php';
  208. throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code);
  209. }
  210. $data = array();
  211. foreach ($result->ReceiveMessageResult->Message as $message) {
  212. $data[] = array(
  213. 'message_id' => (string)$message->MessageId,
  214. 'handle' => (string)$message->ReceiptHandle,
  215. 'md5' => (string)$message->MD5OfBody,
  216. 'body' => urldecode((string)$message->Body),
  217. );
  218. }
  219. return $data;
  220. }
  221. /**
  222. * Delete a message from the queue
  223. *
  224. * Returns true if the message is deleted, false if the deletion is
  225. * unsuccessful.
  226. *
  227. * @param string $queue_url Queue URL
  228. * @param string $handle Message handle as returned by SQS
  229. * @return boolean
  230. * @throws Zend_Service_Amazon_Sqs_Exception
  231. */
  232. public function deleteMessage($queue_url, $handle)
  233. {
  234. $params = array();
  235. $params['ReceiptHandle'] = (string)$handle;
  236. $result = $this->_makeRequest($queue_url, 'DeleteMessage', $params);
  237. if ($result->Error->Code !== null) {
  238. return false;
  239. }
  240. // Will always return true unless ReceiptHandle is malformed
  241. return true;
  242. }
  243. /**
  244. * Get the attributes for the queue
  245. *
  246. * @param string $queue_url Queue URL
  247. * @param string $attribute
  248. * @return string
  249. * @throws Zend_Service_Amazon_Sqs_Exception
  250. */
  251. public function getAttribute($queue_url, $attribute = 'All')
  252. {
  253. $params = array();
  254. $params['AttributeName'] = $attribute;
  255. $result = $this->_makeRequest($queue_url, 'GetQueueAttributes', $params);
  256. if ($result->GetQueueAttributesResult->Attribute === null) {
  257. // require_once 'Zend/Service/Amazon/Sqs/Exception.php';
  258. throw new Zend_Service_Amazon_Sqs_Exception($result->Error->Code);
  259. }
  260. return (string) $result->GetQueueAttributesResult->Attribute->Value;
  261. }
  262. /**
  263. * Make a request to Amazon SQS
  264. *
  265. * @param string $queue Queue Name
  266. * @param string $action SQS action
  267. * @param array $params
  268. * @return SimpleXMLElement
  269. */
  270. private function _makeRequest($queue_url, $action, $params = array())
  271. {
  272. $params['Action'] = $action;
  273. $params = $this->addRequiredParameters($queue_url, $params);
  274. if ($queue_url === null) {
  275. $queue_url = '/';
  276. }
  277. $client = self::getHttpClient();
  278. switch ($action) {
  279. case 'ListQueues':
  280. case 'CreateQueue':
  281. $client->setUri('http://'.$this->_sqsEndpoint);
  282. break;
  283. default:
  284. $client->setUri($queue_url);
  285. break;
  286. }
  287. $retry_count = 0;
  288. do {
  289. $retry = false;
  290. $client->resetParameters();
  291. $client->setParameterGet($params);
  292. $response = $client->request('GET');
  293. $response_code = $response->getStatus();
  294. // Some 5xx errors are expected, so retry automatically
  295. if ($response_code >= 500 && $response_code < 600 && $retry_count <= 5) {
  296. $retry = true;
  297. $retry_count++;
  298. sleep($retry_count / 4 * $retry_count);
  299. }
  300. } while ($retry);
  301. unset($client);
  302. return new SimpleXMLElement($response->getBody());
  303. }
  304. /**
  305. * Adds required authentication and version parameters to an array of
  306. * parameters
  307. *
  308. * The required parameters are:
  309. * - AWSAccessKey
  310. * - SignatureVersion
  311. * - Timestamp
  312. * - Version and
  313. * - Signature
  314. *
  315. * If a required parameter is already set in the <tt>$parameters</tt> array,
  316. * it is overwritten.
  317. *
  318. * @param string $queue_url Queue URL
  319. * @param array $parameters the array to which to add the required
  320. * parameters.
  321. * @return array
  322. */
  323. protected function addRequiredParameters($queue_url, array $parameters)
  324. {
  325. $parameters['AWSAccessKeyId'] = $this->_getAccessKey();
  326. $parameters['SignatureVersion'] = $this->_sqsSignatureVersion;
  327. $parameters['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z', time()+10);
  328. $parameters['Version'] = $this->_sqsApiVersion;
  329. $parameters['SignatureMethod'] = $this->_sqsSignatureMethod;
  330. $parameters['Signature'] = $this->_signParameters($queue_url, $parameters);
  331. return $parameters;
  332. }
  333. /**
  334. * Computes the RFC 2104-compliant HMAC signature for request parameters
  335. *
  336. * This implements the Amazon Web Services signature, as per the following
  337. * specification:
  338. *
  339. * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  340. * excluding <tt>Signature</tt>, the value of which is being created),
  341. * ignoring case.
  342. *
  343. * 2. Iterate over the sorted list and append the parameter name (in its
  344. * original case) and then its value. Do not URL-encode the parameter
  345. * values before constructing this string. Do not use any separator
  346. * characters when appending strings.
  347. *
  348. * @param string $queue_url Queue URL
  349. * @param array $parameters the parameters for which to get the signature.
  350. *
  351. * @return string the signed data.
  352. */
  353. protected function _signParameters($queue_url, array $paramaters)
  354. {
  355. $data = "GET\n";
  356. $data .= $this->_sqsEndpoint . "\n";
  357. if ($queue_url !== null) {
  358. $data .= parse_url($queue_url, PHP_URL_PATH);
  359. }
  360. else {
  361. $data .= '/';
  362. }
  363. $data .= "\n";
  364. uksort($paramaters, 'strcmp');
  365. unset($paramaters['Signature']);
  366. $arrData = array();
  367. foreach($paramaters as $key => $value) {
  368. $arrData[] = $key . '=' . str_replace('%7E', '~', urlencode($value));
  369. }
  370. $data .= implode('&', $arrData);
  371. $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Zend_Crypt_Hmac::BINARY);
  372. return base64_encode($hmac);
  373. }
  374. }