text:
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Builder.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Feed_Builder_Interface
 */
require_once 'Zend/Feed/Builder/Interface.php';

/**
 * @see Zend_Feed_Builder_Header
 */
require_once 'Zend/Feed/Builder/Header.php';

/**
 * @see Zend_Feed_Builder_Entry
 */
require_once 'Zend/Feed/Builder/Entry.php';

/**
 * A simple implementation of Zend_Feed_Builder_Interface.
 *
 * Users are encouraged to make their own classes to implement Zend_Feed_Builder_Interface
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Builder implements Zend_Feed_Builder_Interface
{
    /**
     * The data of the feed
     *
     * @var $_data array
     */
    private $_data;

    /**
     * Header of the feed
     *
     * @var $_header Zend_Feed_Builder_Header
     */
    private $_header;

    /**
     * List of the entries of the feed
     *
     * @var $_entries array
     */
    private $_entries = array();

    /**
     * Constructor. The $data array must conform to the following format:
     * <code>
     *  array(
     *  'title'       => 'title of the feed', //required
     *  'link'        => 'canonical url to the feed', //required
     *  'lastUpdate'  => 'timestamp of the update date', // optional
     *  'published'   => 'timestamp of the publication date', //optional
     *  'charset'     => 'charset', // required
     *  'description' => 'short description of the feed', //optional
     *  'author'      => 'author/publisher of the feed', //optional
     *  'email'       => 'email of the author', //optional
     *  'webmaster'   => 'email address for person responsible for technical issues' // optional, ignored if atom is used
     *  'copyright'   => 'copyright notice', //optional
     *  'image'       => 'url to image', //optional
     *  'generator'   => 'generator', // optional
     *  'language'    => 'language the feed is written in', // optional
     *  'ttl'         => 'how long in minutes a feed can be cached before refreshing', // optional, ignored if atom is used
     *  'rating'      => 'The PICS rating for the channel.', // optional, ignored if atom is used
     *  'cloud'       => array(
     *                    'domain'            => 'domain of the cloud, e.g. rpc.sys.com' // required
     *                    'port'              => 'port to connect to' // optional, default to 80
     *                    'path'              => 'path of the cloud, e.g. /RPC2 //required
     *                    'registerProcedure' => 'procedure to call, e.g. myCloud.rssPleaseNotify' // required
     *                    'protocol'          => 'protocol to use, e.g. soap or xml-rpc' // required
     *                    ), a cloud to be notified of updates // optional, ignored if atom is used
     *  'textInput'   => array(
     *                    'title'       => 'the label of the Submit button in the text input area' // required,
     *                    'description' => 'explains the text input area' // required
     *                    'name'        => 'the name of the text object in the text input area' // required
     *                    'link'        => 'the URL of the CGI script that processes text input requests' // required
     *                    ) // a text input box that can be displayed with the feed // optional, ignored if atom is used
     *  'skipHours'   => array(
     *                    'hour in 24 format', // e.g 13 (1pm)
     *                    // up to 24 rows whose value is a number between 0 and 23
     *                    ) // Hint telling aggregators which hours they can skip // optional, ignored if atom is used
     *  'skipDays '   => array(
     *                    'a day to skip', // e.g Monday
     *                    // up to 7 rows whose value is a Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday
     *                    ) // Hint telling aggregators which days they can skip // optional, ignored if atom is used
     *  'itunes'      => array(
     *                    'author'       => 'Artist column' // optional, default to the main author value
     *                    'owner'        => array(
     *                                        'name' => 'name of the owner' // optional, default to main author value
     *                                        'email' => 'email of the owner' // optional, default to main email value
     *                                        ) // Owner of the podcast // optional
     *                    'image'        => 'album/podcast art' // optional, default to the main image value
     *                    'subtitle'     => 'short description' // optional, default to the main description value
     *                    'summary'      => 'longer description' // optional, default to the main description value
     *                    'block'        => 'Prevent an episode from appearing (yes|no)' // optional
     *                    'category'     => array(
     *                                      array('main' => 'main category', // required
     *                                            'sub'  => 'sub category' // optional
     *                                        ),
     *                                        // up to 3 rows
     *                                        ) // 'Category column and in iTunes Music Store Browse' // required
     *                    'explicit'     => 'parental advisory graphic (yes|no|clean)' // optional
     *                    'keywords'     => 'a comma separated list of 12 keywords maximum' // optional
     *                    'new-feed-url' => 'used to inform iTunes of new feed URL location' // optional
     *                    ) // Itunes extension data // optional, ignored if atom is used
     *  'entries'     => array(
     *                   array(
     *                    'title'        => 'title of the feed entry', //required
     *                    'link'         => 'url to a feed entry', //required
     *                    'description'  => 'short version of a feed entry', // only text, no html, required
     *                    'guid'         => 'id of the article, if not given link value will used', //optional
     *                    'content'      => 'long version', // can contain html, optional
     *                    'lastUpdate'   => 'timestamp of the publication date', // optional
     *                    'comments'     => 'comments page of the feed entry', // optional
     *                    'commentRss'   => 'the feed url of the associated comments', // optional
     *                    'source'       => array(
     *                                        'title' => 'title of the original source' // required,
     *                                        'url' => 'url of the original source' // required
     *                                           ) // original source of the feed entry // optional
     *                    'category'     => array(
     *                                      array(
     *                                        'term' => 'first category label' // required,
     *                                        'scheme' => 'url that identifies a categorization scheme' // optional
     *                                            ),
     *                                      array(
     *                                         //data for the second category and so on
     *                                           )
     *                                        ) // list of the attached categories // optional
     *                    'enclosure'    => array(
     *                                      array(
     *                                        'url' => 'url of the linked enclosure' // required
     *                                        'type' => 'mime type of the enclosure' // optional
     *                                        'length' => 'length of the linked content in octets' // optional
     *                                           ),
     *                                      array(
     *                                         //data for the second enclosure and so on
     *                                           )
     *                                        ) // list of the enclosures of the feed entry // optional
     *                   ),
     *                   array(
     *                   //data for the second entry and so on
     *                   )
     *                 )
     * );
     * </code>
     *
     * @param  array $data
     * @return void
     */
    public function __construct(array $data)
    {
        $this->_data = $data;
        $this->_createHeader($data);
        if (isset($data['entries'])) {
            $this->_createEntries($data['entries']);
        }
    }

    /**
     * Returns an instance of Zend_Feed_Builder_Header
     * describing the header of the feed
     *
     * @return Zend_Feed_Builder_Header
     */
    public function getHeader()
    {
        return $this->_header;
    }

    /**
     * Returns an array of Zend_Feed_Builder_Entry instances
     * describing the entries of the feed
     *
     * @return array of Zend_Feed_Builder_Entry
     */
    public function getEntries()
    {
        return $this->_entries;
    }

    /**
     * Create the Zend_Feed_Builder_Header instance
     *
     * @param  array $data
     * @throws Zend_Feed_Builder_Exception
     * @return void
     */
    protected function _createHeader(array $data)
    {
        $mandatories = array('title', 'link', 'charset');
        foreach ($mandatories as $mandatory) {
            if (!isset($data[$mandatory])) {
                /**
                 * @see Zend_Feed_Builder_Exception
                 */
                require_once 'Zend/Feed/Builder/Exception.php';
                throw new Zend_Feed_Builder_Exception("$mandatory key is missing");
            }
        }
        $this->_header = new Zend_Feed_Builder_Header($data['title'], $data['link'], $data['charset']);
        if (isset($data['lastUpdate'])) {
            $this->_header->setLastUpdate($data['lastUpdate']);
        }
        if (isset($data['published'])) {
            $this->_header->setPublishedDate($data['published']);
        }
        if (isset($data['description'])) {
            $this->_header->setDescription($data['description']);
        }
        if (isset($data['author'])) {
            $this->_header->setAuthor($data['author']);
        }
        if (isset($data['email'])) {
            $this->_header->setEmail($data['email']);
        }
        if (isset($data['webmaster'])) {
            $this->_header->setWebmaster($data['webmaster']);
        }
        if (isset($data['copyright'])) {
            $this->_header->setCopyright($data['copyright']);
        }
        if (isset($data['image'])) {
            $this->_header->setImage($data['image']);
        }
        if (isset($data['generator'])) {
            $this->_header->setGenerator($data['generator']);
        }
        if (isset($data['language'])) {
            $this->_header->setLanguage($data['language']);
        }
        if (isset($data['ttl'])) {
            $this->_header->setTtl($data['ttl']);
        }
        if (isset($data['rating'])) {
            $this->_header->setRating($data['rating']);
        }
        if (isset($data['cloud'])) {
            $mandatories = array('domain', 'path', 'registerProcedure', 'protocol');
            foreach ($mandatories as $mandatory) {
                if (!isset($data['cloud'][$mandatory])) {
                    /**
                     * @see Zend_Feed_Builder_Exception
                     */
                    require_once 'Zend/Feed/Builder/Exception.php';
                    throw new Zend_Feed_Builder_Exception("you have to define $mandatory property of your cloud");
                }
            }
            $uri_str = 'http://' . $data['cloud']['domain'] . $data['cloud']['path'];
            $this->_header->setCloud($uri_str, $data['cloud']['registerProcedure'], $data['cloud']['protocol']);
        }
        if (isset($data['textInput'])) {
            $mandatories = array('title', 'description', 'name', 'link');
            foreach ($mandatories as $mandatory) {
                if (!isset($data['textInput'][$mandatory])) {
                    /**
                     * @see Zend_Feed_Builder_Exception
                     */
                    require_once 'Zend/Feed/Builder/Exception.php';
                    throw new Zend_Feed_Builder_Exception("you have to define $mandatory property of your textInput");
                }
            }
            $this->_header->setTextInput($data['textInput']['title'],
                                         $data['textInput']['description'],
                                         $data['textInput']['name'],
                                         $data['textInput']['link']);
        }
        if (isset($data['skipHours'])) {
            $this->_header->setSkipHours($data['skipHours']);
        }
        if (isset($data['skipDays'])) {
            $this->_header->setSkipDays($data['skipDays']);
        }
        if (isset($data['itunes'])) {
            $itunes = new Zend_Feed_Builder_Header_Itunes($data['itunes']['category']);
            if (isset($data['itunes']['author'])) {
                $itunes->setAuthor($data['itunes']['author']);
            }
            if (isset($data['itunes']['owner'])) {
                $name = isset($data['itunes']['owner']['name']) ? $data['itunes']['owner']['name'] : '';
                $email = isset($data['itunes']['owner']['email']) ? $data['itunes']['owner']['email'] : '';
                $itunes->setOwner($name, $email);
            }
            if (isset($data['itunes']['image'])) {
                $itunes->setImage($data['itunes']['image']);
            }
            if (isset($data['itunes']['subtitle'])) {
                $itunes->setSubtitle($data['itunes']['subtitle']);
            }
            if (isset($data['itunes']['summary'])) {
                $itunes->setSummary($data['itunes']['summary']);
            }
            if (isset($data['itunes']['block'])) {
                $itunes->setBlock($data['itunes']['block']);
            }
            if (isset($data['itunes']['explicit'])) {
                $itunes->setExplicit($data['itunes']['explicit']);
            }
            if (isset($data['itunes']['keywords'])) {
                $itunes->setKeywords($data['itunes']['keywords']);
            }
            if (isset($data['itunes']['new-feed-url'])) {
                $itunes->setNewFeedUrl($data['itunes']['new-feed-url']);
            }

            $this->_header->setITunes($itunes);
        }
    }

    /**
     * Create the array of article entries
     *
     * @param  array $data
     * @throws Zend_Feed_Builder_Exception
     * @return void
     */
    protected function _createEntries(array $data)
    {
        foreach ($data as $row) {
            $mandatories = array('title', 'link', 'description');
            foreach ($mandatories as $mandatory) {
                if (!isset($row[$mandatory])) {
                    /**
                     * @see Zend_Feed_Builder_Exception
                     */
                    require_once 'Zend/Feed/Builder/Exception.php';
                    throw new Zend_Feed_Builder_Exception("$mandatory key is missing");
                }
            }
            $entry = new Zend_Feed_Builder_Entry($row['title'], $row['link'], $row['description']);
            if (isset($row['author'])) {
                $entry->setAuthor($row['author']);
            }
            if (isset($row['guid'])) {
                $entry->setId($row['guid']);
            }
            if (isset($row['content'])) {
                $entry->setContent($row['content']);
            }
            if (isset($row['lastUpdate'])) {
                $entry->setLastUpdate($row['lastUpdate']);
            }
            if (isset($row['comments'])) {
                $entry->setCommentsUrl($row['comments']);
            }
            if (isset($row['commentRss'])) {
                $entry->setCommentsRssUrl($row['commentRss']);
            }
            if (isset($row['source'])) {
                $mandatories = array('title', 'url');
                foreach ($mandatories as $mandatory) {
                    if (!isset($row['source'][$mandatory])) {
                        /**
                         * @see Zend_Feed_Builder_Exception
                         */
                        require_once 'Zend/Feed/Builder/Exception.php';
                        throw new Zend_Feed_Builder_Exception("$mandatory key of source property is missing");
                    }
                }
                $entry->setSource($row['source']['title'], $row['source']['url']);
            }
            if (isset($row['category'])) {
                $entry->setCategories($row['category']);
            }
            if (isset($row['enclosure'])) {
                $entry->setEnclosures($row['enclosure']);
            }

            $this->_entries[] = $entry;
        }
    }
}


