text:
<?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 Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Region.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Service_Amazon_Ec2_Abstract
 */
require_once 'Zend/Service/Amazon/Ec2/Abstract.php';

/**
 * An Amazon EC2 interface to query which Regions your account has access to.
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Ec2_Region extends Zend_Service_Amazon_Ec2_Abstract
{

    /**
     * Describes availability zones that are currently available to the account
     * and their states.
     *
     * @param string|array $region              Name of an region.
     * @return array                            An array that contains all the return items.  Keys: regionName and regionUrl.
     */
    public function describe($region = null)
    {
        $params = array();
        $params['Action'] = 'DescribeRegions';

        if(is_array($region) && !empty($region)) {
            foreach($region as $k=>$name) {
                $params['Region.' . ($k+1)] = $name;
            }
        } elseif($region) {
            $params['Region.1'] = $region;
        }

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

        $xpath  = $response->getXPath();
        $nodes  = $xpath->query('//ec2:item');

        $return = array();
        foreach ($nodes as $k => $node) {
            $item = array();
            $item['regionName']   = $xpath->evaluate('string(ec2:regionName/text())', $node);
            $item['regionUrl']  = $xpath->evaluate('string(ec2:regionUrl/text())', $node);

            $return[] = $item;
            unset($item);
        }

        return $return;
    }
}


text:
<?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 Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Elasticip.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Service_Amazon_Ec2_Abstract
 */
require_once 'Zend/Service/Amazon/Ec2/Abstract.php';

/**
 * An Amazon EC2 interface to allocate, associate, describe and release Elastic IP address
 * from your account.
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Ec2_Elasticip extends Zend_Service_Amazon_Ec2_Abstract
{
    /**
     * Acquires an elastic IP address for use with your account
     *
     * @return string                           Returns the newly Allocated IP Address
     */
    public function allocate()
    {
        $params = array();
        $params['Action'] = 'AllocateAddress';

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

        $xpath = $response->getXPath();
        $ip = $xpath->evaluate('string(//ec2:publicIp/text())');

        return $ip;
    }

    /**
     * Lists elastic IP addresses assigned to your account.
     *
     * @param string|array $publicIp            Elastic IP or list of addresses to describe.
     * @return array
     */
    public function describe($publicIp = null)
    {
        $params = array();
        $params['Action'] = 'DescribeAddresses';

        if(is_array($publicIp) && !empty($publicIp)) {
            foreach($publicIp as $k=>$name) {
                $params['PublicIp.' . ($k+1)] = $name;
            }
        } elseif($publicIp) {
            $params['PublicIp.1'] = $publicIp;
        }

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

        $xpath  = $response->getXPath();
        $nodes  = $xpath->query('//ec2:item');

        $return = array();
        foreach ($nodes as $k => $node) {
            $item = array();
            $item['publicIp']  = $xpath->evaluate('string(ec2:publicIp/text())', $node);
            $item['instanceId']   = $xpath->evaluate('string(ec2:instanceId/text())', $node);

            $return[] = $item;
            unset($item);
        }

        return $return;
    }

    /**
     * Releases an elastic IP address that is associated with your account
     *
     * @param string $publicIp                  IP address that you are releasing from your account.
     * @return boolean
     */
    public function release($publicIp)
    {
        $params = array();
        $params['Action'] = 'ReleaseAddress';
        $params['PublicIp'] = $publicIp;

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $return = $xpath->evaluate('string(//ec2:return/text())');

        return ($return === "true");
    }

    /**
     * Associates an elastic IP address with an instance
     *
     * @param string $instanceId                The instance to which the IP address is assigned
     * @param string $publicIp                  IP address that you are assigning to the instance.
     * @return boolean
     */
    public function associate($instanceId, $publicIp)
    {
        $params = array();
        $params['Action'] = 'AssociateAddress';
        $params['PublicIp'] = $publicIp;
        $params['InstanceId'] = $instanceId;

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $return = $xpath->evaluate('string(//ec2:return/text())');

        return ($return === "true");
    }

    /**
     * Disassociates the specified elastic IP address from the instance to which it is assigned.
     * This is an idempotent operation. If you enter it more than once, Amazon EC2 does not return an error.
     *
     * @param string $publicIp                  IP address that you are disassociating from the instance.
     * @return boolean
     */
    public function disassocate($publicIp)
    {
        $params = array();
        $params['Action'] = 'DisssociateAddress';
        $params['PublicIp'] = $publicIp;

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $return = $xpath->evaluate('string(//ec2:return/text())');

        return ($return === "true");
    }

}

repo_name: michael-romer/zf-boilerplate

repo_language: PHP

mime_type: text/html


text:
<?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 Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Response.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Http_Response
 */
require_once 'Zend/Http/Response.php';

/**
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Ec2_Response {
    /**
     * XML namespace used for EC2 responses.
     */
    protected $_xmlNamespace = 'http://ec2.amazonaws.com/doc/2009-04-04/';

    /**
     * The original HTTP response
     *
     * This contains the response body and headers.
     *
     * @var Zend_Http_Response
     */
    private $_httpResponse = null;

    /**
     * The response document object
     *
     * @var DOMDocument
     */
    private $_document = null;

    /**
     * The response XPath
     *
     * @var DOMXPath
     */
    private $_xpath = null;

    /**
     * Last error code
     *
     * @var integer
     */
    private $_errorCode = 0;

    /**
     * Last error message
     *
     * @var string
     */
    private $_errorMessage = '';

    /**
     * Creates a new high-level EC2 response object
     *
     * @param Zend_Http_Response $httpResponse the HTTP response.
     */
    public function __construct(Zend_Http_Response $httpResponse)
    {
        $this->_httpResponse = $httpResponse;
    }

    /**
     * Gets the XPath object for this response
     *
     * @return DOMXPath the XPath object for response.
     */
    public function getXPath()
    {
        if ($this->_xpath === null) {
            $document = $this->getDocument();
            if ($document === false) {
                $this->_xpath = false;
            } else {
                $this->_xpath = new DOMXPath($document);
                $this->_xpath->registerNamespace('ec2',
                    $this->getNamespace());
            }
        }

        return $this->_xpath;
    }

    /**
     * Gets the document object for this response
     *
     * @return DOMDocument the DOM Document for this response.
     */
    public function getDocument()
    {
        try {
            $body = $this->_httpResponse->getBody();
        } catch (Zend_Http_Exception $e) {
            $body = false;
        }

        if ($this->_document === null) {
            if ($body !== false) {
                // turn off libxml error handling
                $errors = libxml_use_internal_errors();

                $this->_document = new DOMDocument();
                if (!$this->_document->loadXML($body)) {
                    $this->_document = false;
                }

                // reset libxml error handling
                libxml_clear_errors();
                libxml_use_internal_errors($errors);
            } else {
                $this->_document = false;
            }
        }

        return $this->_document;
    }

    /**
     * Return the current set XML Namespace.
     *
     * @return string
     */
    public function getNamespace()
    {
        return $this->_xmlNamespace;
    }

    /**
     * Set a new XML Namespace
     *
     * @param string $namespace
     */
    public function setNamespace($namespace)
    {
        $this->_xmlNamespace = $namespace;
    }

}


text:
<?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 Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Keypair.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Service_Amazon_Ec2_Abstract
 */
require_once 'Zend/Service/Amazon/Ec2/Abstract.php';

