SimpleDb.php 18.4 KB
Newer Older
John Punzalan's avatar
John Punzalan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage SimpleDb
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Service_Amazon_Abstract
 */
#require_once 'Zend/Service/Amazon/Abstract.php';

/**
 * @see Zend_Service_Amazon_SimpleDb_Response
 */
#require_once 'Zend/Service/Amazon/SimpleDb/Response.php';

/**
 * @see Zend_Service_Amazon_SimpleDb_Page
 */
#require_once 'Zend/Service/Amazon/SimpleDb/Page.php';

/**
 * @see Zend_Service_Amazon_SimpleDb_Attribute
 */
#require_once 'Zend/Service/Amazon/SimpleDb/Attribute.php';

/**
 * @see Zend_Service_Amazon_SimpleDb_Exception
 */
#require_once 'Zend/Service/Amazon/SimpleDb/Exception.php';

/**
 * @see Zend_Crypt_Hmac
 */
#require_once 'Zend/Crypt/Hmac.php';

/**
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage SimpleDb
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_SimpleDb extends Zend_Service_Amazon_Abstract
{
    /* Notes */
    // TODO SSL is required

    /**
     * The HTTP query server
     */
    protected $_sdbEndpoint = 'sdb.amazonaws.com/';

    /**
     * Period after which HTTP request will timeout in seconds
     */
    protected $_httpTimeout = 10;

    /**
     * The API version to use
     */
    protected $_sdbApiVersion = '2009-04-15';

    /**
     * Signature Version
     */
    protected $_signatureVersion = '2';

    /**
     * Signature Encoding Method
     */
    protected $_signatureMethod = 'HmacSHA256';

    /**
     * Create Amazon SimpleDB client.
     *
     * @param string $accessKey       Override the default Access Key
     * @param string $secretKey       Override the default Secret Key
     */
    public function __construct($accessKey, $secretKey)
    {
        parent::__construct($accessKey, $secretKey);
        $this->setEndpoint("https://" . $this->_sdbEndpoint);
    }

    /**
     * Set SimpleDB endpoint to use
     *
     * @param string|Zend_Uri_Http $endpoint
     * @throws Zend_Service_Amazon_SimpleDb_Exception
     * @throws Zend_Uri_Exception
     * @return Zend_Service_Amazon_SimpleDb
     */
    public function setEndpoint($endpoint)
    {
        if(!($endpoint instanceof Zend_Uri_Http)) {
            $endpoint = Zend_Uri::factory($endpoint);
        }
        if(!$endpoint->valid()) {
            #require_once 'Zend/Service/Amazon/SimpleDb/Exception.php';
            throw new Zend_Service_Amazon_SimpleDb_Exception("Invalid endpoint supplied");
        }
        $this->_endpoint = $endpoint;
        return $this;
    }

    /**
     * Get SimpleDB endpoint
     *
     * @return Zend_Uri_Http
     */
    public function getEndpoint()
    {
        return $this->_endpoint;
    }

    /**
     * Get attributes API method
     *
     * @param string      $domainName Domain name within database
     * @param string      $itemName
     * @param string|null $attributeName
     * @throws Zend_Service_Amazon_SimpleDb_Exception
     * @return array
     */
    public function getAttributes(
        $domainName, $itemName, $attributeName = null
    ) {
        $params               = array();
        $params['Action']     = 'GetAttributes';
        $params['DomainName'] = $domainName;
        $params['ItemName']   = $itemName;

        if (isset($attributeName)) {
            $params['AttributeName'] = $attributeName;
        }

        $response = $this->_sendRequest($params);
        $document = $response->getSimpleXMLDocument();

        $attributeNodes = $document->GetAttributesResult->Attribute;

        // Return an array of arrays
        $attributes = array();
        foreach($attributeNodes as $attributeNode) {
            $name       = (string)$attributeNode->Name;
            $valueNodes = $attributeNode->Value;
            $data       = null;
            if (is_array($valueNodes) && !empty($valueNodes)) {
                $data = array();
                foreach($valueNodes as $valueNode) {
                    $data[] = (string)$valueNode;
                }
            } elseif (isset($valueNodes)) {
                $data = (string)$valueNodes;
            }
            if (isset($attributes[$name])) {
                $attributes[$name]->addValue($data);
            } else {
                $attributes[$name] = new Zend_Service_Amazon_SimpleDb_Attribute($itemName, $name, $data);
            }
        }
        return $attributes;
    }

    /**
     * Push attributes
     *
     * @param  string $domainName
     * @param  string $itemName
     * @param  array|Traversable $attributes
     * @param  array $replace
     * @return void
     */
    public function putAttributes(
        $domainName, $itemName, $attributes, $replace = array()
    ) {
        $params               = array();
        $params['Action']     = 'PutAttributes';
        $params['DomainName'] = $domainName;
        $params['ItemName']   = $itemName;

        $index = 0;
        foreach ($attributes as $attribute) {
            $attributeName = $attribute->getName();
            foreach ($attribute->getValues() as $value) {
                $params['Attribute.' . $index . '.Name']  = $attributeName;
                $params['Attribute.' . $index . '.Value'] = $value;

                // Check if it should be replaced
                if(array_key_exists($attributeName, $replace) && $replace[$attributeName]) {
                    $params['Attribute.' . $index . '.Replace'] = 'true';
                }
                $index++;
            }
        }

        // Exception should get thrown if there's an error
        $response = $this->_sendRequest($params);
    }

    /**
     * Add many attributes at once
     *
     * @param  array $items
     * @param  string $domainName
     * @param  array $replace
     * @return void
     */
    public function batchPutAttributes($items, $domainName, array $replace = array())
    {

        $params               = array();
        $params['Action']     = 'BatchPutAttributes';
        $params['DomainName'] = $domainName;

        $itemIndex = 0;
        foreach ($items as $name => $attributes) {
            $params['Item.' . $itemIndex . '.ItemName'] = $name;
            $attributeIndex = 0;
            foreach ($attributes as $attribute) {
                // attribute value cannot be array, so when several items are passed
                // they are treated as separate values with the same attribute name
                foreach($attribute->getValues() as $value) {
                    $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Name'] = $attribute->getName();
                    $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Value'] = $value;
                    if (isset($replace[$name])
                        && isset($replace[$name][$attribute->getName()])
                        && $replace[$name][$attribute->getName()]
                    ) {
                        $params['Item.' . $itemIndex . '.Attribute.' . $attributeIndex . '.Replace'] = 'true';
                    }
                    $attributeIndex++;
                }
            }
            $itemIndex++;
        }

        $response = $this->_sendRequest($params);
    }

    /**
     * Delete attributes
     *
     * @param  string $domainName
     * @param  string $itemName
     * @param  array $attributes
     * @return void
     */
    public function deleteAttributes($domainName, $itemName, array $attributes = array())
    {
        $params               = array();
        $params['Action']     = 'DeleteAttributes';
        $params['DomainName'] = $domainName;
        $params['ItemName']   = $itemName;

        $attributeIndex = 0;
        foreach ($attributes as $attribute) {
            foreach ($attribute->getValues() as $value) {
                $params['Attribute.' . $attributeIndex . '.Name'] = $attribute->getName();
                $params['Attribute.' . $attributeIndex . '.Value'] = $value;
                $attributeIndex++;
            }
        }

        $response = $this->_sendRequest($params);

        return true;
    }

    /**
     * List domains
     *
     * @param int $maxNumberOfDomains
     * @param int $nextToken
     * @return array              0 or more domain names
     */
    public function listDomains($maxNumberOfDomains = 100, $nextToken = null)
    {
        $params                       = array();
        $params['Action']             = 'ListDomains';
        $params['MaxNumberOfDomains'] = $maxNumberOfDomains;

        if (null !== $nextToken) {
            $params['NextToken'] = $nextToken;
        }
        $response = $this->_sendRequest($params);

        $domainNodes = $response->getSimpleXMLDocument()->ListDomainsResult->DomainName;

        $data = array();
        foreach ($domainNodes as $domain) {
            $data[] = (string)$domain;
        }

        $nextTokenNode = $response->getSimpleXMLDocument()->ListDomainsResult->NextToken;
        $nextToken     = (string)$nextTokenNode;

        return new Zend_Service_Amazon_SimpleDb_Page($data, $nextToken);
    }

    /**
     * Retrieve domain metadata
     *
     * @param string $domainName Name of the domain for which metadata will be requested
     * @return array Key/value array of metadatum names and values.
     */
    public function domainMetadata($domainName)
    {
        $params               = array();
        $params['Action']     = 'DomainMetadata';
        $params['DomainName'] = $domainName;
        $response             = $this->_sendRequest($params);

        $document = $response->getSimpleXMLDocument();

        $metadataNodes = $document->DomainMetadataResult->children();
        $metadata      = array();
        foreach ($metadataNodes as $metadataNode) {
            $name            = $metadataNode->getName();
            $metadata[$name] = (string)$metadataNode;
        }

        return $metadata;
    }

    /**
     * Create a new domain
     *
     * @param string $domainName Valid domain name of the domain to create
     * @return boolean True if successful, false if not
     */
    public function createDomain($domainName)
    {
        $params               = array();
        $params['Action']     = 'CreateDomain';
        $params['DomainName'] = $domainName;
        $response             = $this->_sendRequest($params);
        return $response->getHttpResponse()->isSuccessful();
    }

    /**
     * Delete a domain
     *
     * @param string $domainName Valid domain name of the domain to delete
     * @return boolean True if successful, false if not
     */
    public function deleteDomain($domainName)
    {
        $params               = array();
        $params['Action']     = 'DeleteDomain';
        $params['DomainName'] = $domainName;
        $response             = $this->_sendRequest($params);
        return $response->getHttpResponse()->isSuccessful();
    }

    /**
     * Select items from the database
     *
     * @param  string $selectExpression
     * @param  null|string $nextToken
     * @return Zend_Service_Amazon_SimpleDb_Page
     */
    public function select($selectExpression, $nextToken = null)
    {
        $params                     = array();
        $params['Action']           = 'Select';
        $params['SelectExpression'] = $selectExpression;

        if (null !== $nextToken) {
            $params['NextToken'] = $nextToken;
        }

        $response = $this->_sendRequest($params);
        $xml      = $response->getSimpleXMLDocument();

        $attributes = array();
        foreach ($xml->SelectResult->Item as $item) {
            $itemName = (string)$item->Name;

            foreach ($item->Attribute as $attribute) {
                $attributeName = (string)$attribute->Name;

                $values = array();
                foreach ($attribute->Value as $value) {
                    $values[] = (string)$value;
                }
                $attributes[$itemName][$attributeName] = new Zend_Service_Amazon_SimpleDb_Attribute($itemName, $attributeName, $values);
            }
        }

        $nextToken = (string)$xml->NextToken;

        return new Zend_Service_Amazon_SimpleDb_Page($attributes, $nextToken);
    }

    /**
     * Quote SDB value
     *
     * Wraps it in ''
     *
     * @param string $value
     * @return string
     */
    public function quote($value)
    {
        // wrap in single quotes and convert each ' inside to ''
        return "'" . str_replace("'", "''", $value) . "'";
    }

    /**
     * Quote SDB column or table name
     *
     * Wraps it in ``
     *
     * @param  string $name
     * @throws Zend_Service_Amazon_SimpleDb_Exception
     * @return string
     */
    public function quoteName($name)
    {
        if (preg_match('/^[a-z_$][a-z0-9_$-]*$/i', $name) == false) {
            throw new Zend_Service_Amazon_SimpleDb_Exception("Invalid name: can contain only alphanumeric characters, \$ and _");
        }
        return "`$name`";
    }

   /**
     * Sends a HTTP request to the SimpleDB service using Zend_Http_Client
     *
     * @param array $params         List of parameters to send with the request
     * @return Zend_Service_Amazon_SimpleDb_Response
     * @throws Zend_Service_Amazon_SimpleDb_Exception
     */
    protected function _sendRequest(array $params = array())
    {
        // UTF-8 encode all parameters and replace '+' characters
        foreach ($params as $name => $value) {
            unset($params[$name]);
            $params[utf8_encode($name)] = $value;
        }

        $params = $this->_addRequiredParameters($params);

        try {
            /* @var $request Zend_Http_Client */
            $request = self::getHttpClient();
            $request->resetParameters();

            $request->setConfig(array(
                'timeout' => $this->_httpTimeout
            ));


            $request->setUri($this->getEndpoint());
            $request->setMethod(Zend_Http_Client::POST);
            foreach ($params as $key => $value) {
                $params_out[] = rawurlencode($key)."=".rawurlencode($value);
            }
            $request->setRawData(join('&', $params_out), Zend_Http_Client::ENC_URLENCODED);
            $httpResponse = $request->request();
        } catch (Zend_Http_Client_Exception $zhce) {
            $message = 'Error in request to AWS service: ' . $zhce->getMessage();
            throw new Zend_Service_Amazon_SimpleDb_Exception($message, $zhce->getCode());
        }
        $response = new Zend_Service_Amazon_SimpleDb_Response($httpResponse);
        $this->_checkForErrors($response);
        return $response;
    }

    /**
     * Adds required authentication and version parameters to an array of
     * parameters
     *
     * The required parameters are:
     * - AWSAccessKey
     * - SignatureVersion
     * - Timestamp
     * - Version and
     * - Signature
     *
     * If a required parameter is already set in the <tt>$parameters</tt> array,
     * it is overwritten.
     *
     * @param array $parameters the array to which to add the required
     *                          parameters.
     *
     * @return array
     */
    protected function _addRequiredParameters(array $parameters)
    {
        $parameters['AWSAccessKeyId']   = $this->_getAccessKey();
        $parameters['SignatureVersion'] = $this->_signatureVersion;
        $parameters['Timestamp']        = gmdate('c');
        $parameters['Version']          = $this->_sdbApiVersion;
        $parameters['SignatureMethod']  = $this->_signatureMethod;
        $parameters['Signature']        = $this->_signParameters($parameters);

        return $parameters;
    }

    /**
     * Computes the RFC 2104-compliant HMAC signature for request parameters
     *
     * This implements the Amazon Web Services signature, as per the following
     * specification:
     *
     * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
     *    excluding <tt>Signature</tt>, the value of which is being created),
     *    ignoring case.
     *
     * 2. Iterate over the sorted list and append the parameter name (in its
     *    original case) and then its value. Do not URL-encode the parameter
     *    values before constructing this string. Do not use any separator
     *    characters when appending strings.
     *
     * @param array $parameters the parameters for which to get the signature.
     * @return string the signed data.
     */
    protected function _signParameters(array $parameters)
    {
        $data  = "POST\n";
        $data .= $this->getEndpoint()->getHost() . "\n";
        $data .= "/\n";

        uksort($parameters, 'strcmp');
        unset($parameters['Signature']);

        $arrData = array();
        foreach ($parameters as $key => $value) {
            $value = urlencode($value);
            $value = str_replace("%7E", "~", $value);
            $value = str_replace("+", "%20", $value);
            $arrData[] = urlencode($key) . '=' . $value;
        }

        $data .= implode('&', $arrData);

        #require_once 'Zend/Crypt/Hmac.php';
        $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Zend_Crypt_Hmac::BINARY);

        return base64_encode($hmac);
    }

    /**
     * Checks for errors responses from Amazon
     *
     * @param Zend_Service_Amazon_SimpleDb_Response $response the response object to
     *                                                   check.
     * @throws Zend_Service_Amazon_SimpleDb_Exception if one or more errors are
     *         returned from Amazon.
     */
    private function _checkForErrors(Zend_Service_Amazon_SimpleDb_Response $response)
    {
        $xpath = new DOMXPath($response->getDocument());
        $list  = $xpath->query('//Error');
        if ($list->length > 0) {
            $node    = $list->item(0);
            $code    = $xpath->evaluate('string(Code/text())', $node);
            $message = $xpath->evaluate('string(Message/text())', $node);
            throw new Zend_Service_Amazon_SimpleDb_Exception($message, 0, $code);
        }
    }
}