text:
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Feed_Exception
 */
require_once 'Zend/Feed/Exception.php';

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

repo_name: michael-romer/zf-boilerplate

repo_language: PHP

mime_type: text/html


text:
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * Input feed data interface
 *
 * Classes implementing this interface can be passe to Zend_Feed::importBuilder
 * as an input data source for the Zend_Feed construction
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_Feed_Builder_Interface
{
    /**
     * Returns an instance of Zend_Feed_Builder_Header
     * describing the header of the feed
     *
     * @return Zend_Feed_Builder_Header
     */
    public function getHeader();

    /**
     * Returns an array of Zend_Feed_Builder_Entry instances
     * describing the entries of the feed
     *
     * @return array of Zend_Feed_Builder_Entry
     */
    public function getEntries();
}


text:
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Header.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Feed_Builder_Header_Itunes
 */
require_once 'Zend/Feed/Builder/Header/Itunes.php';

/**
 * @see Zend_Uri
 */
require_once 'Zend/Uri.php';

/**
 * Header of a custom build feed
 *
 * Classes implementing the Zend_Feed_Builder_Interface interface
 * uses this class to describe the header of a feed
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Builder_Header extends ArrayObject
{
    /**
     * Constructor
     *
     * @param  string $title title of the feed
     * @param  string $link canonical url of the feed
     * @param  string $charset charset of the textual data
     * @return void
     */
    public function __construct($title, $link, $charset = 'utf-8')
    {
        $this->offsetSet('title', $title);
        $this->offsetSet('link', $link);
        $this->offsetSet('charset', $charset);
        $this->setLastUpdate(time())
             ->setGenerator('Zend_Feed');
    }

    /**
     * Read only properties accessor
     *
     * @param  string $name property to read
     * @return mixed
     */
    public function __get($name)
    {
        if (!$this->offsetExists($name)) {
            return NULL;
        }

        return $this->offsetGet($name);
    }

    /**
     * Write properties accessor
     *
     * @param string $name  name of the property to set
     * @param mixed  $value value to set
     * @return void
     */
    public function __set($name, $value)
    {
        $this->offsetSet($name, $value);
    }

    /**
     * Isset accessor
     *
     * @param  string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return $this->offsetExists($key);
    }

    /**
     * Unset accessor
     *
     * @param  string $key
     * @return void
     */
    public function __unset($key)
    {
        if ($this->offsetExists($key)) {
            $this->offsetUnset($key);
        }
    }

    /**
     * Timestamp of the update date
     *
     * @param  int $lastUpdate
     * @return Zend_Feed_Builder_Header
     */
    public function setLastUpdate($lastUpdate)
    {
        $this->offsetSet('lastUpdate', $lastUpdate);
        return $this;
    }

    /**
     * Timestamp of the publication date
     *
     * @param  int $published
     * @return Zend_Feed_Builder_Header
     */
    public function setPublishedDate($published)
    {
        $this->offsetSet('published', $published);
        return $this;
    }

    /**
     * Short description of the feed
     *
     * @param  string $description
     * @return Zend_Feed_Builder_Header
     */
    public function setDescription($description)
    {
        $this->offsetSet('description', $description);
        return $this;
    }

    /**
     * Sets the author of the feed
     *
     * @param  string $author
     * @return Zend_Feed_Builder_Header
     */
    public function setAuthor($author)
    {
        $this->offsetSet('author', $author);
        return $this;
    }

    /**
     * Sets the author's email
     *
     * @param  string $email
     * @return Zend_Feed_Builder_Header
     * @throws Zend_Feed_Builder_Exception
     */
    public function setEmail($email)
    {
        /**
         * @see Zend_Validate_EmailAddress
         */
        require_once 'Zend/Validate/EmailAddress.php';
        $validate = new Zend_Validate_EmailAddress();
        if (!$validate->isValid($email)) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to set a valid email address into the email property");
        }
        $this->offsetSet('email', $email);
        return $this;
    }

    /**
     * Sets the copyright notice
     *
     * @param  string $copyright
     * @return Zend_Feed_Builder_Header
     */
    public function setCopyright($copyright)
    {
        $this->offsetSet('copyright', $copyright);
        return $this;
    }

    /**
     * Sets the image of the feed
     *
     * @param  string $image
     * @return Zend_Feed_Builder_Header
     */
    public function setImage($image)
    {
        $this->offsetSet('image', $image);
        return $this;
    }

    /**
     * Sets the generator of the feed
     *
     * @param  string $generator
     * @return Zend_Feed_Builder_Header
     */
    public function setGenerator($generator)
    {
        $this->offsetSet('generator', $generator);
        return $this;
    }

    /**
     * Sets the language of the feed
     *
     * @param  string $language
     * @return Zend_Feed_Builder_Header
     */
    public function setLanguage($language)
    {
        $this->offsetSet('language', $language);
        return $this;
    }

    /**
     * Email address for person responsible for technical issues
     * Ignored if atom is used
     *
     * @param  string $webmaster
     * @return Zend_Feed_Builder_Header
     * @throws Zend_Feed_Builder_Exception
     */
    public function setWebmaster($webmaster)
    {
        /**
         * @see Zend_Validate_EmailAddress
         */
        require_once 'Zend/Validate/EmailAddress.php';
        $validate = new Zend_Validate_EmailAddress();
        if (!$validate->isValid($webmaster)) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to set a valid email address into the webmaster property");
        }
        $this->offsetSet('webmaster', $webmaster);
        return $this;
    }

    /**
     * How long in minutes a feed can be cached before refreshing
     * Ignored if atom is used
     *
     * @param  int $ttl
     * @return Zend_Feed_Builder_Header
     * @throws Zend_Feed_Builder_Exception
     */
    public function setTtl($ttl)
    {
        /**
         * @see Zend_Validate_Int
         */
        require_once 'Zend/Validate/Int.php';
        $validate = new Zend_Validate_Int();
        if (!$validate->isValid($ttl)) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to set an integer value to the ttl property");
        }
        $this->offsetSet('ttl', $ttl);
        return $this;
    }

    /**
     * PICS rating for the feed
     * Ignored if atom is used
     *
     * @param  string $rating
     * @return Zend_Feed_Builder_Header
     */
    public function setRating($rating)
    {
        $this->offsetSet('rating', $rating);
        return $this;
    }

    /**
     * Cloud to be notified of updates of the feed
     * Ignored if atom is used
     *
     * @param  string|Zend_Uri_Http $uri
     * @param  string               $procedure procedure to call, e.g. myCloud.rssPleaseNotify
     * @param  string               $protocol  protocol to use, e.g. soap or xml-rpc
     * @return Zend_Feed_Builder_Header
     * @throws Zend_Feed_Builder_Exception
     */
    public function setCloud($uri, $procedure, $protocol)
    {
        if (is_string($uri) && Zend_Uri_Http::check($uri)) {
            $uri = Zend_Uri::factory($uri);
        }
        if (!$uri instanceof Zend_Uri_Http) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception('Passed parameter is not a valid HTTP URI');
        }
        if (!$uri->getPort()) {
            $uri->setPort(80);
        }
        $this->offsetSet('cloud', array('uri' => $uri,
                                        'procedure' => $procedure,
                                        'protocol' => $protocol));
        return $this;
    }

    /**
     * A text input box that can be displayed with the feed
     * Ignored if atom is used
     *
     * @param  string $title       the label of the Submit button in the text input area
     * @param  string $description explains the text input area
     * @param  string $name        the name of the text object in the text input area
     * @param  string $link        the URL of the CGI script that processes text input requests
     * @return Zend_Feed_Builder_Header
     */
    public function setTextInput($title, $description, $name, $link)
    {
        $this->offsetSet('textInput', array('title' => $title,
                                            'description' => $description,
                                            'name' => $name,
                                            'link' => $link));
        return $this;
    }

    /**
     * Hint telling aggregators which hours they can skip
     * Ignored if atom is used
     *
     * @param  array $hours list of hours in 24 format
     * @return Zend_Feed_Builder_Header
     * @throws Zend_Feed_Builder_Exception
     */
    public function setSkipHours(array $hours)
    {
        if (count($hours) > 24) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you can not have more than 24 rows in the skipHours property");
        }
        foreach ($hours as $hour) {
            if ($hour < 0 || $hour > 23) {
                /**
                 * @see Zend_Feed_Builder_Exception
                 */
                require_once 'Zend/Feed/Builder/Exception.php';
                throw new Zend_Feed_Builder_Exception("$hour has te be between 0 and 23");
            }
        }
        $this->offsetSet('skipHours', $hours);
        return $this;
    }

    /**
     * Hint telling aggregators which days they can skip
     * Ignored if atom is used
     *
     * @param  array $days list of days to skip, e.g. Monday
     * @return Zend_Feed_Builder_Header
     * @throws Zend_Feed_Builder_Exception
     */
    public function setSkipDays(array $days)
    {
        if (count($days) > 7) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you can not have more than 7 days in the skipDays property");
        }
        $valid = array('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday');
        foreach ($days as $day) {
            if (!in_array(strtolower($day), $valid)) {
                /**
                 * @see Zend_Feed_Builder_Exception
                 */
                require_once 'Zend/Feed/Builder/Exception.php';
                throw new Zend_Feed_Builder_Exception("$day is not a valid day");
            }
        }
        $this->offsetSet('skipDays', $days);
        return $this;
    }

    /**
     * Sets the iTunes rss extension
     *
     * @param  Zend_Feed_Builder_Header_Itunes $itunes
     * @return Zend_Feed_Builder_Header
     */
    public function setITunes(Zend_Feed_Builder_Header_Itunes $itunes)
    {
        $this->offsetSet('itunes', $itunes);
        return $this;
    }
}