/**
 * An Amazon EC2 interface to create, delete and describe Ec2 KeyPairs.
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Ec2_Keypair extends Zend_Service_Amazon_Ec2_Abstract
{
    /**
     * Creates a new 2048 bit RSA key pair and returns a unique ID that can
     * be used to reference this key pair when launching new instances.
     *
     * @param string $keyName           A unique name for the key pair.
     * @throws Zend_Service_Amazon_Ec2_Exception
     * @return array
     */
    public function create($keyName)
    {
        $params = array();

        $params['Action'] = 'CreateKeyPair';

        if(!$keyName) {
            require_once 'Zend/Service/Amazon/Ec2/Exception.php';
            throw new Zend_Service_Amazon_Ec2_Exception('Invalid Key Name');
        }

        $params['KeyName'] = $keyName;

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $return = array();
        $return['keyName']          = $xpath->evaluate('string(//ec2:keyName/text())');
        $return['keyFingerprint']   = $xpath->evaluate('string(//ec2:keyFingerprint/text())');
        $return['keyMaterial']      = $xpath->evaluate('string(//ec2:keyMaterial/text())');

        return $return;
    }

    /**
     * Returns information about key pairs available to you. If you specify
     * key pairs, information about those key pairs is returned. Otherwise,
     * information for all registered key pairs is returned.
     *
     * @param string|rarray $keyName    Key pair IDs to describe.
     * @return array
     */
    public function describe($keyName = null)
    {
        $params = array();

        $params['Action'] = 'DescribeKeyPairs';
        if(is_array($keyName) && !empty($keyName)) {
            foreach($keyName as $k=>$name) {
                $params['KeyName.' . ($k+1)] = $name;
            }
        } elseif($keyName) {
            $params['KeyName.1'] = $keyName;
        }

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $nodes  = $xpath->query('//ec2:keySet/ec2:item');

        $return = array();
        foreach ($nodes as $k => $node) {
            $item = array();
            $item['keyName']          = $xpath->evaluate('string(ec2:keyName/text())', $node);
            $item['keyFingerprint']   = $xpath->evaluate('string(ec2:keyFingerprint/text())', $node);

            $return[] = $item;
            unset($item);
        }

        return $return;
    }

    /**
     * Deletes a key pair
     *
     * @param string $keyName           Name of the key pair to delete.
     * @throws Zend_Service_Amazon_Ec2_Exception
     * @return boolean                  Return true or false from the deletion.
     */
    public function delete($keyName)
    {
        $params = array();

        $params['Action'] = 'DeleteKeyPair';

        if(!$keyName) {
            require_once 'Zend/Service/Amazon/Ec2/Exception.php';
            throw new Zend_Service_Amazon_Ec2_Exception('Invalid Key Name');
        }

        $params['KeyName'] = $keyName;

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

        $xpath = $response->getXPath();
        $success  = $xpath->evaluate('string(//ec2:return/text())');

        return ($success === "true");
    }
}


text:
<?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 Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Instance.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Service_Amazon_Ec2_Abstract
 */
require_once 'Zend/Service/Amazon/Ec2/Abstract.php';

