[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/lib/zend/Zend/Service/WindowsAzure/Storage/ -> Queue.php (source)

   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 [email protected] so we can send you a copy immediately.
  14   *
  15   * @category   Zend
  16   * @package    Zend_Service_WindowsAzure
  17   * @subpackage Storage
  18   * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19   * @license    http://todo     name_todo
  20   * @version    $Id$
  21   */
  22  
  23  /**
  24   * @see Zend_Service_WindowsAzure_Credentials_SharedKey
  25   */
  26  require_once 'Zend/Service/WindowsAzure/Credentials/SharedKey.php';
  27  
  28  /**
  29   * @see Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract
  30   */
  31  require_once 'Zend/Service/WindowsAzure/RetryPolicy/RetryPolicyAbstract.php';
  32  
  33  /**
  34   * @see Zend_Http_Client
  35   */
  36  require_once 'Zend/Http/Client.php';
  37  
  38  /**
  39   * @see Zend_Http_Response
  40   */
  41  require_once 'Zend/Http/Response.php';
  42  
  43  /**
  44   * @see Zend_Service_WindowsAzure_Storage
  45   */
  46  require_once 'Zend/Service/WindowsAzure/Storage.php';
  47  
  48  /**
  49   * Zend_Service_WindowsAzure_Storage_QueueInstance
  50   */
  51  require_once 'Zend/Service/WindowsAzure/Storage/QueueInstance.php';
  52  
  53  /**
  54   * Zend_Service_WindowsAzure_Storage_QueueMessage
  55   */
  56  require_once 'Zend/Service/WindowsAzure/Storage/QueueMessage.php';
  57  
  58  /**
  59   * @see Zend_Service_WindowsAzure_Exception
  60   */
  61  require_once 'Zend/Service/WindowsAzure/Exception.php';
  62  
  63  
  64  /**
  65   * @category   Zend
  66   * @package    Zend_Service_WindowsAzure
  67   * @subpackage Storage
  68   * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  69   * @license    http://framework.zend.com/license/new-bsd     New BSD License
  70   */
  71  class Zend_Service_WindowsAzure_Storage_Queue extends Zend_Service_WindowsAzure_Storage
  72  {
  73      /**
  74       * Maximal message size (in bytes)
  75       */
  76      const MAX_MESSAGE_SIZE = 8388608;
  77      
  78      /**
  79       * Maximal message ttl (in seconds)
  80       */
  81      const MAX_MESSAGE_TTL = 604800;
  82      
  83      /**
  84       * Creates a new Zend_Service_WindowsAzure_Storage_Queue instance
  85       *
  86       * @param string $host Storage host name
  87       * @param string $accountName Account name for Windows Azure
  88       * @param string $accountKey Account key for Windows Azure
  89       * @param boolean $usePathStyleUri Use path-style URI's
  90       * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  91       */
  92  	public function __construct($host = Zend_Service_WindowsAzure_Storage::URL_DEV_QUEUE, $accountName = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_ACCOUNT, $accountKey = Zend_Service_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_KEY, $usePathStyleUri = false, Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null)
  93      {
  94          parent::__construct($host, $accountName, $accountKey, $usePathStyleUri, $retryPolicy);
  95          
  96          // API version
  97          $this->_apiVersion = '2009-04-14';
  98      }
  99      
 100      /**
 101       * Check if a queue exists
 102       * 
 103       * @param string $queueName Queue name
 104       * @return boolean
 105       */
 106  	public function queueExists($queueName = '')
 107      {
 108          if ($queueName === '') {
 109              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 110          }
 111          if (!self::isValidQueueName($queueName)) {
 112              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 113          }
 114              
 115          // List queues
 116          $queues = $this->listQueues($queueName, 1);
 117          foreach ($queues as $queue) {
 118              if ($queue->Name == $queueName) {
 119                  return true;
 120              }
 121          }
 122          
 123          return false;
 124      }
 125      
 126      /**
 127       * Create queue
 128       *
 129       * @param string $queueName Queue name
 130       * @param array  $metadata  Key/value pairs of meta data
 131       * @return object Queue properties
 132       * @throws Zend_Service_WindowsAzure_Exception
 133       */
 134  	public function createQueue($queueName = '', $metadata = array())
 135      {
 136          if ($queueName === '') {
 137              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 138          }
 139          if (!self::isValidQueueName($queueName)) {
 140              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 141          }
 142              
 143          // Create metadata headers
 144          $headers = array();
 145          $headers = array_merge($headers, $this->_generateMetadataHeaders($metadata)); 
 146          
 147          // Perform request
 148          $response = $this->_performRequest($queueName, '', Zend_Http_Client::PUT, $headers);            
 149          if ($response->isSuccessful()) {
 150              return new Zend_Service_WindowsAzure_Storage_QueueInstance(
 151                  $queueName,
 152                  $metadata
 153              );
 154          } else {
 155              throw new Zend_Service_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
 156          }
 157      }
 158      
 159      /**
 160       * Get queue
 161       * 
 162       * @param string $queueName  Queue name
 163       * @return Zend_Service_WindowsAzure_Storage_QueueInstance
 164       * @throws Zend_Service_WindowsAzure_Exception
 165       */
 166  	public function getQueue($queueName = '')
 167      {
 168          if ($queueName === '') {
 169              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 170          }
 171          if (!self::isValidQueueName($queueName)) {
 172              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 173          }
 174              
 175          // Perform request
 176          $response = $this->_performRequest($queueName, '?comp=metadata', Zend_Http_Client::GET);    
 177          if ($response->isSuccessful()) {
 178              // Parse metadata
 179              $metadata = $this->_parseMetadataHeaders($response->getHeaders());
 180  
 181              // Return queue
 182              $queue = new Zend_Service_WindowsAzure_Storage_QueueInstance(
 183                  $queueName,
 184                  $metadata
 185              );
 186              $queue->ApproximateMessageCount = intval($response->getHeader('x-ms-approximate-message-count'));
 187              return $queue;
 188          } else {
 189              throw new Zend_Service_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
 190          }
 191      }
 192      
 193      /**
 194       * Get queue metadata
 195       * 
 196       * @param string $queueName  Queue name
 197       * @return array Key/value pairs of meta data
 198       * @throws Zend_Service_WindowsAzure_Exception
 199       */
 200  	public function getQueueMetadata($queueName = '')
 201      {
 202          if ($queueName === '') {
 203              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 204          }
 205          if (!self::isValidQueueName($queueName)) {
 206              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 207          }
 208              
 209          return $this->getQueue($queueName)->Metadata;
 210      }
 211      
 212      /**
 213       * Set queue metadata
 214       * 
 215       * Calling the Set Queue Metadata operation overwrites all existing metadata that is associated with the queue. It's not possible to modify an individual name/value pair.
 216       *
 217       * @param string $queueName  Queue name
 218       * @param array  $metadata       Key/value pairs of meta data
 219       * @throws Zend_Service_WindowsAzure_Exception
 220       */
 221  	public function setQueueMetadata($queueName = '', $metadata = array())
 222      {
 223          if ($queueName === '') {
 224              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 225          }
 226          if (!self::isValidQueueName($queueName)) {
 227              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 228          }
 229          if (count($metadata) == 0) {
 230              return;
 231          }
 232              
 233          // Create metadata headers
 234          $headers = array();
 235          $headers = array_merge($headers, $this->_generateMetadataHeaders($metadata)); 
 236          
 237          // Perform request
 238          $response = $this->_performRequest($queueName, '?comp=metadata', Zend_Http_Client::PUT, $headers);
 239  
 240          if (!$response->isSuccessful()) {
 241              throw new Zend_Service_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
 242          }
 243      }
 244      
 245      /**
 246       * Delete queue
 247       *
 248       * @param string $queueName Queue name
 249       * @throws Zend_Service_WindowsAzure_Exception
 250       */
 251  	public function deleteQueue($queueName = '')
 252      {
 253          if ($queueName === '') {
 254              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 255          }
 256          if (!self::isValidQueueName($queueName)) {
 257              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 258          }
 259              
 260          // Perform request
 261          $response = $this->_performRequest($queueName, '', Zend_Http_Client::DELETE);
 262          if (!$response->isSuccessful()) {
 263              throw new Zend_Service_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
 264          }
 265      }
 266      
 267      /**
 268       * List queues
 269       *
 270       * @param string $prefix     Optional. Filters the results to return only queues whose name begins with the specified prefix.
 271       * @param int    $maxResults Optional. Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000)
 272       * @param string $marker     Optional string value that identifies the portion of the list to be returned with the next list operation.
 273       * @param int    $currentResultCount Current result count (internal use)
 274       * @return array
 275       * @throws Zend_Service_WindowsAzure_Exception
 276       */
 277  	public function listQueues($prefix = null, $maxResults = null, $marker = null, $currentResultCount = 0)
 278      {
 279          // Build query string
 280          $queryString = '?comp=list';
 281          if (!is_null($prefix)) {
 282              $queryString .= '&prefix=' . $prefix;
 283          }
 284          if (!is_null($maxResults)) {
 285              $queryString .= '&maxresults=' . $maxResults;
 286          }
 287          if (!is_null($marker)) {
 288              $queryString .= '&marker=' . $marker;
 289          }
 290              
 291          // Perform request
 292          $response = $this->_performRequest('', $queryString, Zend_Http_Client::GET);    
 293          if ($response->isSuccessful()) {
 294              $xmlQueues = $this->_parseResponse($response)->Queues->Queue;
 295              $xmlMarker = (string)$this->_parseResponse($response)->NextMarker;
 296  
 297              $queues = array();
 298              if (!is_null($xmlQueues)) {
 299                  for ($i = 0; $i < count($xmlQueues); $i++) {
 300                      $queues[] = new Zend_Service_WindowsAzure_Storage_QueueInstance(
 301                          (string)$xmlQueues[$i]->QueueName
 302                      );
 303                  }
 304              }
 305              $currentResultCount = $currentResultCount + count($queues);
 306              if (!is_null($maxResults) && $currentResultCount < $maxResults) {
 307                  if (!is_null($xmlMarker) && $xmlMarker != '') {
 308                      $queues = array_merge($queues, $this->listQueues($prefix, $maxResults, $xmlMarker, $currentResultCount));
 309                  }
 310              }
 311              if (!is_null($maxResults) && count($queues) > $maxResults) {
 312                  $queues = array_slice($queues, 0, $maxResults);
 313              }
 314                  
 315              return $queues;
 316          } else {
 317              throw new Zend_Service_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
 318          }
 319      }
 320      
 321      /**
 322       * Put message into queue
 323       *
 324       * @param string $queueName  Queue name
 325       * @param string $message    Message
 326       * @param int    $ttl        Message Time-To-Live (in seconds). Defaults to 7 days if the parameter is omitted.
 327       * @throws Zend_Service_WindowsAzure_Exception
 328       */
 329  	public function putMessage($queueName = '', $message = '', $ttl = null)
 330      {
 331          if ($queueName === '') {
 332              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 333          }
 334          if (!self::isValidQueueName($queueName)) {
 335              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 336          }
 337          if (strlen($message) > self::MAX_MESSAGE_SIZE) {
 338              throw new Zend_Service_WindowsAzure_Exception('Message is too big. Message content should be < 8KB.');
 339          }
 340          if ($message == '') {
 341              throw new Zend_Service_WindowsAzure_Exception('Message is not specified.');
 342          }
 343          if (!is_null($ttl) && ($ttl <= 0 || $ttl > self::MAX_MESSAGE_SIZE)) {
 344              throw new Zend_Service_WindowsAzure_Exception('Message TTL is invalid. Maximal TTL is 7 days (' . self::MAX_MESSAGE_SIZE . ' seconds) and should be greater than zero.');
 345          }
 346              
 347          // Build query string
 348          $queryString = '';
 349          if (!is_null($ttl)) {
 350              $queryString .= '?messagettl=' . $ttl;
 351          }
 352              
 353          // Build body
 354          $rawData = '';
 355          $rawData .= '<QueueMessage>';
 356          $rawData .= '    <MessageText>' . base64_encode($message) . '</MessageText>';
 357          $rawData .= '</QueueMessage>';
 358              
 359          // Perform request
 360          $response = $this->_performRequest($queueName . '/messages', $queryString, Zend_Http_Client::POST, array(), false, $rawData);
 361  
 362          if (!$response->isSuccessful()) {
 363              throw new Zend_Service_WindowsAzure_Exception('Error putting message into queue.');
 364          }
 365      }
 366      
 367      /**
 368       * Get queue messages
 369       *
 370       * @param string $queueName         Queue name
 371       * @param string $numOfMessages     Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation.
 372       * @param int    $visibilityTimeout Optional. An integer value that specifies the message's visibility timeout in seconds. The maximum value is 2 hours. The default message visibility timeout is 30 seconds.
 373       * @param string $peek              Peek only?
 374       * @return array
 375       * @throws Zend_Service_WindowsAzure_Exception
 376       */
 377  	public function getMessages($queueName = '', $numOfMessages = 1, $visibilityTimeout = null, $peek = false)
 378      {
 379          if ($queueName === '') {
 380              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 381          }
 382          if (!self::isValidQueueName($queueName)) {
 383              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 384          }
 385          if ($numOfMessages < 1 || $numOfMessages > 32 || intval($numOfMessages) != $numOfMessages) {
 386              throw new Zend_Service_WindowsAzure_Exception('Invalid number of messages to retrieve.');
 387          }
 388          if (!is_null($visibilityTimeout) && ($visibilityTimeout <= 0 || $visibilityTimeout > 7200)) {
 389              throw new Zend_Service_WindowsAzure_Exception('Visibility timeout is invalid. Maximum value is 2 hours (7200 seconds) and should be greater than zero.');
 390          }
 391              
 392          // Build query string
 393          $query = array();
 394          if ($peek) {
 395              $query[] = 'peekonly=true';
 396          }
 397          if ($numOfMessages > 1) {
 398              $query[] = 'numofmessages=' . $numOfMessages;
 399          }
 400          if (!$peek && !is_null($visibilityTimeout)) {
 401              $query[] = 'visibilitytimeout=' . $visibilityTimeout;
 402          }   
 403          $queryString = '?' . implode('&', $query);
 404              
 405          // Perform request
 406          $response = $this->_performRequest($queueName . '/messages', $queryString, Zend_Http_Client::GET);    
 407          if ($response->isSuccessful()) {
 408              // Parse results
 409              $result = $this->_parseResponse($response);
 410              if (!$result) {
 411                  return array();
 412              }
 413  
 414              $xmlMessages = null;
 415              if (count($result->QueueMessage) > 1) {
 416                  $xmlMessages = $result->QueueMessage;
 417              } else {
 418                  $xmlMessages = array($result->QueueMessage);
 419              }
 420  
 421              $messages = array();
 422              for ($i = 0; $i < count($xmlMessages); $i++) {
 423                  $messages[] = new Zend_Service_WindowsAzure_Storage_QueueMessage(
 424                      (string)$xmlMessages[$i]->MessageId,
 425                      (string)$xmlMessages[$i]->InsertionTime,
 426                      (string)$xmlMessages[$i]->ExpirationTime,
 427                      ($peek ? '' : (string)$xmlMessages[$i]->PopReceipt),
 428                      ($peek ? '' : (string)$xmlMessages[$i]->TimeNextVisible),
 429                      base64_decode((string)$xmlMessages[$i]->MessageText)
 430                  );
 431              }
 432                  
 433              return $messages;
 434          } else {
 435              throw new Zend_Service_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
 436          }
 437      }
 438      
 439      /**
 440       * Peek queue messages
 441       *
 442       * @param string $queueName         Queue name
 443       * @param string $numOfMessages     Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation.
 444       * @return array
 445       * @throws Zend_Service_WindowsAzure_Exception
 446       */
 447  	public function peekMessages($queueName = '', $numOfMessages = 1)
 448      {
 449          return $this->getMessages($queueName, $numOfMessages, null, true);
 450      }
 451      
 452      /**
 453       * Clear queue messages
 454       *
 455       * @param string $queueName         Queue name
 456       * @throws Zend_Service_WindowsAzure_Exception
 457       */
 458  	public function clearMessages($queueName = '')
 459      {
 460          if ($queueName === '') {
 461              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 462          }
 463          if (!self::isValidQueueName($queueName)) {
 464              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 465          }
 466  
 467          // Perform request
 468          $response = $this->_performRequest($queueName . '/messages', '', Zend_Http_Client::DELETE);    
 469          if (!$response->isSuccessful()) {
 470              throw new Zend_Service_WindowsAzure_Exception('Error clearing messages from queue.');
 471          }
 472      }
 473      
 474      /**
 475       * Delete queue message
 476       *
 477       * @param string $queueName                             Queue name
 478       * @param Zend_Service_WindowsAzure_Storage_QueueMessage $message Message to delete from queue. A message retrieved using "peekMessages" can NOT be deleted!
 479       * @throws Zend_Service_WindowsAzure_Exception
 480       */
 481  	public function deleteMessage($queueName = '', Zend_Service_WindowsAzure_Storage_QueueMessage $message)
 482      {
 483          if ($queueName === '') {
 484              throw new Zend_Service_WindowsAzure_Exception('Queue name is not specified.');
 485          }
 486          if (!self::isValidQueueName($queueName)) {
 487              throw new Zend_Service_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
 488          }
 489          if ($message->PopReceipt == '') {
 490              throw new Zend_Service_WindowsAzure_Exception('A message retrieved using "peekMessages" can NOT be deleted! Use "getMessages" instead.');
 491          }
 492  
 493          // Perform request
 494          $response = $this->_performRequest($queueName . '/messages/' . $message->MessageId, '?popreceipt=' . $message->PopReceipt, Zend_Http_Client::DELETE);    
 495          if (!$response->isSuccessful()) {
 496              throw new Zend_Service_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
 497          }
 498      }
 499      
 500      /**
 501       * Is valid queue name?
 502       *
 503       * @param string $queueName Queue name
 504       * @return boolean
 505       */
 506      public static function isValidQueueName($queueName = '')
 507      {
 508          if (preg_match("/^[a-z0-9][a-z0-9-]*$/", $queueName) === 0) {
 509              return false;
 510          }
 511      
 512          if (strpos($queueName, '--') !== false) {
 513              return false;
 514          }
 515      
 516          if (strtolower($queueName) != $queueName) {
 517              return false;
 518          }
 519      
 520          if (strlen($queueName) < 3 || strlen($queueName) > 63) {
 521              return false;
 522          }
 523              
 524          if (substr($queueName, -1) == '-') {
 525              return false;
 526          }
 527      
 528          return true;
 529      }
 530      
 531      /**
 532       * Get error message from Zend_Http_Response
 533       * 
 534       * @param Zend_Http_Response $response Repsonse
 535       * @param string $alternativeError Alternative error message
 536       * @return string
 537       */
 538  	protected function _getErrorMessage(Zend_Http_Response $response, $alternativeError = 'Unknown error.')
 539      {
 540          $response = $this->_parseResponse($response);
 541          if ($response && $response->Message) {
 542              return (string)$response->Message;
 543          } else {
 544              return $alternativeError;
 545          }
 546      }
 547  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1