text:
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Entry.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * An entry of a custom build feed
 *
 * Classes implementing the Zend_Feed_Builder_Interface interface
 * uses this class to describe an entry of a feed
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Builder_Entry extends ArrayObject
{
    /**
     * Create a new builder entry
     *
     * @param  string $title
     * @param  string $link
     * @param  string $description short version of the entry, no html
     * @return void
     */
    public function __construct($title, $link, $description)
    {
        $this->offsetSet('title', $title);
        $this->offsetSet('link', $link);
        $this->offsetSet('description', $description);
        $this->setLastUpdate(time());
    }

    /**
     * Read only properties accessor
     *
     * @param  string $name property to read
     * @return mixed
     */
    public function __get($name)
    {
        if (!$this->offsetExists($name)) {
            return NULL;
        }

        return $this->offsetGet($name);
    }

    /**
     * Write properties accessor
     *
     * @param  string $name name of the property to set
     * @param  mixed $value value to set
     * @return void
     */
    public function __set($name, $value)
    {
        $this->offsetSet($name, $value);
    }

    /**
     * Isset accessor
     *
     * @param  string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return $this->offsetExists($key);
    }

    /**
     * Unset accessor
     *
     * @param  string $key
     * @return void
     */
    public function __unset($key)
    {
        if ($this->offsetExists($key)) {
            $this->offsetUnset($key);
        }
    }

    /**
     * Sets the author of the entry
     *
     * @param  string $author
     * @return Zend_Feed_Builder_Entry
     */
    public function setAuthor($author)
    {
        $this->offsetSet('author', $author);
        return $this;
    }

    /**
     * Sets the id/guid of the entry
     *
     * @param  string $id
     * @return Zend_Feed_Builder_Entry
     */
    public function setId($id)
    {
        $this->offsetSet('guid', $id);
        return $this;
    }

    /**
     * Sets the full html content of the entry
     *
     * @param  string $content
     * @return Zend_Feed_Builder_Entry
     */
    public function setContent($content)
    {
        $this->offsetSet('content', $content);
        return $this;
    }

    /**
     * Timestamp of the update date
     *
     * @param  int $lastUpdate
     * @return Zend_Feed_Builder_Entry
     */
    public function setLastUpdate($lastUpdate)
    {
        $this->offsetSet('lastUpdate', $lastUpdate);
        return $this;
    }

    /**
     * Sets the url of the commented page associated to the entry
     *
     * @param  string $comments
     * @return Zend_Feed_Builder_Entry
     */
    public function setCommentsUrl($comments)
    {
        $this->offsetSet('comments', $comments);
        return $this;
    }

    /**
     * Sets the url of the comments feed link
     *
     * @param  string $commentRss
     * @return Zend_Feed_Builder_Entry
     */
    public function setCommentsRssUrl($commentRss)
    {
        $this->offsetSet('commentRss', $commentRss);
        return $this;
    }

    /**
     * Defines a reference to the original source
     *
     * @param  string $title
     * @param  string $url
     * @return Zend_Feed_Builder_Entry
     */
    public function setSource($title, $url)
    {
        $this->offsetSet('source', array('title' => $title,
                                         'url' => $url));
        return $this;
    }

    /**
     * Sets the categories of the entry
     * Format of the array:
     *
     * array(
     *   array(
     *         'term' => 'first category label',
     *         'scheme' => 'url that identifies a categorization scheme' // optional
     *        ),
     *   // second category and so one
     * )
     *
     *
     * @param  array $categories
     * @return Zend_Feed_Builder_Entry
     */
    public function setCategories(array $categories)
    {
        foreach ($categories as $category) {
            $this->addCategory($category);
        }
        return $this;
    }

    /**
     * Add a category to the entry
     *
     * @param  array $category see Zend_Feed_Builder_Entry::setCategories() for format
     * @return Zend_Feed_Builder_Entry
     * @throws Zend_Feed_Builder_Exception
     */
    public function addCategory(array $category)
    {
        if (empty($category['term'])) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to define the name of the category");
        }

        if (!$this->offsetExists('category')) {
            $categories = array($category);
        } else {
            $categories = $this->offsetGet('category');
            $categories[] = $category;
        }
        $this->offsetSet('category', $categories);
        return $this;
    }

    /**
     * Sets the enclosures of the entry
     * Format of the array:
     *
     * array(
     *   array(
     *         'url' => 'url of the linked enclosure',
     *         'type' => 'mime type of the enclosure' // optional
     *         'length' => 'length of the linked content in octets' // optional
     *        ),
     *   // second enclosure and so one
     * )
     *
     *
     * @param  array $enclosures
     * @return Zend_Feed_Builder_Entry
     * @throws Zend_Feed_Builder_Exception
     */
    public function setEnclosures(array $enclosures)
    {
        foreach ($enclosures as $enclosure) {
            if (empty($enclosure['url'])) {
                /**
                 * @see Zend_Feed_Builder_Exception
                 */
                require_once 'Zend/Feed/Builder/Exception.php';
                throw new Zend_Feed_Builder_Exception("you have to supply an url for your enclosure");
            }
            $type = isset($enclosure['type']) ? $enclosure['type'] : '';
            $length = isset($enclosure['length']) ? $enclosure['length'] : '';
            $this->addEnclosure($enclosure['url'], $type, $length);
        }
        return $this;
    }

    /**
     * Add an enclosure to the entry
     *
     * @param  string $url
     * @param  string $type
     * @param  string $length
     * @return Zend_Feed_Builder_Entry
     */
    public function addEnclosure($url, $type = '', $length = '')
    {
        if (!$this->offsetExists('enclosure')) {
            $enclosure = array();
        } else {
            $enclosure = $this->offsetGet('enclosure');
        }
        $enclosure[] = array('url' => $url,
                             'type' => $type,
                             'length' => $length);
        $this->offsetSet('enclosure', $enclosure);
        return $this;
    }
}