/**
 * An Amazon EC2 interface that allows yout to run, terminate, reboot and describe Amazon
 * Ec2 Instances.
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Ec2_Instance extends Zend_Service_Amazon_Ec2_Abstract
{
    /**
     * Constant for Small Instance TYpe
     */
    const SMALL = 'm1.small';

    /**
     * Constant for Large Instance TYpe
     */
    const LARGE = 'm1.large';

    /**
     * Constant for X-Large Instance TYpe
     */
    const XLARGE = 'm1.xlarge';

    /**
     * Constant for High CPU Medium Instance TYpe
     */
    const HCPU_MEDIUM = 'c1.medium';

    /**
     * Constant for High CPU X-Large Instance TYpe
     */
    const HCPU_XLARGE = 'c1.xlarge';

    /**
     * Launches a specified number of Instances.
     *
     * If Amazon EC2 cannot launch the minimum number AMIs you request, no
     * instances launch. If there is insufficient capacity to launch the
     * maximum number of AMIs you request, Amazon EC2 launches as many
     * as possible to satisfy the requested maximum values.
     *
     * Every instance is launched in a security group. If you do not specify
     * a security group at launch, the instances start in your default security group.
     * For more information on creating security groups, see CreateSecurityGroup.
     *
     * An optional instance type can be specified. For information
     * about instance types, see Instance Types.
     *
     * You can provide an optional key pair ID for each image in the launch request
     * (for more information, see CreateKeyPair). All instances that are created
     * from images that use this key pair will have access to the associated public
     * key at boot. You can use this key to provide secure access to an instance of an
     * image on a per-instance basis. Amazon EC2 public images use this feature to
     * provide secure access without passwords.
     *
     * Launching public images without a key pair ID will leave them inaccessible.
     *
     * @param array $options                        An array that contins the options to start an instance.
     *                                              Required Values:
     *                                                imageId string        ID of the AMI with which to launch instances.
     *                                              Optional Values:
     *                                                minCount integer      Minimum number of instances to launch.
     *                                                maxCount integer      Maximum number of instances to launch.
     *                                                keyName string        Name of the key pair with which to launch instances.
     *                                                securityGruop string|array Names of the security groups with which to associate the instances.
     *                                                userData string       The user data available to the launched instances. This should not be Base64 encoded.
     *                                                instanceType constant Specifies the instance type.
     *                                                placement string      Specifies the availability zone in which to launch the instance(s). By default, Amazon EC2 selects an availability zone for you.
     *                                                kernelId string       The ID of the kernel with which to launch the instance.
     *                                                ramdiskId string      The ID of the RAM disk with which to launch the instance.
     *                                                blockDeviceVirtualName string     Specifies the virtual name to map to the corresponding device name. For example: instancestore0
     *                                                blockDeviceName string            Specifies the device to which you are mapping a virtual name. For example: sdb
     *                                                monitor boolean               Turn on CloudWatch Monitoring for an instance.
     * @return array
     */
    public function run(array $options)
    {
        $_defaultOptions = array(
            'minCount'  => 1,
            'maxCount'  => 1,
            'instanceType' => Zend_Service_Amazon_Ec2_Instance::SMALL
        );

        // set / override the defualt optoins if they are not passed into the array;
        $options = array_merge($_defaultOptions, $options);

        if(!isset($options['imageId'])) {
            require_once 'Zend/Service/Amazon/Ec2/Exception.php';
            throw new Zend_Service_Amazon_Ec2_Exception('No Image Id Provided');
        }

        $params = array();
        $params['Action'] = 'RunInstances';
        $params['ImageId'] = $options['imageId'];
        $params['MinCount'] = $options['minCount'];
        $params['MaxCount'] = $options['maxCount'];

        if(isset($options['keyName'])) {
            $params['KeyName'] = $options['keyName'];
        }

        if(is_array($options['securityGroup']) && !empty($options['securityGroup'])) {
            foreach($options['securityGroup'] as $k=>$name) {
                $params['SecurityGroup.' . ($k+1)] = $name;
            }
        } elseif(isset($options['securityGroup'])) {
            $params['SecurityGroup.1'] = $options['securityGroup'];
        }

        if(isset($options['userData'])) {
            $params['UserData'] = base64_encode($options['userData']);
        }

        if(isset($options['instanceType'])) {
            $params['InstanceType'] = $options['instanceType'];
        }

        if(isset($options['placement'])) {
            $params['Placement.AvailabilityZone'] = $options['placement'];
        }

        if(isset($options['kernelId'])) {
            $params['KernelId'] = $options['kernelId'];
        }

        if(isset($options['ramdiskId'])) {
            $params['RamdiskId'] = $options['ramdiskId'];
        }

        if(isset($options['blockDeviceVirtualName']) && isset($options['blockDeviceName'])) {
            $params['BlockDeviceMapping.n.VirtualName'] = $options['blockDeviceVirtualName'];
            $params['BlockDeviceMapping.n.DeviceName'] = $options['blockDeviceName'];
        }

        if(isset($options['monitor']) && $options['monitor'] === true) {
            $params['Monitoring.Enabled'] = true;
        }

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $return = array();

        $return['reservationId'] = $xpath->evaluate('string(//ec2:reservationId/text())');
        $return['ownerId'] = $xpath->evaluate('string(//ec2:ownerId/text())');

        $gs = $xpath->query('//ec2:groupSet/ec2:item');
        foreach($gs as $gs_node) {
            $return['groupSet'][] = $xpath->evaluate('string(ec2:groupId/text())', $gs_node);
            unset($gs_node);
        }
        unset($gs);

        $is = $xpath->query('//ec2:instancesSet/ec2:item');
        foreach($is as $is_node) {
            $item = array();

            $item['instanceId'] = $xpath->evaluate('string(ec2:instanceId/text())', $is_node);
            $item['imageId'] = $xpath->evaluate('string(ec2:imageId/text())', $is_node);
            $item['instanceState']['code'] = $xpath->evaluate('string(ec2:instanceState/ec2:code/text())', $is_node);
            $item['instanceState']['name'] = $xpath->evaluate('string(ec2:instanceState/ec2:name/text())', $is_node);
            $item['privateDnsName'] = $xpath->evaluate('string(ec2:privateDnsName/text())', $is_node);
            $item['dnsName'] = $xpath->evaluate('string(ec2:dnsName/text())', $is_node);
            $item['keyName'] = $xpath->evaluate('string(ec2:keyName/text())', $is_node);
            $item['instanceType'] = $xpath->evaluate('string(ec2:instanceType/text())', $is_node);
            $item['amiLaunchIndex'] = $xpath->evaluate('string(ec2:amiLaunchIndex/text())', $is_node);
            $item['launchTime'] = $xpath->evaluate('string(ec2:launchTime/text())', $is_node);
            $item['availabilityZone'] = $xpath->evaluate('string(ec2:placement/ec2:availabilityZone/text())', $is_node);

            $return['instances'][] = $item;
            unset($item);
            unset($is_node);
        }
        unset($is);

        return $return;

    }

    /**
     * Returns information about instances that you own.
     *
     * If you specify one or more instance IDs, Amazon EC2 returns information
     * for those instances. If you do not specify instance IDs, Amazon EC2
     * returns information for all relevant instances. If you specify an invalid
     * instance ID, a fault is returned. If you specify an instance that you do
     * not own, it will not be included in the returned results.
     *
     * Recently terminated instances might appear in the returned results.
     * This interval is usually less than one hour.
     *
     * @param string|array $instaceId       Set of instances IDs of which to get the status.
     * @param boolean                       Ture to ignore Terminated Instances.
     * @return array
     */
    public function describe($instanceId = null, $ignoreTerminated = false)
    {
        $params = array();
        $params['Action'] = 'DescribeInstances';

        if(is_array($instanceId) && !empty($instanceId)) {
            foreach($instanceId as $k=>$name) {
                $params['InstanceId.' . ($k+1)] = $name;
            }
        } elseif($instanceId) {
            $params['InstanceId.1'] = $instanceId;
        }

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

        $xpath = $response->getXPath();

        $nodes = $xpath->query('//ec2:reservationSet/ec2:item');

        $return = array();
        $return['instances'] = array();

        foreach($nodes as $node) {
            if($xpath->evaluate('string(ec2:instancesSet/ec2:item/ec2:instanceState/ec2:code/text())', $node) == 48 && $ignoreTerminated) continue;
            $item = array();

            $item['reservationId'] = $xpath->evaluate('string(ec2:reservationId/text())', $node);
            $item['ownerId'] = $xpath->evaluate('string(ec2:ownerId/text())', $node);

            $gs = $xpath->query('ec2:groupSet/ec2:item', $node);
            foreach($gs as $gs_node) {
                $item['groupSet'][] = $xpath->evaluate('string(ec2:groupId/text())', $gs_node);
                unset($gs_node);
            }
            unset($gs);

            $is = $xpath->query('ec2:instancesSet/ec2:item', $node);

            foreach($is as $is_node) {

                $item['instanceId'] = $xpath->evaluate('string(ec2:instanceId/text())', $is_node);
                $item['imageId'] = $xpath->evaluate('string(ec2:imageId/text())', $is_node);
                $item['instanceState']['code'] = $xpath->evaluate('string(ec2:instanceState/ec2:code/text())', $is_node);
                $item['instanceState']['name'] = $xpath->evaluate('string(ec2:instanceState/ec2:name/text())', $is_node);
                $item['privateDnsName'] = $xpath->evaluate('string(ec2:privateDnsName/text())', $is_node);
                $item['dnsName'] = $xpath->evaluate('string(ec2:dnsName/text())', $is_node);
                $item['keyName'] = $xpath->evaluate('string(ec2:keyName/text())', $is_node);
                $item['productCode'] = $xpath->evaluate('string(ec2:productCodesSet/ec2:item/ec2:productCode/text())', $is_node);
                $item['instanceType'] = $xpath->evaluate('string(ec2:instanceType/text())', $is_node);
                $item['launchTime'] = $xpath->evaluate('string(ec2:launchTime/text())', $is_node);
                $item['availabilityZone'] = $xpath->evaluate('string(ec2:placement/ec2:availabilityZone/text())', $is_node);
                $item['kernelId'] = $xpath->evaluate('string(ec2:kernelId/text())', $is_node);
                $item['ramediskId'] = $xpath->evaluate('string(ec2:ramediskId/text())', $is_node);
                $item['amiLaunchIndex'] = $xpath->evaluate('string(ec2:amiLaunchIndex/text())', $is_node);
                $item['monitoringState'] = $xpath->evaluate('string(ec2:monitoring/ec2:state/text())', $is_node);

                $return['instances'][] = $item;
                unset($is_node);
            }
            unset($item);
            unset($is);
        }

        return $return;
    }

    /**
     * Returns information about instances that you own that were started from
     * a specific imageId
     *
     * Recently terminated instances might appear in the returned results.
     * This interval is usually less than one hour.
     *
     * @param string $imageId               The imageId used to start the Instance.
     * @param boolean                       Ture to ignore Terminated Instances.
     * @return array
     */
    public function describeByImageId($imageId, $ignoreTerminated = false)
    {
        $arrInstances = $this->describe(null, $ignoreTerminated);

        $return = array();

        foreach($arrInstances['instances'] as $instance) {
            if($instance['imageId'] !== $imageId) continue;
            $return[] = $instance;
        }

        return $return;
    }

    /**
     * Shuts down one or more instances. This operation is idempotent; if you terminate
     * an instance more than once, each call will succeed.
     *
     * Terminated instances will remain visible after termination (approximately one hour).
     *
     * @param string|array $instanceId      One or more instance IDs returned.
     * @return array
     */
    public function terminate($instanceId)
    {
        $params = array();
        $params['Action'] = 'TerminateInstances';

        if(is_array($instanceId) && !empty($instanceId)) {
            foreach($instanceId as $k=>$name) {
                $params['InstanceId.' . ($k+1)] = $name;
            }
        } elseif($instanceId) {
            $params['InstanceId.1'] = $instanceId;
        }

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $nodes = $xpath->query('//ec2:instancesSet/ec2:item');

        $return = array();
        foreach($nodes as $node) {
            $item = array();

            $item['instanceId'] = $xpath->evaluate('string(ec2:instanceId/text())', $node);
            $item['shutdownState']['code'] = $xpath->evaluate('string(ec2:shutdownState/ec2:code/text())', $node);
            $item['shutdownState']['name'] = $xpath->evaluate('string(ec2:shutdownState/ec2:name/text())', $node);
            $item['previousState']['code'] = $xpath->evaluate('string(ec2:previousState/ec2:code/text())', $node);
            $item['previousState']['name'] = $xpath->evaluate('string(ec2:previousState/ec2:name/text())', $node);

            $return[] = $item;
            unset($item);
        }

        return $return;
    }

    /**
     * Requests a reboot of one or more instances.
     *
     * This operation is asynchronous; it only queues a request to reboot the specified instance(s). The operation
     * will succeed if the instances are valid and belong to the user. Requests to reboot terminated instances are ignored.
     *
     * @param string|array $instanceId  One or more instance IDs.
     * @return boolean
     */
    public function reboot($instanceId)
    {
        $params = array();
        $params['Action'] = 'RebootInstances';

        if(is_array($instanceId) && !empty($instanceId)) {
            foreach($instanceId as $k=>$name) {
                $params['InstanceId.' . ($k+1)] = $name;
            }
        } elseif($instanceId) {
            $params['InstanceId.1'] = $instanceId;
        }

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $return = $xpath->evaluate('string(//ec2:return/text())');

        return ($return === "true");
    }

    /**
     * Retrieves console output for the specified instance.
     *
     * Instance console output is buffered and posted shortly after instance boot, reboot, and termination.
     * Amazon EC2 preserves the most recent 64 KB output which will be available for at least one hour after the most recent post.
     *
     * @param string $instanceId       An instance ID
     * @return array
     */
    public function consoleOutput($instanceId)
    {
        $params = array();
        $params['Action'] = 'GetConsoleOutput';
        $params['InstanceId'] = $instanceId;

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $return = array();

        $return['instanceId'] = $xpath->evaluate('string(//ec2:instanceId/text())');
        $return['timestamp'] = $xpath->evaluate('string(//ec2:timestamp/text())');
        $return['output'] = base64_decode($xpath->evaluate('string(//ec2:output/text())'));

        return $return;
    }

    /**
     * Returns true if the specified product code is attached to the specified instance.
     * The operation returns false if the product code is not attached to the instance.
     *
     * The confirmProduct operation can only be executed by the owner of the AMI.
     * This feature is useful when an AMI owner is providing support and wants to
     * verify whether a user's instance is eligible.
     *
     * @param string $productCode           The product code to confirm.
     * @param string $instanceId            The instance for which to confirm the product code.
     * @return array|boolean                An array if the product code is attached to the instance, false if it is not.
     */
    public function confirmProduct($productCode, $instanceId)
    {
        $params = array();
        $params['Action'] = 'ConfirmProductInstance';
        $params['ProductCode'] = $productCode;
        $params['InstanceId'] = $instanceId;

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $result = $xpath->evaluate('string(//ec2:result/text())');

        if($result === "true") {
            $return['result'] = true;
            $return['ownerId'] = $xpath->evaluate('string(//ec2:ownerId/text())');

            return $return;
        }

        return false;
    }

    /**
    * Turn on Amazon CloudWatch Monitoring for an instance or a list of instances
    *
    * @param array|string $instanceId           The instance or list of instances you want to enable monitoring for
    * @return array
    */
    public function monitor($instanceId)
    {
        $params = array();
        $params['Action'] = 'MonitorInstances';

        if(is_array($instanceId) && !empty($instanceId)) {
            foreach($instanceId as $k=>$name) {
                $params['InstanceId.' . ($k+1)] = $name;
            }
        } elseif($instanceId) {
            $params['InstanceId.1'] = $instanceId;
        }

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $items = $xpath->query('//ec2:instancesSet/ec2:item');

        $arrReturn = array();
        foreach($items as $item) {
            $i = array();
            $i['instanceid'] = $xpath->evaluate('string(//ec2:instanceId/text())', $item);
            $i['monitorstate'] = $xpath->evaluate('string(//ec2:monitoring/ec2:state/text())');
            $arrReturn[] = $i;
            unset($i);
        }

        return $arrReturn;
    }
    /**
    * Turn off Amazon CloudWatch Monitoring for an instance or a list of instances
    *
    * @param array|string $instanceId           The instance or list of instances you want to disable monitoring for
    * @return array
    */
    public function unmonitor($instanceId)
    {
        $params = array();
        $params['Action'] = 'UnmonitorInstances';

        if(is_array($instanceId) && !empty($instanceId)) {
            foreach($instanceId as $k=>$name) {
                $params['InstanceId.' . ($k+1)] = $name;
            }
        } elseif($instanceId) {
            $params['InstanceId.1'] = $instanceId;
        }

        $response = $this->sendRequest($params);
        $xpath = $response->getXPath();

        $items = $xpath->query('//ec2:instancesSet/ec2:item');

        $arrReturn = array();
        foreach($items as $item) {
            $i = array();
            $i['instanceid'] = $xpath->evaluate('string(//ec2:instanceId/text())', $item);
            $i['monitorstate'] = $xpath->evaluate('string(//ec2:monitoring/ec2:state/text())');
            $arrReturn[] = $i;
            unset($i);
        }

        return $arrReturn;
    }

}


