Current File : /home/k/a/r/karenpetzb/www/items/category/Service.tar
Akismet.php000060400000023761150715514360006666 0ustar00<?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 Akismet
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Akismet.php 8502 2008-03-01 19:56:46Z weppos $
 */


/**
 * @see Zend_Version
 */
require_once 'Zend/Version.php';

/**   
 * @see Zend_Service_Abstract
 */
require_once 'Zend/Service/Abstract.php';


/**
 * Akismet REST service implementation
 *
 * @uses       Zend_Service_Abstract
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Akismet
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Akismet extends Zend_Service_Abstract
{
    /**
     * Akismet API key
     * @var string
     */
    protected $_apiKey;

    /**
     * Blog URL
     * @var string
     */
    protected $_blogUrl;

    /**
     * Charset used for encoding
     * @var string
     */
    protected $_charset = 'UTF-8';

    /**
     * TCP/IP port to use in requests
     * @var int
     */
    protected $_port = 80;

    /**
     * User Agent string to send in requests
     * @var string
     */
    protected $_userAgent;

    /**
     * Constructor
     *
     * @param string $apiKey Akismet API key
     * @param string $blog Blog URL
     * @return void
     */
    public function __construct($apiKey, $blog)
    {
        $this->setBlogUrl($blog)
             ->setApiKey($apiKey)
             ->setUserAgent('Zend Framework/' . Zend_Version::VERSION . ' | Akismet/1.11');
    }

    /**
     * Retrieve blog URL
     *
     * @return string
     */
    public function getBlogUrl()
    {
        return $this->_blogUrl;
    }

    /**
     * Set blog URL
     *
     * @param string $blogUrl
     * @return Zend_Service_Akismet
     * @throws Zend_Service_Exception if invalid URL provided
     */
    public function setBlogUrl($blogUrl)
    {
        require_once 'Zend/Uri.php';
        if (!Zend_Uri::check($blogUrl)) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid url provided for blog');
        }

        $this->_blogUrl = $blogUrl;
        return $this;
    }

    /**
     * Retrieve API key
     *
     * @return string
     */
    public function getApiKey()
    {
        return $this->_apiKey;
    }

    /**
     * Set API key
     *
     * @param string $apiKey
     * @return Zend_Service_Akismet
     */
    public function setApiKey($apiKey)
    {
        $this->_apiKey = $apiKey;
        return $this;
    }

    /**
     * Retrieve charset
     *
     * @return string
     */
    public function getCharset()
    {
        return $this->_charset;
    }

    /**
     * Set charset
     *
     * @param string $charset
     * @return Zend_Service_Akismet
     */
    public function setCharset($charset)
    {
        $this->_charset = $charset;
        return $this;
    }

    /**
     * Retrieve TCP/IP port
     *
     * @return int
     */
    public function getPort()
    {
        return $this->_port;
    }

    /**
     * Set TCP/IP port
     *
     * @param int $port
     * @return Zend_Service_Akismet
     * @throws Zend_Service_Exception if non-integer value provided
     */
    public function setPort($port)
    {
        if (!is_int($port)) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid port');
        }

        $this->_port = $port;
        return $this;
    }

    /**
     * Retrieve User Agent string
     *
     * @return string
     */
    public function getUserAgent()
    {
        return $this->_userAgent;
    }

    /**
     * Set User Agent
     *
     * Should be of form "Some user agent/version | Akismet/version"
     *
     * @param string $userAgent
     * @return Zend_Service_Akismet
     * @throws Zend_Service_Exception with invalid user agent string
     */
    public function setUserAgent($userAgent)
    {
        if (!is_string($userAgent)
            || !preg_match(":^[^\n/]*/[^ ]* \| Akismet/[0-9\.]*$:i", $userAgent))
        {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid User Agent string; must be of format "Application name/version | Akismet/version"');
        }

        $this->_userAgent = $userAgent;
        return $this;
    }

    /**
     * Post a request
     *
     * @param string $host
     * @param string $path
     * @param array  $params
     * @return mixed
     */
    protected function _post($host, $path, array $params)
    {
        $uri    = 'http://' . $host . ':' . $this->getPort() . $path;
        $client = self::getHttpClient();
        $client->setUri($uri);
        $client->setConfig(array(
            'useragent'    => $this->getUserAgent(),
        ));

        $client->setHeaders(array(
            'Host'         => $host,
            'Content-Type' => 'application/x-www-form-urlencoded; charset=' . $this->getCharset()
        ));
        $client->setParameterPost($params);

        $client->setMethod(Zend_Http_Client::POST);
        return $client->request();
    }

    /**
     * Verify an API key
     *
     * @param string $key Optional; API key to verify
     * @param string $blog Optional; blog URL against which to verify key
     * @return boolean
     */
    public function verifyKey($key = null, $blog = null)
    {
        if (null === $key) {
            $key = $this->getApiKey();
        }

        if (null === $blog) {
            $blog = $this->getBlogUrl();
        }

        $response = $this->_post('rest.akismet.com', '/1.1/verify-key', array(
            'key'  => $key,
            'blog' => $blog
        ));

        return ('valid' == $response->getBody());
    }

    /**
     * Perform an API call
     *
     * @param string $path
     * @param array $params
     * @return Zend_Http_Response
     * @throws Zend_Service_Exception if missing user_ip or user_agent fields
     */
    protected function _makeApiCall($path, $params)
    {
        if (empty($params['user_ip']) || empty($params['user_agent'])) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Missing required Akismet fields (user_ip and user_agent are required)');
        }

        if (!isset($params['blog'])) {
            $params['blog'] = $this->getBlogUrl();
        }

        return $this->_post($this->getApiKey() . '.rest.akismet.com', $path, $params);
    }

    /**
     * Check a comment for spam
     *
     * Checks a comment to see if it is spam. $params should be an associative
     * array with one or more of the following keys (unless noted, all keys are
     * optional):
     * - blog: URL of the blog. If not provided, uses value returned by {@link getBlogUrl()}
     * - user_ip (required): IP address of comment submitter
     * - user_agent (required): User Agent used by comment submitter
     * - referrer: contents of HTTP_REFERER header
     * - permalink: location of the entry to which the comment was submitted
     * - comment_type: typically, one of 'blank', 'comment', 'trackback', or 'pingback', but may be any value
     * - comment_author: name submitted with the content
     * - comment_author_email: email submitted with the content
     * - comment_author_url: URL submitted with the content
     * - comment_content: actual content
     *
     * Additionally, Akismet suggests returning the key/value pairs in the
     * $_SERVER array, and these may be included in the $params.
     *
     * This method implements the Akismet comment-check REST method.
     *
     * @param array $params
     * @return boolean
     * @throws Zend_Service_Exception with invalid API key
     */
    public function isSpam($params)
    {
        $response = $this->_makeApiCall('/1.1/comment-check', $params);

        $return = trim($response->getBody());

        if ('invalid' == $return) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid API key');
        }

        if ('true' == $return) {
            return true;
        }

        return false;
    }

    /**
     * Submit spam
     *
     * Takes the same arguments as {@link isSpam()}.
     *
     * Submits known spam content to Akismet to help train it.
     *
     * This method implements Akismet's submit-spam REST method.
     *
     * @param array $params
     * @return void
     * @throws Zend_Service_Exception with invalid API key
     */
    public function submitSpam($params)
    {
        $response = $this->_makeApiCall('/1.1/submit-spam', $params);
        $value    = trim($response->getBody());
        if ('invalid' == $value) {
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Invalid API key');
        }
    }

    /**
     * Submit ham
     *
     * Takes the same arguments as {@link isSpam()}.
     *
     * Submits a comment that has been falsely categorized as spam by Akismet
     * as a false positive, telling Akismet's filters not to filter such
     * comments as spam in the future.
     *
     * Unlike {@link submitSpam()} and {@link isSpam()}, a valid API key is
     * never necessary; as a result, this method never throws an exception
     * (unless an exception happens with the HTTP client layer).
     *
     * this method implements Akismet's submit-ham REST method.
     *
     * @param array $params
     * @return void
     */
    public function submitHam($params)
    {
        $response = $this->_makeApiCall('/1.1/submit-ham', $params);
    }
}
SlideShare/SlideShow.php000060400000024001150715514360011201 0ustar00<?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 SlideShare
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SlideShow.php 9094 2008-03-30 18:36:55Z thomas $
 */


/**
 * The Zend_Service_SlideShare_SlideShow class represents a slide show on the
 * slideshare.net servers.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage SlideShare
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_SlideShare_SlideShow
{

    /**
     * Status constant mapping for web service
     *
     */
    const STATUS_QUEUED = 0;
    const STATUS_PROCESSING = 1;
    const STATUS_READY = 2;
    const STATUS_FAILED = 3;

    /**
     * The HTML code to embed the slide show in a web page
     *
     * @var string the HTML to embed the slide show
     */
    protected $_embedCode;

    /**
     * The URI for the thumbnail representation of the slide show
     *
     * @var string The URI of a thumbnail image
     */
    protected $_thumbnailUrl;

    /**
     * The title of the slide show
     *
     * @var string The slide show title
     */
    protected $_title;

    /**
     * The Description of the slide show
     *
     * @var string The slide show description
     */
    protected $_description;

    /**
     * The status of the silde show on the server
     *
     * @var int The Slide show status code
     */
    protected $_status;

    /**
     * The Description of the slide show status code
     *
     * @var string The status description
     */
    protected $_statusDescription;

    /**
     * The Permanent link for the slide show
     *
     * @var string the Permalink for the slide show
     */
    protected $_permalink;

    /**
     * The number of views this slide show has received
     *
     * @var int the number of views
     */
    protected $_numViews;

    /**
     * The ID of the slide show on the server
     *
     * @var int the Slide show ID number on the server
     */
    protected $_slideShowId;

    /**
     * A slide show filename on the local filesystem (when uploading)
     *
     * @var string the local filesystem path & file of the slide show to upload
     */
    protected $_slideShowFilename;

    /**
     * An array of tags associated with the slide show
     *
     * @var array An array of tags associated with the slide show
     */
    protected $_tags = array();

    /**
     * The location of the slide show
     *
     * @var string the Location
     */
    protected $_location;

    /**
     * The transcript associated with the slide show
     *
     * @var string the Transscript
     */
    protected $_transcript;


    /**
     * Retrieves the location of the slide show
     *
     * @return string the Location
     */
    public function getLocation()
    {
        return $this->_location;
    }

    /**
     * Sets the location of the slide show
     *
     * @param string $loc The location to use
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setLocation($loc)
    {
        $this->_location = (string)$loc;
        return $this;
    }

    /**
     * Gets the transcript for this slide show
     *
     * @return string the Transcript
     */
    public function getTranscript()
    {
        return $this->_transcript;
    }

    /**
     * Sets the transcript for this slide show
     *
     * @param string $t The transcript
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setTranscript($t)
    {
        $this->_transcript = (string)$t;
        return $this;
    }

    /**
     * Adds a tag to the slide show
     *
     * @param string $tag The tag to add
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function addTag($tag)
    {
        $this->_tags[] = (string)$tag;
        return $this;
    }

    /**
     * Sets the tags for the slide show
     *
     * @param array $tags An array of tags to set
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setTags(Array $tags)
    {
        $this->_tags = $tags;
        return $this;
    }

    /**
     * Gets all of the tags associated with the slide show
     *
     * @return array An array of tags for the slide show
     */
    public function getTags()
    {
        return $this->_tags;
    }

    /**
     * Sets the filename on the local filesystem of the slide show
     * (for uploading a new slide show)
     *
     * @param string $file The full path & filename to the slide show
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setFilename($file)
    {
        $this->_slideShowFilename = (string)$file;
        return $this;
    }

    /**
     * Retrieves the filename on the local filesystem of the slide show
     * which will be uploaded
     *
     * @return string The full path & filename to the slide show
     */
    public function getFilename()
    {
        return $this->_slideShowFilename;
    }

    /**
     * Sets the ID for the slide show
     *
     * @param int $id The slide show ID
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setId($id)
    {
        $this->_slideShowId = (string)$id;
        return $this;
    }

    /**
     * Gets the ID for the slide show
     *
     * @return int The slide show ID
     */
    public function getId()
    {
        return $this->_slideShowId;
    }

    /**
     * Sets the HTML embed code for the slide show
     *
     * @param string $code The HTML embed code
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setEmbedCode($code)
    {
        $this->_embedCode = (string)$code;
        return $this;
    }

    /**
     * Retrieves the HTML embed code for the slide show
     *
     * @return string the HTML embed code
     */
    public function getEmbedCode()
    {
        return $this->_embedCode;
    }

    /**
     * Sets the Thumbnail URI for the slide show
     *
     * @param string $url The URI for the thumbnail image
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setThumbnailUrl($url)
    {
        $this->_thumbnailUrl = (string) $url;
        return $this;
    }

    /**
     * Retrieves the Thumbnail URi for the slide show
     *
     * @return string The URI for the thumbnail image
     */
    public function getThumbnailUrl()
    {
        return $this->_thumbnailUrl;
    }

    /**
     * Sets the title for the Slide show
     *
     * @param string $title The slide show title
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setTitle($title)
    {
        $this->_title = (string)$title;
        return $this;
    }

    /**
     * Retrieves the Slide show title
     *
     * @return string the Slide show title
     */
    public function getTitle()
    {
        return $this->_title;
    }

    /**
     * Sets the description for the Slide show
     *
     * @param strign $desc The description of the slide show
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setDescription($desc)
    {
        $this->_description = (string)$desc;
        return $this;
    }

    /**
     * Gets the description of the slide show
     *
     * @return string The slide show description
     */
    public function getDescription()
    {
        return $this->_description;
    }

    /**
     * Sets the numeric status of the slide show on the server
     *
     * @param int $status The numeric status on the server
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setStatus($status)
    {
        $this->_status = (int)$status;
        return $this;
    }

    /**
     * Gets the numeric status of the slide show on the server
     *
     * @return int A Zend_Service_SlideShare_SlideShow Status constant
     */
    public function getStatus()
    {
        return $this->_status;
    }

    /**
     * Sets the textual description of the status of the slide show on the server
     *
     * @param string $desc The textual description of the status of the slide show
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setStatusDescription($desc)
    {
        $this->_statusDescription = (string)$desc;
        return $this;
    }

    /**
     * Gets the textual description of the status of the slide show on the server
     *
     * @return string the textual description of the service
     */
    public function getStatusDescription()
    {
        return $this->_statusDescription;
    }

    /**
     * Sets the permanent link of the slide show
     *
     * @param string $url The permanent URL for the slide show
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setPermaLink($url)
    {
        $this->_permalink = (string)$url;
        return $this;
    }

    /**
     * Gets the permanent link of the slide show
     *
     * @return string the permanent URL for the slide show
     */
    public function getPermaLink()
    {
        return $this->_permalink;
    }

    /**
     * Sets the number of views the slide show has received
     *
     * @param int $views The number of views
     * @return Zend_Service_SlideShare_SlideShow
     */
    public function setNumViews($views)
    {
        $this->_numViews = (int)$views;
        return $this;
    }

    /**
     * Gets the number of views the slide show has received
     *
     * @return int The number of views
     */
    public function getNumViews()
    {
        return $this->_numViews;
    }
}SlideShare/Exception.php000060400000002205150715514360011240 0ustar00<?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 SlideShare
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * @see Zend_Exception
 */
require_once 'Zend/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage SlideShare
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_SlideShare_Exception extends Zend_Exception
{
}Delicious/PostList.php000060400000016223150715514360010765 0ustar00<?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 Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: PostList.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * List of posts retrived from the del.icio.us web service
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Delicious_PostList implements Countable, Iterator, ArrayAccess
{
    /**
     * @var array Array of Zend_Service_Delicious_Post
     */
    protected $_posts = array();

    /**
     * @var Zend_Service_Delicious Service that has downloaded the post list
     */
    protected $_service;

    /**
     * @var int Iterator key
     */
    protected $_iteratorKey = 0;

    /**
     * @param  Zend_Service_Delicious $service Service that has downloaded the post
     * @param  DOMNodeList|array      $posts
     * @return void
     */
    public function __construct(Zend_Service_Delicious $service, $posts = null)
    {
        $this->_service = $service;
        if ($posts instanceof DOMNodeList) {
            $this->_constructFromNodeList($posts);
        } else if (is_array($posts)) {
            $this->_constructFromArray($posts);
        }
    }

    /**
     * Transforms DOMNodeList to array of posts
     *
     * @param  DOMNodeList $nodeList
     * @return void
     */
    private function _constructFromNodeList(DOMNodeList $nodeList)
    {
        for ($i = 0; $i < $nodeList->length; $i++) {
            $curentNode = $nodeList->item($i);
            if($curentNode->nodeName == 'post') {
                $this->_addPost(new Zend_Service_Delicious_Post($this->_service, $curentNode));
            }
        }
    }

    /**
     * Transforms the Array to array of posts
     *
     * @param  array $postList
     * @return void
     */
    private function _constructFromArray(array $postList)
    {
        foreach ($postList as $f_post) {
            $this->_addPost(new Zend_Service_Delicious_SimplePost($f_post));
        }
    }

    /**
     * Add a post
     *
     * @param  Zend_Service_Delicious_SimplePost $post
     * @return Zend_Service_Delicious_PostList
     */
    protected function _addPost(Zend_Service_Delicious_SimplePost $post)
    {
        $this->_posts[] = $post;

        return $this;
    }

    /**
     * Filter list by list of tags
     *
     * @param  array $tags
     * @return Zend_Service_Delicious_PostList
     */
    public function withTags(array $tags)
    {
        $postList = new self($this->_service);

        foreach ($this->_posts as $post) {
            if (count(array_diff($tags, $post->getTags())) == 0) {
                $postList->_addPost($post);
            }
        }

        return $postList;
    }

    /**
     * Filter list by tag
     *
     * @param  string $tag
     * @return Zend_Service_Delicious_PostList
     */
    public function withTag($tag)
    {
        return $this->withTags(func_get_args());
    }

    /**
     * Filter list by urls matching a regular expression
     *
     * @param  string $regexp
     * @return Zend_Service_Delicious_PostList
     */
    public function withUrl($regexp)
    {
        $postList = new self($this->_service);

        foreach ($this->_posts as $post) {
            if (preg_match($regexp, $post->getUrl())) {
                $postList->_addPost($post);
            }
        }

        return $postList;
    }

    /**
     * Return number of posts
     *
     * Implement Countable::count()
     *
     * @return int
     */
    public function count()
    {
        return count($this->_posts);
    }

    /**
     * Return the current element
     *
     * Implement Iterator::current()
     *
     * @return Zend_Service_Delicious_SimplePost
     */
    public function current()
    {
        return $this->_posts[$this->_iteratorKey];
    }

    /**
     * Return the key of the current element
     *
     * Implement Iterator::key()
     *
     * @return int
     */
    public function key()
    {
        return $this->_iteratorKey;
    }

    /**
     * Move forward to next element
     *
     * Implement Iterator::next()
     *
     * @return void
     */
    public function next()
    {
        $this->_iteratorKey += 1;
    }

    /**
     * Rewind the Iterator to the first element
     *
     * Implement Iterator::rewind()
     *
     * @return void
     */
    public function rewind()
    {
        $this->_iteratorKey = 0;
    }

    /**
     * Check if there is a current element after calls to rewind() or next()
     *
     * Implement Iterator::valid()
     *
     * @return bool
     */
    public function valid()
    {
        $numItems = $this->count();

        if ($numItems > 0 && $this->_iteratorKey < $numItems) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Whether the offset exists
     *
     * Implement ArrayAccess::offsetExists()
     *
     * @param   int     $offset
     * @return  bool
     */
    public function offsetExists($offset)
    {
        return ($offset < $this->count());
    }

    /**
     * Return value at given offset
     *
     * Implement ArrayAccess::offsetGet()
     *
     * @param   int     $offset
     * @throws  OutOfBoundsException
     * @return  Zend_Service_Delicious_SimplePost
     */
    public function offsetGet($offset)
    {
        if ($this->offsetExists($offset)) {
            return $this->_posts[$offset];
        } else {
            throw new OutOfBoundsException('Illegal index');
        }
    }

    /**
     * Throws exception because all values are read-only
     *
     * Implement ArrayAccess::offsetSet()
     *
     * @param   int     $offset
     * @param   string  $value
     * @throws  Zend_Service_Delicious_Exception
     */
    public function offsetSet($offset, $value)
    {
        /**
         * @see Zend_Service_Delicious_Exception
         */
        require_once 'Zend/Service/Delicious/Exception.php';
        throw new Zend_Service_Delicious_Exception('You are trying to set read-only property');
    }

    /**
     * Throws exception because all values are read-only
     *
     * Implement ArrayAccess::offsetUnset()
     *
     * @param   int     $offset
     * @throws  Zend_Service_Delicious_Exception
     */
    public function offsetUnset($offset)
    {
        /**
         * @see Zend_Service_Delicious_Exception
         */
        require_once 'Zend/Service/Delicious/Exception.php';
        throw new Zend_Service_Delicious_Exception('You are trying to unset read-only property');
    }
}
Delicious/Post.php000060400000015773150715514360010142 0ustar00<?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 Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Post.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Date
 */
require_once 'Zend/Date.php';

/**
 * @see Zend_Service_Delicious_SimplePost
 */
require_once 'Zend/Service/Delicious/SimplePost.php';


/**
 * Zend_Service_Delicious_Post represents a post of a user that can be edited
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Delicious_Post extends Zend_Service_Delicious_SimplePost
{
    /**
     * Service that has downloaded the post
     *
     * @var Zend_Service_Delicious
     */
    protected $_service;

    /**
     * @var int Number of people that have the same post
     */
    protected $_others;

    /**
     * @var Zend_Date Post date
     */
    protected $_date;

    /**
     * @var bool Post share
     */
    protected $_shared = true;

    /**
     * @var string Post hash
     */
    protected $_hash;

    /**
     * Constructs a new del.icio.us post
     *
     * @param  Zend_Service_Delicious $service Service that has downloaded the post
     * @param  DOMElement|array       $values  Post content
     * @throws Zend_Service_Delicious_Exception
     * @return void
     */
    public function __construct(Zend_Service_Delicious $service, $values)
    {
        $this->_service = $service;

        if ($values instanceof DOMElement) {
            $values = self::_parsePostNode($values);
        }

        if (!is_array($values) || !isset($values['url']) || !isset($values['title'])) {
            /**
             * @see Zend_Service_Delicious_Exception
             */
            require_once 'Zend/Service/Delicious/Exception.php';
            throw new Zend_Service_Delicious_Exception("Second argument must be array with at least 2 keys ('url' and"
                                                     . " 'title')");
        }

        if (isset($values['date']) && ! $values['date'] instanceof Zend_Date) {
            /**
             * @see Zend_Service_Delicious_Exception
             */
            require_once 'Zend/Service/Delicious/Exception.php';
            throw new Zend_Service_Delicious_Exception("Date has to be an instance of Zend_Date");
        }

        foreach (array('url', 'title', 'notes', 'others', 'tags', 'date', 'shared', 'hash') as $key) {
            if (isset($values[$key])) {
                $this->{"_$key"}  = $values[$key];
            }
        }
    }

    /**
     * Setter for title
     *
     * @param  string $newTitle
     * @return Zend_Service_Delicious_Post
     */
    public function setTitle($newTitle)
    {
        $this->_title = (string) $newTitle;

        return $this;
    }

    /**
     * Setter for notes
     *
     * @param  string $newNotes
     * @return Zend_Service_Delicious_Post
     */
    public function setNotes($newNotes)
    {
        $this->_notes = (string) $newNotes;

        return $this;
    }

    /**
     * Setter for tags
     *
     * @param  array $tags
     * @return Zend_Service_Delicious_Post
     */
    public function setTags(array $tags)
    {
        $this->_tags = $tags;

        return $this;
    }

    /**
     * Add a tag
     *
     * @param  string $tag
     * @return Zend_Service_Delicious_Post
     */
    public function addTag($tag)
    {
        $this->_tags[] = (string) $tag;

        return $this;
    }

    /**
     * Remove a tag
     *
     * @param  string $tag
     * @return Zend_Service_Delicious_Post
     */
    public function removeTag($tag)
    {
        $this->_tags = array_diff($this->_tags, array((string) $tag));

        return $this;
    }

    /**
     * Getter for date
     *
     * @return Zend_Date
     */
    public function getDate()
    {
        return $this->_date;
    }

    /**
     * Getter for others
     *
     * This property is only populated when posts are retrieved
     * with getPosts() method. The getAllPosts() and getRecentPosts()
     * methods will not populate this property.
     *
     * @return int
     */
    public function getOthers()
    {
        return $this->_others;
    }

    /**
     * Getter for hash
     *
     * @return string
     */
    public function getHash()
    {
        return $this->_hash;
    }

    /**
     * Getter for shared
     *
     * @return bool
     */
    public function getShared()
    {
        return $this->_shared;
    }

    /**
     * Setter for shared
     *
     * @param  bool $isShared
     * @return Zend_Service_Delicious_Post
     */
    public function setShared($isShared)
    {
        $this->_shared = (bool) $isShared;

        return $this;
    }

    /**
     * Deletes post
     *
     * @return Zend_Service_Delicious
     */
    public function delete()
    {
        return $this->_service->deletePost($this->_url);
    }

    /**
     * Saves post
     *
     * @return DOMDocument
     */
    public function save()
    {
        $parms = array(
            'url'        => $this->_url,
            'description'=> $this->_title,
            'extended'   => $this->_notes,
            'shared'     => ($this->_shared ? 'yes' : 'no'),
            'tags'       => implode(' ', (array) $this->_tags),
            'replace'    => 'yes'
        );
        /*
        if ($this->_date instanceof Zend_Date) {
            $parms['dt'] = $this->_date->get('Y-m-d\TH:i:s\Z');
        }
        */

        return $this->_service->makeRequest(Zend_Service_Delicious::PATH_POSTS_ADD, $parms);
    }

    /**
     * Extracts content from the DOM element of a post
     *
     * @param  DOMElement $node
     * @return array
     */
    protected static function _parsePostNode(DOMElement $node)
    {
        return array(
            'url'    => $node->getAttribute('href'),
            'title'  => $node->getAttribute('description'),
            'notes'  => $node->getAttribute('extended'),
            'others' => (int) $node->getAttribute('others'),
            'tags'   => explode(' ', $node->getAttribute('tag')),
            /**
             * @todo replace strtotime() with Zend_Date equivalent
             */
            'date'   => new Zend_Date(strtotime($node->getAttribute('time'))),
            'shared' => ($node->getAttribute('shared') == 'no' ? false : true),
            'hash'   => $node->getAttribute('hash')
        );
    }
}
Delicious/SimplePost.php000060400000005214150715514360011301 0ustar00<?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 Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SimplePost.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Represents a publicly available post
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Delicious_SimplePost
{
    /**
     * @var string Post url
     */
    protected $_url;

    /**
     * @var string Post title
     */
    protected $_title;

    /**
     * @var string Post notes
     */
    protected $_notes;

    /**
     * @var array Post tags
     */
    protected $_tags = array();

    /**
     * Constructor
     *
     * @param   array $post Post data
     * @return  void
     * @throws  Zend_Service_Delicious_Exception
     */
    public function __construct(array $post)
    {
        if (!isset($post['u']) || !isset($post['d'])) {
            /**
             * @see Zend_Service_Delicious_Exception
             */
            require_once 'Zend/Service/Delicious/Exception.php';
            throw new Zend_Service_Delicious_Exception('Title and URL not set.');
        }

        $this->_url   = $post['u'];
        $this->_title = $post['d'];

        if (isset($post['t'])) {
            $this->_tags = $post['t'];
        }
        if (isset($post['n'])) {
            $this->_notes = $post['n'];
        }
    }

    /**
     * Getter for URL
     *
     * @return string
     */
    public function getUrl()
    {
        return $this->_url;
    }

    /**
     * Getter for title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->_title;
    }

    /**
     * Getter for notes
     *
     * @return string
     */
    public function getNotes()
    {
        return $this->_notes;
    }

    /**
     * Getter for tags
     *
     * @return array
     */
    public function getTags()
    {
        return $this->_tags;
    }
}
Delicious/Exception.php000060400000002234150715514360011137 0ustar00<?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 Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 */


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


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Delicious_Exception extends Zend_Service_Exception
{}
Exception.php000060400000002103150715514360007212 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Zend_Exception
 */
require_once 'Zend/Exception.php';


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

Technorati.php000060400000113416150715514360007366 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Technorati.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Zend_Service_Technorati provides an easy, intuitive and object-oriented interface 
 * for using the Technorati API. 
 * 
 * It provides access to all available Technorati API queries 
 * and returns the original XML response as a friendly PHP object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati
{
    /** Base Technorati API URI */
    const API_URI_BASE = 'http://api.technorati.com';
    
    /** Query paths */
    const API_PATH_COSMOS           = '/cosmos';
    const API_PATH_SEARCH           = '/search';
    const API_PATH_TAG              = '/tag';
    const API_PATH_DAILYCOUNTS      = '/dailycounts';
    const API_PATH_TOPTAGS          = '/toptags';
    const API_PATH_BLOGINFO         = '/bloginfo';
    const API_PATH_BLOGPOSTTAGS     = '/blogposttags';
    const API_PATH_GETINFO          = '/getinfo';
    const API_PATH_KEYINFO          = '/keyinfo';
        
    /** Prevent magic numbers */
    const PARAM_LIMIT_MIN_VALUE = 1;
    const PARAM_LIMIT_MAX_VALUE = 100;
    const PARAM_DAYS_MIN_VALUE  = 1;
    const PARAM_DAYS_MAX_VALUE  = 180;
    const PARAM_START_MIN_VALUE = 1;


    /**
     * Technorati API key
     *
     * @var     string
     * @access  protected
     */
    protected $_apiKey;

    /**
     * Zend_Rest_Client instance
     *
     * @var     Zend_Rest_Client
     * @access  protected
     */
    protected $_restClient;


    /**
     * Constructs a new Zend_Service_Technorati instance
     * and setup character encoding.
     *
     * @param   string $apiKey  Your Technorati API key
     */
    public function __construct($apiKey)
    {
        iconv_set_encoding('output_encoding', 'UTF-8');
        iconv_set_encoding('input_encoding', 'UTF-8');
        iconv_set_encoding('internal_encoding', 'UTF-8');

        $this->_apiKey = $apiKey;
    }


    /**
     * Cosmos query lets you see what blogs are linking to a given URL.
     * 
     * On the Technorati site, you can enter a URL in the searchbox and
     * it will return a list of blogs linking to it.
     * The API version allows more features and gives you a way
     * to use the cosmos on your own site.
     *
     * Query options include:
     *
     * 'type'       => (link|weblog)
     *      optional - A value of link returns the freshest links referencing your target URL.
     *      A value of weblog returns the last set of unique weblogs referencing your target URL.
     * 'limit'      => (int)
     *      optional - adjust the size of your result from the default value of 20
     *      to between 1 and 100 results.
     * 'start'      => (int)
     *      optional - adjust the range of your result set.
     *      Set this number to larger than zero and you will receive
     *      the portion of Technorati's total result set ranging from start to start+limit.
     *      The default start value is 1.
     * 'current'    => (true|false)
     *      optional - the default setting of true
     *      Technorati returns links that are currently on a weblog's homepage.
     *      Set this parameter to false if you would like to receive all links
     *      to the given URL regardless of their current placement on the source blog.
     *      Internally the value is converted in (yes|no).
     * 'claim'      => (true|false)
     *      optional - the default setting of FALSE returns no user information
     *      about each weblog included in the result set when available.
     *      Set this parameter to FALSE to include Technorati member data
     *      in the result set when a weblog in your result set
     *      has been successfully claimed by a member of Technorati.
     *      Internally the value is converted in (int).
     * 'highlight'  => (true|false)
     *      optional - the default setting of TRUE
     *      highlights the citation of the given URL within the weblog excerpt.
     *      Set this parameter to FALSE to apply no special markup to the blog excerpt.
     *      Internally the value is converted in (int).
     * 
     * @param   string $url     the URL you are searching for. Prefixes http:// and www. are optional.
     * @param   array $options  additional parameters to refine your query
     * @return  Zend_Service_Technorati_CosmosResultSet
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://technorati.com/developers/api/cosmos.html Technorati API: Cosmos Query reference
     */
    public function cosmos($url, $options = null)
    {
        static $defaultOptions = array( 'type'      => 'link',
                                        'start'     => 1,
                                        'limit'     => 20,
                                        'current'   => 'yes',
                                        'format'    => 'xml',
                                        'claim'     => 0,
                                        'highlight' => 1,
                                        );

        $options['url'] = $url;

        $options = $this->_prepareOptions($options, $defaultOptions);
        $this->_validateCosmos($options);
        $response = $this->_makeRequest(self::API_PATH_COSMOS, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_CosmosResultSet 
         */
        require_once 'Zend/Service/Technorati/CosmosResultSet.php';
        return new Zend_Service_Technorati_CosmosResultSet($dom, $options);
    }

    /**
     * Search lets you see what blogs contain a given search string.
     *
     * Query options include:
     *
     * 'language'   => (string)
     *      optional - a ISO 639-1 two character language code 
     *      to retrieve results specific to that language. 
     *      This feature is currently beta and may not work for all languages.
     * 'authority'  => (n|a1|a4|a7)
     *      optional - filter results to those from blogs with at least 
     *      the Technorati Authority specified. 
     *      Technorati calculates a blog's authority by how many people link to it. 
     *      Filtering by authority is a good way to refine your search results. 
     *      There are four settings:
     *      - n  => Any authority: All results.
     *      - a1 => A little authority: Results from blogs with at least one link.
     *      - a4 => Some authority: Results from blogs with a handful of links.
     *      - a7 => A lot of authority: Results from blogs with hundreds of links.
     * 'limit'      => (int)
     *      optional - adjust the size of your result from the default value of 20
     *      to between 1 and 100 results.
     * 'start'      => (int)
     *      optional - adjust the range of your result set.
     *      Set this number to larger than zero and you will receive
     *      the portion of Technorati's total result set ranging from start to start+limit.
     *      The default start value is 1.
     * 'claim'      => (true|false)
     *      optional - the default setting of FALSE returns no user information
     *      about each weblog included in the result set when available.
     *      Set this parameter to FALSE to include Technorati member data
     *      in the result set when a weblog in your result set
     *      has been successfully claimed by a member of Technorati.
     *      Internally the value is converted in (int).
     * 
     * @param   string $query   the words you are searching for.
     * @param   array $options  additional parameters to refine your query
     * @return  Zend_Service_Technorati_SearchResultSet
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://technorati.com/developers/api/search.html Technorati API: Search Query reference
     */
    public function search($query, $options = null)
    {
        static $defaultOptions = array( 'start'     => 1,
                                        'limit'     => 20,
                                        'format'    => 'xml',
                                        'claim'     => 0);

        $options['query'] = $query;

        $options = $this->_prepareOptions($options, $defaultOptions);
        $this->_validateSearch($options);
        $response = $this->_makeRequest(self::API_PATH_SEARCH, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_SearchResultSet
         */
        require_once 'Zend/Service/Technorati/SearchResultSet.php';
        return new Zend_Service_Technorati_SearchResultSet($dom, $options);
    }

    /**
     * Tag lets you see what posts are associated with a given tag.
     *
     * Query options include:
     * 
     * 'limit'          => (int)
     *      optional - adjust the size of your result from the default value of 20
     *      to between 1 and 100 results.
     * 'start'          => (int)
     *      optional - adjust the range of your result set.
     *      Set this number to larger than zero and you will receive
     *      the portion of Technorati's total result set ranging from start to start+limit.
     *      The default start value is 1.
     * 'excerptsize'    => (int)
     *      optional - number of word characters to include in the post excerpts. 
     *      By default 100 word characters are returned.
     * 'topexcerptsize' => (int)
     *      optional - number of word characters to include in the first post excerpt. 
     *      By default 150 word characters are returned.
     * 
     * @param   string $tag     the tag term you are searching posts for.
     * @param   array $options  additional parameters to refine your query
     * @return  Zend_Service_Technorati_TagResultSet
     * @throws  Zend_Service_Technorati_Exception
     *  @link    http://technorati.com/developers/api/tag.html Technorati API: Tag Query reference
     */
    public function tag($tag, $options = null)
    {
        static $defaultOptions = array( 'start'          => 1,
                                        'limit'          => 20,
                                        'format'         => 'xml',
                                        'excerptsize'    => 100,
                                        'topexcerptsize' => 150);

        $options['tag'] = $tag;

        $options = $this->_prepareOptions($options, $defaultOptions);
        $this->_validateTag($options);
        $response = $this->_makeRequest(self::API_PATH_TAG, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_TagResultSet
         */
        require_once 'Zend/Service/Technorati/TagResultSet.php';
        return new Zend_Service_Technorati_TagResultSet($dom, $options);
    }

    /**
     * TopTags provides daily counts of posts containing the queried keyword.
     *
     * Query options include:
     *
     * 'days'       => (int)
     *      optional - Used to specify the number of days in the past 
     *      to request daily count data for. 
     *      Can be any integer between 1 and 180, default is 180
     * 
     * @param   string $q       the keyword query
     * @param   array $options  additional parameters to refine your query
     * @return  Zend_Service_Technorati_DailyCountsResultSet
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://technorati.com/developers/api/dailycounts.html Technorati API: DailyCounts Query reference
     */
    public function dailyCounts($query, $options = null)
    {
        static $defaultOptions = array( 'days'      => 180,
                                        'format'    => 'xml'
                                        );

        $options['q'] = $query;

        $options = $this->_prepareOptions($options, $defaultOptions);
        $this->_validateDailyCounts($options);
        $response = $this->_makeRequest(self::API_PATH_DAILYCOUNTS, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_DailyCountsResultSet
         */
        require_once 'Zend/Service/Technorati/DailyCountsResultSet.php';
        return new Zend_Service_Technorati_DailyCountsResultSet($dom);
    }
    
    /**
     * TopTags provides information on top tags indexed by Technorati.
     *
     * Query options include:
     *
     * 'limit'      => (int)
     *      optional - adjust the size of your result from the default value of 20
     *      to between 1 and 100 results.
     * 'start'      => (int)
     *      optional - adjust the range of your result set.
     *      Set this number to larger than zero and you will receive
     *      the portion of Technorati's total result set ranging from start to start+limit.
     *      The default start value is 1.
     * 
     * @param   array $options  additional parameters to refine your query
     * @return  Zend_Service_Technorati_TagsResultSet
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://technorati.com/developers/api/toptags.html Technorati API: TopTags Query reference
     */
    public function topTags($options = null)
    {
        static $defaultOptions = array( 'start'     => 1,
                                        'limit'     => 20,
                                        'format'    => 'xml'
                                        );

        $options = $this->_prepareOptions($options, $defaultOptions);
        $this->_validateTopTags($options);
        $response = $this->_makeRequest(self::API_PATH_TOPTAGS, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_TagsResultSet
         */
        require_once 'Zend/Service/Technorati/TagsResultSet.php';
        return new Zend_Service_Technorati_TagsResultSet($dom);
    }

    /**
     * BlogInfo provides information on what blog, if any, is associated with a given URL.
     *
     * @param   string $url     the URL you are searching for. Prefixes http:// and www. are optional.
     *                          The URL must be recognized by Technorati as a blog.
     * @param   array $options  additional parameters to refine your query
     * @return  Zend_Service_Technorati_BlogInfoResult
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://technorati.com/developers/api/bloginfo.html Technorati API: BlogInfo Query reference
     */
    public function blogInfo($url, $options = null)
    {
        static $defaultOptions = array( 'format'    => 'xml'
                                        );

        $options['url'] = $url;

        $options = $this->_prepareOptions($options, $defaultOptions);
        $this->_validateBlogInfo($options);
        $response = $this->_makeRequest(self::API_PATH_BLOGINFO, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_BlogInfoResult
         */
        require_once 'Zend/Service/Technorati/BlogInfoResult.php';
        return new Zend_Service_Technorati_BlogInfoResult($dom);
    }
    
    /**
     * BlogPostTags provides information on the top tags used by a specific blog.
     *
     * Query options include:
     *
     * 'limit'      => (int)
     *      optional - adjust the size of your result from the default value of 20
     *      to between 1 and 100 results.
     * 'start'      => (int)
     *      optional - adjust the range of your result set.
     *      Set this number to larger than zero and you will receive
     *      the portion of Technorati's total result set ranging from start to start+limit.
     *      The default start value is 1.
     *      Note. This property is not documented.
     * 
     * @param   string $url     the URL you are searching for. Prefixes http:// and www. are optional.
     *                          The URL must be recognized by Technorati as a blog.
     * @param   array $options  additional parameters to refine your query
     * @return  Zend_Service_Technorati_TagsResultSet
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://technorati.com/developers/api/blogposttags.html Technorati API: BlogPostTags Query reference
     */
    public function blogPostTags($url, $options = null)
    {
        static $defaultOptions = array( 'start'     => 1,
                                        'limit'     => 20,
                                        'format'    => 'xml'
                                        );

        $options['url'] = $url;

        $options = $this->_prepareOptions($options, $defaultOptions);
        $this->_validateBlogPostTags($options);
        $response = $this->_makeRequest(self::API_PATH_BLOGPOSTTAGS, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_TagsResultSet
         */
        require_once 'Zend/Service/Technorati/TagsResultSet.php';
        return new Zend_Service_Technorati_TagsResultSet($dom);
    }
    
    /**
     * GetInfo query tells you things that Technorati knows about a member.
     * 
     * The returned info is broken up into two sections: 
     * The first part describes some information that the user wants 
     * to allow people to know about him- or herself. 
     * The second part of the document is a listing of the weblogs 
     * that the user has successfully claimed and the information 
     * that Technorati knows about these weblogs.
     *
     * @param   string $username    the Technorati user name you are searching for
     * @param   array $options      additional parameters to refine your query
     * @return  Zend_Service_Technorati_GetInfoResult
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://technorati.com/developers/api/getinfo.html Technorati API: GetInfo reference
     */
    public function getInfo($username, $options = null) 
    {
        static $defaultOptions = array('format' => 'xml');

        $options['username'] = $username;

        $options = $this->_prepareOptions($options, $defaultOptions);
        $this->_validateGetInfo($options);
        $response = $this->_makeRequest(self::API_PATH_GETINFO, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_GetInfoResult
         */
        require_once 'Zend/Service/Technorati/GetInfoResult.php';
        return new Zend_Service_Technorati_GetInfoResult($dom);
    }
    
    /**
     * KeyInfo query provides information on daily usage of an API key. 
     * Key Info Queries do not count against a key's daily query limit.
     * 
     * A day is defined as 00:00-23:59 Pacific time.
     * 
     * @return  Zend_Service_Technorati_KeyInfoResult
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://developers.technorati.com/wiki/KeyInfo Technorati API: Key Info reference
     */
    public function keyInfo()
    {
        static $defaultOptions = array();

        $options = $this->_prepareOptions(array(), $defaultOptions);
        // you don't need to validate this request
        // because key is the only mandatory element 
        // and it's already set in #_prepareOptions
        $response = $this->_makeRequest(self::API_PATH_KEYINFO, $options);
        $dom = $this->_convertResponseAndCheckContent($response);

        /** 
         * @see Zend_Service_Technorati_KeyInfoResult
         */
        require_once 'Zend/Service/Technorati/KeyInfoResult.php';       
        return new Zend_Service_Technorati_KeyInfoResult($dom, $this->_apiKey);
    }


    /**
     * Returns Technorati API key.
     *
     * @return string   Technorati API key
     */
    public function getApiKey()
    {
        return $this->_apiKey;
    }

    /**
     * Returns a reference to the REST client object in use.
     *
     * If the reference hasn't being inizialized yet,
     * then a new Zend_Rest_Client instance is created.
     *
     * @return Zend_Rest_Client
     */
    public function getRestClient()
    {
        if (is_null($this->_restClient)) {
            /**
             * @see Zend_Rest_Client
             */
            require_once 'Zend/Rest/Client.php';
            $this->_restClient = new Zend_Rest_Client(self::API_URI_BASE);
        }

        return $this->_restClient;
    }

    /**
     * Sets Technorati API key.
     * 
     * Be aware that this function doesn't validate the key.
     * The key is validated as soon as the first API request is sent.
     * If the key is invalid, the API request method will throw
     * a Zend_Service_Technorati_Exception exception with Invalid Key message.
     *
     * @param   string $key     Technorati API Key
     * @return  void
     * @link    http://technorati.com/developers/apikey.html How to get your Technorati API Key
     */
    public function setApiKey($key)
    {
        $this->_apiKey = $key;
        return $this;
    }


    /**
     * Validates Cosmos query options.
     *
     * @param   array $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateCosmos(array $options)
    {
        static $validOptions = array('key', 'url',
            'type', 'limit', 'start', 'current', 'claim', 'highlight', 'format');

        // Validate keys in the $options array
        $this->_compareOptions($options, $validOptions);
        // Validate url (required)
        $this->_validateOptionUrl($options);
        // Validate limit (optional)
        $this->_validateOptionLimit($options);
        // Validate start (optional)
        $this->_validateOptionStart($options);
        // Validate format (optional)
        $this->_validateOptionFormat($options);
        // Validate type (optional)
        $this->_validateInArrayOption('type', $options, array('link', 'weblog'));
        // Validate claim (optional)
        $this->_validateOptionClaim($options);
        // Validate highlight (optional)
        $this->_validateIntegerOption('highlight', $options);
        // Validate current (optional)
        if (isset($options['current'])) {
            $tmp = (int) $options['current'];
            $options['current'] = $tmp ? 'yes' : 'no';
        }

    }
        
    /**
     * Validates Search query options.
     *
     * @param   array   $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateSearch(array $options)
    {
        static $validOptions = array('key', 'query',
            'language', 'authority', 'limit', 'start', 'claim', 'format');

        // Validate keys in the $options array
        $this->_compareOptions($options, $validOptions);
        // Validate query (required)
        $this->_validateMandatoryOption('query', $options);
        // Validate authority (optional)
        $this->_validateInArrayOption('authority', $options, array('n', 'a1', 'a4', 'a7'));
        // Validate limit (optional)
        $this->_validateOptionLimit($options);
        // Validate start (optional)
        $this->_validateOptionStart($options);
        // Validate claim (optional)
        $this->_validateOptionClaim($options);
        // Validate format (optional)
        $this->_validateOptionFormat($options);
    }
        
    /**
     * Validates Tag query options.
     *
     * @param   array   $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateTag(array $options)
    {
        static $validOptions = array('key', 'tag',
            'limit', 'start', 'excerptsize', 'topexcerptsize', 'format');

        // Validate keys in the $options array
        $this->_compareOptions($options, $validOptions);
        // Validate query (required)
        $this->_validateMandatoryOption('tag', $options);
        // Validate limit (optional)
        $this->_validateOptionLimit($options);
        // Validate start (optional)
        $this->_validateOptionStart($options);
        // Validate excerptsize (optional)
        $this->_validateIntegerOption('excerptsize', $options);
        // Validate excerptsize (optional)
        $this->_validateIntegerOption('topexcerptsize', $options);
        // Validate format (optional)
        $this->_validateOptionFormat($options);
    }

    
    /**
     * Validates DailyCounts query options.
     *
     * @param   array   $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateDailyCounts(array $options)
    {
        static $validOptions = array('key', 'q',
            'days', 'format');

        // Validate keys in the $options array
        $this->_compareOptions($options, $validOptions);
        // Validate q (required)
        $this->_validateMandatoryOption('q', $options);
        // Validate format (optional)
        $this->_validateOptionFormat($options);
        // Validate days (optional)
        if (isset($options['days'])) {
            $options['days'] = (int) $options['days'];
            if ($options['days'] < self::PARAM_DAYS_MIN_VALUE || 
                $options['days'] > self::PARAM_DAYS_MAX_VALUE) {
                /**
                 * @see Zend_Service_Technorati_Exception
                 */
                require_once 'Zend/Service/Technorati/Exception.php';
                throw new Zend_Service_Technorati_Exception(
                            "Invalid value '" . $options['days'] . "' for 'days' option");
            }
        }
    }
    
    /**
     * Validates GetInfo query options.
     *
     * @param   array   $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateGetInfo(array $options)
    {
        static $validOptions = array('key', 'username',
            'format');

        // Validate keys in the $options array
        $this->_compareOptions($options, $validOptions);
        // Validate username (required)
        $this->_validateMandatoryOption('username', $options);
        // Validate format (optional)
        $this->_validateOptionFormat($options);
    }

    /**
     * Validates TopTags query options.
     *
     * @param   array $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateTopTags(array $options)
    {
        static $validOptions = array('key', 
            'limit', 'start', 'format');

        // Validate keys in the $options array
        $this->_compareOptions($options, $validOptions);
        // Validate limit (optional)
        $this->_validateOptionLimit($options);
        // Validate start (optional)
        $this->_validateOptionStart($options);
        // Validate format (optional)
        $this->_validateOptionFormat($options);
    }
    
    /**
     * Validates BlogInfo query options.
     *
     * @param   array   $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateBlogInfo(array $options)
    {
        static $validOptions = array('key', 'url',
            'format');

        // Validate keys in the $options array
        $this->_compareOptions($options, $validOptions);
        // Validate url (required)
        $this->_validateOptionUrl($options);
        // Validate format (optional)
        $this->_validateOptionFormat($options);
    }
    
    /**
     * Validates TopTags query options.
     *
     * @param   array $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateBlogPostTags(array $options)
    {
        static $validOptions = array('key', 'url', 
            'limit', 'start', 'format');

        // Validate keys in the $options array
        $this->_compareOptions($options, $validOptions);
        // Validate url (required)
        $this->_validateOptionUrl($options);
        // Validate limit (optional)
        $this->_validateOptionLimit($options);
        // Validate start (optional)
        $this->_validateOptionStart($options);
        // Validate format (optional)
        $this->_validateOptionFormat($options);
    }

    /**
     * Checks whether an option is in a given array.
     *
     * @param   string $name    option name
     * @param   array $options
     * @param   array $array    array of valid options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateInArrayOption($name, $options, array $array)
    {
        if (isset($options[$name]) && !in_array($options[$name], $array)) {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception(
                        "Invalid value '{$options[$name]}' for '$name' option");
        }
    }
    
    /**
     * Checks whether mandatory $name option exists and it's valid.
     * 
     * @param   array $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _validateMandatoryOption($name, $options) 
    {
        if (!isset($options[$name]) || !trim($options[$name])) {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception(
                        "Empty value for '$name' option");
        }
    }
    
    /**
     * Checks whether $name option is a valid integer and casts it.
     * 
     * @param   array $options
     * @return  void
     * @access  protected
     */
    protected function _validateIntegerOption($name, $options) 
    {
        if (isset($options[$name])) {
            $options[$name] = (int) $options[$name];
        }
    }
    
    /**
     * Makes and HTTP GET request to given $path with $options.
     * HTTP Response is first validated, then returned.
     * 
     * @param   string $path
     * @param   array $options
     * @return  Zend_Http_Response
     * @throws  Zend_Service_Technorati_Exception on failure
     * @access  protected
     */
    protected function _makeRequest($path, $options = array())
    {
        $restClient = $this->getRestClient();
        $restClient->getHttpClient()->resetParameters();
        $response = $restClient->restGet($path, $options);
        self::_checkResponse($response);
        return $response;
    }

    /**
     * Checks whether 'claim' option value is valid. 
     * 
     * @param   array $options
     * @return  void
     * @access  protected
     */
    protected function _validateOptionClaim(array $options) 
    {
        $this->_validateIntegerOption('claim', $options);
    }
    
    /**
     * Checks whether 'format' option value is valid. 
     * Be aware that Zend_Service_Technorati supports only XML as format value.
     * 
     * @param   array $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception if 'format' value != XML
     * @access  protected
     */
    protected function _validateOptionFormat(array $options) 
    {
        if (isset($options['format']) && $options['format'] != 'xml') {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception(
                        "Invalid value '" . $options['format'] . "' for 'format' option. " .
                        "Zend_Service_Technorati supports only 'xml'");
        }
    }
    
    /**
     * Checks whether 'limit' option value is valid. 
     * Value must be an integer greater than PARAM_LIMIT_MIN_VALUE
     * and lower than PARAM_LIMIT_MAX_VALUE.
     * 
     * @param   array $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception if 'limit' value is invalid
     * @access  protected
     */
    protected function _validateOptionLimit(array $options) 
    {
        if (!isset($options['limit'])) return;
        
        $options['limit'] = (int) $options['limit'];
        if ($options['limit'] < self::PARAM_LIMIT_MIN_VALUE || 
            $options['limit'] > self::PARAM_LIMIT_MAX_VALUE) {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception(
                        "Invalid value '" . $options['limit'] . "' for 'limit' option");
        }
    }
    
    /**
     * Checks whether 'start' option value is valid. 
     * Value must be an integer greater than 0.
     * 
     * @param   array $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception if 'start' value is invalid
     * @access  protected
     */
    protected function _validateOptionStart(array $options) 
    {
        if (!isset($options['start'])) return;
        
        $options['start'] = (int) $options['start'];
        if ($options['start'] < self::PARAM_START_MIN_VALUE) {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception(
                        "Invalid value '" . $options['start'] . "' for 'start' option");
        }
    }

    /**
     * Checks whether 'url' option value exists and is valid. 
     * 'url' must be a valid HTTP(s) URL.
     * 
     * @param   array $options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception if 'url' value is invalid
     * @access  protected
     * @todo    support for Zend_Uri_Http
     */
    protected function _validateOptionUrl(array $options) 
    {
        $this->_validateMandatoryOption('url', $options);
    }
    
    /**
     * Checks XML response content for errors.
     *
     * @param   DomDocument $dom    the XML response as a DOM document
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @link    http://technorati.com/developers/api/error.html Technorati API: Error response
     * @access  protected
     */
    protected static function _checkErrors(DomDocument $dom)
    {
        $xpath = new DOMXPath($dom);

        $result = $xpath->query("/tapi/document/result/error");
        if ($result->length >= 1) {
            $error = $result->item(0)->nodeValue;
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception($error);
        }
    }

    /**
     * Converts $response body to a DOM object and checks it.
     * 
     * @param   Zend_Http_Response $response
     * @return  DOMDocument
     * @throws  Zend_Service_Technorati_Exception if response content contains an error message
     * @access  protected
     */
    protected function _convertResponseAndCheckContent(Zend_Http_Response $response)
    {
        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());
        self::_checkErrors($dom);
        return $dom;
    }
    
    /**
     * Checks ReST response for errors.
     *
     * @param   Zend_Http_Response $response    the ReST response
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected static function _checkResponse(Zend_Http_Response $response)
    {
        if ($response->isError()) {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception(sprintf(
                        'Invalid response status code (HTTP/%s %s %s)',
                        $response->getVersion(), $response->getStatus(), $response->getMessage()));
        }
    }

    /**
     * Checks whether user given options are valid.
     * 
     * @param   array $options        user options
     * @param   array $validOptions   valid options
     * @return  void
     * @throws  Zend_Service_Technorati_Exception
     * @access  protected
     */
    protected function _compareOptions(array $options, array $validOptions)
    {
        $difference = array_diff(array_keys($options), $validOptions);
        if ($difference) {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception(
                        "The following parameters are invalid: '" . 
                        implode("', '", $difference) . "'");
        }
    }

    /**
     * Prepares options for the request
     *
     * @param   array $options        user options
     * @param   array $defaultOptions default options
     * @return  array Merged array of user and default/required options.
     * @access  protected
     */
    protected function _prepareOptions($options, array $defaultOptions)
    {
        $options = (array) $options; // force cast to convert null to array()
        $options['key'] = $this->_apiKey;
        $options = array_merge($defaultOptions, $options);
        return $options;
    }
}
Flickr/Image.php000060400000003550150715514360007517 0ustar00<?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 Flickr
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Image.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Flickr
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Flickr_Image
{
    /**
     * The URI of the image
     *
     * @var string
     */
    public $uri;

    /**
     * The URI for linking to the photo on Flickr
     *
     * @var string
     */
    public $clickUri;

    /**
     * The height of the image in pixels
     *
     * @var string
     */
    public $height;

    /**
     * The width of the image in pixels
     *
     * @var string
     */
    public $width;

    /**
     * Parse given Flickr Image element
     *
     * @param  DOMElement $image
     * @return void
     */
    public function __construct(DOMElement $image)
    {
        $this->uri      = (string) $image->getAttribute('source');
        $this->clickUri = (string) $image->getAttribute('url');
        $this->height   = (int) $image->getAttribute('height');
        $this->width    = (int) $image->getAttribute('width');
    }
}

Flickr/ResultSet.php000060400000010606150715514360010427 0ustar00<?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 Flickr
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Flickr_Result
 */
require_once 'Zend/Service/Flickr/Result.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Flickr
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Flickr_ResultSet implements SeekableIterator
{
    /**
     * Total number of available results
     *
     * @var int
     */
    public $totalResultsAvailable;

    /**
     * Number of results in this result set
     *
     * @var int
     */
    public $totalResultsReturned;

    /**
     * The offset of this result set in the total set of available results
     *
     * @var int
     */
    public $firstResultPosition;

    /**
     * Results storage
     *
     * @var DOMNodeList
     */
    protected $_results = null;

    /**
     * Reference to Zend_Service_Flickr object with which the request was made
     *
     * @var Zend_Service_Flickr
     */
    private $_flickr;

    /**
     * Current index for the Iterator
     *
     * @var int
     */
    private $_currentIndex = 0;

    /**
     * Parse the Flickr Result Set
     *
     * @param  DOMDocument         $dom
     * @param  Zend_Service_Flickr $flickr
     * @return void
     */
    public function __construct(DOMDocument $dom, Zend_Service_Flickr $flickr)
    {
        $this->_flickr = $flickr;

        $xpath = new DOMXPath($dom);

        $photos = $xpath->query('//photos')->item(0);

        $page    = $photos->getAttribute('page');
        $pages   = $photos->getAttribute('pages');
        $perPage = $photos->getAttribute('perpage');
        $total   = $photos->getAttribute('total');

        $this->totalResultsReturned  = ($page == $pages) ? ($total - ($page - 1) * $perPage) : (int) $perPage;
        $this->firstResultPosition   = ($page - 1) * $perPage + 1;
        $this->totalResultsAvailable = (int) $total;

        if ($total > 0) {
            $this->_results = $xpath->query('//photo');
        }
    }

    /**
     * Total Number of results returned
     *
     * @return int Total number of results returned
     */
    public function totalResults()
    {
        return $this->totalResultsReturned;
    }

    /**
     * Implements SeekableIterator::current()
     *
     * @return Zend_Service_Flickr_Result
     */
    public function current()
    {
        return new Zend_Service_Flickr_Result($this->_results->item($this->_currentIndex), $this->_flickr);
    }

    /**
     * Implements SeekableIterator::key()
     *
     * @return int
     */
    public function key()
    {
        return $this->_currentIndex;
    }

    /**
     * Implements SeekableIterator::next()
     *
     * @return void
     */
    public function next()
    {
        $this->_currentIndex += 1;
    }

    /**
     * Implements SeekableIterator::rewind()
     *
     * @return void
     */
    public function rewind()
    {
        $this->_currentIndex = 0;
    }

    /**
     * Implements SeekableIterator::seek()
     *
     * @param  int $index
     * @throws OutOfBoundsException
     * @return void
     */
    public function seek($index)
    {
        $indexInt = (int) $index;
        if ($indexInt >= 0 && (null === $this->_results || $indexInt < $this->_results->length)) {
            $this->_currentIndex = $indexInt;
        } else {
            throw new OutOfBoundsException("Illegal index '$index'");
        }
    }

    /**
     * Implements SeekableIterator::valid()
     *
     * @return boolean
     */
    public function valid()
    {
        return null !== $this->_results && $this->_currentIndex < $this->_results->length;
    }
}

Flickr/Result.php000060400000007634150715514360007762 0ustar00<?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 Flickr
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Result.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Flickr
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Flickr_Result
{
    /**
     * The photo's Flickr ID.
     *
     * @var string
     */
    public $id;

    /**
     * The photo owner's NSID.
     *
     * @var string
     */
    public $owner;

    /**
     * A key used in URI construction.
     *
     * @var string
     */
    public $secret;

    /**
     * The servername to use for URI construction.
     *
     * @var string
     */
    public $server;

    /**
     * The photo's title.
     *
     * @var string
     */
    public $title;

    /**
     * Whether the photo is public.
     *
     * @var string
     */
    public $ispublic;

    /**
     * Whether the photo is visible to you because you are a friend of the owner.
     *
     * @var string
     */
    public $isfriend;

    /**
     * Whether the photo is visible to you because you are family of the owner.
     *
     * @var string
     */
    public $isfamily;

    /**
     * The license the photo is available under.
     *
     * @var string
     */
    public $license;

    /**
     * The date the photo was uploaded.
     *
     * @var string
     */
    public $dateupload;

    /**
     * The date the photo was taken.
     *
     * @var string
     */
    public $datetaken;

    /**
     * The screenname of the owner.
     *
     * @var string
     */
    public $ownername;

    /**
     * The server used in assembling icon URLs.
     *
     * @var string
     */
    public $iconserver;

    /**
     * A 75x75 pixel square thumbnail of the image.
     *
     * @var Zend_Service_Flickr_Image
     */
    public $Square;

    /**
     * A 100 pixel thumbnail of the image.
     *
     * @var Zend_Service_Flickr_Image
     */
    public $Thumbnail;

    /**
     * A 240 pixel version of the image.
     *
     * @var Zend_Service_Flickr_Image
     */
    public $Small;

    /**
     * A 500 pixel version of the image.
     *
     * @var Zend_Service_Flickr_Image
     */
    public $Medium;

    /**
     * A 640 pixel version of the image.
     *
     * @var Zend_Service_Flickr_Image
     */
    public $Large;

    /**
     * The original image.
     *
     * @var Zend_Service_Flickr_Image
     */
    public $Original;

    /**
     * Original Zend_Service_Flickr object.
     *
     * @var Zend_Service_Flickr
     */
    protected $_flickr;

    /**
     * Parse the Flickr Result
     *
     * @param  DOMElement          $image
     * @param  Zend_Service_Flickr $flickr Original Zend_Service_Flickr object with which the request was made
     * @return void
     */
    public function __construct(DOMElement $image, Zend_Service_Flickr $flickr)
    {
        $xpath = new DOMXPath($image->ownerDocument);

        foreach ($xpath->query('./@*', $image) as $property) {
            $this->{$property->name} = (string) $property->value;
        }

        $this->_flickr = $flickr;

        foreach ($this->_flickr->getImageDetails($this->id) as $k => $v) {
            $this->$k = $v;
        }
    }
}
ReCaptcha.php000060400000030243150715514360007114 0ustar00<?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 ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** @see Zend_Service_Abstract */
require_once 'Zend/Service/Abstract.php';

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

/** @see Zend_Service_ReCaptcha_Response */
require_once 'Zend/Service/ReCaptcha/Response.php';

/**
 * Zend_Service_ReCaptcha
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Service_ReCaptcha extends Zend_Service_Abstract
{
    /**
     * URI to the regular API
     *
     * @var string
     */
    const API_SERVER = 'http://api.recaptcha.net';

    /**
     * URI to the secure API
     *
     * @var string
     */
    const API_SECURE_SERVER = 'https://api-secure.recaptcha.net';

    /**
     * URI to the verify server
     *
     * @var string
     */
    const VERIFY_SERVER = 'http://api-verify.recaptcha.net/verify';

    /**
     * Public key used when displaying the captcha
     *
     * @var string
     */
    protected $_publicKey = null;

    /**
     * Private key used when verifying user input
     *
     * @var string
     */
    protected $_privateKey = null;

    /**
     * Ip address used when verifying user input
     *
     * @var string
     */
    protected $_ip = null;

    /**
     * Parameters for the object
     *
     * @var array
     */
    protected $_params = array(
        'ssl' => false, /* Use SSL or not when generating the recaptcha */
        'error' => null, /* The error message to display in the recaptcha */
        'xhtml' => false /* Enable XHTML output (this will not be XHTML Strict
                            compliant since the IFRAME is necessary when
                            Javascript is disabled) */
    );

    /**
     * Options for tailoring reCaptcha
     *
     * See the different options on http://recaptcha.net/apidocs/captcha/client.html
     *
     * @var array
     */
    protected $_options = array(
        'theme' => 'red',
        'lang' => 'en',
    );

    /**
     * Response from the verify server
     *
     * @var Zend_Service_ReCaptcha_Response
     */
    protected $_response = null;

    /**
     * Class constructor
     *
     * @param string $publicKey
     * @param string $privateKey
     * @param array $params
     * @param array $options
     * @param string $ip
     * @param array|Zend_Config $params
     */
    public function __construct($publicKey = null, $privateKey = null,
                                $params = null, $options = null, $ip = null)
    {
        if ($publicKey !== null) {
            $this->setPublicKey($publicKey);
        }

        if ($privateKey !== null) {
            $this->setPrivateKey($privateKey);
        }

        if ($ip !== null) {
            $this->setIp($ip);
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $this->setIp($_SERVER['REMOTE_ADDR']);
        }

        if ($params !== null) {
            $this->setParams($params);
        }

        if ($options !== null) {
            $this->setOptions($options);
        }
    }

    /**
     * Serialize as string
     *
     * When the instance is used as a string it will display the recaptcha.
     * Since we can't throw exceptions within this method we will trigger
     * a user warning instead.
     *
     * @return string
     */
    public function __toString()
    {
        try {
            $return = $this->getHtml();
        } catch (Exception $e) {
            $return = '';
            trigger_error($e->getMessage(), E_USER_WARNING);
        }

        return $return;
    }

    /**
     * Set the ip property
     *
     * @param string $ip
     * @return Zend_Service_ReCaptcha
     */
    public function setIp($ip)
    {
        $this->_ip = $ip;

        return $this;
    }

    /**
     * Get the ip property
     *
     * @return string
     */
    public function getIp()
    {
        return $this->_ip;
    }

    /**
     * Set a single parameter
     *
     * @param string $key
     * @param string $value
     * @return Zend_Service_ReCaptcha
     */
    public function setParam($key, $value)
    {
        $this->_params[$key] = $value;

        return $this;
    }

    /**
     * Set parameters
     *
     * @param array|Zend_Config $params
     * @return Zend_Service_ReCaptcha
     * @throws Zend_Service_ReCaptcha_Exception
     */
    public function setParams($params)
    {
        if ($params instanceof Zend_Config) {
            $params = $params->toArray();
        }

        if (is_array($params)) {
            foreach ($params as $k => $v) {
                $this->setParam($k, $v);
            }
        } else {
            /** @see Zend_Service_ReCaptcha_Exception */
            require_once 'Zend/Service/ReCaptcha/Exception.php';

            throw new Zend_Service_ReCaptcha_Exception(
                'Expected array or Zend_Config object'
            );
        }

        return $this;
    }

    /**
     * Get the parameter array
     *
     * @return array
     */
    public function getParams()
    {
        return $this->_params;
    }

    /**
     * Get a single parameter
     *
     * @param string $key
     * @return mixed
     */
    public function getParam($key)
    {
        return $this->_params[$key];
    }

    /**
     * Set a single option
     *
     * @param string $key
     * @param string $value
     * @return Zend_Service_ReCaptcha
     */
    public function setOption($key, $value)
    {
        $this->_options[$key] = $value;

        return $this;
    }

    /**
     * Set options
     *
     * @param array|Zend_Config $options
     * @return Zend_Service_ReCaptcha
     * @throws Zend_Service_ReCaptcha_Exception
     */
    public function setOptions($options)
    {
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        }

        if (is_array($options)) {
            foreach ($options as $k => $v) {
                $this->setOption($k, $v);
            }
        } else {
            /** @see Zend_Service_ReCaptcha_Exception */
            require_once 'Zend/Service/ReCaptcha/Exception.php';

            throw new Zend_Service_ReCaptcha_Exception(
                'Expected array or Zend_Config object'
            );
        }

        return $this;
    }

    /**
     * Get the options array
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->_options;
    }

    /**
     * Get a single option
     *
     * @param string $key
     * @return mixed
     */
    public function getOption($key)
    {
        return $this->_options[$key];
    }

    /**
     * Get the public key
     *
     * @return string
     */
    public function getPublicKey()
    {
        return $this->_publicKey;
    }

    /**
     * Set the public key
     *
     * @param string $publicKey
     * @return Zend_Service_ReCaptcha
     */
    public function setPublicKey($publicKey)
    {
        $this->_publicKey = $publicKey;

        return $this;
    }

    /**
     * Get the private key
     *
     * @return string
     */
    public function getPrivateKey()
    {
        return $this->_privateKey;
    }

    /**
     * Set the private key
     *
     * @param string $privateKey
     * @return Zend_Service_ReCaptcha
     */
    public function setPrivateKey($privateKey)
    {
        $this->_privateKey = $privateKey;

        return $this;
    }

    /**
     * Get the HTML code for the captcha
     *
     * This method uses the public key to fetch a recaptcha form.
     *
     * @return string
     * @throws Zend_Service_ReCaptcha_Exception
     */
    public function getHtml()
    {
        if ($this->_publicKey === null) {
            /** @see Zend_Service_ReCaptcha_Exception */
            require_once 'Zend/Service/ReCaptcha/Exception.php';

            throw new Zend_Service_ReCaptcha_Exception('Missing public key');
        }

        $host = self::API_SERVER;

        if ($this->_params['ssl'] === true) {
            $host = self::API_SECURE_SERVER;
        }

        $htmlBreak = '<br>';
        $htmlInputClosing = '>';

        if ($this->_params['xhtml'] === true) {
            $htmlBreak = '<br />';
            $htmlInputClosing = '/>';
        }

        $errorPart = '';

        if (!empty($this->_params['error'])) {
            $errorPart = '&error=' . urlencode($this->_params['error']);
        }

        $reCaptchaOptions = '';

        if (!empty($this->_options)) {
            $encoded = Zend_Json::encode($this->_options);
            $reCaptchaOptions = <<<SCRIPT
<script type="text/javascript">
    var RecaptchaOptions = {$encoded};
</script>
SCRIPT;
        }

        $return = $reCaptchaOptions;
        $return .= <<<HTML
<script type="text/javascript"
   src="{$host}/challenge?k={$this->_publicKey}{$errorPart}">
</script>
HTML;
        $return .= <<<HTML
<noscript>
   <iframe src="{$host}/noscript?k={$this->_publicKey}{$errorPart}"
       height="300" width="500" frameborder="0"></iframe>{$htmlBreak}
   <textarea name="recaptcha_challenge_field" rows="3" cols="40">
   </textarea>
   <input type="hidden" name="recaptcha_response_field"
       value="manual_challenge"{$htmlInputClosing}
</noscript>
HTML;

        return $return;
    }

    /**
     * Post a solution to the verify server
     *
     * @param string $challengeField
     * @param string $responseField
     * @return Zend_Http_Response
     * @throws Zend_Service_ReCaptcha_Exception
     */
    protected function _post($challengeField, $responseField)
    {
        if ($this->_privateKey === null) {
            /** @see Zend_Service_ReCaptcha_Exception */
            require_once 'Zend/Service/ReCaptcha/Exception.php';

            throw new Zend_Service_ReCaptcha_Exception('Missing private key');
        }

        if ($this->_ip === null) {
            /** @see Zend_Service_ReCaptcha_Exception */
            require_once 'Zend/Service/ReCaptcha/Exception.php';

            throw new Zend_Service_ReCaptcha_Exception('Missing ip address');
        }

        if (empty($challengeField)) {
            /** @see Zend_Service_ReCaptcha_Exception */
            require_once 'Zend/Service/ReCaptcha/Exception.php';
            throw new Zend_Service_ReCaptcha_Exception('Missing challenge field');
        }

        if (empty($responseField)) {
            /** @see Zend_Service_ReCaptcha_Exception */
            require_once 'Zend/Service/ReCaptcha/Exception.php';

            throw new Zend_Service_ReCaptcha_Exception('Missing response field');
        }

        /* Fetch an instance of the http client */
        $httpClient = self::getHttpClient();

        $postParams = array('privatekey' => $this->_privateKey,
                            'remoteip'   => $this->_ip,
                            'challenge'  => $challengeField,
                            'response'   => $responseField);

        /* Make the POST and return the response */
        return $httpClient->setUri(self::VERIFY_SERVER)
                          ->setParameterPost($postParams)
                          ->request(Zend_Http_Client::POST);
    }

    /**
     * Verify the user input
     *
     * This method calls up the post method and returns a
     * Zend_Service_ReCaptcha_Response object.
     *
     * @param string $challengeField
     * @param string $responseField
     * @return Zend_Service_ReCaptcha_Response
     */
    public function verify($challengeField, $responseField)
    {
        $response = $this->_post($challengeField, $responseField);

        return new Zend_Service_ReCaptcha_Response(null, null, $response);
    }
}
StrikeIron/Exception.php000060400000002173150715514360011312 0ustar00<?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 StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 */

/** Zend_Exception */
require_once 'Zend/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_StrikeIron_Exception extends Zend_Exception
{}
StrikeIron/USAddressVerification.php000060400000003173150715514360013555 0ustar00<?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 StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: USAddressVerification.php 8064 2008-02-16 10:58:39Z thomas $
 */

/** Zend_Service_StrikeIron_Base */
require_once 'Zend/Service/StrikeIron/Base.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_StrikeIron_USAddressVerification extends Zend_Service_StrikeIron_Base
{
    /**
     * Configuration options
     * @param array
     */
    protected $_options = array('username' => null,
                                'password' => null,
                                'client'   => null,
                                'options'  => null,
                                'headers'  => null,
                                'wsdl'     => 'http://ws.strikeiron.com/zf1.StrikeIron/USAddressVerification4_0?WSDL');
}
StrikeIron/Base.php000060400000023110150715514360010220 0ustar00<?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 StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Base.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_StrikeIron_Decorator
 */
require_once 'Zend/Service/StrikeIron/Decorator.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_StrikeIron_Base
{
    /**
     * Configuration options
     * @param array
     */
    protected $_options = array('username' => null,
                                'password' => null,
                                'client'   => null,
                                'options'  => null,
                                'headers'  => null,
                                'wsdl'     => null);

    /**
     * Output headers returned by the last call to SOAPClient->__soapCall()
     * @param array
     */
    protected $_outputHeaders = array();

    /**
     * Class constructor
     *
     * @param  array  $options  Key/value pair options
     * @throws Zend_Service_StrikeIron_Exception
     */
    public function __construct($options = array())
    {
        if (!extension_loaded('soap')) {
            /**
             * @see Zend_Service_StrikeIron_Exception
             */
            require_once 'Zend/Service/StrikeIron/Exception.php';
            throw new Zend_Service_StrikeIron_Exception('SOAP extension is not enabled');
        }

        $this->_options  = array_merge($this->_options, $options);

        $this->_initSoapHeaders();
        $this->_initSoapClient();
    }

    /**
     * Proxy method calls to the SOAPClient instance, transforming method
     * calls and responses for convenience.
     *
     * @param  string  $method  Method name
     * @param  array   $params  Parameters for method
     * @return mixed            Result
     * @throws Zend_Service_StrikeIron_Exception
     */
    public function __call($method, $params)
    {
        // prepare method name and parameters for soap call
        list($method, $params) = $this->_transformCall($method, $params);
        $params = isset($params[0]) ? array($params[0]) : array();

        // make soap call, capturing the result and output headers
        try {
            $result = $this->_options['client']->__soapCall($method,
                                                            $params,
                                                            $this->_options['options'],
                                                            $this->_options['headers'],
                                                            $this->_outputHeaders);
        } catch (Exception $e) {
            $message = get_class($e) . ': ' . $e->getMessage();
            /**
             * @see Zend_Service_StrikeIron_Exception
             */
            require_once 'Zend/Service/StrikeIron/Exception.php';
            throw new Zend_Service_StrikeIron_Exception($message, $e->getCode());
        }

        // transform/decorate the result and return it
        $result = $this->_transformResult($result, $method, $params);
        return $result;
    }

    /**
     * Initialize the SOAPClient instance
     *
     * @return void
     */
    protected function _initSoapClient()
    {
        if (! isset($this->_options['options'])) {
            $this->_options['options'] = array();
        }

        if (! isset($this->_options['client'])) {
            $this->_options['client'] = new SoapClient($this->_options['wsdl'],
                                                       $this->_options['options']);
        }
    }

    /**
     * Initialize the headers to pass to SOAPClient->__soapCall()
     *
     * @return void
     * @throws Zend_Service_StrikeIron_Exception
     */
    protected function _initSoapHeaders()
    {
        // validate headers and check if LicenseInfo was given
        $foundLicenseInfo = false;
        if (isset($this->_options['headers'])) {
            if (! is_array($this->_options['headers'])) {
                $this->_options['headers'] = array($this->_options['headers']);
            }

            foreach ($this->_options['headers'] as $header) {
                if (! $header instanceof SoapHeader) {
                    /**
                     * @see Zend_Service_StrikeIron_Exception
                     */
                    require_once 'Zend/Service/StrikeIron/Exception.php';
                    throw new Zend_Service_StrikeIron_Exception('Header must be instance of SoapHeader');
                } else if ($header->name == 'LicenseInfo') {
                    $foundLicenseInfo = true;
                    break;
                }
            }
        } else {
            $this->_options['headers'] = array();
        }

        // add default LicenseInfo header if a custom one was not supplied
        if (! $foundLicenseInfo) {
            $this->_options['headers'][] = new SoapHeader('http://ws.strikeiron.com',
                            'LicenseInfo',
                            array('RegisteredUser' => array('UserID'   => $this->_options['username'],
                                                            'Password' => $this->_options['password'])));
        }
    }

    /**
     * Transform a method name or method parameters before sending them
     * to the remote service.  This can be useful for inflection or other
     * transforms to give the method call a more PHP-like interface.
     *
     * @see    __call()
     * @param  string  $method  Method name called from PHP
     * @param  mixed   $param   Parameters passed from PHP
     * @return array            [$method, $params] for SOAPClient->__soapCall()
     */
    protected function _transformCall($method, $params)
    {
        return array(ucfirst($method), $params);
    }

    /**
     * Transform the result returned from a method before returning
     * it to the PHP caller.  This can be useful for transforming
     * the SOAPClient returned result to be more PHP-like.
     *
     * The $method name and $params passed to the method are provided to
     * allow decisions to be made about how to transform the result based
     * on what was originally called.
     *
     * @see    __call()
     * @param  $result  Raw result returned from SOAPClient_>__soapCall()
     * @param  $method  Method name that was passed to SOAPClient->__soapCall()
     * @param  $params  Method parameters that were passed to SOAPClient->__soapCall()
     * @return mixed    Transformed result
     */
    protected function _transformResult($result, $method, $params)
    {
        $resultObjectName = "{$method}Result";
        if (isset($result->$resultObjectName)) {
            $result = $result->$resultObjectName;
        }
        if (is_object($result)) {
            $result = new Zend_Service_StrikeIron_Decorator($result, $resultObjectName);
        }
        return $result;
    }

    /**
     * Get the WSDL URL for this service.
     *
     * @return string
     */
    public function getWsdl()
    {
        return $this->_options['wsdl'];
    }

    /**
     * Get the SOAP Client instance for this service.
     */
    public function getSoapClient()
    {
        return $this->_options['client'];
    }

    /**
     * Get the StrikeIron output headers returned with the last method response.
     *
     * @return array
     */
    public function getLastOutputHeaders()
    {
        return $this->_outputHeaders;
    }

    /**
     * Get the StrikeIron subscription information for this service.
     * If any service method was recently called, the subscription info
     * should have been returned in the SOAP headers so it is cached
     * and returned from the cache.  Otherwise, the getRemainingHits()
     * method is called as a dummy to get the subscription info headers.
     *
     * @param  boolean  $now          Force a call to getRemainingHits instead of cache?
     * @param  string   $queryMethod  Method that will cause SubscriptionInfo header to be sent
     * @return Zend_Service_StrikeIron_Decorator  Decorated subscription info
     * @throws Zend_Service_StrikeIron_Exception
     */
    public function getSubscriptionInfo($now = false, $queryMethod = 'GetRemainingHits')
    {
        if ($now || empty($this->_outputHeaders['SubscriptionInfo'])) {
            $this->$queryMethod();
        }

        // capture subscription info if returned in output headers
        if (isset($this->_outputHeaders['SubscriptionInfo'])) {
            $info = (object)$this->_outputHeaders['SubscriptionInfo'];
            $subscriptionInfo = new Zend_Service_StrikeIron_Decorator($info, 'SubscriptionInfo');
        } else {
            $msg = 'No SubscriptionInfo header found in last output headers';
            /**
             * @see Zend_Service_StrikeIron_Exception
             */
            require_once 'Zend/Service/StrikeIron/Exception.php';
            throw new Zend_Service_StrikeIron_Exception($msg);
        }

        return $subscriptionInfo;
    }
}
StrikeIron/Decorator.php000060400000007764150715514360011311 0ustar00<?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 StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Decorator.php 8064 2008-02-16 10:58:39Z thomas $
 */

/**
 * Decorates a StrikeIron response object returned by the SOAP extension
 * to provide more a PHP-like interface.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_StrikeIron_Decorator
{
    /**
     * Name of the decorated object
     * @var null|string
     */
    protected $_name = null;

    /**
     * Object to decorate
     * @var object
     */
    protected $_object = null;

    /**
     * Class constructor
     *
     * @param object       $object  Object to decorate
     * @param null|string  $name    Name of the object
     */
    public function __construct($object, $name = null)
    {
        $this->_object = $object;
        $this->_name   = $name;
    }

    /**
     * Proxy property access to the decorated object, inflecting
     * the property name and decorating any child objects returned.
     * If the property is not found in the decorated object, return
     * NULL as a convenience feature to avoid notices.
     *
     * @param  string $property  Property name to retrieve
     * @return mixed             Value of property or NULL
     */
    public function __get($property)
    {
        $result = null;

        if (! isset($this->_object->$property)) {
            $property = $this->_inflect($property);
        }

        if (isset($this->_object->$property)) {
            $result = $this->_object->$property;
            $result = $this->_decorate($result);
        }
        return $result;
    }

    /**
     * Proxy method calls to the decorated object.  This will only
     * be used when the SOAPClient returns a custom PHP object via
     * its classmap option so no inflection is done.
     *
     * @param string  $method  Name of method called
     * @param array   $args    Arguments for method
     */
    public function __call($method, $args)
    {
        return call_user_func_array(array($this->_object, $method), $args);
    }

    /**
     * Inflect a property name from PHP-style to the result object's
     * style.  The default implementation here only inflects the case
     * of the first letter, e.g. from "fooBar" to "FooBar".
     *
     * @param  string $property  Property name to inflect
     * @return string            Inflected property name
     */
    protected function _inflect($property)
    {
        return ucfirst($property);
    }

    /**
     * Decorate a value returned by the result object.  The default
     * implementation here only decorates child objects.
     *
     * @param  mixed  $result  Value to decorate
     * @return mixed           Decorated result
     */
    protected function _decorate($result)
    {
        if (is_object($result)) {
            $result = new self($result);
        }
        return $result;
    }

    /**
     * Return the object being decorated
     *
     * @return object
     */
    public function getDecoratedObject()
    {
        return $this->_object;
    }

    /**
     * Return the name of the object being decorated
     *
     * @return null|string
     */
    public function getDecoratedObjectName()
    {
        return $this->_name;
    }
}
StrikeIron/ZipCodeInfo.php000060400000003140150715514360011520 0ustar00<?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 StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ZipCodeInfo.php 8064 2008-02-16 10:58:39Z thomas $
 */

/** Zend_Service_StrikeIron_Base */
require_once 'Zend/Service/StrikeIron/Base.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_StrikeIron_ZipCodeInfo extends Zend_Service_StrikeIron_Base
{
    /**
     * Configuration options
     * @param array
     */
    protected $_options = array('username' => null,
                                'password' => null,
                                'client'   => null,
                                'options'  => null,
                                'headers'  => null,
                                'wsdl'     => 'http://sdpws.strikeiron.com/zf1.StrikeIron/sdpZIPCodeInfo?WSDL');
}
StrikeIron/SalesUseTaxBasic.php000060400000003146150715514360012520 0ustar00<?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 StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SalesUseTaxBasic.php 8064 2008-02-16 10:58:39Z thomas $
 */

/** Zend_Service_StrikeIron_Base */
require_once 'Zend/Service/StrikeIron/Base.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_StrikeIron_SalesUseTaxBasic extends Zend_Service_StrikeIron_Base
{
    /**
     * Configuration options
     * @param array
     */
    protected $_options = array('username' => null,
                                'password' => null,
                                'client'   => null,
                                'options'  => null,
                                'headers'  => null,
                                'wsdl'     => 'http://ws.strikeiron.com/zf1.StrikeIron/taxdatabasic4?WSDL');
}
Simpy.php000060400000030724150715514360006367 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Simpy.php 10478 2008-07-26 17:29:07Z elazar $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @link       http://www.simpy.com/doc/api/rest/
 */
class Zend_Service_Simpy
{
    /**
     * Base URI to which API methods and parameters will be appended
     *
     * @var string
     */
    protected $_baseUri = 'http://simpy.com';

    /**
     * Zend_Service_Rest object
     *
     * @var Zend_Service_Rest
     */
    protected $_rest;

    /**
     * Constructs a new Simpy (free) REST API Client
     *
     * @param  string $username Username for the Simpy user account
     * @param  string $password Password for the Simpy user account
     * @return void
     */
    public function __construct($username, $password)
    {
        /**
         * @see Zend_Service_Rest
         */
        require_once 'Zend/Rest/Client.php';
        $this->_rest = new Zend_Rest_Client($this->_baseUri);
        $this->_rest->getHttpClient()
            ->setAuth($username, $password);
    }

    /**
     * Sends a request to the REST API service and does initial processing
     * on the response.
     *
     * @param  string       $op    Name of the operation for the request
     * @param  string|array $query Query data for the request (optional)
     * @throws Zend_Service_Exception
     * @return DOMDocument Parsed XML response
     */
    protected function _makeRequest($op, $query = null)
    {
        if ($query != null) {
            $query = array_diff($query, array_filter($query, 'is_null'));
        }

        $response = $this->_rest->restGet('/simpy/api/rest/' . $op . '.do', $query);

        if ($response->isSuccessful()) {
            $doc = new DOMDocument();
            $doc->loadXML($response->getBody());
            $xpath = new DOMXPath($doc);
            $list = $xpath->query('/status/code');

            if ($list->length > 0) {
                $code = $list->item(0)->nodeValue;

                if ($code != 0) {
                    $list = $xpath->query('/status/message');
                    $message = $list->item(0)->nodeValue;
                    /**
                     * @see Zend_Service_Exception
                     */
                    require_once 'Zend/Service/Exception.php';
                    throw new Zend_Service_Exception($message, $code);
                }
            }

            return $doc;
        }

        /**
         * @see Zend_Service_Exception
         */
        require_once 'Zend/Service/Exception.php';
        throw new Zend_Service_Exception('HTTP ' . $response->getStatus());
    }

    /**
     * Returns a list of all tags and their counts, ordered by count in
     * decreasing order
     *
     * @param  int $limit Limits the number of tags returned (optional)
     * @link   http://www.simpy.com/doc/api/rest/GetTags
     * @throws Zend_Service_Exception
     * @return Zend_Service_Simpy_TagSet
     */
    public function getTags($limit = null)
    {
        $query = array(
            'limit' => $limit
        );

        $doc = $this->_makeRequest('GetTags', $query);

        /**
         * @see Zend_Service_Simpy_TagSet
         */
        require_once 'Zend/Service/Simpy/TagSet.php';
        return new Zend_Service_Simpy_TagSet($doc);
    }

    /**
     * Removes a tag.
     *
     * @param  string $tag Tag to be removed
     * @link   http://www.simpy.com/doc/api/rest/RemoveTag
     * @return Zend_Service_Simpy Provides a fluent interface
     */
    public function removeTag($tag)
    {
        $query = array(
            'tag' => $tag
        );

        $this->_makeRequest('RemoveTag', $query);

        return $this;
    }

    /**
     * Renames a tag.
     *
     * @param  string $fromTag Tag to be renamed
     * @param  string $toTag   New tag name
     * @link   http://www.simpy.com/doc/api/rest/RenameTag
     * @return Zend_Service_Simpy Provides a fluent interface
     */
    public function renameTag($fromTag, $toTag)
    {
        $query = array(
            'fromTag' => $fromTag,
            'toTag' => $toTag
        );

        $this->_makeRequest('RenameTag', $query);

        return $this;
    }

    /**
     * Merges two tags into a new tag.
     *
     * @param  string $fromTag1 First tag to merge.
     * @param  string $fromTag2 Second tag to merge.
     * @param  string $toTag    Tag to merge the two tags into.
     * @link   http://www.simpy.com/doc/api/rest/MergeTags
     * @return Zend_Service_Simpy Provides a fluent interface
     */
    public function mergeTags($fromTag1, $fromTag2, $toTag)
    {
        $query = array(
            'fromTag1' => $fromTag1,
            'fromTag2' => $fromTag2,
            'toTag' => $toTag
        );

        $this->_makeRequest('MergeTags', $query);

        return $this;
    }

    /**
     * Splits a single tag into two separate tags.
     *
     * @param  string $tag    Tag to split
     * @param  string $toTag1 First tag to split into
     * @param  string $toTag2 Second tag to split into
     * @link   http://www.simpy.com/doc/api/rest/SplitTag
     * @return Zend_Service_Simpy Provides a fluent interface
     */
    public function splitTag($tag, $toTag1, $toTag2)
    {
        $query = array(
            'tag' => $tag,
            'toTag1' => $toTag1,
            'toTag2' => $toTag2
        );

        $this->_makeRequest('SplitTag', $query);

        return $this;
    }

    /**
     * Performs a query on existing links and returns the results or returns all
     * links if no particular query is specified (which should be used sparingly
     * to prevent overloading Simpy servers)
     *
     * @param  Zend_Service_Simpy_LinkQuery $q Query object to use (optional)
     * @return Zend_Service_Simpy_LinkSet
     */
    public function getLinks(Zend_Service_Simpy_LinkQuery $q = null)
    {
        if ($q != null) {
            $query = array(
                'q'          => $q->getQueryString(),
                'limit'      => $q->getLimit(),
                'date'       => $q->getDate(),
                'afterDate'  => $q->getAfterDate(),
                'beforeDate' => $q->getBeforeDate()
            );

            $doc = $this->_makeRequest('GetLinks', $query);
        } else {
            $doc = $this->_makeRequest('GetLinks');
        }

        /**
         * @see Zend_Service_Simpy_LinkSet
         */
        require_once 'Zend/Service/Simpy/LinkSet.php';
        return new Zend_Service_Simpy_LinkSet($doc);
    }

    /**
     * Saves a given link.
     *
     * @param  string $title       Title of the page to save
     * @param  string $href        URL of the page to save
     * @param  int    $accessType  ACCESSTYPE_PUBLIC or ACCESSTYPE_PRIVATE
     * @param  mixed  $tags        String containing a comma-separated list of
     *                             tags or array of strings containing tags
     *                             (optional)
     * @param  string $urlNickname Alternative custom title (optional)
     * @param  string $note        Free text note (optional)
     * @link   Zend_Service_Simpy::ACCESSTYPE_PUBLIC
     * @link   Zend_Service_Simpy::ACCESSTYPE_PRIVATE
     * @link   http://www.simpy.com/doc/api/rest/SaveLink
     * @return Zend_Service_Simpy Provides a fluent interface
     */
    public function saveLink($title, $href, $accessType, $tags = null, $urlNickname = null, $note = null)
    {
        if (is_array($tags)) {
            $tags = implode(',', $tags);
        }

        $query = array(
            'title'       => $title,
            'href'        => $href,
            'accessType'  => $accessType,
            'tags'        => $tags,
            'urlNickname' => $urlNickname,
            'note'        => $note
        );

        $this->_makeRequest('SaveLink', $query);

        return $this;
    }

    /**
     * Deletes a given link.
     *
     * @param  string $href URL of the bookmark to delete
     * @link   http://www.simpy.com/doc/api/rest/DeleteLink
     * @return Zend_Service_Simpy Provides a fluent interface
     */
    public function deleteLink($href)
    {
        $query = array(
            'href' => $href
        );

        $this->_makeRequest('DeleteLink', $query);

        return $this;
    }

    /**
     * Return a list of watchlists and their meta-data, including the number
     * of new links added to each watchlist since last login.
     *
     * @link   http://www.simpy.com/doc/api/rest/GetWatchlists
     * @return Zend_Service_Simpy_WatchlistSet
     */
    public function getWatchlists()
    {
        $doc = $this->_makeRequest('GetWatchlists');

        /**
         * @see Zend_Service_Simpy_WatchlistSet
         */
        require_once 'Zend/Service/Simpy/WatchlistSet.php';
        return new Zend_Service_Simpy_WatchlistSet($doc);
    }

    /**
     * Returns the meta-data for a given watchlist.
     *
     * @param  int $watchlistId ID of the watchlist to retrieve
     * @link   http://www.simpy.com/doc/api/rest/GetWatchlist
     * @return Zend_Service_Simpy_Watchlist
     */
    public function getWatchlist($watchlistId)
    {
        $query = array(
            'watchlistId' => $watchlistId
        );

        $doc = $this->_makeRequest('GetWatchlist', $query);

        /**
         * @see Zend_Service_Simpy_Watchlist
         */
        require_once 'Zend/Service/Simpy/Watchlist.php';
        return new Zend_Service_Simpy_Watchlist($doc->documentElement);
    }

    /**
     * Returns all notes in reverse chronological order by add date or by
     * rank.
     *
     * @param  string $q     Query string formatted using Simpy search syntax
     *                       and search fields (optional)
     * @param  int    $limit Limits the number notes returned (optional)
     * @link   http://www.simpy.com/doc/api/rest/GetNotes
     * @link   http://www.simpy.com/simpy/FAQ.do#searchSyntax
     * @link   http://www.simpy.com/simpy/FAQ.do#searchFieldsLinks
     * @return Zend_Service_Simpy_NoteSet
     */
    public function getNotes($q = null, $limit = null)
    {
        $query = array(
            'q'     => $q,
            'limit' => $limit
        );

        $doc = $this->_makeRequest('GetNotes', $query);

        /**
         * @see Zend_Service_Simpy_NoteSet
         */
        require_once 'Zend/Service/Simpy/NoteSet.php';
        return new Zend_Service_Simpy_NoteSet($doc);
    }

    /**
     * Saves a note.
     *
     * @param  string $title       Title of the note
     * @param  mixed  $tags        String containing a comma-separated list of
     *                             tags or array of strings containing tags
     *                             (optional)
     * @param  string $description Free-text note (optional)
     * @param  int    $noteId      Unique identifier for an existing note to
     *                             update (optional)
     * @link   http://www.simpy.com/doc/api/rest/SaveNote
     * @return Zend_Service_Simpy Provides a fluent interface
     */
    public function saveNote($title, $tags = null, $description = null, $noteId = null)
    {
        if (is_array($tags)) {
            $tags = implode(',', $tags);
        }

        $query = array(
            'title'       => $title,
            'tags'        => $tags,
            'description' => $description,
            'noteId'      => $noteId
        );

        $this->_makeRequest('SaveNote', $query);

        return $this;
    }

    /**
     * Deletes a given note.
     *
     * @param  int $noteId ID of the note to delete
     * @link   http://www.simpy.com/doc/api/rest/DeleteNote
     * @return Zend_Service_Simpy Provides a fluent interface
     */
    public function deleteNote($noteId)
    {
        $query = array(
            'noteId' => $noteId
        );

        $this->_makeRequest('DeleteNote', $query);

        return $this;
    }
}
ReCaptcha/MailHide.php000060400000021204150715514360010565 0ustar00<?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 ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** @see Zend_Service_ReCaptcha */
require_once 'Zend/Service/ReCaptcha.php';

/**
 * Zend_Service_ReCaptcha_MailHide
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Service_ReCaptcha_MailHide extends Zend_Service_ReCaptcha
{
    /**#@+
     * Encryption constants
     */
    const ENCRYPTION_MODE = MCRYPT_MODE_CBC;
    const ENCRYPTION_CIPHER = MCRYPT_RIJNDAEL_128;
    const ENCRYPTION_BLOCK_SIZE = 16;
    const ENCRYPTION_IV = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    /**#@-*/

    /**
     * Url to the mailhide server
     *
     * @var string
     */
    const MAILHIDE_SERVER = 'http://mailhide.recaptcha.net/d';

    /**
     * The email address to protect
     *
     * @var string
     */
    protected $_email = null;

    /**
     * Binary representation of the private key
     *
     * @var string
     */
    protected $_privateKeyPacked = null;

    /**
     * The local part of the email
     *
     * @var string
     */
    protected $_emailLocalPart = null;

    /**
     * The domain part of the email
     *
     * @var string
     */
    protected $_emailDomainPart = null;

    /**
     * Local constructor
     *
     * @param string $publicKey
     * @param string $privateKey
     * @param string $email
     * @param array|Zend_Config $options
     */
    public function __construct($publicKey = null, $privateKey = null, $email = null, $options = null)
    {
        /* Require the mcrypt extension to be loaded */
        $this->_requireMcrypt();

        /* If options is a Zend_Config object we want to convert it to an array so we can merge it with the default options */
        if ($options instanceof Zend_Config) {
            $options = $options->toArray();
        }

        /* Merge if needed */
        if (is_array($options)) {
            $options = array_merge($this->getDefaultOptions(), $options);
        } else {
            $options = $this->getDefaultOptions();
        }

        parent::__construct($publicKey, $privateKey, null, $options);

        if ($email !== null) {
            $this->setEmail($email);
        }
    }

    /**
     * See if the mcrypt extension is available
     *
     * @throws Zend_Service_ReCaptcha_MailHide_Exception
     */
    protected function _requireMcrypt()
    {
        if (!extension_loaded('mcrypt')) {
            /** @see Zend_Service_ReCaptcha_MailHide_Exception */
            require_once 'Zend/Service/ReCaptcha/MailHide/Exception.php';

            throw new Zend_Service_ReCaptcha_MailHide_Exception('Use of the Zend_Service_ReCaptcha_MailHide component requires the mcrypt extension to be enabled in PHP');
        }
    }

    /**
     * Serialize as string
     *
     * When the instance is used as a string it will display the email address. Since we can't
     * throw exceptions within this method we will trigger a user warning instead.
     *
     * @return string
     */
    public function __toString()
    {
        try {
            $return = $this->getHtml();
        } catch (Exception $e) {
            $return = '';
            trigger_error($e->getMessage(), E_USER_WARNING);
        }

        return $return;
    }

    /**
     * Get the default set of parameters
     *
     * @return array
     */
    public function getDefaultOptions()
    {
        return array(
            'linkTitle'      => 'Reveal this e-mail address',
            'linkHiddenText' => '...',
            'popupWidth'     => 500,
            'popupHeight'    => 300,
        );
    }

    /**
     * Override the setPrivateKey method
     *
     * Override the parent method to store a binary representation of the private key as well.
     *
     * @param string $privateKey
     * @return Zend_Service_ReCaptcha_MailHide
     */
    public function setPrivateKey($privateKey)
    {
        parent::setPrivateKey($privateKey);

        /* Pack the private key into a binary string */
        $this->_privateKeyPacked = pack('H*', $this->_privateKey);

        return $this;
    }

    /**
     * Set the email property
     *
     * This method will set the email property along with the local and domain parts
     *
     * @param string $email
     * @return Zend_Service_ReCaptcha_MailHide
     */
    public function setEmail($email)
    {
        $this->_email = $email;

        $emailParts = explode('@', $email, 2);

        /* Decide on how much of the local part we want to reveal */
        if (strlen($emailParts[0]) <= 4) {
            $emailParts[0] = substr($emailParts[0], 0, 1);
        } else if (strlen($emailParts[0]) <= 6) {
            $emailParts[0] = substr($emailParts[0], 0, 3);
        } else {
            $emailParts[0] = substr($emailParts[0], 0, 4);
        }

        $this->_emailLocalPart = $emailParts[0];
        $this->_emailDomainPart = $emailParts[1];

        return $this;
    }

    /**
     * Get the email property
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->_email;
    }

    /**
     * Get the local part of the email address
     *
     * @return string
     */
    public function getEmailLocalPart()
    {
        return $this->_emailLocalPart;
    }

    /**
     * Get the domain part of the email address
     *
     * @return string
     */
    public function getEmailDomainPart()
    {
        return $this->_emailDomainPart;
    }

    /**
     * Get the HTML code needed for the mail hide
     *
     * @param string $email
     * @return string
     * @throws Zend_Service_ReCaptcha_MailHide_Exception
     */
    public function getHtml($email = null)
    {
        if ($email !== null) {
            $this->setEmail($email);
        } else if ($this->_email === null) {
            /** @see Zend_Service_ReCaptcha_MailHide_Exception */
            require_once 'Zend/Service/ReCaptcha/MailHide/Exception.php';

            throw new Zend_Service_ReCaptcha_MailHide_Exception('Missing email address');
        }

        if ($this->_publicKey === null) {
            /** @see Zend_Service_ReCaptcha_MailHide_Exception */
            require_once 'Zend/Service/ReCaptcha/MailHide/Exception.php';

            throw new Zend_Service_ReCaptcha_MailHide_Exception('Missing public key');
        }

        if ($this->_privateKey === null) {
            /** @see Zend_Service_ReCaptcha_MailHide_Exception */
            require_once 'Zend/Service/ReCaptcha/MailHide/Exception.php';

            throw new Zend_Service_ReCaptcha_MailHide_Exception('Missing private key');
        }

        /* Generate the url */
        $url = $this->_getUrl();

        /* Genrate the HTML used to represent the email address */
        $html = htmlentities($this->_emailLocalPart) . '<a href="' . htmlentities($url) . '" onclick="window.open(\'' . htmlentities($url) . '\', \'\', \'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=' . $this->_options['popupWidth'] . ',height=' . $this->_options['popupHeight'] . '\'); return false;" title="' . $this->_options['linkTitle'] . '">' . $this->_options['linkHiddenText'] . '</a>@' . htmlentities($this->_emailDomainPart);

        return $html;
    }

    /**
     * Get the url used on the "hidden" part of the email address
     *
     * @return string
     */
    protected function _getUrl()
    {
        /* Figure out how much we need to pad the email */
        $numPad = self::ENCRYPTION_BLOCK_SIZE - (strlen($this->_email) % self::ENCRYPTION_BLOCK_SIZE);

        /* Pad the email */
        $emailPadded = str_pad($this->_email, strlen($this->_email) + $numPad, chr($numPad));

        /* Encrypt the email */
        $emailEncrypted = mcrypt_encrypt(self::ENCRYPTION_CIPHER, $this->_privateKeyPacked, $emailPadded, self::ENCRYPTION_MODE, self::ENCRYPTION_IV);

        /* Return the url */
        return self::MAILHIDE_SERVER . '?k=' . $this->_publicKey . '&c=' . strtr(base64_encode($emailEncrypted), '+/', '-_');
    }
}ReCaptcha/Response.php000060400000007177150715514360010724 0ustar00<?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 ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Zend_Service_ReCaptcha_Response
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Service_ReCaptcha_Response
{
    /**
     * Status
     *
     * true if the response is valid or false otherwise
     *
     * @var boolean
     */
    protected $_status = null;

    /**
     * Error code
     *
     * The error code if the status is false. The different error codes can be found in the
     * recaptcha API docs.
     *
     * @var string
     */
    protected $_errorCode = null;

    /**
     * Class constructor used to construct a response
     *
     * @param string $status
     * @param string $errorCode
     * @param Zend_Http_Response $httpResponse If this is set the content will override $status and $errorCode
     */
    public function __construct($status = null, $errorCode = null, Zend_Http_Response $httpResponse = null)
    {
        if ($status !== null) {
            $this->setStatus($status);
        }

        if ($errorCode !== null) {
            $this->setErrorCode($errorCode);
        }

        if ($httpResponse !== null) {
            $this->setFromHttpResponse($httpResponse);
        }
    }

    /**
     * Set the status
     *
     * @param string $status
     * @return Zend_Service_ReCaptcha_Response
     */
    public function setStatus($status)
    {
        if ($status === 'true') {
            $this->_status = true;
        } else {
            $this->_status = false;
        }

        return $this;
    }

    /**
     * Get the status
     *
     * @return boolean
     */
    public function getStatus()
    {
        return $this->_status;
    }

    /**
     * Alias for getStatus()
     *
     * @return boolean
     */
    public function isValid()
    {
        return $this->getStatus();
    }

    /**
     * Set the error code
     *
     * @param string $errorCode
     * @return Zend_Service_ReCaptcha_Response
     */
    public function setErrorCode($errorCode)
    {
        $this->_errorCode = $errorCode;

        return $this;
    }

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

    /**
     * Populate this instance based on a Zend_Http_Response object
     *
     * @param Zend_Http_Response $response
     * @return Zend_Service_ReCaptcha_Response
     */
    public function setFromHttpResponse(Zend_Http_Response $response)
    {
        $body = $response->getBody();

        $parts = explode("\n", $body, 2);

        if (count($parts) !== 2) {
            $status = 'false';
            $errorCode = '';
        } else {
            list($status, $errorCode) = $parts;
        }

        $this->setStatus($status);
        $this->setErrorCode($errorCode);

        return $this;
    }
}ReCaptcha/Exception.php000060400000002162150715514360011051 0ustar00<?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 ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** @see Zend_Exception */
require_once 'Zend/Exception.php';

/**
 * Zend_Service_ReCaptcha_Exception
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Service_ReCaptcha_Exception extends Zend_Exception
{}ReCaptcha/MailHide/Exception.php000060400000002204150715514360012522 0ustar00<?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 ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** @see Zend_Exception */
require_once 'Zend/Exception.php';

/**
 * Zend_Service_ReCaptcha_MailHide_Exception
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Service_ReCaptcha_MailHide_Exception extends Zend_Exception
{}Nirvanix/Namespace/Imfs.php000060400000007421150715514360011654 0ustar00<?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 Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Service_Nirvanix_Namespace_Base
 */
require_once 'Zend/Service/Nirvanix/Namespace/Base.php'; 
 
/**
 * Namespace proxy with additional convenience methods for the IMFS namespace.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Nirvanix_Namespace_Imfs extends Zend_Service_Nirvanix_Namespace_Base
{
    /**
     * Convenience function to get the contents of a file on
     * the Nirvanix IMFS.  Analog to PHP's file_get_contents().
     *
     * @param  string  $filePath    Remote path and filename
     * @param  integer $expiration  Number of seconds that Nirvanix
     *                              make the file available for download.
     * @return string               Contents of file  
     */
    public function getContents($filePath, $expiration = 3600)
    {
        // get url to download the file
        $params = array('filePath'   => $filePath,
                        'expiration' => $expiration);
        $resp = $this->getOptimalUrls($params);
        $url = (string)$resp->Download->DownloadURL;

        // download the file
        $this->_httpClient->resetParameters();
        $this->_httpClient->setUri($url);
        $resp = $this->_httpClient->request(Zend_Http_Client::GET);

        return $resp->getBody();
    }

    /**
     * Convenience function to put the contents of a string into
     * the Nirvanix IMFS.  Analog to PHP's file_put_contents().
     *
     * @param  string  $filePath    Remote path and filename
     * @param  integer $data        Data to store in the file
     * @param  string  $mimeType    Mime type of data
     * @return Zend_Service_Nirvanix_Response
     */
    public function putContents($filePath, $data, $mimeType = null)
    {
        // get storage node for upload
        $params = array('sizeBytes' => strlen($data));
        $resp = $this->getStorageNode($params);
        $host        = (string)$resp->GetStorageNode->UploadHost;
        $uploadToken = (string)$resp->GetStorageNode->UploadToken;

        // http upload data into remote file
        $this->_httpClient->resetParameters();
        $this->_httpClient->setUri("http://{$host}/Upload.ashx");
        $this->_httpClient->setParameterPost('uploadToken', $uploadToken);
        $this->_httpClient->setParameterPost('destFolderPath', dirname($filePath));
        $this->_httpClient->setFileUpload(basename($filePath), 'uploadFile', $data, $mimeType);
        $response = $this->_httpClient->request(Zend_Http_Client::POST);

        return new Zend_Service_Nirvanix_Response($response->getBody());
    }
    
    /**
     * Convenience function to remove a file from the Nirvanix IMFS.
     * Analog to PHP's unlink().
     *
     * @param  string  $filePath  Remove path and filename
     * @return Zend_Service_Nirvanix_Response
     */
    public function unlink($filePath)
    {
        $params = array('filePath' => $filePath);
        return $this->deleteFiles($params);
    }

}Nirvanix/Namespace/Base.php000060400000012556150715514360011635 0ustar00<?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 Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
 
/**
 * @see Zend_Http_Client
 */
require_once 'Zend/Http/Client.php';

/**
 * @see Zend_Service_Nirvanix_Response
 */
require_once 'Zend/Service/Nirvanix/Response.php';

/**
 * The Nirvanix web services are split into namespaces.  This is a proxy class
 * representing one namespace.  It allows calls to the namespace to be made by
 * PHP object calls rather than by having to construct HTTP client requests.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Nirvanix_Namespace_Base
{
    /**
     * HTTP client instance that will be used to make calls to
     * the Nirvanix web services.
     * @var Zend_Http_Client
     */
    protected $_httpClient;
    
    /**
     * Host to use for calls to this Nirvanix namespace.  It is possible
     * that the user will wish to use different hosts for different namespaces.
     * @var string
     */
    protected $_host = 'http://services.nirvanix.com';

    /**
     * Name of this namespace as used in the URL.
     * @var string
     */
    protected $_namespace = '';

    /**
     * Defaults for POST parameters.  When a request to the service is to be
     * made, the POST parameters are merged into these.  This is a convenience
     * feature so parameters that are repeatedly required like sessionToken
     * do not need to be supplied again and again by the user. 
     *
     * @param array
     */
    protected $_defaults = array();    

    /**
     * Class constructor.  
     *
     * @param  $options  array  Options and dependency injection
     */
    public function __construct($options = array())
    {   
        if (isset($options['baseUrl'])) {
            $this->_host = $options['baseUrl'];
        }

        if (isset($options['namespace'])) {
            $this->_namespace = $options['namespace'];
        }

        if (isset($options['defaults'])) {
            $this->_defaults = $options['defaults'];
        }

        if (! isset($options['httpClient'])) {
            $options['httpClient'] = new Zend_Http_Client();
        }
        $this->_httpClient = $options['httpClient'];
    }
    
    /**
     * When a method call is made against this proxy, convert it to
     * an HTTP request to make against the Nirvanix REST service.  
     *
     * $imfs->DeleteFiles(array('filePath' => 'foo'));
     *
     * Assuming this object was proxying the IMFS namespace, the 
     * method call above would call the DeleteFiles command.  The
     * POST parameters would be filePath, merged with the 
     * $this->_defaults (containing the sessionToken).
     *
     * @param  string  $methodName  Name of the command to call 
     *                              on this namespace.
     * @param  array   $args        Only the first is used and it must be
     *                              an array.  It contains the POST params.
     *
     * @return Zend_Service_Nirvanix_Response
     */
    public function __call($methodName, $args)
    {
        $uri = $this->_makeUri($methodName);
        $this->_httpClient->setUri($uri);

        if (!isset($args[0]) || !is_array($args[0])) { 
            $args[0] = array();
        }

        $params = array_merge($this->_defaults, $args[0]);
        $this->_httpClient->resetParameters();
        $this->_httpClient->setParameterPost($params);

        $httpResponse = $this->_httpClient->request(Zend_Http_Client::POST);
        return $this->_wrapResponse($httpResponse);
    }

    /**
     * Return the HTTP client used for this namespace.  This is useful
     * for inspecting the last request or directly interacting with the
     * HTTP client.
     *
     * @return Zend_Http_Client
     */
    public function getHttpClient()
    {
        return $this->_httpClient;
    }

    /**
     * Make a complete URI from an RPC method name.  All Nirvanix REST
     * service URIs use the same format.
     * 
     * @param  string  $methodName  RPC method name
     * @return string    
     */
    protected function _makeUri($methodName)
    {
        $methodName = ucfirst($methodName);
        return "{$this->_host}/ws/{$this->_namespace}/{$methodName}.ashx";
    }
    
    /**
     * All Nirvanix REST service calls return an XML payload.  This method
     * makes a Zend_Service_Nirvanix_Response from that XML payload.  
     *
     * @param  Zend_Http_Response  $httpResponse  Raw response from Nirvanix
     * @return Zend_Service_Nirvanix_Response     Wrapped response
     */
    protected function _wrapResponse($httpResponse)
    {
        return new Zend_Service_Nirvanix_Response($httpResponse->getBody());
    }
}Nirvanix/Exception.php000060400000002072150715514360011015 0ustar00<?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 Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
 
/**
 * @see Zend_Exception
 */
require_once 'Zend/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Nirvanix_Exception extends Zend_Exception
{}
Nirvanix/Response.php000060400000007070150715514360010660 0ustar00<?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 Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * This class decorates a SimpleXMLElement parsed from a Nirvanix web service
 * response.  It is primarily exists to provide a convenience feature that 
 * throws an exception when <ResponseCode> contains an error.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Nirvanix_Response
{
    /**
     * SimpleXMLElement parsed from Nirvanix web service response.
     * 
     * @var SimpleXMLElement
     */
    protected $_sxml;
    
    /**
     * Class constructor.  Parse the XML response from a Nirvanix method
     * call into a decorated SimpleXMLElement element.
     *
     * @param string $xml  XML response string from Nirvanix
     * @throws Zend_Service_Nirvanix_Exception
     */
    public function __construct($xml)
    {
        $this->_sxml = @simplexml_load_string($xml);

        if (! $this->_sxml instanceof SimpleXMLElement) {
            $this->_throwException("XML could not be parsed from response: $xml");
        }

        $name = $this->_sxml->getName();
        if ($name != 'Response') {
            $this->_throwException("Expected XML element Response, got $name");
        }
        
        $code = (int)$this->_sxml->ResponseCode;
        if ($code != 0) {
            $msg = (string)$this->_sxml->ErrorMessage;
            $this->_throwException($msg, $code);
        }
    }

    /**
     * Return the SimpleXMLElement representing this response
     * for direct access.
     *
     * @return SimpleXMLElement
     */
    public function getSxml()
    {
        return $this->_sxml;
    }

    /**
     * Delegate undefined properties to the decorated SimpleXMLElement.
     *
     * @param  string  $offset  Undefined property name
     * @return mixed
     */
    public function __get($offset) 
    {
        return $this->_sxml->$offset;
    }

    /**
     * Delegate undefined methods to the decorated SimpleXMLElement.
     *
     * @param  string  $offset  Underfined method name
     * @param  array   $args    Method arguments
     * @return mixed
     */
    public function __call($method, $args)
    {
        return call_user_func_array(array($this->_sxml, $method), $args);
    }

    /**
     * Throw an exception.  This method exists to only contain the
     * lazy-require() of the exception class.
     * 
     * @param  string   $message  Error message
     * @param  integer  $code     Error code
     * @throws Zend_Service_Nirvanix_Exception
     * @return void
     */
    protected function _throwException($message, $code = null)
    {
        /**
         * @see Zend_Service_Nirvanix_Exception
         */
        require_once 'Zend/Service/Nirvanix/Exception.php';        

        throw new Zend_Service_Nirvanix_Exception($message, $code);
    }

}
SlideShare.php000060400000045244150715514360007314 0ustar00<?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 SlideShare
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SlideShare.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_Http_Client
 */
require_once 'Zend/Http/Client.php';

/**
 * Zend_Cache
 */
require_once 'Zend/Cache.php';

/**
 * Zend_Service_SlideShare_Exception
 */
require_once 'Zend/Service/SlideShare/Exception.php';

/**
 * Zend_Service_SlideShare_SlideShow
 */
require_once 'Zend/Service/SlideShare/SlideShow.php';

/**
 * The Zend_Service_SlideShare component is used to interface with the
 * slideshare.net web server to retrieve slide shows hosted on the web site for
 * display or other processing.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage SlideShare
 * @throws     Zend_Service_SlideShare_Exception
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_SlideShare
{

    /**
     * Web service result code mapping
     */
    const SERVICE_ERROR_BAD_APIKEY       = 1;
    const SERVICE_ERROR_BAD_AUTH         = 2;
    const SERVICE_ERROR_MISSING_TITLE    = 3;
    const SERVICE_ERROR_MISSING_FILE     = 4;
    const SERVICE_ERROR_EMPTY_TITLE      = 5;
    const SERVICE_ERROR_NOT_SOURCEOBJ    = 6;
    const SERVICE_ERROR_INVALID_EXT      = 7;
    const SERVICE_ERROR_FILE_TOO_BIG     = 8;
    const SERVICE_ERROR_SHOW_NOT_FOUND   = 9;
    const SERVICE_ERROR_USER_NOT_FOUND   = 10;
    const SERVICE_ERROR_GROUP_NOT_FOUND  = 11;
    const SERVICE_ERROR_MISSING_TAG      = 12;
    const SERVICE_ERROR_DAILY_LIMIT      = 99;
    const SERVICE_ERROR_ACCOUNT_BLOCKED  = 100;

    /**
     * Slide share Web service communication URIs
     */
    const SERVICE_UPLOAD_URI                  = 'http://www.slideshare.net/api/1/upload_slideshow';
    const SERVICE_GET_SHOW_URI                = 'http://www.slideshare.net/api/1/get_slideshow';
    const SERVICE_GET_SHOW_BY_USER_URI        = 'http://www.slideshare.net/api/1/get_slideshow_by_user';
    const SERVICE_GET_SHOW_BY_TAG_URI         = 'http://www.slideshare.net/api/1/get_slideshow_by_tag';
    const SERVICE_GET_SHOW_BY_GROUP_URI       = 'http://www.slideshare.net/api/1/get_slideshows_from_group';

    /**
     * The MIME type of Slideshow files
     *
     */
    const POWERPOINT_MIME_TYPE    = "application/vnd.ms-powerpoint";

    /**
     * The API key to use in requests
     *
     * @var string The API key
     */
    protected $_apiKey;

    /**
     * The shared secret to use in requests
     *
     * @var string the Shared secret
     */
    protected $_sharedSecret;

    /**
     * The username to use in requests
     *
     * @var string the username
     */
    protected $_username;

    /**
     * The password to use in requests
     *
     * @var string the password
     */
    protected $_password;

    /**
     * The HTTP Client object to use to perform requests
     *
     * @var Zend_Http_Client
     */
    protected $_httpclient;

    /**
     * The Cache object to use to perform caching
     *
     * @var Zend_Cache_Core
     */
    protected $_cacheobject;

    /**
     * Sets the Zend_Http_Client object to use in requests. If not provided a default will
     * be used.
     *
     * @param Zend_Http_Client $client The HTTP client instance to use
     * @return Zend_Service_SlideShare
     */
    public function setHttpClient(Zend_Http_Client $client)
    {
        $this->_httpclient = $client;
        return $this;
    }

    /**
     * Returns the instance of the Zend_Http_Client which will be used. Creates an instance
     * of Zend_Http_Client if no previous client was set.
     *
     * @return Zend_Http_Client The HTTP client which will be used
     */
    public function getHttpClient()
    {

        if(!($this->_httpclient instanceof Zend_Http_Client)) {
            $client = new Zend_Http_Client();
            $client->setConfig(array('maxredirects' => 2,
                                     'timeout' => 5));

            $this->setHttpClient($client);
        }

        $this->_httpclient->resetParameters();
        return $this->_httpclient;
    }

    /**
     * Sets the Zend_Cache object to use to cache the results of API queries
     *
     * @param Zend_Cache_Core $cacheobject The Zend_Cache object used
     * @return Zend_Service_SlideShare
     */
    public function setCacheObject(Zend_Cache_Core $cacheobject)
    {
        $this->_cacheobject = $cacheobject;
        return $this;
    }

    /**
     * Gets the Zend_Cache object which will be used to cache API queries. If no cache object
     * was previously set the the default will be used (Filesystem caching in /tmp with a life
     * time of 43200 seconds)
     *
     * @return Zend_Cache_Core The object used in caching
     */
    public function getCacheObject()
    {

        if(!($this->_cacheobject instanceof Zend_Cache_Core)) {
            $cache = Zend_Cache::factory('Core', 'File', array('lifetime' => 43200,
                                                               'automatic_serialization' => true),
                                                         array('cache_dir' => '/tmp'));

            $this->setCacheObject($cache);
        }

        return $this->_cacheobject;
    }

    /**
     * Returns the user name used for API calls
     *
     * @return string The username
     */
    public function getUserName()
    {
        return $this->_username;
    }

    /**
     * Sets the user name to use for API calls
     *
     * @param string $un The username to use
     * @return Zend_Service_SlideShare
     */
    public function setUserName($un)
    {
        $this->_username = $un;
        return $this;
    }

    /**
     * Gets the password to use in API calls
     *
     * @return string the password to use in API calls
     */
    public function getPassword()
    {
        return $this->_password;
    }

    /**
     * Sets the password to use in API calls
     *
     * @param string $pw The password to use
     * @return Zend_Service_SlideShare
     */
    public function setPassword($pw)
    {
        $this->_password = (string)$pw;
        return $this;
    }

    /**
     * Gets the API key to be used in making API calls
     *
     * @return string the API Key
     */
    public function getApiKey()
    {
        return $this->_apiKey;
    }

    /**
     * Sets the API key to be used in making API calls
     *
     * @param string $key The API key to use
     * @return Zend_Service_SlideShare
     */
    public function setApiKey($key)
    {
        $this->_apiKey = (string)$key;
        return $this;
    }

    /**
     * Gets the shared secret used in making API calls
     *
     * @return string the Shared secret
     */
    public function getSharedSecret()
    {
        return $this->_sharedSecret;
    }

    /**
     * Sets the shared secret used in making API calls
     *
     * @param string $secret the shared secret
     * @return Zend_Service_SlideShare
     */
    public function setSharedSecret($secret)
    {
        $this->_sharedSecret = (string)$secret;
        return $this;
    }

    /**
     * The Constructor
     *
     * @param string $apikey The API key
     * @param string $sharedSecret The shared secret
     * @param string $username The username
     * @param string $password The password
     */
    public function __construct($apikey, $sharedSecret, $username = null, $password = null)
    {
        $this->setApiKey($apikey)
             ->setSharedSecret($sharedSecret)
             ->setUserName($username)
             ->setPassword($password);

        $this->_httpclient = new Zend_Http_Client();
    }

    /**
     * Uploads the specified Slide show the the server
     *
     * @param Zend_Service_SlideShare_SlideShow $ss The slide show object representing the slide show to upload
     * @param boolean $make_src_public Determines if the the slide show's source file is public or not upon upload
     * @return Zend_Service_SlideShare_SlideShow The passed Slide show object, with the new assigned ID provided
     */
    public function uploadSlideShow(Zend_Service_SlideShare_SlideShow $ss, $make_src_public = true)
    {

        $timestamp = time();

        $params = array('api_key' => $this->getApiKey(),
                        'ts' => $timestamp,
                        'hash' => sha1($this->getSharedSecret().$timestamp),
                        'username' => $this->getUserName(),
                        'password' => $this->getPassword(),
                        'slideshow_title' => $ss->getTitle());

        $description = $ss->getDescription();
        $tags = $ss->getTags();

        $filename = $ss->getFilename();

        if(!file_exists($filename) || !is_readable($filename)) {
            throw new Zend_Service_SlideShare_Exception("Specified Slideshow for upload not found or unreadable");
        }

        if(!empty($description)) {
            $params['slideshow_description'] = $description;
        } else {
            $params['slideshow_description'] = "";
        }

        if(!empty($tags)) {
            $tmp = array();
            foreach($tags as $tag) {
                $tmp[] = "\"$tag\"";
            }
            $params['slideshow_tags'] = implode(' ', $tmp);
        } else {
            $params['slideshow_tags'] = "";
        }


        $client = $this->getHttpClient();
        $client->setUri(self::SERVICE_UPLOAD_URI);
        $client->setParameterPost($params);
        $client->setFileUpload($filename, "slideshow_srcfile");

        try {
            $response = $client->request('POST');
        } catch(Zend_Http_Client_Exception $e) {
            throw new Zend_Service_SlideShare_Exception("Service Request Failed: {$e->getMessage()}");
        }

        $sxe = simplexml_load_string($response->getBody());

        if($sxe->getName() == "SlideShareServiceError") {
            $message = (string)$sxe->Message[0];
            list($code, $error_str) = explode(':', $message);
            throw new Zend_Service_SlideShare_Exception(trim($error_str), $code);
        }

        if(!$sxe->getName() == "SlideShowUploaded") {
            throw new Zend_Service_SlideShare_Exception("Unknown XML Respons Received");
        }

        $ss->setId((int)(string)$sxe->SlideShowID);

        return $ss;
    }

    /**
     * Retrieves a slide show's information based on slide show ID
     *
     * @param int $ss_id The slide show ID
     * @return Zend_Service_SlideShare_SlideShow the Slideshow object
     */
    public function getSlideShow($ss_id)
    {
        $timestamp = time();

        $params = array('api_key' => $this->getApiKey(),
                        'ts' => $timestamp,
                        'hash' => sha1($this->getSharedSecret().$timestamp),
                        'slideshow_id' => $ss_id);

        $cache = $this->getCacheObject();

        $cache_key = md5("__zendslideshare_cache_$ss_id");

        if(!$retval = $cache->load($cache_key)) {
            $client = $this->getHttpClient();

            $client->setUri(self::SERVICE_GET_SHOW_URI);
            $client->setParameterPost($params);

            try {
                $response = $client->request('POST');
            } catch(Zend_Http_Client_Exception $e) {
                throw new Zend_Service_SlideShare_Exception("Service Request Failed: {$e->getMessage()}");
            }

            $sxe = simplexml_load_string($response->getBody());

            if($sxe->getName() == "SlideShareServiceError") {
                $message = (string)$sxe->Message[0];
                list($code, $error_str) = explode(':', $message);
                throw new Zend_Service_SlideShare_Exception(trim($error_str), $code);
            }

            if(!$sxe->getName() == 'Slideshows') {
                throw new Zend_Service_SlideShare_Exception('Unknown XML Repsonse Received');
            }

            $retval = $this->_slideShowNodeToObject(clone $sxe->Slideshow[0]);

            $cache->save($retval, $cache_key);
        }

        return $retval;
    }

    /**
     * Retrieves an array of slide shows for a given username
     *
     * @param string $username The username to retrieve slide shows from
     * @param int $offset The offset of the list to start retrieving from
     * @param int $limit The maximum number of slide shows to retrieve
     * @return array An array of Zend_Service_SlideShare_SlideShow objects
     */
    public function getSlideShowsByUsername($username, $offset = null, $limit = null)
    {
        return $this->_getSlideShowsByType('username_for', $username, $offset, $limit);
    }

    /**
     * Retrieves an array of slide shows based on tag
     *
     * @param string $tag The tag to retrieve slide shows with
     * @param int $offset The offset of the list to start retrieving from
     * @param int $limit The maximum number of slide shows to retrieve
     * @return array An array of Zend_Service_SlideShare_SlideShow objects
     */
    public function getSlideShowsByTag($tag, $offset = null, $limit = null)
    {

        if(is_array($tag)) {
            $tmp = array();
            foreach($tag as $t) {
                $tmp[] = "\"$t\"";
            }

            $tag = implode(" ", $tmp);
        }

        return $this->_getSlideShowsByType('tag', $tag, $offset, $limit);
    }

    /**
     * Retrieves an array of slide shows based on group name
     *
     * @param string $group The group name to retrieve slide shows for
     * @param int $offset The offset of the list to start retrieving from
     * @param int $limit The maximum number of slide shows to retrieve
     * @return array An array of Zend_Service_SlideShare_SlideShow objects
     */
    public function getSlideShowsByGroup($group, $offset = null, $limit = null)
    {
        return $this->_getSlideShowsByType('group_name', $group, $offset, $limit);
    }

    /**
     * Retrieves Zend_Service_SlideShare_SlideShow object arrays based on the type of
     * list desired
     *
     * @param string $key The type of slide show object to retrieve
     * @param string $value The specific search query for the slide show type to look up
     * @param int $offset The offset of the list to start retrieving from
     * @param int $limit The maximum number of slide shows to retrieve
     * @return array An array of Zend_Service_SlideShare_SlideShow objects
     */
    protected function _getSlideShowsByType($key, $value, $offset = null, $limit = null)
    {

        $key = strtolower($key);

        switch($key) {
            case 'username_for':
                $responseTag = 'User';
                $queryUri = self::SERVICE_GET_SHOW_BY_USER_URI;
                break;
            case 'group_name':
                $responseTag = 'Group';
                $queryUri = self::SERVICE_GET_SHOW_BY_GROUP_URI;
                break;
            case 'tag':
                $responseTag = 'Tag';
                $queryUri = self::SERVICE_GET_SHOW_BY_TAG_URI;
                break;
            default:
                throw new Zend_Service_SlideShare_Exception("Invalid SlideShare Query");
        }

        $timestamp = time();

        $params = array('api_key' => $this->getApiKey(),
                        'ts' => $timestamp,
                        'hash' => sha1($this->getSharedSecret().$timestamp),
                        $key => $value);

        if(!is_null($offset)) {
            $params['offset'] = (int)$offset;
        }

        if(!is_null($limit)) {
            $params['limit'] = (int)$limit;
        }

        $cache = $this->getCacheObject();

        $cache_key = md5($key.$value.$offset.$limit);

        if(!$retval = $cache->load($cache_key)) {

            $client = $this->getHttpClient();

            $client->setUri($queryUri);
            $client->setParameterPost($params);

            try {
                $response = $client->request('POST');
            } catch(Zend_Http_Client_Exception $e) {
                throw new Zend_Service_SlideShare_Exception("Service Request Failed: {$e->getMessage()}");
            }

            $sxe = simplexml_load_string($response->getBody());

            if($sxe->getName() == "SlideShareServiceError") {
                $message = (string)$sxe->Message[0];
                list($code, $error_str) = explode(':', $message);
                throw new Zend_Service_SlideShare_Exception(trim($error_str), $code);
            }

            if(!$sxe->getName() == $responseTag) {
                throw new Zend_Service_SlideShare_Exception('Unknown or Invalid XML Repsonse Received');
            }

            $retval = array();

            foreach($sxe->children() as $node) {
                if($node->getName() == 'Slideshow') {
                    $retval[] = $this->_slideShowNodeToObject($node);
                }
            }

            $cache->save($retval, $cache_key);
        }

        return $retval;
    }

    /**
     * Converts a SimpleXMLElement object representing a response from the service
     * into a Zend_Service_SlideShare_SlideShow object
     *
     * @param SimpleXMLElement $node The input XML from the slideshare.net service
     * @return Zend_Service_SlideShare_SlideShow The resulting object
     */
    protected function _slideShowNodeToObject(SimpleXMLElement $node)
    {

        if($node->getName() == 'Slideshow') {

            $ss = new Zend_Service_SlideShare_SlideShow();

            $ss->setId((string)$node->ID);
            $ss->setDescription((string)$node->Description);
            $ss->setEmbedCode((string)$node->EmbedCode);
            $ss->setNumViews((string)$node->Views);
            $ss->setPermaLink((string)$node->Permalink);
            $ss->setStatus((string)$node->Status);
            $ss->setStatusDescription((string)$node->StatusDescription);

            foreach(explode(",", (string)$node->Tags) as $tag) {

                if(!in_array($tag, $ss->getTags())) {
                    $ss->addTag($tag);
                }
            }

            $ss->setThumbnailUrl((string)$node->Thumbnail);
            $ss->setTitle((string)$node->Title);
            $ss->setLocation((string)$node->Location);
            $ss->setTranscript((string)$node->Transcript);

            return $ss;

        }

        throw new Zend_Service_SlideShare_Exception("Was not provided the expected XML Node for processing");
    }
}Abstract.php000060400000003526150715514360007031 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Abstract.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Zend_Http_Client
 */
require_once 'Zend/Http/Client.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Service_Abstract
{
    /**
     * HTTP Client used to query all web services
     *
     * @var Zend_Http_Client
     */
    protected static $_httpClient = null;


    /**
     * Sets the HTTP client object to use for retrieving the feeds.  If none
     * is set, the default Zend_Http_Client will be used.
     *
     * @param Zend_Http_Client $httpClient
     */
    final public static function setHttpClient(Zend_Http_Client $httpClient)
    {
        self::$_httpClient = $httpClient;
    }


    /**
     * Gets the HTTP client object.
     *
     * @return Zend_Http_Client
     */
    final public static function getHttpClient()
    {
        if (!self::$_httpClient instanceof Zend_Http_Client) {
            self::$_httpClient = new Zend_Http_Client();
        }

        return self::$_httpClient;
    }
}

Delicious.php000060400000043367150715514360007215 0ustar00<?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 Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Delicious.php 9638 2008-06-08 15:58:11Z ghacek $
 */


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

/**
 * @see Zend_Json_Decoder
 */
require_once 'Zend/Json/Decoder.php';

/**
 * @see Zend_Service_Delicious_SimplePost
 */
require_once 'Zend/Service/Delicious/SimplePost.php';

/**
 * @see Zend_Service_Delicious_Post
 */
require_once 'Zend/Service/Delicious/Post.php';

/**
 * @see Zend_Service_Delicious_PostList
 */
require_once 'Zend/Service/Delicious/PostList.php';


/**
 * Zend_Service_Delicious is a concrete implementation of the del.icio.us web service
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Delicious
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Delicious
{
    const API_URI = 'https://api.del.icio.us';

    const PATH_UPDATE        = '/v1/posts/update';
    const PATH_TAGS          = '/v1/tags/get';
    const PATH_TAG_RENAME    = '/v1/tags/rename';
    const PATH_BUNDLES       = '/v1/tags/bundles/all';
    const PATH_BUNDLE_DELETE = '/v1/tags/bundles/delete';
    const PATH_BUNDLE_ADD    = '/v1/tags/bundles/set';
    const PATH_DATES         = '/v1/posts/dates';
    const PATH_POST_DELETE   = '/v1/posts/delete';
    const PATH_POSTS_GET     = '/v1/posts/get';
    const PATH_POSTS_ALL     = '/v1/posts/all';
    const PATH_POSTS_ADD     = '/v1/posts/add';
    const PATH_POSTS_RECENT  = '/v1/posts/recent';

    const JSON_URI     = 'http://del.icio.us';
    const JSON_POSTS   = '/feeds/json/%s/%s';
    const JSON_TAGS    = '/feeds/json/tags/%s';
    const JSON_NETWORK = '/feeds/json/network/%s';
    const JSON_FANS    = '/feeds/json/fans/%s';
    const JSON_URL     = '/feeds/json/url/data';

    /**
     * Zend_Service_Rest instance
     *
     * @var Zend_Service_Rest
     */
    protected $_rest;

    /**
     * Username
     *
     * @var string
     */
    protected $_authUname;

    /**
     * Password
     *
     * @var string
     */
    protected $_authPass;

    /**
     * Microtime of last request
     *
     * @var float
     */
    protected static $_lastRequestTime = 0;

    /**
     * Constructs a new del.icio.us Web Services Client
     *
     * @param  string $uname Client username
     * @param  string $pass  Client password
     * @return void
     */
    public function __construct($uname = null, $pass = null)
    {
        $this->_rest = new Zend_Rest_Client();
        $this->_rest->getHttpClient()->setConfig(array('ssltransport' => 'ssl'));
        $this->setAuth($uname, $pass);
    }

    /**
     * Set client username and password
     *
     * @param  string $uname Client user name
     * @param  string $pass  Client password
     * @return Zend_Service_Delicious Provides a fluent interface
     */
    public function setAuth($uname, $pass)
    {
        $this->_authUname = $uname;
        $this->_authPass  = $pass;

        return $this;
    }

    /**
     * Get time of the last update
     *
     * @throws Zend_Service_Delicious_Exception
     * @return Zend_Date
     */
    public function getLastUpdate()
    {
        $response = $this->makeRequest(self::PATH_UPDATE);

        $rootNode = $response->documentElement;
        if ($rootNode && $rootNode->nodeName == 'update') {
            /**
             * @todo replace strtotime() with Zend_Date equivalent
             */
            return new Zend_Date(strtotime($rootNode->getAttribute('time')));
        } else {
            /**
             * @see Zend_Service_Delicious_Exception
             */
            require_once 'Zend/Service/Delicious/Exception.php';
            throw new Zend_Service_Delicious_Exception('del.icio.us web service has returned something odd!');
        }
    }

    /**
     * Get all tags, returning an array with tags as keys and number of corresponding posts as values
     *
     * @return array list of tags
     */
    public function getTags()
    {
        $response = $this->makeRequest(self::PATH_TAGS);

        return self::_xmlResponseToArray($response, 'tags', 'tag', 'tag', 'count');
    }

    /**
     * Rename a tag
     *
     * @param  string $old Old tag name
     * @param  string $new New tag name
     * @return Zend_Service_Delicious Provides a fluent interface
     */
    public function renameTag($old, $new)
    {
        $response = $this->makeRequest(self::PATH_TAG_RENAME, array('old' => $old, 'new' => $new));

        self::_evalXmlResult($response);

        return $this;
    }

    /**
     * Get all bundles, returning an array with bundles as keys and array of tags as values
     *
     * @return array list of bundles
     */
    public function getBundles()
    {
        $response = $this->makeRequest(self::PATH_BUNDLES);

        $bundles = self::_xmlResponseToArray($response, 'bundles', 'bundle', 'name', 'tags');
        foreach ($bundles as &$tags) {
            $tags = explode(' ', $tags);
        }
        return $bundles;
    }

    /**
     * Adds a new bundle
     *
     * @param  string $bundle Name of new bundle
     * @param  array  $tags   Array of tags
     * @return Zend_Service_Delicious Provides a fluent interface
     */
    public function addBundle($bundle, array $tags)
    {
        $tags = implode(' ', (array) $tags);
        $response = $this->makeRequest(self::PATH_BUNDLE_ADD, array('bundle' => $bundle, 'tags' => $tags));

        self::_evalXmlResult($response);

        return $this;
    }

    /**
     * Delete a bundle
     *
     * @param  string $bundle Name of bundle to be deleted
     * @return Zend_Service_Delicious Provides a fluent interface
     */
    public function deleteBundle($bundle)
    {
        $response = $this->makeRequest(self::PATH_BUNDLE_DELETE, array('bundle' => $bundle));

        self::_evalXmlResult($response);

        return $this;
    }

    /**
     * Delete a post
     *
     * @param  string $url URL of post to be deleted
     * @return Zend_Service_Delicious Provides a fluent interface
     */
    public function deletePost($url)
    {
        $response = $this->makeRequest(self::PATH_POST_DELETE, array('url' => $url));

        self::_evalXmlResult($response);

        return $this;
    }

    /**
     * Get number of posts by date
     *
     * Returns array where keys are dates and values are numbers of posts
     *
     * @param  string $tag Optional filtering by tag
     * @return array list of dates
     */
    public function getDates($tag = null)
    {
        $parms = array();
        if ($tag) {
            $parms['tag'] = $tag;
        }

        $response = $this->makeRequest(self::PATH_DATES, $parms);

        return self::_xmlResponseToArray($response, 'dates', 'date', 'date', 'count');
    }

    /**
     * Get posts matching the arguments
     *
     * If no date or url is given, most recent date will be used
     *
     * @param  string    $tag Optional filtering by tag
     * @param  Zend_Date $dt  Optional filtering by date
     * @param  string    $url Optional filtering by url
     * @throws Zend_Service_Delicious_Exception
     * @return Zend_Service_Delicious_PostList
     */
    public function getPosts($tag = null, Zend_Date $dt = null, $url = null)
    {
        $parms = array();
        if ($tag) {
            $parms['tag'] = $tag;
        }
        if ($url) {
            $parms['url'] = $url;
        }
        if ($dt) {
            $parms['dt'] = $dt->get('Y-m-d\TH:i:s\Z');
        }

        $response = $this->makeRequest(self::PATH_POSTS_GET, $parms);

        return $this->_parseXmlPostList($response);
    }

    /**
     * Get all posts
     *
     * @param  string $tag Optional filtering by tag
     * @return Zend_Service_Delicious_PostList
     */
    public function getAllPosts($tag = null)
    {
        $parms = array();
        if ($tag) {
            $parms['tag'] = $tag;
        }

        $response = $this->makeRequest(self::PATH_POSTS_ALL, $parms);

        return $this->_parseXmlPostList($response);
    }

    /**
     * Get recent posts
     *
     * @param  string $tag   Optional filtering by tag
     * @param  string $count Maximum number of posts to be returned (default 15)
     * @return Zend_Service_Delicious_PostList
     */
    public function getRecentPosts($tag = null, $count = 15)
    {
        $parms = array();
        if ($tag) {
            $parms['tag'] = $tag;
        }
        if ($count) {
            $parms['count'] = $count;
        }

        $response = $this->makeRequest(self::PATH_POSTS_RECENT, $parms);

        return $this->_parseXmlPostList($response);
    }

    /**
     * Create new post
     *
     * @return Zend_Service_Delicious_Post
     */
    public function createNewPost($title, $url)
    {
        return new Zend_Service_Delicious_Post($this, array('title' => $title, 'url' => $url));
    }

    /**
     * Get posts of a user
     *
     * @param  string $user  Owner of the posts
     * @param  int    $count Number of posts (default 15, max. 100)
     * @param  string $tag   Optional filtering by tag
     * @return Zend_Service_Delicious_PostList
     */
    public function getUserPosts($user, $count = null, $tag = null)
    {
        $parms = array();
        if ($count) {
            $parms['count'] = $count;
        }

        $path = sprintf(self::JSON_POSTS, $user, $tag);
        $res = $this->makeRequest($path, $parms, 'json');

        return new Zend_Service_Delicious_PostList($this, $res);
    }

    /**
     * Get tags of a user
     *
     * Returned array has tags as keys and number of posts as values
     *
     * @param  string $user    Owner of the posts
     * @param  int    $atleast Include only tags for which there are at least ### number of posts
     * @param  int    $count   Number of tags to get (default all)
     * @param  string $sort    Order of returned tags ('alpha' || 'count')
     * @return array
     */
    public function getUserTags($user, $atleast = null, $count = null, $sort = 'alpha')
    {
        $parms = array();
        if ($atleast) {
            $parms['atleast'] = $atleast;
        }
        if ($count) {
            $parms['count'] = $count;
        }
        if ($sort) {
            $parms['sort'] = $sort;
        }

        $path = sprintf(self::JSON_TAGS, $user);

        return $this->makeRequest($path, $parms, 'json');
    }

    /**
     * Get network of a user
     *
     * @param  string $user Owner of the network
     * @return array
     */
    public function getUserNetwork($user)
    {
        $path = sprintf(self::JSON_NETWORK, $user);
        return $this->makeRequest($path, array(), 'json');
    }

    /**
     * Get fans of a user
     *
     * @param  string $user Owner of the fans
     * @return array
     */
    public function getUserFans($user)
    {
        $path = sprintf(self::JSON_FANS, $user);
        return $this->makeRequest($path, array(), 'json');
    }
    
    /**
     * Get details on a particular bookmarked URL
     * 
     * Returned array contains four elements:
     *  - hash - md5 hash of URL
     *  - top_tags - array of tags and their respective usage counts
     *  - url - URL for which details were returned
     *  - total_posts - number of users that have bookmarked URL
     *
     * If URL hasen't been bookmarked null is returned.
     *
     * @param  string $url URL for which to get details
     * @return array 
     */
    public function getUrlDetails($url) 
    {
        $parms = array('hash' => md5($url));
        
        $res = $this->makeRequest(self::JSON_URL, $parms, 'json');
        
        if(isset($res[0])) {
            return $res[0];
        } else {
            return null;
        }
    }

    /**
     * Handles all GET requests to a web service
     *
     * @param   string $path  Path
     * @param   array  $parms Array of GET parameters
     * @param   string $type  Type of a request ("xml"|"json")
     * @return  mixed  decoded response from web service
     * @throws  Zend_Service_Delicious_Exception
     */
    public function makeRequest($path, array $parms = array(), $type = 'xml')
    {
        // if previous request was made less then 1 sec ago
        // wait until we can make a new request
        $timeDiff = microtime(true) - self::$_lastRequestTime;
        if ($timeDiff < 1) {
            usleep((1 - $timeDiff) * 1000000);
        }

        $this->_rest->getHttpClient()->setAuth($this->_authUname, $this->_authPass);

        switch ($type) {
            case 'xml':
                $this->_rest->setUri(self::API_URI);
                break;
            case 'json':
                $parms['raw'] = true;
                $this->_rest->setUri(self::JSON_URI);
                break;
            default:
                /**
                 * @see Zend_Service_Delicious_Exception
                 */
                require_once 'Zend/Service/Delicious/Exception.php';
                throw new Zend_Service_Delicious_Exception('Unknown request type');
        }

        self::$_lastRequestTime = microtime(true);
        $response = $this->_rest->restGet($path, $parms);

        if (!$response->isSuccessful()) {
            /**
             * @see Zend_Service_Delicious_Exception
             */
            require_once 'Zend/Service/Delicious/Exception.php';
            throw new Zend_Service_Delicious_Exception("Http client reported an error: '{$response->getMessage()}'");
        }

        $responseBody = $response->getBody();

        switch ($type) {
            case 'xml':
                $dom = new DOMDocument() ;

                if (!@$dom->loadXML($responseBody)) {
                    /**
                     * @see Zend_Service_Delicious_Exception
                     */
                    require_once 'Zend/Service/Delicious/Exception.php';
                    throw new Zend_Service_Delicious_Exception('XML Error');
                }

                return $dom;
            case 'json':
                return Zend_Json_Decoder::decode($responseBody);
        }
    }

    /**
     * Transform XML string to array
     *
     * @param   DOMDocument $response
     * @param   string      $root     Name of root tag
     * @param   string      $child    Name of children tags
     * @param   string      $attKey   Attribute of child tag to be used as a key
     * @param   string      $attValue Attribute of child tag to be used as a value
     * @return  array
     * @throws  Zend_Service_Delicious_Exception
     */
    private static function _xmlResponseToArray(DOMDocument $response, $root, $child, $attKey, $attValue)
    {
        $rootNode = $response->documentElement;
        $arrOut = array();

        if ($rootNode->nodeName == $root) {
            $childNodes = $rootNode->childNodes;

            for ($i = 0; $i < $childNodes->length; $i++) {
                $currentNode = $childNodes->item($i);
                if ($currentNode->nodeName == $child) {
                    $arrOut[$currentNode->getAttribute($attKey)] = $currentNode->getAttribute($attValue);
                }
            }
        } else {
            /**
             * @see Zend_Service_Delicious_Exception
             */
            require_once 'Zend/Service/Delicious/Exception.php';
            throw new Zend_Service_Delicious_Exception('del.icio.us web service has returned something odd!');
        }

        return $arrOut;
    }

    /**
     * Constructs Zend_Service_Delicious_PostList from XML response
     *
     * @param   DOMDocument $response
     * @return  Zend_Service_Delicious_PostList
     * @throws  Zend_Service_Delicious_Exception
     */
    private function _parseXmlPostList(DOMDocument $response)
    {
        $rootNode = $response->documentElement;

        if ($rootNode->nodeName == 'posts') {
            return new Zend_Service_Delicious_PostList($this, $rootNode->childNodes);
        } else {
            /**
             * @see Zend_Service_Delicious_Exception
             */
            require_once 'Zend/Service/Delicious/Exception.php';
            throw new Zend_Service_Delicious_Exception('del.icio.us web service has returned something odd!');
        }
    }

    /**
     * Evaluates XML response
     *
     * @param   DOMDocument $response
     * @return  void
     * @throws  Zend_Service_Delicious_Exception
     */
    private static function _evalXmlResult(DOMDocument $response)
    {
        $rootNode = $response->documentElement;

        if ($rootNode && $rootNode->nodeName == 'result') {

            if ($rootNode->hasAttribute('code')) {
                $strResponse = $rootNode->getAttribute('code');
            } else {
                $strResponse = $rootNode->nodeValue;
            }

            if ($strResponse != 'done' && $strResponse != 'ok') {
                /**
                 * @see Zend_Service_Delicious_Exception
                 */
                require_once 'Zend/Service/Delicious/Exception.php';
                throw new Zend_Service_Delicious_Exception("del.icio.us web service: '{$strResponse}'");
            }
        } else {
            /**
             * @see Zend_Service_Delicious_Exception
             */
            require_once 'Zend/Service/Delicious/Exception.php';
            throw new Zend_Service_Delicious_Exception('del.icio.us web service has returned something odd!');
        }
    }
}
Flickr.php000060400000052006150715514360006475 0ustar00<?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 Flickr
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Flickr.php 8733 2008-03-10 15:56:48Z jokke $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Flickr
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Flickr
{
    /**
     * Base URI for the REST client
     */
    const URI_BASE = 'http://www.flickr.com';

    /**
     * Your Flickr API key
     *
     * @var string
     */
    public $apiKey;

    /**
     * Reference to REST client object
     *
     * @var Zend_Rest_Client
     */
    protected $_restClient = null;


    /**
     * Performs object initializations
     *
     *  # Sets up character encoding
     *  # Saves the API key
     *
     * @param  string $apiKey Your Flickr API key
     * @return void
     */
    public function __construct($apiKey)
    {
        iconv_set_encoding('output_encoding', 'UTF-8');
        iconv_set_encoding('input_encoding', 'UTF-8');
        iconv_set_encoding('internal_encoding', 'UTF-8');

        $this->apiKey = (string) $apiKey;
    }


    /**
     * Find Flickr photos by tag.
     *
     * Query options include:
     *
     *  # per_page:        how many results to return per query
     *  # page:            the starting page offset.  first result will be (page - 1) * per_page + 1
     *  # tag_mode:        Either 'any' for an OR combination of tags,
     *                     or 'all' for an AND combination. Default is 'any'.
     *  # min_upload_date: Minimum upload date to search on.  Date should be a unix timestamp.
     *  # max_upload_date: Maximum upload date to search on.  Date should be a unix timestamp.
     *  # min_taken_date:  Minimum upload date to search on.  Date should be a MySQL datetime.
     *  # max_taken_date:  Maximum upload date to search on.  Date should be a MySQL datetime.
     *
     * @param  string|array $query   A single tag or an array of tags.
     * @param  array        $options Additional parameters to refine your query.
     * @return Zend_Service_Flickr_ResultSet
     * @throws Zend_Service_Exception
     */
    public function tagSearch($query, array $options = array())
    {
        static $method = 'flickr.photos.search';
        static $defaultOptions = array('per_page' => 10,
                                       'page'     => 1,
                                       'tag_mode' => 'or',
                                       'extras'   => 'license, date_upload, date_taken, owner_name, icon_server');

        $options['tags'] = is_array($query) ? implode(',', $query) : $query;

        $options = $this->_prepareOptions($method, $options, $defaultOptions);

        $this->_validateTagSearch($options);

        // now search for photos
        $restClient = $this->getRestClient();
        $restClient->getHttpClient()->resetParameters();
        $response = $restClient->restGet('/services/rest/', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: '
                                           . $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_Flickr_ResultSet
         */
        require_once 'Zend/Service/Flickr/ResultSet.php';
        return new Zend_Service_Flickr_ResultSet($dom, $this);
    }


    /**
     * Finds photos by a user's username or email.
     *
     * Additional query options include:
     *
     *  # per_page:        how many results to return per query
     *  # page:            the starting page offset.  first result will be (page - 1) * per_page + 1
     *  # min_upload_date: Minimum upload date to search on.  Date should be a unix timestamp.
     *  # max_upload_date: Maximum upload date to search on.  Date should be a unix timestamp.
     *  # min_taken_date:  Minimum upload date to search on.  Date should be a MySQL datetime.
     *  # max_taken_date:  Maximum upload date to search on.  Date should be a MySQL datetime.
     *
     * @param  string $query   username or email
     * @param  array  $options Additional parameters to refine your query.
     * @return Zend_Service_Flickr_ResultSet
     * @throws Zend_Service_Exception
     */
    public function userSearch($query, array $options = null)
    {
        static $method = 'flickr.people.getPublicPhotos';
        static $defaultOptions = array('per_page' => 10,
                                       'page'     => 1,
                                       'extras'   => 'license, date_upload, date_taken, owner_name, icon_server');


        // can't access by username, must get ID first
        if (strchr($query, '@')) {
            // optimistically hope this is an email
            $options['user_id'] = $this->getIdByEmail($query);
        } else {
            // we can safely ignore this exception here
            $options['user_id'] = $this->getIdByUsername($query);
        }

        $options = $this->_prepareOptions($method, $options, $defaultOptions);
        $this->_validateUserSearch($options);

        // now search for photos
        $restClient = $this->getRestClient();
        $restClient->getHttpClient()->resetParameters();
        $response = $restClient->restGet('/services/rest/', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: '
                                           . $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_Flickr_ResultSet
         */
        require_once 'Zend/Service/Flickr/ResultSet.php';
        return new Zend_Service_Flickr_ResultSet($dom, $this);
    }
    
    /**
     * Finds photos in a group's pool.
     *
     * @param  string $query   group id
     * @param  array  $options Additional parameters to refine your query.
     * @return Zend_Service_Flickr_ResultSet
     * @throws Zend_Service_Exception
     */
    public function groupPoolGetPhotos($query, array $options = array())
    {
        static $method = 'flickr.groups.pools.getPhotos';
        static $defaultOptions = array('per_page' => 10,
                                       'page'     => 1,
                                       'extras'   => 'license, date_upload, date_taken, owner_name, icon_server');

        if (empty($query) || !is_string($query)) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('You must supply a group id');
        }

        $options['group_id'] = $query;

        $options = $this->_prepareOptions($method, $options, $defaultOptions);

        $this->_validateGroupPoolGetPhotos($options);

        // now search for photos
        $restClient = $this->getRestClient();
        $restClient->getHttpClient()->resetParameters();
        $response = $restClient->restGet('/services/rest/', $options);

        if ($response->isError()) {
            /**
            * @see Zend_Service_Exception
            */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: '
                                           . $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
        * @see Zend_Service_Flickr_ResultSet
        */
        require_once 'Zend/Service/Flickr/ResultSet.php';
        return new Zend_Service_Flickr_ResultSet($dom, $this);
    }



    /**
     * Utility function to find Flickr User IDs for usernames.
     *
     * (You can only find a user's photo with their NSID.)
     *
     * @param  string $username the username
     * @return string the NSID (userid)
     * @throws Zend_Service_Exception
     */
    public function getIdByUsername($username)
    {
        static $method = 'flickr.people.findByUsername';

        $options = array('api_key' => $this->apiKey, 'method' => $method, 'username' => (string) $username);

        if (empty($username)) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('You must supply a username');
        }

        $restClient = $this->getRestClient();
        $restClient->getHttpClient()->resetParameters();
        $response = $restClient->restGet('/services/rest/', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: '
                                           . $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());
        self::_checkErrors($dom);
        $xpath = new DOMXPath($dom);
        return (string) $xpath->query('//user')->item(0)->getAttribute('id');
    }


    /**
     * Utility function to find Flickr User IDs for emails.
     *
     * (You can only find a user's photo with their NSID.)
     *
     * @param  string $email the email
     * @return string the NSID (userid)
     * @throws Zend_Service_Exception
     */
    public function getIdByEmail($email)
    {
        static $method = 'flickr.people.findByEmail';

        if (empty($email)) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('You must supply an e-mail address');
        }

        $options = array('api_key' => $this->apiKey, 'method' => $method, 'find_email' => (string) $email);

        $restClient = $this->getRestClient();
        $restClient->getHttpClient()->resetParameters();
        $response = $restClient->restGet('/services/rest/', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: '
                                           . $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());
        self::_checkErrors($dom);
        $xpath = new DOMXPath($dom);
        return (string) $xpath->query('//user')->item(0)->getAttribute('id');
    }


    /**
     * Returns Flickr photo details by for the given photo ID
     *
     * @param  string $id the NSID
     * @return array of Zend_Service_Flickr_Image, details for the specified image
     * @throws Zend_Service_Exception
     */
    public function getImageDetails($id)
    {
        static $method = 'flickr.photos.getSizes';

        if (empty($id)) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('You must supply a photo ID');
        }

        $options = array('api_key' => $this->apiKey, 'method' => $method, 'photo_id' => $id);

        $restClient = $this->getRestClient();
        $restClient->getHttpClient()->resetParameters();
        $response = $restClient->restGet('/services/rest/', $options);

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());
        $xpath = new DOMXPath($dom);
        self::_checkErrors($dom);
        $retval = array();
        /**
         * @see Zend_Service_Flickr_Image
         */
        require_once 'Zend/Service/Flickr/Image.php';
        foreach ($xpath->query('//size') as $size) {
            $label = (string) $size->getAttribute('label');
            $retval[$label] = new Zend_Service_Flickr_Image($size);
        }

        return $retval;
    }


    /**
     * Returns a reference to the REST client, instantiating it if necessary
     *
     * @return Zend_Rest_Client
     */
    public function getRestClient()
    {
        if (null === $this->_restClient) {
            /**
             * @see Zend_Rest_Client
             */
            require_once 'Zend/Rest/Client.php';
            $this->_restClient = new Zend_Rest_Client(self::URI_BASE);
        }

        return $this->_restClient;
    }


    /**
     * Validate User Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateUserSearch(array $options)
    {
        $validOptions = array('api_key', 'method', 'user_id', 'per_page', 'page', 'extras', 'min_upload_date',
                              'min_taken_date', 'max_upload_date', 'max_taken_date');

        $this->_compareOptions($options, $validOptions);

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 500, true);
        if (!$between->isValid($options['per_page'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception($options['per_page'] . ' is not valid for the "per_page" option');
        }

        /**
         * @see Zend_Validate_Int
         */
        require_once 'Zend/Validate/Int.php';
        $int = new Zend_Validate_Int();
        if (!$int->isValid($options['page'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception($options['page'] . ' is not valid for the "page" option');
        }

        // validate extras, which are delivered in csv format
        if ($options['extras']) {
            $extras = explode(',', $options['extras']);
            $validExtras = array('license', 'date_upload', 'date_taken', 'owner_name', 'icon_server');
            foreach($extras as $extra) {
                /**
                 * @todo The following does not do anything [yet], so it is commented out.
                 */
                //in_array(trim($extra), $validExtras);
            }
        }
    }


    /**
     * Validate Tag Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateTagSearch(array $options)
    {
        $validOptions = array('method', 'api_key', 'user_id', 'tags', 'tag_mode', 'text', 'min_upload_date',
                              'max_upload_date', 'min_taken_date', 'max_taken_date', 'license', 'sort',
                              'privacy_filter', 'bbox', 'accuracy', 'machine_tags', 'machine_tag_mode', 'group_id',
                              'extras', 'per_page', 'page');

        $this->_compareOptions($options, $validOptions);

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 500, true);
        if (!$between->isValid($options['per_page'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception($options['per_page'] . ' is not valid for the "per_page" option');
        }

        /**
         * @see Zend_Validate_Int
         */
        require_once 'Zend/Validate/Int.php';
        $int = new Zend_Validate_Int();
        if (!$int->isValid($options['page'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception($options['page'] . ' is not valid for the "page" option');
        }

        // validate extras, which are delivered in csv format
        if ($options['extras']) {
            $extras = explode(',', $options['extras']);
            $validExtras = array('license', 'date_upload', 'date_taken', 'owner_name', 'icon_server');
            foreach($extras as $extra) {
                /**
                 * @todo The following does not do anything [yet], so it is commented out.
                 */
                //in_array(trim($extra), $validExtras);
            }
        }

    }
    
    
    /**
    * Validate Group Search Options
    *
    * @param  array $options
    * @throws Zend_Service_Exception
    * @return void
    */
    protected function _validateGroupPoolGetPhotos(array $options)
    {
        $validOptions = array('api_key', 'tags', 'method', 'group_id', 'per_page', 'page', 'extras', 'user_id');

        $this->_compareOptions($options, $validOptions);

        /**
        * @see Zend_Validate_Between
        */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 500, true);
        if (!$between->isValid($options['per_page'])) {
            /**
            * @see Zend_Service_Exception
            */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception($options['per_page'] . ' is not valid for the "per_page" option');
        }

        /**
        * @see Zend_Validate_Int
        */
        require_once 'Zend/Validate/Int.php';
        $int = new Zend_Validate_Int();
        
        if (!$int->isValid($options['page'])) {
            /**
            * @see Zend_Service_Exception
            */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception($options['page'] . ' is not valid for the "page" option');
        }

        // validate extras, which are delivered in csv format
        if (isset($options['extras'])) {
            $extras = explode(',', $options['extras']);
            $validExtras = array('license', 'date_upload', 'date_taken', 'owner_name', 'icon_server');
            foreach($extras as $extra) {
                /**
                * @todo The following does not do anything [yet], so it is commented out.
                */
                //in_array(trim($extra), $validExtras);
            }
        }
    }


    /**
     * Throws an exception if and only if the response status indicates a failure
     *
     * @param  DOMDocument $dom
     * @return void
     * @throws Zend_Service_Exception
     */
    protected static function _checkErrors(DOMDocument $dom)
    {
        if ($dom->documentElement->getAttribute('stat') === 'fail') {
            $xpath = new DOMXPath($dom);
            $err = $xpath->query('//err')->item(0);
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Search failed due to error: ' . $err->getAttribute('msg')
                                           . ' (error #' . $err->getAttribute('code') . ')');
        }
    }


    /**
     * Prepare options for the request
     *
     * @param  string $method         Flickr Method to call
     * @param  array  $options        User Options
     * @param  array  $defaultOptions Default Options
     * @return array Merged array of user and default/required options
     */
    protected function _prepareOptions($method, array $options, array $defaultOptions)
    {
        $options['method']  = (string) $method;
        $options['api_key'] = $this->apiKey;

        return array_merge($defaultOptions, $options);
    }


    /**
     * Throws an exception if and only if any user options are invalid
     *
     * @param  array $options      User options
     * @param  array $validOptions Valid options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _compareOptions(array $options, array $validOptions)
    {
        $difference = array_diff(array_keys($options), $validOptions);
        if ($difference) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('The following parameters are invalid: ' . implode(',', $difference));
        }
    }
}

StrikeIron.php000060400000005544150715514360007361 0ustar00<?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 StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: StrikeIron.php 8539 2008-03-04 20:29:55Z darby $
 */


/**
 * @see Zend_Loader
 */
require_once 'Zend/Loader.php';


/**
 * This class allows StrikeIron authentication credentials to be specified
 * in one place and provides a factory for returning instances of different
 * StrikeIron service classes.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage StrikeIron
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_StrikeIron
{
    /**
     * Options to pass to Zend_Service_StrikeIron_Base constructor
     * @param array
     */
    protected $_options;

    /**
     * Class constructor
     *
     * @param array  $options  Options to pass to Zend_Service_StrikeIron_Base constructor
     */
    public function __construct($options = array())
    {
        $this->_options = $options;
    }

    /**
     * Factory method to return a preconfigured Zend_Service_StrikeIron_*
     * instance.
     *
     * @param  null|string  $options  Service options
     * @return object       Zend_Service_StrikeIron_* instance
     * @throws Zend_Service_StrikeIron_Exception
     */
    public function getService($options = array())
    {
        $class = isset($options['class']) ? $options['class'] : 'Base';
        unset($options['class']);

        if (strpos($class, '_') === false) {
            $class = "Zend_Service_StrikeIron_{$class}";
        }

        try {
            @Zend_Loader::loadClass($class);
            if (!class_exists($class, false)) {
                throw new Exception('Class file not found');
            }
        } catch (Exception $e) {
            $msg = "Service '$class' could not be loaded: " . $e->getMessage();
            /**
             * @see Zend_Service_StrikeIron_Exception
             */
            require_once 'Zend/Service/StrikeIron/Exception.php';
            throw new Zend_Service_StrikeIron_Exception($msg, $e->getCode());
        }

        // instantiate and return the service
        $service = new $class(array_merge($this->_options, $options));
        return $service;
    }

}
Nirvanix.php000060400000006641150715514360007065 0ustar00<?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 Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
 
/**
 * @see Zend_Loader
 */
require_once 'Zend/Loader.php';

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

/**
 * This class allows Nirvanix authentication credentials to be specified
 * in one place and provides a factory for returning convenience wrappers
 * around the Nirvanix web service namespaces.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Nirvanix
{
    /**
     * Options to pass to namespace proxies
     * @param array
     */
    protected $_options;

    /**
     * Class constructor.  Authenticates with Nirvanix to receive a 
     * sessionToken, which is then passed to each future request.
     *
     * @param  array  $authParams  Authentication POST parameters.  This
     *                             should have keys "username", "password",
     *                             and "appKey".
     * @param  array  $options     Options to pass to namespace proxies
     */
    public function __construct($authParams, $options = array())
    {
        // merge options with default options
        $defaultOptions = array('defaults'   => array(),
                                'httpClient' => new Zend_Http_Client(),
                                'host'       => 'http://services.nirvanix.com');
        $this->_options = array_merge($defaultOptions, $options);

        // login and save sessionToken to default POST params
        $resp = $this->getService('Authentication')->login($authParams);
        $this->_options['defaults']['sessionToken'] = (string)$resp->SessionToken;
    }    

    /**
     * Nirvanix divides its service into namespaces, with each namespace
     * providing different functionality.  This is a factory method that
     * returns a preconfigured Zend_Service_Nirvanix_Namespace_Base proxy.
     *
     * @param  string  $namespace  Name of the namespace
     * @return Zend_Service_Nirvanix_Namespace_Base
     */
    public function getService($namespace, $options = array())
    {
        switch ($namespace) {
            case 'IMFS':
                $class = 'Zend_Service_Nirvanix_Namespace_Imfs';
                break;
            default:
                $class = 'Zend_Service_Nirvanix_Namespace_Base';
        }

        $options['namespace'] = ucfirst($namespace);
        $options = array_merge($this->_options, $options);

        Zend_Loader::loadClass($class);
        return new $class($options);
    }
    
    /**
     * Get the configured options.
     *
     * @return array
     */
    public function getOptions()
    {
        return $this->_options;
    }

}
Amazon.php000060400000017640150715514360006515 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Amazon.php 13635 2009-01-14 21:16:36Z beberlei $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon
{
    /**
     * Amazon Web Services Access Key ID
     *
     * @var string
     */
    public $appId;

    /**
     * List of Amazon Web Service base URLs, indexed by country code
     *
     * @var array
     */
    protected $_baseUriList = array('US' => 'http://webservices.amazon.com',
                                    'UK' => 'http://webservices.amazon.co.uk',
                                    'DE' => 'http://webservices.amazon.de',
                                    'JP' => 'http://webservices.amazon.co.jp',
                                    'FR' => 'http://webservices.amazon.fr',
                                    'CA' => 'http://webservices.amazon.ca');

    /**
     * Reference to REST client object
     *
     * @var Zend_Rest_Client
     */
    protected $_rest;


    /**
     * Constructs a new Amazon Web Services Client
     *
     * @param  string $appId       Developer's Amazon appid
     * @param  string $countryCode Country code for Amazon service; may be US, UK, DE, JP, FR, CA
     * @throws Zend_Service_Exception
     * @return Zend_Service_Amazon
     */
    public function __construct($appId, $countryCode = 'US')
    {
        $this->appId = (string) $appId;
        $countryCode = (string) $countryCode;

        if (!isset($this->_baseUriList[$countryCode])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Unknown country code: $countryCode");
        }

        /**
         * @see Zend_Rest_Client
         */
        require_once 'Zend/Rest/Client.php';
        $this->_rest = new Zend_Rest_Client($this->_baseUriList[$countryCode]);
    }


    /**
     * Search for Items
     *
     * @param  array $options Options to use for the Search Query
     * @throws Zend_Service_Exception
     * @return Zend_Service_Amazon_ResultSet
     * @see http://www.amazon.com/gp/aws/sdk/main.html/102-9041115-9057709?s=AWSEcommerceService&v=2005-10-05&p=ApiReference/ItemSearchOperation
     */
    public function itemSearch(array $options)
    {
        $defaultOptions = array('ResponseGroup' => 'Small');
        $options = $this->_prepareOptions('ItemSearch', $options, $defaultOptions);
        $this->_rest->getHttpClient()->resetParameters();
        $response = $this->_rest->restGet('/onca/xml', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: '
                                           . $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());
        self::_checkErrors($dom);

        /**
         * @see Zend_Service_Amazon_ResultSet
         */
        require_once 'Zend/Service/Amazon/ResultSet.php';
        return new Zend_Service_Amazon_ResultSet($dom);
    }


    /**
     * Look up item(s) by ASIN
     *
     * @param  string $asin    Amazon ASIN ID
     * @param  array  $options Query Options
     * @see http://www.amazon.com/gp/aws/sdk/main.html/102-9041115-9057709?s=AWSEcommerceService&v=2005-10-05&p=ApiReference/ItemLookupOperation
     * @throws Zend_Service_Exception
     * @return Zend_Service_Amazon_Item|Zend_Service_Amazon_ResultSet
     */
    public function itemLookup($asin, array $options = array())
    {
        $defaultOptions = array('IdType' => 'ASIN', 'ResponseGroup' => 'Small');
        $options['ItemId'] = (string) $asin;
        $options = $this->_prepareOptions('ItemLookup', $options, $defaultOptions);
        $this->_rest->getHttpClient()->resetParameters();
        $response = $this->_rest->restGet('/onca/xml', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: '
                                           . $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());
        self::_checkErrors($dom);
        $xpath = new DOMXPath($dom);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        $items = $xpath->query('//az:Items/az:Item');

        if ($items->length == 1) {
            /**
             * @see Zend_Service_Amazon_Item
             */
            require_once 'Zend/Service/Amazon/Item.php';
            return new Zend_Service_Amazon_Item($items->item(0));
        }

        /**
         * @see Zend_Service_Amazon_ResultSet
         */
        require_once 'Zend/Service/Amazon/ResultSet.php';
        return new Zend_Service_Amazon_ResultSet($dom);
    }


    /**
     * Returns a reference to the REST client
     *
     * @return Zend_Rest_Client
     */
    public function getRestClient()
    {
        return $this->_rest;
    }


    /**
     * Prepare options for request
     *
     * @param  string $query          Action to perform
     * @param  array  $options        User supplied options
     * @param  array  $defaultOptions Default options
     * @return array
     */
    protected function _prepareOptions($query, array $options, array $defaultOptions)
    {
        $options['SubscriptionId'] = $this->appId;
        $options['Service']        = 'AWSECommerceService';
        $options['Operation']      = (string) $query;

        // de-canonicalize out sort key
        if (isset($options['ResponseGroup'])) {
            $responseGroup = split(',', $options['ResponseGroup']);

            if (!in_array('Request', $responseGroup)) {
                $responseGroup[] = 'Request';
                $options['ResponseGroup'] = implode(',', $responseGroup);
            }
        }

        $options = array_merge($defaultOptions, $options);
        return $options;
    }


    /**
     * Check result for errors
     *
     * @param  DOMDocument $dom
     * @throws Zend_Service_Exception
     * @return void
     */
    protected static function _checkErrors(DOMDocument $dom)
    {
        $xpath = new DOMXPath($dom);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');

        if ($xpath->query('//az:Error')->length >= 1) {
            $code = $xpath->query('//az:Error/az:Code/text()')->item(0)->data;
            $message = $xpath->query('//az:Error/az:Message/text()')->item(0)->data;

            switch($code) {
                case 'AWS.ECommerceService.NoExactMatches':
                    break;
                default:
                    /**
                     * @see Zend_Service_Exception
                     */
                    require_once 'Zend/Service/Exception.php';
                    throw new Zend_Service_Exception("$message ($code)");
            }
        }
    }
}
Audioscrobbler.php000060400000050660150715514360010226 0ustar00<?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 Audioscrobbler
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Audioscrobbler.php 13633 2009-01-14 21:05:51Z beberlei $
 */


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


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Audioscrobbler
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Audioscrobbler
{
    /**
     * Zend_Http_Client Object
     *
     * @var     Zend_Http_Client
     * @access  protected
     */
    protected $_client;

    /**
     * Array that contains parameters being used by the webservice
     *
     * @var     array
     * @access  protected
     */
    protected $_params;

    /**
     * Flag if we're doing testing or not
     *
     * @var     boolean
     * @access  protected
     */
    protected $_testing;

    /**
     * Http response used for testing purposes
     *
     * @var     string
     * @access  protected
     */
    protected $_testingResponse;

    /**
     * Holds error information (e.g., for handling simplexml_load_string() warnings)
     *
     * @var     array
     * @access  protected
     */
    protected $_error = null;


    //////////////////////////////////////////////////////////
    ///////////////////  CORE METHODS  ///////////////////////
    //////////////////////////////////////////////////////////


    /**
     * Sets up character encoding, instantiates the HTTP client, and assigns the web service version
     * and testing parameters (if provided).
     *
     * @param  boolean $testing
     * @param  string  $testingResponse
     * @return void
     */
    public function __construct($testing = false, $testingResponse = null)
    {
        $this->set('version', '1.0');

        iconv_set_encoding('output_encoding', 'UTF-8');
        iconv_set_encoding('input_encoding', 'UTF-8');
        iconv_set_encoding('internal_encoding', 'UTF-8');

        $this->_client = new Zend_Http_Client();

        $this->_testing          = (boolean) $testing;
        $this->_testingResponse  = (string) $testingResponse;
    }


    /**
     * Returns a field value, or false if the named field does not exist
     *
     * @param  string $field
     * @return string|false
     */
    public function get($field)
    {
        if (array_key_exists($field, $this->_params)) {
            return $this->_params[$field];
        } else {
            return false;
        }
    }

    /**
     * Generic set action for a field in the parameters being used
     *
     * @param  string $field name of field to set
     * @param  string $value value to assign to the named field
     * @return Zend_Service_Audioscrobbler Provides a fluent interface
     */
    public function set($field, $value)
    {
        $this->_params[$field] = urlencode($value);

        return $this;
    }

    /**
     * Protected method that queries REST service and returns SimpleXML response set
     *
     * @param  string $service name of Audioscrobbler service file we're accessing
     * @param  string $params  parameters that we send to the service if needded
     * @throws Zend_Http_Client_Exception
     * @throws Zend_Service_Exception
     * @return SimpleXMLElement result set
     * @access protected
     */
    protected function _getInfo($service, $params = null)
    {
        $service = (string) $service;
        $params  = (string) $params;

        if ($params === '') {
            $this->_client->setUri("http://ws.audioscrobbler.com{$service}");
        } else {
            $this->_client->setUri("http://ws.audioscrobbler.com{$service}?{$params}");
        }

        if ($this->_testing) {
            /**
             * @see Zend_Http_Client_Adapter_Test
             */
            require_once 'Zend/Http/Client/Adapter/Test.php';
            $adapter = new Zend_Http_Client_Adapter_Test();

            $this->_client->setConfig(array('adapter' => $adapter));

            $adapter->setResponse($this->_testingResponse);
        }

        $response     = $this->_client->request();
        $responseBody = $response->getBody();

        if (preg_match('/No such path/', $responseBody)) {
            /**
             * @see Zend_Http_Client_Exception
             */
            require_once 'Zend/Http/Client/Exception.php';
            throw new Zend_Http_Client_Exception('Could not find: ' . $this->_client->getUri());
        } elseif (preg_match('/No user exists with this name/', $responseBody)) {
            /**
             * @see Zend_Http_Client_Exception
             */
            require_once 'Zend/Http/Client/Exception.php';
            throw new Zend_Http_Client_Exception('No user exists with this name');
        } elseif (!$response->isSuccessful()) {
            /**
             * @see Zend_Http_Client_Exception
             */
            require_once 'Zend/Http/Client/Exception.php';
            throw new Zend_Http_Client_Exception('The web service ' . $this->_client->getUri() . ' returned the following status code: ' . $response->getStatus());
        }

        set_error_handler(array($this, '_errorHandler'));

        if (!$simpleXmlElementResponse = simplexml_load_string($responseBody)) {
            restore_error_handler();
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            $exception = new Zend_Service_Exception('Response failed to load with SimpleXML');
            $exception->error    = $this->_error;
            $exception->response = $responseBody;
            throw $exception;
        }

        restore_error_handler();

        return $simpleXmlElementResponse;
    }

    //////////////////////////////////////////////////////////
    ///////////////////////  USER  ///////////////////////////
    //////////////////////////////////////////////////////////

    /**
    * Utility function to get Audioscrobbler profile information (eg: Name, Gender)
    * @return array containing information
    */
    public function userGetProfileInformation()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/profile.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function get this user's 50 most played artists
     * @return array containing info
    */
    public function userGetTopArtists()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/topartists.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function to get this user's 50 most played albums
     * @return SimpleXML object containing result set
    */
    public function userGetTopAlbums()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/topalbums.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function to get this user's 50 most played tracks
     * @return SimpleXML object containing resut set
    */
    public function userGetTopTracks()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/toptracks.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function to get this user's 50 most used tags
     * @return SimpleXML object containing result set
     */
    public function userGetTopTags()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/tags.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns the user's top tags used most used on a specific artist
     * @return SimpleXML object containing result set
     *
     */
    public function userGetTopTagsForArtist()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/artisttags.xml";
        $params = "artist={$this->get('artist')}";
        return $this->_getInfo($service, $params);
    }

    /**
     * Utility function that returns this user's top tags for an album
     * @return SimpleXML object containing result set
     *
     */
    public function userGetTopTagsForAlbum()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/albumtags.xml";
        $params = "artist={$this->get('artist')}&album={$this->get('album')}";
        return $this->_getInfo($service, $params);
    }

    /**
     * Utility function that returns this user's top tags for a track
     * @return SimpleXML object containing result set
     *
     */
    public function userGetTopTagsForTrack()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/tracktags.xml";
        $params = "artist={$this->get('artist')}&track={$this->get('track')}";
        return $this->_getInfo($service, $params);
    }

    /**
     * Utility function that retrieves this user's list of friends
     * @return SimpleXML object containing result set
     */
    public function userGetFriends()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/friends.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of people with similar listening preferences to this user
     * @return SimpleXML object containing result set
     *
     */
    public function userGetNeighbours()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/neighbours.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of the 10 most recent tracks played by this user
     * @return SimpleXML object containing result set
     *
     */
    public function userGetRecentTracks()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/recenttracks.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of the 10 tracks most recently banned by this user
     * @return SimpleXML object containing result set
     *
     */
    public function userGetRecentBannedTracks()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/recentbannedtracks.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of the 10 tracks most recently loved by this user
     * @return SimpleXML object containing result set
     *
     */
    public function userGetRecentLovedTracks()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/recentlovedtracks.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of dates of available weekly charts for a this user
     * Should actually be named userGetWeeklyChartDateList() but we have to follow audioscrobbler's naming
     * @return SimpleXML object containing result set
     *
     */
    public function userGetWeeklyChartList()
    {
        $service = "/{$this->get('version')}/user/{$this->get('user')}/weeklychartlist.xml";
        return $this->_getInfo($service);
    }


    /**
     * Utility function that returns weekly album chart data for this user
     * @return SimpleXML object containing result set
     *
     * @param integer $from optional UNIX timestamp for start of date range
     * @param integer $to optional UNIX timestamp for end of date range
     */
    public function userGetWeeklyAlbumChart($from = NULL, $to = NULL)
    {
        $params = "";

        if ($from != NULL && $to != NULL) {
            $from = (int)$from;
            $to = (int)$to;
            $params = "from={$from}&to={$to}";
        }

        $service = "/{$this->get('version')}/user/{$this->get('user')}/weeklyalbumchart.xml";
        return $this->_getInfo($service, $params);
    }

    /**
     * Utility function that returns weekly artist chart data for this user
     * @return SimpleXML object containing result set
     *
     * @param integer $from optional UNIX timestamp for start of date range
     * @param integer $to optional UNIX timestamp for end of date range
     */
    public function userGetWeeklyArtistChart($from = NULL, $to = NULL)
    {
        $params = "";

        if ($from != NULL && $to != NULL) {
            $from = (int)$from;
            $to = (int)$to;
            $params = "from={$from}&to={$to}";
        }

        $service = "/{$this->get('version')}/user/{$this->get('user')}/weeklyartistchart.xml";
        return $this->_getInfo($service, $params);
    }

    /**
     * Utility function that returns weekly track chart data for this user
     * @return SimpleXML object containing result set
     *
     * @param integer $from optional UNIX timestamp for start of date range
     * @param integer $to optional UNIX timestamp for end of date range
     */
    public function userGetWeeklyTrackChart($from = NULL, $to = NULL)
    {
        $params = "";

        if ($from != NULL && $to != NULL) {
            $from = (int)$from;
            $to = (int)$to;
            $params = "from={$from}&to={$to}";
        }

        $service = "/{$this->get('version')}/user/{$this->get('user')}/weeklytrackchart.xml";
        return $this->_getInfo($service, $params);
    }


    //////////////////////////////////////////////////////////
    ///////////////////////  ARTIST  /////////////////////////
    //////////////////////////////////////////////////////////

    /**
     * Public functions for retrieveing artist-specific information
     *
     */


    /**
     * Utility function that returns a list of artists similiar to this artist
     * @return SimpleXML object containing result set
     *
     */
    public function artistGetRelatedArtists()
    {
        $service = "/{$this->get('version')}/artist/{$this->get('artist')}/similar.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of this artist's top listeners
     * @return SimpleXML object containing result set
     *
     */
    public function artistGetTopFans()
    {
        $service = "/{$this->get('version')}/artist/{$this->get('artist')}/fans.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of this artist's top-rated tracks
     * @return SimpleXML object containing result set
     *
     */
    public function artistGetTopTracks()
    {
        $service = "/{$this->get('version')}/artist/{$this->get('artist')}/toptracks.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of this artist's top-rated albums
     * @return SimpleXML object containing result set
     *
     */
    public function artistGetTopAlbums()
    {
        $service = "/{$this->get('version')}/artist/{$this->get('artist')}/topalbums.xml";
        return $this->_getInfo($service);
    }

    /**
     * Utility function that returns a list of this artist's top-rated tags
     * @return SimpleXML object containing result set
     *
     */
    public function artistGetTopTags()
    {
        $service = "/{$this->get('version')}/artist/{$this->get('artist')}/toptags.xml";
        return $this->_getInfo($service);
    }

    //////////////////////////////////////////////////////////
    ///////////////////////  ALBUM  //////////////////////////
    //////////////////////////////////////////////////////////

    public function albumGetInfo()
    {
        $service = "/{$this->get('version')}/album/{$this->get('artist')}/{$this->get('album')}/info.xml";
        return $this->_getInfo($service);
    }

    //////////////////////////////////////////////////////////
    ///////////////////////  TRACKS //////////////////////////
    //////////////////////////////////////////////////////////

    public function trackGetTopFans()
    {
        $service = "/{$this->get('version')}/track/{$this->get('artist')}/{$this->get('track')}/fans.xml";
        return $this->_getInfo($service);
    }

    public function trackGetTopTags()
    {
        $service = "/{$this->get('version')}/track/{$this->get('artist')}/{$this->get('track')}/toptags.xml";
        return $this->_getInfo($service);
    }

    //////////////////////////////////////////////////////////
    ///////////////////////  TAGS   //////////////////////////
    //////////////////////////////////////////////////////////

    public function tagGetTopTags()
    {
        $service = "/{$this->get('version')}/tag/toptags.xml";
        return $this->_getInfo($service);
    }

    public function tagGetTopAlbums()
    {
        $service = "/{$this->get('version')}/tag/{$this->get('tag')}/topalbums.xml";
        return $this->_getInfo($service);
    }

    public function tagGetTopArtists()
    {
        $service = "/{$this->get('version')}/tag/{$this->get('tag')}/topartists.xml";
        return $this->_getInfo($service);
    }

    public function tagGetTopTracks()
    {
        $service = "/{$this->get('version')}/tag/{$this->get('tag')}/toptracks.xml";
        return $this->_getInfo($service);
    }

    //////////////////////////////////////////////////////////
    /////////////////////// GROUPS  //////////////////////////
    //////////////////////////////////////////////////////////

    public function groupGetWeeklyChartList()
    {
        $service = "/{$this->get('version')}/group/{$this->get('group')}/weeklychartlist.xml";
        return $this->_getInfo($service);
    }

    public function groupGetWeeklyArtistChartList($from = NULL, $to = NULL)
    {

        if ($from != NULL && $to != NULL) {
            $from = (int)$from;
            $to = (int)$to;
            $params = "from={$from}&$to={$to}";
        } else {
            $params = "";
        }

        $service = "/{$this->get('version')}/group/{$this->get('group')}/weeklyartistchart.xml";
        return $this->_getInfo($service, $params);
    }

    public function groupGetWeeklyTrackChartList($from = NULL, $to = NULL)
    {
        if ($from != NULL && $to != NULL) {
            $from = (int)$from;
            $to = (int)$to;
            $params = "from={$from}&to={$to}";
        } else {
            $params = "";
        }

        $service = "/{$this->get('version')}/group/{$this->get('group')}/weeklytrackchart.xml";
        return $this->_getInfo($service, $params);
    }

    public function groupGetWeeklyAlbumChartList($from = NULL, $to = NULL)
    {
        if ($from != NULL && $to != NULL) {
            $from = (int)$from;
            $to = (int)$to;
            $params = "from={$from}&to={$to}";
        } else {
            $params = "";
        }

        $service = "/{$this->get('version')}/group/{$this->get('group')}/weeklyalbumchart.xml";
        return $this->_getInfo($service, $params);
    }

    /**
     * Saves the provided error information to this instance
     *
     * @param  integer $errno
     * @param  string  $errstr
     * @param  string  $errfile
     * @param  integer $errline
     * @param  array   $errcontext
     * @return void
     */
    protected function _errorHandler($errno, $errstr, $errfile, $errline, array $errcontext)
    {
        $this->_error = array(
            'errno'      => $errno,
            'errstr'     => $errstr,
            'errfile'    => $errfile,
            'errline'    => $errline,
            'errcontext' => $errcontext
            );
    }

    /**
     * Call Intercept for set($name, $field)
     *
     * @param  string $method
     * @param  array  $args
     * @return Zend_Service_Audioscrobbler
     */
    public function __call($method, $args)
    {
        if(substr($method, 0, 3) !== "set") {
            require_once "Zend/Service/Audioscrobbler/Exception.php";
            throw new Zend_Service_Audioscrobbler_Exception(
                "Method ".$method." does not exist in class Zend_Service_Audioscrobbler."
            );
        }
        $field = strtolower(substr($method, 3));

        if(!is_array($args) || count($args) != 1) {
            require_once "Zend/Service/Audioscrobbler/Exception.php";
            throw new Zend_Service_Audioscrobbler_Exception(
                "A value is required for setting a parameter field."
            );
        }
        $this->set($field, $args[0]);

        return $this;
    }
}
Amazon/Accessories.php000060400000003032150715514360010746 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Accessories.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Accessories
{
    /**
     * Assigns values to properties relevant to Accessories
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        foreach (array('ASIN', 'Title') as $el) {
            $this->$el = (string) $xpath->query("./az:$el/text()", $dom)->item(0)->data;
        }
    }
}
Amazon/CustomerReview.php000060400000003277150715514360011501 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: CustomerReview.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_CustomerReview
{
    /**
     * Assigns values to properties relevant to CustomerReview
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        foreach (array('Rating', 'HelpfulVotes', 'CustomerId', 'TotalVotes', 'Date', 'Summary', 'Content') as $el) {
            $result = $xpath->query("./az:$el/text()", $dom);
            if ($result->length == 1) {
                $this->$el = (string) $result->item(0)->data;
            }
        }
    }
}
Amazon/ResultSet.php000060400000007734150715514360010452 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Amazon_Item
 */
require_once 'Zend/Service/Amazon/Item.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_ResultSet implements SeekableIterator
{
    /**
     * A DOMNodeList of <Item> elements
     *
     * @var DOMNodeList
     */
    protected $_results = null;

    /**
     * Amazon Web Service Return Document
     *
     * @var DOMDocument
     */
    protected $_dom;

    /**
     * XPath Object for $this->_dom
     *
     * @var DOMXPath
     */
    protected $_xpath;

    /**
     * Current index for SeekableIterator
     *
     * @var int
     */
    protected $_currentIndex = 0;

    /**
     * Create an instance of Zend_Service_Amazon_ResultSet and create the necessary data objects
     *
     * @param  DOMDocument $dom
     * @return void
     */
    public function __construct(DOMDocument $dom)
    {
        $this->_dom = $dom;
        $this->_xpath = new DOMXPath($dom);
        $this->_xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        $this->_results = $this->_xpath->query('//az:Item');
    }

    /**
     * Total Number of results returned
     *
     * @return int Total number of results returned
     */
    public function totalResults()
    {
        $result = $this->_xpath->query('//az:TotalResults/text()');
        return (int) $result->item(0)->data;
    }

    /**
     * Total Number of pages returned
     *
     * @return int Total number of pages returned
     */
    public function totalPages()
    {
        $result = $this->_xpath->query('//az:TotalPages/text()');
        return (int) $result->item(0)->data;
    }

    /**
     * Implement SeekableIterator::current()
     *
     * @return Zend_Service_Amazon_Item
     */
    public function current()
    {
        return new Zend_Service_Amazon_Item($this->_results->item($this->_currentIndex));
    }

    /**
     * Implement SeekableIterator::key()
     *
     * @return int
     */
    public function key()
    {
        return $this->_currentIndex;
    }

    /**
     * Implement SeekableIterator::next()
     *
     * @return void
     */
    public function next()
    {
        $this->_currentIndex += 1;
    }

    /**
     * Implement SeekableIterator::rewind()
     *
     * @return void
     */
    public function rewind()
    {
        $this->_currentIndex = 0;
    }

    /**
     * Implement SeekableIterator::seek()
     *
     * @param  int $index
     * @throws OutOfBoundsException
     * @return void
     */
    public function seek($index)
    {
        $indexInt = (int) $index;
        if ($indexInt >= 0 && (null === $this->_results || $indexInt < $this->_results->length)) {
            $this->_currentIndex = $indexInt;
        } else {
            throw new OutOfBoundsException("Illegal index '$index'");
        }
    }

    /**
     * Implement SeekableIterator::valid()
     *
     * @return boolean
     */
    public function valid()
    {
        return null !== $this->_results && $this->_currentIndex < $this->_results->length;
    }
}
Amazon/Query.php000060400000005330150715514360007613 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Query.php 8064 2008-02-16 10:58:39Z thomas $
 */


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


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Query extends Zend_Service_Amazon
{
    /**
     * Search parameters
     *
     * @var array
     */
    protected $_search = array();

    /**
     * Search index
     *
     * @var string
     */
    protected $_searchIndex = null;

    /**
     * Prepares query parameters
     *
     * @param  string $method
     * @param  array  $args
     * @throws Zend_Service_Exception
     * @return Zend_Service_Amazon_Query Provides a fluent interface
     */
    public function __call($method, $args)
    {
        if (strtolower($method) === 'asin') {
            $this->_searchIndex = 'asin';
            $this->_search['ItemId'] = $args[0];
            return $this;
        }

        if (strtolower($method) === 'category') {
            $this->_searchIndex = $args[0];
            $this->_search['SearchIndex'] = $args[0];
        } else if (isset($this->_search['SearchIndex']) || $this->_searchIndex !== null || $this->_searchIndex === 'asin') {
            $this->_search[$method] = $args[0];
        } else {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('You must set a category before setting the search parameters');
        }

        return $this;
    }

    /**
     * Search using the prepared query
     *
     * @return Zend_Service_Amazon_Item|Zend_Service_Amazon_ResultSet
     */
    public function search()
    {
        if ($this->_searchIndex === 'asin') {
            return $this->itemLookup($this->_search['ItemId'], $this->_search);
        }
        return $this->itemSearch($this->_search);
    }
}
Amazon/Item.php000060400000016115150715514360007407 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Item.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Item
{
    public $ASIN;
    public $DetailPageURL;
    public $SalesRank;
    public $SmallImage;
    public $MediumImage;
    public $LargeImage;
    public $Subjects;
    public $Offers;
    public $CustomerReviews;
    public $SimilarProducts;
    public $Accessories;
    public $Tracks;
    public $ListmaniaLists;
    public $PromotionalTag;

    protected $_dom;


    /**
     * Parse the given <Item> element
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        $this->ASIN = $xpath->query('./az:ASIN/text()', $dom)->item(0)->data;

        $result = $xpath->query('./az:DetailPageURL/text()', $dom);
        if ($result->length == 1) {
            $this->DetailPageURL = $result->item(0)->data;
        }

        if ($xpath->query('./az:ItemAttributes/az:ListPrice', $dom)->length >= 1) {
            $this->CurrencyCode = (string) $xpath->query('./az:ItemAttributes/az:ListPrice/az:CurrencyCode/text()', $dom)->item(0)->data;
            $this->Amount = (int) $xpath->query('./az:ItemAttributes/az:ListPrice/az:Amount/text()', $dom)->item(0)->data;
            $this->FormattedPrice = (string) $xpath->query('./az:ItemAttributes/az:ListPrice/az:FormattedPrice/text()', $dom)->item(0)->data;
        }

        $result = $xpath->query('./az:ItemAttributes/az:*/text()', $dom);
        if ($result->length >= 1) {
            foreach ($result as $v) {
                if (isset($this->{$v->parentNode->tagName})) {
                    if (is_array($this->{$v->parentNode->tagName})) {
                        array_push($this->{$v->parentNode->tagName}, (string) $v->data);
                    } else {
                        $this->{$v->parentNode->tagName} = array($this->{$v->parentNode->tagName}, (string) $v->data);
                    }
                } else {
                    $this->{$v->parentNode->tagName} = (string) $v->data;
                }
            }
        }

        foreach (array('SmallImage', 'MediumImage', 'LargeImage') as $im) {
            $result = $xpath->query("./az:ImageSets/az:ImageSet[position() = 1]/az:$im", $dom);
            if ($result->length == 1) {
                /**
                 * @see Zend_Service_Amazon_Image
                 */
                require_once 'Zend/Service/Amazon/Image.php';
                $this->$im = new Zend_Service_Amazon_Image($result->item(0));
            }
        }

        $result = $xpath->query('./az:SalesRank/text()', $dom);
        if ($result->length == 1) {
            $this->SalesRank = (int) $result->item(0)->data;
        }

        $result = $xpath->query('./az:CustomerReviews/az:Review', $dom);
        if ($result->length >= 1) {
            /**
             * @see Zend_Service_Amazon_CustomerReview
             */
            require_once 'Zend/Service/Amazon/CustomerReview.php';
            foreach ($result as $review) {
                $this->CustomerReviews[] = new Zend_Service_Amazon_CustomerReview($review);
            }
            $this->AverageRating = (float) $xpath->query('./az:CustomerReviews/az:AverageRating/text()', $dom)->item(0)->data;
            $this->TotalReviews = (int) $xpath->query('./az:CustomerReviews/az:TotalReviews/text()', $dom)->item(0)->data;
        }

        $result = $xpath->query('./az:EditorialReviews/az:*', $dom);
        if ($result->length >= 1) {
            /**
             * @see Zend_Service_Amazon_EditorialReview
             */
            require_once 'Zend/Service/Amazon/EditorialReview.php';
            foreach ($result as $r) {
                $this->EditorialReviews[] = new Zend_Service_Amazon_EditorialReview($r);
            }
        }

        $result = $xpath->query('./az:SimilarProducts/az:*', $dom);
        if ($result->length >= 1) {
            /**
             * @see Zend_Service_Amazon_SimilarProduct
             */
            require_once 'Zend/Service/Amazon/SimilarProduct.php';
            foreach ($result as $r) {
                $this->SimilarProducts[] = new Zend_Service_Amazon_SimilarProduct($r);
            }
        }

        $result = $xpath->query('./az:ListmaniaLists/*', $dom);
        if ($result->length >= 1) {
            /**
             * @see Zend_Service_Amazon_ListmaniaList
             */
            require_once 'Zend/Service/Amazon/ListmaniaList.php';
            foreach ($result as $r) {
                $this->ListmaniaLists[] = new Zend_Service_Amazon_ListmaniaList($r);
            }
        }

        $result = $xpath->query('./az:Tracks/az:Disc', $dom);
        if ($result->length > 1) {
            foreach ($result as $disk) {
                foreach ($xpath->query('./*/text()', $disk) as $t) {
                    $this->Tracks[$disk->getAttribute('number')] = (string) $t->data;
                }
            }
        } else if ($result->length == 1) {
            foreach ($xpath->query('./*/text()', $result->item(0)) as $t) {
                $this->Tracks[] = (string) $t->data;
            }
        }

        $result = $xpath->query('./az:Offers', $dom);
        $resultSummary = $xpath->query('./az:OfferSummary', $dom);
        if ($result->length > 1 || $resultSummary->length == 1) {
            /**
             * @see Zend_Service_Amazon_OfferSet
             */
            require_once 'Zend/Service/Amazon/OfferSet.php';
            $this->Offers = new Zend_Service_Amazon_OfferSet($dom);
        }

        $result = $xpath->query('./az:Accessories/*', $dom);
        if ($result->length > 1) {
            /**
             * @see Zend_Service_Amazon_Accessories
             */
            require_once 'Zend/Service/Amazon/Accessories.php';
            foreach ($result as $r) {
                $this->Accessories[] = new Zend_Service_Amazon_Accessories($r);
            }
        }

        $this->_dom = $dom;
    }


    /**
     * Returns the item's original XML
     *
     * @return string
     */
    public function asXml()
    {
        return $this->_dom->ownerDocument->saveXML($this->_dom);
    }
}
Amazon/OfferSet.php000060400000006256150715514360010233 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: OfferSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_OfferSet
{
    /**
     * Parse the given Offer Set Element
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');

        $offer = $xpath->query('./az:OfferSummary', $dom);
        if ($offer->length == 1) {
            $lowestNewPrice = $xpath->query('./az:OfferSummary/az:LowestNewPrice', $dom);
            if ($lowestNewPrice->length == 1) {
                $this->LowestNewPrice = (int) $xpath->query('./az:OfferSummary/az:LowestNewPrice/az:Amount/text()', $dom)->item(0)->data;
                $this->LowestNewPriceCurrency = (string) $xpath->query('./az:OfferSummary/az:LowestNewPrice/az:CurrencyCode/text()', $dom)->item(0)->data;
            }
            $lowestUsedPrice = $xpath->query('./az:OfferSummary/az:LowestUsedPrice', $dom);
            if ($lowestUsedPrice->length == 1) {
                $this->LowestUsedPrice = (int) $xpath->query('./az:OfferSummary/az:LowestUsedPrice/az:Amount/text()', $dom)->item(0)->data;
                $this->LowestUsedPriceCurrency = (string) $xpath->query('./az:OfferSummary/az:LowestUsedPrice/az:CurrencyCode/text()', $dom)->item(0)->data;
            }
            $this->TotalNew = (int) $xpath->query('./az:OfferSummary/az:TotalNew/text()', $dom)->item(0)->data;
            $this->TotalUsed = (int) $xpath->query('./az:OfferSummary/az:TotalUsed/text()', $dom)->item(0)->data;
            $this->TotalCollectible = (int) $xpath->query('./az:OfferSummary/az:TotalCollectible/text()', $dom)->item(0)->data;
            $this->TotalRefurbished = (int) $xpath->query('./az:OfferSummary/az:TotalRefurbished/text()', $dom)->item(0)->data;
        }
        $offers = $xpath->query('./az:Offers/az:Offer', $dom);
        if ($offers->length >= 1) {
            /**
             * @see Zend_Service_Amazon_Offer
             */
            require_once 'Zend/Service/Amazon/Offer.php';
            foreach ($offers as $offer) {
                $this->Offers[] = new Zend_Service_Amazon_Offer($offer);
            }
        }
    }
}
Amazon/ListmaniaList.php000060400000003045150715514360011264 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ListmaniaList.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_ListmaniaList
{
    /**
     * Assigns values to properties relevant to ListmaniaList
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        foreach (array('ListId', 'ListName') as $el) {
            $this->$el = (string) $xpath->query("./az:$el/text()", $dom)->item(0)->data;
        }
    }
}
Amazon/SimilarProduct.php000060400000003043150715514360011446 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SimilarProduct.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_SimilarProduct
{
    /**
     * Assigns values to properties relevant to SimilarProduct
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        foreach (array('ASIN', 'Title') as $el) {
            $this->$el = (string) $xpath->query("./az:$el/text()", $dom)->item(0)->data;
        }
    }
}
Amazon/EditorialReview.php000060400000003052150715514360011603 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: EditorialReview.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_EditorialReview
{
    /**
     * Assigns values to properties relevant to EditorialReview
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        foreach (array('Source', 'Content') as $el) {
            $this->$el = (string) $xpath->query("./az:$el/text()", $dom)->item(0)->data;
        }
    }
}
Amazon/Image.php000060400000003601150715514360007527 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Image.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Image
{
    /**
     * Image URL
     *
     * @var Zend_Uri
     */
    public $Url;

    /**
     * Image height in pixels
     *
     * @var int
     */
    public $Height;

    /**
     * Image width in pixels
     *
     * @var int
     */
    public $Width;

    /**
     * Assigns values to properties relevant to Image
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        $this->Url = Zend_Uri::factory($xpath->query('./az:URL/text()', $dom)->item(0)->data);
        $this->Height = (int) $xpath->query('./az:Height/text()', $dom)->item(0)->data;
        $this->Width = (int) $xpath->query('./az:Width/text()', $dom)->item(0)->data;
    }
}
Amazon/Offer.php000060400000004576150715514360007562 0ustar00<?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
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Offer.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Amazon
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Amazon_Offer
{
    /**
     * Parse the given Offer element
     *
     * @param  DOMElement $dom
     * @return void
     */
    public function __construct(DOMElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
        $this->MerchantId = (string) $xpath->query('./az:Merchant/az:MerchantId/text()', $dom)->item(0)->data;
        $this->GlancePage = (string) $xpath->query('./az:Merchant/az:GlancePage/text()', $dom)->item(0)->data;
        $this->Condition = (string) $xpath->query('./az:OfferAttributes/az:Condition/text()', $dom)->item(0)->data;
        $this->OfferListingId = (string) $xpath->query('./az:OfferListing/az:OfferListingId/text()', $dom)->item(0)->data;
        $this->Price = (int) $xpath->query('./az:OfferListing/az:Price/az:Amount/text()', $dom)->item(0)->data;
        $this->CurrencyCode = (string) $xpath->query('./az:OfferListing/az:Price/az:CurrencyCode/text()', $dom)->item(0)->data;
        $this->Availability = (string) $xpath->query('./az:OfferListing/az:Availability/text()', $dom)->item(0)->data;
        $result = $xpath->query('./az:OfferListing/az:IsEligibleForSuperSaverShipping/text()', $dom);
        if ($result->length >= 1) {
            $this->IsEligibleForSuperSaverShipping = (bool) $result->item(0)->data;
        }
    }
}
Technorati/TagsResultSet.php000060400000004212150715514360012130 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: TagsResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_ResultSet 
 */
require_once 'Zend/Service/Technorati/ResultSet.php';


/**
 * Represents a Technorati TopTags or BlogPostTags queries result set.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_TagsResultSet extends Zend_Service_Technorati_ResultSet
{
    /**
     * Constructs a new object object from DOM Document.
     *
     * @param   DomDocument $dom the ReST fragment for this object
     */
    public function __construct(DomDocument $dom, $options = array())
    {
        parent::__construct($dom, $options);

        $this->_totalResultsReturned  = (int) $this->_xpath->evaluate("count(/tapi/document/item)");
        $this->_totalResultsAvailable = (int) $this->_totalResultsReturned;
    }

    /**
     * Implements Zend_Service_Technorati_ResultSet::current().
     *
     * @return Zend_Service_Technorati_TagsResult current result
     */
    public function current()
    {
        /**
         * @see Zend_Service_Technorati_TagsResult
         */
        require_once 'Zend/Service/Technorati/TagsResult.php';
        return new Zend_Service_Technorati_TagsResult($this->_results->item($this->_currentIndex));
    }
}
Technorati/ResultSet.php000060400000016575150715514360011330 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Technorati_Result
 */
require_once 'Zend/Service/Technorati/Result.php';


/**
 * This is the most essential result set.
 * The scope of this class is to be extended by a query-specific child result set class,
 * and it should never be used to initialize a standalone object.
 *
 * Each of the specific result sets represents a collection of query-specific
 * Zend_Service_Technorati_Result objects.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @abstract
 */
abstract class Zend_Service_Technorati_ResultSet implements SeekableIterator
{
    /**
     * The total number of results available
     *
     * @var     int
     * @access  protected
     */
    protected $_totalResultsAvailable;

    /**
     * The number of results in this result set
     *
     * @var     int
     * @access  protected
     */
    protected $_totalResultsReturned;

    /**
     * The offset in the total result set of this search set
     *
     * @var     int
     * @todo
     */
    // public $firstResultPosition;


    /**
     * A DomNodeList of results
     *
     * @var     DomNodeList
     * @access  protected
     */
    protected $_results;

    /**
     * Technorati API response document
     *
     * @var     DomDocument
     * @access  protected
     */
    protected $_dom;

    /**
     * Object for $this->_dom
     *
     * @var     DOMXpath
     * @access  protected
     */
    protected $_xpath;

    /**
     * XML string representation for $this->_dom
     *
     * @var     string
     * @access  protected
     */
    protected $_xml;

    /**
     * Current Item
     *
     * @var     int
     * @access  protected
     */
    protected $_currentIndex = 0;


    /**
     * Parses the search response and retrieves the results for iteration.
     *
     * @param   DomDocument $dom    the ReST fragment for this object
     * @param   array $options      query options as associative array
     */
    public function __construct(DomDocument $dom, $options = array())
    {
        $this->_init($dom, $options);

        // Technorati loves to make developer's life really hard
        // I must read query options in order to normalize a single way
        // to display start and limit.
        // The value is printed out in XML using many different tag names,
        // too hard to get it from XML

        // Additionally, the following tags should be always available
        // according to API documentation but... this is not the truth!
        // - querytime
        // - limit
        // - start (sometimes rankingstart)

        // query tag is only available for some requests, the same for url.
        // For now ignore them.

        //$start = isset($options['start']) ? $options['start'] : 1;
        //$limit = isset($options['limit']) ? $options['limit'] : 20;
        //$this->_firstResultPosition = $start;
    }

    /**
     * Initializes this object from a DomDocument response.
     *
     * Because __construct and __wakeup shares some common executions,
     * it's useful to group them in a single initialization method.
     * This method is called once each time a new instance is created
     * or a serialized object is unserialized.
     *
     * @param   DomDocument $dom    the ReST fragment for this object
     * @param   array $options      query options as associative array
     *      * @return  void
     */
    protected function _init(DomDocument $dom, $options = array())
    {
        $this->_dom     = $dom;
        $this->_xpath   = new DOMXPath($dom);

        $this->_results = $this->_xpath->query("//item");
    }

    /**
     * Number of results returned.
     *
     * @return  int     total number of results returned
     */
    public function totalResults()
    {
        return (int) $this->_totalResultsReturned;
    }


    /**
     * Number of available results.
     *
     * @return  int     total number of available results
     */
    public function totalResultsAvailable()
    {
        return (int) $this->_totalResultsAvailable;
    }

    /**
     * Implements SeekableIterator::current().
     *
     * @return  void
     * @throws  Zend_Service_Exception
     * @abstract
     */
    // abstract public function current();

    /**
     * Implements SeekableIterator::key().
     *
     * @return  int
     */
    public function key()
    {
        return $this->_currentIndex;
    }

    /**
     * Implements SeekableIterator::next().
     *
     * @return  void
     */
    public function next()
    {
        $this->_currentIndex += 1;
    }

    /**
     * Implements SeekableIterator::rewind().
     *
     * @return  bool
     */
    public function rewind()
    {
        $this->_currentIndex = 0;
        return true;
    }

    /**
     * Implement SeekableIterator::seek().
     *
     * @param   int $index
     * @return  void
     * @throws  OutOfBoundsException
     */
    public function seek($index)
    {
        $indexInt = (int) $index;
        if ($indexInt >= 0 && $indexInt < $this->_results->length) {
            $this->_currentIndex = $indexInt;
        } else {
            throw new OutOfBoundsException("Illegal index '$index'");
        }
    }

    /**
     * Implement SeekableIterator::valid().
     *
     * @return boolean
     */
    public function valid()
    {
        return null !== $this->_results && $this->_currentIndex < $this->_results->length;
    }

    /**
     * Returns the response document as XML string.
     *
     * @return string   the response document converted into XML format
     */
    public function getXml()
    {
        return $this->_dom->saveXML();
    }

    /**
     * Overwrites standard __sleep method to make this object serializable.
     *
     * DomDocument and DOMXpath objects cannot be serialized.
     * This method converts them back to an XML string.
     *
     * @return void
     */
    public function __sleep() {
        $this->_xml     = $this->getXml();
        $vars = array_keys(get_object_vars($this));
        return array_diff($vars, array('_dom', '_xpath'));
    }

    /**
     * Overwrites standard __wakeup method to make this object unserializable.
     *
     * Restores object status before serialization.
     * Converts XML string into a DomDocument object and creates a valid
     * DOMXpath instance for given DocDocument.
     *
     * @return void
     */
    public function __wakeup() {
        $dom = new DOMDocument();
        $dom->loadXml($this->_xml);
        $this->_init($dom);
        $this->_xml = null; // reset XML content
    }
}
Technorati/CosmosResultSet.php000060400000012365150715514360012505 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: CosmosResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_ResultSet 
 */
require_once 'Zend/Service/Technorati/ResultSet.php';


/**
 * Represents a Technorati Cosmos query result set.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_CosmosResultSet extends Zend_Service_Technorati_ResultSet
{
    /**
     * Technorati weblog url, if queried URL is a valid weblog.
     *
     * @var     Zend_Uri_Http
     * @access  protected
     */
    protected $_url;

    /**
     * Technorati weblog, if queried URL is a valid weblog.
     *
     * @var     Zend_Service_Technorati_Weblog
     * @access  protected
     */
    protected $_weblog;

    /**
     * Number of unique blogs linking this blog
     *
     * @var     integer
     * @access  protected
     */
    protected $_inboundBlogs;

    /**
     * Number of incoming links to this blog
     *
     * @var     integer
     * @access  protected
     */
    protected $_inboundLinks;

    /**
     * Parses the search response and retrieve the results for iteration.
     *
     * @param   DomDocument $dom    the ReST fragment for this object
     * @param   array $options      query options as associative array
     */
    public function __construct(DomDocument $dom, $options = array())
    {
        parent::__construct($dom, $options);

        $result = $this->_xpath->query('/tapi/document/result/inboundlinks/text()');
        if ($result->length == 1) $this->_inboundLinks = (int) $result->item(0)->data;

        $result = $this->_xpath->query('/tapi/document/result/inboundblogs/text()');
        if ($result->length == 1) $this->_inboundBlogs = (int) $result->item(0)->data;

        $result = $this->_xpath->query('/tapi/document/result/weblog');
        if ($result->length == 1) {
            /**
             * @see Zend_Service_Technorati_Weblog
             */
            require_once 'Zend/Service/Technorati/Weblog.php';
            $this->_weblog = new Zend_Service_Technorati_Weblog($result->item(0));
        }

        $result = $this->_xpath->query('/tapi/document/result/url/text()');
        if ($result->length == 1) {
            try {
                // fetched URL often doens't include schema 
                // and this issue causes the following line to fail
                $this->_url = Zend_Service_Technorati_Utils::normalizeUriHttp($result->item(0)->data);
            } catch(Zend_Service_Technorati_Exception $e) {
                if ($this->getWeblog() instanceof Zend_Service_Technorati_Weblog) {
                    $this->_url = $this->getWeblog()->getUrl();
                }
            }
        }

        $this->_totalResultsReturned  = (int) $this->_xpath->evaluate("count(/tapi/document/item)");

        // total number of results depends on query type
        // for now check only getInboundLinks() and getInboundBlogs() value
        if ((int) $this->getInboundLinks() > 0) {
            $this->_totalResultsAvailable = $this->getInboundLinks();
        } elseif ((int) $this->getInboundBlogs() > 0) {
            $this->_totalResultsAvailable = $this->getInboundBlogs();
        } else {
            $this->_totalResultsAvailable = 0;
        }
    }


    /**
     * Returns the weblog URL.
     * 
     * @return  Zend_Uri_Http
     */
    public function getUrl() {
        return $this->_url;
    }

    /**
     * Returns the weblog.
     * 
     * @return  Zend_Service_Technorati_Weblog
     */
    public function getWeblog() {
        return $this->_weblog;
    }

    /**
     * Returns number of unique blogs linking this blog.
     * 
     * @return  integer the number of inbound blogs
     */
    public function getInboundBlogs() 
    {
        return $this->_inboundBlogs;
    }

    /**
     * Returns number of incoming links to this blog.
     * 
     * @return  integer the number of inbound links
     */
    public function getInboundLinks() 
    {
        return $this->_inboundLinks;
    }

    /**
     * Implements Zend_Service_Technorati_ResultSet::current().
     *
     * @return Zend_Service_Technorati_CosmosResult current result
     */
    public function current()
    {
        /**
         * @see Zend_Service_Technorati_CosmosResult
         */
        require_once 'Zend/Service/Technorati/CosmosResult.php';
        return new Zend_Service_Technorati_CosmosResult($this->_results->item($this->_currentIndex));
    }
}
Technorati/GetInfoResult.php000060400000005351150715514360012116 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: GetInfoResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Represents a single Technorati GetInfo query result object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_GetInfoResult
{
    /**
     * Technorati author
     *
     * @var     Zend_Service_Technorati_Author
     * @access  protected
     */
    protected $_author;

    /**
     * A list of weblogs claimed by this author
     *
     * @var     array
     * @access  protected
     */
    protected $_weblogs = array();


    /**
     * Constructs a new object object from DOM Document.
     *
     * @param   DomDocument $dom the ReST fragment for this object
     */
    public function __construct(DomDocument $dom)
    {
        $xpath = new DOMXPath($dom);

        /**
         * @see Zend_Service_Technorati_Author
         */
        require_once 'Zend/Service/Technorati/Author.php';

        $result = $xpath->query('//result');
        if ($result->length == 1) {
            $this->_author = new Zend_Service_Technorati_Author($result->item(0));
        }

        /**
         * @see Zend_Service_Technorati_Weblog
         */
        require_once 'Zend/Service/Technorati/Weblog.php';

        $result = $xpath->query('//item/weblog');
        if ($result->length >= 1) {
            foreach ($result as $weblog) {
                $this->_weblogs[] = new Zend_Service_Technorati_Weblog($weblog);
            }
        }
    }


    /**
     * Returns the author associated with queried username.
     * 
     * @return  Zend_Service_Technorati_Author
     */
    public function getAuthor() {
        return $this->_author;
    }

    /**
     * Returns the collection of weblogs authored by queried username.
     * 
     * @return  array of Zend_Service_Technorati_Weblog
     */
    public function getWeblogs() {
        return $this->_weblogs;
    }

}
Technorati/TagResult.php000060400000010556150715514360011301 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: TagResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_Result 
 */
require_once 'Zend/Service/Technorati/Result.php';


/**
 * Represents a single Technorati Tag query result object. 
 * It is never returned as a standalone object, 
 * but it always belongs to a valid Zend_Service_Technorati_TagResultSet object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_TagResult extends Zend_Service_Technorati_Result
{
    /**
     * Technorati weblog object corresponding to queried keyword.
     * 
     * @var     Zend_Service_Technorati_Weblog
     * @access  protected
     */
    protected $_weblog;

    /**
     * The title of the entry.
     * 
     * @var     string
     * @access  protected
     */
    protected $_title;
    
    /**
     * The blurb from entry with search term highlighted.
     * 
     * @var     string
     * @access  protected
     */
    protected $_excerpt;

    /**
     * The datetime the entry was created.
     * 
     * @var     Zend_Date
     * @access  protected
     */
    protected $_created;
    
    /**
     * The datetime the entry was updated.
     * Called 'postupdate' in original XML response,
     * it has been renamed to provide more coherence.
     * 
     * @var     Zend_Date
     * @access  protected
     */
    protected $_updated;
    
    /**
     * The permalink of the blog entry.
     * 
     * @var     Zend_Uri_Http
     * @access  protected
     */
    protected $_permalink;
    

    /**
     * Constructs a new object object from DOM Element.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $this->_fields = array( '_permalink'    => 'permalink',
                                '_excerpt'      => 'excerpt',
                                '_created'      => 'created',
                                '_updated'      => 'postupdate',
                                '_title'        => 'title');
        parent::__construct($dom);

        // weblog object field
        $this->_parseWeblog();

        // filter fields
        $this->_permalink = Zend_Service_Technorati_Utils::normalizeUriHttp($this->_permalink);
        $this->_created = Zend_Service_Technorati_Utils::normalizeDate($this->_created);
        $this->_updated = Zend_Service_Technorati_Utils::normalizeDate($this->_updated);
    }

    /**
     * Returns the weblog object that links queried URL.
     * 
     * @return  Zend_Service_Technorati_Weblog
     */
    public function getWeblog() {
        return $this->_weblog;
    }
    
    /**
     * Returns the title of the entry.
     * 
     * @return  string
     */
    public function getTitle() {
        return $this->_title;
    }
    
    /**
     * Returns the blurb from entry with search term highlighted.
     * 
     * @return  string
     */
    public function getExcerpt() {
        return $this->_excerpt;
    }
        
    /**
     * Returns the datetime the entry was created.
     * 
     * @return  Zend_Date
     */
    public function getCreated() {
        return $this->_created;
    }
        
    /**
     * Returns the datetime the entry was updated.
     * 
     * @return  Zend_Date
     */
    public function getUpdated() {
        return $this->_updated;
    }
    
    /**
     * Returns the permalink of the blog entry.
     * 
     * @return  Zend_Uri_Http
     */
    public function getPermalink() {
        return $this->_permalink;
    }
    
}
Technorati/KeyInfoResult.php000060400000006210150715514360012122 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: KeyInfoResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Represents a single Technorati KeyInfo query result object.
 * It provides information about your Technorati API Key daily usage.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_KeyInfoResult
{
    /**
     * Technorati API key
     *
     * @var     string
     * @access  protected
     */
    protected $_apiKey;

    /**
     * Number of queries used today
     *
     * @var     int
     * @access  protected
     */
    protected $_apiQueries;

    /**
     * Total number of available queries per day
     *
     * @var     int
     * @access  protected
     */
    protected $_maxQueries;
    

    /**
     * Constructs a new object from DOM Element.
     * Parses given Key element from $dom and sets API key string.
     *
     * @param   DomElement $dom the ReST fragment for this object
     * @param   string $apiKey  the API Key string
     */
    public function __construct(DomDocument $dom, $apiKey = null)
    {
        // $this->_dom   = $dom;
        // $this->_xpath = new DOMXPath($dom);
        $xpath = new DOMXPath($dom);

        $this->_apiQueries   = (int) $xpath->query('/tapi/document/result/apiqueries/text()')->item(0)->data;
        $this->_maxQueries   = (int) $xpath->query('/tapi/document/result/maxqueries/text()')->item(0)->data;
        $this->setApiKey($apiKey);
    }
    
    
    /**
     * Returns API Key string.
     * 
     * @return  string  API Key string
     */
    public function getApiKey() {
        return $this->_apiKey;
    }
    
    /**
     * Returns the number of queries sent today.
     * 
     * @return  int     number of queries sent today
     */
    public function getApiQueries() {
        return $this->_apiQueries;
    }
    
    /**
     * Returns Key's daily query limit.
     * 
     * @return  int     maximum number of available queries per day
     */
    public function getMaxQueries() {
        return $this->_maxQueries;
    }
    
    
    /**
     * Sets API Key string.
     * 
     * @param   string $apiKey  the API Key
     * @return  Zend_Service_Technorati_KeyInfoResult $this instance
     */
    public function setApiKey($apiKey) {
        $this->_apiKey = $apiKey;
        return $this;
    }
}
Technorati/Author.php000060400000014377150715514360010636 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Author.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Technorati_Utils
 */
require_once 'Zend/Service/Technorati/Utils.php';


/**
 * Represents a weblog Author object. It usually belongs to a Technorati account.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_Author
{
    /**
     * Author first name
     *
     * @var     string
     * @access  protected
     */
    protected $_firstName;

    /**
     * Author last name
     *
     * @var     string
     * @access  protected
     */
    protected $_lastName;
    
    /**
     * Technorati account username
     *
     * @var     string
     * @access  protected
     */
    protected $_username;
    
    /**
     * Technorati account description
     *
     * @var     string
     * @access  protected
     */
    protected $_description;

    /**
     * Technorati account biography
     *
     * @var     string
     * @access  protected
     */
    protected $_bio;

    /**
     * Technorati account thumbnail picture URL, if any
     *
     * @var     null|Zend_Uri_Http
     * @access  protected
     */
    protected $_thumbnailPicture;


    /**
     * Constructs a new object from DOM Element.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);

        $result = $xpath->query('./firstname/text()', $dom);
        if ($result->length == 1) $this->setFirstName($result->item(0)->data);
        
        $result = $xpath->query('./lastname/text()', $dom);
        if ($result->length == 1) $this->setLastName($result->item(0)->data);
        
        $result = $xpath->query('./username/text()', $dom);
        if ($result->length == 1) $this->setUsername($result->item(0)->data);
        
        $result = $xpath->query('./description/text()', $dom);
        if ($result->length == 1) $this->setDescription($result->item(0)->data);
        
        $result = $xpath->query('./bio/text()', $dom);
        if ($result->length == 1) $this->setBio($result->item(0)->data);

        $result = $xpath->query('./thumbnailpicture/text()', $dom);
        if ($result->length == 1) $this->setThumbnailPicture($result->item(0)->data);
    }
    

    /**
     * Returns Author first name.
     * 
     * @return  string  Author first name
     */
    public function getFirstName() {
        return $this->_firstName;
    }

    /**
     * Returns Author last name.
     * 
     * @return  string  Author last name
     */
    public function getLastName() {
        return $this->_lastName;
    }

    /**
     * Returns Technorati account username.
     * 
     * @return  string  Technorati account username
     */
    public function getUsername() {
        return $this->_username;
    }

    /**
     * Returns Technorati account description.
     * 
     * @return  string  Technorati account description
     */
    public function getDescription() {
        return $this->_description;
    }

    /**
     * Returns Technorati account biography.
     * 
     * @return  string  Technorati account biography
     */
    public function getBio() {
        return $this->_bio;
    }

    /**
     * Returns Technorati account thumbnail picture.
     * 
     * @return  null|Zend_Uri_Http  Technorati account thumbnail picture
     */
    public function getThumbnailPicture() {
        return $this->_thumbnailPicture;
    }


    /**
     * Sets author first name.
     * 
     * @param   string $input   first Name input value 
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setFirstName($input) {
        $this->_firstName = (string) $input;
        return $this;
    }

    /**
     * Sets author last name.
     * 
     * @param   string $input   last Name input value 
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setLastName($input) {
        $this->_lastName = (string) $input;
        return $this;
    }

    /**
     * Sets Technorati account username.
     * 
     * @param   string $input   username input value 
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setUsername($input) {
        $this->_username = (string) $input;
        return $this;
    }

    /**
     * Sets Technorati account biography.
     * 
     * @param   string $input   biography input value
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setBio($input) {
        $this->_bio = (string) $input;
        return $this;
    }

    /**
     * Sets Technorati account description.
     * 
     * @param   string $input   description input value
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setDescription($input) {
        $this->_description = (string) $input;
        return $this;
    }

    /**
     * Sets Technorati account thumbnail picture.
     * 
     * @param   string|Zend_Uri_Http $input thumbnail picture URI
     * @return  Zend_Service_Technorati_Author  $this instance
     * @throws  Zend_Service_Technorati_Exception if $input is an invalid URI
     *          (via Zend_Service_Technorati_Utils::normalizeUriHttp)
     */
    public function setThumbnailPicture($input) {
        $this->_thumbnailPicture = Zend_Service_Technorati_Utils::normalizeUriHttp($input);
        return $this;
    }

}
Technorati/SearchResult.php000060400000007451150715514360011773 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SearchResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_Result 
 */
require_once 'Zend/Service/Technorati/Result.php';


/**
 * Represents a single Technorati Search query result object. 
 * It is never returned as a standalone object, 
 * but it always belongs to a valid Zend_Service_Technorati_SearchResultSet object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_SearchResult extends Zend_Service_Technorati_Result
{
    /**
     * Technorati weblog object corresponding to queried keyword.
     * 
     * @var     Zend_Service_Technorati_Weblog
     * @access  protected
     */
    protected $_weblog;

    /**
     * The title of the entry.
     * 
     * @var     string
     * @access  protected
     */
    protected $_title;
    
    /**
     * The blurb from entry with search term highlighted.
     * 
     * @var     string
     * @access  protected
     */
    protected $_excerpt;

    /**
     * The datetime the entry was created.
     * 
     * @var     Zend_Date
     * @access  protected
     */
    protected $_created;

    /**
     * The permalink of the blog entry.
     * 
     * @var     Zend_Uri_Http
     * @access  protected
     */
    protected $_permalink;
    

    /**
     * Constructs a new object object from DOM Element.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $this->_fields = array( '_permalink'    => 'permalink',
                                '_excerpt'      => 'excerpt',
                                '_created'      => 'created',
                                '_title'        => 'title');
        parent::__construct($dom);

        // weblog object field
        $this->_parseWeblog();

        // filter fields
        $this->_permalink = Zend_Service_Technorati_Utils::normalizeUriHttp($this->_permalink);
        $this->_created = Zend_Service_Technorati_Utils::normalizeDate($this->_created);
    }

    /**
     * Returns the weblog object that links queried URL.
     * 
     * @return  Zend_Service_Technorati_Weblog
     */
    public function getWeblog() {
        return $this->_weblog;
    }
    
    /**
     * Returns the title of the entry.
     * 
     * @return  string
     */
    public function getTitle() {
        return $this->_title;
    }
    
    /**
     * Returns the blurb from entry with search term highlighted.
     * 
     * @return  string
     */
    public function getExcerpt() {
        return $this->_excerpt;
    }
        
    /**
     * Returns the datetime the entry was created.
     * 
     * @return  Zend_Date
     */
    public function getCreated() {
        return $this->_created;
    }
        
    /**
     * Returns the permalink of the blog entry.
     * 
     * @return  Zend_Uri_Http
     */
    public function getPermalink() {
        return $this->_permalink;
    }
    
}
Technorati/Weblog.php000060400000030253150715514360010602 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Weblog.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Technorati_Author
 */
require_once 'Zend/Service/Technorati/Author.php';

/**
 * @see Zend_Service_Technorati_Utils
 */
require_once 'Zend/Service/Technorati/Utils.php';


/**
 * Represents a Weblog object successful recognized by Technorati.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_Weblog
{
    /**
     * Blog name as written in the feed.
     *
     * @var     string
     * @access  protected
     */
    protected $_name;

    /**
     * Base blog URL.
     *
     * @var     Zend_Uri_Http
     * @access  protected
     */
    protected $_url;

    /**
     * RSS feed URL, if any.
     *
     * @var     null|Zend_Uri_Http
     * @access  protected
     */
    protected $_rssUrl;

    /**
     * Atom feed URL, if any.
     *
     * @var     null|Zend_Uri_Http
     * @access  protected
     */
    protected $_atomUrl;

    /**
     * Number of unique blogs linking this blog.
     *
     * @var     integer
     * @access  protected
     */
    protected $_inboundBlogs;

    /**
     * Number of incoming links to this blog.
     *
     * @var     integer
     * @access  protected
     */
    protected $_inboundLinks;

    /**
     * Last blog update UNIX timestamp.
     *
     * @var     null|Zend_Date
     * @access  protected
     */
    protected $_lastUpdate;

    /**
     * Technorati rank value for this weblog.
     * 
     * Note. This property has no official documentation.
     *
     * @var     integer
     * @access  protected
     */
    protected $_rank;
    
    /**
     * Blog latitude coordinate.
     * 
     * Note. This property has no official documentation.
     *
     * @var     float
     * @access  protected
     */
    protected $_lat;

    /**
     * Blog longitude coordinate.
     * 
     * Note. This property has no official documentation.
     *
     * @var     float
     * @access  protected
     */
    protected $_lon;

    /**
     * Whether the author who claimed this weblog has a photo.
     * 
     * Note. This property has no official documentation.
     *
     * @var     bool
     * @access  protected
     * @see     Zend_Service_Technorati_Author::$thumbnailPicture
     */
    protected $_hasPhoto = false;

    /**
     * An array of Zend_Service_Technorati_Author who claimed this blog
     *
     * @var     array
     * @access  protected
     */
    protected $_authors = array();


    /**
     * Constructs a new object from DOM Element.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);

        $result = $xpath->query('./name/text()', $dom);
        if ($result->length == 1) $this->setName($result->item(0)->data);

        $result = $xpath->query('./url/text()', $dom);
        if ($result->length == 1) $this->setUrl($result->item(0)->data);
        
        $result = $xpath->query('./inboundblogs/text()', $dom);
        if ($result->length == 1) $this->setInboundBlogs($result->item(0)->data);
        
        $result = $xpath->query('./inboundlinks/text()', $dom);
        if ($result->length == 1) $this->setInboundLinks($result->item(0)->data);
        
        $result = $xpath->query('./lastupdate/text()', $dom);
        if ($result->length == 1) $this->setLastUpdate($result->item(0)->data);

        /* The following elements need more attention */

        $result = $xpath->query('./rssurl/text()', $dom);
        if ($result->length == 1) $this->setRssUrl($result->item(0)->data);
        
        $result = $xpath->query('./atomurl/text()', $dom);
        if ($result->length == 1) $this->setAtomUrl($result->item(0)->data);
                            
        $result = $xpath->query('./author', $dom);
        if ($result->length >= 1) {
            foreach ($result as $author) {
                $this->_authors[] = new Zend_Service_Technorati_Author($author);
            }
        }

        /**
         * The following are optional elements
         * 
         * I can't find any official documentation about the following properties
         * however they are included in response DTD and/or test responses.
         */
        
        $result = $xpath->query('./rank/text()', $dom);
        if ($result->length == 1) $this->setRank($result->item(0)->data);

        $result = $xpath->query('./lat/text()', $dom);
        if ($result->length == 1) $this->setLat($result->item(0)->data);

        $result = $xpath->query('./lon/text()', $dom);
        if ($result->length == 1) $this->setLon($result->item(0)->data);

        $result = $xpath->query('./hasphoto/text()', $dom);
        if ($result->length == 1) $this->setHasPhoto($result->item(0)->data);
    }
    
    
    /**
     * Returns weblog name.
     * 
     * @return  string  Weblog name
     */
    public function getName() 
    {
        return $this->_name;
    }
    
    /**
     * Returns weblog URL.
     * 
     * @return  null|Zend_Uri_Http object representing weblog base URL
     */
    public function getUrl() 
    {
        return $this->_url;
    }
    
    /**
     * Returns number of unique blogs linking this blog.
     * 
     * @return  integer the number of inbound blogs
     */
    public function getInboundBlogs() 
    {
        return $this->_inboundBlogs;
    }
    
    /**
     * Returns number of incoming links to this blog.
     * 
     * @return  integer the number of inbound links
     */
    public function getInboundLinks() 
    {
        return $this->_inboundLinks;
    }
    
    /**
     * Returns weblog Rss URL.
     * 
     * @return  null|Zend_Uri_Http object representing the URL
     *          of the RSS feed for given blog
     */
    public function getRssUrl() 
    {
        return $this->_rssUrl;
    }
    
    /**
     * Returns weblog Atom URL.
     * 
     * @return  null|Zend_Uri_Http object representing the URL
     *          of the Atom feed for given blog
     */
    public function getAtomUrl() 
    {
        return $this->_atomUrl;
    }
    
    /**
     * Returns UNIX timestamp of the last weblog update.
     * 
     * @return  integer UNIX timestamp of the last weblog update
     */
    public function getLastUpdate() 
    {
        return $this->_lastUpdate;
    }
    
    /**
     * Returns weblog rank value.
     * 
     * Note. This property is not documented.
     * 
     * @return  integer weblog rank value
     */
    public function getRank() 
    {
        return $this->_rank;
    }
        
    /**
     * Returns weblog latitude coordinate.
     * 
     * Note. This property is not documented.
     * 
     * @return  float   weblog latitude coordinate
     */
    public function getLat() {
        return $this->_lat;
    }
        
    /**
     * Returns weblog longitude coordinate.
     * 
     * Note. This property is not documented.
     * 
     * @return  float   weblog longitude coordinate
     */
    public function getLon() 
    {
        return $this->_lon;
    }
    
    /**
     * Returns whether the author who claimed this weblog has a photo.
     * 
     * Note. This property is not documented.
     * 
     * @return  bool    TRUE if the author who claimed this weblog has a photo,
     *                  FALSE otherwise.
     */
    public function hasPhoto() 
    {
        return (bool) $this->_hasPhoto;
    }

    /**
     * Returns the array of weblog authors.
     * 
     * @return  array of Zend_Service_Technorati_Author authors
     */
    public function getAuthors() 
    {
        return (array) $this->_authors;
    }


    /**
     * Sets weblog name.
     * 
     * @param   string $name
     * @return  Zend_Service_Technorati_Weblog $this instance
     */
    public function setName($name) 
    {
        $this->_name = (string) $name;
        return $this;
    }

    /**
     * Sets weblog URL.
     * 
     * @param   string|Zend_Uri_Http $url
     * @return  void
     * @throws  Zend_Service_Technorati_Exception if $input is an invalid URI
     *          (via Zend_Service_Technorati_Utils::normalizeUriHttp)
     */
    public function setUrl($url) 
    {
        $this->_url = Zend_Service_Technorati_Utils::normalizeUriHttp($url);
        return $this;
    }
    
    /**
     * Sets number of inbound blogs.
     * 
     * @param   integer $number
     * @return  Zend_Service_Technorati_Weblog $this instance
     */
    public function setInboundBlogs($number) 
    {
        $this->_inboundBlogs = (int) $number;
        return $this;
    }
    
    /**
     * Sets number of Iinbound links.
     * 
     * @param   integer $number
     * @return  Zend_Service_Technorati_Weblog $this instance
     */
    public function setInboundLinks($number) 
    {
        $this->_inboundLinks = (int) $number;
        return $this;
    }

    /**
     * Sets weblog Rss URL.
     * 
     * @param   string|Zend_Uri_Http $url
     * @return  Zend_Service_Technorati_Weblog $this instance
     * @throws  Zend_Service_Technorati_Exception if $input is an invalid URI
     *          (via Zend_Service_Technorati_Utils::normalizeUriHttp)
     */
    public function setRssUrl($url) 
    {
        $this->_rssUrl = Zend_Service_Technorati_Utils::normalizeUriHttp($url);
        return $this;
    }

    /**
     * Sets weblog Atom URL.
     * 
     * @param   string|Zend_Uri_Http $url
     * @return  Zend_Service_Technorati_Weblog $this instance
     * @throws  Zend_Service_Technorati_Exception if $input is an invalid URI
     *          (via Zend_Service_Technorati_Utils::normalizeUriHttp)
     */
    public function setAtomUrl($url) 
    {
        $this->_atomUrl = Zend_Service_Technorati_Utils::normalizeUriHttp($url);
        return $this;
    }
    
    /**
     * Sets weblog Last Update timestamp.
     * 
     * $datetime can be any value supported by 
     * Zend_Service_Technorati_Utils::normalizeDate().
     * 
     * @param   mixed $datetime A string representing the last update date time
     *                          in a valid date time format
     * @return  Zend_Service_Technorati_Weblog $this instance
     * @throws  Zend_Service_Technorati_Exception
     */
    public function setLastUpdate($datetime) 
    {
        $this->_lastUpdate = Zend_Service_Technorati_Utils::normalizeDate($datetime);
        return $this;
    }
    
    /**
     * Sets weblog Rank.
     * 
     * @param   integer $rank
     * @return  Zend_Service_Technorati_Weblog $this instance
     */
    public function setRank($rank) 
    {
        $this->_rank = (int) $rank;
        return $this;
    }
        
    /**
     * Sets weblog latitude coordinate.
     * 
     * @param   float $coordinate
     * @return  Zend_Service_Technorati_Weblog $this instance
     */
    public function setLat($coordinate) 
    {
        $this->_lat = (float) $coordinate;
        return $this;
    }
        
    /**
     * Sets weblog longitude coordinate.
     * 
     * @param   float $coordinate
     * @return  Zend_Service_Technorati_Weblog $this instance
     */
    public function setLon($coordinate) 
    {
        $this->_lon = (float) $coordinate;
        return $this;
    }
        
    /**
     * Sets hasPhoto property.
     * 
     * @param   bool $hasPhoto
     * @return  Zend_Service_Technorati_Weblog $this instance
     */
    public function setHasPhoto($hasPhoto) 
    {
        $this->_hasPhoto = (bool) $hasPhoto;
        return $this;
    }
    
}
Technorati/Result.php000060400000006703150715514360010644 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Result.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Represents a single Technorati Search query result object. 
 * It is never returned as a standalone object, 
 * but it always belongs to a valid Zend_Service_Technorati_SearchResultSet object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @abstract 
 */
abstract class Zend_Service_Technorati_Result
{
    /**
     * An associative array of 'fieldName' => 'xmlfieldtag'
     *
     * @var     array
     * @access  protected
     */
    protected $_fields;

    /**
     * The ReST fragment for this result object
     *
     * @var     DomElement
     * @access  protected
     */
    protected $_dom;

    /**
     * Object for $this->_dom
     *
     * @var     DOMXpath
     * @access  protected
     */
    protected $_xpath;


    /**
     * Constructs a new object from DOM Element.
     * Properties are automatically fetched from XML
     * according to array of $_fields to be read.
     *
     * @param   DomElement $result  the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $this->_xpath = new DOMXPath($dom->ownerDocument);
        $this->_dom = $dom;
        
        // default fields for all search results
        $fields = array();

        // merge with child's object fields
        $this->_fields = array_merge($this->_fields, $fields);

        // add results to appropriate fields
        foreach($this->_fields as $phpName => $xmlName) {
            $query = "./$xmlName/text()";
            $node = $this->_xpath->query($query, $this->_dom);
            if ($node->length == 1) {
                $this->{$phpName} = (string) $node->item(0)->data;
            }
        }
    }
    
    /**
     * Parses weblog node and sets weblog object.
     * 
     * @return  void
     */
    protected function _parseWeblog()
    {
        // weblog object field
        $result = $this->_xpath->query('./weblog', $this->_dom);
        if ($result->length == 1) {
            /**
             * @see Zend_Service_Technorati_Weblog
             */
            require_once 'Zend/Service/Technorati/Weblog.php';
            $this->_weblog = new Zend_Service_Technorati_Weblog($result->item(0));
        } else {
            $this->_weblog = null;
        }
    }

    /**
     * Returns the document fragment for this object as XML string.
     *
     * @return string   the document fragment for this object
     *                  converted into XML format
     */
    public function getXml()
    {
        return $this->_dom->ownerDocument->saveXML($this->_dom);
    }
}
Technorati/DailyCountsResultSet.php000060400000007114150715514360013474 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: DailyCountsResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Date
 */
require_once 'Zend/Date.php';

/** 
 * @see Zend_Service_Technorati_ResultSet 
 */
require_once 'Zend/Service/Technorati/ResultSet.php';

/**
 * @see Zend_Service_Technorati_Utils
 */
require_once 'Zend/Service/Technorati/Utils.php';


/**
 * Represents a Technorati Tag query result set.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_DailyCountsResultSet extends Zend_Service_Technorati_ResultSet
{
    /**
     * Technorati search URL for given query.
     *
     * @var     Zend_Uri_Http
     * @access  protected
     */
    protected $_searchUrl;

    /**
     * Number of days for which counts provided.
     * 
     * @var     Zend_Service_Technorati_Weblog
     * @access  protected
     */
    protected $_days;

    /**
     * Parses the search response and retrieve the results for iteration.
     *
     * @param   DomDocument $dom    the ReST fragment for this object
     * @param   array $options      query options as associative array
     */
    public function __construct(DomDocument $dom, $options = array())
    {
        parent::__construct($dom, $options);
        
        // default locale prevent Zend_Date to fail
        // when script is executed via shell
        // Zend_Locale::setDefault('en');

        $result = $this->_xpath->query('/tapi/document/result/days/text()');
        if ($result->length == 1) $this->_days = (int) $result->item(0)->data;

        $result = $this->_xpath->query('/tapi/document/result/searchurl/text()');
        if ($result->length == 1) {
            $this->_searchUrl = Zend_Service_Technorati_Utils::normalizeUriHttp($result->item(0)->data);
        }

        $this->_totalResultsReturned  = (int) $this->_xpath->evaluate("count(/tapi/document/items/item)");
        $this->_totalResultsAvailable = (int) $this->getDays();
    }


    /**
     * Returns the search URL for given query.
     * 
     * @return  Zend_Uri_Http
     */
    public function getSearchUrl() {
        return $this->_searchUrl;
    }

    /**
     * Returns the number of days for which counts provided.
     * 
     * @return  int
     */
    public function getDays() {
        return $this->_days;
    }

    /**
     * Implements Zend_Service_Technorati_ResultSet::current().
     *
     * @return Zend_Service_Technorati_DailyCountsResult current result
     */
    public function current()
    {
        /**
         * @see Zend_Service_Technorati_DailyCountsResult
         */
        require_once 'Zend/Service/Technorati/DailyCountsResult.php';
        return new Zend_Service_Technorati_DailyCountsResult($this->_results->item($this->_currentIndex));
    }
}
Technorati/SearchResultSet.php000060400000005007150715514360012442 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SearchResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_ResultSet 
 */
require_once 'Zend/Service/Technorati/ResultSet.php';


/**
 * Represents a Technorati Search query result set.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_SearchResultSet extends Zend_Service_Technorati_ResultSet
{
    /**
     * Number of query results.
     *
     * @var     int
     * @access  protected
     */
    protected $_queryCount;

    /**
     * Parses the search response and retrieve the results for iteration.
     *
     * @param   DomDocument $dom    the ReST fragment for this object
     * @param   array $options      query options as associative array
     */
    public function __construct(DomDocument $dom, $options = array())
    {
        parent::__construct($dom, $options);

        $result = $this->_xpath->query('/tapi/document/result/querycount/text()');
        if ($result->length == 1) $this->_queryCount = (int) $result->item(0)->data;
        
        $this->_totalResultsReturned  = (int) $this->_xpath->evaluate("count(/tapi/document/item)");
        $this->_totalResultsAvailable = (int) $this->_queryCount;
    }

    /**
     * Implements Zend_Service_Technorati_ResultSet::current().
     *
     * @return Zend_Service_Technorati_SearchResult current result
     */
    public function current()
    {
        /**
         * @see Zend_Service_Technorati_SearchResult
         */
        require_once 'Zend/Service/Technorati/SearchResult.php';
        return new Zend_Service_Technorati_SearchResult($this->_results->item($this->_currentIndex));
    }
}
Technorati/TagsResult.php000060400000004634150715514360011464 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: TagsResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_Result 
 */
require_once 'Zend/Service/Technorati/Result.php';


/**
 * Represents a single Technorati TopTags or BlogPostTags query result object. 
 * It is never returned as a standalone object, 
 * but it always belongs to a valid Zend_Service_Technorati_TagsResultSet object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_TagsResult extends Zend_Service_Technorati_Result
{
    /**
     * Name of the tag.
     * 
     * @var     string
     * @access  protected
     */
    protected $_tag;
    
    /**
     * Number of posts containing this tag.
     * 
     * @var     int
     * @access  protected
     */
    protected $_posts;
    

    /**
     * Constructs a new object object from DOM Document.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $this->_fields = array( '_tag'   => 'tag',
                                '_posts' => 'posts');
        parent::__construct($dom);
        
        // filter fields
        $this->_tag   = (string) $this->_tag;
        $this->_posts = (int) $this->_posts;
    }

    /**
     * Returns the tag name.
     * 
     * @return  string
     */
    public function getTag() {
        return $this->_tag;
    }
    
    /**
     * Returns the number of posts.
     * 
     * @return  int
     */
    public function getPosts() {
        return $this->_posts;
    }
}
Technorati/BlogInfoResult.php000060400000010767150715514360012271 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: BlogInfoResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Technorati_Utils
 */
require_once 'Zend/Service/Technorati/Utils.php';


/**
 * Represents a single Technorati BlogInfo query result object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_BlogInfoResult
{
    /**
     * Technorati weblog url, if queried URL is a valid weblog.
     *
     * @var     Zend_Uri_Http
     * @access  protected
     */
    protected $_url;

    /**
     * Technorati weblog, if queried URL is a valid weblog.
     *
     * @var     Zend_Service_Technorati_Weblog
     * @access  protected
     */
    protected $_weblog;

    /**
     * Number of unique blogs linking this blog
     *
     * @var     integer
     * @access  protected
     */
    protected $_inboundBlogs;

    /**
     * Number of incoming links to this blog
     *
     * @var     integer
     * @access  protected
     */
    protected $_inboundLinks;
    

    /**
     * Constructs a new object object from DOM Document.
     *
     * @param   DomDocument $dom the ReST fragment for this object
     */
    public function __construct(DomDocument $dom)
    {
        $xpath = new DOMXPath($dom);
        /**
         * @see Zend_Service_Technorati_Weblog
         */
        require_once 'Zend/Service/Technorati/Weblog.php';

        $result = $xpath->query('//result/weblog');
        if ($result->length == 1) {
            $this->_weblog = new Zend_Service_Technorati_Weblog($result->item(0));
        } else {
            // follow the same behavior of blogPostTags 
            // and raise an Exception if the URL is not a valid weblog
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception(
                "Your URL is not a recognized Technorati weblog");
        }
        
        $result = $xpath->query('//result/url/text()');
        if ($result->length == 1) {
            try {
                // fetched URL often doens't include schema 
                // and this issue causes the following line to fail
                $this->_url = Zend_Service_Technorati_Utils::normalizeUriHttp($result->item(0)->data);
            } catch(Zend_Service_Technorati_Exception $e) {
                if ($this->getWeblog() instanceof Zend_Service_Technorati_Weblog) {
                    $this->_url = $this->getWeblog()->getUrl();
                }
            }
        }
        
        $result = $xpath->query('//result/inboundblogs/text()');
        if ($result->length == 1) $this->_inboundBlogs = (int) $result->item(0)->data;
        
        $result = $xpath->query('//result/inboundlinks/text()');
        if ($result->length == 1) $this->_inboundLinks = (int) $result->item(0)->data;
        
    }


    /**
     * Returns the weblog URL.
     * 
     * @return  Zend_Uri_Http
     */
    public function getUrl() {
        return $this->_url;
    }
    
    /**
     * Returns the weblog.
     * 
     * @return  Zend_Service_Technorati_Weblog
     */
    public function getWeblog() {
        return $this->_weblog;
    }
    
    /**
     * Returns number of unique blogs linking this blog.
     * 
     * @return  integer the number of inbound blogs
     */
    public function getInboundBlogs() 
    {
        return (int) $this->_inboundBlogs;
    }
    
    /**
     * Returns number of incoming links to this blog.
     * 
     * @return  integer the number of inbound links
     */
    public function getInboundLinks() 
    {
        return (int) $this->_inboundLinks;
    }
    
}
Technorati/DailyCountsResult.php000060400000004760150715514360013024 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: DailyCountsResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_Result 
 */
require_once 'Zend/Service/Technorati/Result.php';


/**
 * Represents a single Technorati DailyCounts query result object. 
 * It is never returned as a standalone object, 
 * but it always belongs to a valid Zend_Service_Technorati_DailyCountsResultSet object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_DailyCountsResult extends Zend_Service_Technorati_Result
{
    /**
     * Date of count.
     * 
     * @var     Zend_Date
     * @access  protected
     */
    protected $_date;
    
    /**
     * Number of posts containing query on given date.
     * 
     * @var     int
     * @access  protected
     */
    protected $_count;
    

    /**
     * Constructs a new object object from DOM Document.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $this->_fields = array( '_date'   => 'date',
                                '_count'  => 'count');
        parent::__construct($dom);
        
        // filter fields
        $this->_date  = new Zend_Date(strtotime($this->_date));
        $this->_count = (int) $this->_count;
    }

    /**
     * Returns the date of count.
     * 
     * @return  Zend_Date
     */
    public function getDate() {
        return $this->_date;
    }
    
    /**
     * Returns the number of posts containing query on given date.
     * 
     * @return  int
     */
    public function getCount() {
        return $this->_count;
    }
}
Technorati/TagResultSet.php000060400000006342150715514360011753 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: TagResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_ResultSet 
 */
require_once 'Zend/Service/Technorati/ResultSet.php';


/**
 * Represents a Technorati Tag query result set.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_TagResultSet extends Zend_Service_Technorati_ResultSet
{
    /**
     * Number of posts that match the tag.
     *
     * @var     int
     * @access  protected
     */
    protected $_postsMatched;

    /**
     * Number of blogs that match the tag.
     *
     * @var     int
     * @access  protected
     */
    protected $_blogsMatched;

    /**
     * Parses the search response and retrieve the results for iteration.
     *
     * @param   DomDocument $dom    the ReST fragment for this object
     * @param   array $options      query options as associative array
     */
    public function __construct(DomDocument $dom, $options = array())
    {
        parent::__construct($dom, $options);

        $result = $this->_xpath->query('/tapi/document/result/postsmatched/text()');
        if ($result->length == 1) $this->_postsMatched = (int) $result->item(0)->data;

        $result = $this->_xpath->query('/tapi/document/result/blogsmatched/text()');
        if ($result->length == 1) $this->_blogsMatched = (int) $result->item(0)->data;

        $this->_totalResultsReturned  = (int) $this->_xpath->evaluate("count(/tapi/document/item)");
        /** @todo Validate the following assertion */
        $this->_totalResultsAvailable = (int) $this->getPostsMatched();
    }


    /**
     * Returns the number of posts that match the tag.
     * 
     * @return  int
     */
    public function getPostsMatched() {
        return $this->_postsMatched;
    }

    /**
     * Returns the number of blogs that match the tag.
     * 
     * @return  int
     */
    public function getBlogsMatched() {
        return $this->_blogsMatched;
    }

    /**
     * Implements Zend_Service_Technorati_ResultSet::current().
     *
     * @return Zend_Service_Technorati_TagResult current result
     */
    public function current()
    {
        /**
         * @see Zend_Service_Technorati_TagResult
         */
        require_once 'Zend/Service/Technorati/TagResult.php';
        return new Zend_Service_Technorati_TagResult($this->_results->item($this->_currentIndex));
    }
}
Technorati/Utils.php000060400000010246150715514360010463 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Utils.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Collection of utilities for various Zend_Service_Technorati classes.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_Utils
{
    /**
     * Parses, validates and returns a valid Zend_Uri object
     * from given $input.
     *
     * @param   string|Zend_Uri_Http $input
     * @return  null|Zend_Uri_Http
     * @throws  Zend_Service_Technorati_Exception
     * @static
     */
    public static function normalizeUriHttp($input)
    {
        // allow null as value
        if ($input === null) {
            return null;
        }

        /**
         * @see Zend_Uri
         */
        require_once 'Zend/Uri.php';
        if ($input instanceof Zend_Uri_Http) {
            $uri = $input;
        } else {
            try {
                $uri = Zend_Uri::factory((string) $input);
            }
            // wrap exception under Zend_Service_Technorati_Exception object
            catch (Exception $e) {
                /**
                 * @see Zend_Service_Technorati_Exception
                 */
                require_once 'Zend/Service/Technorati/Exception.php';
                throw new Zend_Service_Technorati_Exception($e->getMessage());
            }
        }

        // allow inly Zend_Uri_Http objects or child classes
        if (!($uri instanceof Zend_Uri_Http)) {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php'; 
            throw new Zend_Service_Technorati_Exception(
                "Invalid URL $uri, only HTTP(S) protocols can be used");
        }
        
        return $uri;
    }
    /**
     * Parses, validates and returns a valid Zend_Date object
     * from given $input.
     * 
     * $input can be either a string, an integer or a Zend_Date object.
     * If $input is string or int, it will be provided to Zend_Date as it is.
     * If $input is a Zend_Date object, the object instance will be returned. 
     *
     * @param   mixed|Zend_Date $input
     * @return  null|Zend_Date
     * @throws  Zend_Service_Technorati_Exception
     * @static
     */
    public static function normalizeDate($input)
    {
        /**
         * @see Zend_Date
         */
        require_once 'Zend/Date.php';
        /**
         * @see Zend_Locale
         */
        require_once 'Zend/Locale.php';
        
        // allow null as value and return valid Zend_Date objects
        if (($input === null) || ($input instanceof Zend_Date)) {
            return $input;
        }
        
        // due to a BC break as of ZF 1.5 it's not safe to use Zend_Date::isDate() here
        // see ZF-2524, ZF-2334
        if (@strtotime($input) !== FALSE) {
            return new Zend_Date($input);
        } else {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception("'$input' is not a valid Date/Time");
        }
    }
    
    /**
     * @todo public static function xpathQueryAndSet() {}
     */

    /**
     * @todo public static function xpathQueryAndSetIf() {}
     */

    /**
     * @todo public static function xpathQueryAndSetUnless() {}
     */
}
Technorati/Exception.php000060400000002237150715514360011322 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 */


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


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

Technorati/CosmosResult.php000060400000010071150715514360012021 0ustar00<?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 Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: CosmosResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_Result 
 */
require_once 'Zend/Service/Technorati/Result.php';


/**
 * Represents a single Technorati Cosmos query result object. 
 * It is never returned as a standalone object, 
 * but it always belongs to a valid Zend_Service_Technorati_CosmosResultSet object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_CosmosResult extends Zend_Service_Technorati_Result
{
    /**
     * Technorati weblog object that links queried URL.
     * 
     * @var     Zend_Service_Technorati_Weblog
     * @access  protected
     */
    protected $_weblog;

    /**
     * The nearest permalink tracked for queried URL.
     * 
     * @var     Zend_Uri_Http
     * @access  protected
     */
    protected $_nearestPermalink;

    /**
     * The excerpt of the blog/page linking queried URL.
     * 
     * @var     string
     * @access  protected
     */
    protected $_excerpt;

    /**
     * The the datetime the link was created.
     * 
     * @var     Zend_Date
     * @access  protected
     */
    protected $_linkCreated;

    /**
     * The URL of the specific link target page
     * 
     * @var     Zend_Uri_Http
     * @access  protected
     */
    protected $_linkUrl;


    /**
     * Constructs a new object object from DOM Element.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $this->_fields = array( '_nearestPermalink' => 'nearestpermalink',
                                '_excerpt'          => 'excerpt',
                                '_linkCreated'      => 'linkcreated',
                                '_linkUrl'          => 'linkurl');
        parent::__construct($dom);

        // weblog object field
        $this->_parseWeblog();
        
        // filter fields
        $this->_nearestPermalink = Zend_Service_Technorati_Utils::normalizeUriHttp($this->_nearestPermalink);
        $this->_linkUrl = Zend_Service_Technorati_Utils::normalizeUriHttp($this->_linkUrl);
        $this->_linkCreated = Zend_Service_Technorati_Utils::normalizeDate($this->_linkCreated);
    }

    /**
     * Returns the weblog object that links queried URL.
     * 
     * @return  Zend_Service_Technorati_Weblog
     */
    public function getWeblog() {
        return $this->_weblog;
    }

    /**
     * Returns the nearest permalink tracked for queried URL.
     * 
     * @return  Zend_Uri_Http
     */
    public function getNearestPermalink() {
        return $this->_nearestPermalink;
    }

    /**
     * Returns the excerpt of the blog/page linking queried URL.
     * 
     * @return  string
     */
    public function getExcerpt() {
        return $this->_excerpt;
    }
    
    /**
     * Returns the datetime the link was created.
     * 
     * @return  Zend_Date
     */
    public function getLinkCreated() {
        return $this->_linkCreated;
    }
    
    /**
     * If queried URL is a valid blog,
     * returns the URL of the specific link target page.
     * 
     * @return  Zend_Uri_Http
     */
    public function getLinkUrl() {
        return $this->_linkUrl;
    }
    
}
Simpy/Watchlist.php000060400000010654150715514360010331 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Watchlist.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Simpy_WatchlistFilterSet
 */
require_once 'Zend/Service/Simpy/WatchlistFilterSet.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_Watchlist
{
    /**
     * Identifier for the watchlist
     *
     * @var int
     */
    protected $_id;

    /**
     * Name of the watchlist
     *
     * @var string
     */
    protected $_name;

    /**
     * Description of the watchlist
     *
     * @var string
     */
    protected $_description;

    /**
     * Timestamp for when the watchlist was added
     *
     * @var string
     */
    protected $_addDate;

    /**
     * Number of new links in the watchlist
     *
     * @var int
     */
    protected $_newLinks;

    /**
     * List of usernames for users included in the watchlist
     *
     * @var array
     */
    protected $_users;

    /**
     * List of filters included in the watchlist
     *
     * @var Zend_Service_Simpy_WatchlistFilterSet
     */
    protected $_filters;

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMNode $node Individual <watchlist> node from a parsed
     *                       response from a GetWatchlists or GetWatchlist
     *                       operation
     * @return void
     */
    public function __construct($node)
    {
        $map =& $node->attributes;

        $this->_id = $map->getNamedItem('id')->nodeValue;
        $this->_name = $map->getNamedItem('name')->nodeValue;
        $this->_description = $map->getNamedItem('description')->nodeValue;
        $this->_addDate = $map->getNamedItem('addDate')->nodeValue;
        $this->_newLinks = $map->getNamedItem('newLinks')->nodeValue;

        $this->_users = array();
        $this->_filters = new Zend_Service_Simpy_WatchlistFilterSet();

        $childNode = $node->firstChild;
        while (is_null($childNode) == false) {
            if ($childNode->nodeName == 'user') {
                $this->_users[] = $childNode->attributes->getNamedItem('username')->nodeValue;
            } elseif ($childNode->nodeName == 'filter') {
                $filter = new Zend_Service_Simpy_WatchlistFilter($childNode);
                $this->_filters->add($filter);
            }
            $childNode = $childNode->nextSibling;
        }
    }

    /**
     * Returns the identifier for the watchlist
     *
     * @return int
     */
    public function getId()
    {
        return $this->_id;
    }

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

    /**
     * Returns the description of the watchlist
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->_description;
    }

    /**
     * Returns a timestamp for when the watchlist was added
     *
     * @return string
     */
    public function getAddDate()
    {
        return $this->_addDate;
    }

    /**
     * Returns the number of new links in the watchlist
     *
     * @return int
     */
    public function getNewLinks()
    {
        return $this->_newLinks;
    }

    /**
     * Returns a list of usernames for users included in the watchlist
     *
     * @return array
     */
    public function getUsers()
    {
        return $this->_users;
    }

    /**
     * Returns a list of filters included in the watchlist
     *
     * @return Zend_Service_Simpy_WatchlistFilterSet
     */
    public function getFilters()
    {
        return $this->_filters;
    }
}
Simpy/LinkQuery.php000060400000011264150715514360010310 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: LinkQuery.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_LinkQuery
{
    /**
     * Query string for the query
     *
     * @var string
     */
    protected $_query = null;

    /**
     * Maximum number of search results to return
     *
     * @var int
     */
    protected $_limit = null;

    /**
     * Date on which search results must have been added
     *
     * @var string
     */
    protected $_date = null;

    /**
     * Date after which search results must have been added
     *
     * @var string
     */
    protected $_afterDate = null;

    /**
     * Date before which search results must have been added
     *
     * @var string
     */
    protected $_beforeDate = null;

    /**
     * Sets the query string for the query
     *
     * @param  string $query Query string in valid Simpy syntax
     * @see    http://www.simpy.com/faq#searchSyntax
     * @see    http://www.simpy.com/faq#searchFieldsLinks
     * @return Zend_Service_Simpy_LinkQuery Provides a fluent interface
     */
    public function setQueryString($query)
    {
        $this->_query = $query;

        return $this;
    }

    /**
     * Returns the query string set for this query
     *
     * @return string
     */
    public function getQueryString()
    {
        return $this->_query;
    }

    /**
     * Sets the maximum number of search results to return
     *
     * @param  int $limit
     * @return Zend_Service_Simpy_LinkQuery Provides a fluent interface
     */
    public function setLimit($limit)
    {
        $this->_limit = intval($limit);

        if ($this->_limit == 0) {
            $this->_limit = null;
        }

        return $this;
    }

    /**
     * Returns the maximum number of search results to return
     *
     * @return int
     */
    public function getLimit()
    {
        return $this->_limit;
    }

    /**
     * Sets the date on which search results must have been added, which will
     * override any existing values set using setAfterDate() and setBeforeDate()
     *
     * @param  string $date
     * @see    setAfterDate()
     * @see    setBeforeDate()
     * @return Zend_Service_Simpy_LinkQuery Provides a fluent interface
     */
    public function setDate($date)
    {
        $this->_date = $date;
        $this->_afterDate = null;
        $this->_beforeDate = null;

        return $this;
    }

    /**
     * Returns the date on which search results must have been added
     *
     * @return string
     */
    public function getDate()
    {
        return $this->_date;
    }

    /**
     * Sets the date after which search results must have been added, which will
     * override any existing values set using setDate()
     *
     * @param  string $date
     * @see    setDate()
     * @return Zend_Service_Simpy_LinkQuery Provides a fluent interface
     */
    public function setAfterDate($date)
    {
        $this->_afterDate = $date;
        $this->_date = null;

        return $this;
    }

    /**
     * Returns the date after which search results must have been added
     *
     * @return string
     */
    public function getAfterDate()
    {
        return $this->_afterDate;
    }

    /**
     * Sets the date before which search results must have been added, which
     * will override any existing values set using setDate()
     *
     * @param  string $date
     * @see    setDate()
     * @return Zend_Service_Simpy_LinkQuery Provides a fluent interface
     */
    public function setBeforeDate($date)
    {
        $this->_beforeDate = $date;
        $this->_date = null;

        return $this;
    }

    /**
     * Returns the date before which search results must have been added
     *
     * @return string
     */
    public function getBeforeDate()
    {
        return $this->_beforeDate;
    }
}
Simpy/Link.php000060400000011053150715514360007256 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Link.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_Link
{
    /**
     * Private access type
     *
     * @var string
     */
    const ACCESSTYPE_PRIVATE = '0';

    /**
     * Public access type
     *
     * @var string
     */
    const ACCESSTYPE_PUBLIC  = '1';

    /**
     * Access type assigned to the link
     *
     * @var string
     */
    protected $_accessType;

    /**
     * URL of the link
     *
     * @var string
     */
    protected $_url;

    /**
     * Date of the last modification made to the link
     *
     * @var string
     */
    protected $_modDate;

    /**
     * Date the link was added
     *
     * @var string
     */
    protected $_addDate;

    /**
     * Title assigned to the link
     *
     * @var string
     */
    protected $_title;

    /**
     * Nickname assigned to the link
     *
     * @var string
     */
    protected $_nickname;

    /**
     * Tags assigned to the link
     *
     * @var array
     */
    protected $_tags;

    /**
     * Note assigned to the link
     *
     * @var string
     */
    protected $_note;

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMNode $node Individual <link> node from a parsed response from
     *                       a GetLinks operation
     * @return void
     */
    public function __construct($node)
    {
        $this->_accessType = $node->attributes->getNamedItem('accessType')->nodeValue;

        $doc = new DOMDocument();
        $doc->appendChild($doc->importNode($node, true));
        $xpath = new DOMXPath($doc);

        $this->_url = $xpath->evaluate('/link/url')->item(0)->nodeValue;
        $this->_modDate = $xpath->evaluate('/link/modDate')->item(0)->nodeValue;
        $this->_addDate = $xpath->evaluate('/link/addDate')->item(0)->nodeValue;
        $this->_title = $xpath->evaluate('/link/title')->item(0)->nodeValue;
        $this->_nickname = $xpath->evaluate('/link/nickname')->item(0)->nodeValue;
        $this->_note = $xpath->evaluate('/link/note')->item(0)->nodeValue;

        $list = $xpath->query('/link/tags/tag');
        $this->_tags = array();

        for ($x = 0; $x < $list->length; $x++) {
            $this->_tags[$x] = $list->item($x)->nodeValue;
        }
    }

    /**
     * Returns the access type assigned to the link
     *
     * @see ACCESSTYPE_PRIVATE
     * @see ACCESSTYPE_PUBLIC
     * @return string
     */
    public function getAccessType()
    {
        return $this->_accessType;
    }

    /**
     * Returns the URL of the link
     *
     * @return string
     */
    public function getUrl()
    {
        return $this->_url;
    }

    /**
     * Returns the date of the last modification made to the link
     *
     * @return string
     */
    public function getModDate()
    {
        return $this->_modDate;
    }

    /**
     * Returns the date the link was added
     *
     * @return string
     */
    public function getAddDate()
    {
        return $this->_addDate;
    }

    /**
     * Returns the title assigned to the link
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->_title;
    }

    /**
     * Returns the nickname assigned to the link
     *
     * @return string
     */
    public function getNickname()
    {
        return $this->_nickname;
    }

    /**
     * Returns the tags assigned to the link
     *
     * @return array
     */
    public function getTags()
    {
        return $this->_tags;
    }

    /**
     * Returns the note assigned to the link
     *
     * @return string
     */
    public function getNote()
    {
        return $this->_note;
    }
}
Simpy/WatchlistSet.php000060400000004221150715514360010776 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: WatchlistSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Simpy_Watchlist
 */
require_once 'Zend/Service/Simpy/Watchlist.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_WatchlistSet implements IteratorAggregate
{
    /**
     * List of watchlists
     *
     * @var array of Zend_Service_Simpy_Watchlist objects
     */
    protected $_watchlists = array();

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMDocument $doc Parsed response from a GetWatchlists operation
     * @return void
     */
    public function __construct(DOMDocument $doc)
    {
        $xpath = new DOMXPath($doc);
        $list = $xpath->query('//watchlists/watchlist');

        for ($x = 0; $x < $list->length; $x++) {
            $this->_watchlists[$x] = new Zend_Service_Simpy_Watchlist($list->item($x));
        }
    }

    /**
     * Returns an iterator for the watchlist set
     *
     * @return ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->_watchlists);
    }

    /**
     * Returns the number of watchlists in the set
     *
     * @return int
     */
    public function getLength()
    {
        return count($this->_watchlists);
    }
}
Simpy/LinkSet.php000060400000004130150715514360007730 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: LinkSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Simpy_Link
 */
require_once 'Zend/Service/Simpy/Link.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_LinkSet implements IteratorAggregate
{
    /**
     * List of links
     *
     * @var array of Zend_Service_Simpy_Link objects
     */
    protected $_links;

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMDocument $doc Parsed response from a GetLinks operation
     * @return void
     */
    public function __construct(DOMDocument $doc)
    {
        $xpath = new DOMXPath($doc);
        $list = $xpath->query('//links/link');
        $this->_links = array();

        for ($x = 0; $x < $list->length; $x++) {
            $this->_links[$x] = new Zend_Service_Simpy_Link($list->item($x));
        }
    }

    /**
     * Returns an iterator for the link set
     *
     * @return ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->_links);
    }

    /**
     * Returns the number of links in the set
     *
     * @return int
     */
    public function getLength()
    {
        return count($this->_links);
    }
}
Simpy/Note.php000060400000011052150715514360007265 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Note.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_Note
{
    /**
     * Private access type
     *
     * @var string
     */
    const ACCESSTYPE_PRIVATE = 'private';

    /**
     * Public access type
     *
     * @var string
     */
    const ACCESSTYPE_PUBLIC  = 'public';

    /**
     * Access type assigned to the note
     *
     * @var string
     */
    protected $_accessType;

    /**
     * ID of the note
     *
     * @var int
     */
    protected $_id;

    /**
     * URI of the note
     *
     * @var string
     */
    protected $_uri;

    /**
     * Date of the last modification made to the note
     *
     * @var string
     */
    protected $_modDate;

    /**
     * Date the note was added
     *
     * @var string
     */
    protected $_addDate;

    /**
     * Title of to the note
     *
     * @var string
     */
    protected $_title;

    /**
     * Tags assigned to the note
     *
     * @var array
     */
    protected $_tags;

    /**
     * Description of the note
     *
     * @var string
     */
    protected $_description;

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMNode $node Individual <link> node from a parsed response from
     *                       a GetLinks operation
     * @return void
     */
    public function __construct($node)
    {
        $this->_accessType = $node->attributes->getNamedItem('accessType')->nodeValue;

        $doc = new DOMDocument();
        $doc->appendChild($doc->importNode($node, true));
        $xpath = new DOMXPath($doc);

        $this->_uri = $xpath->evaluate('/note/uri')->item(0)->nodeValue;
        $this->_id = substr($this->_uri, strrpos($this->_uri, '=') + 1);
        $this->_modDate = trim($xpath->evaluate('/note/modDate')->item(0)->nodeValue);
        $this->_addDate = trim($xpath->evaluate('/note/addDate')->item(0)->nodeValue);
        $this->_title = $xpath->evaluate('/note/title')->item(0)->nodeValue;
        $this->_description = $xpath->evaluate('/note/description')->item(0)->nodeValue;

        $list = $xpath->query('/note/tags/tag');
        $this->_tags = array();

        for ($x = 0; $x < $list->length; $x++) {
            $this->_tags[$x] = $list->item($x)->nodeValue;
        }
    }

    /**
     * Returns the access type assigned to the note
     *
     * @see    ACCESSTYPE_PRIVATE
     * @see    ACCESSTYPE_PUBLIC
     * @return string
     */
    public function getAccessType()
    {
        return $this->_accessType;
    }

    /**
     * Returns the ID of the note
     *
     * @return int
     */
    public function getId()
    {
        return $this->_id;
    }

    /**
     * Returns the URI of the note
     *
     * @return string
     */
    public function getUri()
    {
        return $this->_uri;
    }

    /**
     * Returns the date of the last modification made to the note
     *
     * @return string
     */
    public function getModDate()
    {
        return $this->_modDate;
    }

    /**
     * Returns the date the note was added
     *
     * @return string
     */
    public function getAddDate()
    {
        return $this->_addDate;
    }

    /**
     * Returns the title assigned to the note
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->_title;
    }

    /**
     * Returns the tags assigned to the note
     *
     * @return array
     */
    public function getTags()
    {
        return $this->_tags;
    }

    /**
     * Returns the description assigned to the note
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->_description;
    }
}
Simpy/WatchlistFilterSet.php000060400000003737150715514360012157 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: WatchlistFilterSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Simpy_WatchlistFilter
 */
require_once 'Zend/Service/Simpy/WatchlistFilter.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_WatchlistFilterSet implements IteratorAggregate
{
    /**
     * List of filters in the set
     *
     * @var array of Zend_Service_Simpy_WatchlistFilter objects
     */
    protected $_filters = array();

    /**
     * Adds a filter to the set
     *
     * @param  Zend_Service_Simpy_WatchlistFilter $filter Filter to be added
     * @return void
     */
    public function add(Zend_Service_Simpy_WatchlistFilter $filter)
    {
        $this->_filters[] = $filter;
    }

    /**
     * Returns an iterator for the watchlist filter set
     *
     * @return ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->_filters);
    }

    /**
     * Returns the number of filters in the set
     *
     * @return int
     */
    public function getLength()
    {
        return count($this->_filters);
    }
}
Simpy/Tag.php000060400000003672150715514360007104 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Tag.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_Tag
{
    /**
     * Name of the tag
     *
     * @var string
     */
    protected $_tag;

    /**
     * Number of links with the tag
     *
     * @var int
     */
    protected $_count;

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMNode $node Individual <tag> node from a parsed response from
     *                       a GetTags operation
     * @return void
     */
    public function __construct($node)
    {
        $map =& $node->attributes;
        $this->_tag = $map->getNamedItem('name')->nodeValue;
        $this->_count = $map->getNamedItem('count')->nodeValue;
    }

    /**
     * Returns the name of the tag
     *
     * @return string
     */
    public function getTag()
    {
        return $this->_tag;
    }

    /**
     * Returns the number of links with the tag
     *
     * @return int
     */
    public function getCount()
    {
        return $this->_count;
    }
}
Simpy/WatchlistFilter.php000060400000003753150715514360011501 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: WatchlistFilter.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_WatchlistFilter
{
    /**
     * Name of the filter
     *
     * @var string
     */
    protected $_name;

    /**
     * Query for the filter
     *
     * @var string
     */
    protected $_query;

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMNode $node Individual <filter> node from a parsed response from
     *                       a GetWatchlists or GetWatchlist operation
     * @return void
     */
    public function __construct($node)
    {
        $map =& $node->attributes;
        $this->_name = $map->getNamedItem('name')->nodeValue;
        $this->_query = $map->getNamedItem('query')->nodeValue;
    }

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

    /**
     * Returns the query for the filter
     *
     * @return string
     */
    public function getQuery()
    {
        return $this->_query;
    }
}
Simpy/NoteSet.php000060400000004130150715514360007740 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: NoteSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Simpy_Note
 */
require_once 'Zend/Service/Simpy/Note.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_NoteSet implements IteratorAggregate
{
    /**
     * List of notes
     *
     * @var array of Zend_Service_Simpy_Note objects
     */
    protected $_notes;

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMDocument $doc Parsed response from a GetNotes operation
     * @return void
     */
    public function __construct(DOMDocument $doc)
    {
        $xpath = new DOMXPath($doc);
        $list = $xpath->query('//notes/note');
        $this->_notes = array();

        for ($x = 0; $x < $list->length; $x++) {
            $this->_notes[$x] = new Zend_Service_Simpy_Note($list->item($x));
        }
    }

    /**
     * Returns an iterator for the note set
     *
     * @return ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->_notes);
    }

    /**
     * Returns the number of notes in the set
     *
     * @return int
     */
    public function getLength()
    {
        return count($this->_notes);
    }
}
Simpy/TagSet.php000060400000004107150715514360007552 0ustar00<?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 Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: TagSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Simpy_Tag
 */
require_once 'Zend/Service/Simpy/Tag.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Simpy
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Simpy_TagSet implements IteratorAggregate
{
    /**
     * List of tags
     *
     * @var array of Zend_Service_Simpy_Tag objects
     */
    protected $_tags;

    /**
     * Constructor to initialize the object with data
     *
     * @param  DOMDocument $doc Parsed response from a GetTags operation
     * @return void
     */
    public function __construct(DOMDocument $doc)
    {
        $xpath = new DOMXPath($doc);
        $list = $xpath->query('//tags/tag');
        $this->_tags = array();

        for ($x = 0; $x < $list->length; $x++) {
            $this->_tags[$x] = new Zend_Service_Simpy_Tag($list->item($x));
        }
    }

    /**
     * Returns an iterator for the tag set
     *
     * @return ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->_tags);
    }

    /**
     * Returns the number of tags in the set
     *
     * @return int
     */
    public function getLength()
    {
        return count($this->_tags);
    }
}
Twitter.php000060400000051153150715514360006727 0ustar00<?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-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */


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

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

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Twitter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Twitter extends Zend_Rest_Client
{
    /**
     * Whether or not authorization has been initialized for the current user.
     * @var bool
     */
    protected $_authInitialized = false;

    /**
     * @var Zend_Http_CookieJar
     */
    protected $_cookieJar;

    /**
     * Date format for 'since' strings
     * @var string
     */
    protected $_dateFormat = 'D, d M Y H:i:s e';

    /**
     * Username
     * @var string
     */
    protected $_username;

    /**
     * Password
     * @var string
     */
    protected $_password;

    /**
     * Current method type (for method proxying)
     * @var string
     */
    protected $_methodType;

    /**
     * Types of API methods
     * @var array
     */
    protected $_methodTypes = array(
        'status',
        'user',
        'directMessage',
        'friendship',
        'account',
        'favorite'
    );

    /**
     * Constructor
     *
     * @param  string $username
     * @param  string $password
     * @return void
     */
    public function __construct($username, $password)
    {
        $this->setUsername($username);
        $this->setPassword($password);
        $this->setUri('http://twitter.com');

        $client = self::getHttpClient();
        $client->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8');
    }

    /**
     * Retrieve username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->_username;
    }

    /**
     * Set username
     *
     * @param  string $value
     * @return Zend_Service_Twitter
     */
    public function setUsername($value)
    {
        $this->_username = $value;
        $this->_authInitialized = false;
        return $this;
    }

    /**
     * Retrieve password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->_password;
    }

    /**
     * Set password
     *
     * @param  string $value
     * @return Zend_Service_Twitter
     */
    public function setPassword($value)
    {
        $this->_password = $value;
        $this->_authInitialized = false;
        return $this;
    }

    /**
     * Proxy service methods
     *
     * @param  string $type
     * @return Zend_Service_Twitter
     * @throws Zend_Service_Twitter_Exception if method is not in method types list
     */
    public function __get($type)
    {
        if (!in_array($type, $this->_methodTypes)) {
            include_once 'Zend/Service/Twitter/Exception.php';
            throw new Zend_Service_Twitter_Exception('Invalid method type "' . $type . '"');
        }

        $this->_methodType = $type;
        return $this;
    }

    /**
     * Method overloading
     *
     * @param  string $method
     * @param  array $params
     * @return mixed
     * @throws Zend_Service_Twitter_Exception if unable to find method
     */
    public function __call($method, $params)
    {
        if (empty($this->_methodType)) {
            include_once 'Zend/Service/Twitter/Exception.php';
            throw new Zend_Service_Twitter_Exception('Invalid method "' . $method . '"');
        }

        $test = $this->_methodType . ucfirst($method);
        if (!method_exists($this, $test)) {
            include_once 'Zend/Service/Twitter/Exception.php';
            throw new Zend_Service_Twitter_Exception('Invalid method "' . $test . '"');
        }

        return call_user_func_array(array($this, $test), $params);
    }

    /**
     * Initialize HTTP authentication
     *
     * @return void
     */
    protected function _init()
    {
        $client = self::getHttpClient();

        $client->resetParameters();

        if (null == $this->_cookieJar) {
            $client->setCookieJar();
            $this->_cookieJar = $client->getCookieJar();
        } else {
            $client->setCookieJar($this->_cookieJar);
        }

        if (!$this->_authInitialized) {
            $client->setAuth($this->getUsername(), $this->getPassword());
            $this->_authInitialized = true;
        }
    }

    /**
     * Set date header
     *
     * @param  int|string $value
     * @return void
     */
    protected function _setDate($value)
    {
        if (is_int($value)) {
            $date = date($this->_dateFormat, $value);
        } else {
            $date = date($this->_dateFormat, strtotime($value));
        }
        self::getHttpClient()->setHeaders('If-Modified-Since', $date);
    }

    /**
     * Public Timeline status
     *
     * @return Zend_Rest_Client_Result
     */
    public function statusPublicTimeline()
    {
        $this->_init();
        $path = '/statuses/public_timeline.xml';
        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Friend Timeline Status
     *
     * $params may include one or more of the following keys
     * - id: ID of a friend whose timeline you wish to receive
     * - since: return results only after the date specified
     * - page: return page X of results
     *
     * @param  array $params
     * @return void
     */
    public function statusFriendsTimeline(array $params = array())
    {
        $this->_init();
        $path = '/statuses/friends_timeline';
        foreach ($params as $key => $value) {
            switch (strtolower($key)) {
                case 'since':
                    $this->_setDate($value);
                    break;
                case 'page':
                    $this->page = (int) $value;
                    break;
                default:
                    break;
            }
        }
        $path    .= '.xml';
        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * User Timeline status
     *
     * $params may include one or more of the following keys
     * - id: ID of a friend whose timeline you wish to receive
     * - since: return results only after the date specified
     * - page: return page X of results
     * - count: how many statuses to return
     *
     * @return Zend_Rest_Client_Result
     */
    public function statusUserTimeline(array $params = array())
    {
        $this->_init();
        $path = '/statuses/user_timeline';
        $_params = array();
        foreach ($params as $key => $value) {
            switch (strtolower($key)) {
                case 'id':
                    $path .= '/' . $value;
                    break;
                case 'since':
                    $this->_setDate($value);
                    break;
                case 'page':
                    $_params['page'] = (int) $value;
                    break;
                case 'count':
                    $count = (int) $value;
                    if (0 >= $count) {
                        $count = 1;
                    } elseif (200 < $count) {
                        $count = 200;
                    }
                    $_params['count'] = $count;
                    break;
                default:
                    break;
            }
        }
        $path    .= '.xml';
        $response = $this->restGet($path, $_params);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Show a single status
     *
     * @param  int $id Id of status to show
     * @return Zend_Rest_Client_Result
     */
    public function statusShow($id)
    {
        $this->_init();
        $path = '/statuses/show/' . $id . '.xml';
        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Update user's current status
     *
     * @param  string $status
     * @param  int $in_reply_to_status_id
     * @return Zend_Rest_Client_Result
     * @throws Zend_Service_Twitter_Exception if message is too short or too long
     */
    public function statusUpdate($status, $in_reply_to_status_id = null)
    {
        $this->_init();
        $path = '/statuses/update.xml';
        $len  = strlen($status);
        if ($len > 140) {
            include_once 'Zend/Service/Twitter/Exception.php';
            throw new Zend_Service_Twitter_Exception('Status must be no more than 140 characters in length');
        } elseif (0 == $len) {
            include_once 'Zend/Service/Twitter/Exception.php';
            throw new Zend_Service_Twitter_Exception('Status must contain at least one character');
        }

        $data = array(
            'status' => $status
        );

        if(is_numeric($in_reply_to_status_id) && !empty($in_reply_to_status_id)) {
            $data['in_reply_to_status_id'] = $in_reply_to_status_id;
        }

        //$this->status = $status;
        $response = $this->restPost($path, $data);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Get status replies
     *
     * $params may include one or more of the following keys
     * - since: return results only after the date specified
     * - since_id: return results only after the specified tweet id
     * - page: return page X of results
     *
     * @return Zend_Rest_Client_Result
     */
    public function statusReplies(array $params = array())
    {
        $this->_init();
        $path = '/statuses/replies.xml';

        $_params = array();
        foreach ($params as $key => $value) {
            switch (strtolower($key)) {
                case 'since':
                    $this->_setDate($value);
                    break;
                case 'since_id':
                    $_params['since_id'] = (int) $value;
                    break;
                case 'page':
                    $_params['page'] = (int) $value;
                    break;
                default:
                    break;
            }
        }

        $response = $this->restGet($path, $_params);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Destroy a status message
     *
     * @param  int $id ID of status to destroy
     * @return Zend_Rest_Client_Result
     */
    public function statusDestroy($id)
    {
        $this->_init();
        $path = '/statuses/destroy/' . (int) $id . '.xml';

        $response = $this->restPost($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * User friends
     *
     * @param  int|string $id Id or username of user for whom to fetch friends
     * @return Zend_Rest_Client_Result
     */
    public function userFriends(array $params = array())
    {
        $this->_init();
        $path = '/statuses/friends';
        $_params = array();
        foreach ($params as $key => $value) {
            switch (strtolower($key)) {
                case 'id':
                    $path .= '/' . $value;
                    break;
                case 'since':
                    $this->_setDate($value);
                    break;
                case 'page':
                    $_params['page'] = (int) $value;
                    break;
                default:
                    break;
            }
        }
        $path    .= '.xml';

        $response = $this->restGet($path, $_params);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * User Followers
     *
     * @param  bool $lite If true, prevents inline inclusion of current status for followers; defaults to false
     * @return Zend_Rest_Client_Result
     */
    public function userFollowers($lite = false)
    {
        $this->_init();
        $path = '/statuses/followers.xml';
        if ($lite) {
            $this->lite = 'true';
        }

        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Get featured users
     *
     * @return Zend_Rest_Client_Result
     */
    public function userFeatured()
    {
        $this->_init();
        $path = '/statuses/featured.xml';

        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Show extended information on a user
     *
     * @param  int|string $id User ID or name
     * @return Zend_Rest_Client_Result
     */
    public function userShow($id)
    {
        $this->_init();
        $path = '/users/show/' . $id . '.xml';

        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Retrieve direct messages for the current user
     *
     * $params may include one or more of the following keys
     * - since: return results only after the date specified
     * - since_id: return statuses only greater than the one specified
     * - page: return page X of results
     *
     * @param  array $params
     * @return Zend_Rest_Client_Result
     */
    public function directMessageMessages(array $params = array())
    {
        $this->_init();
        $path = '/direct_messages.xml';
        foreach ($params as $key => $value) {
            switch (strtolower($key)) {
                case 'since':
                    $this->_setDate($value);
                    break;
                case 'since_id':
                    $this->since_id = (int) $value;
                    break;
                case 'page':
                    $this->page = (int) $value;
                    break;
                default:
                    break;
            }
        }
        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Retrieve list of direct messages sent by current user
     *
     * $params may include one or more of the following keys
     * - since: return results only after the date specified
     * - since_id: return statuses only greater than the one specified
     * - page: return page X of results
     *
     * @param  array $params
     * @return Zend_Rest_Client_Result
     */
    public function directMessageSent(array $params = array())
    {
        $this->_init();
        $path = '/direct_messages/sent.xml';
        foreach ($params as $key => $value) {
            switch (strtolower($key)) {
                case 'since':
                    $this->_setDate($value);
                    break;
                case 'since_id':
                    $this->since_id = (int) $value;
                    break;
                case 'page':
                    $this->page = (int) $value;
                    break;
                default:
                    break;
            }
        }
        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Send a direct message to a user
     *
     * @param  int|string $user User to whom to send message
     * @param  string $text Message to send to user
     * @return Zend_Rest_Client_Result
     * @throws Zend_Service_Twitter_Exception if message is too short or too long
     */
    public function directMessageNew($user, $text)
    {
        $this->_init();
        $path = '/direct_messages/new.xml';

        $len = strlen($text);
        if (0 == $len) {
            throw new Zend_Service_Twitter_Exception('Direct message must contain at least one character');
        } elseif (140 < $len) {
            throw new Zend_Service_Twitter_Exception('Direct message must contain no more than 140 characters');
        }

        $data = array(
            'user'	=> $user,
            'text'	=> $text,
        );

        $response = $this->restPost($path, $data);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Destroy a direct message
     *
     * @param  int $id ID of message to destroy
     * @return Zend_Rest_Client_Result
     */
    public function directMessageDestroy($id)
    {
        $this->_init();
        $path = '/direct_messages/destroy/' . $id . '.xml';

        $response = $this->restPost($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Create friendship
     *
     * @param  int|string $id User ID or name of new friend
     * @return Zend_Rest_Client_Result
     */
    public function friendshipCreate($id)
    {
        $this->_init();
        $path = '/friendships/create/' . $id . '.xml';

        $response = $this->restPost($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Destroy friendship
     *
     * @param  int|string $id User ID or name of friend to remove
     * @return Zend_Rest_Client_Result
     */
    public function friendshipDestroy($id)
    {
        $this->_init();
        $path = '/friendships/destroy/' . $id . '.xml';

        $response = $this->restPost($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Friendship exists
     *
     * @param int|string $id User ID or name of friend to see if they are your friend
     * @return Zend_Rest_Client_result
     */
    public function friendshipExists($id)
    {
        $this->_init();
        $path = '/friendships/exists.xml';

        $data = array(
            'user_a' => $this->getUsername(),
            'user_b' => $id
        );

        $response = $this->restGet($path, $data);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Verify Account Credentials
     *
     * @return Zend_Rest_Client_Result
     */
    public function accountVerifyCredentials()
    {
        $this->_init();
        $response = $this->restGet('/account/verify_credentials.xml');
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * End current session
     *
     * @return true
     */
    public function accountEndSession()
    {
        $this->_init();
        $this->restGet('/account/end_session');
        return true;
    }

    /**
     * Returns the number of api requests you have left per hour.
     *
     * @return Zend_Rest_Client_Result
     */
    public function accountRateLimitStatus()
    {
        $this->_init();
        $response = $this->restGet('/account/rate_limit_status.xml');
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Fetch favorites
     *
     * $params may contain one or more of the following:
     * - 'id': Id of a user for whom to fetch favorites
     * - 'page': Retrieve a different page of resuls
     *
     * @param  array $params
     * @return Zend_Rest_Client_Result
     */
    public function favoriteFavorites(array $params = array())
    {
        $this->_init();
        $path = '/favorites';
        foreach ($params as $key => $value) {
            switch (strtolower($key)) {
                case 'id':
                    $path .= '/' . $value;
                    break;
                case 'page':
                    $this->page = (int) $value;
                    break;
                default:
                    break;
            }
        }
        $path .= '.xml';
        $response = $this->restGet($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Mark a status as a favorite
     *
     * @param  int $id Status ID you want to mark as a favorite
     * @return Zend_Rest_Client_Result
     */
    public function favoriteCreate($id)
    {
        $this->_init();
        $path = '/favorites/create/' . (int) $id . '.xml';

        $response = $this->restPost($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }

    /**
     * Remove a favorite
     *
     * @param  int $id Status ID you want to de-list as a favorite
     * @return Zend_Rest_Client_Result
     */
    public function favoriteDestroy($id)
    {
        $this->_init();
        $path = '/favorites/destroy/' . (int) $id . '.xml';

        $response = $this->restPost($path);
        return new Zend_Rest_Client_Result($response->getBody());
    }
}
Twitter/Exception.php000060400000002005150715514360010655 0ustar00<?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-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */

/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Twitter
 * @copyright  Copyright (c) 2005-2008 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 Exception
{
}
Twitter/Search.php000060400000010131150715514360010123 0ustar00<?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-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */

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

/**
 * @see Zend_Uri_Http
 */
require_once 'Zend/Uri/Http.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-2008 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_Http_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->_uri = Zend_Uri_Http::fromString("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)) {
            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.
     *
     * @return array
     */
    public function trends()
    {
        $this->_uri->setPath('/trends.json');
        $this->setUri($this->_uri);
        $response     = $this->request();

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

    public function search($query, array $params = array())
    {

        $this->_uri->setPath('/search.' . $this->_responseType);
        $this->_uri->setQuery(null);

        $_query = array();

        $_query['q'] = $query;

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

        $this->_uri->setQuery($_query);

        $this->setUri($this->_uri);
        $response     = $this->request();

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

        return ;
    }
}
Yahoo.php000060400000105032150715514360006340 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Yahoo.php 13006 2008-12-03 21:17:01Z matthew $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo
{
    /**
     * Yahoo Developer Application ID
     *
     * @var string
     */
    public $appId;

    /**
     * Reference to the REST client
     *
     * @var Zend_Rest_Client
     */
    protected $_rest;


    /**
     * Sets the application ID and instantiates the REST client
     *
     * @param  string $appId specified the developer's appid
     * @return void
     */
    public function __construct($appId)
    {
        $this->appId = (string) $appId;
        /**
         * @see Zend_Rest_Client
         */
        require_once 'Zend/Rest/Client.php';
        $this->_rest = new Zend_Rest_Client('http://search.yahooapis.com');
    }


    /**
     * Retrieve Inlink Data from siteexplorer.yahoo.com.  A basic query
     * consists simply of a URL.  Additional options that can be
     * specified consist of:
     * 'results'      => int  How many results to return, max is 100
     * 'start'        => int  The start offset for search results
     * 'entire_site'  => bool  Data for the whole site or a single page
     * 'omit_inlinks' => (none|domain|subdomain)  Filter inlinks from these sources
     *
     * @param  string $query    the query being run
     * @param  array  $options  any optional parameters
     * @return Zend_Service_Yahoo_ResultSet  The return set
     * @throws Zend_Service_Exception
     */
    public function inlinkDataSearch($query, array $options = array())
    {
        static $defaultOptions = array('results'     => '50',
                                       'start'    => 1);

        $options = $this->_prepareOptions($query, $options, $defaultOptions);
        $this->_validateInlinkDataSearch($options);

        $this->_rest->getHttpClient()->resetParameters();
        $this->_rest->setUri('http://search.yahooapis.com');
        $response = $this->_rest->restGet('/SiteExplorerService/V1/inlinkData', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
                                             $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_Yahoo_InlinkDataResultSet
         */
        require_once 'Zend/Service/Yahoo/InlinkDataResultSet.php';
        return new Zend_Service_Yahoo_InlinkDataResultSet($dom);
    }


    /**
     * Perform a search of images.  The most basic query consists simply
     * of a plain text search, but you can also specify the type of
     * image, the format, color, etc.
     *
     * The specific options are:
     * 'type'       => (all|any|phrase)  How to parse the query terms
     * 'results'    => int  How many results to return, max is 50
     * 'start'      => int  The start offset for search results
     * 'format'     => (any|bmp|gif|jpeg|png)  The type of images to search for
     * 'coloration' => (any|color|bw)  The coloration of images to search for
     * 'adult_ok'   => bool  Flag to allow 'adult' images.
     *
     * @param  string $query   the query to be run
     * @param  array  $options an optional array of query options
     * @return Zend_Service_Yahoo_ImageResultSet the search results
     * @throws Zend_Service_Exception
     */
    public function imageSearch($query, array $options = array())
    {
        static $defaultOptions = array('type'       => 'all',
                                       'results'    => 10,
                                       'start'      => 1,
                                       'format'     => 'any',
                                       'coloration' => 'any');

        $options = $this->_prepareOptions($query, $options, $defaultOptions);

        $this->_validateImageSearch($options);

        $this->_rest->getHttpClient()->resetParameters();
        $this->_rest->setUri('http://search.yahooapis.com');
        $response = $this->_rest->restGet('/ImageSearchService/V1/imageSearch', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
                                             $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_YahooImageResultSet
         */
        require_once 'Zend/Service/Yahoo/ImageResultSet.php';
        return new Zend_Service_Yahoo_ImageResultSet($dom);
    }


    /**
     * Perform a search on local.yahoo.com.  The basic search
     * consists of a query and some fragment of location information;
     * for example zipcode, latitude/longitude, or street address.
     *
     * Query options include:
     * 'results'    => int  How many results to return, max is 50
     * 'start'      => int  The start offset for search results
     * 'sort'       => (relevance|title|distance|rating) How to order your results
     *
     * 'radius'     => float  The radius (in miles) in which to search
     *
     * 'longitude'  => float  The longitude of the location to search around
     * 'latitude'   => float  The latitude of the location to search around
     *
     * 'zip'        => string The zipcode to search around
     *
     * 'street'     => string  The street address to search around
     * 'city'       => string  The city for address search
     * 'state'      => string  The state for address search
     * 'location'   => string  An adhoc location string to search around
     *
     * @param  string $query    The query string you want to run
     * @param  array  $options  The search options, including location
     * @return Zend_Service_Yahoo_LocalResultSet The results
     * @throws Zend_Service_Exception
     */
    public function localSearch($query, array $options = array())
    {
        static $defaultOptions = array('results' => 10,
                                       'start'   => 1,
                                       'sort'    => 'distance',
                                       'radius'  => 5);

        $options = $this->_prepareOptions($query, $options, $defaultOptions);

        $this->_validateLocalSearch($options);

        $this->_rest->getHttpClient()->resetParameters();
        $this->_rest->setUri('http://local.yahooapis.com');
        $response = $this->_rest->restGet('/LocalSearchService/V1/localSearch', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
                                             $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_Yahoo_LocalResultSet
         */
        require_once 'Zend/Service/Yahoo/LocalResultSet.php';
        return new Zend_Service_Yahoo_LocalResultSet($dom);
    }


    /**
     * Execute a search on news.yahoo.com. This method minimally takes a
     * text query to search on.
     *
     * Query options coonsist of:
     *
     * 'results'    => int  How many results to return, max is 50
     * 'start'      => int  The start offset for search results
     * 'sort'       => (rank|date)  How to order your results
     * 'language'   => lang  The target document language to match
     * 'type'       => (all|any|phrase)  How the query should be parsed
     * 'site'       => string  A site to which your search should be restricted
     *
     * @param  string $query    The query to run
     * @param  array  $options  The array of optional parameters
     * @return Zend_Service_Yahoo_NewsResultSet  The query return set
     * @throws Zend_Service_Exception
     */
    public function newsSearch($query, array $options = array())
    {
        static $defaultOptions = array('type'     => 'all',
                                       'start'    => 1,
                                       'sort'     => 'rank');

        $options = $this->_prepareOptions($query, $options, $defaultOptions);

        $this->_validateNewsSearch($options);

        $this->_rest->getHttpClient()->resetParameters();
        $this->_rest->setUri('http://search.yahooapis.com');
        $response = $this->_rest->restGet('/NewsSearchService/V1/newsSearch', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
                                             $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_Yahoo_NewsResultSet
         */
        require_once 'Zend/Service/Yahoo/NewsResultSet.php';
        return new Zend_Service_Yahoo_NewsResultSet($dom);
    }


    /**
     * Retrieve Page Data from siteexplorer.yahoo.com.  A basic query
     * consists simply of a URL.  Additional options that can be
     * specified consist of:
     * 'results'      => int  How many results to return, max is 100
     * 'start'        => int  The start offset for search results
     * 'domain_only'  => bool  Data for just the given domain or all sub-domains also
     *
     * @param  string $query    the query being run
     * @param  array  $options  any optional parameters
     * @return Zend_Service_Yahoo_ResultSet  The return set
     * @throws Zend_Service_Exception
     */
    public function pageDataSearch($query, array $options = array())
    {
        static $defaultOptions = array('results'     => '50',
                                       'start'    => 1);

        $options = $this->_prepareOptions($query, $options, $defaultOptions);
        $this->_validatePageDataSearch($options);

        $this->_rest->getHttpClient()->resetParameters();
        $this->_rest->setUri('http://search.yahooapis.com');
        $response = $this->_rest->restGet('/SiteExplorerService/V1/pageData', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
                                             $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_Yahoo_PageDataResultSet
         */
        require_once 'Zend/Service/Yahoo/PageDataResultSet.php';
        return new Zend_Service_Yahoo_PageDataResultSet($dom);
    }


    /**
     * Perform a search of videos.  The most basic query consists simply
     * of a plain text search, but you can also specify the format of
     * video.
     *
     * The specific options are:
     * 'type'       => (all|any|phrase)  How to parse the query terms
     * 'results'    => int  How many results to return, max is 50
     * 'start'      => int  The start offset for search results
     * 'format'     => (any|avi|flash|mpeg|msmedia|quicktime|realmedia)  The type of videos to search for
     * 'adult_ok'   => bool  Flag to allow 'adult' videos.
     *
     * @param  string $query   the query to be run
     * @param  array  $options an optional array of query options
     * @return Zend_Service_Yahoo_VideoResultSet the search results
     * @throws Zend_Service_Exception
     */
    public function videoSearch($query, array $options = array())
    {
        static $defaultOptions = array('type'       => 'all',
                                       'results'    => 10,
                                       'start'      => 1,
                                       'format'     => 'any');

        $options = $this->_prepareOptions($query, $options, $defaultOptions);

        $this->_validateVideoSearch($options);

        $this->_rest->getHttpClient()->resetParameters();
        $this->_rest->setUri('http://search.yahooapis.com');
        $response = $this->_rest->restGet('/VideoSearchService/V1/videoSearch', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
                                             $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_YahooVideoResultSet
         */
        require_once 'Zend/Service/Yahoo/VideoResultSet.php';
        return new Zend_Service_Yahoo_VideoResultSet($dom);
    }


    /**
     * Perform a web content search on search.yahoo.com.  A basic query
     * consists simply of a text query.  Additional options that can be
     * specified consist of:
     * 'results'    => int  How many results to return, max is 50
     * 'start'      => int  The start offset for search results
     * 'language'   => lang  The target document language to match
     * 'type'       => (all|any|phrase)  How the query should be parsed
     * 'site'       => string  A site to which your search should be restricted
     * 'format'     => (any|html|msword|pdf|ppt|rss|txt|xls)
     * 'adult_ok'   => bool  permit 'adult' content in the search results
     * 'similar_ok' => bool  permit similar results in the result set
     * 'country'    => string  The country code for the content searched
     * 'license'    => (any|cc_any|cc_commercial|cc_modifiable)  The license of content being searched
     * 'region'     => The regional search engine on which the service performs the search. default us.
     *
     * @param  string $query    the query being run
     * @param  array  $options  any optional parameters
     * @return Zend_Service_Yahoo_WebResultSet  The return set
     * @throws Zend_Service_Exception
     */
    public function webSearch($query, array $options = array())
    {
        static $defaultOptions = array('type'     => 'all',
                                       'start'    => 1,
                                       'license'  => 'any',
                                       'results'  => 10,
                                       'format'   => 'any');

        $options = $this->_prepareOptions($query, $options, $defaultOptions);
        $this->_validateWebSearch($options);

        $this->_rest->getHttpClient()->resetParameters();
        $this->_rest->setUri('http://search.yahooapis.com');
        $response = $this->_rest->restGet('/WebSearchService/V1/webSearch', $options);

        if ($response->isError()) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('An error occurred sending request. Status code: ' .
                                             $response->getStatus());
        }

        $dom = new DOMDocument();
        $dom->loadXML($response->getBody());

        self::_checkErrors($dom);

        /**
         * @see Zend_Service_Yahoo_WebResultSet
         */
        require_once 'Zend/Service/Yahoo/WebResultSet.php';
        return new Zend_Service_Yahoo_WebResultSet($dom);
    }


    /**
     * Returns a reference to the REST client
     *
     * @return Zend_Rest_Client
     */
    public function getRestClient()
    {
        return $this->_rest;
    }


    /**
     * Validate Inlink Data Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateInlinkDataSearch(array $options)
    {
        $validOptions = array('appid', 'query', 'results', 'start', 'entire_site', 'omit_inlinks');

        $this->_compareOptions($options, $validOptions);

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 100, true);

        if (isset($options['results']) && !$between->setMin(1)->setMax(100)->isValid($options['results'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
        }

        if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
        }

        if (isset($options['omit_inlinks'])) {
            $this->_validateInArray('omit_inlinks', $options['omit_inlinks'], array('none', 'domain', 'subdomain'));
        }
    }


    /**
     * Validate Image Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateImageSearch(array $options)
    {
        $validOptions = array('appid', 'query', 'type', 'results', 'start', 'format', 'coloration', 'adult_ok');

        $this->_compareOptions($options, $validOptions);

        if (isset($options['type'])) {
            switch($options['type']) {
                case 'all':
                case 'any':
                case 'phrase':
                    break;
                default:
                    /**
                     * @see Zend_Service_Exception
                     */
                    require_once 'Zend/Service/Exception.php';
                    throw new Zend_Service_Exception("Invalid value for option 'type': '{$options['type']}'");
            }
        }

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 50, true);

        if (isset($options['results']) && !$between->setMin(1)->setMax(50)->isValid($options['results'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
        }

        if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
        }

        if (isset($options['format'])) {
            switch ($options['format']) {
                case 'any':
                case 'bmp':
                case 'gif':
                case 'jpeg':
                case 'png':
                    break;
                default:
                    /**
                     * @see Zend_Service_Exception
                     */
                    require_once 'Zend/Service/Exception.php';
                    throw new Zend_Service_Exception("Invalid value for option 'format': {$options['format']}");
            }
        }

        if (isset($options['coloration'])) {
            switch ($options['coloration']) {
                case 'any':
                case 'color':
                case 'bw':
                    break;
                default:
                    /**
                     * @see Zend_Service_Exception
                     */
                    require_once 'Zend/Service/Exception.php';
                    throw new Zend_Service_Exception("Invalid value for option 'coloration': "
                                                   . "{$options['coloration']}");
            }
        }
    }


    /**
     * Validate Local Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateLocalSearch(array $options)
    {
        $validOptions = array('appid', 'query', 'results', 'start', 'sort', 'radius', 'street',
                              'city', 'state', 'zip', 'location', 'latitude', 'longitude');

        $this->_compareOptions($options, $validOptions);

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 20, true);

        if (isset($options['results']) && !$between->setMin(1)->setMax(20)->isValid($options['results'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
        }

        if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
        }

        if (isset($options['longitude']) && !$between->setMin(-90)->setMax(90)->isValid($options['longitude'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'longitude': {$options['longitude']}");
        }

        if (isset($options['latitude']) && !$between->setMin(-180)->setMax(180)->isValid($options['latitude'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'latitude': {$options['latitude']}");
        }

        if (isset($options['zip']) && !preg_match('/(^\d{5}$)|(^\d{5}-\d{4}$)/', $options['zip'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'zip': {$options['zip']}");
        }

        $hasLocation = false;
        $locationFields = array('street', 'city', 'state', 'zip', 'location');
        foreach ($locationFields as $field) {
            if (isset($options[$field]) && $options[$field] != '') {
                $hasLocation = true;
                break;
            }
        }

        if (!$hasLocation && (!isset($options['latitude']) || !isset($options['longitude']))) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('Location data are required but missing');
        }

        if (!in_array($options['sort'], array('relevance', 'title', 'distance', 'rating'))) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'sort': {$options['sort']}");
        }
    }


    /**
     * Validate News Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateNewsSearch(array $options)
    {
        $validOptions = array('appid', 'query', 'results', 'start', 'sort', 'language', 'type', 'site');

        $this->_compareOptions($options, $validOptions);

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 50, true);

        if (isset($options['results']) && !$between->setMin(1)->setMax(50)->isValid($options['results'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
        }

        if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
        }

        if (isset($options['language'])) {
            $this->_validateLanguage($options['language']);
        }

        $this->_validateInArray('sort', $options['sort'], array('rank', 'date'));
        $this->_validateInArray('type', $options['type'], array('all', 'any', 'phrase'));
    }


    /**
     * Validate Page Data Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validatePageDataSearch(array $options)
    {
        $validOptions = array('appid', 'query', 'results', 'start', 'domain_only');

        $this->_compareOptions($options, $validOptions);

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 100, true);

        if (isset($options['results']) && !$between->setMin(1)->setMax(100)->isValid($options['results'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
        }

        if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
        }
    }


    /**
     * Validate Video Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateVideoSearch(array $options)
    {
        $validOptions = array('appid', 'query', 'type', 'results', 'start', 'format', 'adult_ok');

        $this->_compareOptions($options, $validOptions);

        if (isset($options['type'])) {
            $this->_validateInArray('type', $options['type'], array('all', 'any', 'phrase'));
        }

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 50, true);

        if (isset($options['results']) && !$between->setMin(1)->setMax(50)->isValid($options['results'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
        }

        if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
        }

        if (isset($options['format'])) {
            $this->_validateInArray('format', $options['format'], array('any', 'avi', 'flash', 'mpeg', 'msmedia', 'quicktime', 'realmedia'));
        }
    }


    /**
     * Validate Web Search Options
     *
     * @param  array $options
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateWebSearch(array $options)
    {
        $validOptions = array('appid', 'query', 'results', 'start', 'language', 'type', 'format', 'adult_ok',
                              'similar_ok', 'country', 'site', 'subscription', 'license', 'region');

        $this->_compareOptions($options, $validOptions);

        /**
         * @see Zend_Validate_Between
         */
        require_once 'Zend/Validate/Between.php';
        $between = new Zend_Validate_Between(1, 100, true);

        if (isset($options['results']) && !$between->setMin(1)->setMax(100)->isValid($options['results'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'results': {$options['results']}");
        }

        if (isset($options['start']) && !$between->setMin(1)->setMax(1000)->isValid($options['start'])) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option 'start': {$options['start']}");
        }

        if (isset($options['language'])) {
            $this->_validateLanguage($options['language']);
        }

        $this->_validateInArray('type', $options['type'], array('all', 'any', 'phrase'));
        $this->_validateInArray('format', $options['format'], array('any', 'html', 'msword', 'pdf', 'ppt', 'rss',
                                                                    'txt', 'xls'));
        $this->_validateInArray('license', $options['license'], array('any', 'cc_any', 'cc_commercial',
                                                                      'cc_modifiable'));
        if (isset($options['region'])){
            $this->_validateInArray('region', $options['region'], array('ar', 'au', 'at', 'br', 'ca', 'ct', 'dk', 'fi',
                                                                          'fr', 'de', 'in', 'id', 'it', 'my', 'mx', 
                                                                          'nl', 'no', 'ph', 'ru', 'sg', 'es', 'se',
                                                                          'ch', 'th', 'uk', 'us'));
        }
    }


    /**
     * Prepare options for sending to Yahoo!
     *
     * @param  string $query          Search Query
     * @param  array  $options        User specified options
     * @param  array  $defaultOptions Required/Default options
     * @return array
     */
    protected function _prepareOptions($query, array $options, array $defaultOptions = array())
    {
        $options['appid'] = $this->appId;
        $options['query'] = (string) $query;

        return array_merge($defaultOptions, $options);
    }


    /**
     * Throws an exception if the chosen language is not supported
     *
     * @param  string $lang Language code
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateLanguage($lang)
    {
        $languages = array('ar', 'bg', 'ca', 'szh', 'tzh', 'hr', 'cs', 'da', 'nl', 'en', 'et', 'fi', 'fr', 'de', 'el',
            'he', 'hu', 'is', 'id', 'it', 'ja', 'ko', 'lv', 'lt', 'no', 'fa', 'pl', 'pt', 'ro', 'ru', 'sk', 'sr', 'sl',
            'es', 'sv', 'th', 'tr'
            );
        if (!in_array($lang, $languages)) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("The selected language '$lang' is not supported");
        }
    }


    /**
     * Utility function to check for a difference between two arrays.
     *
     * @param  array $options      User specified options
     * @param  array $validOptions Valid options
     * @return void
     * @throws Zend_Service_Exception if difference is found (e.g., unsupported query option)
     */
    protected function _compareOptions(array $options, array $validOptions)
    {
        $difference = array_diff(array_keys($options), $validOptions);
        if ($difference) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception('The following parameters are invalid: ' . join(', ', $difference));
        }
    }


    /**
     * Check that a named value is in the given array
     *
     * @param  string $name  Name associated with the value
     * @param  mixed  $value Value
     * @param  array  $array Array in which to check for the value
     * @return void
     * @throws Zend_Service_Exception
     */
    protected function _validateInArray($name, $value, array $array)
    {
        if (!in_array($value, $array)) {
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception("Invalid value for option '$name': $value");
        }
    }


    /**
     * Check if response is an error
     *
     * @param  DOMDocument $dom DOM Object representing the result XML
     * @return void
     * @throws Zend_Service_Exception Thrown when the result from Yahoo! is an error
     */
    protected static function _checkErrors(DOMDocument $dom)
    {
        $xpath = new DOMXPath($dom);
        $xpath->registerNamespace('yapi', 'urn:yahoo:api');

        if ($xpath->query('//yapi:Error')->length >= 1) {
            $message = $xpath->query('//yapi:Error/yapi:Message/text()')->item(0)->data;
            /**
             * @see Zend_Service_Exception
             */
            require_once 'Zend/Service/Exception.php';
            throw new Zend_Service_Exception($message);
        }
    }
}
Yahoo/PageDataResult.php000060400000002734150715514360011212 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */


/**
 * @see Zend_Service_Yahoo_Result
 */
require_once 'Zend/Service/Yahoo/Result.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_PageDataResult extends Zend_Service_Yahoo_Result
{
    /**
     * Web result namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srch';


    /**
     * Initializes the web result
     *
     * @param  DOMElement $result
     * @return void
     */
    public function __construct(DOMElement $result)
    {
        $this->_fields = array();
        parent::__construct($result);
    }
}
Yahoo/VideoResult.php000060400000005374150715514360010615 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2006 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: VideoResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_Result
 */
require_once 'Zend/Service/Yahoo/Result.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_VideoResult extends Zend_Service_Yahoo_Result
{
    /**
     * Summary info for the video
     *
     * @var string
     */
    public $Summary;

    /**
     * The URL of the webpage hosting the video
     *
     * @var string
     */
    public $RefererUrl;

    /**
     * The size of the files in bytes
     *
     * @var string
     */
    public $FileSize;

    /**
     * The type of file (bmp, gif, jpeg, etc.)
     *
     * @var string
     */
    public $FileFormat;

    /**
     * The height of the video in pixels
     *
     * @var string
     */
    public $Height;

    /**
     * The width of the video in pixels
     *
     * @var string
     */
    public $Width;

    /**
     * The duration of the video in seconds
     *
     * @var string
     */
    public $Duration;

    /**
     * The number of audio channels in the video 
     *
     * @var string
     */
    public $Channels;

    /**
     * Whether the video is streamed or not
     *
     * @var boolean
     */
    public $Streaming;

    /**
     * The thubmnail video for the article, if it exists
     *
     * @var Zend_Service_Yahoo_Video
     */
    public $Thumbnail;

    /**
     * Video result namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srchmv';


    /**
     * Initializes the video result
     *
     * @param  DOMElement $result
     * @return void
     */
    public function __construct(DOMElement $result)
    {
        $this->_fields = array('Summary', 'RefererUrl', 'FileSize', 'FileFormat', 'Height', 'Width', 'Duration', 'Channels', 'Streaming', 'Thumbnail');

        parent::__construct($result);

        $this->_setThumbnail();
    }
}
Yahoo/Image.php000060400000003530150715514360007362 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Image.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_Image
{
    /**
     * Image URL
     *
     * @var string
     */
    public $Url;

    /**
     * Image height in pixels
     *
     * @var int
     */
    public $Height;

    /**
     * Image width in pixels
     *
     * @var int
     */
    public $Width;


    /**
     * Initializes the image
     *
     * @param  DOMNode $dom
     * @param  string  $namespace
     * @return void
     */
    public function __construct(DOMNode $dom, $namespace)
    {
        $xpath = new DOMXPath($dom->ownerDocument);
        $xpath->registerNamespace('yh', $namespace);
        $this->Url = Zend_Uri::factory($xpath->query('./yh:Url/text()', $dom)->item(0)->data);
        $this->Height = (int) $xpath->query('./yh:Height/text()', $dom)->item(0)->data;
        $this->Width = (int) $xpath->query('./yh:Width/text()', $dom)->item(0)->data;
    }
}
Yahoo/ImageResult.php000060400000004615150715514360010566 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ImageResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_Result
 */
require_once 'Zend/Service/Yahoo/Result.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_ImageResult extends Zend_Service_Yahoo_Result
{
    /**
     * Summary info for the image
     *
     * @var string
     */
    public $Summary;

    /**
     * The URL of the webpage hosting the image
     *
     * @var string
     */
    public $RefererUrl;

    /**
     * The size of the files in bytes
     *
     * @var string
     */
    public $FileSize;

    /**
     * The type of file (bmp, gif, jpeg, etc.)
     *
     * @var string
     */
    public $FileFormat;

    /**
     * The height of the image in pixels
     *
     * @var string
     */
    public $Height;

    /**
     * The width of the image in pixels
     *
     * @var string
     */
    public $Width;

    /**
     * The thubmnail image for the article, if it exists
     *
     * @var Zend_Service_Yahoo_Image
     */
    public $Thumbnail;

    /**
     * Image result namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srchmi';


    /**
     * Initializes the image result
     *
     * @param  DOMElement $result
     * @return void
     */
    public function __construct(DOMElement $result)
    {
        $this->_fields = array('Summary', 'RefererUrl', 'FileSize', 'FileFormat', 'Height', 'Width', 'Thumbnail');

        parent::__construct($result);

        $this->_setThumbnail();
    }
}
Yahoo/ImageResultSet.php000060400000003227150715514360011240 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ImageResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_ResultSet
 */
require_once 'Zend/Service/Yahoo/ResultSet.php';


/**
 * @see Zend_Service_Yahoo_ImageResult
 */
require_once 'Zend/Service/Yahoo/ImageResult.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_ImageResultSet extends Zend_Service_Yahoo_ResultSet
{
    /**
     * Image result set namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srchmi';


    /**
     * Overrides Zend_Service_Yahoo_ResultSet::current()
     *
     * @return Zend_Service_Yahoo_ImageResult
     */
    public function current()
    {
        return new Zend_Service_Yahoo_ImageResult($this->_results->item($this->_currentIndex));
    }
}
Yahoo/LocalResult.php000060400000005167150715514360010601 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: LocalResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_Result
 */
require_once 'Zend/Service/Yahoo/Result.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_LocalResult extends Zend_Service_Yahoo_Result
{
    /**
     * Street address of the result
     *
     * @var string
     */
    public $Address;

    /**
     * City in which the result resides
     *
     * @var string
     */
    public $City;

    /**
     * State in which the result resides
     *
     * @var string
     */
    public $State;

    /**
     * Phone number for the result
     *
     * @var string
     */
    public $Phone;

    /**
     * User-submitted rating for the result
     *
     * @var string
     */
    public $Rating;

    /**
     * The distance to the result from your specified location
     *
     * @var string
     */
    public $Distance;

    /**
     * A URL of a map for the result
     *
     * @var string
     */
    public $MapUrl;

    /**
     * The URL for the business website, if known
     *
     * @var string
     */
    public $BusinessUrl;

    /**
     * The URL for linking to the business website, if known
     *
     * @var string
     */
    public $BusinessClickUrl;

    /**
     * Local result namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:lcl';


    /**
     * Initializes the local result
     *
     * @param  DOMElement $result
     * @return void
     */
    public function __construct(DOMElement $result)
    {
        $this->_fields = array('Address','City', 'City', 'State', 'Phone', 'Rating', 'Distance', 'MapUrl',
                               'BusinessUrl', 'BusinessClickUrl');

        parent::__construct($result);
    }
}
Yahoo/VideoResultSet.php000060400000003222150715514360011257 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2006 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: VideoResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_ResultSet
 */
require_once 'Zend/Service/Yahoo/ResultSet.php';


/**
 * @see Zend_Service_Yahoo_VideoResult
 */
require_once 'Zend/Service/Yahoo/VideoResult.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_VideoResultSet extends Zend_Service_Yahoo_ResultSet
{
    /**
     * Video result set namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srchmv';


    /**
     * Overrides Zend_Service_Yahoo_ResultSet::current()
     *
     * @return Zend_Service_Yahoo_VideoResult
     */
    public function current()
    {
        return new Zend_Service_Yahoo_VideoResult($this->_results->item($this->_currentIndex));
    }
}
Yahoo/WebResultSet.php000060400000003207150715514360010731 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: WebResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_ResultSet
 */
require_once 'Zend/Service/Yahoo/ResultSet.php';


/**
 * @see Zend_Service_Yahoo_WebResult
 */
require_once 'Zend/Service/Yahoo/WebResult.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_WebResultSet extends Zend_Service_Yahoo_ResultSet
{
    /**
     * Web result set namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srch';


    /**
     * Overrides Zend_Service_Yahoo_ResultSet::current()
     *
     * @return Zend_Service_Yahoo_WebResult
     */
    public function current()
    {
        return new Zend_Service_Yahoo_WebResult($this->_results->item($this->_currentIndex));
    }
}
Yahoo/InlinkDataResult.php000060400000002736150715514360011564 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */


/**
 * @see Zend_Service_Yahoo_Result
 */
require_once 'Zend/Service/Yahoo/Result.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_InlinkDataResult extends Zend_Service_Yahoo_Result
{
    /**
     * Web result namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srch';


    /**
     * Initializes the web result
     *
     * @param  DOMElement $result
     * @return void
     */
    public function __construct(DOMElement $result)
    {
        $this->_fields = array();
        parent::__construct($result);
    }
}
Yahoo/PageDataResultSet.php000060400000003143150715514360011661 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */


/**
 * @see Zend_Service_Yahoo_ResultSet
 */
require_once 'Zend/Service/Yahoo/ResultSet.php';


/**
 * @see Zend_Service_Yahoo_WebResult
 */
require_once 'Zend/Service/Yahoo/PageDataResult.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_PageDataResultSet extends Zend_Service_Yahoo_ResultSet
{
    /**
     * Web result set namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srch';


    /**
     * Overrides Zend_Service_Yahoo_ResultSet::current()
     *
     * @return Zend_Service_Yahoo_WebResult
     */
    public function current()
    {
        return new Zend_Service_Yahoo_PageDataResult($this->_results->item($this->_currentIndex));
    }
}
Yahoo/ResultSet.php000060400000010626150715514360010276 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_ResultSet implements SeekableIterator
{
    /**
     * Total number of results available
     *
     * @var int
     */
    public $totalResultsAvailable;

    /**
     * The number of results in this result set
     *
     * @var int
     */
    public $totalResultsReturned;

    /**
     * The offset in the total result set of this search set
     *
     * @var int
     */
    public $firstResultPosition;

    /**
     * A DOMNodeList of results
     *
     * @var DOMNodeList
     */
    protected $_results;

    /**
     * Yahoo Web Service Return Document
     *
     * @var DOMDocument
     */
    protected $_dom;

    /**
     * Xpath Object for $this->_dom
     *
     * @var DOMXPath
     */
    protected $_xpath;

    /**
     * Current Index for SeekableIterator
     *
     * @var int
     */
    protected $_currentIndex = 0;


    /**
     * Parse the search response and retrieve the results for iteration
     *
     * @param  DOMDocument $dom the REST fragment for this object
     * @return void
     */
    public function __construct(DOMDocument $dom)
    {
        $this->totalResultsAvailable = (int) $dom->documentElement->getAttribute('totalResultsAvailable');
        $this->totalResultsReturned = (int) $dom->documentElement->getAttribute('totalResultsReturned');
        $this->firstResultPosition = (int) $dom->documentElement->getAttribute('firstResultPosition');

        $this->_dom = $dom;
        $this->_xpath = new DOMXPath($dom);

        $this->_xpath->registerNamespace('yh', $this->_namespace);

        $this->_results = $this->_xpath->query('//yh:Result');
    }


    /**
     * Total Number of results returned
     *
     * @return int Total number of results returned
     */
    public function totalResults()
    {
        return $this->totalResultsReturned;
    }


    /**
     * Implement SeekableIterator::current()
     *
     * Must be implemented by child classes
     *
     * @throws Zend_Service_Exception
     * @return Zend_Service_Yahoo_Result
     */
    public function current()
    {
        /**
         * @see Zend_Service_Exception
         */
        require_once 'Zend/Service/Exception.php';
        throw new Zend_Service_Exception('Zend_Service_Yahoo_ResultSet::current() must be implemented by child '
                                       . 'classes');
    }


    /**
     * Implement SeekableIterator::key()
     *
     * @return int
     */
    public function key()
    {
        return $this->_currentIndex;
    }


    /**
     * Implement SeekableIterator::next()
     *
     * @return void
     */
    public function next()
    {
        $this->_currentIndex += 1;
    }


    /**
     * Implement SeekableIterator::rewind()
     *
     * @return void
     */
    public function rewind()
    {
        $this->_currentIndex = 0;
    }


    /**
     * Implement SeekableIterator::seek()
     *
     * @param  int $index
     * @return void
     * @throws OutOfBoundsException
     */
    public function seek($index)
    {
        $indexInt = (int) $index;
        if ($indexInt >= 0 && $indexInt < $this->_results->length) {
            $this->_currentIndex = $indexInt;
        } else {
            throw new OutOfBoundsException("Illegal index '$index'");
        }
    }


    /**
     * Implement SeekableIterator::valid()
     *
     * @return boolean
     */
    public function valid()
    {
        return $this->_currentIndex < $this->_results->length;
    }
}
Yahoo/NewsResult.php000060400000005042150715514360010453 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: NewsResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_Result
 */
require_once 'Zend/Service/Yahoo/Result.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_NewsResult extends Zend_Service_Yahoo_Result
{
    /**
     * Sumamry text associated with the result article
     *
     * @var string
     */
    public $Summary;

    /**
     * The company who distributed the article
     *
     * @var string
     */
    public $NewsSource;

    /**
     * The URL for the company who distributed the article
     *
     * @var string
     */
    public $NewsSourceUrl;

    /**
     * The language the article is in
     *
     * @var string
     */
    public $Language;

    /**
     * The date the article was published (in unix timestamp format)
     *
     * @var string
     */
    public $PublishDate;

    /**
     * The date the article was modified (in unix timestamp format)
     *
     * @var string
     */
    public $ModificationDate;

    /**
     * The thubmnail image for the article, if it exists
     *
     * @var Zend_Service_Yahoo_Image
     */
    public $Thumbnail;

    /**
     * News result namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:yn';


    /**
     * Initializes the news result
     *
     * @param  DOMElement $result
     * @return void
     */
    public function __construct(DOMElement $result)
    {
        $this->_fields = array('Summary', 'NewsSource', 'NewsSourceUrl', 'Language', 'PublishDate',
                               'ModificationDate', 'Thumbnail');

        parent::__construct($result);

        $this->_setThumbnail();
    }
}
Yahoo/LocalResultSet.php000060400000004166150715514360011253 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: LocalResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_ResultSet
 */
require_once 'Zend/Service/Yahoo/ResultSet.php';


/**
 * @see Zend_Service_Yahoo_LocalResult
 */
require_once 'Zend/Service/Yahoo/LocalResult.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_LocalResultSet extends Zend_Service_Yahoo_ResultSet
{
    /**
     * The URL of a webpage containing a map graphic with all returned results plotted on it.
     *
     * @var string
     */
    public $resultSetMapURL;

    /**
     * Local result set namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:lcl';


    /**
     * Initializes the local result set
     *
     * @param  DOMDocument $dom
     * @return void
     */
    public function __construct(DOMDocument $dom)
    {
        parent::__construct($dom);

        $this->resultSetMapURL = $this->_xpath->query('//yh:ResultSetMapUrl/text()')->item(0)->data;
    }


    /**
     * Overrides Zend_Service_Yahoo_ResultSet::current()
     *
     * @return Zend_Service_Yahoo_LocalResult
     */
    public function current()
    {
        return new Zend_Service_Yahoo_LocalResult($this->_results->item($this->_currentIndex));
    }
}
Yahoo/WebResult.php000060400000005271150715514360010260 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: WebResult.php 13006 2008-12-03 21:17:01Z matthew $
 */


/**
 * @see Zend_Service_Yahoo_Result
 */
require_once 'Zend/Service/Yahoo/Result.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_WebResult extends Zend_Service_Yahoo_Result
{
    /**
     * A summary of the result
     *
     * @var string
     */
    public $Summary;

    /**
     * The file type of the result (text, html, pdf, etc.)
     *
     * @var string
     */
    public $MimeType;

    /**
     * The modification time of the result (as a unix timestamp)
     *
     * @var string
     */
    public $ModificationDate;

    /**
     * The URL for the Yahoo cache of this page, if it exists
     *
     * @var string
     */
    public $CacheUrl;

    /**
     * The size of the cache entry
     *
     * @var int
     */
    public $CacheSize;

    /**
     * Web result namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srch';


    /**
     * Initializes the web result
     *
     * @param  DOMElement $result
     * @return void
     */
    public function __construct(DOMElement $result)
    {
        $this->_fields = array('Summary', 'MimeType', 'ModificationDate');
        parent::__construct($result);

        $this->_xpath = new DOMXPath($result->ownerDocument);
        $this->_xpath->registerNamespace('yh', $this->_namespace);
		
        // check if the cache section exists
        $cacheUrl = $this->_xpath->query('./yh:Cache/yh:Url/text()', $result)->item(0);
        if ($cacheUrl instanceof DOMNode)
        {
        	$this->CacheUrl = $cacheUrl->data;
        }
        $cacheSize = $this->_xpath->query('./yh:Cache/yh:Size/text()', $result)->item(0);
        if ($cacheSize instanceof DOMNode)
        {
        	$this->CacheSize = (int) $cacheSize->data;
        }
    }
}
Yahoo/NewsResultSet.php000060400000003214150715514360011126 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: NewsResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Yahoo_ResultSet
 */
require_once 'Zend/Service/Yahoo/ResultSet.php';


/**
 * @see Zend_Service_Yahoo_NewsResult
 */
require_once 'Zend/Service/Yahoo/NewsResult.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_NewsResultSet extends Zend_Service_Yahoo_ResultSet
{
    /**
     * News result set namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:yn';


    /**
     * Overrides Zend_Service_Yahoo_ResultSet::current()
     *
     * @return Zend_Service_Yahoo_NewsResult
     */
    public function current()
    {
        return new Zend_Service_Yahoo_NewsResult($this->_results->item($this->_currentIndex));
    }
}
Yahoo/Result.php000060400000005732150715514360007624 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Result.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_Result
{
    /**
     * The title of the search entry
     *
     * @var string
     */
    public $Title;

    /**
     * The URL of the found object
     *
     * @var string
     */
    public $Url;

    /**
     * The URL for linking to the found object
     *
     * @var string
     */
    public $ClickUrl;

    /**
     * Result fields
     *
     * @var array
     */
    protected $_fields;

    /**
     * REST response fragment for the result
     *
     * @var DOMElement
     */
    protected $_result;

    /**
     * Object for XPath queries
     *
     * @var DOMXPath
     */
    protected $_xpath;


    /**
     * Initializes the result
     *
     * @param  DOMElement $result
     * @return void
     */
    public function __construct(DOMElement $result)
    {
        // default fields for all search results:
        $fields = array('Title', 'Url', 'ClickUrl');

        // merge w/ child's fields
        $this->_fields = array_merge($this->_fields, $fields);

        $this->_xpath = new DOMXPath($result->ownerDocument);
        $this->_xpath->registerNamespace('yh', $this->_namespace);

        // add search results to appropriate fields

        foreach ($this->_fields as $f) {
            $query = "./yh:$f/text()";
            $node = $this->_xpath->query($query, $result);
            if ($node->length == 1) {
                $this->{$f} = $node->item(0)->data;
            }
        }

        $this->_result = $result;
    }


    /**
     * Sets the Thumbnail property
     *
     * @return void
     */
    protected function _setThumbnail()
    {
        $node = $this->_xpath->query('./yh:Thumbnail', $this->_result);
        if ($node->length == 1) {
            /**
             * @see Zend_Service_Yahoo_Image
             */
            require_once 'Zend/Service/Yahoo/Image.php';
            $this->Thumbnail = new Zend_Service_Yahoo_Image($node->item(0), $this->_namespace);
        } else {
            $this->Thumbnail = null;
        }
    }
}
Yahoo/InlinkDataResultSet.php000060400000003160150715514360012230 0ustar00<?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 Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */


/**
 * @see Zend_Service_Yahoo_ResultSet
 */
require_once 'Zend/Service/Yahoo/ResultSet.php';


/**
 * @see Zend_Service_Yahoo_WebResult
 */
require_once 'Zend/Service/Yahoo/InlinkDataResult.php';


/**
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Yahoo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Yahoo_InlinkDataResultSet extends Zend_Service_Yahoo_ResultSet
{
    /**
     * Web result set namespace
     *
     * @var string
     */
    protected $_namespace = 'urn:yahoo:srch';


    /**
     * Overrides Zend_Service_Yahoo_ResultSet::current()
     *
     * @return Zend_Service_Yahoo_InlinkDataResult
     */
    public function current()
    {
        return new Zend_Service_Yahoo_InlinkDataResult($this->_results->item($this->_currentIndex));
    }
}