text:
<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Itunes.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * ITunes rss extension
 *
 * Classes used to describe the itunes channel extension
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Builder_Header_Itunes extends ArrayObject
{
    /**
     * Constructor
     *
     * @param  array $categories Categories columns and in iTunes Music Store Browse
     * @return void
     */
    public function __construct(array $categories)
    {
        $this->setCategories($categories);
    }

    /**
     * Sets the categories column and in iTunes Music Store Browse
     * $categories must conform to the following format:
     * <code>
     * array(array('main' => 'main category',
     *             'sub' => 'sub category' // optionnal
     *            ),
     *       // up to 3 rows
     *      )
     * </code>
     *
     * @param  array $categories
     * @return Zend_Feed_Builder_Header_Itunes
     * @throws Zend_Feed_Builder_Exception
     */
    public function setCategories(array $categories)
    {
        $nb = count($categories);
        if (0 === $nb) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to set at least one itunes category");
        }
        if ($nb > 3) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to set at most three itunes categories");
        }
        foreach ($categories as $i => $category) {
            if (empty($category['main'])) {
                /**
                 * @see Zend_Feed_Builder_Exception
                 */
                require_once 'Zend/Feed/Builder/Exception.php';
                throw new Zend_Feed_Builder_Exception("you have to set the main category (category #$i)");
            }
        }
        $this->offsetSet('category', $categories);
        return $this;
    }

    /**
     * Sets the artist value, default to the feed's author value
     *
     * @param  string $author
     * @return Zend_Feed_Builder_Header_Itunes
     */
    public function setAuthor($author)
    {
        $this->offsetSet('author', $author);
        return $this;
    }

    /**
     * Sets the owner of the postcast
     *
     * @param  string $name  default to the feed's author value
     * @param  string $email default to the feed's email value
     * @return Zend_Feed_Builder_Header_Itunes
     * @throws Zend_Feed_Builder_Exception
     */
    public function setOwner($name = '', $email = '')
    {
        if (!empty($email)) {
            /**
             * @see Zend_Validate_EmailAddress
             */
            require_once 'Zend/Validate/EmailAddress.php';
            $validate = new Zend_Validate_EmailAddress();
            if (!$validate->isValid($email)) {
                /**
                 * @see Zend_Feed_Builder_Exception
                 */
                require_once 'Zend/Feed/Builder/Exception.php';
                throw new Zend_Feed_Builder_Exception("you have to set a valid email address into the itunes owner's email property");
            }
        }
        $this->offsetSet('owner', array('name' => $name, 'email' => $email));
        return $this;
    }

    /**
     * Sets the album/podcast art picture
     * Default to the feed's image value
     *
     * @param  string $image
     * @return Zend_Feed_Builder_Header_Itunes
     */
    public function setImage($image)
    {
        $this->offsetSet('image', $image);
        return $this;
    }

    /**
     * Sets the short description of the podcast
     * Default to the feed's description
     *
     * @param  string $subtitle
     * @return Zend_Feed_Builder_Header_Itunes
     */
    public function setSubtitle($subtitle)
    {
        $this->offsetSet('subtitle', $subtitle);
        return $this;
    }

    /**
     * Sets the longer description of the podcast
     * Default to the feed's description
     *
     * @param  string $summary
     * @return Zend_Feed_Builder_Header_Itunes
     */
    public function setSummary($summary)
    {
        $this->offsetSet('summary', $summary);
        return $this;
    }

    /**
     * Prevent a feed from appearing
     *
     * @param  string $block can be 'yes' or 'no'
     * @return Zend_Feed_Builder_Header_Itunes
     * @throws Zend_Feed_Builder_Exception
     */
    public function setBlock($block)
    {
        $block = strtolower($block);
        if (!in_array($block, array('yes', 'no'))) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to set yes or no to the itunes block property");
        }
        $this->offsetSet('block', $block);
        return $this;
    }

    /**
     * Configuration of the parental advisory graphic
     *
     * @param  string $explicit can be 'yes', 'no' or 'clean'
     * @return Zend_Feed_Builder_Header_Itunes
     * @throws Zend_Feed_Builder_Exception
     */
    public function setExplicit($explicit)
    {
        $explicit = strtolower($explicit);
        if (!in_array($explicit, array('yes', 'no', 'clean'))) {
            /**
             * @see Zend_Feed_Builder_Exception
             */
            require_once 'Zend/Feed/Builder/Exception.php';
            throw new Zend_Feed_Builder_Exception("you have to set yes, no or clean to the itunes explicit property");
        }
        $this->offsetSet('explicit', $explicit);
        return $this;
    }

    /**
     * Sets a comma separated list of 12 keywords maximum
     *
     * @param  string $keywords
     * @return Zend_Feed_Builder_Header_Itunes
     */
    public function setKeywords($keywords)
    {
        $this->offsetSet('keywords', $keywords);
        return $this;
    }

    /**
     * Sets the new feed URL location
     *
     * @param  string $url
     * @return Zend_Feed_Builder_Header_Itunes
     */
    public function setNewFeedUrl($url)
    {
        $this->offsetSet('new_feed_url', $url);
        return $this;
    }

    /**
     * Read only properties accessor
     *
     * @param  string $name property to read
     * @return mixed
     */
    public function __get($name)
    {
        if (!$this->offsetExists($name)) {
            return NULL;
        }

        return $this->offsetGet($name);
    }

    /**
     * Write properties accessor
     *
     * @param  string $name  name of the property to set
     * @param  mixed  $value value to set
     * @return void
     */
    public function __set($name, $value)
    {
        $this->offsetSet($name, $value);
    }

    /**
     * Isset accessor
     *
     * @param  string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return $this->offsetExists($key);
    }

    /**
     * Unset accessor
     *
     * @param  string $key
     * @return void
     */
    public function __unset($key)
    {
        if ($this->offsetExists($key)) {
            $this->offsetUnset($key);
        }
    }

}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: HttpResponse.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Feed_Pubsubhubbub
 */