text:
<?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 Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Windows.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Service_Amazon_Ec2_Abstract
 */
require_once 'Zend/Service/Amazon/Ec2/Abstract.php';

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

/**
 * @see Zend_Json
 */
require_once 'Zend/Json.php';

/**
 * An Amazon EC2 interface that allows yout to run, terminate, reboot and describe Amazon
 * Ec2 Instances.
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Ec2_Instance_Windows extends Zend_Service_Amazon_Ec2_Abstract
{
    /**
     * Bundles an Amazon EC2 instance running Windows
     *
     * @param string $instanceId        The instance you want to bundle
     * @param string $s3Bucket          Where you want the ami to live on S3
     * @param string $s3Prefix          The prefix you want to assign to the AMI on S3
     * @param integer $uploadExpiration The expiration of the upload policy.  Amazon recommends 12 hours or longer.
     *                                  This is based in nubmer of minutes. Default is 1440 minutes (24 hours)
     * @return array                    containing the information on the new bundle operation
     */
    public function bundle($instanceId, $s3Bucket, $s3Prefix, $uploadExpiration = 1440)
    {
        $params = array();
        $params['Action'] = 'BundleInstance';
        $params['InstanceId'] = $instanceId;
        $params['Storage.S3.AWSAccessKeyId'] = $this->_getAccessKey();
        $params['Storage.S3.Bucket'] = $s3Bucket;
        $params['Storage.S3.Prefix'] = $s3Prefix;
        $uploadPolicy = $this->_getS3UploadPolicy($s3Bucket, $s3Prefix, $uploadExpiration);
        $params['Storage.S3.UploadPolicy'] = $uploadPolicy;
        $params['Storage.S3.UploadPolicySignature'] = $this->_signS3UploadPolicy($uploadPolicy);

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

        $xpath = $response->getXPath();

        $return = array();
        $return['instanceId'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:instanceId/text())');
        $return['bundleId'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:bundleId/text())');
        $return['state'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:state/text())');
        $return['startTime'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:startTime/text())');
        $return['updateTime'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:updateTime/text())');
        $return['progress'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:progress/text())');
        $return['storage']['s3']['bucket'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:storage/ec2:S3/ec2:bucket/text())');
        $return['storage']['s3']['prefix'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:storage/ec2:S3/ec2:prefix/text())');

        return $return;
    }

    /**
     * Cancels an Amazon EC2 bundling operation
     *
     * @param string $bundleId          The ID of the bundle task to cancel
     * @return array                    Information on the bundle task
     */
    public function cancelBundle($bundleId)
    {
        $params = array();
        $params['Action'] = 'CancelBundleTask';
        $params['BundleId'] = $bundleId;

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

        $xpath = $response->getXPath();

        $return = array();
        $return['instanceId'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:instanceId/text())');
        $return['bundleId'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:bundleId/text())');
        $return['state'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:state/text())');
        $return['startTime'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:startTime/text())');
        $return['updateTime'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:updateTime/text())');
        $return['progress'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:progress/text())');
        $return['storage']['s3']['bucket'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:storage/ec2:S3/ec2:bucket/text())');
        $return['storage']['s3']['prefix'] = $xpath->evaluate('string(//ec2:bundleInstanceTask/ec2:storage/ec2:S3/ec2:prefix/text())');

        return $return;
    }

    /**
     * Describes current bundling tasks
     *
     * @param string|array $bundleId            A single or a list of bundle tasks that you want
     *                                          to find information for.
     * @return array                            Information for the task that you requested
     */
    public function describeBundle($bundleId = '')
    {
        $params = array();
        $params['Action'] = 'DescribeBundleTasks';

        if(is_array($bundleId) && !empty($bundleId)) {
            foreach($bundleId as $k=>$name) {
                $params['bundleId.' . ($k+1)] = $name;
            }
        } elseif(!empty($bundleId)) {
            $params['bundleId.1'] = $bundleId;
        }

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

        $xpath = $response->getXPath();

        $items = $xpath->evaluate('//ec2:bundleInstanceTasksSet/ec2:item');
        $return = array();

        foreach($items as $item) {
            $i = array();
            $i['instanceId'] = $xpath->evaluate('string(ec2:instanceId/text())', $item);
            $i['bundleId'] = $xpath->evaluate('string(ec2:bundleId/text())', $item);
            $i['state'] = $xpath->evaluate('string(ec2:state/text())', $item);
            $i['startTime'] = $xpath->evaluate('string(ec2:startTime/text())', $item);
            $i['updateTime'] = $xpath->evaluate('string(ec2:updateTime/text())', $item);
            $i['progress'] = $xpath->evaluate('string(ec2:progress/text())', $item);
            $i['storage']['s3']['bucket'] = $xpath->evaluate('string(ec2:storage/ec2:S3/ec2:bucket/text())', $item);
            $i['storage']['s3']['prefix'] = $xpath->evaluate('string(ec2:storage/ec2:S3/ec2:prefix/text())', $item);

            $return[] = $i;
            unset($i);
        }

        return $return;
    }

    /**
     * Generates the S3 Upload Policy Information
     *
     * @param string $bucketName        Which bucket you want the ami to live in on S3
     * @param string $prefix            The prefix you want to assign to the AMI on S3
     * @param integer $expireInMinutes  The expiration of the upload policy.  Amazon recommends 12 hours or longer.
     *                                  This is based in nubmer of minutes. Default is 1440 minutes (24 hours)
     * @return string                   Base64 encoded string that is the upload policy
     */
    protected function _getS3UploadPolicy($bucketName, $prefix, $expireInMinutes = 1440)
    {
        $arrParams = array();
        $arrParams['expiration'] = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", (time() + ($expireInMinutes * 60)));
        $arrParams['conditions'][] = array('bucket' => $bucketName);
        $arrParams['conditions'][] = array('acl' => 'ec2-bundle-read');
        $arrParams['conditions'][] = array('starts-with', '$key', $prefix);

        return base64_encode(Zend_Json::encode($arrParams));
    }

    /**
     * Signed S3 Upload Policy
     *
     * @param string $policy            Base64 Encoded string that is the upload policy
     * @return string                   SHA1 encoded S3 Upload Policy
     */
    protected function _signS3UploadPolicy($policy)
    {
        $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA1', $policy, Zend_Crypt_Hmac::BINARY);
        return $hmac;
    }
}


text:
<?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 Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Reserved.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Service_Amazon_Ec2_Abstract
 */
require_once 'Zend/Service/Amazon/Ec2/Abstract.php';

/**
 * Allows you to interface with the reserved instances on Amazon Ec2
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Ec2
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Ec2_Instance_Reserved extends Zend_Service_Amazon_Ec2_Abstract
{
    /**
     * Describes Reserved Instances that you purchased.
     *
     * @param string|array $instanceId        IDs of the Reserved Instance to describe.
     * @return array
     */
    public function describeInstances($instanceId)
    {
        $params = array();
        $params['Action'] = 'DescribeReservedInstances';

        if(is_array($instanceId) && !empty($instanceId)) {
            foreach($instanceId as $k=>$name) {
                $params['ReservedInstancesId.' . ($k+1)] = $name;
            }
        } elseif($instanceId) {
            $params['ReservedInstancesId.1'] = $instanceId;
        }

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

        $xpath = $response->getXPath();
        $items = $xpath->query('//ec2:reservedInstancesSet/ec2:item');

        $return = array();
        foreach($items as $item) {
            $i = array();
            $i['reservedInstancesId'] = $xpath->evaluate('string(ec2:reservedInstancesId/text())', $item);
            $i['instanceType'] = $xpath->evaluate('string(ec2:instanceType/text())', $item);
            $i['availabilityZone'] = $xpath->evaluate('string(ec2:availabilityZone/text())', $item);
            $i['duration'] = $xpath->evaluate('string(ec2:duration/text())', $item);
            $i['fixedPrice'] = $xpath->evaluate('string(ec2:fixedPrice/text())', $item);
            $i['usagePrice'] = $xpath->evaluate('string(ec2:usagePrice/text())', $item);
            $i['productDescription'] = $xpath->evaluate('string(ec2:productDescription/text())', $item);
            $i['instanceCount'] = $xpath->evaluate('string(ec2:instanceCount/text())', $item);
            $i['state'] = $xpath->evaluate('string(ec2:state/text())', $item);

            $return[] = $i;
            unset($i);
        }

        return $return;
    }

    /**
     * Describes Reserved Instance offerings that are available for purchase.
     * With Amazon EC2 Reserved Instances, you purchase the right to launch Amazon
     * EC2 instances for a period of time (without getting insufficient capacity
     * errors) and pay a lower usage rate for the actual time used.
     *
     * @return array
     */
    public function describeOfferings()
    {
        $params = array();
        $params['Action'] = 'DescribeReservedInstancesOfferings';

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

        $xpath = $response->getXPath();
        $items = $xpath->query('//ec2:reservedInstancesOfferingsSet/ec2:item');

        $return = array();
        foreach($items as $item) {
            $i = array();
            $i['reservedInstancesOfferingId'] = $xpath->evaluate('string(ec2:reservedInstancesOfferingId/text())', $item);
            $i['instanceType'] = $xpath->evaluate('string(ec2:instanceType/text())', $item);
            $i['availabilityZone'] = $xpath->evaluate('string(ec2:availabilityZone/text())', $item);
            $i['duration'] = $xpath->evaluate('string(ec2:duration/text())', $item);
            $i['fixedPrice'] = $xpath->evaluate('string(ec2:fixedPrice/text())', $item);
            $i['usagePrice'] = $xpath->evaluate('string(ec2:usagePrice/text())', $item);
            $i['productDescription'] = $xpath->evaluate('string(ec2:productDescription/text())', $item);

            $return[] = $i;
            unset($i);
        }

        return $return;
    }

    /**
     * Purchases a Reserved Instance for use with your account. With Amazon EC2
     * Reserved Instances, you purchase the right to launch Amazon EC2 instances
     * for a period of time (without getting insufficient capacity errors) and
     * pay a lower usage rate for the actual time used.
     *
     * @param string $offeringId            The offering ID of the Reserved Instance to purchase
     * @param integer $intanceCount         The number of Reserved Instances to purchase.
     * @return string                       The ID of the purchased Reserved Instances.
     */
    public function purchaseOffering($offeringId, $intanceCount = 1)
    {
        $params = array();
        $params['Action'] = 'PurchaseReservedInstancesOffering';
        $params['OfferingId.1'] = $offeringId;
        $params['instanceCount.1'] = intval($intanceCount);

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

        $xpath = $response->getXPath();
        $reservedInstancesId = $xpath->evaluate('string(//ec2:reservedInstancesId/text())');

        return $reservedInstancesId;
    }
}


text:
<?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
 * @subpackage Amazon_S3
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Stream.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Service_Amazon_S3
 */
require_once 'Zend/Service/Amazon/S3.php';