require_once 'Zend/Feed/Pubsubhubbub.php';

/**
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Pubsubhubbub_HttpResponse
{
    /**
     * The body of any response to the current callback request
     *
     * @var string
     */
    protected $_body = '';

    /**
     * Array of headers. Each header is an array with keys 'name' and 'value'
     *
     * @var array
     */
    protected $_headers = array();

    /**
     * HTTP response code to use in headers
     *
     * @var int
     */
    protected $_httpResponseCode = 200;

    /**
     * Send the response, including all headers
     *
     * @return void
     */
    public function sendResponse()
    {
        $this->sendHeaders();
        echo $this->getBody();
    }

    /**
     * Send all headers
     *
     * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code}
     * has been specified, it is sent with the first header.
     *
     * @return void
     */
    public function sendHeaders()
    {
        if (count($this->_headers) || (200 != $this->_httpResponseCode)) {
            $this->canSendHeaders(true);
        } elseif (200 == $this->_httpResponseCode) {
            return;
        }
        $httpCodeSent = false;
        foreach ($this->_headers as $header) {
            if (!$httpCodeSent && $this->_httpResponseCode) {
                header($header['name'] . ': ' . $header['value'], $header['replace'], $this->_httpResponseCode);
                $httpCodeSent = true;
            } else {
                header($header['name'] . ': ' . $header['value'], $header['replace']);
            }
        }
        if (!$httpCodeSent) {
            header('HTTP/1.1 ' . $this->_httpResponseCode);
            $httpCodeSent = true;
        }
    }

    /**
     * Set a header
     *
     * If $replace is true, replaces any headers already defined with that
     * $name.
     *
     * @param  string $name
     * @param  string $value
     * @param  boolean $replace
     * @return Zend_Feed_Pubsubhubbub_HttpResponse
     */
    public function setHeader($name, $value, $replace = false)
    {
        $name  = $this->_normalizeHeader($name);
        $value = (string) $value;
        if ($replace) {
            foreach ($this->_headers as $key => $header) {
                if ($name == $header['name']) {
                    unset($this->_headers[$key]);
                }
            }
        }
        $this->_headers[] = array(
            'name'    => $name,
            'value'   => $value,
            'replace' => $replace,
        );

        return $this;
    }

    /**
     * Check if a specific Header is set and return its value
     *
     * @param  string $name
     * @return string|null
     */
    public function getHeader($name)
    {
        $name = $this->_normalizeHeader($name);
        foreach ($this->_headers as $header) {
            if ($header['name'] == $name) {
                return $header['value'];
            }
        }
    }

    /**
     * Return array of headers; see {@link $_headers} for format
     *
     * @return array
     */
    public function getHeaders()
    {
        return $this->_headers;
    }

    /**
     * Can we send headers?
     *
     * @param  boolean $throw Whether or not to throw an exception if headers have been sent; defaults to false
     * @return boolean
     * @throws Zend_Feed_Pubsubhubbub_Exception
     */
    public function canSendHeaders($throw = false)
    {
        $ok = headers_sent($file, $line);
        if ($ok && $throw) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
        }
        return !$ok;
    }

    /**
     * Set HTTP response code to use with headers
     *
     * @param  int $code
     * @return Zend_Feed_Pubsubhubbub_HttpResponse
     */
    public function setHttpResponseCode($code)
    {
        if (!is_int($code) || (100 > $code) || (599 < $code)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid HTTP response'
            . ' code:' . $code);
        }
        $this->_httpResponseCode = $code;
        return $this;
    }

    /**
     * Retrieve HTTP response code
     *
     * @return int
     */
    public function getHttpResponseCode()
    {
        return $this->_httpResponseCode;
    }

    /**
     * Set body content
     *
     * @param  string $content
     * @return Zend_Feed_Pubsubhubbub_HttpResponse
     */
    public function setBody($content)
    {
        $this->_body = (string) $content;
        $this->setHeader('content-length', strlen($content));
        return $this;
    }

    /**
     * Return the body content
     *
     * @return string
     */
    public function getBody()
    {
        return $this->_body;
    }

    /**
     * Normalizes a header name to X-Capitalized-Names
     *
     * @param  string $name
     * @return string
     */
    protected function _normalizeHeader($name)
    {
        $filtered = str_replace(array('-', '_'), ' ', (string) $name);
        $filtered = ucwords(strtolower($filtered));
        $filtered = str_replace(' ', '-', $filtered);
        return $filtered;
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
 */

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

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


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @subpackage Callback
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: CallbackInterface.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @subpackage Callback
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_Feed_Pubsubhubbub_CallbackInterface
{
    /**
     * Handle any callback from a Hub Server responding to a subscription or
     * unsubscription request. This should be the Hub Server confirming the
     * the request prior to taking action on it.
     *
     * @param array $httpData GET/POST data if available and not in $_GET/POST
     * @param bool $sendResponseNow Whether to send response now or when asked
     */
    public function handle(array $httpData = null, $sendResponseNow = false);

    /**
     * Send the response, including all headers.
     * If you wish to handle this via Zend_Controller, use the getter methods
     * to retrieve any data needed to be set on your HTTP Response object, or
     * simply give this object the HTTP Response instance to work with for you!
     *
     * @return void
     */
    public function sendResponse();

    /**
     * An instance of a class handling Http Responses. This is implemented in
     * Zend_Feed_Pubsubhubbub_HttpResponse which shares an unenforced interface with
     * (i.e. not inherited from) Zend_Controller_Response_Http.
     *
     * @param Zend_Feed_Pubsubhubbub_HttpResponse|Zend_Controller_Response_Http $httpResponse
     */
    public function setHttpResponse($httpResponse);

    /**
     * An instance of a class handling Http Responses. This is implemented in
     * Zend_Feed_Pubsubhubbub_HttpResponse which shares an unenforced interface with
     * (i.e. not inherited from) Zend_Controller_Response_Http.
     *
     * @return Zend_Feed_Pubsubhubbub_HttpResponse|Zend_Controller_Response_Http
     */
    public function getHttpResponse();
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @subpackage Callback
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: CallbackAbstract.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Feed_Pubsubhubbub_CallbackInterface
 */
require_once 'Zend/Feed/Pubsubhubbub/CallbackInterface.php';

/**
 * @see Zend_Feed_Pubsubhubbub_HttpResponse
 */
require_once 'Zend/Feed/Pubsubhubbub/HttpResponse.php';

/**
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @subpackage Callback
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Feed_Pubsubhubbub_CallbackAbstract
    implements Zend_Feed_Pubsubhubbub_CallbackInterface
{
    /**
     * An instance of Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface used
     * to background save any verification tokens associated with a subscription
     * or other.
     *
     * @var Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface
     */
    protected $_storage = null;

    /**
     * An instance of a class handling Http Responses. This is implemented in
     * Zend_Feed_Pubsubhubbub_HttpResponse which shares an unenforced interface with
     * (i.e. not inherited from) Zend_Controller_Response_Http.
     *
     * @var Zend_Feed_Pubsubhubbub_HttpResponse|Zend_Controller_Response_Http
     */
    protected $_httpResponse = null;

    /**
     * The number of Subscribers for which any updates are on behalf of.
     *
     * @var int
     */
    protected $_subscriberCount = 1;

    /**
     * Constructor; accepts an array or Zend_Config instance to preset
     * options for the Subscriber without calling all supported setter
     * methods in turn.
     *
     * @param array|Zend_Config $options Options array or Zend_Config instance
     */
    public function __construct($config = null)
    {
        if ($config !== null) {
            $this->setConfig($config);
        }
    }

    /**
     * Process any injected configuration options
     *
     * @param  array|Zend_Config $options Options array or Zend_Config instance
     * @return Zend_Feed_Pubsubhubbub_CallbackAbstract
     */
    public function setConfig($config)
    {
        if ($config instanceof Zend_Config) {
            $config = $config->toArray();
        } elseif (!is_array($config)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Array or Zend_Config object'
            . 'expected, got ' . gettype($config));
        }
        if (array_key_exists('storage', $config)) {
            $this->setStorage($config['storage']);
        }
        return $this;
    }

    /**
     * Send the response, including all headers.
     * If you wish to handle this via Zend_Controller, use the getter methods
     * to retrieve any data needed to be set on your HTTP Response object, or
     * simply give this object the HTTP Response instance to work with for you!
     *
     * @return void
     */
    public function sendResponse()
    {
        $this->getHttpResponse()->sendResponse();
    }

    /**
     * Sets an instance of Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface used
     * to background save any verification tokens associated with a subscription
     * or other.
     *
     * @param  Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface $storage
     * @return Zend_Feed_Pubsubhubbub_CallbackAbstract
     */
    public function setStorage(Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface $storage)
    {
        $this->_storage = $storage;
        return $this;
    }

    /**
     * Gets an instance of Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface used
     * to background save any verification tokens associated with a subscription
     * or other.
     *
     * @return Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface
     */
    public function getStorage()
    {
        if ($this->_storage === null) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('No storage object has been'
                . ' set that subclasses Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface');
        }
        return $this->_storage;
    }

    /**
     * An instance of a class handling Http Responses. This is implemented in
     * Zend_Feed_Pubsubhubbub_HttpResponse which shares an unenforced interface with
     * (i.e. not inherited from) Zend_Controller_Response_Http.
     *
     * @param  Zend_Feed_Pubsubhubbub_HttpResponse|Zend_Controller_Response_Http $httpResponse
     * @return Zend_Feed_Pubsubhubbub_CallbackAbstract
     */
    public function setHttpResponse($httpResponse)
    {
        if (!is_object($httpResponse)
            || (!$httpResponse instanceof Zend_Feed_Pubsubhubbub_HttpResponse
                && !$httpResponse instanceof Zend_Controller_Response_Http)
        ) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('HTTP Response object must'
                . ' implement one of Zend_Feed_Pubsubhubbub_HttpResponse or'
                . ' Zend_Controller_Response_Http');
        }
        $this->_httpResponse = $httpResponse;
        return $this;
    }

    /**
     * An instance of a class handling Http Responses. This is implemented in
     * Zend_Feed_Pubsubhubbub_HttpResponse which shares an unenforced interface with
     * (i.e. not inherited from) Zend_Controller_Response_Http.
     *
     * @return Zend_Feed_Pubsubhubbub_HttpResponse|Zend_Controller_Response_Http
     */
    public function getHttpResponse()
    {
        if ($this->_httpResponse === null) {
            $this->_httpResponse = new Zend_Feed_Pubsubhubbub_HttpResponse;
        }
        return $this->_httpResponse;
    }

    /**
     * Sets the number of Subscribers for which any updates are on behalf of.
     * In other words, is this class serving one or more subscribers? How many?
     * Defaults to 1 if left unchanged.
     *
     * @param  string|int $count
     * @return Zend_Feed_Pubsubhubbub_CallbackAbstract
     */
    public function setSubscriberCount($count)
    {
        $count = intval($count);
        if ($count <= 0) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Subscriber count must be'
                . ' greater than zero');
        }
        $this->_subscriberCount = $count;
        return $this;
    }

    /**
     * Gets the number of Subscribers for which any updates are on behalf of.
     * In other words, is this class serving one or more subscribers? How many?
     *
     * @return int
     */
    public function getSubscriberCount()
    {
        return $this->_subscriberCount;
    }

    /**
     * Attempt to detect the callback URL (specifically the path forward)
     */
    protected function _detectCallbackUrl()
    {
        $callbackUrl = '';
        if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
            $callbackUrl = $_SERVER['HTTP_X_REWRITE_URL'];
        } elseif (isset($_SERVER['REQUEST_URI'])) {
            $callbackUrl = $_SERVER['REQUEST_URI'];
            $scheme = 'http';
            if ($_SERVER['HTTPS'] == 'on') {
                $scheme = 'https';
            }
            $schemeAndHttpHost = $scheme . '://' . $this->_getHttpHost();
            if (strpos($callbackUrl, $schemeAndHttpHost) === 0) {
                $callbackUrl = substr($callbackUrl, strlen($schemeAndHttpHost));
            }
        } elseif (isset($_SERVER['ORIG_PATH_INFO'])) {
            $callbackUrl= $_SERVER['ORIG_PATH_INFO'];
            if (!empty($_SERVER['QUERY_STRING'])) {
                $callbackUrl .= '?' . $_SERVER['QUERY_STRING'];
            }
        }
        return $callbackUrl;
    }

    /**
     * Get the HTTP host
     *
     * @return string
     */
    protected function _getHttpHost()
    {
        if (!empty($_SERVER['HTTP_HOST'])) {
            return $_SERVER['HTTP_HOST'];
        }
        $scheme = 'http';
        if ($_SERVER['HTTPS'] == 'on') {
            $scheme = 'https';
        }
        $name = $_SERVER['SERVER_NAME'];
        $port = $_SERVER['SERVER_PORT'];
        if (($scheme == 'http' && $port == 80)
            || ($scheme == 'https' && $port == 443)
        ) {
            return $name;
        } else {
            return $name . ':' . $port;
        }
    }

    /**
     * Retrieve a Header value from either $_SERVER or Apache
     *
     * @param string $header
     */
    protected function _getHeader($header)
    {
        $temp = strtoupper(str_replace('-', '_', $header));
        if (!empty($_SERVER[$temp])) {
            return $_SERVER[$temp];
        }
        $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
        if (!empty($_SERVER[$temp])) {
            return $_SERVER[$temp];
        }
        if (function_exists('apache_request_headers')) {
            $headers = apache_request_headers();
            if (!empty($headers[$header])) {
                return $headers[$header];
            }
        }
        return false;
    }

    /**
     * Return the raw body of the request
     *
     * @return string|false Raw body, or false if not present
     */
    protected function _getRawBody()
    {
        $body = file_get_contents('php://input');
        if (strlen(trim($body)) == 0 && isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
            $body = $GLOBALS['HTTP_RAW_POST_DATA'];
        }
        if (strlen(trim($body)) > 0) {
            return $body;
        }
        return false;
    }
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Subscriber.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Feed_Pubsubhubbub
 */