/**
 * Amazon S3 PHP stream wrapper
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon_S3
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_S3_Stream
{
    /**
     * @var boolean Write the buffer on fflush()?
     */
    private $_writeBuffer = false;

    /**
     * @var integer Current read/write position
     */
    private $_position = 0;

    /**
     * @var integer Total size of the object as returned by S3 (Content-length)
     */
    private $_objectSize = 0;

    /**
     * @var string File name to interact with
     */
    private $_objectName = null;

    /**
     * @var string Current read/write buffer
     */
    private $_objectBuffer = null;

    /**
     * @var array Available buckets
     */
    private $_bucketList = array();

    /**
     * @var Zend_Service_Amazon_S3
     */
    private $_s3 = null;

    /**
     * Retrieve client for this stream type
     *
     * @param  string $path
     * @return Zend_Service_Amazon_S3
     */
    protected function _getS3Client($path)
    {
        if ($this->_s3 === null) {
            $url = explode(':', $path);

            if (!$url) {
                /**
                 * @see Zend_Service_Amazon_S3_Exception
                 */
                require_once 'Zend/Service/Amazon/S3/Exception.php';
                throw new Zend_Service_Amazon_S3_Exception("Unable to parse URL $path");
            }

            $this->_s3 = Zend_Service_Amazon_S3::getWrapperClient($url[0]);
            if (!$this->_s3) {
                /**
                 * @see Zend_Service_Amazon_S3_Exception
                 */
                require_once 'Zend/Service/Amazon/S3/Exception.php';
                throw new Zend_Service_Amazon_S3_Exception("Unknown client for wrapper {$url[0]}");
            }
        }

        return $this->_s3;
    }

    /**
     * Extract object name from URL
     *
     * @param string $path
     * @return string
     */
    protected function _getNamePart($path)
    {
        $url = parse_url($path);
        if ($url['host']) {
            return !empty($url['path']) ? $url['host'].$url['path'] : $url['host'];
        }

        return '';
    }
    /**
     * Open the stream
     *
     * @param  string  $path
     * @param  string  $mode
     * @param  integer $options
     * @param  string  $opened_path
     * @return boolean
     */
    public function stream_open($path, $mode, $options, $opened_path)
    {
        $name = $this->_getNamePart($path);
        // If we open the file for writing, just return true. Create the object
        // on fflush call
        if (strpbrk($mode, 'wax')) {
            $this->_objectName = $name;
            $this->_objectBuffer = null;
            $this->_objectSize = 0;
            $this->_position = 0;
            $this->_writeBuffer = true;
            $this->_getS3Client($path);
            return true;
        } else {
            // Otherwise, just see if the file exists or not
            $info = $this->_getS3Client($path)->getInfo($name);
            if ($info) {
                $this->_objectName = $name;
                $this->_objectBuffer = null;
                $this->_objectSize = $info['size'];
                $this->_position = 0;
                $this->_writeBuffer = false;
                $this->_getS3Client($path);
                return true;
            }
        }
        return false;
    }

    /**
     * Close the stream
     *
     * @return void
     */
    public function stream_close()
    {
        $this->_objectName = null;
        $this->_objectBuffer = null;
        $this->_objectSize = 0;
        $this->_position = 0;
        $this->_writeBuffer = false;
        unset($this->_s3);
    }

    /**
     * Read from the stream
     *
     * http://bugs.php.net/21641 - stream_read() is always passed PHP's
     * internal read buffer size (8192) no matter what is passed as $count
     * parameter to fread().
     *
     * @param  integer $count
     * @return string
     */
    public function stream_read($count)
    {
        if (!$this->_objectName) {
            return false;
        }

        // make sure that count doesn't exceed object size
        if ($count + $this->_position > $this->_objectSize) {
            $count = $this->_objectSize - $this->_position;
        }

        $range_start = $this->_position;
        $range_end   = $this->_position + $count - 1;

        // Only fetch more data from S3 if we haven't fetched any data yet (postion=0)
        // OR, the range end position plus 1 is greater than the size of the current
        // object buffer
        if ($this->_objectBuffer === null  ||  $range_end >= strlen($this->_objectBuffer)) {
            $headers = array(
                'Range' => "bytes=$range_start-$range_end"
            );

            $response = $this->_s3->_makeRequest('GET', $this->_objectName, null, $headers);

            if ($response->getStatus() == 206) { // 206 Partial Content
                $this->_objectBuffer .= $response->getBody();
            }
        }

        $data = substr($this->_objectBuffer, $this->_position, $count);
        $this->_position += strlen($data);
        return $data;
    }

    /**
     * Write to the stream
     *
     * @param  string $data
     * @return integer
     */
    public function stream_write($data)
    {
        if (!$this->_objectName) {
            return 0;
        }
        $len = strlen($data);
        $this->_objectBuffer .= $data;
        $this->_objectSize += $len;
        // TODO: handle current position for writing!
        return $len;
    }

    /**
     * End of the stream?
     *
     * @return boolean
     */
    public function stream_eof()
    {
        if (!$this->_objectName) {
            return true;
        }

        return ($this->_position >= $this->_objectSize);
    }

    /**
     * What is the current read/write position of the stream
     *
     * @return integer
     */
    public function stream_tell()
    {
        return $this->_position;
    }

    /**
     * Update the read/write position of the stream
     *
     * @param  integer $offset
     * @param  integer $whence
     * @return boolean
     */
    public function stream_seek($offset, $whence)
    {
        if (!$this->_objectName) {
            return false;
        }

        switch ($whence) {
            case SEEK_CUR:
                // Set position to current location plus $offset
                $new_pos = $this->_position + $offset;
                break;
            case SEEK_END:
                // Set position to end-of-file plus $offset
                $new_pos = $this->_objectSize + $offset;
                break;
            case SEEK_SET:
            default:
                // Set position equal to $offset
                $new_pos = $offset;
                break;
        }
        $ret = ($new_pos >= 0 && $new_pos <= $this->_objectSize);
        if ($ret) {
            $this->_position = $new_pos;
        }
        return $ret;
    }

    /**
     * Flush current cached stream data to storage
     *
     * @return boolean
     */
    public function stream_flush()
    {
        // If the stream wasn't opened for writing, just return false
        if (!$this->_writeBuffer) {
            return false;
        }

        $ret = $this->_s3->putObject($this->_objectName, $this->_objectBuffer);

        $this->_objectBuffer = null;

        return $ret;
    }

    /**
     * Returns data array of stream variables
     *
     * @return array
     */
    public function stream_stat()
    {
        if (!$this->_objectName) {
            return false;
        }

        $stat = array();
        $stat['dev'] = 0;
        $stat['ino'] = 0;
        $stat['mode'] = 0777;
        $stat['nlink'] = 0;
        $stat['uid'] = 0;
        $stat['gid'] = 0;
        $stat['rdev'] = 0;
        $stat['size'] = 0;
        $stat['atime'] = 0;
        $stat['mtime'] = 0;
        $stat['ctime'] = 0;
        $stat['blksize'] = 0;
        $stat['blocks'] = 0;

    if(($slash = strchr($this->_objectName, '/')) === false || $slash == strlen($this->_objectName)-1) {
        /* bucket */
        $stat['mode'] |= 040000;
    } else {
        $stat['mode'] |= 0100000;
    }
           $info = $this->_s3->getInfo($this->_objectName);
        if (!empty($info)) {
            $stat['size']  = $info['size'];
            $stat['atime'] = time();
            $stat['mtime'] = $info['mtime'];
        }

        return $stat;
    }

    /**
     * Attempt to delete the item
     *
     * @param  string $path
     * @return boolean
     */
    public function unlink($path)
    {
        return $this->_getS3Client($path)->removeObject($this->_getNamePart($path));
    }

    /**
     * Attempt to rename the item
     *
     * @param  string  $path_from
     * @param  string  $path_to
     * @return boolean False
     */
    public function rename($path_from, $path_to)
    {
        // TODO: Renaming isn't supported, always return false
        return false;
    }

    /**
     * Create a new directory
     *
     * @param  string  $path
     * @param  integer $mode
     * @param  integer $options
     * @return boolean
     */
    public function mkdir($path, $mode, $options)
    {
        return $this->_getS3Client($path)->createBucket(parse_url($path, PHP_URL_HOST));
    }

    /**
     * Remove a directory
     *
     * @param  string  $path
     * @param  integer $options
     * @return boolean
     */
    public function rmdir($path, $options)
    {
        return $this->_getS3Client($path)->removeBucket(parse_url($path, PHP_URL_HOST));
    }

    /**
     * Attempt to open a directory
     *
     * @param  string $path
     * @param  integer $options
     * @return boolean
     */
    public function dir_opendir($path, $options)
    {

        if (preg_match('@^([a-z0-9+.]|-)+://$@', $path)) {
            $this->_bucketList = $this->_getS3Client($path)->getBuckets();
        }
        else {
            $host = parse_url($path, PHP_URL_HOST);
            $this->_bucketList = $this->_getS3Client($path)->getObjectsByBucket($host);
        }

        return ($this->_bucketList !== false);
    }

    /**
     * Return array of URL variables
     *
     * @param  string $path
     * @param  integer $flags
     * @return array
     */
    public function url_stat($path, $flags)
    {
        $stat = array();
        $stat['dev'] = 0;
        $stat['ino'] = 0;
        $stat['mode'] = 0777;
        $stat['nlink'] = 0;
        $stat['uid'] = 0;
        $stat['gid'] = 0;
        $stat['rdev'] = 0;
        $stat['size'] = 0;
        $stat['atime'] = 0;
        $stat['mtime'] = 0;
        $stat['ctime'] = 0;
        $stat['blksize'] = 0;
        $stat['blocks'] = 0;

    $name = $this->_getNamePart($path);
    if(($slash = strchr($name, '/')) === false || $slash == strlen($name)-1) {
        /* bucket */
        $stat['mode'] |= 040000;
    } else {
        $stat['mode'] |= 0100000;
    }
           $info = $this->_getS3Client($path)->getInfo($name);

        if (!empty($info)) {
            $stat['size']  = $info['size'];
            $stat['atime'] = time();
            $stat['mtime'] = $info['mtime'];
        }

        return $stat;
    }

    /**
     * Return the next filename in the directory
     *
     * @return string
     */
    public function dir_readdir()
    {
        $object = current($this->_bucketList);
        if ($object !== false) {
            next($this->_bucketList);
        }
        return $object;
    }

    /**
     * Reset the directory pointer
     *
     * @return boolean True
     */
    public function dir_rewinddir()
    {
        reset($this->_bucketList);
        return true;
    }

    /**
     * Close a directory
     *
     * @return boolean True
     */
    public function dir_closedir()
    {
        $this->_bucketList = array();
        return true;
    }
}


text:
<?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
 * @subpackage Amazon_S3
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * Zend_Service_Amazon_Exception
 */
require_once 'Zend/Service/Amazon/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_S3_Exception extends Zend_Service_Amazon_Exception
{}


text:
<?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
 * @subpackage Amazon_Sqs
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * Zend_Service_Amazon/Exception
 */
require_once 'Zend/Service/Amazon/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon_Sqs
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Sqs_Exception extends Zend_Service_Amazon_Exception
{}


text:
<?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 Authentication
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Service_Amazon_Exception
 */
require_once 'Zend/Service/Amazon/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Authentication
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Authentication_Exception extends Zend_Service_Amazon_Exception
{

}


text:
<?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 Authentication
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Service_Amazon_Authentication
 */
require_once 'Zend/Service/Amazon/Authentication.php';

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

/**
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Authentication
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Authentication_V1 extends Zend_Service_Amazon_Authentication
{
    /**
     * Signature Version
     */
    protected $_signatureVersion = '1';

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

    /**
     * Generate the required attributes for the signature
     * @param string $url
     * @param array $parameters
     * @return string
     */
    public function generateSignature($url, array &$parameters)
    {
        $parameters['AWSAccessKeyId']   = $this->_accessKey;
        $parameters['SignatureVersion'] = $this->_signatureVersion;
        $parameters['Version']          = $this->_apiVersion;
        if(!isset($parameters['Timestamp'])) {
            $parameters['Timestamp']    = gmdate('Y-m-d\TH:i:s\Z', time()+10);
        }

        $data = $this->_signParameters($url, $parameters);

        return $data;
    }

    /**
     * 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  string $queue_url  Queue URL
     * @param  array  $parameters the parameters for which to get the signature.
     *
     * @return string the signed data.
     */
    protected function _signParameters($url, array &$paramaters)
    {
        $data = '';

        uksort($paramaters, 'strcasecmp');
        unset($paramaters['Signature']);

        foreach($paramaters as $key => $value) {
            $data .= $key . $value;
        }

        $hmac = Zend_Crypt_Hmac::compute($this->_secretKey, 'SHA1', $data, Zend_Crypt_Hmac::BINARY);

        $paramaters['Signature'] = base64_encode($hmac);

        return $data;
    }
}


text:
<?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 Authentication
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Service_Amazon_Authentication
 */
require_once 'Zend/Service/Amazon/Authentication.php';

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

/**
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Authentication
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Authentication_V2 extends Zend_Service_Amazon_Authentication
{
    /**
     * Signature Version
     */
    protected $_signatureVersion = '2';

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

    /**
     * Type of http request
     * @var string
     */
    protected $_httpMethod = "POST";

    /**
     * Generate the required attributes for the signature
     * @param string $url
     * @param array $parameters
     * @return string
     */
    public function generateSignature($url, array &$parameters)
    {
        $parameters['AWSAccessKeyId']   = $this->_accessKey;
        $parameters['SignatureVersion'] = $this->_signatureVersion;
        $parameters['Version']          = $this->_apiVersion;
        $parameters['SignatureMethod']  = $this->_signatureMethod;
        if(!isset($parameters['Timestamp'])) {
            $parameters['Timestamp']    = gmdate('Y-m-d\TH:i:s\Z', time()+10);
        }

        $data = $this->_signParameters($url, $parameters);

        return $data;
    }

    /**
     * Set http request type to POST or GET
     * @param string $method
     */
    public function setHttpMethod($method = "POST") {
        $this->_httpMethod = strtoupper($method);
    }

    /**
     * Get the current http request type
     * @return string
     */
    public function getHttpMethod()
    {
        return $this->_httpMethod;
    }

    /**
     * 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  string $queue_url  Queue URL
     * @param  array  $parameters the parameters for which to get the signature.
     *
     * @return string the signed data.
     */
    protected function _signParameters($url, array &$paramaters)
    {
        $data = $this->_httpMethod . "\n";
        $data .= parse_url($url, PHP_URL_HOST) . "\n";
        $data .= ('' == $path = parse_url($url, PHP_URL_PATH)) ? '/' : $path;
        $data .= "\n";

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

        $arrData = array();
        foreach($paramaters as $key => $value) {
            $arrData[] = $key . '=' . str_replace('%7E', '~', rawurlencode($value));
        }

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

        $hmac = Zend_Crypt_Hmac::compute($this->_secretKey, 'SHA256', $data, Zend_Crypt_Hmac::BINARY);

        $paramaters['Signature'] = base64_encode($hmac);

        return $data;
    }
}


text:
<?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 Authentication
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Service_Amazon_Authentication
 */
require_once 'Zend/Service/Amazon/Authentication.php';

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

/**
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage Authentication
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Authentication_S3 extends Zend_Service_Amazon_Authentication
{
    /**
     * Add the S3 Authorization signature to the request headers
     *
     * @param  string $method
     * @param  string $path
     * @param  array &$headers
     * @return string
     */
    public function generateSignature($method, $path, &$headers)
    {
        if (! is_array($headers)) {
            $headers = array($headers);
        }

        $type = $md5 = $date = '';

        // Search for the Content-type, Content-MD5 and Date headers
        foreach ($headers as $key => $val) {
            if (strcasecmp($key, 'content-type') == 0) {
                $type = $val;
            } else if (strcasecmp($key, 'content-md5') == 0) {
                $md5 = $val;
            } else if (strcasecmp($key, 'date') == 0) {
                $date = $val;
            }
        }

        // If we have an x-amz-date header, use that instead of the normal Date
        if (isset($headers['x-amz-date']) && isset($date)) {
            $date = '';
        }

        $sig_str = "$method\n$md5\n$type\n$date\n";

        // For x-amz- headers, combine like keys, lowercase them, sort them
        // alphabetically and remove excess spaces around values
        $amz_headers = array();
        foreach ($headers as $key => $val) {
            $key = strtolower($key);
            if (substr($key, 0, 6) == 'x-amz-') {
                if (is_array($val)) {
                    $amz_headers[$key] = $val;
                } else {
                    $amz_headers[$key][] = preg_replace('/\s+/', ' ', $val);
                }
            }
        }
        if (!empty($amz_headers)) {
            ksort($amz_headers);
            foreach ($amz_headers as $key => $val) {
                $sig_str .= $key . ':' . implode(',', $val) . "\n";
            }
        }

        $sig_str .= '/'.parse_url($path, PHP_URL_PATH);
        if (strpos($path, '?location') !== false) {
            $sig_str .= '?location';
        } else
            if (strpos($path, '?acl') !== false) {
                $sig_str .= '?acl';
            } else
                if (strpos($path, '?torrent') !== false) {
                    $sig_str .= '?torrent';
                }

        $signature = base64_encode(Zend_Crypt_Hmac::compute($this->_secretKey, 'sha1', utf8_encode($sig_str), Zend_Crypt_Hmac::BINARY));
        $headers['Authorization'] = 'AWS ' . $this->_accessKey . ':' . $signature;

        return $sig_str;
    }
}


text:
<?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-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Response.php 17539 2009-08-10 22:51:26Z mikaelkael $
 */

/**
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage SimpleDb
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_SimpleDb_Attribute
{
    protected $_itemName;
    protected $_name;
    protected $_values;

    /**
     * Constructor
     *
     * @param  string $itemName
     * @param  string $name
     * @param  array $values
     * @return void
     */
    function __construct($itemName, $name, $values)
    {
        $this->_itemName = $itemName;
        $this->_name     = $name;

        if (!is_array($values)) {
            $this->_values = array($values);
        } else {
            $this->_values = $values;
        }
    }

    /**
     * Return the item name to which the attribute belongs
     *
     * @return string
     */
    public function getItemName ()
    {
        return $this->_itemName;
    }

    /**
     * Retrieve attribute values
     *
     * @return array
     */
    public function getValues()
    {
        return $this->_values;
    }

    /**
     * Retrieve the attribute name
     *
     * @return string
     */
    public function getName ()
    {
        return $this->_name;
    }

    /**
     * Add value
     *
     * @param  mixed $value
     * @return void
     */
    public function addValue($value)
    {
        if (is_array($value)) {
             $this->_values += $value;
        } else {
            $this->_values[] = $value;
        }
    }

    public function setValues($values)
    {
        if (!is_array($values)) {
            $values = array($values);
        }
        $this->_values = $values;
    }
}