require_once 'Zend/Feed/Pubsubhubbub.php';

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

/**
 * @category   Zend
 * @package    Zend_Feed_Pubsubhubbub
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Pubsubhubbub_Subscriber
{
    /**
     * An array of URLs for all Hub Servers to subscribe/unsubscribe.
     *
     * @var array
     */
    protected $_hubUrls = array();

    /**
     * An array of optional parameters to be included in any
     * (un)subscribe requests.
     *
     * @var array
     */
    protected $_parameters = array();

    /**
     * The URL of the topic (Rss or Atom feed) which is the subject of
     * our current intent to subscribe to/unsubscribe from updates from
     * the currently configured Hub Servers.
     *
     * @var string
     */
    protected $_topicUrl = '';

    /**
     * The URL Hub Servers must use when communicating with this Subscriber
     *
     * @var string
     */
    protected $_callbackUrl = '';

    /**
     * The number of seconds for which the subscriber would like to have the
     * subscription active. Defaults to null, i.e. not sent, to setup a
     * permanent subscription if possible.
     *
     * @var int
     */
    protected $_leaseSeconds = null;

    /**
     * The preferred verification mode (sync or async). By default, this
     * Subscriber prefers synchronous verification, but is considered
     * desireable to support asynchronous verification if possible.
     *
     * Zend_Feed_Pubsubhubbub_Subscriber will always send both modes, whose
     * order of occurance in the parameter list determines this preference.
     *
     * @var string
     */
    protected $_preferredVerificationMode
        = Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_SYNC;

    /**
     * An array of any errors including keys for 'response', 'hubUrl'.
     * The response is the actual Zend_Http_Response object.
     *
     * @var array
     */
    protected $_errors = array();

    /**
     * An array of Hub Server URLs for Hubs operating at this time in
     * asynchronous verification mode.
     *
     * @var array
     */
    protected $_asyncHubs = array();

    /**
     * An instance of Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface used to background
     * save any verification tokens associated with a subscription or other.
     *
     * @var Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface
     */
    protected $_storage = null;

    /**
     * An array of authentication credentials for HTTP Basic Authentication
     * if required by specific Hubs. The array is indexed by Hub Endpoint URI
     * and the value is a simple array of the username and password to apply.
     *
     * @var array
     */
    protected $_authentications = array();

    /**
     * Tells the Subscriber to append any subscription identifier to the path
     * of the base Callback URL. E.g. an identifier "subkey1" would be added
     * to the callback URL "http://www.example.com/callback" to create a subscription
     * specific Callback URL of "http://www.example.com/callback/subkey1".
     *
     * This is required for all Hubs using the Pubsubhubbub 0.1 Specification.
     * It should be manually intercepted and passed to the Callback class using
     * Zend_Feed_Pubsubhubbub_Subscriber_Callback::setSubscriptionKey(). Will
     * require a route in the form "callback/:subkey" to allow the parameter be
     * retrieved from an action using the Zend_Controller_Action::_getParam()
     * method.
     *
     * @var string
     */
    protected $_usePathParameter = false;

    /**
     * Constructor; accepts an array or Zend_Config instance to preset
     * options for the Subscriber without calling all supported setter
     * methods in turn.
     *
     * @param  array|Zend_Config $options Options array or Zend_Config instance
     * @return void
     */
    public function __construct($config = null)
    {
        if ($config !== null) {
            $this->setConfig($config);
        }
    }

    /**
     * Process any injected configuration options
     *
     * @param  array|Zend_Config $options Options array or Zend_Config instance
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function setConfig($config)
    {
        if ($config instanceof Zend_Config) {
            $config = $config->toArray();
        } elseif (!is_array($config)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Array or Zend_Config object'
                . ' expected, got ' . gettype($config));
        }
        if (array_key_exists('hubUrls', $config)) {
            $this->addHubUrls($config['hubUrls']);
        }
        if (array_key_exists('callbackUrl', $config)) {
            $this->setCallbackUrl($config['callbackUrl']);
        }
        if (array_key_exists('topicUrl', $config)) {
            $this->setTopicUrl($config['topicUrl']);
        }
        if (array_key_exists('storage', $config)) {
            $this->setStorage($config['storage']);
        }
        if (array_key_exists('leaseSeconds', $config)) {
            $this->setLeaseSeconds($config['leaseSeconds']);
        }
        if (array_key_exists('parameters', $config)) {
            $this->setParameters($config['parameters']);
        }
        if (array_key_exists('authentications', $config)) {
            $this->addAuthentications($config['authentications']);
        }
        if (array_key_exists('usePathParameter', $config)) {
            $this->usePathParameter($config['usePathParameter']);
        }
        if (array_key_exists('preferredVerificationMode', $config)) {
            $this->setPreferredVerificationMode(
                $config['preferredVerificationMode']
            );
        }
        return $this;
    }

    /**
     * Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe
     * event will relate
     *
     * @param  string $url
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function setTopicUrl($url)
    {
        if (empty($url) || !is_string($url) || !Zend_Uri::check($url)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid parameter "url"'
                .' of "' . $url . '" must be a non-empty string and a valid'
                .' URL');
        }
        $this->_topicUrl = $url;
        return $this;
    }

    /**
     * Set the topic URL (RSS or Atom feed) to which the intended (un)subscribe
     * event will relate
     *
     * @return string
     */
    public function getTopicUrl()
    {
        if (empty($this->_topicUrl)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('A valid Topic (RSS or Atom'
                . ' feed) URL MUST be set before attempting any operation');
        }
        return $this->_topicUrl;
    }

    /**
     * Set the number of seconds for which any subscription will remain valid
     *
     * @param  int $seconds
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function setLeaseSeconds($seconds)
    {
        $seconds = intval($seconds);
        if ($seconds <= 0) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Expected lease seconds'
                . ' must be an integer greater than zero');
        }
        $this->_leaseSeconds = $seconds;
        return $this;
    }

    /**
     * Get the number of lease seconds on subscriptions
     *
     * @return int
     */
    public function getLeaseSeconds()
    {
        return $this->_leaseSeconds;
    }

    /**
     * Set the callback URL to be used by Hub Servers when communicating with
     * this Subscriber
     *
     * @param  string $url
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function setCallbackUrl($url)
    {
        if (empty($url) || !is_string($url) || !Zend_Uri::check($url)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid parameter "url"'
                . ' of "' . $url . '" must be a non-empty string and a valid'
                . ' URL');
        }
        $this->_callbackUrl = $url;
        return $this;
    }

    /**
     * Get the callback URL to be used by Hub Servers when communicating with
     * this Subscriber
     *
     * @return string
     */
    public function getCallbackUrl()
    {
        if (empty($this->_callbackUrl)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('A valid Callback URL MUST be'
                . ' set before attempting any operation');
        }
        return $this->_callbackUrl;
    }

    /**
     * Set preferred verification mode (sync or async). By default, this
     * Subscriber prefers synchronous verification, but does support
     * asynchronous if that's the Hub Server's utilised mode.
     *
     * Zend_Feed_Pubsubhubbub_Subscriber will always send both modes, whose
     * order of occurance in the parameter list determines this preference.
     *
     * @param  string $mode Should be 'sync' or 'async'
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function setPreferredVerificationMode($mode)
    {
        if ($mode !== Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_SYNC
        && $mode !== Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_ASYNC) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid preferred'
                . ' mode specified: "' . $mode . '" but should be one of'
                . ' Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_SYNC or'
                . ' Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_ASYNC');
        }
        $this->_preferredVerificationMode = $mode;
        return $this;
    }

    /**
     * Get preferred verification mode (sync or async).
     *
     * @return string
     */
    public function getPreferredVerificationMode()
    {
        return $this->_preferredVerificationMode;
    }

    /**
     * Add a Hub Server URL supported by Publisher
     *
     * @param  string $url
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function addHubUrl($url)
    {
        if (empty($url) || !is_string($url) || !Zend_Uri::check($url)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid parameter "url"'
                . ' of "' . $url . '" must be a non-empty string and a valid'
                . ' URL');
        }
        $this->_hubUrls[] = $url;
        return $this;
    }

    /**
     * Add an array of Hub Server URLs supported by Publisher
     *
     * @param  array $urls
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function addHubUrls(array $urls)
    {
        foreach ($urls as $url) {
            $this->addHubUrl($url);
        }
        return $this;
    }

    /**
     * Remove a Hub Server URL
     *
     * @param  string $url
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function removeHubUrl($url)
    {
        if (!in_array($url, $this->getHubUrls())) {
            return $this;
        }
        $key = array_search($url, $this->_hubUrls);
        unset($this->_hubUrls[$key]);
        return $this;
    }

    /**
     * Return an array of unique Hub Server URLs currently available
     *
     * @return array
     */
    public function getHubUrls()
    {
        $this->_hubUrls = array_unique($this->_hubUrls);
        return $this->_hubUrls;
    }

    /**
     * Add authentication credentials for a given URL
     *
     * @param  string $url
     * @param  array $authentication
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function addAuthentication($url, array $authentication)
    {
        if (empty($url) || !is_string($url) || !Zend_Uri::check($url)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid parameter "url"'
                . ' of "' . $url . '" must be a non-empty string and a valid'
                . ' URL');
        }
        $this->_authentications[$url] = $authentication;
        return $this;
    }

    /**
     * Add authentication credentials for hub URLs
     *
     * @param  array $authentications
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function addAuthentications(array $authentications)
    {
        foreach ($authentications as $url => $authentication) {
            $this->addAuthentication($url, $authentication);
        }
        return $this;
    }

    /**
     * Get all hub URL authentication credentials
     *
     * @return array
     */
    public function getAuthentications()
    {
        return $this->_authentications;
    }

    /**
     * Set flag indicating whether or not to use a path parameter
     *
     * @param  bool $bool
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function usePathParameter($bool = true)
    {
        $this->_usePathParameter = $bool;
        return $this;
    }

    /**
     * Add an optional parameter to the (un)subscribe requests
     *
     * @param  string $name
     * @param  string|null $value
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function setParameter($name, $value = null)
    {
        if (is_array($name)) {
            $this->setParameters($name);
            return $this;
        }
        if (empty($name) || !is_string($name)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid parameter "name"'
                . ' of "' . $name . '" must be a non-empty string');
        }
        if ($value === null) {
            $this->removeParameter($name);
            return $this;
        }
        if (empty($value) || (!is_string($value) && $value !== null)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid parameter "value"'
                . ' of "' . $value . '" must be a non-empty string');
        }
        $this->_parameters[$name] = $value;
        return $this;
    }

    /**
     * Add an optional parameter to the (un)subscribe requests
     *
     * @param  string $name
     * @param  string|null $value
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function setParameters(array $parameters)
    {
        foreach ($parameters as $name => $value) {
            $this->setParameter($name, $value);
        }
        return $this;
    }

    /**
     * Remove an optional parameter for the (un)subscribe requests
     *
     * @param  string $name
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function removeParameter($name)
    {
        if (empty($name) || !is_string($name)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid parameter "name"'
                . ' of "' . $name . '" must be a non-empty string');
        }
        if (array_key_exists($name, $this->_parameters)) {
            unset($this->_parameters[$name]);
        }
        return $this;
    }

    /**
     * Return an array of optional parameters for (un)subscribe requests
     *
     * @return array
     */
    public function getParameters()
    {
        return $this->_parameters;
    }

    /**
     * Sets an instance of Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface used to background
     * save any verification tokens associated with a subscription or other.
     *
     * @param  Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface $storage
     * @return Zend_Feed_Pubsubhubbub_Subscriber
     */
    public function setStorage(Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface $storage)
    {
        $this->_storage = $storage;
        return $this;
    }

    /**
     * Gets an instance of Zend_Feed_Pubsubhubbub_Storage_StorageInterface used
     * to background save any verification tokens associated with a subscription
     * or other.
     *
     * @return Zend_Feed_Pubsubhubbub_Model_SubscriptionInterface
     */
    public function getStorage()
    {
        if ($this->_storage === null) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('No storage vehicle '
                . 'has been set.');
        }
        return $this->_storage;
    }

    /**
     * Subscribe to one or more Hub Servers using the stored Hub URLs
     * for the given Topic URL (RSS or Atom feed)
     *
     * @return void
     */
    public function subscribeAll()
    {
        return $this->_doRequest('subscribe');
    }

    /**
     * Unsubscribe from one or more Hub Servers using the stored Hub URLs
     * for the given Topic URL (RSS or Atom feed)
     *
     * @return void
     */
    public function unsubscribeAll()
    {
        return $this->_doRequest('unsubscribe');
    }

    /**
     * Returns a boolean indicator of whether the notifications to Hub
     * Servers were ALL successful. If even one failed, FALSE is returned.
     *
     * @return bool
     */
    public function isSuccess()
    {
        if (count($this->_errors) > 0) {
            return false;
        }
        return true;
    }

    /**
     * Return an array of errors met from any failures, including keys:
     * 'response' => the Zend_Http_Response object from the failure
     * 'hubUrl' => the URL of the Hub Server whose notification failed
     *
     * @return array
     */
    public function getErrors()
    {
        return $this->_errors;
    }

    /**
     * Return an array of Hub Server URLs who returned a response indicating
     * operation in Asynchronous Verification Mode, i.e. they will not confirm
     * any (un)subscription immediately but at a later time (Hubs may be
     * doing this as a batch process when load balancing)
     *
     * @return array
     */
    public function getAsyncHubs()
    {
        return $this->_asyncHubs;
    }

    /**
     * Executes an (un)subscribe request
     *
     * @param  string $mode
     * @return void
     */
    protected function _doRequest($mode)
    {
        $client = $this->_getHttpClient();
        $hubs   = $this->getHubUrls();
        if (empty($hubs)) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('No Hub Server URLs'
                . ' have been set so no subscriptions can be attempted');
        }
        $this->_errors = array();
        $this->_asyncHubs = array();
        foreach ($hubs as $url) {
            if (array_key_exists($url, $this->_authentications)) {
                $auth = $this->_authentications[$url];
                $client->setAuth($auth[0], $auth[1]);
            }
            $client->setUri($url);
            $client->setRawData(
                $this->_getRequestParameters($url, $mode),
                'application/x-www-form-urlencoded'
            );
            $response = $client->request();
            if ($response->getStatus() !== 204
                && $response->getStatus() !== 202
            ) {
                $this->_errors[] = array(
                    'response' => $response,
                    'hubUrl'   => $url,
                );
            /**
             * At first I thought it was needed, but the backend storage will
             * allow tracking async without any user interference. It's left
             * here in case the user is interested in knowing what Hubs
             * are using async verification modes so they may update Models and
             * move these to asynchronous processes.
             */
            } elseif ($response->getStatus() == 202) {
                $this->_asyncHubs[] = array(
                    'response' => $response,
                    'hubUrl'   => $url,
                );
            }
        }
    }

    /**
     * Get a basic prepared HTTP client for use
     *
     * @param  string $mode Must be "subscribe" or "unsubscribe"
     * @return Zend_Http_Client
     */
    protected function _getHttpClient()
    {
        $client = Zend_Feed_Pubsubhubbub::getHttpClient();
        $client->setMethod(Zend_Http_Client::POST);
        $client->setConfig(array('useragent' => 'Zend_Feed_Pubsubhubbub_Subscriber/'
            . Zend_Version::VERSION));
        return $client;
    }

    /**
     * Return a list of standard protocol/optional parameters for addition to
     * client's POST body that are specific to the current Hub Server URL
     *
     * @param  string $hubUrl
     * @param  mode $hubUrl
     * @return string
     */
    protected function _getRequestParameters($hubUrl, $mode)
    {
        if (!in_array($mode, array('subscribe', 'unsubscribe'))) {
            require_once 'Zend/Feed/Pubsubhubbub/Exception.php';
            throw new Zend_Feed_Pubsubhubbub_Exception('Invalid mode specified: "'
                . $mode . '" which should have been "subscribe" or "unsubscribe"');
        }

        $params = array(
            'hub.mode'  => $mode,
            'hub.topic' => $this->getTopicUrl(),
        );

        if ($this->getPreferredVerificationMode()
                == Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_SYNC
        ) {
            $vmodes = array(
                Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_SYNC,
                Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_ASYNC,
            );
        } else {
            $vmodes = array(
                Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_ASYNC,
                Zend_Feed_Pubsubhubbub::VERIFICATION_MODE_SYNC,
            );
        }
        $params['hub.verify'] = array();
        foreach($vmodes as $vmode) {
            $params['hub.verify'][] = $vmode;
        }

        /**
         * Establish a persistent verify_token and attach key to callback
         * URL's path/querystring
         */
        $key   = $this->_generateSubscriptionKey($params, $hubUrl);
        $token = $this->_generateVerifyToken();
        $params['hub.verify_token'] = $token;

        // Note: query string only usable with PuSH 0.2 Hubs
        if (!$this->_usePathParameter) {
            $params['hub.callback'] = $this->getCallbackUrl()
                . '?xhub.subscription=' . Zend_Feed_Pubsubhubbub::urlencode($key);
        } else {
            $params['hub.callback'] = rtrim($this->getCallbackUrl(), '/')
                . '/' . Zend_Feed_Pubsubhubbub::urlencode($key);
        }
        if ($mode == 'subscribe' && $this->getLeaseSeconds() !== null) {
            $params['hub.lease_seconds'] = $this->getLeaseSeconds();
        }

        // hub.secret not currently supported
        $optParams = $this->getParameters();
        foreach ($optParams as $name => $value) {
            $params[$name] = $value;
        }

        // store subscription to storage
        $now = new Zend_Date;
        $expires = null;
        if (isset($params['hub.lease_seconds'])) {
            $expires = $now->add($params['hub.lease_seconds'], Zend_Date::SECOND)
                ->get('yyyy-MM-dd HH:mm:ss');
        }
        $data = array(
            'id'                 => $key,
            'topic_url'          => $params['hub.topic'],
            'hub_url'            => $hubUrl,
            'created_time'       => $now->get('yyyy-MM-dd HH:mm:ss'),
            'lease_seconds'      => $expires,
            'verify_token'       => hash('sha256', $params['hub.verify_token']),
            'secret'             => null,
            'expiration_time'    => $expires,
            'subscription_state' => Zend_Feed_Pubsubhubbub::SUBSCRIPTION_NOTVERIFIED,
        );
        $this->getStorage()->setSubscription($data);

        return $this->_toByteValueOrderedString(
            $this->_urlEncode($params)
        );
    }

    /**
     * Simple helper to generate a verification token used in (un)subscribe
     * requests to a Hub Server. Follows no particular method, which means
     * it might be improved/changed in future.
     *
     * @param  string $hubUrl The Hub Server URL for which this token will apply
     * @return string
     */
    protected function _generateVerifyToken()
    {
        if (!empty($this->_testStaticToken)) {
            return $this->_testStaticToken;
        }
        return uniqid(rand(), true) . time();
    }

    /**
     * Simple helper to generate a verification token used in (un)subscribe
     * requests to a Hub Server.
     *
     * @param  string $hubUrl The Hub Server URL for which this token will apply
     * @return string
     */
    protected function _generateSubscriptionKey(array $params, $hubUrl)
    {
        $keyBase = $params['hub.topic'] . $hubUrl;
        $key     = md5($keyBase);
        return $key;
    }

    /**
     * URL Encode an array of parameters
     *
     * @param  array $params
     * @return array
     */
    protected function _urlEncode(array $params)
    {
        $encoded = array();
        foreach ($params as $key => $value) {
            if (is_array($value)) {
                $ekey = Zend_Feed_Pubsubhubbub::urlencode($key);
                $encoded[$ekey] = array();
                foreach ($value as $duplicateKey) {
                    $encoded[$ekey][]
                        = Zend_Feed_Pubsubhubbub::urlencode($duplicateKey);
                }
            } else {
                $encoded[Zend_Feed_Pubsubhubbub::urlencode($key)]
                    = Zend_Feed_Pubsubhubbub::urlencode($value);
            }
        }
        return $encoded;
    }

    /**
     * Order outgoing parameters
     *
     * @param  array $params
     * @return array
     */
    protected function _toByteValueOrderedString(array $params)
    {
        $return = array();
        uksort($params, 'strnatcmp');
        foreach ($params as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $keyduplicate) {
                    $return[] = $key . '=' . $keyduplicate;
                }
            } else {
                $return[] = $key . '=' . $value;
            }
        }
        return implode('&', $return);
    }

    /**
     * This is STRICTLY for testing purposes only...
     */
    protected $_testStaticToken = null;

    final public function setTestStaticToken($token)
    {
        $this->_testStaticToken = (string) $token;
    }
}