text:
<?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-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Service_Amazon_Exception
 */
require_once 'Zend/Service/Amazon/Exception.php';

/**
 * The Custom Exception class that allows you to have access to the AWS Error Code.
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage SimpleDb
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_SimpleDb_Page
{
    /** @var string Page data */
    protected $_data;

    /** @var string|null Token identifying page */
    protected $_token;

    /**
     * Constructor
     *
     * @param  string $data
     * @param  string|null $token
     * @return void
     */
    public function __construct($data, $token = null)
    {
        $this->_data  = $data;
        $this->_token = $token;
    }

    /**
     * Retrieve page data
     *
     * @return string
     */
    public function getData()
    {
        return $this->_data;
    }

    /**
     * Retrieve token
     *
     * @return string|null
     */
    public function getToken()
    {
        return $this->_token;
    }

    /**
     * Determine whether this is the last page of data
     *
     * @return void
     */
    public function isLast()
    {
        return (null === $this->_token);
    }

    /**
     * Cast to string
     *
     * @return string
     */
    public function __toString()
    {
        return "Page with token: " . $this->_token
             . "\n and data: " . $this->_data;
    }
}


text:
<?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-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Service_Amazon_Exception
 */
require_once 'Zend/Service/Amazon/Exception.php';

/**
 * The Custom Exception class that allows you to have access to the AWS Error Code.
 *
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage SimpleDb
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_SimpleDb_Exception extends Zend_Service_Amazon_Exception
{
    /**
     * @var string
     */
    private $_awsErrorCode = '';

    /**
     * Constructor
     *
     * @param string $message
     * @param int $code
     * @param string $awsErrorCode
     * @return void
     */
    public function __construct($message, $code = 0, $awsErrorCode = '')
    {
        parent::__construct($message, $code);
        $this->_awsErrorCode = $awsErrorCode;
    }

    /**
     * Get AWS error code
     *
     * @return string
     */
    public function getErrorCode()
    {
        return $this->_awsErrorCode;
    }
}


text:
<?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-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Http_Response
 */
require_once 'Zend/Http/Response.php';

/**
 * @category   Zend
 * @package    Zend_Service_Amazon
 * @subpackage SimpleDb
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_SimpleDb_Response
{
    /**
     * XML namespace used for SimpleDB responses.
     */
    protected $_xmlNamespace = 'http://sdb.amazonaws.com/doc/2009-04-15/';

    /**
     * The original HTTP response
     *
     * This contains the response body and headers.
     *
     * @var Zend_Http_Response
     */
    private $_httpResponse = null;

    /**
     * The response document object
     *
     * @var DOMDocument
     */
    private $_document = null;

    /**
     * The response XPath
     *
     * @var DOMXPath
     */
    private $_xpath = null;

    /**
     * Last error code
     *
     * @var integer
     */
    private $_errorCode = 0;

    /**
     * Last error message
     *
     * @var string
     */
    private $_errorMessage = '';

    /**
     * Creates a new high-level SimpleDB response object
     *
     * @param  Zend_Http_Response $httpResponse the HTTP response.
     * @return void
     */
    public function __construct(Zend_Http_Response $httpResponse)
    {
        $this->_httpResponse = $httpResponse;
    }

    /**
     * Gets the XPath object for this response
     *
     * @return DOMXPath the XPath object for response.
     */
    public function getXPath()
    {
        if ($this->_xpath === null) {
            $document = $this->getDocument();
            if ($document === false) {
                $this->_xpath = false;
            } else {
                $this->_xpath = new DOMXPath($document);
                $this->_xpath->registerNamespace('sdb',
                    $this->getNamespace());
            }
        }

        return $this->_xpath;
    }

    /**
     * Gets the SimpleXML document object for this response
     *
     * @return SimpleXMLElement
     */
    public function getSimpleXMLDocument()
    {
        try {
            $body = $this->_httpResponse->getBody();
        } catch (Zend_Http_Exception $e) {
            $body = false;
        }

        return simplexml_load_string($body);
    }

    /**
     * Get HTTP response object
     *
     * @return Zend_Http_Response
     */
    public function getHttpResponse()
    {
        return $this->_httpResponse;
    }

    /**
     * Gets the document object for this response
     *
     * @return DOMDocument the DOM Document for this response.
     */
    public function getDocument()
    {
        try {
            $body = $this->_httpResponse->getBody();
        } catch (Zend_Http_Exception $e) {
            $body = false;
        }

        if ($this->_document === null) {
            if ($body !== false) {
                // turn off libxml error handling
                $errors = libxml_use_internal_errors();

                $this->_document = new DOMDocument();
                if (!$this->_document->loadXML($body)) {
                    $this->_document = false;
                }

                // reset libxml error handling
                libxml_clear_errors();
                libxml_use_internal_errors($errors);
            } else {
                $this->_document = false;
            }
        }

        return $this->_document;
    }

    /**
     * Return the current set XML Namespace.
     *
     * @return string
     */
    public function getNamespace()
    {
        return $this->_xmlNamespace;
    }

    /**
     * Set a new XML Namespace
     *
     * @param string $namespace
     */
    public function setNamespace($namespace)
    {
        $this->_xmlNamespace = $namespace;
    }
}


text:
<?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
 * @subpackage Twitter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Service_Exception
 */
require_once 'Zend/Service/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Twitter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Twitter_Exception extends Zend_Service_Exception
{
}


text:
<?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
 * @subpackage Twitter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Search.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Http_Client
 */
require_once 'Zend/Rest/Client.php';

/**
 * @see Zend_Json
 */
require_once 'Zend/Json.php';

/**
 * @see Zend_Feed
 */
require_once 'Zend/Feed.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Twitter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

class Zend_Service_Twitter_Search extends Zend_Rest_Client
{
    /**
     * Return Type
     * @var String
     */
    protected $_responseType = 'json';

    /**
     * Response Format Types
     * @var array
     */
    protected $_responseTypes = array(
        'atom',
        'json'
    );

    /**
     * Uri Compoent
     *
     * @var Zend_Uri_Http
     */
    protected $_uri;

    /**
     * Constructor
     *
     * @param  string $returnType
     * @return void
     */
    public function __construct($responseType = 'json')
    {
        $this->setResponseType($responseType);
        $this->setUri("http://search.twitter.com");

        $this->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8');
    }

    /**
     * set responseType
     *
     * @param string $responseType
     * @throws Zend_Service_Twitter_Exception
     * @return Zend_Service_Twitter_Search
     */
    public function setResponseType($responseType = 'json')
    {
        if(!in_array($responseType, $this->_responseTypes, TRUE)) {
            require_once 'Zend/Service/Twitter/Exception.php';
            throw new Zend_Service_Twitter_Exception('Invalid Response Type');
        }
        $this->_responseType = $responseType;
        return $this;
    }

    /**
     * Retrieve responseType
     *
     * @return string
     */
    public function getResponseType()
    {
        return $this->_responseType;
    }

    /**
     * Get the current twitter trends.  Currnetly only supports json as the return.
     *
     * @throws Zend_Http_Client_Exception
     * @return array
     */
    public function trends()
    {
        $response     = $this->restGet('/trends.json');

        return Zend_Json::decode($response->getBody());
    }

    /**
     * Performs a Twitter search query.
     *
     * @throws Zend_Http_Client_Exception
     */
    public function search($query, array $params = array())
    {

        $_query = array();

        $_query['q'] = $query;

        foreach($params as $key=>$param) {
            switch($key) {
                case 'geocode':
                case 'lang':
                case 'since_id':
                    $_query[$key] = $param;
                    break;
                case 'rpp':
                    $_query[$key] = (intval($param) > 100) ? 100 : intval($param);
                    break;
                case 'page':
                    $_query[$key] = intval($param);
                    break;
                case 'show_user':
                    $_query[$key] = 'true';
            }
        }

        $response = $this->restGet('/search.' . $this->_responseType, $_query);

        switch($this->_responseType) {
            case 'json':
                return Zend_Json::decode($response->getBody());
                break;
            case 'atom':
                return Zend_Feed::importString($response->getBody());
                break;
        }

        return ;
    }
}