?
Current File : /home/c/i/d/cideo/www/wp-includesVIp/js/crop/images/Zend.tar
Form/SubForm.php000066600000003372151256604600007553 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Form */
require_once 'Zend/Form.php';

/**
 * Zend_Form_SubForm
 * 
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SubForm.php 8585 2008-03-06 19:32:34Z matthew $
 */
class Zend_Form_SubForm extends Zend_Form
{
    /**
     * Whether or not form elements are members of an array
     * @var bool
     */
    protected $_isArray = true;

    /**
     * Load the default decorators
     * 
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }

        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('FormElements')
                 ->addDecorator('HtmlTag', array('tag' => 'dl'))
                 ->addDecorator('Fieldset')
                 ->addDecorator('DtDdWrapper');
        }
    }
}
Form/Decorator/Captcha/Word.php000066600000004426151256604600012377 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Decorator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Form_Decorator_Abstract */
require_once 'Zend/Form/Decorator/Abstract.php';

/**
 * Word-based captcha decorator
 * 
 * Adds hidden field for ID and text input field for captcha text
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */
class Zend_Form_Decorator_Captcha_Word extends Zend_Form_Decorator_Abstract
{
    /**
     * Render captcha
     * 
     * @param  string $content 
     * @return string
     */
    public function render($content)
    {
        $element = $this->getElement();
        $view    = $element->getView();
        if (null === $view) {
            return $content;
        }

        $name = $element->getFullyQualifiedName();

        $hiddenName = $name . '[id]';
        $textName   = $name . '[input]';

        $placement = $this->getPlacement();
        $separator = $this->getSeparator();

        $hidden = $view->formHidden($hiddenName, $element->getValue(), $element->getAttribs());
        $text   = $view->formText($textName, '', $element->getAttribs());
        switch ($placement) {
            case 'PREPEND':
                $content = $hidden . $separator . $text . $separator . $content;
                break;
            case 'APPEND':
            default:
                $content = $content . $separator . $hidden . $separator . $text;
        }
        return $content;
    }
}
Form/Exception.php000066600000002200151256604600010121 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

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

/**
 * Exception for Zend_Form component.
 *
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Form_Exception extends Zend_Exception
{
}
Form/Element/Submit.php000066600000006210151256604600011024 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Form_Element_Xhtml */
require_once 'Zend/Form/Element/Xhtml.php';

/**
 * Submit form element
 * 
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Submit.php 8585 2008-03-06 19:32:34Z matthew $
 */
class Zend_Form_Element_Submit extends Zend_Form_Element_Xhtml
{
    /**
     * Default view helper to use
     * @var string
     */
    public $helper = 'formSubmit';

    /**
     * Constructor
     * 
     * @param  string|array|Zend_Config $spec Element name or configuration
     * @param  string|array|Zend_Config $options Element value or configuration
     * @return void
     */
    public function __construct($spec, $options = null)
    {
        if (is_string($spec) && ((null !== $options) && is_string($options))) {
            $options = array('label' => $options);
        }

        parent::__construct($spec, $options);
    }

    /**
     * Return label
     *
     * If no label is present, returns the currently set name.
     *
     * If a translator is present, returns the translated label.
     * 
     * @return string
     */
    public function getLabel()
    {
        $value = parent::getLabel();

        if (null === $value) {
            $value = $this->getName();
        }

        if (null !== ($translator = $this->getTranslator())) {
            return $translator->translate($value);
        }

        return $value;
    }

    /**
     * Has this submit button been selected?
     * 
     * @return bool
     */
    public function isChecked()
    {
        $value = $this->getValue();

        if (empty($value)) {
            return false;
        }
        if ($value != $this->getLabel()) {
            return false;
        }

        return true;
    }

    /**
     * Default decorators
     *
     * Uses only 'Submit' and 'DtDdWrapper' decorators by default.
     * 
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }

        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('ViewHelper')
                 ->addDecorator('DtDdWrapper');
        }
    }
}
Form/Element/Hash.php000066600000014003151256604600010443 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Form_Element_Xhtml */
require_once 'Zend/Form/Element/Xhtml.php';

/**
 * CSRF form protection
 * 
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Hash.php 11332 2008-09-10 16:35:45Z matthew $
 */
class Zend_Form_Element_Hash extends Zend_Form_Element_Xhtml
{
    /**
     * Use formHidden view helper by default
     * @var string
     */
    public $helper = 'formHidden';

    /**
     * Actual hash used.
     * 
     * @var mixed
     */
    protected $_hash;

    /**
     * Salt for CSRF token
     * @var string
     */
    protected $_salt = 'salt';

    /**
     * @var Zend_Session_Namespace
     */
    protected $_session;

    /**
     * TTL for CSRF token
     * @var int
     */
    protected $_timeout = 300;

    /**
     * Constructor
     *
     * Creates session namespace for CSRF token, and adds validator for CSRF 
     * token.
     * 
     * @param  string|array|Zend_Config $spec 
     * @param  array|Zend_Config $options 
     * @return void
     */
    public function __construct($spec, $options = null)
    {
        parent::__construct($spec, $options);

        $this->setAllowEmpty(false)
             ->setRequired(true)
             ->initCsrfValidator();
    }

    /**
     * Set session object
     * 
     * @param  Zend_Session_Namespace $session 
     * @return Zend_Form_Element_Hash
     */
    public function setSession($session)
    {
        $this->_session = $session;
        return $this;
    }

    /**
     * Get session object
     *
     * Instantiate session object if none currently exists
     * 
     * @return Zend_Session_Namespace
     */
    public function getSession()
    {
        if (null === $this->_session) {
            require_once 'Zend/Session/Namespace.php';
            $this->_session = new Zend_Session_Namespace($this->getSessionName());
        }
        return $this->_session;
    }

    /**
     * Initialize CSRF validator
     *
     * Creates Session namespace, and initializes CSRF token in session. 
     * Additionally, adds validator for validating CSRF token.
     * 
     * @return Zend_Form_Element_Hash
     */
    public function initCsrfValidator()
    {
        $session = $this->getSession();
        if (isset($session->hash)) {
            $rightHash = $session->hash;
        } else {
            $rightHash = null;
        }

        $this->addValidator('Identical', true, array($rightHash));
        return $this;
    }

    /**
     * Salt for CSRF token
     *
     * @param  string $salt
     * @return Zend_Form_Element_Hash
     */
    public function setSalt($salt)
    {
        $this->_salt = (string) $salt;
        return $this;
    }

    /**
     * Retrieve salt for CSRF token
     *
     * @return string
     */
    public function getSalt()
    {
        return $this->_salt;
    }

    /**
     * Retrieve CSRF token
     *
     * If no CSRF token currently exists, generates one.
     * 
     * @return string
     */
    public function getHash()
    {
        if (null === $this->_hash) {
            $this->_generateHash();
        }
        return $this->_hash;
    }

    /**
     * Get session namespace for CSRF token
     *
     * Generates a session namespace based on salt, element name, and class.
     * 
     * @return string
     */
    public function getSessionName()
    {
        return __CLASS__ . '_' . $this->getSalt() . '_' . $this->getName();
    }

    /**
     * Set timeout for CSRF session token
     * 
     * @param  int $ttl 
     * @return Zend_Form_Element_Hash
     */
    public function setTimeout($ttl)
    {
        $this->_timeout = (int) $ttl;
        return $this;
    }

    /**
     * Get CSRF session token timeout
     * 
     * @return int
     */
    public function getTimeout()
    {
        return $this->_timeout;
    }

    /**
     * Override getLabel() to always be empty
     * 
     * @return null
     */
    public function getLabel()
    {
        return null;
    }

    /**
     * Initialize CSRF token in session
     * 
     * @return void
     */
    public function initCsrfToken()
    {
        $session = $this->getSession();
        $session->setExpirationHops(1, null, true);
        $session->setExpirationSeconds($this->getTimeout());
        $session->hash = $this->getHash();
    }

    /**
     * Render CSRF token in form
     * 
     * @param  Zend_View_Interface $view 
     * @return string
     */
    public function render(Zend_View_Interface $view = null)
    {
        $this->initCsrfToken();
        return parent::render($view);
    }

    /**
     * Generate CSRF token
     *
     * Generates CSRF token and stores both in {@link $_hash} and element 
     * value.
     * 
     * @return void
     */
    protected function _generateHash()
    {
        $this->_hash = md5(
            mt_rand(1,1000000) 
            .  $this->getSalt() 
            .  $this->getName() 
            .  mt_rand(1,1000000)
        );
        $this->setValue($this->_hash);
    }
}
Form/Element/Textarea.php000066600000002501151256604600011335 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Form_Element_Xhtml */
require_once 'Zend/Form/Element/Xhtml.php';

/**
 * Textarea form element
 * 
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Textarea.php 8064 2008-02-16 10:58:39Z thomas $
 */
class Zend_Form_Element_Textarea extends Zend_Form_Element_Xhtml
{
    /**
     * Use formTextarea view helper by default
     * @var string
     */
    public $helper = 'formTextarea';
}
Form/Element.php000066600000165612151256604600007575 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Filter */
require_once 'Zend/Filter.php';

/** Zend_Validate_Interface */
require_once 'Zend/Validate/Interface.php';

/**
 * Zend_Form_Element 
 * 
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Element.php 12787 2008-11-23 14:17:44Z matthew $
 */
class Zend_Form_Element implements Zend_Validate_Interface
{
    /**
     * Element Constants
     */
    const DECORATOR = 'DECORATOR';
    const FILTER    = 'FILTER';
    const VALIDATE  = 'VALIDATE';

    /**
     * Default view helper to use
     * @var string
     */
    public $helper = 'formText';

    /**
     * 'Allow empty' flag
     * @var bool
     */
    protected $_allowEmpty = true;

    /**
     * Flag indicating whether or not to insert NotEmpty validator when element is required
     * @var bool
     */
    protected $_autoInsertNotEmptyValidator = true;

    /**
     * Array to which element belongs
     * @var string
     */
    protected $_belongsTo;

    /**
     * Element decorators 
     * @var array
     */
    protected $_decorators = array();

    /**
     * Element description
     * @var string
     */
    protected $_description;

    /**
     * Should we disable loading the default decorators?
     * @var bool
     */
    protected $_disableLoadDefaultDecorators = false;

    /**
     * Custom error messages
     * @var array
     */
    protected $_errorMessages = array();

    /**
     * Validation errors
     * @var array
     */
    protected $_errors = array();

    /**
     * Element filters
     * @var array
     */
    protected $_filters = array();

    /**
     * Ignore flag (used when retrieving values at form level)
     * @var bool
     */
    protected $_ignore = false;

    /**
     * Does the element represent an array?
     * @var bool
     */
    protected $_isArray = false;

    /**
     * Is the error marked as in an invalid state?
     * @var bool
     */
    protected $_isError = false;

    /**
     * Element label
     * @var string
     */
    protected $_label;

    /**
     * Plugin loaders for filter and validator chains
     * @var array
     */
    protected $_loaders = array();

    /**
     * Formatted validation error messages
     * @var array
     */
    protected $_messages = array();

    /**
     * Element name
     * @var string
     */
    protected $_name;

    /**
     * Order of element
     * @var int
     */
    protected $_order;

    /**
     * Required flag
     * @var bool
     */
    protected $_required = false;

    /**
     * @var Zend_Translate
     */
    protected $_translator;

    /**
     * Is translation disabled?
     * @var bool
     */
    protected $_translatorDisabled = false;

    /**
     * Element type
     * @var string
     */
    protected $_type;

    /**
     * Array of initialized validators
     * @var array Validators
     */
    protected $_validators = array();

    /**
     * Array of un-initialized validators
     * @var array
     */
    protected $_validatorRules = array();

    /**
     * Element value
     * @var mixed
     */
    protected $_value;

    /**
     * @var Zend_View_Interface
     */
    protected $_view;

    /**
     * Constructor
     *
     * $spec may be:
     * - string: name of element
     * - array: options with which to configure element
     * - Zend_Config: Zend_Config with options for configuring element
     * 
     * @param  string|array|Zend_Config $spec 
     * @return void
     * @throws Zend_Form_Exception if no element name after initialization
     */
    public function __construct($spec, $options = null)
    {
        if (is_string($spec)) {
            $this->setName($spec);
        } elseif (is_array($spec)) {
            $this->setOptions($spec);
        } elseif ($spec instanceof Zend_Config) {
            $this->setConfig($spec);
        } 
        
        if (is_string($spec) && is_array($options)) {
            $this->setOptions($options);
        } elseif (is_string($spec) && ($options instanceof Zend_Config)) {
            $this->setConfig($options);
        }

        if (null === $this->getName()) {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception('Zend_Form_Element requires each element to have a name');
        }

        /**
         * Extensions
         */
        $this->init();

        /**
         * Register ViewHelper decorator by default
         */
        $this->loadDefaultDecorators();
    }

    /**
     * Initialize object; used by extending classes
     * 
     * @return void
     */
    public function init()
    {
    }

    /**
     * Set flag to disable loading default decorators
     * 
     * @param  bool $flag 
     * @return Zend_Form_Element
     */
    public function setDisableLoadDefaultDecorators($flag)
    {
        $this->_disableLoadDefaultDecorators = (bool) $flag;
        return $this;
    }

    /**
     * Should we load the default decorators?
     * 
     * @return bool
     */
    public function loadDefaultDecoratorsIsDisabled()
    {
        return $this->_disableLoadDefaultDecorators;
    }

    /**
     * Load default decorators
     * 
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }

        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('ViewHelper')
                ->addDecorator('Errors')
                ->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
                ->addDecorator('HtmlTag', array('tag' => 'dd'))
                ->addDecorator('Label', array('tag' => 'dt'));
        }
    }

    /**
     * Set object state from options array
     * 
     * @param  array $options 
     * @return Zend_Form_Element
     */
    public function setOptions(array $options)
    {
        if (isset($options['prefixPath'])) {
            $this->addPrefixPaths($options['prefixPath']);
            unset($options['prefixPath']);
        }

        if (isset($options['disableTranslator'])) {
            $this->setDisableTranslator($options['disableTranslator']);
            unset($options['disableTranslator']);
        }

        unset($options['options']);
        unset($options['config']);

        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);

            if (in_array($method, array('setTranslator', 'setPluginLoader', 'setView'))) {
                if (!is_object($value)) {
                    continue;
                }
            }

            if (method_exists($this, $method)) {
                // Setter exists; use it
                $this->$method($value);
            } else {
                // Assume it's metadata
                $this->setAttrib($key, $value);
            }
        }
        return $this;
    }

    /**
     * Set object state from Zend_Config object
     * 
     * @param  Zend_Config $config 
     * @return Zend_Form_Element
     */
    public function setConfig(Zend_Config $config)
    {
        return $this->setOptions($config->toArray());
    }


    // Localization:

    /**
     * Set translator object for localization
     * 
     * @param  Zend_Translate|null $translator 
     * @return Zend_Form_Element
     */
    public function setTranslator($translator = null)
    {
        if (null === $translator) {
            $this->_translator = null;
        } elseif ($translator instanceof Zend_Translate_Adapter) {
            $this->_translator = $translator;
        } elseif ($translator instanceof Zend_Translate) {
            $this->_translator = $translator->getAdapter();
        } else {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception('Invalid translator specified');
        }
        return $this;
    }

    /**
     * Retrieve localization translator object
     * 
     * @return Zend_Translate_Adapter|null
     */
    public function getTranslator()
    {
        if ($this->translatorIsDisabled()) {
            return null;
        }

        if (null === $this->_translator) {
            require_once 'Zend/Form.php';
            return Zend_Form::getDefaultTranslator();
        }
        return $this->_translator;
    }

    /**
     * Indicate whether or not translation should be disabled
     * 
     * @param  bool $flag 
     * @return Zend_Form_Element
     */
    public function setDisableTranslator($flag)
    {
        $this->_translatorDisabled = (bool) $flag;
        return $this;
    }

    /**
     * Is translation disabled?
     * 
     * @return bool
     */
    public function translatorIsDisabled()
    {
        return $this->_translatorDisabled;
    }

    // Metadata

    /**
     * Filter a name to only allow valid variable characters
     * 
     * @param  string $value 
     * @param  bool $allowBrackets
     * @return string
     */
    public function filterName($value, $allowBrackets = false)
    {
        $charset = '^a-zA-Z0-9_\x7f-\xff';
        if ($allowBrackets) {
            $charset .= '\[\]';
        }
        return preg_replace('/[' . $charset . ']/', '', (string) $value);
    }

    /**
     * Set element name
     * 
     * @param  string $name 
     * @return Zend_Form_Element
     */
    public function setName($name)
    {
        $name = $this->filterName($name);
        if ('' === $name) {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception('Invalid name provided; must contain only valid variable characters and be non-empty');
        }

        $this->_name = $name;
        return $this;
    }

    /**
     * Return element name
     * 
     * @return string
     */
    public function getName()
    {
        return $this->_name;
    }

    /**
     * Get fully qualified name
     *
     * Places name as subitem of array and/or appends brackets.
     * 
     * @return string
     */
    public function getFullyQualifiedName()
    {
        $name = $this->getName();

        if (null !== ($belongsTo = $this->getBelongsTo())) {
            $name = $belongsTo . '[' . $name . ']';
        }

        if ($this->isArray()) {
            $name .= '[]';
        }

        return $name;
    }

    /**
     * Get element id
     * 
     * @return string
     */
    public function getId()
    {
        if (isset($this->id)) {
            return $this->id;
        }

        $id = $this->getFullyQualifiedName();

        // Bail early if no array notation detected
        if (!strstr($id, '[')) {
            return $id;
        }

        // Strip array notation
        if ('[]' == substr($id, -2)) {
            $id = substr($id, 0, strlen($id) - 2);
        }
        $id = str_replace('][', '-', $id);
        $id = str_replace(array(']', '['), '-', $id);
        $id = trim($id, '-');

        return $id;
    }

    /**
     * Set element value
     * 
     * @param  mixed $value 
     * @return Zend_Form_Element
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }

    /**
     * Filter a value
     * 
     * @param  string $value 
     * @param  string $key 
     * @return void
     */
    protected function _filterValue(&$value, &$key)
    {
        foreach ($this->getFilters() as $filter) {
            $value = $filter->filter($value);
        }
    }

    /**
     * Retrieve filtered element value
     * 
     * @return mixed
     */
    public function getValue()
    {
        $valueFiltered = $this->_value;

        if ($this->isArray() && is_array($valueFiltered)) {
            array_walk_recursive($valueFiltered, array($this, '_filterValue'));
        } else {
            $this->_filterValue($valueFiltered, $valueFiltered);
        }

        return $valueFiltered;
    }

    /**
     * Retrieve unfiltered element value
     * 
     * @return mixed
     */
    public function getUnfilteredValue()
    {
        return $this->_value;
    }

    /**
     * Set element label
     * 
     * @param  string $label 
     * @return Zend_Form_Element
     */
    public function setLabel($label)
    {
        $this->_label = (string) $label;
        return $this;
    }

    /**
     * Retrieve element label
     * 
     * @return string
     */
    public function getLabel()
    {
        return $this->_label;
    }

    /**
     * Set element order
     * 
     * @param  int $order 
     * @return Zend_Form_Element
     */
    public function setOrder($order)
    {
        $this->_order = (int) $order;
        return $this;
    }

    /**
     * Retrieve element order
     * 
     * @return int
     */
    public function getOrder()
    {
        return $this->_order;
    }

    /**
     * Set required flag
     * 
     * @param  bool $flag Default value is true
     * @return Zend_Form_Element
     */
    public function setRequired($flag = true)
    {
        $this->_required = (bool) $flag;
        return $this;
    }

    /**
     * Is the element required?
     * 
     * @return bool
     */
    public function isRequired()
    {
        return $this->_required;
    }

    /**
     * Set flag indicating whether a NotEmpty validator should be inserted when element is required
     * 
     * @param  bool $flag 
     * @return Zend_Form_Element
     */
    public function setAutoInsertNotEmptyValidator($flag)
    {
        $this->_autoInsertNotEmptyValidator = (bool) $flag;
        return $this;
    }

    /**
     * Get flag indicating whether a NotEmpty validator should be inserted when element is required
     * 
     * @return bool
     */
    public function autoInsertNotEmptyValidator()
    {
        return $this->_autoInsertNotEmptyValidator;
    }

    /**
     * Set element description
     * 
     * @param  string $description 
     * @return Zend_Form_Element
     */
    public function setDescription($description)
    {
        $this->_description = (string) $description;
        return $this;
    }

    /**
     * Retrieve element description
     * 
     * @return string
     */
    public function getDescription()
    {
        return $this->_description;
    }

    /**
     * Set 'allow empty' flag
     *
     * When the allow empty flag is enabled and the required flag is false, the
     * element will validate with empty values.
     * 
     * @param  bool $flag 
     * @return Zend_Form_Element
     */
    public function setAllowEmpty($flag)
    {
        $this->_allowEmpty = (bool) $flag;
        return $this;
    }

    /**
     * Get 'allow empty' flag
     * 
     * @return bool
     */
    public function getAllowEmpty()
    {
        return $this->_allowEmpty;
    }

    /**
     * Set ignore flag (used when retrieving values at form level)
     * 
     * @param  bool $flag 
     * @return Zend_Form_Element
     */
    public function setIgnore($flag)
    {
        $this->_ignore = (bool) $flag;
        return $this;
    }

    /**
     * Get ignore flag (used when retrieving values at form level)
     * 
     * @return bool
     */
    public function getIgnore()
    {
        return $this->_ignore;
    }

    /**
     * Set flag indicating if element represents an array
     * 
     * @param  bool $flag 
     * @return Zend_Form_Element
     */
    public function setIsArray($flag)
    {
        $this->_isArray = (bool) $flag;
        return $this;
    }

    /**
     * Is the element representing an array?
     * 
     * @return bool
     */
    public function isArray()
    {
        return $this->_isArray;
    }

    /**
     * Set array to which element belongs
     * 
     * @param  string $array 
     * @return Zend_Form_Element
     */
    public function setBelongsTo($array)
    {
        $array = $this->filterName($array, true);
        if (!empty($array)) {
            $this->_belongsTo = $array;
        }

        return $this;
    }

    /**
     * Return array name to which element belongs
     * 
     * @return string
     */
    public function getBelongsTo()
    {
        return $this->_belongsTo;
    }

    /**
     * Return element type
     * 
     * @return string
     */
    public function getType()
    {
        if (null === $this->_type) {
            $this->_type = get_class($this);
        }

        return $this->_type;
    }

    /**
     * Set element attribute
     * 
     * @param  string $name 
     * @param  mixed $value 
     * @return Zend_Form_Element
     * @throws Zend_Form_Exception for invalid $name values
     */
    public function setAttrib($name, $value)
    {
        $name = (string) $name;
        if ('_' == $name[0]) {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception(sprintf('Invalid attribute "%s"; must not contain a leading underscore', $name));
        }

        if (null === $value) {
            unset($this->$name);
        } else {
            $this->$name = $value;
        }

        return $this;
    }

    /**
     * Set multiple attributes at once
     * 
     * @param  array $attribs 
     * @return Zend_Form_Element
     */
    public function setAttribs(array $attribs)
    {
        foreach ($attribs as $key => $value) {
            $this->setAttrib($key, $value);
        }

        return $this;
    }

    /**
     * Retrieve element attribute
     * 
     * @param  string $name 
     * @return string
     */
    public function getAttrib($name)
    {
        $name = (string) $name;
        if (isset($this->$name)) {
            return $this->$name;
        }

        return null;
    }

    /**
     * Return all attributes
     * 
     * @return array
     */
    public function getAttribs()
    {
        $attribs = get_object_vars($this);
        foreach ($attribs as $key => $value) {
            if ('_' == substr($key, 0, 1)) {
                unset($attribs[$key]);
            }
        }

        return $attribs;
    }

    /**
     * Overloading: retrieve object property
     *
     * Prevents access to properties beginning with '_'.
     * 
     * @param  string $key 
     * @return mixed
     */
    public function __get($key)
    {
        if ('_' == $key[0]) {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception(sprintf('Cannot retrieve value for protected/private property "%s"', $key));
        }

        if (!isset($this->$key)) {
            return null;
        }

        return $this->$key;
    }

    /**
     * Overloading: set object property
     *
     * @param  string $key
     * @param  mixed $value
     * @return voide
     */
    public function __set($key, $value)
    {
        $this->setAttrib($key, $value);
    }

    /**
     * Overloading: allow rendering specific decorators
     *
     * Call renderDecoratorName() to render a specific decorator.
     * 
     * @param  string $method 
     * @param  array $args 
     * @return string
     * @throws Zend_Form_Exception for invalid decorator or invalid method call
     */
    public function __call($method, $args)
    {
        if ('render' == substr($method, 0, 6)) {
            $decoratorName = substr($method, 6);
            if (false !== ($decorator = $this->getDecorator($decoratorName))) {
                $decorator->setElement($this);
                $seed = '';
                if (0 < count($args)) {
                    $seed = array_shift($args);
                }
                return $decorator->render($seed);
            }

            require_once 'Zend/Form/Element/Exception.php';
            throw new Zend_Form_Element_Exception(sprintf('Decorator by name %s does not exist', $decoratorName));
        }

        require_once 'Zend/Form/Element/Exception.php';
        throw new Zend_Form_Element_Exception(sprintf('Method %s does not exist', $method));
    }

    // Loaders

    /**
     * Set plugin loader to use for validator or filter chain
     * 
     * @param  Zend_Loader_PluginLoader_Interface $loader 
     * @param  string $type 'decorator', 'filter', or 'validate'
     * @return Zend_Form_Element
     * @throws Zend_Form_Exception on invalid type
     */
    public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type)
    {
        $type = strtoupper($type);
        switch ($type) {
            case self::DECORATOR:
            case self::FILTER:
            case self::VALIDATE:
                $this->_loaders[$type] = $loader;
                return $this;
            default:
                require_once 'Zend/Form/Exception.php';
                throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to setPluginLoader()', $type));
        }
    }

    /**
     * Retrieve plugin loader for validator or filter chain
     *
     * Instantiates with default rules if none available for that type. Use 
     * 'decorator', 'filter', or 'validate' for $type.
     * 
     * @param  string $type 
     * @return Zend_Loader_PluginLoader
     * @throws Zend_Loader_Exception on invalid type.
     */
    public function getPluginLoader($type)
    {
        $type = strtoupper($type);
        switch ($type) {
            case self::FILTER:
            case self::VALIDATE:
                $prefixSegment = ucfirst(strtolower($type));
                $pathSegment   = $prefixSegment;
            case self::DECORATOR:
                if (!isset($prefixSegment)) {
                    $prefixSegment = 'Form_Decorator';
                    $pathSegment   = 'Form/Decorator';
                }
                if (!isset($this->_loaders[$type])) {
                    require_once 'Zend/Loader/PluginLoader.php';
                    $this->_loaders[$type] = new Zend_Loader_PluginLoader(
                        array('Zend_' . $prefixSegment . '_' => 'Zend/' . $pathSegment . '/')
                    );
                }
                return $this->_loaders[$type];
            default:
                require_once 'Zend/Form/Exception.php';
                throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
        }
    }

    /**
     * Add prefix path for plugin loader
     *
     * If no $type specified, assumes it is a base path for both filters and 
     * validators, and sets each according to the following rules:
     * - decorators: $prefix = $prefix . '_Decorator'
     * - filters: $prefix = $prefix . '_Filter'
     * - validators: $prefix = $prefix . '_Validate'
     *
     * Otherwise, the path prefix is set on the appropriate plugin loader.
     * 
     * @param  string $path 
     * @return Zend_Form_Element
     * @throws Zend_Form_Exception for invalid type
     */
    public function addPrefixPath($prefix, $path, $type = null)
    {
        $type = strtoupper($type);
        switch ($type) {
            case self::DECORATOR:
            case self::FILTER:
            case self::VALIDATE:
                $loader = $this->getPluginLoader($type);
                $loader->addPrefixPath($prefix, $path);
                return $this;
            case null:
                $prefix = rtrim($prefix, '_');
                $path   = rtrim($path, DIRECTORY_SEPARATOR);
                foreach (array(self::DECORATOR, self::FILTER, self::VALIDATE) as $type) {
                    $cType        = ucfirst(strtolower($type));
                    $pluginPath   = $path . DIRECTORY_SEPARATOR . $cType . DIRECTORY_SEPARATOR;
                    $pluginPrefix = $prefix . '_' . $cType;
                    $loader       = $this->getPluginLoader($type);
                    $loader->addPrefixPath($pluginPrefix, $pluginPath);
                }
                return $this;
            default:
                require_once 'Zend/Form/Exception.php';
                throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
        }
    }

    /**
     * Add many prefix paths at once
     * 
     * @param  array $spec 
     * @return Zend_Form_Element
     */
    public function addPrefixPaths(array $spec)
    {
        if (isset($spec['prefix']) && isset($spec['path'])) {
            return $this->addPrefixPath($spec['prefix'], $spec['path']);
        } 
        foreach ($spec as $type => $paths) {
            if (is_numeric($type) && is_array($paths)) {
                $type = null;
                if (isset($paths['prefix']) && isset($paths['path'])) {
                    if (isset($paths['type'])) {
                        $type = $paths['type'];
                    }
                    $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
                }
            } elseif (!is_numeric($type)) {
                if (!isset($paths['prefix']) || !isset($paths['path'])) {
                    foreach ($paths as $prefix => $spec) {
                        if (is_array($spec)) {
                            foreach ($spec as $path) {
                                if (!is_string($path)) {
                                    continue;
                                }
                                $this->addPrefixPath($prefix, $path, $type);
                            }
                        } elseif (is_string($spec)) {
                            $this->addPrefixPath($prefix, $spec, $type);
                        }
                    }
                } else {
                    $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
                }
            }
        }
        return $this;
    }

    // Validation

    /**
     * Add validator to validation chain
     *
     * Note: will overwrite existing validators if they are of the same class.
     * 
     * @param  string|Zend_Validate_Interface $validator 
     * @param  bool $breakChainOnFailure
     * @param  array $options 
     * @return Zend_Form_Element
     * @throws Zend_Form_Exception if invalid validator type
     */
    public function addValidator($validator, $breakChainOnFailure = false, $options = array())
    {
        if ($validator instanceof Zend_Validate_Interface) {
            $name = get_class($validator);

            if (!isset($validator->zfBreakChainOnFailure)) {
                $validator->zfBreakChainOnFailure = $breakChainOnFailure;
            }
        } elseif (is_string($validator)) {
            $name      = $validator;
            $validator = array(
                'validator' => $validator,
                'breakChainOnFailure' => $breakChainOnFailure,
                'options'             => $options,
            );
        } else {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception('Invalid validator provided to addValidator; must be string or Zend_Validate_Interface');
        }


        $this->_validators[$name] = $validator;

        return $this;
    }

    /**
     * Add multiple validators
     * 
     * @param  array $validators 
     * @return Zend_Form_Element
     */
    public function addValidators(array $validators)
    {
        foreach ($validators as $validatorInfo) {
            if (is_string($validatorInfo)) {
                $this->addValidator($validatorInfo);
            } elseif ($validatorInfo instanceof Zend_Validate_Interface) {
                $this->addValidator($validatorInfo);
            } elseif (is_array($validatorInfo)) {
                $argc                = count($validatorInfo);
                $breakChainOnFailure = false;
                $options             = array();
                if (isset($validatorInfo['validator'])) {
                    $validator = $validatorInfo['validator'];
                    if (isset($validatorInfo['breakChainOnFailure'])) {
                        $breakChainOnFailure = $validatorInfo['breakChainOnFailure'];
                    }
                    if (isset($validatorInfo['options'])) {
                        $options = $validatorInfo['options'];
                    }
                    $this->addValidator($validator, $breakChainOnFailure, $options);
                } else {
                    switch (true) {
                        case (0 == $argc):
                            break;
                        case (1 <= $argc):
                            $validator  = array_shift($validatorInfo);
                        case (2 <= $argc):
                            $breakChainOnFailure = array_shift($validatorInfo);
                        case (3 <= $argc):
                            $options = array_shift($validatorInfo);
                        default:
                            $this->addValidator($validator, $breakChainOnFailure, $options);
                            break;
                    }
                }
            } else {
                require_once 'Zend/Form/Exception.php';
                throw new Zend_Form_Exception('Invalid validator passed to addValidators()');
            }
        }

        return $this;
    }

    /**
     * Set multiple validators, overwriting previous validators
     * 
     * @param  array $validators 
     * @return Zend_Form_Element
     */
    public function setValidators(array $validators)
    {
        $this->clearValidators();
        return $this->addValidators($validators);
    }

    /**
     * Retrieve a single validator by name
     * 
     * @param  string $name 
     * @return Zend_Validate_Interface|false False if not found, validator otherwise
     */
    public function getValidator($name)
    {
        if (!isset($this->_validators[$name])) {
            $len = strlen($name);
            foreach ($this->_validators as $localName => $validator) {
                if ($len > strlen($localName)) {
                    continue;
                }
                if (0 === substr_compare($localName, $name, -$len, $len, true)) {
                    if (is_array($validator)) {
                        return $this->_loadValidator($validator);
                    }
                    return $validator;
                }
            }
            return false;
        }

        if (is_array($this->_validators[$name])) {
            return $this->_loadValidator($this->_validators[$name]);
        }

        return $this->_validators[$name];
    }

    /**
     * Retrieve all validators
     * 
     * @return array
     */
    public function getValidators()
    {
        $validators = array();
        foreach ($this->_validators as $key => $value) {
            if ($value instanceof Zend_Validate_Interface) {
                $validators[$key] = $value;
                continue;
            }
            $validator = $this->_loadValidator($value);
            $validators[get_class($validator)] = $validator;
        }
        return $validators;
    }

    /**
     * Remove a single validator by name
     * 
     * @param  string $name 
     * @return bool
     */
    public function removeValidator($name)
    {
        if (isset($this->_validators[$name])) {
            unset($this->_validators[$name]);
        } else {
            $len = strlen($name);
            foreach (array_keys($this->_validators) as $validator) {
                if ($len > strlen($validator)) {
                    continue;
                }
                if (0 === substr_compare($validator, $name, -$len, $len, true)) {
                    unset($this->_validators[$validator]);
                    break;
                }
            }
        }

        return $this;
    }

    /**
     * Clear all validators
     * 
     * @return Zend_Form_Element
     */
    public function clearValidators()
    {
        $this->_validators = array();
        return $this;
    }

    /**
     * Validate element value
     *
     * If a translation adapter is registered, any error messages will be 
     * translated according to the current locale, using the given error code; 
     * if no matching translation is found, the original message will be 
     * utilized.
     *
     * Note: The *filtered* value is validated.
     * 
     * @param  mixed $value 
     * @param  mixed $context 
     * @return boolean
     */
    public function isValid($value, $context = null)
    {
        $this->setValue($value);
        $value = $this->getValue();

        if ((('' === $value) || (null === $value)) 
            && !$this->isRequired() 
            && $this->getAllowEmpty()
        ) {
            return true;
        }

        if ($this->isRequired() 
            && $this->autoInsertNotEmptyValidator() 
            && !$this->getValidator('NotEmpty'))
        {
            $validators = $this->getValidators();
            $notEmpty   = array('validator' => 'NotEmpty', 'breakChainOnFailure' => true);
            array_unshift($validators, $notEmpty);
            $this->setValidators($validators);
        }

        $this->_messages = array();
        $this->_errors   = array();
        $result          = true;
        $translator      = $this->getTranslator();
        $isArray         = $this->isArray();
        foreach ($this->getValidators() as $key => $validator) {
            if (method_exists($validator, 'setTranslator')) {
                $validator->setTranslator($translator);
            }

            if ($isArray && is_array($value)) {
                $messages = array();
                $errors   = array();
                foreach ($value as $val) {
                    if (!$validator->isValid($val, $context)) {
                        $result = false;
                        if ($this->_hasErrorMessages()) {
                            $messages = $this->_getErrorMessages();
                            $errors   = $messages;
                        } else {
                            $messages = array_merge($messages, $validator->getMessages());
                            $errors   = array_merge($errors,   $validator->getErrors());
                        }
                    }
                }
                if ($result) {
                    continue;
                }
            } elseif ($validator->isValid($value, $context)) {
                continue;
            } else {
                $result = false;
                if ($this->_hasErrorMessages()) {
                    $messages = $this->_getErrorMessages();
                    $errors   = $messages;
                } else {
                    $messages = $validator->getMessages();
                    $errors   = array_keys($messages);
                }
            }

            $result          = false;
            $this->_messages = array_merge($this->_messages, $messages);
            $this->_errors   = array_merge($this->_errors,   $errors);

            if ($validator->zfBreakChainOnFailure) {
                break;
            }
        }

        return $result;
    }

    /**
     * Add a custom error message to return in the event of failed validation
     * 
     * @param  string $message 
     * @return Zend_Form_Element
     */
    public function addErrorMessage($message)
    {
        $this->_errorMessages[] = (string) $message;
        return $this;
    }

    /**
     * Add multiple custom error messages to return in the event of failed validation
     * 
     * @param  array $messages 
     * @return Zend_Form_Element
     */
    public function addErrorMessages(array $messages)
    {
        foreach ($messages as $message) {
            $this->addErrorMessage($message);
        }
        return $this;
    }

    /**
     * Same as addErrorMessages(), but clears custom error message stack first
     * 
     * @param  array $messages 
     * @return Zend_Form_Element
     */
    public function setErrorMessages(array $messages)
    {
        $this->clearErrorMessages();
        return $this->addErrorMessages($messages);
    }

    /**
     * Retrieve custom error messages
     * 
     * @return array
     */
    public function getErrorMessages()
    {
        return $this->_errorMessages;
    }

    /**
     * Clear custom error messages stack
     * 
     * @return Zend_Form_Element
     */
    public function clearErrorMessages()
    {
        $this->_errorMessages = array();
        return $this;
    }

    /**
     * Mark the element as being in a failed validation state
     * 
     * @return Zend_Form_Element
     */
    public function markAsError()
    {
        $messages       = $this->getMessages();
        $customMessages = $this->_getErrorMessages();
        $messages       = $messages + $customMessages;
        if (empty($messages)) {
            $this->_isError = true;
        } else {
            $this->_messages = $messages;
        }
        return $this;
    }

    /**
     * Add an error message and mark element as failed validation
     * 
     * @param  string $message 
     * @return Zend_Form_Element
     */
    public function addError($message)
    {
        $this->addErrorMessage($message);
        $this->markAsError();
        return $this;
    }

    /**
     * Add multiple error messages and flag element as failed validation
     * 
     * @param  array $messages 
     * @return Zend_Form_Element
     */
    public function addErrors(array $messages)
    {
        foreach ($messages as $message) {
            $this->addError($message);
        }
        return $this;
    }

    /**
     * Overwrite any previously set error messages and flag as failed validation
     * 
     * @param  array $messages 
     * @return Zend_Form_Element
     */
    public function setErrors(array $messages)
    {
        $this->clearErrorMessages();
        return $this->addErrors($messages);
    }

    /**
     * Are there errors registered?
     * 
     * @return bool
     */
    public function hasErrors()
    {
        return (!empty($this->_messages) || $this->_isError);
    }

    /**
     * Retrieve validator chain errors
     * 
     * @return array
     */
    public function getErrors()
    {
        return $this->_errors;
    }

    /**
     * Retrieve error messages
     * 
     * @return array
     */
    public function getMessages()
    {
        return $this->_messages;
    }


    // Filtering

    /**
     * Add a filter to the element
     * 
     * @param  string|Zend_Filter_Interface $filter 
     * @return Zend_Form_Element
     */
    public function addFilter($filter, $options = array())
    {
        if ($filter instanceof Zend_Filter_Interface) {
            $name = get_class($filter);
        } elseif (is_string($filter)) {
            $name = $filter;
            $filter = array(
                'filter'  => $filter, 
                'options' => $options,
            );
            $this->_filters[$name] = $filter;
        } else {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception('Invalid filter provided to addFilter; must be string or Zend_Filter_Interface');
        }

        $this->_filters[$name] = $filter;

        return $this;
    }

    /**
     * Add filters to element
     * 
     * @param  array $filters 
     * @return Zend_Form_Element
     */
    public function addFilters(array $filters)
    {
        foreach ($filters as $filterInfo) {
            if (is_string($filterInfo)) {
                $this->addFilter($filterInfo);
            } elseif ($filterInfo instanceof Zend_Filter_Interface) {
                $this->addFilter($filterInfo);
            } elseif (is_array($filterInfo)) {
                $argc                = count($filterInfo);
                $options             = array();
                if (isset($filterInfo['filter'])) {
                    $filter = $filterInfo['filter'];
                    if (isset($filterInfo['options'])) {
                        $options = $filterInfo['options'];
                    }
                    $this->addFilter($filter, $options);
                } else {
                    switch (true) {
                        case (0 == $argc):
                            break;
                        case (1 <= $argc):
                            $filter  = array_shift($filterInfo);
                        case (2 <= $argc):
                            $options = array_shift($filterInfo);
                        default:
                            $this->addFilter($filter, $options);
                            break;
                    }
                }
            } else {
                require_once 'Zend/Form/Exception.php';
                throw new Zend_Form_Exception('Invalid filter passed to addFilters()');
            }
        }

        return $this;
    }

    /**
     * Add filters to element, overwriting any already existing
     * 
     * @param  array $filters 
     * @return Zend_Form_Element
     */
    public function setFilters(array $filters)
    {
        $this->clearFilters();
        return $this->addFilters($filters);
    }

    /**
     * Retrieve a single filter by name
     * 
     * @param  string $name 
     * @return Zend_Filter_Interface
     */
    public function getFilter($name)
    {
        if (!isset($this->_filters[$name])) {
            $len = strlen($name);
            foreach ($this->_filters as $localName => $filter) {
                if ($len > strlen($localName)) {
                    continue;
                }

                if (0 === substr_compare($localName, $name, -$len, $len, true)) {
                    if (is_array($filter)) {
                        return $this->_loadFilter($filter);
                    }
                    return $filter;
                }
            }
            return false;
        }

        if (is_array($this->_filters[$name])) {
            return $this->_loadFilter($this->_filters[$name]);
        }

        return $this->_filters[$name];
    }

    /**
     * Get all filters
     * 
     * @return array
     */
    public function getFilters()
    {
        $filters = array();
        foreach ($this->_filters as $key => $value) {
            if ($value instanceof Zend_Filter_Interface) {
                $filters[$key] = $value;
                continue;
            }
            $filter = $this->_loadFilter($value);
            $filters[get_class($filter)] = $filter;
        }
        return $filters;
    }

    /**
     * Remove a filter by name
     * 
     * @param  string $name 
     * @return Zend_Form_Element
     */
    public function removeFilter($name)
    {
        if (isset($this->_filters[$name])) {
            unset($this->_filters[$name]);
        } else {
            $len = strlen($name);
            foreach (array_keys($this->_filters) as $filter) {
                if ($len > strlen($filter)) {
                    continue;
                }
                if (0 === substr_compare($filter, $name, -$len, $len, true)) {
                    unset($this->_filters[$filter]);
                    break;
                }
            }
        }

        return $this;
    }

    /**
     * Clear all filters
     * 
     * @return Zend_Form_Element
     */
    public function clearFilters()
    {
        $this->_filters = array();
        return $this;
    }

    // Rendering

    /**
     * Set view object
     * 
     * @param  Zend_View_Interface $view 
     * @return Zend_Form_Element
     */
    public function setView(Zend_View_Interface $view = null)
    {
        $this->_view = $view;
        return $this;
    }

    /**
     * Retrieve view object
     *
     * Retrieves from ViewRenderer if none previously set.
     * 
     * @return null|Zend_View_Interface
     */
    public function getView()
    {
        if (null === $this->_view) {
            require_once 'Zend/Controller/Action/HelperBroker.php';
            $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
            $this->setView($viewRenderer->view);
        }
        return $this->_view;
    }

    /**
     * Instantiate a decorator based on class name or class name fragment
     * 
     * @param  string $name 
     * @param  null|array $options 
     * @return Zend_Form_Decorator_Interface
     */
    protected function _getDecorator($name, $options)
    {
        $class = $this->getPluginLoader(self::DECORATOR)->load($name);
        if (null === $options) {
            $decorator = new $class;
        } else {
            $decorator = new $class($options);
        }

        return $decorator;
    }

    /**
     * Add a decorator for rendering the element
     * 
     * @param  string|Zend_Form_Decorator_Interface $decorator 
     * @param  array|Zend_Config $options Options with which to initialize decorator
     * @return Zend_Form_Element
     */
    public function addDecorator($decorator, $options = null)
    {
        if ($decorator instanceof Zend_Form_Decorator_Interface) {
            $name = get_class($decorator);
        } elseif (is_string($decorator)) {
            $name      = $decorator;
            $decorator = array(
                'decorator' => $name,
                'options'   => $options,
            );
        } elseif (is_array($decorator)) {
            foreach ($decorator as $name => $spec) {
                break;
            }
            if (is_numeric($name)) {
                require_once 'Zend/Form/Exception.php';
                throw new Zend_Form_Exception('Invalid alias provided to addDecorator; must be alphanumeric string');
            }
            if (is_string($spec)) {
                $decorator = array(
                    'decorator' => $spec,
                    'options'   => $options,
                );
            } elseif ($spec instanceof Zend_Form_Decorator_Interface) {
                $decorator = $spec;
            }
        } else {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception('Invalid decorator provided to addDecorator; must be string or Zend_Form_Decorator_Interface');
        }

        $this->_decorators[$name] = $decorator;

        return $this;
    }

    /**
     * Add many decorators at once
     * 
     * @param  array $decorators 
     * @return Zend_Form_Element
     */
    public function addDecorators(array $decorators)
    {
        foreach ($decorators as $decoratorInfo) {
            if (is_string($decoratorInfo)) {
                $this->addDecorator($decoratorInfo);
            } elseif ($decoratorInfo instanceof Zend_Form_Decorator_Interface) {
                $this->addDecorator($decoratorInfo);
            } elseif (is_array($decoratorInfo)) {
                $argc    = count($decoratorInfo);
                $options = array();
                if (isset($decoratorInfo['decorator'])) {
                    $decorator = $decoratorInfo['decorator'];
                    if (isset($decoratorInfo['options'])) {
                        $options = $decoratorInfo['options'];
                    }
                    $this->addDecorator($decorator, $options);
                } else {
                    switch (true) {
                        case (0 == $argc):
                            break;
                        case (1 <= $argc):
                            $decorator  = array_shift($decoratorInfo);
                        case (2 <= $argc):
                            $options = array_shift($decoratorInfo);
                        default:
                            $this->addDecorator($decorator, $options);
                            break;
                    }
                }
            } else {
                require_once 'Zend/Form/Exception.php';
                throw new Zend_Form_Exception('Invalid decorator passed to addDecorators()');
            }
        }

        return $this;
    }

    /**
     * Overwrite all decorators
     * 
     * @param  array $decorators 
     * @return Zend_Form_Element
     */
    public function setDecorators(array $decorators)
    {
        $this->clearDecorators();
        return $this->addDecorators($decorators);
    }

    /**
     * Retrieve a registered decorator
     * 
     * @param  string $name 
     * @return false|Zend_Form_Decorator_Abstract
     */
    public function getDecorator($name)
    {
        if (!isset($this->_decorators[$name])) {
            $len = strlen($name);
            foreach ($this->_decorators as $localName => $decorator) {
                if ($len > strlen($localName)) {
                    continue;
                }

                if (0 === substr_compare($localName, $name, -$len, $len, true)) {
                    if (is_array($decorator)) {
                        return $this->_loadDecorator($decorator, $localName);
                    }
                    return $decorator;
                }
            }
            return false;
        }

        if (is_array($this->_decorators[$name])) {
            return $this->_loadDecorator($this->_decorators[$name], $name);
        }

        return $this->_decorators[$name];
    }

    /**
     * Retrieve all decorators
     * 
     * @return array
     */
    public function getDecorators()
    {
        foreach ($this->_decorators as $key => $value) {
            if (is_array($value)) {
                $this->_loadDecorator($value, $key);
            }
        }
        return $this->_decorators;
    }

    /**
     * Remove a single decorator
     * 
     * @param  string $name 
     * @return bool
     */
    public function removeDecorator($name)
    {
        if (isset($this->_decorators[$name])) {
            unset($this->_decorators[$name]);
        } else {
            $len = strlen($name);
            foreach (array_keys($this->_decorators) as $decorator) {
                if ($len > strlen($decorator)) {
                    continue;
                }
                if (0 === substr_compare($decorator, $name, -$len, $len, true)) {
                    unset($this->_decorators[$decorator]);
                    break;
                }
            }
        }

        return $this;
    }

    /**
     * Clear all decorators
     * 
     * @return Zend_Form_Element
     */
    public function clearDecorators()
    {
        $this->_decorators = array();
        return $this;
    }

    /**
     * Render form element
     * 
     * @param  Zend_View_Interface $view 
     * @return string
     */
    public function render(Zend_View_Interface $view = null)
    {
        if (null !== $view) {
            $this->setView($view);
        }

        $content = '';
        foreach ($this->getDecorators() as $decorator) {
            $decorator->setElement($this);
            $content = $decorator->render($content);
        }
        return $content;
    }

    /**
     * String representation of form element
     *
     * Proxies to {@link render()}.
     * 
     * @return string
     */
    public function __toString()
    {
        try {
            $return = $this->render();
            return $return;
        } catch (Exception $e) {
            trigger_error($e->getMessage(), E_USER_WARNING);
            return '';
        }
    }

    /**
     * Lazy-load a filter
     * 
     * @param  array $filter 
     * @return Zend_Filter_Interface
     */
    protected function _loadFilter(array $filter)
    {
        $origName = $filter['filter'];
        $name     = $this->getPluginLoader(self::FILTER)->load($filter['filter']);

        if (array_key_exists($name, $this->_filters)) {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception(sprintf('Filter instance already exists for filter "%s"', $origName));
        }

        if (empty($filter['options'])) {
            $instance = new $name;
        } else {
            $r = new ReflectionClass($name);
            if ($r->hasMethod('__construct')) {
                $instance = $r->newInstanceArgs((array) $filter['options']);
            } else {
                $instance = $r->newInstance();
            }
        }

        if ($origName != $name) {
            $filterNames  = array_keys($this->_filters);
            $order        = array_flip($filterNames);
            $order[$name] = $order[$origName];
            $filtersExchange = array();
            unset($order[$origName]);
            asort($order);
            foreach ($order as $key => $index) {
                if ($key == $name) {
                    $filtersExchange[$key] = $instance;
                    continue;
                }
                $filtersExchange[$key] = $this->_filters[$key];
            }
            $this->_filters = $filtersExchange;
        } else {
            $this->_filters[$name] = $instance;
        }

        return $instance;
    }

    /**
     * Lazy-load a validator
     * 
     * @param  array $validator Validator definition
     * @return Zend_Validate_Interface
     */
    protected function _loadValidator(array $validator)
    {
        $origName = $validator['validator'];
        $name     = $this->getPluginLoader(self::VALIDATE)->load($validator['validator']);

        if (array_key_exists($name, $this->_validators)) {
            require_once 'Zend/Form/Exception.php';
            throw new Zend_Form_Exception(sprintf('Validator instance already exists for validator "%s"', $origName));
        }

        if (empty($validator['options'])) {
            $instance = new $name;
        } else {
            $messages = false;
            if (isset($validator['options']['messages'])) {
                $messages = $validator['options']['messages'];
                unset($validator['options']['messages']);
            }

            $r = new ReflectionClass($name);
            if ($r->hasMethod('__construct')) {
                $instance = $r->newInstanceArgs((array) $validator['options']);
            } else {
                $instance = $r->newInstance();
            }

            if ($messages) {
                if (is_array($messages)) {
                    $instance->setMessages($messages);
                } elseif (is_string($messages)) {
                    $instance->setMessage($messages);
                }
            }
        }

        $instance->zfBreakChainOnFailure = $validator['breakChainOnFailure'];

        if ($origName != $name) {
            $validatorNames     = array_keys($this->_validators);
            $order              = array_flip($validatorNames);
            $order[$name]       = $order[$origName];
            $validatorsExchange = array();
            unset($order[$origName]);
            asort($order);
            foreach ($order as $key => $index) {
                if ($key == $name) {
                    $validatorsExchange[$key] = $instance;
                    continue;
                }
                $validatorsExchange[$key] = $this->_validators[$key];
            }
            $this->_validators = $validatorsExchange;
        } else {
            $this->_validators[$name] = $instance;
        }

        return $instance;
    }

    /**
     * Lazy-load a decorator
     * 
     * @param  array $decorator Decorator type and options
     * @param  mixed $name Decorator name or alias
     * @return Zend_Form_Decorator_Interface
     */
    protected function _loadDecorator(array $decorator, $name)
    {
        $sameName = false;
        if ($name == $decorator['decorator']) {
            $sameName = true;
        }

        $instance = $this->_getDecorator($decorator['decorator'], $decorator['options']);
        if ($sameName) {
            $newName            = get_class($instance);
            $decoratorNames     = array_keys($this->_decorators);
            $order              = array_flip($decoratorNames);
            $order[$newName]    = $order[$name];
            $decoratorsExchange = array();
            unset($order[$name]);
            asort($order);
            foreach ($order as $key => $index) {
                if ($key == $newName) {
                    $decoratorsExchange[$key] = $instance;
                    continue;
                }
                $decoratorsExchange[$key] = $this->_decorators[$key];
            }
            $this->_decorators = $decoratorsExchange;
        } else {
            $this->_decorators[$name] = $instance;
        }

        return $instance;
    }

    /**
     * Retrieve error messages and perform translation and value substitution
     * 
     * @return array
     */
    protected function _getErrorMessages()
    {
        $translator = $this->getTranslator();
        $messages   = $this->getErrorMessages();
        $value      = $this->getValue();
        foreach ($messages as $key => $message) {
            if (null !== $translator) {
                $message = $translator->translate($message);
            }
            if ($this->isArray() || is_array($value)) {
                $aggregateMessages = array();
                foreach ($value as $val) {
                    $aggregateMessages[] = str_replace('%value%', $val, $message);
                }
                $messages[$key] = $aggregateMessages;
            } else {
                $messages[$key] = str_replace('%value%', $value, $message);
            }
        }
        return $messages;
    }

    /**
     * Are there custom error messages registered?
     * 
     * @return bool
     */
    protected function _hasErrorMessages()
    {
        return !empty($this->_errorMessages);
    }
}
Loader/PluginLoader/Interface.php000066600000004050151256604600012760 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Loader
 * @subpackage PluginLoader
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Plugin class loader interface
 *
 * @category   Zend
 * @package    Zend_Loader
 * @subpackage PluginLoader
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_Loader_PluginLoader_Interface
{
    /**
     * Add prefixed paths to the registry of paths
     *
     * @param string $prefix
     * @param string $path
     * @return Zend_Loader_PluginLoader
     */
    public function addPrefixPath($prefix, $path);
    
    /**
     * Remove a prefix (or prefixed-path) from the registry
     *
     * @param string $prefix
     * @param string $path OPTIONAL
     * @return Zend_Loader_PluginLoader
     */
    public function removePrefixPath($prefix, $path = null);
    
    /**
     * Whether or not a Helper by a specific name
     *
     * @param string $name
     * @return Zend_Loader_PluginLoader
     */
    public function isLoaded($name);

    /**
     * Return full class name for a named helper
     *
     * @param string $name
     * @return string
     */
    public function getClassName($name);
    
    /**
     * Load a helper via the name provided
     *
     * @param string $name
     * @return string
     */
    public function load($name);
}
Test/PHPUnit/Constraint/DomQuery.php000066600000027511151256604600013373 0ustar00<?php
/** PHPUnit_Framework_Constraint */
require_once 'PHPUnit/Framework/Constraint.php';

/** Zend_Dom_Query */
require_once 'Zend/Dom/Query.php';

/**
 * Zend_Dom_Query-based PHPUnit Constraint
 * 
 * @uses       PHPUnit_Framework_Constraint
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (C) 2008 - Present, Zend Technologies, Inc.
 * @license    New BSD {@link http://framework.zend.com/license/new-bsd}
 */
class Zend_Test_PHPUnit_Constraint_DomQuery extends PHPUnit_Framework_Constraint
{
    /**#@+
     * @const string Assertion type constants
     */
    const ASSERT_QUERY            = 'assertQuery';
    const ASSERT_CONTENT_CONTAINS = 'assertQueryContentContains';
    const ASSERT_CONTENT_REGEX    = 'assertQueryContentRegex';
    const ASSERT_CONTENT_COUNT    = 'assertQueryCount';
    const ASSERT_CONTENT_COUNT_MIN= 'assertQueryCountMin';
    const ASSERT_CONTENT_COUNT_MAX= 'assertQueryCountMax';
    /**#@-*/

    /**
     * Current assertion type
     * @var string
     */
    protected $_assertType        = null;

    /**
     * Available assertion types
     * @var array
     */
    protected $_assertTypes       = array(
        self::ASSERT_QUERY,
        self::ASSERT_CONTENT_CONTAINS,
        self::ASSERT_CONTENT_REGEX,
        self::ASSERT_CONTENT_COUNT,
        self::ASSERT_CONTENT_COUNT_MIN,
        self::ASSERT_CONTENT_COUNT_MAX,
    );

    /**
     * Content being matched
     * @var string
     */
    protected $_content           = null;

    /**
     * Whether or not assertion is negated
     * @var bool
     */
    protected $_negate            = false;

    /**
     * CSS selector or XPath path to select against
     * @var string
     */
    protected $_path              = null;

    /**
     * Whether or not to use XPath when querying
     * @var bool
     */
    protected $_useXpath          = false;

    /**
     * Constructor; setup constraint state
     * 
     * @param  string $path CSS selector path
     * @return void
     */
    public function __construct($path)
    {
        $this->_path = $path;
    }

    /**
     * Indicate negative match
     * 
     * @param  bool $flag 
     * @return void
     */
    public function setNegate($flag = true)
    {
        $this->_negate = $flag;
    }

    /**
     * Whether or not path is a straight XPath expression
     * 
     * @param  bool $flag 
     * @return Zend_Test_PHPUnit_Constraint_DomQuery
     */
    public function setUseXpath($flag = true)
    {
        $this->_useXpath = (bool) $flag;
        return $this;
    }

    /**
     * Evaluate an object to see if it fits the constraints
     * 
     * @param  string $other String to examine
     * @param  null|string Assertion type
     * @return bool
     */
    public function evaluate($other, $assertType = null)
    {
        if (strstr($assertType, 'Not')) {
            $this->setNegate(true);
            $assertType = str_replace('Not', '', $assertType);
        }

        if (strstr($assertType, 'Xpath')) {
            $this->setUseXpath(true);
            $assertType = str_replace('Xpath', 'Query', $assertType);
        }

        if (!in_array($assertType, $this->_assertTypes)) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__));
        }

        $this->_assertType = $assertType;

        $method   = $this->_useXpath ? 'queryXpath' : 'query';
        $domQuery = new Zend_Dom_Query($other);
        $result   = $domQuery->$method($this->_path);
        $argv     = func_get_args();
        $argc     = func_num_args();

        switch ($assertType) {
            case self::ASSERT_CONTENT_CONTAINS:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No content provided against which to match');
                }
                $this->_content = $content = $argv[2];
                return ($this->_negate)
                    ? $this->_notMatchContent($result, $content)
                    : $this->_matchContent($result, $content);
            case self::ASSERT_CONTENT_REGEX:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match');
                }
                $this->_content = $content = $argv[2];
                return ($this->_negate)
                    ? $this->_notRegexContent($result, $content)
                    : $this->_regexContent($result, $content);
            case self::ASSERT_CONTENT_COUNT:
            case self::ASSERT_CONTENT_COUNT_MIN:
            case self::ASSERT_CONTENT_COUNT_MAX:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No count provided against which to compare');
                }
                $this->_content = $content = $argv[2];
                return $this->_countContent($result, $content, $assertType);
            case self::ASSERT_QUERY:
            default:
                if ($this->_negate) {
                    return (0 == count($result));
                } else {
                    return (0 != count($result));
                }
        }
    }

    /**
     * Report Failure
     * 
     * @see    PHPUnit_Framework_Constraint for implementation details
     * @param  mixed $other CSS selector path
     * @param  string $description 
     * @param  bool $not 
     * @return void
     * @throws PHPUnit_Framework_ExpectationFailedException
     */
    public function fail($other, $description, $not = false)
    {
        require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
        switch ($this->_assertType) {
            case self::ASSERT_CONTENT_CONTAINS:
                $failure = 'Failed asserting node denoted by %s CONTAINS content "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content "%s"';
                }
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_CONTENT_REGEX:
                $failure = 'Failed asserting node denoted by %s CONTAINS content MATCHING "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting node DENOTED BY %s DOES NOT CONTAIN content MATCHING "%s"';
                }
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_CONTENT_COUNT:
                $failure = 'Failed asserting node DENOTED BY %s OCCURS EXACTLY %d times';
                if ($this->_negate) {
                    $failure = 'Failed asserting node DENOTED BY %s DOES NOT OCCUR EXACTLY %d times';
                }
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_CONTENT_COUNT_MIN:
                $failure = 'Failed asserting node DENOTED BY %s OCCURS AT LEAST %d times';
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_CONTENT_COUNT_MAX:
                $failure = 'Failed asserting node DENOTED BY %s OCCURS AT MOST %d times';
                $failure = sprintf($failure, $other, $this->_content);
                break;
            case self::ASSERT_QUERY:
            default:
                $failure = 'Failed asserting node DENOTED BY %s EXISTS';
                if ($this->_negate) {
                    $failure = 'Failed asserting node DENOTED BY %s DOES NOT EXIST';
                }
                $failure = sprintf($failure, $other);
                break;
        }

        if (!empty($description)) {
            $failure = $description . "\n" . $failure;
        }

        throw new Zend_Test_PHPUnit_Constraint_Exception($failure);
    }

    /**
     * Complete implementation
     * 
     * @return string
     */
    public function toString()
    {
        return '';
    }

    /**
     * Check to see if content is matched in selected nodes
     * 
     * @param  Zend_Dom_Query_Result $result 
     * @param  string $match Content to match
     * @return bool
     */
    protected function _matchContent($result, $match)
    {
        if (0 == count($result)) {
            return false;
        }

        foreach ($result as $node) {
            $content = $this->_getNodeContent($node);
            if (strstr($content, $match)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check to see if content is NOT matched in selected nodes
     * 
     * @param  Zend_Dom_Query_Result $result 
     * @param  string $match 
     * @return bool
     */
    protected function _notMatchContent($result, $match)
    {
        if (0 == count($result)) {
            return true;
        }

        foreach ($result as $node) {
            $content = $this->_getNodeContent($node);
            if (strstr($content, $match)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Check to see if content is matched by regex in selected nodes
     * 
     * @param  Zend_Dom_Query_Result $result 
     * @param  string $pattern
     * @return bool
     */
    protected function _regexContent($result, $pattern)
    {
        if (0 == count($result)) {
            return false;
        }

        foreach ($result as $node) {
            $content = $this->_getNodeContent($node);
            if (preg_match($pattern, $content)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check to see if content is NOT matched by regex in selected nodes
     * 
     * @param  Zend_Dom_Query_Result $result 
     * @param  string $pattern
     * @return bool
     */
    protected function _notRegexContent($result, $pattern)
    {
        if (0 == count($result)) {
            return true;
        }

        foreach ($result as $node) {
            $content = $this->_getNodeContent($node);
            if (preg_match($pattern, $content)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Determine if content count matches criteria
     * 
     * @param  Zend_Dom_Query_Result $result 
     * @param  int $test Value against which to test
     * @param  string $type assertion type
     * @return boolean
     */
    protected function _countContent($result, $test, $type)
    {
        $count = count($result);

        switch ($type) {
            case self::ASSERT_CONTENT_COUNT:
                return ($this->_negate)
                    ? ($test != $count)
                    : ($test == $count);
            case self::ASSERT_CONTENT_COUNT_MIN:
                return ($count >= $test);
            case self::ASSERT_CONTENT_COUNT_MAX:
                return ($count <= $test);
            default:
                return false;
        }
    }

    /**
     * Get node content, minus node markup tags
     * 
     * @param  DOMNode $node 
     * @return string
     */
    protected function _getNodeContent(DOMNode $node)
    {
        $doc     = $node->ownerDocument;
        $content = $doc->saveXML($node);
        $tag     = $node->nodeName;
        $regex   = '|</?' . $tag . '[^>]*>|';
        return preg_replace($regex, '', $content);
    }
}
Test/PHPUnit/Constraint/ResponseHeader.php000066600000030756151256604600014542 0ustar00<?php
/** PHPUnit_Framework_Constraint */
require_once 'PHPUnit/Framework/Constraint.php';

/**
 * Response header PHPUnit Constraint
 * 
 * @uses       PHPUnit_Framework_Constraint
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (C) 2008 - Present, Zend Technologies, Inc.
 * @license    New BSD {@link http://framework.zend.com/license/new-bsd}
 */
class Zend_Test_PHPUnit_Constraint_ResponseHeader extends PHPUnit_Framework_Constraint
{
    /**#@+
     * @const string Assertion type constants
     */
    const ASSERT_RESPONSE_CODE   = 'assertResponseCode';
    const ASSERT_HEADER          = 'assertHeader';
    const ASSERT_HEADER_CONTAINS = 'assertHeaderContains';
    const ASSERT_HEADER_REGEX    = 'assertHeaderRegex';
    /**#@-*/

    /**
     * Current assertion type
     * @var string
     */
    protected $_assertType      = null;

    /**
     * Available assertion types
     * @var array
     */
    protected $_assertTypes     = array(
        self::ASSERT_RESPONSE_CODE,
        self::ASSERT_HEADER,
        self::ASSERT_HEADER_CONTAINS,
        self::ASSERT_HEADER_REGEX,
    );

    /**
     * @var int Response code
     */
    protected $_code              = 200;

    /**
     * @var string Header
     */
    protected $_header            = null;

    /**
     * @var string pattern against which to compare header content
     */
    protected $_match             = null;

    /**
     * Whether or not assertion is negated
     * @var bool
     */
    protected $_negate            = false;

    /**
     * Constructor; setup constraint state
     * 
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Indicate negative match
     * 
     * @param  bool $flag 
     * @return void
     */
    public function setNegate($flag = true)
    {
        $this->_negate = $flag;
    }

    /**
     * Evaluate an object to see if it fits the constraints
     * 
     * @param  Zend_Controller_Response_Abstract $other String to examine
     * @param  null|string Assertion type
     * @return bool
     */
    public function evaluate($other, $assertType = null)
    {
        if (!$other instanceof Zend_Controller_Response_Abstract) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception('Header constraint assertions require a response object');
        }

        if (strstr($assertType, 'Not')) {
            $this->setNegate(true);
            $assertType = str_replace('Not', '', $assertType);
        }

        if (!in_array($assertType, $this->_assertTypes)) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__));
        }

        $this->_assertType = $assertType;

        $response = $other;
        $argv     = func_get_args();
        $argc     = func_num_args();

        switch ($assertType) {
            case self::ASSERT_RESPONSE_CODE:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No response code provided against which to match');
                }
                $this->_code = $code = $argv[2];
                return ($this->_negate)
                    ? $this->_notCode($response, $code)
                    : $this->_code($response, $code);
            case self::ASSERT_HEADER:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No header provided against which to match');
                }
                $this->_header = $header = $argv[2];
                return ($this->_negate)
                    ? $this->_notHeader($response, $header)
                    : $this->_header($response, $header);
            case self::ASSERT_HEADER_CONTAINS:
                if (4 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . __FUNCTION__);
                }
                $this->_header = $header = $argv[2];
                $this->_match  = $match  = $argv[3];
                return ($this->_negate)
                    ? $this->_notHeaderContains($response, $header, $match)
                    : $this->_headerContains($response, $header, $match);
            case self::ASSERT_HEADER_REGEX:
                if (4 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('Both a header name and content to match are required for ' . __FUNCTION__);
                }
                $this->_header = $header = $argv[2];
                $this->_match  = $match  = $argv[3];
                return ($this->_negate)
                    ? $this->_notHeaderRegex($response, $header, $match)
                    : $this->_headerRegex($response, $header, $match);
            default:
                require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . __FUNCTION__);
        }
    }

    /**
     * Report Failure
     * 
     * @see    PHPUnit_Framework_Constraint for implementation details
     * @param  mixed $other 
     * @param  string $description Additional message to display
     * @param  bool $not 
     * @return void
     * @throws PHPUnit_Framework_ExpectationFailedException
     */
    public function fail($other, $description, $not = false)
    {
        require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
        switch ($this->_assertType) {
            case self::ASSERT_RESPONSE_CODE:
                $failure = 'Failed asserting response code "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response code IS NOT "%s"';
                }
                $failure = sprintf($failure, $this->_code);
                break;
            case self::ASSERT_HEADER:
                $failure = 'Failed asserting response header "%s" found';
                if ($this->_negate) {
                    $failure = 'Failed asserting response response header "%s" WAS NOT found';
                }
                $failure = sprintf($failure, $this->_header);
                break;
            case self::ASSERT_HEADER_CONTAINS:
                $failure = 'Failed asserting response header "%s" exists and contains "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response header "%s" DOES NOT CONTAIN "%s"';
                }
                $failure = sprintf($failure, $this->_header, $this->_match);
                break;
            case self::ASSERT_HEADER_REGEX:
                $failure = 'Failed asserting response header "%s" exists and matches regex "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response header "%s" DOES NOT MATCH regex "%s"';
                }
                $failure = sprintf($failure, $this->_header, $this->_match);
                break;
            default:
                throw new Zend_Test_PHPUnit_Constraint_Exception('Invalid assertion type ' . __FUNCTION__);
        }

        if (!empty($description)) {
            $failure = $description . "\n" . $failure;
        }

        throw new Zend_Test_PHPUnit_Constraint_Exception($failure);
    }

    /**
     * Complete implementation
     * 
     * @return string
     */
    public function toString()
    {
        return '';
    }

    /**
     * Compare response code for positive match
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  int $code 
     * @return bool
     */
    protected function _code(Zend_Controller_Response_Abstract $response, $code)
    {
        $test = $this->_getCode($response);
        return ($test == $code);
    }

    /**
     * Compare response code for negative match
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  int $code 
     * @return bool
     */
    protected function _notCode(Zend_Controller_Response_Abstract $response, $code)
    {
        $test = $this->_getCode($response);
        return ($test != $code);
    }

    /**
     * Retrieve response code
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @return int
     */
    protected function _getCode(Zend_Controller_Response_Abstract $response)
    {
        $test = $response->getHttpResponseCode();
        if (null === $test) {
            $test = 200;
        }
        return $test;
    }

    /**
     * Positive check for response header presence
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  string $header 
     * @return bool
     */
    protected function _header(Zend_Controller_Response_Abstract $response, $header)
    {
        return (null !== $this->_getHeader($response, $header));
    }

    /**
     * Negative check for response header presence
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  string $header 
     * @return bool
     */
    protected function _notHeader(Zend_Controller_Response_Abstract $response, $header)
    {
        return (null === $this->_getHeader($response, $header));
    }

    /**
     * Retrieve response header
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  string $header 
     * @return string|null
     */
    protected function _getHeader(Zend_Controller_Response_Abstract $response, $header)
    {
        $headers = $response->sendHeaders();
        $header  = strtolower($header);
        if (array_key_exists($header, $headers)) {
            return $headers[$header];
        }
        return null;
    }

    /**
     * Positive check for header contents matching pattern
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  string $header 
     * @param  string $match 
     * @return bool
     */
    protected function _headerContains(Zend_Controller_Response_Abstract $response, $header, $match)
    {
        if (null === ($fullHeader = $this->_getHeader($response, $header))) {
            return false;
        }

        $contents = str_replace($header . ': ', '', $fullHeader);

        return (strstr($contents, $match));
    }

    /**
     * Negative check for header contents matching pattern
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  string $header 
     * @param  string $match 
     * @return bool
     */
    protected function _notHeaderContains(Zend_Controller_Response_Abstract $response, $header, $match)
    {
        if (null === ($fullHeader = $this->_getHeader($response, $header))) {
            return true;
        }

        $contents = str_replace($header . ': ', '', $fullHeader);

        return (!strstr($contents, $match));
    }

    /**
     * Positive check for header contents matching regex
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  string $header 
     * @param  string $pattern 
     * @return bool
     */
    protected function _headerRegex(Zend_Controller_Response_Abstract $response, $header, $pattern)
    {
        if (null === ($fullHeader = $this->_getHeader($response, $header))) {
            return false;
        }

        $contents = str_replace($header . ': ', '', $fullHeader);

        return preg_match($pattern, $contents);
    }

    /**
     * Negative check for header contents matching regex
     * 
     * @param  Zend_Controller_Response_Abstract $response 
     * @param  string $header 
     * @param  string $pattern 
     * @return bool
     */
    protected function _notHeaderRegex(Zend_Controller_Response_Abstract $response, $header, $pattern)
    {
        if (null === ($fullHeader = $this->_getHeader($response, $header))) {
            return true;
        }

        $contents = str_replace($header . ': ', '', $fullHeader);

        return !preg_match($pattern, $contents);
    }
}
Test/PHPUnit/Constraint/Redirect.php000066600000017726151256604600013376 0ustar00<?php
/** PHPUnit_Framework_Constraint */
require_once 'PHPUnit/Framework/Constraint.php';

/**
 * Redirection constraints
 * 
 * @uses       PHPUnit_Framework_Constraint
 * @package    Zend_Test
 * @subpackage PHPUnit
 * @copyright  Copyright (C) 2008 - Present, Zend Technologies, Inc.
 * @license    New BSD {@link http://framework.zend.com/license/new-bsd}
 */
class Zend_Test_PHPUnit_Constraint_Redirect extends PHPUnit_Framework_Constraint
{
    /**#@+
     * @const string Assertion type constants
     */
    const ASSERT_REDIRECT       = 'assertRedirect';
    const ASSERT_REDIRECT_TO    = 'assertRedirectTo';
    const ASSERT_REDIRECT_REGEX = 'assertRedirectRegex';
    /**#@-*/

    /**
     * Current assertion type
     * @var string
     */
    protected $_assertType      = null;

    /**
     * Available assertion types
     * @var array
     */
    protected $_assertTypes     = array(
        self::ASSERT_REDIRECT,
        self::ASSERT_REDIRECT_TO,
        self::ASSERT_REDIRECT_REGEX,
    );

    /**
     * Pattern to match against
     * @var string
     */
    protected $_match             = null;

    /**
     * Whether or not assertion is negated
     * @var bool
     */
    protected $_negate            = false;

    /**
     * Constructor; setup constraint state
     * 
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Indicate negative match
     * 
     * @param  bool $flag 
     * @return void
     */
    public function setNegate($flag = true)
    {
        $this->_negate = $flag;
    }

    /**
     * Evaluate an object to see if it fits the constraints
     * 
     * @param  string $other String to examine
     * @param  null|string Assertion type
     * @return bool
     */
    public function evaluate($other, $assertType = null)
    {
        if (!$other instanceof Zend_Controller_Response_Abstract) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception('Redirect constraint assertions require a response object');
        }

        if (strstr($assertType, 'Not')) {
            $this->setNegate(true);
            $assertType = str_replace('Not', '', $assertType);
        }

        if (!in_array($assertType, $this->_assertTypes)) {
            require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
            throw new Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__));
        }

        $this->_assertType = $assertType;

        $response = $other;
        $argv     = func_get_args();
        $argc     = func_num_args();

        switch ($assertType) {
            case self::ASSERT_REDIRECT_TO:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No redirect URL provided against which to match');
                }
                $this->_match = $match = $argv[2];
                return ($this->_negate)
                    ? $this->_notMatch($response, $match)
                    : $this->_match($response, $match);
            case self::ASSERT_REDIRECT_REGEX:
                if (3 > $argc) {
                    require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
                    throw new Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match redirect');
                }
                $this->_match = $match = $argv[2];
                return ($this->_negate)
                    ? $this->_notRegex($response, $match)
                    : $this->_regex($response, $match);
            case self::ASSERT_REDIRECT:
            default:
                return ($this->_negate) ? !$response->isRedirect() : $response->isRedirect();
        }
    }

    /**
     * Report Failure
     * 
     * @see    PHPUnit_Framework_Constraint for implementation details
     * @param  mixed $other 
     * @param  string $description Additional message to display
     * @param  bool $not 
     * @return void
     * @throws PHPUnit_Framework_ExpectationFailedException
     */
    public function fail($other, $description, $not = false)
    {
        require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
        switch ($this->_assertType) {
            case self::ASSERT_REDIRECT_TO:
                $failure = 'Failed asserting response redirects to "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response DOES NOT redirect to "%s"';
                }
                $failure = sprintf($failure, $this->_match);
                break;
            case self::ASSERT_REDIRECT_REGEX:
                $failure = 'Failed asserting response redirects to URL MATCHING "%s"';
                if ($this->_negate) {
                    $failure = 'Failed asserting response DOES NOT redirect to URL MATCHING "%s"';
                }
                $failure = sprintf($failure, $this->_match);
                break;
            case self::ASSERT_REDIRECT:
            default:
                $failure = 'Failed asserting response is a redirect';
                if ($this->_negate) {
                    $failure = 'Failed asserting response is NOT a redirect';
                }
                break;
        }

        if (!empty($description)) {
            $failure = $description . "\n" . $failure;
        }

        throw new Zend_Test_PHPUnit_Constraint_Exception($failure);
    }

    /**
     * Complete implementation
     * 
     * @return string
     */
    public function toString()
    {
        return '';
    }

    /**
     * Check to see if content is matched in selected nodes
     * 
     * @param  Zend_Controller_Response_HttpTestCase $response
     * @param  string $match Content to match
     * @return bool
     */
    protected function _match($response, $match)
    {
        if (!$response->isRedirect()) {
            return false;
        }

        $headers  = $response->sendHeaders();
        $redirect = $headers['location'];
        $redirect = str_replace('Location: ', '', $redirect);

        return ($redirect == $match);
    }

    /**
     * Check to see if content is NOT matched in selected nodes
     * 
     * @param  Zend_Controller_Response_HttpTestCase $response
     * @param  string $match 
     * @return bool
     */
    protected function _notMatch($response, $match)
    {
        if (!$response->isRedirect()) {
            return true;
        }

        $headers  = $response->sendHeaders();
        $redirect = $headers['location'];
        $redirect = str_replace('Location: ', '', $redirect);

        return ($redirect != $match);
    }

    /**
     * Check to see if content is matched by regex in selected nodes
     * 
     * @param  Zend_Controller_Response_HttpTestCase $response
     * @param  string $pattern
     * @return bool
     */
    protected function _regex($response, $pattern)
    {
        if (!$response->isRedirect()) {
            return false;
        }

        $headers  = $response->sendHeaders();
        $redirect = $headers['location'];
        $redirect = str_replace('Location: ', '', $redirect);

        return preg_match($pattern, $redirect);
    }

    /**
     * Check to see if content is NOT matched by regex in selected nodes
     * 
     * @param  Zend_Controller_Response_HttpTestCase $response
     * @param  string $pattern
     * @return bool
     */
    protected function _notRegex($response, $pattern)
    {
        if (!$response->isRedirect()) {
            return true;
        }

        $headers  = $response->sendHeaders();
        $redirect = $headers['location'];
        $redirect = str_replace('Location: ', '', $redirect);

        return !preg_match($pattern, $redirect);
    }
}
Layout/Controller/Action/Helper/Layout.php000066600000012007151256604600014577 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Layout.php 11508 2008-09-24 14:21:30Z doctorrock83 $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Controller_Action_Helper_Abstract */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * Helper for interacting with Zend_Layout objects
 *
 * @uses       Zend_Controller_Action_Helper_Abstract
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Layout_Controller_Action_Helper_Layout extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Zend_Controller_Front
     */
    protected $_frontController;

    /**
     * @var Zend_Layout
     */
    protected $_layout;

    /**
     * @var bool
     */
    protected $_isActionControllerSuccessful = false;
    
    /**
     * Constructor
     * 
     * @param  Zend_Layout $layout 
     * @return void
     */
    public function __construct(Zend_Layout $layout = null)
    {
        if (null !== $layout) {
            $this->setLayoutInstance($layout);
        } else {
            /**
             * @see Zend_Layout
             */
            require_once 'Zend/Layout.php';
            $layout = Zend_Layout::getMvcInstance();
        }
        
        if (null !== $layout) {
            $pluginClass = $layout->getPluginClass();
            $front = $this->getFrontController();
            if ($front->hasPlugin($pluginClass)) {
                $plugin = $front->getPlugin($pluginClass);
                $plugin->setLayoutActionHelper($this);
            }
        }
    }

    public function init()
    {
        $this->_isActionControllerSuccessful = false;
    }

    /**
     * Get front controller instance
     * 
     * @return Zend_Controller_Front
     */
    public function getFrontController()
    {
        if (null === $this->_frontController) {
            /**
             * @see Zend_Controller_Front
             */
            require_once 'Zend/Controller/Front.php';
            $this->_frontController = Zend_Controller_Front::getInstance();
        }

        return $this->_frontController;
    }
    
    /**
     * Get layout object
     * 
     * @return Zend_Layout
     */
    public function getLayoutInstance()
    {
        if (null === $this->_layout) {
            /**
             * @see Zend_Layout
             */
            require_once 'Zend/Layout.php';
            if (null === ($this->_layout = Zend_Layout::getMvcInstance())) {
                $this->_layout = new Zend_Layout();
            }
        }

        return $this->_layout;
    }

    /**
     * Set layout object
     * 
     * @param  Zend_Layout $layout 
     * @return Zend_Layout_Controller_Action_Helper_Layout
     */
    public function setLayoutInstance(Zend_Layout $layout)
    {
        $this->_layout = $layout;
        return $this;
    }

    /**
     * Mark Action Controller (according to this plugin) as Running successfully
     *
     * @return Zend_Layout_Controller_Action_Helper_Layout
     */
    public function postDispatch()
    {
        $this->_isActionControllerSuccessful = true;
        return $this;
    }
    
    /**
     * Did the previous action successfully complete?
     *
     * @return bool
     */
    public function isActionControllerSuccessful()
    {
        return $this->_isActionControllerSuccessful;
    }
    
    /**
     * Strategy pattern; call object as method
     *
     * Returns layout object
     * 
     * @return Zend_Layout
     */
    public function direct()
    {
        return $this->getLayoutInstance();
    }

    /**
     * Proxy method calls to layout object
     * 
     * @param  string $method 
     * @param  array $args 
     * @return mixed
     */
    public function __call($method, $args)
    {
        $layout = $this->getLayoutInstance();
        if (method_exists($layout, $method)) {
            return call_user_func_array(array($layout, $method), $args);
        }

        require_once 'Zend/Layout/Exception.php';
        throw new Zend_Layout_Exception(sprintf("Invalid method '%s' called on layout action helper", $method));
    }
}
Wildfire/Plugin/FirePhp/Message.php000066600000014245151256604600013220 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Wildfire
 * @subpackage Plugin
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * A message envelope that can be passed to Zend_Wildfire_Plugin_FirePhp to be
 * logged to Firebug instead of a variable.
 * 
 * @category   Zend
 * @package    Zend_Wildfire
 * @subpackage Plugin
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Wildfire_Plugin_FirePhp_Message
{
    /**
     * The style of the message
     * @var string
     */
    protected $_style = null;
    
    /**
     * The label of the message
     * @var string
     */
    protected $_label = null;
    
    /**
     * The message value
     * @var mixed
     */
    protected $_message = null;
    
    /**
     * Flag indicating if message buffering is enabled
     * @var boolean
     */
    protected $_buffered = false;

    /**
     * Flag indicating if message should be destroyed and not delivered
     * @var boolean
     */
    protected $_destroy = false;
    
    /**
     * Random unique ID used to identify message in comparison operations
     * @var string
     */
    protected $_ruid = false;

    /**
     * Options for the object
     * @var array
     */
    protected $_options = array(
        'traceOffset' => null, /* The offset in the trace which identifies the source of the message */
        'includeLineNumbers' => null /* Whether to include line and file info for this message */
    );

    /**
     * Creates a new message with the given style and message
     * 
     * @param string $style Style of the message.
     * @param mixed $message The message
     * @return void
     */
    function __construct($style, $message)
    {
        $this->_style = $style;
        $this->_message = $message;
        $this->_ruid = md5(microtime().mt_rand());
    }
    
    /**
     * Set the label of the message
     * 
     * @param string $label The label to be set
     * @return void
     */
    public function setLabel($label)
    {
        $this->_label = $label;
    }
    
    /**
     * Get the label of the message
     * 
     * @return string The label of the message
     */
    public function getLabel()
    {
        return $this->_label;
    }
    
    /**
     * Enable or disable message buffering
     * 
     * If a message is buffered it can be updated for the duration of the
     * request and is only flushed at the end of the request.
     * 
     * @param boolean $buffered TRUE to enable buffering FALSE otherwise
     * @return boolean Returns previous buffering value
     */
    public function setBuffered($buffered)
    {
        $previous = $this->_buffered;
        $this->_buffered = $buffered;
        return $previous;
    }

    /**
     * Determine if buffering is enabled or disabled
     * 
     * @return boolean Returns TRUE if buffering is enabled, FALSE otherwise. 
     */
    public function getBuffered()
    {
        return $this->_buffered;
    }
    
    /**
     * Destroy the message to prevent delivery
     * 
     * @param boolean $destroy TRUE to destroy FALSE otherwise
     * @return boolean Returns previous destroy value
     */
    public function setDestroy($destroy)
    {
        $previous = $this->_destroy;
        $this->_destroy = $destroy;
        return $previous;
    }
    
    /**
     * Determine if message should be destroyed
     * 
     * @return boolean Returns TRUE if message should be destroyed, FALSE otherwise. 
     */
    public function getDestroy()
    {
        return $this->_destroy;
    }

    /**
     * Set the style of the message
     * 
     * @return void
     */
    public function setStyle($style)
    {
        $this->_style = $style;
    }

    /**
     * Get the style of the message
     * 
     * @return string The style of the message
     */
    public function getStyle()
    {
        return $this->_style;
    }

    /**
     * Set the actual message to be sent in its final format.
     * 
     * @return void
     */
    public function setMessage($message)
    {
        $this->_message = $message;
    }

    /**
     * Get the actual message to be sent in its final format.
     * 
     * @return mixed Returns the message to be sent.
     */
    public function getMessage()
    {
        return $this->_message;
    }
    
    /**
     * Set a single option
     * 
     * @param  string $key The name of the option
     * @param  mixed $value The value of the option
     * @return mixed The previous value of the option
     */
    public function setOption($key, $value)
    {
      if(!array_key_exists($key,$this->_options)) {
        throw new Zend_Wildfire_Exception('Option with name "'.$key.'" does not exist!');
      }
      $previous = $this->_options[$key];
      $this->_options[$key] = $value;
      return $previous;
    }

    /**
     * Retrieve a single option
     * 
     * @param  string $key The name of the option
     * @return mixed The value of the option
     */
    public function getOption($key)
    {
      if(!array_key_exists($key,$this->_options)) {
        throw new Zend_Wildfire_Exception('Option with name "'.$key.'" does not exist!');
      }
      return $this->_options[$key];
    }

    /**
     * Retrieve all options
     * 
     * @return array All options
     */
    public function getOptions()
    {
      return $this->_options;
    }    
}

Wildfire/Plugin/FirePhp/TableMessage.php000066600000005157151256604600014172 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Wildfire
 * @subpackage Plugin
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Wildfire_Plugin_FirePhp */
require_once 'Zend/Wildfire/Plugin/FirePhp.php';

/** Zend_Wildfire_Plugin_FirePhp_Message */
require_once 'Zend/Wildfire/Plugin/FirePhp/Message.php';

/**
 * A message envelope that can be updated for the duration of the requet before
 * it gets flushed at the end of the request.
 * 
 * @category   Zend
 * @package    Zend_Wildfire
 * @subpackage Plugin
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Wildfire_Plugin_FirePhp_TableMessage extends Zend_Wildfire_Plugin_FirePhp_Message
{
    /**
     * The header of the table containing all columns
     * @var array
     */
    protected $_header = null;
    
    /**
     * The rows of the table
     * $var array
     */ 
    protected $_rows = array();
    
    /**
     * Constructor
     * 
     * @param string $label The label of the table
     */
    function __construct($label)
    {
        parent::__construct(Zend_Wildfire_Plugin_FirePhp::TABLE, null);
        $this->setLabel($label);
    }
    
    /**
     * Set the table header
     * 
     * @param array $header The header columns
     * @return void
     */
    public function setHeader($header)
    {
        $this->_header = $header;
    }
    
    /**
     * Append a row to the end of the table.
     * 
     * @param array $row An array of column values representing a row.
     * @return void
     */
    public function addRow($row)
    {
        $this->_rows[] = $row;
    }
    
    /**
     * Get the actual message to be sent in its final format.
     * 
     * @return mixed Returns the message to be sent.
     */
    public function getMessage()
    {
        $table = $this->_rows;
        array_unshift($table,$this->_header);
        return $table;
    }

}

File/Transfer/Adapter/Http.php000066600000017011151256604600012230 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: $
 */

require_once 'Zend/File/Transfer/Adapter/Abstract.php';

/**
 * File transfer adapter class for the HTTP protocol
 *
 * @category  Zend
 * @package   Zend_File_Transfer
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_File_Transfer_Adapter_Http extends Zend_File_Transfer_Adapter_Abstract
{
    /**
     * Constructor for Http File Transfers
     *
     * @param array $options OPTIONAL Options to set
     */
    public function __construct($options = array())
    {
        if (ini_get('file_uploads') == false) {
            require_once 'Zend/File/Transfer/Exception.php';
            throw new Zend_File_Transfer_Exception('File uploads are not allowed in your php config!');
        }

        $this->_files = $this->_prepareFiles($_FILES);
        $this->addValidator('Upload', false, $this->_files);

        if (is_array($options)) {
            $this->setOptions($options);
        }
    }

    /**
     * Sets a validator for the class, erasing all previous set
     *
     * @param  string|array $validator Validator to set
     * @param  string|array $files     Files to limit this validator to
     * @return Zend_File_Transfer_Adapter
     */
    public function setValidators(array $validators, $files = null)
    {
        $this->clearValidators();
        $this->addValidator('Upload', false, $this->_files);
        return $this->addValidators($validators, $files);
    }

    /**
     * Send the file to the client (Download)
     *
     * @param  string|array $options Options for the file(s) to send
     * @return void
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function send($options = null)
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Receive the file from the client (Upload)
     *
     * @param  string|array $files (Optional) Files to receive
     * @return bool
     */
    public function receive($files = null)
    {
        if (!$this->isValid($files)) {
            return false;
        }

        $check = $this->_getFiles($files);
        foreach ($check as $file => $content) {
            if (!$content['received']) {
                $directory   = '';
                $destination = $this->getDestination($file);
                if ($destination !== null) {
                    $directory = $destination . DIRECTORY_SEPARATOR;
                }

                // Should never return false when it's tested by the upload validator
                if (!move_uploaded_file($content['tmp_name'], ($directory . $content['name']))) {
                    if ($content['options']['ignoreNoFile']) {
                        $this->_files[$file]['received'] = true;
                        $this->_files[$file]['filtered'] = true;
                        continue;
                    }

                    $this->_files[$file]['received'] = false;
                    return false;
                }

                $this->_files[$file]['received'] = true;
            }

            if (!$content['filtered']) {
                if (!$this->_filter($file)) {
                    $this->_files[$file]['filtered'] = false;
                    return false;
                }

                $this->_files[$file]['filtered'] = true;
            }
        }

        return true;
    }

    /**
     * Checks if the file was already sent
     *
     * @param  string|array $file Files to check
     * @return bool
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function isSent($files = null)
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Checks if the file was already received
     *
     * @param  string|array $files (Optional) Files to check
     * @return bool
     */
    public function isReceived($files = null)
    {
        $files = $this->_getFiles($files);
        foreach ($files as $content) {
            if ($content['received'] !== true) {
                return false;
            }
        }

        return true;
    }

    /**
     * Checks if the file was already filtered
     *
     * @param  string|array $files (Optional) Files to check
     * @return bool
     */
    public function isFiltered($files = null)
    {
        $files = $this->_getFiles($files);
        foreach ($files as $content) {
            if ($content['filtered'] !== true) {
                return false;
            }
        }

        return true;
    }

    /**
     * Has a file been uploaded ?
     *
     * @param  array|string|null $file
     * @return bool
     */
    public function isUploaded($files = null)
    {
        $files = $this->_getFiles($files);
        foreach ($files as $file) {
            if (empty($file['name'])) {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns the actual progress of file up-/downloads
     *
     * @return string Returns the state
     * @return int
     * @throws Zend_File_Transfer_Exception Not implemented
     */
    public function getProgress()
    {
        require_once 'Zend/File/Transfer/Exception.php';
        throw new Zend_File_Transfer_Exception('Method not implemented');
    }

    /**
     * Prepare the $_FILES array to match the internal syntax of one file per entry
     *
     * @param  array $files
     * @return array
     */
    protected function _prepareFiles(array $files = array())
    {
        $result = array();
        foreach ($files as $form => $content) {
            if (is_array($content['name'])) {
                foreach ($content as $param => $file) {
                    foreach ($file as $number => $target) {
                        $result[$form . '_' . $number . '_'][$param]      = $target;
                        $result[$form . '_' . $number . '_']['options']   = $this->_options;
                        $result[$form . '_' . $number . '_']['validated'] = false;
                        $result[$form . '_' . $number . '_']['received']  = false;
                        $result[$form . '_' . $number . '_']['filtered']  = false;
                    }
                }
            } else {
                $result[$form]              = $content;
                $result[$form]['options']   = $this->_options;
                $result[$form]['validated'] = false;
                $result[$form]['received']  = false;
                $result[$form]['filtered']  = false;
            }
        }

        return $result;
    }
}
Config/Xml.php000066600000022274151256604600007242 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Config
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: Xml.php 14413 2009-03-21 19:30:23Z rob $
 */

/**
 * @see Zend_Config
 */
require_once 'Zend/Config.php';

/**
 * XML Adapter for Zend_Config
 *
 * @category  Zend
 * @package   Zend_Config
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Config_Xml extends Zend_Config
{
    /**
     * Wether to skip extends or not
     *
     * @var boolean
     */
    protected $_skipExtends = false;
    
    /**
     * Loads the section $section from the config file (or string $xml for
     * access facilitated by nested object properties.
     *
     * Sections are defined in the XML as children of the root element.
     *
     * In order to extend another section, a section defines the "extends"
     * attribute having a value of the section name from which the extending
     * section inherits values.
     *
     * Note that the keys in $section will override any keys of the same
     * name in the sections that have been included via "extends".
     *
     * @param  string  $filename           File to process
     * @param  mixed   $section            Section to process
     * @param  boolean $allowModifications Wether modifiacations are allowed at runtime
     * @throws Zend_Config_Exception When filename is not set
     * @throws Zend_Config_Exception When section $sectionName cannot be found in $filename
     */
    public function __construct($filename, $section = null, $options = false)
    {
        if (empty($filename)) {
            require_once 'Zend/Config/Exception.php';
            throw new Zend_Config_Exception('Filename is not set');
        }

        $allowModifications = false;
        if (is_bool($options)) {
            $allowModifications = $options;
        } elseif (is_array($options)) {
            if (isset($options['allowModifications'])) {
                $allowModifications = (bool) $options['allowModifications'];
            }
            if (isset($options['skipExtends'])) {
                $this->_skipExtends = (bool) $options['skipExtends'];
            }
        }
        
        set_error_handler(array($this, '_loadFileErrorHandler'));
        $config = simplexml_load_file($filename); // Warnings and errors are suppressed
        restore_error_handler();
        // Check if there was a error while loading file
        if ($this->_loadFileErrorStr !== null) {
            require_once 'Zend/Config/Exception.php';
            throw new Zend_Config_Exception($this->_loadFileErrorStr);
        }

        if ($section === null) {
            $dataArray = array();
            foreach ($config as $sectionName => $sectionData) {
                $dataArray[$sectionName] = $this->_processExtends($config, $sectionName);
            }

            parent::__construct($dataArray, $allowModifications);
        } else if (is_array($section)) {
            $dataArray = array();
            foreach ($section as $sectionName) {
                if (!isset($config->$sectionName)) {
                    require_once 'Zend/Config/Exception.php';
                    throw new Zend_Config_Exception("Section '$sectionName' cannot be found in $filename");
                }

                $dataArray = array_merge($this->_processExtends($config, $sectionName), $dataArray);
            }

            parent::__construct($dataArray, $allowModifications);
        } else {
            if (!isset($config->$section)) {
                require_once 'Zend/Config/Exception.php';
                throw new Zend_Config_Exception("Section '$section' cannot be found in $filename");
            }

            $dataArray = $this->_processExtends($config, $section);
            if (!is_array($dataArray)) {
                // Section in the XML file contains just one top level string
                $dataArray = array($section => $dataArray);
            }

            parent::__construct($dataArray, $allowModifications);
        }

        $this->_loadedSection = $section;
    }

    /**
     * Helper function to process each element in the section and handle
     * the "extends" inheritance attribute.
     *
     * @param  SimpleXMLElement $element XML Element to process
     * @param  string           $section Section to process
     * @param  array            $config  Configuration which was parsed yet
     * @throws Zend_Config_Exception When $section cannot be found
     * @return array
     */
    protected function _processExtends(SimpleXMLElement $element, $section, array $config = array())
    {
        if (!isset($element->$section)) {
            require_once 'Zend/Config/Exception.php';
            throw new Zend_Config_Exception("Section '$section' cannot be found");
        }

        $thisSection = $element->$section;

        if (isset($thisSection['extends'])) {
            $extendedSection = (string) $thisSection['extends'];
            $this->_assertValidExtend($section, $extendedSection);
            
            if (!$this->_skipExtends) {
                $config = $this->_processExtends($element, $extendedSection, $config);
            }
        }

        $config = $this->_arrayMergeRecursive($config, $this->_toArray($thisSection));

        return $config;
    }

    /**
     * Returns a string or an associative and possibly multidimensional array from
     * a SimpleXMLElement.
     *
     * @param  SimpleXMLElement $xmlObject Convert a SimpleXMLElement into an array
     * @return array|string
     */
    protected function _toArray(SimpleXMLElement $xmlObject)
    {
        $config = array();

        // Search for parent node values
        if (count($xmlObject->attributes()) > 0) {
            foreach ($xmlObject->attributes() as $key => $value) {
                if ($key === 'extends') {
                    continue;
                }

                $value = (string) $value;

                if (array_key_exists($key, $config)) {
                    if (!is_array($config[$key])) {
                        $config[$key] = array($config[$key]);
                    }

                    $config[$key][] = $value;
                } else {
                    $config[$key] = $value;
                }
            }
        }

        // Search for children
        if (count($xmlObject->children()) > 0) {
            foreach ($xmlObject->children() as $key => $value) {
                if (count($value->children()) > 0) {
                    $value = $this->_toArray($value);
                } else if (count($value->attributes()) > 0) {
                    $attributes = $value->attributes();
                    if (isset($attributes['value'])) {
                        $value = (string) $attributes['value'];
                    } else {
                        $value = $this->_toArray($value);
                    }
                } else {
                    $value = (string) $value;
                }

                if (array_key_exists($key, $config)) {
                    if (!is_array($config[$key]) || !array_key_exists(0, $config[$key])) {
                        $config[$key] = array($config[$key]);
                    }

                    $config[$key][] = $value;
                } else {
                    $config[$key] = $value;
                }
            }
        } else if (!isset($xmlObject['extends']) && (count($config) === 0)) {
            // Object has no children nor attributes and doesn't use the extends
            // attribute: it's a string
            $config = (string) $xmlObject;
        }

        return $config;
    }

    /**
     * Merge two arrays recursively, overwriting keys of the same name
     * in $firstArray with the value in $secondArray.
     *
     * @param  mixed $firstArray  First array
     * @param  mixed $secondArray Second array to merge into first array
     * @return array
     */
    protected function _arrayMergeRecursive($firstArray, $secondArray)
    {
        if (is_array($firstArray) && is_array($secondArray)) {
            foreach ($secondArray as $key => $value) {
                if (isset($firstArray[$key])) {
                    $firstArray[$key] = $this->_arrayMergeRecursive($firstArray[$key], $value);
                } else {
                    $firstArray[$key] = $value;
                }
            }
        } else {
            $firstArray = $secondArray;
        }

        return $firstArray;
    }
}
Config/Ini.php000066600000023420151256604600007213 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Config
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Ini.php 14412 2009-03-21 18:40:48Z dasprid $
 */


/**
 * @see Zend_Config
 */
require_once 'Zend/Config.php';


/**
 * @category   Zend
 * @package    Zend_Config
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Config_Ini extends Zend_Config
{
    /**
     * String that separates nesting levels of configuration data identifiers
     *
     * @var string
     */
    protected $_nestSeparator = '.';

    /**
     * Wether to skip extends or not
     *
     * @var boolean
     */
    protected $_skipExtends = false;
    
    /**
     * Loads the section $section from the config file $filename for
     * access facilitated by nested object properties.
     *
     * If the section name contains a ":" then the section name to the right
     * is loaded and included into the properties. Note that the keys in
     * this $section will override any keys of the same
     * name in the sections that have been included via ":".
     *
     * If the $section is null, then all sections in the ini file are loaded.
     *
     * If any key includes a ".", then this will act as a separator to
     * create a sub-property.
     *
     * example ini file:
     *      [all]
     *      db.connection = database
     *      hostname = live
     *
     *      [staging : all]
     *      hostname = staging
     *
     * after calling $data = new Zend_Config_Ini($file, 'staging'); then
     *      $data->hostname === "staging"
     *      $data->db->connection === "database"
     *
     * The $options parameter may be provided as either a boolean or an array.
     * If provided as a boolean, this sets the $allowModifications option of
     * Zend_Config. If provided as an array, there are two configuration
     * directives that may be set. For example:
     *
     * $options = array(
     *     'allowModifications' => false,
     *     'nestSeparator'      => '->'
     *      );
     *
     * @param  string        $filename
     * @param  string|null   $section
     * @param  boolean|array $options
     * @throws Zend_Config_Exception
     * @return void
     */
    public function __construct($filename, $section = null, $options = false)
    {
        if (empty($filename)) {
            /**
             * @see Zend_Config_Exception
             */
            require_once 'Zend/Config/Exception.php';
            throw new Zend_Config_Exception('Filename is not set');
        }

        $allowModifications = false;
        if (is_bool($options)) {
            $allowModifications = $options;
        } elseif (is_array($options)) {
            if (isset($options['allowModifications'])) {
                $allowModifications = (bool) $options['allowModifications'];
            }
            if (isset($options['nestSeparator'])) {
                $this->_nestSeparator = (string) $options['nestSeparator'];
            }
            if (isset($options['skipExtends'])) {
                $this->_skipExtends = (bool) $options['skipExtends'];
            }
        }

        set_error_handler(array($this, '_loadFileErrorHandler'));
        $iniArray = parse_ini_file($filename, true); // Warnings and errors are suppressed
        restore_error_handler();
        // Check if there was a error while loading file
        if ($this->_loadFileErrorStr !== null) {
            /**
             * @see Zend_Config_Exception
             */
            require_once 'Zend/Config/Exception.php';
            throw new Zend_Config_Exception($this->_loadFileErrorStr);
        }
        
        $preProcessedArray = array();
        foreach ($iniArray as $key => $data)
        {
            $bits = explode(':', $key);
            $thisSection = trim($bits[0]);
            switch (count($bits)) {
                case 1:
                    $preProcessedArray[$thisSection] = $data;
                    break;

                case 2:
                    $extendedSection = trim($bits[1]);
                    $preProcessedArray[$thisSection] = array_merge(array(';extends'=>$extendedSection), $data);
                    break;

                default:
                    /**
                     * @see Zend_Config_Exception
                     */
                    require_once 'Zend/Config/Exception.php';
                    throw new Zend_Config_Exception("Section '$thisSection' may not extend multiple sections in $filename");
            }
        }

        if (null === $section) {
            $dataArray = array();
            foreach ($preProcessedArray as $sectionName => $sectionData) {
                if(!is_array($sectionData)) {
                    $dataArray = array_merge_recursive($dataArray, $this->_processKey(array(), $sectionName, $sectionData));
                } else {
                    $dataArray[$sectionName] = $this->_processExtends($preProcessedArray, $sectionName);
                }
            }
            parent::__construct($dataArray, $allowModifications);
        } elseif (is_array($section)) {
            $dataArray = array();
            foreach ($section as $sectionName) {
                if (!isset($preProcessedArray[$sectionName])) {
                    /**
                     * @see Zend_Config_Exception
                     */
                    require_once 'Zend/Config/Exception.php';
                    throw new Zend_Config_Exception("Section '$sectionName' cannot be found in $filename");
                }
                $dataArray = array_merge($this->_processExtends($preProcessedArray, $sectionName), $dataArray);

            }
            parent::__construct($dataArray, $allowModifications);
        } else {
            if (!isset($preProcessedArray[$section])) {
                /**
                 * @see Zend_Config_Exception
                 */
                require_once 'Zend/Config/Exception.php';
                throw new Zend_Config_Exception("Section '$section' cannot be found in $filename");
            }
            parent::__construct($this->_processExtends($preProcessedArray, $section), $allowModifications);
        }

        $this->_loadedSection = $section;
    }
    
    /**
     * Helper function to process each element in the section and handle
     * the "extends" inheritance keyword. Passes control to _processKey()
     * to handle the "dot" sub-property syntax in each key.
     *
     * @param  array  $iniArray
     * @param  string $section
     * @param  array  $config
     * @throws Zend_Config_Exception
     * @return array
     */
    protected function _processExtends($iniArray, $section, $config = array())
    {
        $thisSection = $iniArray[$section];

        foreach ($thisSection as $key => $value) {
            if (strtolower($key) == ';extends') {
                if (isset($iniArray[$value])) {
                    $this->_assertValidExtend($section, $value);
                    
                    if (!$this->_skipExtends) {
                        $config = $this->_processExtends($iniArray, $value, $config);
                    }
                } else {
                    /**
                     * @see Zend_Config_Exception
                     */
                    require_once 'Zend/Config/Exception.php';
                    throw new Zend_Config_Exception("Section '$section' cannot be found");
                }
            } else {
                $config = $this->_processKey($config, $key, $value);
            }
        }
        return $config;
    }

    /**
     * Assign the key's value to the property list. Handle the "dot"
     * notation for sub-properties by passing control to
     * processLevelsInKey().
     *
     * @param  array  $config
     * @param  string $key
     * @param  string $value
     * @throws Zend_Config_Exception
     * @return array
     */
    protected function _processKey($config, $key, $value)
    {
        if (strpos($key, $this->_nestSeparator) !== false) {
            $pieces = explode($this->_nestSeparator, $key, 2);
            if (strlen($pieces[0]) && strlen($pieces[1])) {
                if (!isset($config[$pieces[0]])) {
                    $config[$pieces[0]] = array();
                } elseif (!is_array($config[$pieces[0]])) {
                    /**
                     * @see Zend_Config_Exception
                     */
                    require_once 'Zend/Config/Exception.php';
                    throw new Zend_Config_Exception("Cannot create sub-key for '{$pieces[0]}' as key already exists");
                }
                $config[$pieces[0]] = $this->_processKey($config[$pieces[0]], $pieces[1], $value);
            } else {
                /**
                 * @see Zend_Config_Exception
                 */
                require_once 'Zend/Config/Exception.php';
                throw new Zend_Config_Exception("Invalid key '$key'");
            }
        } else {
            $config[$key] = $value;
        }
        return $config;
    }
}
Config/Writer.php000066600000005067151256604600007757 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Config
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Writer.php 12220 2008-10-31 20:13:55Z dasprid $
 */

/**
 * @category   Zend
 * @package    Zend_Config
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Config_Writer
{
    /**
     * Option keys to skip when calling setOptions()
     * 
     * @var array
     */
    protected $_skipOptions = array(
        'options'
    );
    
    /**
     * Config object to write
     *
     * @var Zend_Config
     */
    protected $_config = null;

    /**
     * Create a new adapter
     * 
     * $options can only be passed as array or be omitted 
     *
     * @param null|array $options
     */
    public function __construct(array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }
    
    /**
     * Set options via a Zend_Config instance
     *
     * @param  Zend_Config $config
     * @return Zend_Config_Writer
     */
    public function setConfig(Zend_Config $config)
    {
        $this->_config = $config;
        
        return $this;
    }
    
    /**
     * Set options via an array
     *
     * @param  array $options
     * @return Zend_Config_Writer
     */
    public function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            if (in_array(strtolower($key), $this->_skipOptions)) {
                continue;
            }

            $method = 'set' . ucfirst($key);
            if (method_exists($this, $method)) {
                $this->$method($value);
            }
        }
        
        return $this;
    }
    
    /**
     * Write a Zend_Config object to it's target
     *
     * @return void
     */
    abstract public function write();
}
Measure/Viscosity/Kinematic.php000066600000013573151256604600012600 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Measure
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: Kinematic.php 9508 2008-05-23 10:56:41Z thomas $
 */

/**
 * Implement needed classes
 */
require_once 'Zend/Measure/Exception.php';
require_once 'Zend/Measure/Abstract.php';
require_once 'Zend/Locale.php';

/**
 * Class for handling acceleration conversions
 *
 * @category   Zend
 * @package    Zend_Measure
 * @subpackage Zend_Measure_Viscosity_Kinematic
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Measure_Viscosity_Kinematic extends Zend_Measure_Abstract
{
    const STANDARD = 'SQUARE_METER_PER_SECOND';

    const CENTISTOKES                     = 'CENTISTOKES';
    const LENTOR                          = 'LENTOR';
    const LITER_PER_CENTIMETER_DAY        = 'LITER_PER_CENTIMETER_DAY';
    const LITER_PER_CENTIMETER_HOUR       = 'LITER_PER_CENTIMETER_HOUR';
    const LITER_PER_CENTIMETER_MINUTE     = 'LITER_PER_CENTIMETER_MINUTE';
    const LITER_PER_CENTIMETER_SECOND     = 'LITER_PER_CENTIMETER_SECOND';
    const POISE_CUBIC_CENTIMETER_PER_GRAM = 'POISE_CUBIC_CENTIMETER_PER_GRAM';
    const SQUARE_CENTIMETER_PER_DAY       = 'SQUARE_CENTIMETER_PER_DAY';
    const SQUARE_CENTIMETER_PER_HOUR      = 'SQUARE_CENTIMETER_PER_HOUR';
    const SQUARE_CENTIMETER_PER_MINUTE    = 'SQUARE_CENTIMETER_PER_MINUTE';
    const SQUARE_CENTIMETER_PER_SECOND    = 'SQUARE_CENTIMETER_PER_SECOND';
    const SQUARE_FOOT_PER_DAY             = 'SQUARE_FOOT_PER_DAY';
    const SQUARE_FOOT_PER_HOUR            = 'SQUARE_FOOT_PER_HOUR';
    const SQUARE_FOOT_PER_MINUTE          = 'SQUARE_FOOT_PER_MINUTE';
    const SQUARE_FOOT_PER_SECOND          = 'SQUARE_FOOT_PER_SECOND';
    const SQUARE_INCH_PER_DAY             = 'SQUARE_INCH_PER_DAY';
    const SQUARE_INCH_PER_HOUR            = 'SQUARE_INCH_PER_HOUR';
    const SQUARE_INCH_PER_MINUTE          = 'SQUARE_INCH_PER_MINUTE';
    const SQUARE_INCH_PER_SECOND          = 'SQUARE_INCH_PER_SECOND';
    const SQUARE_METER_PER_DAY            = 'SQUARE_METER_PER_DAY';
    const SQUARE_METER_PER_HOUR           = 'SQUARE_METER_PER_HOUR';
    const SQUARE_METER_PER_MINUTE         = 'SQUARE_METER_PER_MINUTE';
    const SQUARE_METER_PER_SECOND         = 'SQUARE_METER_PER_SECOND';
    const SQUARE_MILLIMETER_PER_DAY       = 'SQUARE_MILLIMETER_PER_DAY';
    const SQUARE_MILLIMETER_PER_HOUR      = 'SQUARE_MILLIMETER_PER_HOUR';
    const SQUARE_MILLIMETER_PER_MINUTE    = 'SQUARE_MILLIMETER_PER_MINUTE';
    const SQUARE_MILLIMETER_PER_SECOND    = 'SQUARE_MILLIMETER_PER_SECOND';
    const STOKES                          = 'STOKES';

    /**
     * Calculations for all kinematic viscosity units
     *
     * @var array
     */
    protected $_units = array(
        'CENTISTOKES'                  => array('0.000001',        'cSt'),
        'LENTOR'                       => array('0.0001',          'lentor'),
        'LITER_PER_CENTIMETER_DAY'     => array(array('' => '1', '/' => '864000'), 'l/cm day'),
        'LITER_PER_CENTIMETER_HOUR'    => array(array('' => '1', '/' => '36000'),  'l/cm h'),
        'LITER_PER_CENTIMETER_MINUTE'  => array(array('' => '1', '/' => '600'),    'l/cm m'),
        'LITER_PER_CENTIMETER_SECOND'  => array('0.1',             'l/cm s'),
        'POISE_CUBIC_CENTIMETER_PER_GRAM' => array('0.0001',       'P cm³/g'),
        'SQUARE_CENTIMETER_PER_DAY'    => array(array('' => '1', '/' => '864000000'),'cm²/day'),
        'SQUARE_CENTIMETER_PER_HOUR'   => array(array('' => '1', '/' => '36000000'),'cm²/h'),
        'SQUARE_CENTIMETER_PER_MINUTE' => array(array('' => '1', '/' => '600000'),'cm²/m'),
        'SQUARE_CENTIMETER_PER_SECOND' => array('0.0001',          'cm²/s'),
        'SQUARE_FOOT_PER_DAY'          => array('0.0000010752667', 'ft²/day'),
        'SQUARE_FOOT_PER_HOUR'         => array('0.0000258064',    'ft²/h'),
        'SQUARE_FOOT_PER_MINUTE'       => array('0.001548384048',  'ft²/m'),
        'SQUARE_FOOT_PER_SECOND'       => array('0.09290304',      'ft²/s'),
        'SQUARE_INCH_PER_DAY'          => array('7.4671296e-9',    'in²/day'),
        'SQUARE_INCH_PER_HOUR'         => array('0.00000017921111', 'in²/h'),
        'SQUARE_INCH_PER_MINUTE'       => array('0.000010752667',  'in²/m'),
        'SQUARE_INCH_PER_SECOND'       => array('0.00064516',      'in²/s'),
        'SQUARE_METER_PER_DAY'         => array(array('' => '1', '/' => '86400'), 'm²/day'),
        'SQUARE_METER_PER_HOUR'        => array(array('' => '1', '/' => '3600'),  'm²/h'),
        'SQUARE_METER_PER_MINUTE'      => array(array('' => '1', '/' => '60'),    'm²/m'),
        'SQUARE_METER_PER_SECOND'      => array('1',               'm²/s'),
        'SQUARE_MILLIMETER_PER_DAY'    => array(array('' => '1', '/' => '86400000000'), 'mm²/day'),
        'SQUARE_MILLIMETER_PER_HOUR'   => array(array('' => '1', '/' => '3600000000'),  'mm²/h'),
        'SQUARE_MILLIMETER_PER_MINUTE' => array(array('' => '1', '/' => '60000000'),    'mm²/m'),
        'SQUARE_MILLIMETER_PER_SECOND' => array('0.000001',        'mm²/s'),
        'STOKES'                       => array('0.0001',          'St'),
        'STANDARD'                     => 'SQUARE_METER_PER_SECOND'
    );
}
Auth/Adapter/InfoCard.php000066600000020442151256604600011236 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: InfoCard.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * @see Zend_Auth_Adapter_Interface
 */
require_once 'Zend/Auth/Adapter/Interface.php';

/**
 * @see Zend_Auth_Result
 */
require_once 'Zend/Auth/Result.php';

/**
 * @see Zend_InfoCard
 */
require_once 'Zend/InfoCard.php';

/**
 * A Zend_Auth Authentication Adapter allowing the use of Information Cards as an
 * authentication mechanism
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Auth_Adapter_InfoCard implements Zend_Auth_Adapter_Interface
{
    /**
     * The XML Token being authenticated
     *
     * @var string
     */
    protected $_xmlToken;

    /**
     * The instance of Zend_InfoCard
     *
     * @var Zend_InfoCard
     */
    protected $_infoCard;

    /**
     * Constructor
     *
     * @param  string $strXmlDocument The XML Token provided by the client
     * @return void
     */
    public function __construct($strXmlDocument)
    {
        $this->_xmlToken = $strXmlDocument;
        $this->_infoCard = new Zend_InfoCard();
    }

    /**
     * Sets the InfoCard component Adapter to use
     *
     * @param  Zend_InfoCard_Adapter_Interface $a
     * @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
     */
    public function setAdapter(Zend_InfoCard_Adapter_Interface $a)
    {
        $this->_infoCard->setAdapter($a);
        return $this;
    }

    /**
     * Retrieves the InfoCard component adapter being used
     *
     * @return Zend_InfoCard_Adapter_Interface
     */
    public function getAdapter()
    {
        return $this->_infoCard->getAdapter();
    }

    /**
     * Retrieves the InfoCard public key cipher object being used
     *
     * @return Zend_InfoCard_Cipher_PKI_Interface
     */
    public function getPKCipherObject()
    {
        return $this->_infoCard->getPKCipherObject();
    }

    /**
     * Sets the InfoCard public key cipher object to use
     *
     * @param  Zend_InfoCard_Cipher_PKI_Interface $cipherObj
     * @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
     */
    public function setPKICipherObject(Zend_InfoCard_Cipher_PKI_Interface $cipherObj)
    {
        $this->_infoCard->setPKICipherObject($cipherObj);
        return $this;
    }

    /**
     * Retrieves the Symmetric cipher object being used
     *
     * @return Zend_InfoCard_Cipher_Symmetric_Interface
     */
    public function getSymCipherObject()
    {
        return $this->_infoCard->getSymCipherObject();
    }

    /**
     * Sets the InfoCard symmetric cipher object to use
     *
     * @param  Zend_InfoCard_Cipher_Symmetric_Interface $cipherObj
     * @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
     */
    public function setSymCipherObject(Zend_InfoCard_Cipher_Symmetric_Interface $cipherObj)
    {
        $this->_infoCard->setSymCipherObject($cipherObj);
        return $this;
    }

    /**
     * Remove a Certificate Pair by Key ID from the search list
     *
     * @param  string $key_id The Certificate Key ID returned from adding the certificate pair
     * @throws Zend_InfoCard_Exception
     * @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
     */
    public function removeCertificatePair($key_id)
    {
        $this->_infoCard->removeCertificatePair($key_id);
        return $this;
    }

    /**
     * Add a Certificate Pair to the list of certificates searched by the component
     *
     * @param  string $private_key_file    The path to the private key file for the pair
     * @param  string $public_key_file     The path to the certificate / public key for the pair
     * @param  string $type                (optional) The URI for the type of key pair this is (default RSA with OAEP padding)
     * @param  string $password            (optional) The password for the private key file if necessary
     * @throws Zend_InfoCard_Exception
     * @return string A key ID representing this key pair in the component
     */
    public function addCertificatePair($private_key_file, $public_key_file, $type = Zend_InfoCard_Cipher::ENC_RSA_OAEP_MGF1P, $password = null)
    {
        return $this->_infoCard->addCertificatePair($private_key_file, $public_key_file, $type, $password);
    }

    /**
     * Return a Certificate Pair from a key ID
     *
     * @param  string $key_id The Key ID of the certificate pair in the component
     * @throws Zend_InfoCard_Exception
     * @return array An array containing the path to the private/public key files,
     *               the type URI and the password if provided
     */
    public function getCertificatePair($key_id)
    {
        return $this->_infoCard->getCertificatePair($key_id);
    }

    /**
     * Set the XML Token to be processed
     *
     * @param  string $strXmlToken The XML token to process
     * @return Zend_Auth_Adapter_InfoCard Provides a fluent interface
     */
    public function setXmlToken($strXmlToken)
    {
        $this->_xmlToken = $strXmlToken;
        return $this;
    }

    /**
     * Get the XML Token being processed
     *
     * @return string The XML token to be processed
     */
    public function getXmlToken()
    {
        return $this->_xmlToken;
    }

    /**
     * Authenticates the XML token
     *
     * @return Zend_Auth_Result The result of the authentication
     */
    public function authenticate()
    {
        try {
            $claims = $this->_infoCard->process($this->getXmlToken());
        } catch(Exception $e) {
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE , null, array('Exception Thrown',
                                                                                $e->getMessage(),
                                                                                $e->getTraceAsString(),
                                                                                serialize($e)));
        }

        if(!$claims->isValid()) {
            switch($claims->getCode()) {
                case Zend_infoCard_Claims::RESULT_PROCESSING_FAILURE:
                    return new Zend_Auth_Result(
                        Zend_Auth_Result::FAILURE,
                        $claims,
                        array(
                            'Processing Failure',
                            $claims->getErrorMsg()
                        )
                    );
                    break;
                case Zend_InfoCard_Claims::RESULT_VALIDATION_FAILURE:
                    return new Zend_Auth_Result(
                        Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
                        $claims,
                        array(
                            'Validation Failure',
                            $claims->getErrorMsg()
                        )
                    );
                    break;
                default:
                    return new Zend_Auth_Result(
                        Zend_Auth_Result::FAILURE,
                        $claims,
                        array(
                            'Unknown Failure',
                            $claims->getErrorMsg()
                        )
                    );
                    break;
            }
        }

        return new Zend_Auth_Result(
            Zend_Auth_Result::SUCCESS,
            $claims
        );
    }
}
Auth/Adapter/DbTable.php000066600000036755151256604600011064 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: DbTable.php 13202 2008-12-13 19:53:44Z sidhighwind $
 */


/**
 * @see Zend_Auth_Adapter_Interface
 */
require_once 'Zend/Auth/Adapter/Interface.php';

/**
 * @see Zend_Db_Adapter_Abstract
 */
require_once 'Zend/Db/Adapter/Abstract.php';

/**
 * @see Zend_Auth_Result
 */
require_once 'Zend/Auth/Result.php';


/**
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Auth_Adapter_DbTable implements Zend_Auth_Adapter_Interface
{
    /**
     * Database Connection
     *
     * @var Zend_Db_Adapter_Abstract
     */
    protected $_zendDb = null;

    /**
     * $_tableName - the table name to check
     *
     * @var string
     */
    protected $_tableName = null;

    /**
     * $_identityColumn - the column to use as the identity
     *
     * @var string
     */
    protected $_identityColumn = null;

    /**
     * $_credentialColumns - columns to be used as the credentials
     *
     * @var string
     */
    protected $_credentialColumn = null;

    /**
     * $_identity - Identity value
     *
     * @var string
     */
    protected $_identity = null;

    /**
     * $_credential - Credential values
     *
     * @var string
     */
    protected $_credential = null;

    /**
     * $_credentialTreatment - Treatment applied to the credential, such as MD5() or PASSWORD()
     *
     * @var string
     */
    protected $_credentialTreatment = null;

    /**
     * $_authenticateResultInfo
     *
     * @var array
     */
    protected $_authenticateResultInfo = null;

    /**
     * $_resultRow - Results of database authentication query
     *
     * @var array
     */
    protected $_resultRow = null;

    /**
     * __construct() - Sets configuration options
     *
     * @param  Zend_Db_Adapter_Abstract $zendDb
     * @param  string                   $tableName
     * @param  string                   $identityColumn
     * @param  string                   $credentialColumn
     * @param  string                   $credentialTreatment
     * @return void
     */
    public function __construct(Zend_Db_Adapter_Abstract $zendDb, $tableName = null, $identityColumn = null,
                                $credentialColumn = null, $credentialTreatment = null)
    {
        $this->_zendDb = $zendDb;

        if (null !== $tableName) {
            $this->setTableName($tableName);
        }

        if (null !== $identityColumn) {
            $this->setIdentityColumn($identityColumn);
        }

        if (null !== $credentialColumn) {
            $this->setCredentialColumn($credentialColumn);
        }

        if (null !== $credentialTreatment) {
            $this->setCredentialTreatment($credentialTreatment);
        }
    }

    /**
     * setTableName() - set the table name to be used in the select query
     *
     * @param  string $tableName
     * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
     */
    public function setTableName($tableName)
    {
        $this->_tableName = $tableName;
        return $this;
    }

    /**
     * setIdentityColumn() - set the column name to be used as the identity column
     *
     * @param  string $identityColumn
     * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
     */
    public function setIdentityColumn($identityColumn)
    {
        $this->_identityColumn = $identityColumn;
        return $this;
    }

    /**
     * setCredentialColumn() - set the column name to be used as the credential column
     *
     * @param  string $credentialColumn
     * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
     */
    public function setCredentialColumn($credentialColumn)
    {
        $this->_credentialColumn = $credentialColumn;
        return $this;
    }

    /**
     * setCredentialTreatment() - allows the developer to pass a parameterized string that is
     * used to transform or treat the input credential data
     *
     * In many cases, passwords and other sensitive data are encrypted, hashed, encoded,
     * obscured, or otherwise treated through some function or algorithm. By specifying a
     * parameterized treatment string with this method, a developer may apply arbitrary SQL
     * upon input credential data.
     *
     * Examples:
     *
     *  'PASSWORD(?)'
     *  'MD5(?)'
     *
     * @param  string $treatment
     * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
     */
    public function setCredentialTreatment($treatment)
    {
        $this->_credentialTreatment = $treatment;
        return $this;
    }

    /**
     * setIdentity() - set the value to be used as the identity
     *
     * @param  string $value
     * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
     */
    public function setIdentity($value)
    {
        $this->_identity = $value;
        return $this;
    }

    /**
     * setCredential() - set the credential value to be used, optionally can specify a treatment
     * to be used, should be supplied in parameterized form, such as 'MD5(?)' or 'PASSWORD(?)'
     *
     * @param  string $credential
     * @return Zend_Auth_Adapter_DbTable Provides a fluent interface
     */
    public function setCredential($credential)
    {
        $this->_credential = $credential;
        return $this;
    }

    /**
     * getResultRowObject() - Returns the result row as a stdClass object
     *
     * @param  string|array $returnColumns
     * @param  string|array $omitColumns
     * @return stdClass|boolean
     */
    public function getResultRowObject($returnColumns = null, $omitColumns = null)
    {
        if (!$this->_resultRow) {
            return false;
        }

        $returnObject = new stdClass();

        if (null !== $returnColumns) {

            $availableColumns = array_keys($this->_resultRow);
            foreach ( (array) $returnColumns as $returnColumn) {
                if (in_array($returnColumn, $availableColumns)) {
                    $returnObject->{$returnColumn} = $this->_resultRow[$returnColumn];
                }
            }
            return $returnObject;

        } elseif (null !== $omitColumns) {

            $omitColumns = (array) $omitColumns;
            foreach ($this->_resultRow as $resultColumn => $resultValue) {
                if (!in_array($resultColumn, $omitColumns)) {
                    $returnObject->{$resultColumn} = $resultValue;
                }
            }
            return $returnObject;

        } else {

            foreach ($this->_resultRow as $resultColumn => $resultValue) {
                $returnObject->{$resultColumn} = $resultValue;
            }
            return $returnObject;

        }
    }

    /**
     * authenticate() - defined by Zend_Auth_Adapter_Interface.  This method is called to
     * attempt an authenication.  Previous to this call, this adapter would have already
     * been configured with all nessissary information to successfully connect to a database
     * table and attempt to find a record matching the provided identity.
     *
     * @throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {
        $this->_authenticateSetup();
        $dbSelect = $this->_authenticateCreateSelect();
        $resultIdentities = $this->_authenticateQuerySelect($dbSelect);

        if ( ($authResult = $this->_authenticateValidateResultset($resultIdentities)) instanceof Zend_Auth_Result) {
            return $authResult;
        }

        $authResult = $this->_authenticateValidateResult(array_shift($resultIdentities));
        return $authResult;
    }

    /**
     * _authenticateSetup() - This method abstracts the steps involved with making sure
     * that this adapter was indeed setup properly with all required peices of information.
     *
     * @throws Zend_Auth_Adapter_Exception - in the event that setup was not done properly
     * @return true
     */
    protected function _authenticateSetup()
    {
        $exception = null;

        if ($this->_tableName == '') {
            $exception = 'A table must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
        } elseif ($this->_identityColumn == '') {
            $exception = 'An identity column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
        } elseif ($this->_credentialColumn == '') {
            $exception = 'A credential column must be supplied for the Zend_Auth_Adapter_DbTable authentication adapter.';
        } elseif ($this->_identity == '') {
            $exception = 'A value for the identity was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
        } elseif ($this->_credential === null) {
            $exception = 'A credential value was not provided prior to authentication with Zend_Auth_Adapter_DbTable.';
        }

        if (null !== $exception) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception($exception);
        }

        $this->_authenticateResultInfo = array(
            'code'     => Zend_Auth_Result::FAILURE,
            'identity' => $this->_identity,
            'messages' => array()
            );

        return true;
    }

    /**
     * _authenticateCreateSelect() - This method creates a Zend_Db_Select object that
     * is completely configured to be queried against the database.
     *
     * @return Zend_Db_Select
     */
    protected function _authenticateCreateSelect()
    {
        // build credential expression
        if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, '?') === false)) {
            $this->_credentialTreatment = '?';
        }

        $credentialExpression = new Zend_Db_Expr(
            '(CASE WHEN ' .
            $this->_zendDb->quoteInto(
                $this->_zendDb->quoteIdentifier($this->_credentialColumn, true)
                . ' = ' . $this->_credentialTreatment, $this->_credential
                )
            . ' THEN 1 ELSE 0 END) AS '
            . $this->_zendDb->quoteIdentifier('zend_auth_credential_match')
            );

        // get select
        $dbSelect = $this->_zendDb->select();
        $dbSelect->from($this->_tableName, array('*', $credentialExpression))
                 ->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity);

        return $dbSelect;
    }

    /**
     * _authenticateQuerySelect() - This method accepts a Zend_Db_Select object and
     * performs a query against the database with that object.
     *
     * @param Zend_Db_Select $dbSelect
     * @throws Zend_Auth_Adapter_Exception - when a invalid select object is encoutered
     * @return array
     */
    protected function _authenticateQuerySelect(Zend_Db_Select $dbSelect)
    {
        try {
            if ($this->_zendDb->getFetchMode() != Zend_DB::FETCH_ASSOC) {
                $origDbFetchMode = $this->_zendDb->getFetchMode();
                $this->_zendDb->setFetchMode(Zend_DB::FETCH_ASSOC);
            }
            $resultIdentities = $this->_zendDb->fetchAll($dbSelect->__toString());
            if (isset($origDbFetchMode)) {
                $this->_zendDb->setFetchMode($origDbFetchMode);
                unset($origDbFetchMode);
            }
        } catch (Exception $e) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('The supplied parameters to Zend_Auth_Adapter_DbTable failed to '
                                                . 'produce a valid sql statement, please check table and column names '
                                                . 'for validity.');
        }
        return $resultIdentities;
    }

    /**
     * _authenticateValidateResultSet() - This method attempts to make certian that only one
     * record was returned in the result set
     *
     * @param array $resultIdentities
     * @return true|Zend_Auth_Result
     */
    protected function _authenticateValidateResultSet(array $resultIdentities)
    {


        if (count($resultIdentities) < 1) {
            $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
            $this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.';
            return $this->_authenticateCreateAuthResult();
        } elseif (count($resultIdentities) > 1) {
            $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
            $this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.';
            return $this->_authenticateCreateAuthResult();
        }

        return true;
    }

    /**
     * _authenticateValidateResult() - This method attempts to validate that the record in the
     * result set is indeed a record that matched the identity provided to this adapter.
     *
     * @param array $resultIdentity
     * @return Zend_Auth_Result
     */
    protected function _authenticateValidateResult($resultIdentity)
    {
        if ($resultIdentity['zend_auth_credential_match'] != '1') {
            $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
            $this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
            return $this->_authenticateCreateAuthResult();
        }

        unset($resultIdentity['zend_auth_credential_match']);
        $this->_resultRow = $resultIdentity;

        $this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS;
        $this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
        return $this->_authenticateCreateAuthResult();
    }

    /**
     * _authenticateCreateAuthResult() - This method creates a Zend_Auth_Result object
     * from the information that has been collected during the authenticate() attempt.
     *
     * @return Zend_Auth_Result
     */
    protected function _authenticateCreateAuthResult()
    {
        return new Zend_Auth_Result(
            $this->_authenticateResultInfo['code'],
            $this->_authenticateResultInfo['identity'],
            $this->_authenticateResultInfo['messages']
            );
    }

}
Auth/Adapter/Http/Resolver/File.php000066600000013524151256604600013153 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter_Http
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: File.php 8862 2008-03-16 15:36:00Z thomas $
 */


/**
 * @see Zend_Auth_Adapter_Http_Resolver_Interface
 */
require_once 'Zend/Auth/Adapter/Http/Resolver/Interface.php';


/**
 * HTTP Authentication File Resolver
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter_Http
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Auth_Adapter_Http_Resolver_File implements Zend_Auth_Adapter_Http_Resolver_Interface
{
    /**
     * Path to credentials file
     *
     * @var string
     */
    protected $_file;

    /**
     * Constructor
     *
     * @param  string $path Complete filename where the credentials are stored
     * @return void
     */
    public function __construct($path = '')
    {
        if (!empty($path)) {
            $this->setFile($path);
        }
    }

    /**
     * Set the path to the credentials file
     *
     * @param  string $path
     * @throws Zend_Auth_Adapter_Http_Resolver_Exception
     * @return Zend_Auth_Adapter_Http_Resolver_File Provides a fluent interface
     */
    public function setFile($path)
    {
        if (empty($path) || !is_readable($path)) {
            /**
             * @see Zend_Auth_Adapter_Http_Resolver_Exception
             */
            require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Path not readable: ' . $path);
        }
        $this->_file = $path;

        return $this;
    }

    /**
     * Returns the path to the credentials file
     *
     * @return string
     */
    public function getFile()
    {
        return $this->_file;
    }

    /**
     * Resolve credentials
     *
     * Only the first matching username/realm combination in the file is
     * returned. If the file contains credentials for Digest authentication,
     * the returned string is the password hash, or h(a1) from RFC 2617. The
     * returned string is the plain-text password for Basic authentication.
     *
     * The expected format of the file is:
     *   username:realm:sharedSecret
     *
     * That is, each line consists of the user's username, the applicable
     * authentication realm, and the password or hash, each delimited by
     * colons.
     *
     * @param  string $username Username
     * @param  string $realm    Authentication Realm
     * @throws Zend_Auth_Adapter_Http_Resolver_Exception
     * @return string|false User's shared secret, if the user is found in the
     *         realm, false otherwise.
     */
    public function resolve($username, $realm)
    {
        if (empty($username)) {
            /**
             * @see Zend_Auth_Adapter_Http_Resolver_Exception
             */
            require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username is required');
        } else if (!ctype_print($username) || strpos($username, ':') !== false) {
            /**
             * @see Zend_Auth_Adapter_Http_Resolver_Exception
             */
            require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Username must consist only of printable characters, '
                                                              . 'excluding the colon');
        }
        if (empty($realm)) {
            /**
             * @see Zend_Auth_Adapter_Http_Resolver_Exception
             */
            require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm is required');
        } else if (!ctype_print($realm) || strpos($realm, ':') !== false) {
            /**
             * @see Zend_Auth_Adapter_Http_Resolver_Exception
             */
            require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Realm must consist only of printable characters, '
                                                              . 'excluding the colon.');
        }

        // Open file, read through looking for matching credentials
        $fp = @fopen($this->_file, 'r');
        if (!$fp) {
            /**
             * @see Zend_Auth_Adapter_Http_Resolver_Exception
             */
            require_once 'Zend/Auth/Adapter/Http/Resolver/Exception.php';
            throw new Zend_Auth_Adapter_Http_Resolver_Exception('Unable to open password file: ' . $this->_file);
        }

        // No real validation is done on the contents of the password file. The
        // assumption is that we trust the administrators to keep it secure.
        while (($line = fgetcsv($fp, 512, ':')) !== false) {
            if ($line[0] == $username && $line[1] == $realm) {
                $password = $line[2];
                fclose($fp);
                return $password;
            }
        }

        fclose($fp);
        return false;
    }
}
Auth/Adapter/Http/Resolver/Interface.php000066600000003143151256604600014170 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter_Http
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 8862 2008-03-16 15:36:00Z thomas $
 */


/**
 * Auth HTTP Resolver Interface
 *
 * Defines an interace to resolve a username/realm combination into a shared
 * secret usable by HTTP Authentication.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter_Http
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_Auth_Adapter_Http_Resolver_Interface
{
    /**
     * Resolve username/realm to password/hash/etc.
     *
     * @param  string $username Username
     * @param  string $realm    Authentication Realm
     * @return string|false User's shared secret, if the user is found in the
     *         realm, false otherwise.
     */
    public function resolve($username, $realm);
}
Auth/Adapter/Http/Resolver/Exception.php000066600000002372151256604600014231 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter_Http
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8862 2008-03-16 15:36:00Z thomas $
 */


/**
 * @see Zend_Auth_Exception
 */
require_once 'Zend/Auth/Exception.php';


/**
 * HTTP Auth Resolver Exception
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter_Http
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Auth_Adapter_Http_Resolver_Exception extends Zend_Auth_Exception
{}
Auth/Storage/Exception.php000066600000002275151256604600011537 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 9101 2008-03-30 19:54:38Z thomas $
 */


/**
 * @see Zend_Auth_Exception
 */
require_once 'Zend/Auth/Exception.php';


/**
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Auth_Storage_Exception extends Zend_Auth_Exception
{}
Auth/Result.php000066600000007167151256604600007460 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Auth
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Result.php 8862 2008-03-16 15:36:00Z thomas $
 */


/**
 * @category   Zend
 * @package    Zend_Auth
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Auth_Result
{
    /**
     * General Failure
     */
    const FAILURE                        =  0;

    /**
     * Failure due to identity not being found.
     */
    const FAILURE_IDENTITY_NOT_FOUND     = -1;

    /**
     * Failure due to identity being ambiguous.
     */
    const FAILURE_IDENTITY_AMBIGUOUS     = -2;

    /**
     * Failure due to invalid credential being supplied.
     */
    const FAILURE_CREDENTIAL_INVALID     = -3;

    /**
     * Failure due to uncategorized reasons.
     */
    const FAILURE_UNCATEGORIZED          = -4;

    /**
     * Authentication success.
     */
    const SUCCESS                        =  1;

    /**
     * Authentication result code
     *
     * @var int
     */
    protected $_code;

    /**
     * The identity used in the authentication attempt
     *
     * @var mixed
     */
    protected $_identity;

    /**
     * An array of string reasons why the authentication attempt was unsuccessful
     *
     * If authentication was successful, this should be an empty array.
     *
     * @var array
     */
    protected $_messages;

    /**
     * Sets the result code, identity, and failure messages
     *
     * @param  int     $code
     * @param  mixed   $identity
     * @param  array   $messages
     * @return void
     */
    public function __construct($code, $identity, array $messages = array())
    {
        $code = (int) $code;

        if ($code < self::FAILURE_UNCATEGORIZED) {
            $code = self::FAILURE;
        } elseif ($code > self::SUCCESS ) {
            $code = 1;
        }

        $this->_code     = $code;
        $this->_identity = $identity;
        $this->_messages = $messages;
    }

    /**
     * Returns whether the result represents a successful authentication attempt
     *
     * @return boolean
     */
    public function isValid()
    {
        return ($this->_code > 0) ? true : false;
    }

    /**
     * getCode() - Get the result code for this authentication attempt
     *
     * @return int
     */
    public function getCode()
    {
        return $this->_code;
    }

    /**
     * Returns the identity used in the authentication attempt
     *
     * @return mixed
     */
    public function getIdentity()
    {
        return $this->_identity;
    }

    /**
     * Returns an array of string reasons why the authentication attempt was unsuccessful
     *
     * If authentication was successful, this method returns an empty array.
     *
     * @return array
     */
    public function getMessages()
    {
        return $this->_messages;
    }
}
Amf/Request.php000066600000016502151256604600007425 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Amf_Parse_InputStream */
require_once 'Zend/Amf/Parse/InputStream.php';

/** Zend_Amf_Parse_Amf0_Deserializer */
require_once 'Zend/Amf/Parse/Amf0/Deserializer.php';

/** Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';

/** Zend_Amf_Value_MessageHeader */
require_once 'Zend/Amf/Value/MessageHeader.php';

/** Zend_Amf_Value_MessageBody */
require_once 'Zend/Amf/Value/MessageBody.php';

/**
 * Handle the incoming AMF request by deserializing the data to php object
 * types and storing the data for Zend_Amf_Server to handle for processing.
 *
 * @todo       Currently not checking if the object needs to be Type Mapped to a server object.
 * @package    Zend_Amf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Amf_Request
{
    /**
     * @var int AMF client type (AMF0, AMF3)
     */
    protected $_clientType = 0; // default AMF0

    /**
     * @var array Message bodies
     */
    protected $_bodies = array();

    /**
     * @var array Message headers
     */
    protected $_headers = array();

    /**
     * @var int Message encoding to use for objects in response
     */
    protected $_objectEncoding = 0;

    /**
     * @var Zend_Amf_Parse_InputStream
     */
    protected $_inputStream;

    /**
     * @var Zend_Amf_Parse_AMF0_Deserializer
     */
    protected $_deserializer;

    /**
     * Time of the request
     * @var  mixed
     */
    protected $_time;

    /**
     * Prepare the AMF InputStream for parsing.
     *
     * @param  string $request
     * @return Zend_Amf_Request
     */
    public function initialize($request)
    {
        $this->_inputStream  = new Zend_Amf_Parse_InputStream($request);
        $this->_deserializer = new Zend_Amf_Parse_AMF0_Deserializer($this->_inputStream);
        $this->readMessage($this->_inputStream);
        return $this;
    }

    /**
     * Takes the raw AMF input stream and converts it into valid PHP objects
     *
     * @param  Zend_Amf_Parse_InputStream
     * @return Zend_Amf_Request
     */
    public function readMessage(Zend_Amf_Parse_InputStream $stream)
    {
        $clientVersion = $stream->readUnsignedShort();
        if (($clientVersion != Zend_Amf_Constants::AMF0_OBJECT_ENCODING)
            && ($clientVersion != Zend_Amf_Constants::AMF3_OBJECT_ENCODING)
        ) {
            require_once 'Zend/Amf/Exception.php';
            throw new Zend_Amf_Exception('Unknown Player Version ' . $clientVersion);
        }

        $this->_bodies  = array();
        $this->_headers = array();
        $headerCount    = $stream->readInt();

        // Iterate through the AMF envelope header
        while ($headerCount--) {
            $this->_headers[] = $this->readHeader();
        }

        // Iterate through the AMF envelope body
        $bodyCount = $stream->readInt();
        while ($bodyCount--) {
            $this->_bodies[] = $this->readBody();
        }

        return $this;
    }

    /**
     * Deserialize a message header from the input stream.
     *
     * A message header is structured as:
     * - NAME String
     * - MUST UNDERSTAND Boolean
     * - LENGTH Int
     * - DATA Object
     *
     * @return Zend_Amf_Value_MessageHeader
     */
    public function readHeader()
    {
        $name     = $this->_inputStream->readUTF();
        $mustRead = (bool)$this->_inputStream->readByte();
        $length   = $this->_inputStream->readLong();

        try {
            $data = $this->_deserializer->readTypeMarker();
        } catch (Exception $e) {
            require_once 'Zend/Amf/Exception.php';
            throw new Zend_Amf_Exception('Unable to parse ' . $name . ' header data: ' . $e->getMessage() . ' '. $e->getLine());
        }

        $header = new Zend_Amf_Value_MessageHeader($name, $mustRead, $data, $length);
        return $header;
    }

    /**
     * Deserialize a message body from the input stream
     *
     * @return Zend_Amf_Value_MessageBody
     */
    public function readBody()
    {
        $targetURI   = $this->_inputStream->readUTF();
        $responseURI = $this->_inputStream->readUTF();
        $length      = $this->_inputStream->readLong();

        try {
            $data = $this->_deserializer->readTypeMarker();
        } catch (Exception $e) {
            require_once 'Zend/Amf/Exception.php';
            throw new Zend_Amf_Exception('Unable to parse ' . $targetURI . ' body data ' . $e->getMessage());
        }

        // Check for AMF3 objectEncoding
        if ($this->_deserializer->getObjectEncoding() == Zend_Amf_Constants::AMF3_OBJECT_ENCODING) {
            /*
             * When and AMF3 message is sent to the server it is nested inside
             * an AMF0 array called Content. The following code gets the object
             * out of the content array and sets it as the message data.
             */
            if(is_array($data) && $data[0] instanceof Zend_Amf_Value_Messaging_AbstractMessage){
                $data = $data[0];
            }

            // set the encoding so we return our message in AMF3
            $this->_objectEncoding = Zend_Amf_Constants::AMF3_OBJECT_ENCODING;
        }

        $body = new Zend_Amf_Value_MessageBody($targetURI, $responseURI, $data);
        return $body;
    }

    /**
     * Return an array of the body objects that were found in the amf request.
     *
     * @return array {target, response, length, content}
     */
    public function getAmfBodies()
    {
        return $this->_bodies;
    }

    /**
     * Accessor to private array of message bodies.
     *
     * @param  Zend_Amf_Value_MessageBody $message
     * @return Zend_Amf_Request
     */
    public function addAmfBody(Zend_Amf_Value_MessageBody $message)
    {
        $this->_bodies[] = $message;
        return $this;
    }

    /**
     * Return an array of headers that were found in the amf request.
     *
     * @return array {operation, mustUnderstand, length, param}
     */
    public function getAmfHeaders()
    {
        return $this->_headers;
    }

    /**
     * Return the either 0 or 3 for respect AMF version
     *
     * @return int
     */
    public function getObjectEncoding()
    {
        return $this->_objectEncoding;
    }

    /**
     * Set the object response encoding
     *
     * @param  mixed $int
     * @return Zend_Amf_Request
     */
    public function setObjectEncoding($int)
    {
        $this->_objectEncoding = $int;
        return $this;
    }
}
Amf/Server.php000066600000057706151256604600007256 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Server_Interface */
require_once 'Zend/Server/Interface.php';

/** Zend_Server_Reflection */
require_once 'Zend/Server/Reflection.php';

/** Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';

/** Zend_Amf_Value_MessageBody */
require_once 'Zend/Amf/Value/MessageBody.php';

/** Zend_Amf_Value_MessageHeader */
require_once 'Zend/Amf/Value/MessageHeader.php';

/** Zend_Amf_Value_Messaging_CommandMessage */
require_once 'Zend/Amf/Value/Messaging/CommandMessage.php';

/**
 * An AMF gateway server implementation to allow the connection of the Adobe Flash Player to
 * Zend Framework
 *
 * @todo       Make the relection methods cache and autoload.
 * @package    Zend_Amf
 * @subpackage Server
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Amf_Server implements Zend_Server_Interface
{
    /**
     * Array of dispatchables
     * @var array
     */
    protected $_methods = array();

    /**
     * Array of directories to search for loading classes dynamically
     * @var array
     */
    protected $_directories = array();

    /**
     * @var bool Production flag; whether or not to return exception messages
     */
    protected $_production = true;

    /**
     * Request processed
     * @var null|Zend_Amf_Request
     */
    protected $_request = null;

    /**
     * Class to use for responses
     * @var null|Zend_Amf_Response
     */
    protected $_response;

    /**
     * Dispatch table of name => method pairs
     * @var array
     */
    protected $_table = array();

    /**
     *
     * @var bool session flag; whether or not to add a session to each response.
     */
    protected $_session = false;

    /**
     * Namespace allows all AMF calls to not clobber other php session variables
     * @var Zend_Session_NameSpace default session namespace zend_amf
     */
    protected $_sesionNamespace = 'zend_amf';

    /**
     * Set the default session.name if php_
     * @var unknown_type
     */
    protected $_sessionName = 'PHPSESSID';

    /**
     * Set production flag
     *
     * @param  bool $flag
     * @return Zend_Amf_Server
     */
    public function setProduction($flag)
    {
        $this->_production = (bool) $flag;
        return $this;
    }

    /**
     * Whether or not the server is in production
     *
     * @return bool
     */
    public function isProduction()
    {
        return $this->_production;
    }


    /**
     * @param namespace of all incoming sessions defaults to Zend_Amf
     * @return Zend_Amf_Server
     */
    public function setSession($namespace = 'Zend_Amf')
    {
        require_once 'Zend/Session.php';
        $this->_session = true;
        $this->_sesionNamespace = new Zend_Session_Namespace($namespace);
        return $this;
    }

    /**
     * Whether of not the server is using sessions
     * @return bool
     */
    public function isSession()
    {
        return $this->_session;
    }

    /**
     * Loads a remote class or method and executes the function and returns
     * the result
     *
     * @param  string $method Is the method to execute
     * @param  mixed $param values for the method
     * @return mixed $response the result of executing the method
     * @throws Zend_Amf_Server_Exception
     */
    protected function _dispatch($method, $params = null, $source = null)
    {
        $qualifiedName = empty($source) ? $method : $source.".".$method;
        
        if (!isset($this->_table[$qualifiedName])) {
            // if source is null a method that was not defined was called.
            if ($source) {
                $classPath    = array();
                $path         = explode('.', $source);
                $className    = array_pop($path);
                $uriclasspath = implode('/', $path);

                // Take the user supplied directories and add the unique service path to the end.
                foreach ($this->_directories as $dir) {
                    $classPath[] = $dir . $uriclasspath;
                }

                require_once('Zend/Loader.php');
                try {
                    Zend_Loader::loadClass($className, $classPath);
                } catch (Exception $e) {
                    require_once 'Zend/Amf/Server/Exception.php';
                    throw new Zend_Amf_Server_Exception('Class "' . $className . '" does not exist');
                }
                // Add the new loaded class to the server.
                $this->setClass($className, $source);
            } else {
                require_once 'Zend/Amf/Server/Exception.php';
                throw new Zend_Amf_Server_Exception('Method "' . $method . '" does not exist');
            }
        }

        $info = $this->_table[$qualifiedName];
        $argv = $info->getInvokeArguments();
        
        if (0 < count($argv)) {
            $params = array_merge($params, $argv);
        }

        if ($info instanceof Zend_Server_Reflection_Function) {
            $func = $info->getName();
            $return = call_user_func_array($func, $params);
        } elseif ($info instanceof Zend_Server_Reflection_Method) {
            // Get class
            $class = $info->getDeclaringClass()->getName();
            if ('static' == $info->isStatic()) {
                // for some reason, invokeArgs() does not work the same as
                // invoke(), and expects the first argument to be an object.
                // So, using a callback if the method is static.
                $return = call_user_func_array(array($class, $info->getName()), $params);
            } else {
                // Object methods
                try {
                    $object = $info->getDeclaringClass()->newInstance();
                } catch (Exception $e) {
                    require_once 'Zend/Amf/Server/Exception.php';
                    throw new Zend_Amf_Server_Exception('Error instantiating class ' . $class . ' to invoke method ' . $info->getName(), 621);
                }
                $return = $info->invokeArgs($object, $params);
            }
        } else {
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception('Method missing implementation ' . get_class($info));
        }

        return $return;
    }

    /**
     * Handles each of the 11 different command message types.
     *
     * A command message is a flex.messaging.messages.CommandMessage
     *
     * @see    Zend_Amf_Value_Messaging_CommandMessage
     * @param  Zend_Amf_Value_Messaging_CommandMessage $message
     * @return Zend_Amf_Value_Messaging_AcknowledgeMessage
     */
    protected function _loadCommandMessage(Zend_Amf_Value_Messaging_CommandMessage $message)
    {
        switch($message->operation) {
            case Zend_Amf_Value_Messaging_CommandMessage::CLIENT_PING_OPERATION :
                require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
                $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
                break;
            default :
                require_once 'Zend/Amf/Server/Exception.php';
                throw new Zend_Amf_Server_Exception('CommandMessage::' . $message->operation . ' not implemented');
                break;
        }
        return $return;
    }

    /**
     * Takes the deserialized AMF request and performs any operations.
     *
     * @todo   should implement and SPL observer pattern for custom AMF headers
     * @todo   implement AMF header authentication
     * @param  Zend_Amf_Request $request
     * @return Zend_Amf_Response
     * @throws Zend_Amf_server_Exception|Exception
     */
    protected function _handle(Zend_Amf_Request $request)
    {
        // Get the object encoding of the request.
        $objectEncoding = $request->getObjectEncoding();

        // create a response object to place the output from the services.
        $response = $this->getResponse();

        // set reponse encoding
        $response->setObjectEncoding($objectEncoding);

        $responseBody = $request->getAmfBodies();

        // Iterate through each of the service calls in the AMF request
        foreach($responseBody as $body)
        {
            try {
                if ($objectEncoding == Zend_Amf_Constants::AMF0_OBJECT_ENCODING) {
                    // AMF0 Object Encoding
                    $targetURI = $body->getTargetURI();

                    // Split the target string into its values.
                    $source = substr($targetURI, 0, strrpos($targetURI, '.'));

                    if ($source) {
                        // Break off method name from namespace into source
                        $method = substr(strrchr($targetURI, '.'), 1);
                        $return = $this->_dispatch($method, $body->getData(), $source);
                    } else {
                        // Just have a method name.
                        $return = $this->_dispatch($targetURI, $body->getData());
                    }
                } else {
                    // AMF3 read message type
                    $message = $body->getData();
                    if ($message instanceof Zend_Amf_Value_Messaging_CommandMessage) {
                        // async call with command message
                        $return = $this->_loadCommandMessage($message);
                    } elseif ($message instanceof Zend_Amf_Value_Messaging_RemotingMessage) {
                        require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
                        $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
                        $return->body = $this->_dispatch($message->operation, $message->body, $message->source);
                    } else {
                        // Amf3 message sent with netConnection
                        $targetURI = $body->getTargetURI();

                        // Split the target string into its values.
                        $source = substr($targetURI, 0, strrpos($targetURI, '.'));

                        if ($source) {
                            // Break off method name from namespace into source
                            $method = substr(strrchr($targetURI, '.'), 1);
                            $return = $this->_dispatch($method, $body->getData(), $source);
                        } else {
                            // Just have a method name.
                            $return = $this->_dispatch($targetURI, $body->getData());
                        }
                    }
                }
                $responseType = Zend_AMF_Constants::RESULT_METHOD;
            } catch (Exception $e) {
                switch ($objectEncoding) {
                    case Zend_Amf_Constants::AMF0_OBJECT_ENCODING :
                        $return = array(
                            'description' => ($this->isProduction()) ? '' : $e->getMessage(),
                            'detail'      => ($this->isProduction()) ? '' : $e->getTraceAsString(),
                            'line'        => ($this->isProduction()) ? 0  : $e->getLine(),
                            'code'        => $e->getCode(),
                        );
                        break;
                    case Zend_Amf_Constants::AMF3_OBJECT_ENCODING :
                        require_once 'Zend/Amf/Value/Messaging/ErrorMessage.php';
                        $return = new Zend_Amf_Value_Messaging_ErrorMessage($message);
                        $return->faultString = $this->isProduction() ? '' : $e->getMessage();
                        $return->faultCode   = $e->getCode();
                        $return->faultDetail = $this->isProduction() ? '' : $e->getTraceAsString();
                        break;
                }
                $responseType = Zend_AMF_Constants::STATUS_METHOD;
            }

            $responseURI = $body->getResponseURI() . $responseType;
            $newBody     = new Zend_Amf_Value_MessageBody($responseURI, null, $return);
            $response->addAmfBody($newBody);
        }
        // Add a session header to the body if session is requested.
        if($this->isSession()) {
           $currentID = session_id();
           $joint = "?";
           if(isset($_SERVER['QUERY_STRING'])) {
               if(!strpos($_SERVER['QUERY_STRING'], $currentID) !== FALSE) {
                   if(strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) {
                       $joint = "&";
                   } 
               }    
           }
           
            // create a new AMF message header with the session id as a variable.
            $sessionValue = $joint . $this->_sessionName . "=" . $currentID;
            $sessionHeader = new Zend_Amf_Value_MessageHeader("AppendToGatewayUrl", false, $sessionValue);
            $response->addAmfHeader($sessionHeader);
        }

        // serialize the response and return serialized body.
        $response->finalize();
    }

    /**
     * Handle an AMF call from the gateway.
     *
     * @param  null|Zend_Amf_Request $request Optional
     * @return Zend_Amf_Response
     */
    public function handle($request = null)
    {
        // Check if request was passed otherwise get it from the server
        if (is_null($request) || !$request instanceof Zend_Amf_Request) {
            $request = $this->getRequest();
        } else {
            $this->setRequest($request);
        }
        if ($this->isSession()) {
             // Check if a session is being sent from the amf call
             if (isset($_COOKIE[$this->_sessionName])) {
                 session_id($_COOKIE[$this->_sessionName]);
             }
        }

        // Check for errors that may have happend in deserialization of Request.
        try {
            // Take converted PHP objects and handle service call.
            // Serialize to Zend_Amf_response for output stream
            $this->_handle($request);
            $response = $this->getResponse();
        } catch (Exception $e) {
            // Handle any errors in the serialization and service  calls.
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception('Handle error: ' . $e->getMessage() . ' ' . $e->getLine());
        }

        // Return the Amf serialized output string
        return $response;
    }

    /**
     * Set request object
     *
     * @param  string|Zend_Amf_Request $request
     * @return Zend_Amf_Server
     */
    public function setRequest($request)
    {
        if (is_string($request) && class_exists($request)) {
            $request = new $request();
            if (!$request instanceof Zend_Amf_Request) {
                require_once 'Zend/Amf/Server/Exception.php';
                throw new Zend_Amf_Server_Exception('Invalid request class');
            }
        } elseif (!$request instanceof Zend_Amf_Request) {
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception('Invalid request object');
        }
        $this->_request = $request;
        return $this;
    }

    /**
     * Return currently registered request object
     *
     * @return null|Zend_Amf_Request
     */
    public function getRequest()
    {
        if (null === $this->_request) {
            require_once 'Zend/Amf/Request/Http.php';
            $this->setRequest(new Zend_Amf_Request_Http());
        }

        return $this->_request;
    }

    /**
     * Public access method to private Zend_Amf_Server_Response refrence
     *
     * @param  string|Zend_Amf_Server_Response $response
     * @return Zend_Amf_Server
     */
    public function setResponse($response)
    {
        if (is_string($response) && class_exists($response)) {
            $response = new $response();
            if (!$response instanceof Zend_Amf_Response) {
                require_once 'Zend/Amf/Server/Exception.php';
                throw new Zend_Amf_Server_Exception('Invalid response class');
            }
        } elseif (!$response instanceof Zend_Amf_Response) {
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception('Invalid response object');
        }
        $this->_response = $response;
        return $this;
    }

    /**
     * get a refrence to the Zend_Amf_response instance
     *
     * @return Zend_Amf_Server_Response
     */
    public function getResponse()
    {
        if (null === ($response = $this->_response)) {
            require_once 'Zend/Amf/Response/Http.php';
            $this->setResponse(new Zend_Amf_Response_Http());
        }
        return $this->_response;
    }

    /**
     * Attach a class or object to the server
     *
     * Class may be either a class name or an instantiated object. Reflection
     * is done on the class or object to determine the available public
     * methods, and each is attached to the server as and available method. If
     * a $namespace has been provided, that namespace is used to prefix
     * AMF service call.
     *
     * @param  string|object $class
     * @param  string $namespace Optional
     * @param  mixed $arg Optional arguments to pass to a method
     * @return Zend_Amf_Server
     * @throws Zend_Amf_Server_Exception on invalid input
     */
    public function setClass($class, $namespace = '', $argv = null)
    {
        if (is_string($class) && !class_exists($class)){
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception('Invalid method or class');
        } elseif (!is_string($class) && !is_object($class)) {
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception('Invalid method or class; must be a classname or object');
        }

        $argv = null;
        if (2 < func_num_args()) {
            $argv = array_slice(func_get_args(), 2);
        }

        // Use the class name as the name space by default.
        
        if ($namespace == '') {
            $namespace = is_object($class) ? get_class($class) : $class;
        }
        

        $this->_methods[] = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
        $this->_buildDispatchTable();

        return $this;
    }

    /**
     * Attach a function to the server
     *
     * Additional arguments to pass to the function at dispatch may be passed;
     * any arguments following the namespace will be aggregated and passed at
     * dispatch time.
     *
     * @param  string|array $function Valid callback
     * @param  string $namespace Optional namespace prefix
     * @return Zend_Amf_Server
     * @throws Zend_Amf_Server_Exception
     */
    public function addFunction($function, $namespace = '')
    {
        if (!is_string($function) && !is_array($function)) {
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception('Unable to attach function');
        }

        $argv = null;
        if (2 < func_num_args()) {
            $argv = array_slice(func_get_args(), 2);
        }

        $function = (array) $function;
        foreach ($function as $func) {
            if (!is_string($func) || !function_exists($func)) {
                require_once 'Zend/Amf/Server/Exception.php';
                throw new Zend_Amf_Server_Exception('Unable to attach function');
            }
            $this->_methods[] = Zend_Server_Reflection::reflectFunction($func, $argv, $namespace);
        }

        $this->_buildDispatchTable();
        return $this;
    }


    /**
     * Creates an array of directories in which services can reside.
     *
     * @param string $dir
     */
    public function addDirectory($dir)
    {
        $this->_directories[] = $dir;
    }

    /**
     * Returns an array of directories that can hold services.
     *
     * @return array
     */
    public function getDirectory()
    {
        return $this->_directories;
    }

    /**
     * (Re)Build the dispatch table
     *
     * The dispatch table consists of a an array of method name =>
     * Zend_Server_Reflection_Function_Abstract pairs
     *
     * @return void
     */
    protected function _buildDispatchTable()
    {
        $table = array();
        foreach ($this->_methods as $key => $dispatchable) {
            if ($dispatchable instanceof Zend_Server_Reflection_Function_Abstract) {
                $ns   = $dispatchable->getNamespace();
                $name = $dispatchable->getName();
                $name = empty($ns) ? $name : $ns . '.' . $name;

                if (isset($table[$name])) {
                    require_once 'Zend/Amf/Server/Exception.php';
                    throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name);
                }
                $table[$name] = $dispatchable;
                continue;
            }

            if ($dispatchable instanceof Zend_Server_Reflection_Class) {
                foreach ($dispatchable->getMethods() as $method) {
                    $ns   = $method->getNamespace();
                    $name = $method->getName();
                    $name = empty($ns) ? $name : $ns . '.' . $name;

                    if (isset($table[$name])) {
                        require_once 'Zend/Amf/Server/Exception.php';
                        throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name);
                    }
                    $table[$name] = $method;
                    continue;
                }
            }
        }
        $this->_table = $table;
    }



    /**
     * Raise a server fault
     *
     * Unimplemented
     *
     * @param  string|Exception $fault
     * @return void
     */
    public function fault($fault = null, $code = 404)
    {
    }

    /**
     * Returns a list of registered methods
     *
     * Returns an array of dispatchables (Zend_Server_Reflection_Function,
     * _Method, and _Class items).
     *
     * @return array
     */
    public function getFunctions()
    {
        return $this->_table;
    }

    /**
     * Set server persistence
     *
     * Unimplemented
     *
     * @param  mixed $mode
     * @return void
     */
    public function setPersistence($mode)
    {
    }

    /**
     * Load server definition
     *
     * Unimplemented
     *
     * @param  array $definition
     * @return void
     */
    public function loadFunctions($definition)
    {
    }

    /**
     * Map ActionScript classes to PHP classes
     *
     * @param  string $asClass
     * @param  string $phpClass
     * @return Zend_Amf_Server
     */
    public function setClassMap($asClass, $phpClass)
    {
        require_once 'Zend/Amf/Parse/TypeLoader.php';
        Zend_Amf_Parse_TypeLoader::setMapping($asClass, $phpClass);
        return $this;
    }

    /**
     * List all available methods
     *
     * Returns an array of method names.
     *
     * @return array
     */
    public function listMethods()
    {
        return array_keys($this->_table);
    }
}Amf/Response.php000066600000012764151256604600007601 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Amf_Constants */
require_once 'Zend/Amf/Constants.php';

/** Zend_Amf_Parse_OutputStream */
require_once 'Zend/Amf/Parse/OutputStream.php';

/** Zend_Amf_Parse_Amf0_Serializer */
require_once 'Zend/Amf/Parse/Amf0/Serializer.php';

/**
 * Handles converting the PHP object ready for response back into AMF
 *
 * @package    Zend_Amf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Amf_Response
{
    /**
     * @var int Object encoding for response
     */
    protected $_objectEncoding = 0;

    /**
     * Array of Zend_Amf_Value_MessageBody objects
     * @var array
     */
    protected $_bodies = array();

    /**
     * Array of Zend_Amf_Value_MessageHeader objects
     * @var array
     */
    protected $_headers = array();

    /**
     * @var Zend_Amf_Parse_OutputStream
     */
    protected $_outputStream;

    /**
     * Instantiate new output stream and start serialization
     *
     * @return Zend_Amf_Response
     */
    public function finalize()
    {
        $this->_outputStream = new Zend_Amf_Parse_OutputStream();
        $this->writeMessage($this->_outputStream);
        return $this;
    }

    /**
     * Serialize the PHP data types back into Actionscript and
     * create and AMF stream.
     *
     * @param  Zend_Amf_Parse_OutputStream $stream
     * @return Zend_Amf_Response
     */
    public function writeMessage(Zend_Amf_Parse_OutputStream $stream)
    {
        $objectEncoding = $this->_objectEncoding;

        //Write encoding to start of stream. Preamble byte is written of two byte Unsigned Short
        $stream->writeByte(0x00);
        $stream->writeByte($objectEncoding);

        // Loop through the AMF Headers that need to be returned.
        $headerCount = count($this->_headers);
        $stream->writeInt($headerCount);
        foreach ($this->getAmfHeaders() as $header) {
            $serializer = new Zend_Amf_Parse_Amf0_Serializer($stream);
            $stream->writeUTF($header->name);
            $stream->writeByte($header->mustRead);
            $stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH);
            $serializer->writeTypeMarker($header->data);
        }

        // loop through the AMF bodies that need to be returned.
        $bodyCount = count($this->_bodies);
        $stream->writeInt($bodyCount);
        foreach ($this->_bodies as $body) {
            $serializer = new Zend_Amf_Parse_Amf0_Serializer($stream);
            $stream->writeUTF($body->getTargetURI());
            $stream->writeUTF($body->getResponseURI());
            $stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH);
            if($this->_objectEncoding == Zend_Amf_Constants::AMF0_OBJECT_ENCODING) {
                $serializer->writeTypeMarker($body->getData());
            } else {
                // Content is AMF3
                $serializer->writeTypeMarker($body->getData(),Zend_Amf_Constants::AMF0_AMF3);
            }
        }

        return $this;
    }

    /**
     * Return the output stream content
     *
     * @return string The contents of the output stream
     */
    public function getResponse()
    {
        return $this->_outputStream->getStream();
    }

    /**
     * Return the output stream content
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getResponse();
    }

    /**
     * Add an AMF body to be sent to the Flash Player
     *
     * @param  Zend_Amf_Value_MessageBody $body
     * @return Zend_Amf_Response
     */
    public function addAmfBody(Zend_Amf_Value_MessageBody $body)
    {
        $this->_bodies[] = $body;
        return $this;
    }

    /**
     * Return an array of AMF bodies to be serialized
     *
     * @return array
     */
    public function getAmfBodies()
    {
        return $this->_bodies;
    }

    /**
     * Add an AMF Header to be sent back to the flash player
     *
     * @param  Zend_Amf_Value_MessageHeader $header
     * @return Zend_Amf_Response
     */
    public function addAmfHeader(Zend_Amf_Value_MessageHeader $header)
    {
        $this->_headers[] = $header;
        return $this;
    }

    /**
     * Retrieve attached AMF message headers
     * 
     * @return array Array of Zend_Amf_Value_MessageHeader objects
     */
    public function getAmfHeaders()
    {
        return $this->_headers;
    }

    /**
     * Set the AMF encoding that will be used for serialization
     *
     * @param  int $encoding
     * @return Zend_Amf_Response
     */
    public function setObjectEncoding($encoding)
    {
        $this->_objectEncoding = $encoding;
        return $this;
    }
}
Amf/Response/Http.php000066600000002731151256604600010511 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @subpackage Response
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Amf_Response */
require_once 'Zend/Amf/Response.php';

/**
 * Creates the proper http headers and send the serialized AMF stream to standard out.
 *
 * @package    Zend_Amf
 * @subpackage Response
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Amf_Response_Http extends Zend_Amf_Response
{
    /**
     * Create the application response header for AMF and sends the serialized AMF string
     *
     * @return string
     */
    public function getResponse()
    {
        if (!headers_sent()) {
            header('Content-Type: application/x-amf');
        }
        return parent::getResponse();
    }
}
Amf/Value/Messaging/AcknowledgeMessage.php000066600000003633151256604600014517 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Amf_Value_Messaging_AsyncMessage */
require_once 'Zend/Amf/Value/Messaging/AsyncMessage.php';

/**
 * This is the type of message returned by the MessageBroker
 * to endpoints after the broker has routed an endpoint's message
 * to a service.
 *
 * flex.messaging.messages.AcknowledgeMessage
 *
 * @package    Zend_Amf
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Amf_Value_Messaging_AcknowledgeMessage extends Zend_Amf_Value_Messaging_AsyncMessage
{
    /**
     * Create a new Acknowledge Message
     *
     * @param unknown_type $message
     */
    public function __construct($message)
    {
        $this->clientId    = $this->generateId();
        $this->destination = null;
        $this->messageId   = $this->generateId();
        $this->timestamp   = time().'00';
        $this->timeToLive  = 0;
        $this->headers     = new STDClass();
        $this->body        = null;

        // correleate the two messages
        if ($message) {
            $this->correlationId = $message->messageId;
        }
    }
}
Amf/Value/Messaging/CommandMessage.php000066600000007600151256604600013650 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

require_once 'Zend/Amf/Value/Messaging/AsyncMessage.php';

/**
 * A message that represents an infrastructure command passed between
 * client and server. Subscribe/unsubscribe operations result in
 * CommandMessage transmissions, as do polling operations.
 *
 * Corresponds to flex.messaging.messages.CommandMessage
 *
 * Note: THESE VALUES MUST BE THE SAME ON CLIENT AND SERVER
 *
 * @package    Zend_Amf
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Amf_Value_Messaging_CommandMessage extends Zend_Amf_Value_Messaging_AsyncMessage
{
    /**
     *  This operation is used to subscribe to a remote destination.
     *  @const int
     */
    const SUBSCRIBE_OPERATION = 0;

    /**
     * This operation is used to unsubscribe from a remote destination.
     * @const int
     */
    const UNSUSBSCRIBE_OPERATION = 1;

    /**
     * This operation is used to poll a remote destination for pending,
     * undelivered messages.
     * @const int
     */
    const POLL_OPERATION = 2;

    /**
     * This operation is used by a remote destination to sync missed or cached messages
     * back to a client as a result of a client issued poll command.
     * @const int
     */
    const CLIENT_SYNC_OPERATION = 4;

    /**
     * This operation is used to test connectivity over the current channel to
     * the remote endpoint.
     * @const int
     */
    const CLIENT_PING_OPERATION = 5;

    /**
     * This operation is used to request a list of failover endpoint URIs
     * for the remote destination based on cluster membership.
     * @const int
     */
    const CLUSTER_REQUEST_OPERATION = 7;

    /**
     * This operation is used to send credentials to the endpoint so that
     * the user can be logged in over the current channel.
     * The credentials need to be Base64 encoded and stored in the <code>body</code>
     * of the message.
     * @const int
     */
    const LOGIN_OPERATION = 8;

    /**
     * This operation is used to log the user out of the current channel, and
     * will invalidate the server session if the channel is HTTP based.
     * @const int
     */
    const LOGOUT_OPERATION = 9;

    /**
     * This operation is used to indicate that the client's subscription to a
     * remote destination has been invalidated.
     * @const int
     */
    const SESSION_INVALIDATE_OPERATION = 10;

    /**
     * This operation is used by the MultiTopicConsumer to subscribe/unsubscribe
     * from multiple subtopics/selectors in the same message.
     * @const int
     */
    const MULTI_SUBSCRIBE_OPERATION = 11;

    /**
     * This operation is used to indicate that a channel has disconnected
     * @const int
     */
    const DISCONNECT_OPERATION = 12;

    /**
     * This is the default operation for new CommandMessage instances.
     * @const int
     */
    const UNKNOWN_OPERATION = 10000;

    /**
     * The operation to execute for messages of this type
     * @var int
     */
    public $operation = self::UNKNOWN_OPERATION;
}
Amf/Value/Messaging/RemotingMessage.php000066600000004060151256604600014053 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Amf_Value_Messaging_AbstractMessage */
require_once 'Zend/Amf/Value/Messaging/AbstractMessage.php';

/**
 * This type of message contains information needed to perform
 * a Remoting invocation.
 *
 * Corresponds to flex.messaging.messages.RemotingMessage
 *
 * @package    Zend_Amf
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Amf_Value_Messaging_RemotingMessage extends Zend_Amf_Value_Messaging_AbstractMessage
{

    /**
     * The name of the service to be called including package name
     * @var String
     */
    public $source;

    /**
     * The name of the method to be called
     * @var string
     */
    public $operation;

    /**
     * The arguments to call the mathod with
     * @var array
     */
    public $parameters;

    /**
     * Create a new Remoting Message
     *
     * @return void
     */
    public function __construct()
    {
        $this->clientId    = $this->generateId();
        $this->destination = null;
        $this->messageId   = $this->generateId();
        $this->timestamp   = time().'00';
        $this->timeToLive  = 0;
        $this->headers     = new stdClass();
        $this->body        = null;
    }
}
Amf/Value/Messaging/AbstractMessage.php000066600000004504151256604600014035 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * This is the default Implementation of Message, which provides
 * a convenient base for behavior and association of common endpoints
 *
 * @package    Zend_Amf
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Amf_Value_Messaging_AbstractMessage
{
    /**
     * @var string Client identifier
     */
    public $clientId;

    /**
     * @var string Destination
     */
    public $destination;

    /**
     * @var string Message identifier
     */
    public $messageId;

    /**
     * @var int Message timestamp
     */
    public $timestamp;

    /**
     * @var int Message TTL
     */
    public $timeToLive;

    /**
     * @var object Message headers
     */
    public $headers;

    /**
     * @var string Message body
     */
    public $body;

    /**
     * generate a unique id
     *
     * Format is: ########-####-####-####-############
     * Where # is an uppercase letter or number
     * example: 6D9DC7EC-A273-83A9-ABE3-00005FD752D6
     *
     * @return string
     */
    public function generateId()
    {
        return sprintf(
            '%08X-%04X-%04X-%02X%02X-%012X',
            mt_rand(),
            mt_rand(0, 65535),
            bindec(substr_replace(
                sprintf('%016b', mt_rand(0, 65535)), '0100', 11, 4)
            ),
            bindec(substr_replace(sprintf('%08b', mt_rand(0, 255)), '01', 5, 2)),
            mt_rand(0, 255),
            mt_rand()
        );
    }
}
Json/Server/Request/Http.php000066600000003276151256604600012024 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Json
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Json_Server_Request
 */
require_once 'Zend/Json/Server/Request.php';

/**
 * @category   Zend
 * @package    Zend_Json
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Json_Server_Request_Http extends Zend_Json_Server_Request
{
    /**
     * Raw JSON pulled from POST body
     * @var string
     */
    protected $_rawJson;

    /**
     * Constructor
     *
     * Pull JSON request from raw POST body and use to populate request.
     * 
     * @return void
     */
    public function __construct()
    {
        $json = file_get_contents('php://input');
        $this->_rawJson = $json;
        if (!empty($json)) {
            $this->loadJson($json);
        }
    }

    /**
     * Get JSON from raw POST body
     * 
     * @return string
     */
    public function getRawJson()
    {
        return $this->_rawJson;
    }
}
Json/Server/Response/Http.php000066600000004241151256604600012163 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Json
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Json_Server_Response
 */
require_once 'Zend/Json/Server/Response.php';

/**
 * @category   Zend
 * @package    Zend_Json
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Json_Server_Response_Http extends Zend_Json_Server_Response
{
    /**
     * Emit JSON
     *
     * Send appropriate HTTP headers. If no Id, then return an empty string.
     * 
     * @return string
     */
    public function toJson()
    {
        $this->sendHeaders();
        if (!$this->isError() && null === $this->getId()) {
            return '';
        }

        return parent::toJson();
    }

    /**
     * Send headers
     *
     * If headers are already sent, do nothing. If null ID, send HTTP 204 
     * header. Otherwise, send content type header based on content type of 
     * service map.
     * 
     * @return void
     */
    public function sendHeaders()
    {
        if (headers_sent()) {
            return;
        }

        if (!$this->isError() && (null === $this->getId())) {
            header('HTTP/1.1 204 No Content');
            return;
        }

        if (null === ($smd = $this->getServiceMap())) {
            return;
        }

        $contentType = $smd->getContentType();
        if (!empty($contentType)) {
            header('Content-Type: ' . $contentType);
        }
    }
}
Json/Exception.php000066600000002031151256604600010131 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Json
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


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


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

Json/Server.php000066600000036631151256604600007456 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Json
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Server_Abstract
 */
require_once 'Zend/Server/Abstract.php';

/**
 * @category   Zend
 * @package    Zend_Json
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Json_Server extends Zend_Server_Abstract
{
    /**#@+
     * Version Constants
     * @const string
     */
    const VERSION_1 = '1.0';
    const VERSION_2 = '2.0';
    /**#@-*/

    /**
     * Flag: whether or not to auto-emit the response
     * @var bool
     */
    protected $_autoEmitResponse = true;

    /**
     * @var bool Flag; allow overwriting existing methods when creating server definition
     */
    protected $_overwriteExistingMethods = true;

    /**
     * Request object
     * @var Zend_Json_Server_Request
     */
    protected $_request;

    /**
     * Response object
     * @var Zend_Json_Server_Response
     */
    protected $_response;

    /**
     * SMD object
     * @var Zend_Json_Server_Smd
     */
    protected $_serviceMap;

    /**
     * SMD class accessors
     * @var array
     */
    protected $_smdMethods;

    /**
     * @var Zend_Server_Description
     */
    protected $_table;

    /**
     * Attach a function or callback to the server
     * 
     * @param  string|array $function Valid PHP callback
     * @param  string $namespace  Ignored
     * @return Zend_Json_Server
     */
    public function addFunction($function, $namespace = '')
    {
        if (!is_string($function) && (!is_array($function) || (2 > count($function)))) {
            require_once 'Zend/Json/Server/Exception.php';
            throw new Zend_Json_Server_Exception('Unable to attach function; invalid');
        }

        if (!is_callable($function)) {
            require_once 'Zend/Json/Server/Exception.php';
            throw new Zend_Json_Server_Exception('Unable to attach function; does not exist');
        }

        $argv = null;
        if (2 < func_num_args()) {
            $argv = func_get_args();
            $argv = array_slice($argv, 2);
        }

        require_once 'Zend/Server/Reflection.php';
        if (is_string($function)) {
            $method = Zend_Server_Reflection::reflectFunction($function, $argv, $namespace);
        } else {
            $class  = array_shift($function);
            $action = array_shift($function);
            $reflection = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
            $methods = $reflection->getMethods();
            $found   = false;
            foreach ($methods as $method) {
                if ($action == $method->getName()) {
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $this->fault('Method not found', -32601);
                return $this;
            }
        }

        $definition = $this->_buildSignature($method);
        $this->_addMethodServiceMap($definition);

        return $this;
    }

    /**
     * Register a class with the server
     * 
     * @param  string $class 
     * @param  string $namespace Ignored
     * @param  mixed $argv Ignored
     * @return Zend_Json_Server
     */
    public function setClass($class, $namespace = '', $argv = null)
    {
        $argv = null;
        if (3 < func_num_args()) {
            $argv = func_get_args();
            $argv = array_slice($argv, 3);
        }

        require_once 'Zend/Server/Reflection.php';
        $reflection = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);

        foreach ($reflection->getMethods() as $method) {
            $definition = $this->_buildSignature($method, $class);
            $this->_addMethodServiceMap($definition);
        }
        return $this;
    }

    /**
     * Indicate fault response
     * 
     * @param  string $fault 
     * @param  int $code 
     * @return false
     */
    public function fault($fault = null, $code = 404, $data = null)
    {
        require_once 'Zend/Json/Server/Error.php';
        $error = new Zend_Json_Server_Error($fault, $code, $data);
        $this->getResponse()->setError($error);
        return $error;
    }

    /**
     * Handle request
     * 
     * @param  Zend_Json_Server_Request $request 
     * @return null|Zend_Json_Server_Response
     */
    public function handle($request = false)
    {
        if ((false !== $request) && (!$request instanceof Zend_Json_Server_Request)) {
            require_once 'Zend/Json/Server/Exception.php';
            throw new Zend_Json_Server_Exception('Invalid request type provided; cannot handle');
        } elseif ($request) {
            $this->setRequest($request);
        }

        // Handle request
        $this->_handle();

        // Get response
        $response = $this->_getReadyResponse();

        // Emit response?
        if ($this->autoEmitResponse()) {
            echo $response;
            return;
        }

        // or return it?
        return $response;
    }

    /**
     * Load function definitions
     * 
     * @param  array|Zend_Server_Definition $definition 
     * @return void
     */
    public function loadFunctions($definition)
    {
        if (!is_array($definition) && (!$definition instanceof Zend_Server_Definition)) {
            require_once 'Zend/Json/Server/Exception.php';
            throw new Zend_Json_Server_Exception('Invalid definition provided to loadFunctions()');
        }

        foreach ($definition as $key => $method) {
            $this->_table->addMethod($method, $key);
            $this->_addMethodServiceMap($method);
        }
    }

    public function setPersistence($mode)
    {
    }

    /**
     * Set request object
     * 
     * @param  Zend_Json_Server_Request $request 
     * @return Zend_Json_Server
     */
    public function setRequest(Zend_Json_Server_Request $request)
    {
        $this->_request = $request;
        return $this;
    }

    /**
     * Get JSON-RPC request object
     * 
     * @return Zend_Json_Server_Request
     */
    public function getRequest()
    {
        if (null === ($request = $this->_request)) {
            require_once 'Zend/Json/Server/Request/Http.php';
            $this->setRequest(new Zend_Json_Server_Request_Http());
        }
        return $this->_request;
    }

    /**
     * Set response object
     * 
     * @param  Zend_Json_Server_Response $response 
     * @return Zend_Json_Server
     */
    public function setResponse(Zend_Json_Server_Response $response)
    {
        $this->_response = $response;
        return $this;
    }

    /**
     * Get response object
     * 
     * @return Zend_Json_Server_Response
     */
    public function getResponse()
    {
        if (null === ($response = $this->_response)) {
            require_once 'Zend/Json/Server/Response/Http.php';
            $this->setResponse(new Zend_Json_Server_Response_Http());
        }
        return $this->_response;
    }

    /**
     * Set flag indicating whether or not to auto-emit response
     * 
     * @param  bool $flag 
     * @return Zend_Json_Server
     */
    public function setAutoEmitResponse($flag)
    {
        $this->_autoEmitResponse = (bool) $flag;
        return $this;
    }

    /**
     * Will we auto-emit the response?
     * 
     * @return bool
     */
    public function autoEmitResponse()
    {
        return $this->_autoEmitResponse;
    }

    // overloading for SMD metadata
    /**
     * Overload to accessors of SMD object
     * 
     * @param  string $method 
     * @param  array $args 
     * @return mixed
     */
    public function __call($method, $args)
    {
        if (preg_match('/^(set|get)/', $method, $matches)) {
            if (in_array($method, $this->_getSmdMethods())) {
                if ('set' == $matches[1]) {
                    $value = array_shift($args);
                    $this->getServiceMap()->$method($value);
                    return $this;
                } else {
                    return $this->getServiceMap()->$method();
                }
            }
        }
        return null;
    }

    /**
     * Retrieve SMD object
     * 
     * @return Zend_Json_Server_Smd
     */
    public function getServiceMap()
    {
        if (null === $this->_serviceMap) {
            require_once 'Zend/Json/Server/Smd.php';
            $this->_serviceMap = new Zend_Json_Server_Smd();
        }
        return $this->_serviceMap;
    }

    /**
     * Add service method to service map
     * 
     * @param  Zend_Server_Reflection_Function $method 
     * @return void
     */
    protected function _addMethodServiceMap(Zend_Server_Method_Definition $method)
    {
        $serviceInfo = array(
            'name'   => $method->getName(),
            'return' => $this->_getReturnType($method),
        );
        $params = $this->_getParams($method);
        $serviceInfo['params'] = $params;
        $serviceMap = $this->getServiceMap();
        if (false !== $serviceMap->getService($serviceInfo['name'])) {
            $serviceMap->removeService($serviceInfo['name']);
        }
        $serviceMap->addService($serviceInfo);
    }

    /**
     * Translate PHP type to JSON type
     * 
     * @param  string $type 
     * @return string
     */
    protected function _fixType($type)
    {
        return $type;
    }

    /**
     * Get default params from signature
     * 
     * @param  array $args 
     * @param  array $params 
     * @return array
     */
    protected function _getDefaultParams(array $args, array $params)
    {
        $defaultParams = array_slice($params, count($args));
        foreach ($defaultParams as $param) {
            $value = null;
            if (array_key_exists('default', $param)) {
                $value = $param['default'];
            }
            array_push($args, $value);
        }
        return $args;
    }

    /**
     * Get method param type
     * 
     * @param  Zend_Server_Reflection_Function_Abstract $method 
     * @return string|array
     */
    protected function _getParams(Zend_Server_Method_Definition $method)
    {
        $params = array();
        foreach ($method->getPrototypes() as $prototype) {
            foreach ($prototype->getParameterObjects() as $key => $parameter) {
                if (!isset($params[$key])) {
                    $params[$key] = array(
                        'type'     => $parameter->getType(),
                        'name'     => $parameter->getName(),
                        'optional' => $parameter->isOptional(),
                    );
                    if (null !== ($default = $parameter->getDefaultValue())) {
                        $params[$key]['default'] = $default;
                    }
                    $description = $parameter->getDescription();
                    if (!empty($description)) {
                        $params[$key]['description'] = $description;
                    }
                    continue;
                }
                $newType = $parameter->getType();
                if (!is_array($params[$key]['type'])) {
                    if ($params[$key]['type'] == $newType) {
                        continue;
                    }
                    $params[$key]['type'] = (array) $params[$key]['type'];
                } elseif (in_array($newType, $params[$key]['type'])) {
                    continue;
                }
                array_push($params[$key]['type'], $parameter->getType());
            }
        }
        return $params;
    }

    /**
     * Set response state
     * 
     * @return Zend_Json_Server_Response
     */
    protected function _getReadyResponse()
    {
        $request  = $this->getRequest();
        $response = $this->getResponse();

        $response->setServiceMap($this->getServiceMap());
        if (null !== ($id = $request->getId())) {
            $response->setId($id);
        }
        if (null !== ($version = $request->getVersion())) {
            $response->setVersion($version);
        }

        return $response;
    }

    /**
     * Get method return type
     * 
     * @param  Zend_Server_Reflection_Function_Abstract $method 
     * @return string|array
     */
    protected function _getReturnType(Zend_Server_Method_Definition $method)
    {
        $return = array();
        foreach ($method->getPrototypes() as $prototype) {
            $return[] = $prototype->getReturnType();
        }
        if (1 == count($return)) {
            return $return[0];
        }
        return $return;
    }

    /**
     * Retrieve list of allowed SMD methods for proxying
     * 
     * @return array
     */
    protected function _getSmdMethods()
    {
        if (null === $this->_smdMethods) {
            $this->_smdMethods = array();
            require_once 'Zend/Json/Server/Smd.php';
            $methods = get_class_methods('Zend_Json_Server_Smd');
            foreach ($methods as $key => $method) {
                if (!preg_match('/^(set|get)/', $method)) {
                    continue;
                }
                if (strstr($method, 'Service')) {
                    continue;
                }
                $this->_smdMethods[] = $method;
            }
        }
        return $this->_smdMethods;
    }

    /**
     * Internal method for handling request
     * 
     * @return void
     */
    protected function _handle()
    {
        $request = $this->getRequest();

        if (!$request->isMethodError() && (null === $request->getMethod())) {
            return $this->fault('Invalid Request', -32600);
        }

        if ($request->isMethodError()) {
            return $this->fault('Invalid Request', -32600);
        }

        $method = $request->getMethod();
        if (!$this->_table->hasMethod($method)) {
            return $this->fault('Method not found', -32601);
        }

        $params        = $request->getParams();
        $invocable     = $this->_table->getMethod($method);
        $serviceMap    = $this->getServiceMap();
        $service       = $serviceMap->getService($method);
        $serviceParams = $service->getParams();

        if (count($params) < count($serviceParams)) {
            $params = $this->_getDefaultParams($params, $serviceParams);
        }

        try {
            $result = $this->_dispatch($invocable, $params);
        } catch (Exception $e) {
            return $this->fault($e->getMessage(), $e->getCode());
        }

        $this->getResponse()->setResult($result);
    }
}
Rest/Client/Result/Exception.php000066600000001575151256604600012645 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Rest
 * @subpackage Client
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Rest_Client_Exception
 */
require_once "Zend/Rest/Client/Exception.php";

class Zend_Rest_Client_Result_Exception extends Zend_Rest_Client_Exception{}Rest/Exception.php000066600000002031151256604600010135 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Rest
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


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


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

Rest/Client.php000066600000016733151256604600007433 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Rest
 * @subpackage Client
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


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

/** Zend_Rest_Client_Result */
require_once 'Zend/Rest/Client/Result.php';

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

/**
 * @category   Zend
 * @package    Zend_Rest
 * @subpackage Client
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Rest_Client extends Zend_Service_Abstract
{
    /**
     * Data for the query
     * @var array
     */
    protected $_data = array();

     /**
     * Zend_Uri of this web service
     * @var Zend_Uri_Http
     */
    protected $_uri = null;

    /**
     * Constructor
     *
     * @param string|Zend_Uri_Http $uri URI for the web service
     * @return void
     */
    public function __construct($uri = null)
    {
        if (!empty($uri)) {
            $this->setUri($uri);
        }
    }

    /**
     * Set the URI to use in the request
     *
     * @param string|Zend_Uri_Http $uri URI for the web service
     * @return Zend_Rest_Client
     */
    public function setUri($uri)
    {
        if ($uri instanceof Zend_Uri_Http) {
            $this->_uri = $uri;
        } else {
            $this->_uri = Zend_Uri::factory($uri);
        }

        return $this;
    }

    /**
     * Retrieve the current request URI object
     *
     * @return Zend_Uri_Http
     */
    public function getUri()
    {
        return $this->_uri;
    }

    /**
     * Call a remote REST web service URI and return the Zend_Http_Response object
     *
     * @param  string $path            The path to append to the URI
     * @throws Zend_Rest_Client_Exception
     * @return void
     */
    final private function _prepareRest($path)
    {
        // Get the URI object and configure it
        if (!$this->_uri instanceof Zend_Uri_Http) {
            require_once 'Zend/Rest/Client/Exception.php';
            throw new Zend_Rest_Client_Exception('URI object must be set before performing call');
        }

        $uri = $this->_uri->getUri();

        if ($path[0] != '/' && $uri[strlen($uri)-1] != '/') {
            $path = '/' . $path;
        }

        $this->_uri->setPath($path);

        /**
         * Get the HTTP client and configure it for the endpoint URI.  Do this each time
         * because the Zend_Http_Client instance is shared among all Zend_Service_Abstract subclasses.
         */
        self::getHttpClient()->resetParameters()->setUri($this->_uri);
    }

    /**
     * Performs an HTTP GET request to the $path.
     *
     * @param string $path
     * @param array  $query Array of GET parameters
     * @return Zend_Http_Response
     */
    final public function restGet($path, array $query = null)
    {
        $this->_prepareRest($path);
        $client = self::getHttpClient();
        $client->setParameterGet($query);
        return $client->request('GET');
    }

    /**
     * Perform a POST or PUT
     *
     * Performs a POST or PUT request. Any data provided is set in the HTTP
     * client. String data is pushed in as raw POST data; array or object data
     * is pushed in as POST parameters.
     *
     * @param mixed $method
     * @param mixed $data
     * @return Zend_Http_Response
     */
    protected function _performPost($method, $data = null)
    {
        $client = self::getHttpClient();
        if (is_string($data)) {
            $client->setRawData($data);
        } elseif (is_array($data) || is_object($data)) {
            $client->setParameterPost((array) $data);
        }
        return $client->request($method);
    }

    /**
     * Performs an HTTP POST request to $path.
     *
     * @param string $path
     * @param mixed $data Raw data to send
     * @return Zend_Http_Response
     */
    final public function restPost($path, $data = null)
    {
        $this->_prepareRest($path);
        return $this->_performPost('POST', $data);
    }

    /**
     * Performs an HTTP PUT request to $path.
     *
     * @param string $path
     * @param mixed $data Raw data to send in request
     * @return Zend_Http_Response
     */
    final public function restPut($path, $data = null)
    {
        $this->_prepareRest($path);
        return $this->_performPost('PUT', $data);
    }

    /**
     * Performs an HTTP DELETE request to $path.
     *
     * @param string $path
     * @return Zend_Http_Response
     */
    final public function restDelete($path)
    {
        $this->_prepareRest($path);
        return self::getHttpClient()->request('DELETE');
    }

    /**
     * Method call overload
     *
     * Allows calling REST actions as object methods; however, you must
     * follow-up by chaining the request with a request to an HTTP request
     * method (post, get, delete, put):
     * <code>
     * $response = $rest->sayHello('Foo', 'Manchu')->get();
     * </code>
     *
     * Or use them together, but in sequential calls:
     * <code>
     * $rest->sayHello('Foo', 'Manchu');
     * $response = $rest->get();
     * </code>
     *
     * @param string $method Method name
     * @param array $args Method args
     * @return Zend_Rest_Client_Result|Zend_Rest_Client Zend_Rest_Client if using
     * a remote method, Zend_Rest_Client_Result if using an HTTP request method
     */
    public function __call($method, $args)
    {
        $methods = array('post', 'get', 'delete', 'put');

        if (in_array(strtolower($method), $methods)) {
            if (!isset($args[0])) {
                $args[0] = $this->_uri->getPath();
            }
            $this->_data['rest'] = 1;
            $data = array_slice($args, 1) + $this->_data;
            $response = $this->{'rest' . $method}($args[0], $data);
            $this->_data = array();//Initializes for next Rest method.
            return new Zend_Rest_Client_Result($response->getBody());
        } else {
            // More than one arg means it's definitely a Zend_Rest_Server
            if (sizeof($args) == 1) {
                // Uses first called function name as method name
                if (!isset($this->_data['method'])) {
                    $this->_data['method'] = $method;
                    $this->_data['arg1']  = $args[0];
                }
                $this->_data[$method]  = $args[0];
            } else {
                $this->_data['method'] = $method;
                if (sizeof($args) > 0) {
                    foreach ($args as $key => $arg) {
                        $key = 'arg' . $key;
                        $this->_data[$key] = $arg;
                    }
                }
            }
            return $this;
        }
    }
}
Acl/Resource.php000066600000003267151256604600007564 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Acl
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Resource.php 8861 2008-03-16 14:30:18Z thomas $
 */


/**
 * @see Zend_Acl_Resource_Interface
 */
require_once 'Zend/Acl/Resource/Interface.php';


/**
 * @category   Zend
 * @package    Zend_Acl
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Acl_Resource implements Zend_Acl_Resource_Interface
{
    /**
     * Unique id of Resource
     *
     * @var string
     */
    protected $_resourceId;

    /**
     * Sets the Resource identifier
     *
     * @param  string $resourceId
     * @return void
     */
    public function __construct($resourceId)
    {
        $this->_resourceId = (string) $resourceId;
    }

    /**
     * Defined by Zend_Acl_Resource_Interface; returns the Resource identifier
     *
     * @return string
     */
    public function getResourceId()
    {
        return $this->_resourceId;
    }

}
Acl/Exception.php000066600000002137151256604600007726 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Acl
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8861 2008-03-16 14:30:18Z thomas $
 */


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


/**
 * @category   Zend
 * @package    Zend_Acl
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Acl_Exception extends Zend_Exception
{}
Db/Table/Row/Abstract.php000066600000111661151256604600011162 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Table
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Abstract.php 6332 2007-09-13 00:35:08Z bkarwin $
 */

/**
 * @see Zend_Db
 */
require_once 'Zend/Db.php';

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

/**
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Table
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Db_Table_Row_Abstract implements ArrayAccess
{

    /**
     * The data for each column in the row (column_name => value).
     * The keys must match the physical names of columns in the
     * table for which this row is defined.
     *
     * @var array
     */
    protected $_data = array();

    /**
     * This is set to a copy of $_data when the data is fetched from
     * a database, specified as a new tuple in the constructor, or
     * when dirty data is posted to the database with save().
     *
     * @var array
     */
    protected $_cleanData = array();

    /**
     * Tracks columns where data has been updated. Allows more specific insert and
     * update operations.
     *
     * @var array
     */
    protected $_modifiedFields = array();

    /**
     * Zend_Db_Table_Abstract parent class or instance.
     *
     * @var Zend_Db_Table_Abstract
     */
    protected $_table = null;

    /**
     * Connected is true if we have a reference to a live
     * Zend_Db_Table_Abstract object.
     * This is false after the Rowset has been deserialized.
     *
     * @var boolean
     */
    protected $_connected = true;

    /**
     * A row is marked read only if it contains columns that are not physically represented within
     * the database schema (e.g. evaluated columns/Zend_Db_Expr columns). This can also be passed
     * as a run-time config options as a means of protecting row data.
     *
     * @var boolean
     */
    protected $_readOnly = false;

    /**
     * Name of the class of the Zend_Db_Table_Abstract object.
     *
     * @var string
     */
    protected $_tableClass = null;

    /**
     * Primary row key(s).
     *
     * @var array
     */
    protected $_primary;

    /**
     * Constructor.
     *
     * Supported params for $config are:-
     * - table       = class name or object of type Zend_Db_Table_Abstract
     * - data        = values of columns in this row.
     *
     * @param  array $config OPTIONAL Array of user-specified config options.
     * @return void
     * @throws Zend_Db_Table_Row_Exception
     */
    public function __construct(array $config = array())
    {
        if (isset($config['table']) && $config['table'] instanceof Zend_Db_Table_Abstract) {
            $this->_table = $config['table'];
            $this->_tableClass = get_class($this->_table);
        }

        if (isset($config['data'])) {
            if (!is_array($config['data'])) {
                require_once 'Zend/Db/Table/Row/Exception.php';
                throw new Zend_Db_Table_Row_Exception('Data must be an array');
            }
            $this->_data = $config['data'];
        }
        if (isset($config['stored']) && $config['stored'] === true) {
            $this->_cleanData = $this->_data;
        }

        if (isset($config['readOnly']) && $config['readOnly'] === true) {
            $this->setReadOnly(true);
        }

        // Retrieve primary keys from table schema
        if (($table = $this->_getTable())) {
            $info = $table->info();
            $this->_primary = (array) $info['primary'];
        }

        $this->init();
    }

    /**
     * Transform a column name from the user-specified form
     * to the physical form used in the database.
     * You can override this method in a custom Row class
     * to implement column name mappings, for example inflection.
     *
     * @param string $columnName Column name given.
     * @return string The column name after transformation applied (none by default).
     * @throws Zend_Db_Table_Row_Exception if the $columnName is not a string.
     */
    protected function _transformColumn($columnName)
    {
        if (!is_string($columnName)) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception('Specified column is not a string');
        }
        // Perform no transformation by default
        return $columnName;
    }

    /**
     * Retrieve row field value
     *
     * @param  string $columnName The user-specified column name.
     * @return string             The corresponding column value.
     * @throws Zend_Db_Table_Row_Exception if the $columnName is not a column in the row.
     */
    public function __get($columnName)
    {
        $columnName = $this->_transformColumn($columnName);
        if (!array_key_exists($columnName, $this->_data)) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("Specified column \"$columnName\" is not in the row");
        }
        return $this->_data[$columnName];
    }

    /**
     * Set row field value
     *
     * @param  string $columnName The column key.
     * @param  mixed  $value      The value for the property.
     * @return void
     * @throws Zend_Db_Table_Row_Exception
     */
    public function __set($columnName, $value)
    {
        $columnName = $this->_transformColumn($columnName);
        if (!array_key_exists($columnName, $this->_data)) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("Specified column \"$columnName\" is not in the row");
        }
        $this->_data[$columnName] = $value;
        $this->_modifiedFields[$columnName] = true;
    }

    /**
     * Test existence of row field
     *
     * @param  string  $columnName   The column key.
     * @return boolean
     */
    public function __isset($columnName)
    {
        $columnName = $this->_transformColumn($columnName);
        return array_key_exists($columnName, $this->_data);
    }

    /**
     * Store table, primary key and data in serialized object
     *
     * @return array
     */
    public function __sleep()
    {
        return array('_tableClass', '_primary', '_data', '_cleanData', '_readOnly' ,'_modifiedFields');
    }

    /**
     * Setup to do on wakeup.
     * A de-serialized Row should not be assumed to have access to a live
     * database connection, so set _connected = false.
     *
     * @return void
     */
    public function __wakeup()
    {
        $this->_connected = false;
    }

    /**
     * Proxy to __isset
     * Required by the ArrayAccess implementation
     *
     * @param string $offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return $this->__isset($offset);
    }

    /**
     * Proxy to __get
     * Required by the ArrayAccess implementation
     *
     * @param string $offset
     * @return string
     */
     public function offsetGet($offset)
     {
         return $this->__get($offset);
     }

     /**
      * Proxy to __set
      * Required by the ArrayAccess implementation
      *
      * @param string $offset
      * @param mixed $value
      */
     public function offsetSet($offset, $value)
     {
         $this->__set($offset, $value);
     }

     /**
      * Does nothing
      * Required by the ArrayAccess implementation
      *
      * @param string $offset
      */
     public function offsetUnset($offset)
     {
     }

    /**
     * Initialize object
     *
     * Called from {@link __construct()} as final step of object instantiation.
     *
     * @return void
     */
    public function init()
    {
    }

    /**
     * Returns the table object, or null if this is disconnected row
     *
     * @return Zend_Db_Table_Abstract|null
     */
    public function getTable()
    {
        return $this->_table;
    }

    /**
     * Set the table object, to re-establish a live connection
     * to the database for a Row that has been de-serialized.
     *
     * @param Zend_Db_Table_Abstract $table
     * @return boolean
     * @throws Zend_Db_Table_Row_Exception
     */
    public function setTable(Zend_Db_Table_Abstract $table = null)
    {
        if ($table == null) {
            $this->_table = null;
            $this->_connected = false;
            return false;
        }

        $tableClass = get_class($table);
        if (! $table instanceof $this->_tableClass) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("The specified Table is of class $tableClass, expecting class to be instance of $this->_tableClass");
        }

        $this->_table = $table;
        $this->_tableClass = $tableClass;

        $info = $this->_table->info();

        if ($info['cols'] != array_keys($this->_data)) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception('The specified Table does not have the same columns as the Row');
        }

        if (! array_intersect((array) $this->_primary, $info['primary']) == (array) $this->_primary) {

            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("The specified Table '$tableClass' does not have the same primary key as the Row");
        }

        $this->_connected = true;
        return true;
    }

    /**
     * Query the class name of the Table object for which this
     * Row was created.
     *
     * @return string
     */
    public function getTableClass()
    {
        return $this->_tableClass;
    }

    /**
     * Test the connected status of the row.
     *
     * @return boolean
     */
    public function isConnected()
    {
        return $this->_connected;
    }

    /**
     * Test the read-only status of the row.
     *
     * @return boolean
     */
    public function isReadOnly()
    {
        return $this->_readOnly;
    }

    /**
     * Set the read-only status of the row.
     *
     * @param boolean $flag
     * @return boolean
     */
    public function setReadOnly($flag)
    {
        $this->_readOnly = (bool) $flag;
    }

    /**
     * Returns an instance of the parent table's Zend_Db_Table_Select object.
     *
     * @return Zend_Db_Table_Select
     */
    public function select()
    {
        return $this->getTable()->select();
    }

    /**
     * Saves the properties to the database.
     *
     * This performs an intelligent insert/update, and reloads the
     * properties with fresh data from the table on success.
     *
     * @return mixed The primary key value(s), as an associative array if the
     *     key is compound, or a scalar if the key is single-column.
     */
    public function save()
    {
        /**
         * If the _cleanData array is empty,
         * this is an INSERT of a new row.
         * Otherwise it is an UPDATE.
         */
        if (empty($this->_cleanData)) {
            return $this->_doInsert();
        } else {
            return $this->_doUpdate();
        }
    }

    /**
     * @return mixed The primary key value(s), as an associative array if the
     *     key is compound, or a scalar if the key is single-column.
     */
    protected function _doInsert()
    {
        /**
         * A read-only row cannot be saved.
         */
        if ($this->_readOnly === true) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception('This row has been marked read-only');
        }

        /**
         * Run pre-INSERT logic
         */
        $this->_insert();

        /**
         * Execute the INSERT (this may throw an exception)
         */
        $data = array_intersect_key($this->_data, $this->_modifiedFields);
        $primaryKey = $this->_getTable()->insert($data);

        /**
         * Normalize the result to an array indexed by primary key column(s).
         * The table insert() method may return a scalar.
         */
        if (is_array($primaryKey)) {
            $newPrimaryKey = $primaryKey;
        } else {
            $newPrimaryKey = array(current((array) $this->_primary) => $primaryKey);
        }

        /**
         * Save the new primary key value in _data.  The primary key may have
         * been generated by a sequence or auto-increment mechanism, and this
         * merge should be done before the _postInsert() method is run, so the
         * new values are available for logging, etc.
         */
        $this->_data = array_merge($this->_data, $newPrimaryKey);

        /**
         * Run post-INSERT logic
         */
        $this->_postInsert();

        /**
         * Update the _cleanData to reflect that the data has been inserted.
         */
        $this->_refresh();

        return $primaryKey;
    }

    /**
     * @return mixed The primary key value(s), as an associative array if the
     *     key is compound, or a scalar if the key is single-column.
     */
    protected function _doUpdate()
    {
        /**
         * A read-only row cannot be saved.
         */
        if ($this->_readOnly === true) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception('This row has been marked read-only');
        }

        /**
         * Get expressions for a WHERE clause
         * based on the primary key value(s).
         */
        $where = $this->_getWhereQuery(false);

        /**
         * Run pre-UPDATE logic
         */
        $this->_update();

        /**
         * Compare the data to the modified fields array to discover
         * which columns have been changed.
         */
        $diffData = array_intersect_key($this->_data, $this->_modifiedFields);

        /**
         * Were any of the changed columns part of the primary key?
         */
        $pkDiffData = array_intersect_key($diffData, array_flip((array)$this->_primary));

        /**
         * Execute cascading updates against dependent tables.
         * Do this only if primary key value(s) were changed.
         */
        if (count($pkDiffData) > 0) {
            $depTables = $this->_getTable()->getDependentTables();
            if (!empty($depTables)) {
                $db = $this->_getTable()->getAdapter();
                $pkNew = $this->_getPrimaryKey(true);
                $pkOld = $this->_getPrimaryKey(false);
                foreach ($depTables as $tableClass) {
                    try {
                        @Zend_Loader::loadClass($tableClass);
                    } catch (Zend_Exception $e) {
                        require_once 'Zend/Db/Table/Row/Exception.php';
                        throw new Zend_Db_Table_Row_Exception($e->getMessage());
                    }
                    $t = new $tableClass(array('db' => $db));
                    $t->_cascadeUpdate($this->getTableClass(), $pkOld, $pkNew);
                }
            }
        }

        /**
         * Execute the UPDATE (this may throw an exception)
         * Do this only if data values were changed.
         * Use the $diffData variable, so the UPDATE statement
         * includes SET terms only for data values that changed.
         */
        if (count($diffData) > 0) {
            $this->_getTable()->update($diffData, $where);
        }

        /**
         * Run post-UPDATE logic.  Do this before the _refresh()
         * so the _postUpdate() function can tell the difference
         * between changed data and clean (pre-changed) data.
         */
        $this->_postUpdate();

        /**
         * Refresh the data just in case triggers in the RDBMS changed
         * any columns.  Also this resets the _cleanData.
         */
        $this->_refresh();

        /**
         * Return the primary key value(s) as an array
         * if the key is compound or a scalar if the key
         * is a scalar.
         */
        $primaryKey = $this->_getPrimaryKey(true);
        if (count($primaryKey) == 1) {
            return current($primaryKey);
        }

        return $primaryKey;
    }

    /**
     * Deletes existing rows.
     *
     * @return int The number of rows deleted.
     */
    public function delete()
    {
        /**
         * A read-only row cannot be deleted.
         */
        if ($this->_readOnly === true) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception('This row has been marked read-only');
        }

        $where = $this->_getWhereQuery();

        /**
         * Execute pre-DELETE logic
         */
        $this->_delete();

        /**
         * Execute cascading deletes against dependent tables
         */
        $depTables = $this->_getTable()->getDependentTables();
        if (!empty($depTables)) {
            $db = $this->_getTable()->getAdapter();
            $pk = $this->_getPrimaryKey();
            foreach ($depTables as $tableClass) {
                try {
                    @Zend_Loader::loadClass($tableClass);
                } catch (Zend_Exception $e) {
                    require_once 'Zend/Db/Table/Row/Exception.php';
                    throw new Zend_Db_Table_Row_Exception($e->getMessage());
                }
                $t = new $tableClass(array('db' => $db));
                $t->_cascadeDelete($this->getTableClass(), $pk);
            }
        }

        /**
         * Execute the DELETE (this may throw an exception)
         */
        $result = $this->_getTable()->delete($where);

        /**
         * Execute post-DELETE logic
         */
        $this->_postDelete();

        /**
         * Reset all fields to null to indicate that the row is not there
         */
        $this->_data = array_combine(
            array_keys($this->_data),
            array_fill(0, count($this->_data), null)
        );

        return $result;
    }

    /**
     * Returns the column/value data as an array.
     *
     * @return array
     */
    public function toArray()
    {
        return (array)$this->_data;
    }

    /**
     * Sets all data in the row from an array.
     *
     * @param  array $data
     * @return Zend_Db_Table_Row_Abstract Provides a fluent interface
     */
    public function setFromArray(array $data)
    {
        $data = array_intersect_key($data, $this->_data);

        foreach ($data as $columnName => $value) {
            $this->__set($columnName, $value);
        }

        return $this;
    }

    /**
     * Refreshes properties from the database.
     *
     * @return void
     */
    public function refresh()
    {
        return $this->_refresh();
    }

    /**
     * Retrieves an instance of the parent table.
     *
     * @return Zend_Db_Table_Abstract
     */
    protected function _getTable()
    {
        if (!$this->_connected) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception('Cannot save a Row unless it is connected');
        }
        return $this->_table;
    }

    /**
     * Retrieves an associative array of primary keys.
     *
     * @param bool $useDirty
     * @return array
     */
    protected function _getPrimaryKey($useDirty = true)
    {
        if (!is_array($this->_primary)) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("The primary key must be set as an array");
        }

        $primary = array_flip($this->_primary);
        if ($useDirty) {
            $array = array_intersect_key($this->_data, $primary);
        } else {
            $array = array_intersect_key($this->_cleanData, $primary);
        }
        if (count($primary) != count($array)) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("The specified Table '$this->_tableClass' does not have the same primary key as the Row");
        }
        return $array;
    }

    /**
     * Constructs where statement for retrieving row(s).
     *
     * @param bool $useDirty
     * @return array
     */
    protected function _getWhereQuery($useDirty = true)
    {
        $where = array();
        $db = $this->_getTable()->getAdapter();
        $primaryKey = $this->_getPrimaryKey($useDirty);
        $info = $this->_getTable()->info();
        $metadata = $info[Zend_Db_Table_Abstract::METADATA];

        // retrieve recently updated row using primary keys
        $where = array();
        foreach ($primaryKey as $column => $value) {
            $tableName = $db->quoteIdentifier($info[Zend_Db_Table_Abstract::NAME], true);
            $type = $metadata[$column]['DATA_TYPE'];
            $columnName = $db->quoteIdentifier($column, true);
            $where[] = $db->quoteInto("{$tableName}.{$columnName} = ?", $value, $type);
        }
        return $where;
    }

    /**
     * Refreshes properties from the database.
     *
     * @return void
     */
    protected function _refresh()
    {
        $where = $this->_getWhereQuery();
        $row = $this->_getTable()->fetchRow($where);

        if (null === $row) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception('Cannot refresh row as parent is missing');
        }

        $this->_data = $row->toArray();
        $this->_cleanData = $this->_data;
        $this->_modifiedFields = array();
    }

    /**
     * Allows pre-insert logic to be applied to row.
     * Subclasses may override this method.
     *
     * @return void
     */
    protected function _insert()
    {
    }

    /**
     * Allows post-insert logic to be applied to row.
     * Subclasses may override this method.
     *
     * @return void
     */
    protected function _postInsert()
    {
    }

    /**
     * Allows pre-update logic to be applied to row.
     * Subclasses may override this method.
     *
     * @return void
     */
    protected function _update()
    {
    }

    /**
     * Allows post-update logic to be applied to row.
     * Subclasses may override this method.
     *
     * @return void
     */
    protected function _postUpdate()
    {
    }

    /**
     * Allows pre-delete logic to be applied to row.
     * Subclasses may override this method.
     *
     * @return void
     */
    protected function _delete()
    {
    }

    /**
     * Allows post-delete logic to be applied to row.
     * Subclasses may override this method.
     *
     * @return void
     */
    protected function _postDelete()
    {
    }

    /**
     * Prepares a table reference for lookup.
     *
     * Ensures all reference keys are set and properly formatted.
     *
     * @param Zend_Db_Table_Abstract $dependentTable
     * @param Zend_Db_Table_Abstract $parentTable
     * @param string                 $ruleKey
     * @return array
     */
    protected function _prepareReference(Zend_Db_Table_Abstract $dependentTable, Zend_Db_Table_Abstract $parentTable, $ruleKey)
    {
        $map = $dependentTable->getReference(get_class($parentTable), $ruleKey);

        if (!isset($map[Zend_Db_Table_Abstract::REF_COLUMNS])) {
            $parentInfo = $parentTable->info();
            $map[Zend_Db_Table_Abstract::REF_COLUMNS] = array_values((array) $parentInfo['primary']);
        }

        $map[Zend_Db_Table_Abstract::COLUMNS] = (array) $map[Zend_Db_Table_Abstract::COLUMNS];
        $map[Zend_Db_Table_Abstract::REF_COLUMNS] = (array) $map[Zend_Db_Table_Abstract::REF_COLUMNS];

        return $map;
    }

    /**
     * Query a dependent table to retrieve rows matching the current row.
     *
     * @param string|Zend_Db_Table_Abstract  $dependentTable
     * @param string                         OPTIONAL $ruleKey
     * @param Zend_Db_Table_Select           OPTIONAL $select
     * @return Zend_Db_Table_Rowset_Abstract Query result from $dependentTable
     * @throws Zend_Db_Table_Row_Exception If $dependentTable is not a table or is not loadable.
     */
    public function findDependentRowset($dependentTable, $ruleKey = null, Zend_Db_Table_Select $select = null)
    {
        $db = $this->_getTable()->getAdapter();

        if (is_string($dependentTable)) {
            try {
                @Zend_Loader::loadClass($dependentTable);
            } catch (Zend_Exception $e) {
                require_once 'Zend/Db/Table/Row/Exception.php';
                throw new Zend_Db_Table_Row_Exception($e->getMessage());
            }
            $dependentTable = new $dependentTable(array('db' => $db));
        }
        if (! $dependentTable instanceof Zend_Db_Table_Abstract) {
            $type = gettype($dependentTable);
            if ($type == 'object') {
                $type = get_class($dependentTable);
            }
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("Dependent table must be a Zend_Db_Table_Abstract, but it is $type");
        }

        if ($select === null) {
            $select = $dependentTable->select();
        } else {
            $select->setTable($dependentTable);
        }

        $map = $this->_prepareReference($dependentTable, $this->_getTable(), $ruleKey);

        for ($i = 0; $i < count($map[Zend_Db_Table_Abstract::COLUMNS]); ++$i) {
            $parentColumnName = $db->foldCase($map[Zend_Db_Table_Abstract::REF_COLUMNS][$i]);
            $value = $this->_data[$parentColumnName];
            // Use adapter from dependent table to ensure correct query construction
            $dependentDb = $dependentTable->getAdapter();
            $dependentColumnName = $dependentDb->foldCase($map[Zend_Db_Table_Abstract::COLUMNS][$i]);
            $dependentColumn = $dependentDb->quoteIdentifier($dependentColumnName, true);
            $dependentInfo = $dependentTable->info();
            $type = $dependentInfo[Zend_Db_Table_Abstract::METADATA][$dependentColumnName]['DATA_TYPE'];
            $select->where("$dependentColumn = ?", $value, $type);
        }

        return $dependentTable->fetchAll($select);
    }

    /**
     * Query a parent table to retrieve the single row matching the current row.
     *
     * @param string|Zend_Db_Table_Abstract $parentTable
     * @param string                        OPTIONAL $ruleKey
     * @return Zend_Db_Table_Row_Abstract   Query result from $parentTable
     * @throws Zend_Db_Table_Row_Exception If $parentTable is not a table or is not loadable.
     */
    public function findParentRow($parentTable, $ruleKey = null, Zend_Db_Table_Select $select = null)
    {
        $db = $this->_getTable()->getAdapter();

        if (is_string($parentTable)) {
            try {
                @Zend_Loader::loadClass($parentTable);
            } catch (Zend_Exception $e) {
                require_once 'Zend/Db/Table/Row/Exception.php';
                throw new Zend_Db_Table_Row_Exception($e->getMessage());
            }
            $parentTable = new $parentTable(array('db' => $db));
        }
        if (! $parentTable instanceof Zend_Db_Table_Abstract) {
            $type = gettype($parentTable);
            if ($type == 'object') {
                $type = get_class($parentTable);
            }
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("Parent table must be a Zend_Db_Table_Abstract, but it is $type");
        }

        if ($select === null) {
            $select = $parentTable->select();
        } else {
            $select->setTable($parentTable);
        }

        $map = $this->_prepareReference($this->_getTable(), $parentTable, $ruleKey);

        for ($i = 0; $i < count($map[Zend_Db_Table_Abstract::COLUMNS]); ++$i) {
            $dependentColumnName = $db->foldCase($map[Zend_Db_Table_Abstract::COLUMNS][$i]);
            $value = $this->_data[$dependentColumnName];
            // Use adapter from parent table to ensure correct query construction
            $parentDb = $parentTable->getAdapter();
            $parentColumnName = $parentDb->foldCase($map[Zend_Db_Table_Abstract::REF_COLUMNS][$i]);
            $parentColumn = $parentDb->quoteIdentifier($parentColumnName, true);
            $parentInfo = $parentTable->info();
            $type = $parentInfo[Zend_Db_Table_Abstract::METADATA][$parentColumnName]['DATA_TYPE'];
            $select->where("$parentColumn = ?", $value, $type);
        }

        return $parentTable->fetchRow($select);
    }

    /**
     * @param  string|Zend_Db_Table_Abstract  $matchTable
     * @param  string|Zend_Db_Table_Abstract  $intersectionTable
     * @param  string                         OPTIONAL $primaryRefRule
     * @param  string                         OPTIONAL $matchRefRule
     * @return Zend_Db_Table_Rowset_Abstract Query result from $matchTable
     * @throws Zend_Db_Table_Row_Exception If $matchTable or $intersectionTable is not a table class or is not loadable.
     */
    public function findManyToManyRowset($matchTable, $intersectionTable, $callerRefRule = null,
                                         $matchRefRule = null, Zend_Db_Table_Select $select = null)
    {
        $db = $this->_getTable()->getAdapter();

        if (is_string($intersectionTable)) {
            try {
                @Zend_Loader::loadClass($intersectionTable);
            } catch (Zend_Exception $e) {
                require_once 'Zend/Db/Table/Row/Exception.php';
                throw new Zend_Db_Table_Row_Exception($e->getMessage());
            }
            $intersectionTable = new $intersectionTable(array('db' => $db));
        }
        if (! $intersectionTable instanceof Zend_Db_Table_Abstract) {
            $type = gettype($intersectionTable);
            if ($type == 'object') {
                $type = get_class($intersectionTable);
            }
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("Intersection table must be a Zend_Db_Table_Abstract, but it is $type");
        }

        if (is_string($matchTable)) {
            try {
                @Zend_Loader::loadClass($matchTable);
            } catch (Zend_Exception $e) {
                require_once 'Zend/Db/Table/Row/Exception.php';
                throw new Zend_Db_Table_Row_Exception($e->getMessage());
            }
            $matchTable = new $matchTable(array('db' => $db));
        }
        if (! $matchTable instanceof Zend_Db_Table_Abstract) {
            $type = gettype($matchTable);
            if ($type == 'object') {
                $type = get_class($matchTable);
            }
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception("Match table must be a Zend_Db_Table_Abstract, but it is $type");
        }

        if ($select === null) {
            $select = $matchTable->select();
        } else {
            $select->setTable($matchTable);
        }

        // Use adapter from intersection table to ensure correct query construction
        $interInfo = $intersectionTable->info();
        $interDb   = $intersectionTable->getAdapter();
        $interName = $interInfo['name'];
        $interSchema = isset($interInfo['schema']) ? $interInfo['schema'] : null;
        $matchInfo = $matchTable->info();
        $matchName = $matchInfo['name'];
        $matchSchema = isset($matchInfo['schema']) ? $matchInfo['schema'] : null;

        $matchMap = $this->_prepareReference($intersectionTable, $matchTable, $matchRefRule);

        for ($i = 0; $i < count($matchMap[Zend_Db_Table_Abstract::COLUMNS]); ++$i) {
            $interCol = $interDb->quoteIdentifier('i' . '.' . $matchMap[Zend_Db_Table_Abstract::COLUMNS][$i], true);
            $matchCol = $interDb->quoteIdentifier('m' . '.' . $matchMap[Zend_Db_Table_Abstract::REF_COLUMNS][$i], true);
            $joinCond[] = "$interCol = $matchCol";
        }
        $joinCond = implode(' AND ', $joinCond);

        $select->from(array('i' => $interName), Zend_Db_Select::SQL_WILDCARD, $interSchema)
               ->joinInner(array('m' => $matchName), $joinCond, Zend_Db_Select::SQL_WILDCARD, $matchSchema)
               ->setIntegrityCheck(false);

        $callerMap = $this->_prepareReference($intersectionTable, $this->_getTable(), $callerRefRule);

        for ($i = 0; $i < count($callerMap[Zend_Db_Table_Abstract::COLUMNS]); ++$i) {
            $callerColumnName = $db->foldCase($callerMap[Zend_Db_Table_Abstract::REF_COLUMNS][$i]);
            $value = $this->_data[$callerColumnName];
            $interColumnName = $interDb->foldCase($callerMap[Zend_Db_Table_Abstract::COLUMNS][$i]);
            $interCol = $interDb->quoteIdentifier("i.$interColumnName", true);
            $interInfo = $intersectionTable->info();
            $type = $interInfo[Zend_Db_Table_Abstract::METADATA][$interColumnName]['DATA_TYPE'];
            $select->where($interDb->quoteInto("$interCol = ?", $value, $type));
        }

        $stmt = $select->query();

        $config = array(
            'table'    => $matchTable,
            'data'     => $stmt->fetchAll(Zend_Db::FETCH_ASSOC),
            'rowClass' => $matchTable->getRowClass(),
            'readOnly' => false,
            'stored'   => true
        );

        $rowsetClass = $matchTable->getRowsetClass();
        try {
            @Zend_Loader::loadClass($rowsetClass);
        } catch (Zend_Exception $e) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception($e->getMessage());
        }
        $rowset = new $rowsetClass($config);
        return $rowset;
    }

    /**
     * Turn magic function calls into non-magic function calls
     * to the above methods.
     *
     * @param string $method
     * @param array $args OPTIONAL Zend_Db_Table_Select query modifier
     * @return Zend_Db_Table_Row_Abstract|Zend_Db_Table_Rowset_Abstract
     * @throws Zend_Db_Table_Row_Exception If an invalid method is called.
     */
    public function __call($method, array $args)
    {
        $matches = array();

        if (count($args) && $args[0] instanceof Zend_Db_Table_Select) {
            $select = $args[0];
        } else {
            $select = null;
        }

        /**
         * Recognize methods for Has-Many cases:
         * findParent<Class>()
         * findParent<Class>By<Rule>()
         * Use the non-greedy pattern repeat modifier e.g. \w+?
         */
        if (preg_match('/^findParent(\w+?)(?:By(\w+))?$/', $method, $matches)) {
            $class    = $matches[1];
            $ruleKey1 = isset($matches[2]) ? $matches[2] : null;
            return $this->findParentRow($class, $ruleKey1, $select);
        }

        /**
         * Recognize methods for Many-to-Many cases:
         * find<Class1>Via<Class2>()
         * find<Class1>Via<Class2>By<Rule>()
         * find<Class1>Via<Class2>By<Rule1>And<Rule2>()
         * Use the non-greedy pattern repeat modifier e.g. \w+?
         */
        if (preg_match('/^find(\w+?)Via(\w+?)(?:By(\w+?)(?:And(\w+))?)?$/', $method, $matches)) {
            $class    = $matches[1];
            $viaClass = $matches[2];
            $ruleKey1 = isset($matches[3]) ? $matches[3] : null;
            $ruleKey2 = isset($matches[4]) ? $matches[4] : null;
            return $this->findManyToManyRowset($class, $viaClass, $ruleKey1, $ruleKey2, $select);
        }

        /**
         * Recognize methods for Belongs-To cases:
         * find<Class>()
         * find<Class>By<Rule>()
         * Use the non-greedy pattern repeat modifier e.g. \w+?
         */
        if (preg_match('/^find(\w+?)(?:By(\w+))?$/', $method, $matches)) {
            $class    = $matches[1];
            $ruleKey1 = isset($matches[2]) ? $matches[2] : null;
            return $this->findDependentRowset($class, $ruleKey1, $select);
        }

        require_once 'Zend/Db/Table/Row/Exception.php';
        throw new Zend_Db_Table_Row_Exception("Unrecognized method '$method()'");
    }

}
Db/Table/Row/Exception.php000066600000002142151256604600011346 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Table
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Zend_Db_Table_Exception
 */
require_once 'Zend/Db/Table/Exception.php';

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

Db/Select.php000066600000121064151256604600007036 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Select
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Select.php 6897 2007-11-22 08:31:59Z thomas $
 */


/**
 * @see Zend_Db_Adapter_Abstract
 */
require_once 'Zend/Db/Adapter/Abstract.php';

/**
 * @see Zend_Db_Expr
 */
require_once 'Zend/Db/Expr.php';


/**
 * Class for SQL SELECT generation and results.
 *
 * @category   Zend
 * @package    Zend_Db
 * @subpackage Select
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Db_Select
{

    const DISTINCT       = 'distinct';
    const COLUMNS        = 'columns';
    const FROM           = 'from';
    const UNION          = 'union';
    const WHERE          = 'where';
    const GROUP          = 'group';
    const HAVING         = 'having';
    const ORDER          = 'order';
    const LIMIT_COUNT    = 'limitcount';
    const LIMIT_OFFSET   = 'limitoffset';
    const FOR_UPDATE     = 'forupdate';

    const INNER_JOIN     = 'inner join';
    const LEFT_JOIN      = 'left join';
    const RIGHT_JOIN     = 'right join';
    const FULL_JOIN      = 'full join';
    const CROSS_JOIN     = 'cross join';
    const NATURAL_JOIN   = 'natural join';

    const SQL_WILDCARD   = '*';
    const SQL_SELECT     = 'SELECT';
    const SQL_UNION      = 'UNION';
    const SQL_UNION_ALL  = 'UNION ALL';
    const SQL_FROM       = 'FROM';
    const SQL_WHERE      = 'WHERE';
    const SQL_DISTINCT   = 'DISTINCT';
    const SQL_GROUP_BY   = 'GROUP BY';
    const SQL_ORDER_BY   = 'ORDER BY';
    const SQL_HAVING     = 'HAVING';
    const SQL_FOR_UPDATE = 'FOR UPDATE';
    const SQL_AND        = 'AND';
    const SQL_AS         = 'AS';
    const SQL_OR         = 'OR';
    const SQL_ON         = 'ON';
    const SQL_ASC        = 'ASC';
    const SQL_DESC       = 'DESC';

    /**
     * Zend_Db_Adapter_Abstract object.
     *
     * @var Zend_Db_Adapter_Abstract
     */
    protected $_adapter;

    /**
     * The initial values for the $_parts array.
     * NOTE: It is important for the 'FOR_UPDATE' part to be last to ensure
     * meximum compatibility with database adapters.
     *
     * @var array
     */
    protected static $_partsInit = array(
        self::DISTINCT     => false,
        self::COLUMNS      => array(),
        self::UNION        => array(),
        self::FROM         => array(),
        self::WHERE        => array(),
        self::GROUP        => array(),
        self::HAVING       => array(),
        self::ORDER        => array(),
        self::LIMIT_COUNT  => null,
        self::LIMIT_OFFSET => null,
        self::FOR_UPDATE   => false
    );

    /**
     * Specify legal join types.
     *
     * @var array
     */
    protected static $_joinTypes = array(
        self::INNER_JOIN,
        self::LEFT_JOIN,
        self::RIGHT_JOIN,
        self::FULL_JOIN,
        self::CROSS_JOIN,
        self::NATURAL_JOIN,
    );

    /**
     * Specify legal union types.
     *
     * @var array
     */
    protected static $_unionTypes = array(
        self::SQL_UNION,
        self::SQL_UNION_ALL
    );

    /**
     * The component parts of a SELECT statement.
     * Initialized to the $_partsInit array in the constructor.
     *
     * @var array
     */
    protected $_parts = array();

    /**
     * Tracks which columns are being select from each table and join.
     *
     * @var array
     */
    protected $_tableCols = array();

    /**
     * Class constructor
     *
     * @param Zend_Db_Adapter_Abstract $adapter
     */
    public function __construct(Zend_Db_Adapter_Abstract $adapter)
    {
        $this->_adapter = $adapter;
        $this->_parts = self::$_partsInit;
    }

    /**
     * Makes the query SELECT DISTINCT.
     *
     * @param bool $flag Whether or not the SELECT is DISTINCT (default true).
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function distinct($flag = true)
    {
        $this->_parts[self::DISTINCT] = (bool) $flag;
        return $this;
    }

    /**
     * Adds a FROM table and optional columns to the query.
     *
     * The first parameter $name can be a simple string, in which case the
     * correlation name is generated automatically.  If you want to specify
     * the correlation name, the first parameter must be an associative
     * array in which the key is the physical table name, and the value is
     * the correlation name.  For example, array('table' => 'alias').
     * The correlation name is prepended to all columns fetched for this
     * table.
     *
     * The second parameter can be a single string or Zend_Db_Expr object,
     * or else an array of strings or Zend_Db_Expr objects.
     *
     * The first parameter can be null or an empty string, in which case
     * no correlation name is generated or prepended to the columns named
     * in the second parameter.
     *
     * @param  array|string|Zend_Db_Expr $name The table name or an associative array relating table name to
     *                                         correlation name.
     * @param  array|string|Zend_Db_Expr $cols The columns to select from this table.
     * @param  string $schema The schema name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function from($name, $cols = '*', $schema = null)
    {
        return $this->joinInner($name, null, $cols, $schema);
    }

    /**
     * Specifies the columns used in the FROM clause.
     *
     * The parameter can be a single string or Zend_Db_Expr object,
     * or else an array of strings or Zend_Db_Expr objects.
     *
     * @param  array|string|Zend_Db_Expr $cols The columns to select from this table.
     * @param  string $correlationName Correlation name of target table. OPTIONAL
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function columns($cols = '*', $correlationName = null)
    {
        if ($correlationName === null && count($this->_parts[self::FROM])) {
            $correlationName = current(array_keys($this->_parts[self::FROM]));
        }

        if (!array_key_exists($correlationName, $this->_parts[self::FROM])) {
            /**
             * @see Zend_Db_Select_Exception
             */
            require_once 'Zend/Db/Select/Exception.php';
            throw new Zend_Db_Select_Exception("No table has been specified for the FROM clause");
        }

        $this->_tableCols($correlationName, $cols);

        return $this;
    }

    /**
     * Adds a UNION clause to the query.
     *
     * The first parameter $select can be a string, an existing Zend_Db_Select
     * object or an array of either of these types.
     *
     * @param  array|string|Zend_Db_Select $select One or more select clauses for the UNION.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function union($select = array(), $type = self::SQL_UNION)
    {
        if (!is_array($select)) {
            $select = array();
        }

        if (!in_array($type, self::$_unionTypes)) {
            require_once 'Zend/Db/Select/Exception.php';
            throw new Zend_Db_Select_Exception("Invalid union type '{$type}'");
        }

        foreach ($select as $target) {
            $this->_parts[self::UNION][] = array($target, $type);
        }

        return $this;
    }

    /**
     * Adds a JOIN table and columns to the query.
     *
     * The $name and $cols parameters follow the same logic
     * as described in the from() method.
     *
     * @param  array|string|Zend_Db_Expr $name The table name.
     * @param  string $cond Join on this condition.
     * @param  array|string $cols The columns to select from the joined table.
     * @param  string $schema The database name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function join($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
    {
        return $this->joinInner($name, $cond, $cols, $schema);
    }

    /**
     * Add an INNER JOIN table and colums to the query
     * Rows in both tables are matched according to the expression
     * in the $cond argument.  The result set is comprised
     * of all cases where rows from the left table match
     * rows from the right table.
     *
     * The $name and $cols parameters follow the same logic
     * as described in the from() method.
     *
     * @param  array|string|Zend_Db_Expr $name The table name.
     * @param  string $cond Join on this condition.
     * @param  array|string $cols The columns to select from the joined table.
     * @param  string $schema The database name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function joinInner($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
    {
        return $this->_join(self::INNER_JOIN, $name, $cond, $cols, $schema);
    }

    /**
     * Add a LEFT OUTER JOIN table and colums to the query
     * All rows from the left operand table are included,
     * matching rows from the right operand table included,
     * and the columns from the right operand table are filled
     * with NULLs if no row exists matching the left table.
     *
     * The $name and $cols parameters follow the same logic
     * as described in the from() method.
     *
     * @param  array|string|Zend_Db_Expr $name The table name.
     * @param  string $cond Join on this condition.
     * @param  array|string $cols The columns to select from the joined table.
     * @param  string $schema The database name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function joinLeft($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
    {
        return $this->_join(self::LEFT_JOIN, $name, $cond, $cols, $schema);
    }

    /**
     * Add a RIGHT OUTER JOIN table and colums to the query.
     * Right outer join is the complement of left outer join.
     * All rows from the right operand table are included,
     * matching rows from the left operand table included,
     * and the columns from the left operand table are filled
     * with NULLs if no row exists matching the right table.
     *
     * The $name and $cols parameters follow the same logic
     * as described in the from() method.
     *
     * @param  array|string|Zend_Db_Expr $name The table name.
     * @param  string $cond Join on this condition.
     * @param  array|string $cols The columns to select from the joined table.
     * @param  string $schema The database name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function joinRight($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
    {
        return $this->_join(self::RIGHT_JOIN, $name, $cond, $cols, $schema);
    }

    /**
     * Add a FULL OUTER JOIN table and colums to the query.
     * A full outer join is like combining a left outer join
     * and a right outer join.  All rows from both tables are
     * included, paired with each other on the same row of the
     * result set if they satisfy the join condition, and otherwise
     * paired with NULLs in place of columns from the other table.
     *
     * The $name and $cols parameters follow the same logic
     * as described in the from() method.
     *
     * @param  array|string|Zend_Db_Expr $name The table name.
     * @param  string $cond Join on this condition.
     * @param  array|string $cols The columns to select from the joined table.
     * @param  string $schema The database name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function joinFull($name, $cond, $cols = self::SQL_WILDCARD, $schema = null)
    {
        return $this->_join(self::FULL_JOIN, $name, $cond, $cols, $schema);
    }

    /**
     * Add a CROSS JOIN table and colums to the query.
     * A cross join is a cartesian product; there is no join condition.
     *
     * The $name and $cols parameters follow the same logic
     * as described in the from() method.
     *
     * @param  array|string|Zend_Db_Expr $name The table name.
     * @param  array|string $cols The columns to select from the joined table.
     * @param  string $schema The database name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function joinCross($name, $cols = self::SQL_WILDCARD, $schema = null)
    {
        return $this->_join(self::CROSS_JOIN, $name, null, $cols, $schema);
    }

    /**
     * Add a NATURAL JOIN table and colums to the query.
     * A natural join assumes an equi-join across any column(s)
     * that appear with the same name in both tables.
     * Only natural inner joins are supported by this API,
     * even though SQL permits natural outer joins as well.
     *
     * The $name and $cols parameters follow the same logic
     * as described in the from() method.
     *
     * @param  array|string|Zend_Db_Expr $name The table name.
     * @param  array|string $cols The columns to select from the joined table.
     * @param  string $schema The database name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function joinNatural($name, $cols = self::SQL_WILDCARD, $schema = null)
    {
        return $this->_join(self::NATURAL_JOIN, $name, null, $cols, $schema);
    }

    /**
     * Adds a WHERE condition to the query by AND.
     *
     * If a value is passed as the second param, it will be quoted
     * and replaced into the condition wherever a question-mark
     * appears. Array values are quoted and comma-separated.
     *
     * <code>
     * // simplest but non-secure
     * $select->where("id = $id");
     *
     * // secure (ID is quoted but matched anyway)
     * $select->where('id = ?', $id);
     *
     * // alternatively, with named binding
     * $select->where('id = :id');
     * </code>
     *
     * Note that it is more correct to use named bindings in your
     * queries for values other than strings. When you use named
     * bindings, don't forget to pass the values when actually
     * making a query:
     *
     * <code>
     * $db->fetchAll($select, array('id' => 5));
     * </code>
     *
     * @param string   $cond  The WHERE condition.
     * @param string   $value OPTIONAL A single value to quote into the condition.
     * @param constant $type  OPTIONAL The type of the given value
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function where($cond, $value = null, $type = null)
    {
        $this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, true);

        return $this;
    }

    /**
     * Adds a WHERE condition to the query by OR.
     *
     * Otherwise identical to where().
     *
     * @param string   $cond  The WHERE condition.
     * @param string   $value OPTIONAL A single value to quote into the condition.
     * @param constant $type  OPTIONAL The type of the given value
     * @return Zend_Db_Select This Zend_Db_Select object.
     *
     * @see where()
     */
    public function orWhere($cond, $value = null, $type = null)
    {
        $this->_parts[self::WHERE][] = $this->_where($cond, $value, $type, false);

        return $this;
    }

    /**
     * Adds grouping to the query.
     *
     * @param  array|string $spec The column(s) to group by.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function group($spec)
    {
        if (!is_array($spec)) {
            $spec = array($spec);
        }

        foreach ($spec as $val) {
            if (preg_match('/\(.*\)/', (string) $val)) {
                $val = new Zend_Db_Expr($val);
            }
            $this->_parts[self::GROUP][] = $val;
        }

        return $this;
    }

    /**
     * Adds a HAVING condition to the query by AND.
     *
     * If a value is passed as the second param, it will be quoted
     * and replaced into the condition wherever a question-mark
     * appears. See {@link where()} for an example
     *
     * @param string $cond The HAVING condition.
     * @param string|Zend_Db_Expr $val A single value to quote into the condition.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function having($cond)
    {
        if (func_num_args() > 1) {
            $val = func_get_arg(1);
            $cond = $this->_adapter->quoteInto($cond, $val);
        }

        if ($this->_parts[self::HAVING]) {
            $this->_parts[self::HAVING][] = self::SQL_AND . " ($cond)";
        } else {
            $this->_parts[self::HAVING][] = "($cond)";
        }

        return $this;
    }

    /**
     * Adds a HAVING condition to the query by OR.
     *
     * Otherwise identical to orHaving().
     *
     * @param string $cond The HAVING condition.
     * @param string $val A single value to quote into the condition.
     * @return Zend_Db_Select This Zend_Db_Select object.
     *
     * @see having()
     */
    public function orHaving($cond)
    {
        if (func_num_args() > 1) {
            $val = func_get_arg(1);
            $cond = $this->_adapter->quoteInto($cond, $val);
        }

        if ($this->_parts[self::HAVING]) {
            $this->_parts[self::HAVING][] = self::SQL_OR . " ($cond)";
        } else {
            $this->_parts[self::HAVING][] = "($cond)";
        }

        return $this;
    }

    /**
     * Adds a row order to the query.
     *
     * @param mixed $spec The column(s) and direction to order by.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function order($spec)
    {
        if (!is_array($spec)) {
            $spec = array($spec);
        }

        // force 'ASC' or 'DESC' on each order spec, default is ASC.
        foreach ($spec as $val) {
            if ($val instanceof Zend_Db_Expr) {
                $expr = $val->__toString();
                if (empty($expr)) {
                    continue;
                }
                $this->_parts[self::ORDER][] = $val;
            } else {
                if (empty($val)) {
                    continue;
                }
                $direction = self::SQL_ASC;
                if (preg_match('/(.*\W)(' . self::SQL_ASC . '|' . self::SQL_DESC . ')\b/si', $val, $matches)) {
                    $val = trim($matches[1]);
                    $direction = $matches[2];
                }
                if (preg_match('/\(.*\)/', $val)) {
                    $val = new Zend_Db_Expr($val);
                }
                $this->_parts[self::ORDER][] = array($val, $direction);
            }
        }

        return $this;
    }

    /**
     * Sets a limit count and offset to the query.
     *
     * @param int $count OPTIONAL The number of rows to return.
     * @param int $offset OPTIONAL Start returning after this many rows.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function limit($count = null, $offset = null)
    {
        $this->_parts[self::LIMIT_COUNT]  = (int) $count;
        $this->_parts[self::LIMIT_OFFSET] = (int) $offset;
        return $this;
    }

    /**
     * Sets the limit and count by page number.
     *
     * @param int $page Limit results to this page number.
     * @param int $rowCount Use this many rows per page.
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function limitPage($page, $rowCount)
    {
        $page     = ($page > 0)     ? $page     : 1;
        $rowCount = ($rowCount > 0) ? $rowCount : 1;
        $this->_parts[self::LIMIT_COUNT]  = (int) $rowCount;
        $this->_parts[self::LIMIT_OFFSET] = (int) $rowCount * ($page - 1);
        return $this;
    }

    /**
     * Makes the query SELECT FOR UPDATE.
     *
     * @param bool $flag Whether or not the SELECT is FOR UPDATE (default true).
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function forUpdate($flag = true)
    {
        $this->_parts[self::FOR_UPDATE] = (bool) $flag;
        return $this;
    }

    /**
     * Get part of the structured information for the currect query.
     *
     * @param string $part
     * @return mixed
     * @throws Zend_Db_Select_Exception
     */
    public function getPart($part)
    {
        $part = strtolower($part);
        if (!array_key_exists($part, $this->_parts)) {
            require_once 'Zend/Db/Select/Exception.php';
            throw new Zend_Db_Select_Exception("Invalid Select part '$part'");
        }
        return $this->_parts[$part];
    }

    /**
     * Executes the current select object and returns the result
     *
     * @param integer $fetchMode OPTIONAL
     * @return PDO_Statement|Zend_Db_Statement
     */
    public function query($fetchMode = null)
    {
        $stmt = $this->_adapter->query($this);
        if ($fetchMode == null) {
            $fetchMode = $this->_adapter->getFetchMode();
        }
        $stmt->setFetchMode($fetchMode);
        return $stmt;
    }

    /**
     * Converts this object to an SQL SELECT string.
     *
     * @return string This object as a SELECT string.
     */
    public function assemble()
    {
        $sql = self::SQL_SELECT;
        foreach (array_keys(self::$_partsInit) as $part) {
            $method = '_render' . ucfirst($part);
            if (method_exists($this, $method)) {
                $sql = $this->$method($sql);
            }
        }
        return $sql;
    }

    /**
     * Clear parts of the Select object, or an individual part.
     *
     * @param string $part OPTIONAL
     * @return Zend_Db_Select
     */
    public function reset($part = null)
    {
        if ($part == null) {
            $this->_parts = self::$_partsInit;
        } else if (array_key_exists($part, self::$_partsInit)) {
            $this->_parts[$part] = self::$_partsInit[$part];
        }
        return $this;
    }

    /**
     * Gets the Zend_Db_Adapter_Abstract for this
     * particular Zend_Db_Select object.
     *
     * @return Zend_Db_Adapter_Abstract
     */
    public function getAdapter()
    {
        return $this->_adapter;
    }

    /**
     * Populate the {@link $_parts} 'join' key
     *
     * Does the dirty work of populating the join key.
     *
     * The $name and $cols parameters follow the same logic
     * as described in the from() method.
     *
     * @param  null|string $type Type of join; inner, left, and null are currently supported
     * @param  array|string|Zend_Db_Expr $name Table name
     * @param  string $cond Join on this condition
     * @param  array|string $cols The columns to select from the joined table
     * @param  string $schema The database name to specify, if any.
     * @return Zend_Db_Select This Zend_Db_Select object
     * @throws Zend_Db_Select_Exception
     */
    protected function _join($type, $name, $cond, $cols, $schema = null)
    {
        if (!in_array($type, self::$_joinTypes)) {
            /**
             * @see Zend_Db_Select_Exception
             */
            require_once 'Zend/Db/Select/Exception.php';
            throw new Zend_Db_Select_Exception("Invalid join type '$type'");
        }

        if (count($this->_parts[self::UNION])) {
            require_once 'Zend/Db/Select/Exception.php';
            throw new Zend_Db_Select_Exception("Invalid use of table with " . self::SQL_UNION);
        }

        if (empty($name)) {
            $correlationName = $tableName = '';
        } else if (is_array($name)) {
            // Must be array($correlationName => $tableName) or array($ident, ...)
            foreach ($name as $_correlationName => $_tableName) {
                if (is_string($_correlationName)) {
                    // We assume the key is the correlation name and value is the table name
                    $tableName = $_tableName;
                    $correlationName = $_correlationName;
                } else {
                    // We assume just an array of identifiers, with no correlation name
                    $tableName = $name;
                    $correlationName = $this->_uniqueCorrelation($tableName);
                }
                break;
            }
        } else if ($name instanceof Zend_Db_Expr|| $name instanceof Zend_Db_Select) {
            $tableName = $name;
            $correlationName = $this->_uniqueCorrelation('t');
        } else if (preg_match('/^(.+)\s+AS\s+(.+)$/i', $name, $m)) {
            $tableName = $m[1];
            $correlationName = $m[2];
        } else {
            $tableName = $name;
            $correlationName = $this->_uniqueCorrelation($tableName);
        }

        // Schema from table name overrides schema argument
        if (!is_object($tableName) && false !== strpos($tableName, '.')) {
            list($schema, $tableName) = explode('.', $tableName);
        }

        if (!empty($correlationName)) {
            if (array_key_exists($correlationName, $this->_parts[self::FROM])) {
                /**
                 * @see Zend_Db_Select_Exception
                 */
                require_once 'Zend/Db/Select/Exception.php';
                throw new Zend_Db_Select_Exception("You cannot define a correlation name '$correlationName' more than once");
            }

            $this->_parts[self::FROM][$correlationName] = array(
                'joinType'      => $type,
                'schema'        => $schema,
                'tableName'     => $tableName,
                'joinCondition' => $cond
            );
        }

        // add to the columns from this joined table
        $this->_tableCols($correlationName, $cols);

        return $this;
    }

    /**
     * Handle JOIN... USING... syntax
     *
     * This is functionality identical to the existing JOIN methods, however
     * the join condition can be passed as a single column name. This method
     * then completes the ON condition by using the same field for the FROM
     * table and the JOIN table.
     *
     * <code>
     * $select = $db->select()->from('table1')
     *                        ->joinUsing('table2', 'column1');
     *
     * // SELECT * FROM table1 JOIN table2 ON table1.column1 = table2.column2
     * </code>
     *
     * These joins are called by the developer simply by adding 'Using' to the
     * method name. E.g.
     * * joinUsing
     * * joinInnerUsing
     * * joinFullUsing
     * * joinRightUsing
     * * joinLeftUsing
     *
     * @return Zend_Db_Select This Zend_Db_Select object.
     */
    public function _joinUsing($type, $name, $cond, $cols = '*', $schema = null)
    {
        if (empty($this->_parts[self::FROM])) {
            require_once 'Zend/Db/Select/Exception.php';
            throw new Zend_Db_Select_Exception("You can only perform a joinUsing after specifying a FROM table");
        }

        $join  = $this->_adapter->quoteIdentifier(key($this->_parts[self::FROM]), true);
        $from  = $this->_adapter->quoteIdentifier($this->_uniqueCorrelation($name), true);

        $cond1 = $from . '.' . $cond;
        $cond2 = $join . '.' . $cond;
        $cond  = $cond1 . ' = ' . $cond2;

        return $this->_join($type, $name, $cond, $cols, $schema);
    }

    /**
     * Generate a unique correlation name
     *
     * @param string|array $name A qualified identifier.
     * @return string A unique correlation name.
     */
    private function _uniqueCorrelation($name)
    {
        if (is_array($name)) {
            $c = end($name);
        } else {
            // Extract just the last name of a qualified table name
            $dot = strrpos($name,'.');
            $c = ($dot === false) ? $name : substr($name, $dot+1);
        }
        for ($i = 2; array_key_exists($c, $this->_parts[self::FROM]); ++$i) {
            $c = $name . '_' . (string) $i;
        }
        return $c;
    }

    /**
     * Adds to the internal table-to-column mapping array.
     *
     * @param  string $tbl The table/join the columns come from.
     * @param  array|string $cols The list of columns; preferably as
     * an array, but possibly as a string containing one column.
     * @return void
     */
    protected function _tableCols($correlationName, $cols)
    {
        if (!is_array($cols)) {
            $cols = array($cols);
        }

        if ($correlationName == null) {
            $correlationName = '';
        }

        foreach (array_filter($cols) as $alias => $col) {
            $currentCorrelationName = $correlationName;
            if (is_string($col)) {
                // Check for a column matching "<column> AS <alias>" and extract the alias name
                if (preg_match('/^(.+)\s+' . self::SQL_AS . '\s+(.+)$/i', $col, $m)) {
                    $col = $m[1];
                    $alias = $m[2];
                }
                // Check for columns that look like functions and convert to Zend_Db_Expr
                if (preg_match('/\(.*\)/', $col)) {
                    $col = new Zend_Db_Expr($col);
                } elseif (preg_match('/(.+)\.(.+)/', $col, $m)) {
                    $currentCorrelationName = $m[1];
                    $col = $m[2];
                }
            }
            $this->_parts[self::COLUMNS][] = array($currentCorrelationName, $col, is_string($alias) ? $alias : null);
        }
    }

    /**
     * Internal function for creating the where clause
     *
     * @param string   $condition
     * @param string   $value  optional
     * @param string   $type   optional
     * @param boolean  $bool  true = AND, false = OR
     * @return string  clause
     */
    protected function _where($condition, $value = null, $type = null, $bool = true)
    {
        if (count($this->_parts[self::UNION])) {
            require_once 'Zend/Db/Select/Exception.php';
            throw new Zend_Db_Select_Exception("Invalid use of where clause with " . self::SQL_UNION);
        }

        if ($value !== null) {
            $condition = $this->_adapter->quoteInto($condition, $value, $type);
        }

        $cond = "";
        if ($this->_parts[self::WHERE]) {
            if ($bool === true) {
                $cond = self::SQL_AND . ' ';
            } else {
                $cond = self::SQL_OR . ' ';
            }
        }

        return $cond . "($condition)";
    }

    /**
     * @return array
     */
    protected function _getDummyTable()
    {
        return array();
    }

    /**
     * Return a quoted schema name
     *
     * @param string   $schema  The schema name OPTIONAL
     * @return string|null
     */
    protected function _getQuotedSchema($schema = null)
    {
        if ($schema === null) {
            return null;
        }
        return $this->_adapter->quoteIdentifier($schema, true) . '.';
    }

    /**
     * Return a quoted table name
     *
     * @param string   $tableName        The table name
     * @param string   $correlationName  The correlation name OPTIONAL
     * @return string
     */
    protected function _getQuotedTable($tableName, $correlationName = null)
    {
        return $this->_adapter->quoteTableAs($tableName, $correlationName, true);
    }

    /**
     * Render DISTINCT clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderDistinct($sql)
    {
        if ($this->_parts[self::DISTINCT]) {
            $sql .= ' ' . self::SQL_DISTINCT;
        }

        return $sql;
    }

    /**
     * Render DISTINCT clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderColumns($sql)
    {
        if (!count($this->_parts[self::COLUMNS])) {
            return null;
        }

        $columns = array();
        foreach ($this->_parts[self::COLUMNS] as $columnEntry) {
            list($correlationName, $column, $alias) = $columnEntry;
            if ($column instanceof Zend_Db_Expr) {
                $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
            } else {
                if ($column == self::SQL_WILDCARD) {
                    $column = new Zend_Db_Expr(self::SQL_WILDCARD);
                    $alias = null;
                }
                if (empty($correlationName)) {
                    $columns[] = $this->_adapter->quoteColumnAs($column, $alias, true);
                } else {
                    $columns[] = $this->_adapter->quoteColumnAs(array($correlationName, $column), $alias, true);
                }
            }
        }

        return $sql .= ' ' . implode(', ', $columns);
    }

    /**
     * Render FROM clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderFrom($sql)
    {
        /*
         * If no table specified, use RDBMS-dependent solution
         * for table-less query.  e.g. DUAL in Oracle.
         */
        if (empty($this->_parts[self::FROM])) {
            $this->_parts[self::FROM] = $this->_getDummyTable();
        }

        $from = array();

        foreach ($this->_parts[self::FROM] as $correlationName => $table) {
            $tmp = '';

            // Add join clause (if applicable)
            if (! empty($from)) {
                $tmp .= ' ' . strtoupper($table['joinType']) . ' ';
            }

            $tmp .= $this->_getQuotedSchema($table['schema']);
            $tmp .= $this->_getQuotedTable($table['tableName'], $correlationName);

            // Add join conditions (if applicable)
            if (!empty($from) && ! empty($table['joinCondition'])) {
                $tmp .= ' ' . self::SQL_ON . ' ' . $table['joinCondition'];
            }

            // Add the table name and condition add to the list
            $from[] = $tmp;
        }

        // Add the list of all joins
        if (!empty($from)) {
            $sql .= ' ' . self::SQL_FROM . ' ' . implode("\n", $from);
        }

        return $sql;
    }

    /**
     * Render UNION query
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderUnion($sql)
    {
        if ($this->_parts[self::UNION]) {
            $parts = count($this->_parts[self::UNION]);
            foreach ($this->_parts[self::UNION] as $cnt => $union) {
                list($target, $type) = $union;
                if ($target instanceof Zend_Db_Select) {
                    $target = $target->assemble();
                }
                $sql .= $target;
                if ($cnt < $parts - 1) {
                    $sql .= ' ' . $type . ' ';
                }
            }
        }

        return $sql;
    }

    /**
     * Render WHERE clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderWhere($sql)
    {
        if ($this->_parts[self::FROM] && $this->_parts[self::WHERE]) {
            $sql .= ' ' . self::SQL_WHERE . ' ' .  implode(' ', $this->_parts[self::WHERE]);
        }

        return $sql;
    }

    /**
     * Render GROUP clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderGroup($sql)
    {
        if ($this->_parts[self::FROM] && $this->_parts[self::GROUP]) {
            $group = array();
            foreach ($this->_parts[self::GROUP] as $term) {
                $group[] = $this->_adapter->quoteIdentifier($term, true);
            }
            $sql .= ' ' . self::SQL_GROUP_BY . ' ' . implode(",\n\t", $group);
        }

        return $sql;
    }

    /**
     * Render HAVING clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderHaving($sql)
    {
        if ($this->_parts[self::FROM] && $this->_parts[self::HAVING]) {
            $sql .= ' ' . self::SQL_HAVING . ' ' . implode(' ', $this->_parts[self::HAVING]);
        }

        return $sql;
    }

    /**
     * Render ORDER clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderOrder($sql)
    {
        if ($this->_parts[self::ORDER]) {
            $order = array();
            foreach ($this->_parts[self::ORDER] as $term) {
                if (is_array($term)) {
                    $order[] = $this->_adapter->quoteIdentifier($term[0], true) . ' ' . $term[1];
                } else {
                    $order[] = $this->_adapter->quoteIdentifier($term, true);
                }
            }
            $sql .= ' ' . self::SQL_ORDER_BY . ' ' . implode(', ', $order);
        }

        return $sql;
    }

    /**
     * Render LIMIT OFFSET clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderLimitoffset($sql)
    {
        $count = 0;
        $offset = 0;

        if (!empty($this->_parts[self::LIMIT_OFFSET])) {
            $offset = (int) $this->_parts[self::LIMIT_OFFSET];
            // This should reduce to the max integer PHP can support
            $count = intval(9223372036854775807);
        }

        if (!empty($this->_parts[self::LIMIT_COUNT])) {
            $count = (int) $this->_parts[self::LIMIT_COUNT];
        }

        /*
         * Add limits clause
         */
        if ($count > 0) {
            $sql = trim($this->_adapter->limit($sql, $count, $offset));
        }

        return $sql;
    }

    /**
     * Render FOR UPDATE clause
     *
     * @param string   $sql SQL query
     * @return string
     */
    protected function _renderForupdate($sql)
    {
        if ($this->_parts[self::FOR_UPDATE]) {
            $sql .= ' ' . self::SQL_FOR_UPDATE;
        }

        return $sql;
    }

    /**
     * Turn magic function calls into non-magic function calls
     * for joinUsing syntax
     *
     * @param string $method
     * @param array $args OPTIONAL Zend_Db_Table_Select query modifier
     * @return Zend_Db_Select
     * @throws Zend_Db_Select_Exception If an invalid method is called.
     */
    public function __call($method, array $args)
    {
        $matches = array();

        /**
         * Recognize methods for Has-Many cases:
         * findParent<Class>()
         * findParent<Class>By<Rule>()
         * Use the non-greedy pattern repeat modifier e.g. \w+?
         */
        if (preg_match('/^join([a-zA-Z]*?)Using$/', $method, $matches)) {
            $type = strtolower($matches[1]);
            if ($type) {
                $type .= ' join';
                if (!in_array($type, self::$_joinTypes)) {
                    require_once 'Zend/Db/Select/Exception.php';
                    throw new Zend_Db_Select_Exception("Unrecognized method '$method()'");
                }
                if (in_array($type, array(self::CROSS_JOIN, self::NATURAL_JOIN))) {
                    require_once 'Zend/Db/Select/Exception.php';
                    throw new Zend_Db_Select_Exception("Cannot perform a joinUsing with method '$method()'");
                }
            } else {
                $type = self::INNER_JOIN;
            }
            array_unshift($args, $type);
            return call_user_func_array(array($this, '_joinUsing'), $args);
        }

        require_once 'Zend/Db/Select/Exception.php';
        throw new Zend_Db_Select_Exception("Unrecognized method '$method()'");
    }

    /**
     * Implements magic method.
     *
     * @return string This object as a SELECT string.
     */
    public function __toString()
    {
        try {
            $sql = $this->assemble();
        } catch (Exception $e) {
            trigger_error($e->getMessage(), E_USER_WARNING);
            $sql = '';
        }
        return (string)$sql;
    }

}
Feed/Builder.php000066600000043613151256604600007526 0ustar00<?php

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


/**
 * @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-2008 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
     */
    private 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
     */
    private 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['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;
        }
    }
}Feed/Element.php000066600000027172151256604600007533 0ustar00<?php

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


/**
 * Wraps a DOMElement allowing for SimpleXML-like access to attributes.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Element implements ArrayAccess
{

    /**
     * @var DOMElement
     */
    protected $_element;

    /**
     * @var Zend_Feed_Element
     */
    protected $_parentElement;

    /**
     * @var boolean
     */
    protected $_appended = true;


    /**
     * Zend_Feed_Element constructor.
     *
     * @param  DOMElement $element The DOM element we're encapsulating.
     * @return void
     */
    public function __construct($element = null)
    {
        $this->_element = $element;
    }


    /**
     * Get a DOM representation of the element
     *
     * Returns the underlying DOM object, which can then be
     * manipulated with full DOM methods.
     *
     * @return DOMDocument
     */
    public function getDOM()
    {
        return $this->_element;
    }


    /**
     * Update the object from a DOM element
     *
     * Take a DOMElement object, which may be originally from a call
     * to getDOM() or may be custom created, and use it as the
     * DOM tree for this Zend_Feed_Element.
     *
     * @param  DOMElement $element
     * @return void
     */
    public function setDOM(DOMElement $element)
    {
        $this->_element = $this->_element->ownerDocument->importNode($element, true);
    }

    /**
     * Set the parent element of this object to another
     * Zend_Feed_Element.
     *
     * @param  Zend_Feed_Element $element
     * @return void
     */
    public function setParent(Zend_Feed_Element $element)
    {
        $this->_parentElement = $element;
        $this->_appended = false;
    }


    /**
     * Appends this element to its parent if necessary.
     *
     * @return void
     */
    protected function ensureAppended()
    {
        if (!$this->_appended) {
            $this->_parentElement->getDOM()->appendChild($this->_element);
            $this->_appended = true;
            $this->_parentElement->ensureAppended();
        }
    }


    /**
     * Get an XML string representation of this element
     *
     * Returns a string of this element's XML, including the XML
     * prologue.
     *
     * @return string
     */
    public function saveXml()
    {
        // Return a complete document including XML prologue.
        $doc = new DOMDocument($this->_element->ownerDocument->version,
                               $this->_element->ownerDocument->actualEncoding);
        $doc->appendChild($doc->importNode($this->_element, true));
        return $doc->saveXML();
    }


    /**
     * Get the XML for only this element
     *
     * Returns a string of this element's XML without prologue.
     *
     * @return string
     */
    public function saveXmlFragment()
    {
        return $this->_element->ownerDocument->saveXML($this->_element);
    }


    /**
     * Map variable access onto the underlying entry representation.
     *
     * Get-style access returns a Zend_Feed_Element representing the
     * child element accessed. To get string values, use method syntax
     * with the __call() overriding.
     *
     * @param  string $var The property to access.
     * @return mixed
     */
    public function __get($var)
    {
        $nodes = $this->_children($var);
        $length = count($nodes);

        if ($length == 1) {
            return new Zend_Feed_Element($nodes[0]);
        } elseif ($length > 1) {
            return array_map(create_function('$e', 'return new Zend_Feed_Element($e);'), $nodes);
        } else {
            // When creating anonymous nodes for __set chaining, don't
            // call appendChild() on them. Instead we pass the current
            // element to them as an extra reference; the child is
            // then responsible for appending itself when it is
            // actually set. This way "if ($foo->bar)" doesn't create
            // a phantom "bar" element in our tree.
            if (strpos($var, ':') !== false) {
                list($ns, $elt) = explode(':', $var, 2);
                $node = $this->_element->ownerDocument->createElementNS(Zend_Feed::lookupNamespace($ns), $elt);
            } else {
                $node = $this->_element->ownerDocument->createElement($var);
            }
            $node = new self($node);
            $node->setParent($this);
            return $node;
        }
    }


    /**
     * Map variable sets onto the underlying entry representation.
     *
     * @param  string $var The property to change.
     * @param  string $val The property's new value.
     * @return void
     * @throws Zend_Feed_Exception
     */
    public function __set($var, $val)
    {
        $this->ensureAppended();

        $nodes = $this->_children($var);
        if (!$nodes) {
            if (strpos($var, ':') !== false) {
                list($ns, $elt) = explode(':', $var, 2);
                $node = $this->_element->ownerDocument->createElementNS(Zend_Feed::lookupNamespace($ns), $var, $val);
                $this->_element->appendChild($node);
            } else {
                $node = $this->_element->ownerDocument->createElement($var, $val);
                $this->_element->appendChild($node);
            }
        } elseif (count($nodes) > 1) {
            /** 
             * @see Zend_Feed_Exception
             */
            require_once 'Zend/Feed/Exception.php';
            throw new Zend_Feed_Exception('Cannot set the value of multiple tags simultaneously.');
        } else {
            $nodes[0]->nodeValue = $val;
        }
    }


    /**
     * Map isset calls onto the underlying entry representation.
     *
     * @param  string $var
     * @return boolean
     */
    public function __isset($var)
    {
        // Look for access of the form {ns:var}. We don't use
        // _children() here because we can break out of the loop
        // immediately once we find something.
        if (strpos($var, ':') !== false) {
            list($ns, $elt) = explode(':', $var, 2);
            foreach ($this->_element->childNodes as $child) {
                if ($child->localName == $elt && $child->prefix == $ns) {
                    return true;
                }
            }
        } else {
            foreach ($this->_element->childNodes as $child) {
                if ($child->localName == $var) {
                    return true;
                }
            }
        }
    }


    /**
     * Get the value of an element with method syntax.
     *
     * Map method calls to get the string value of the requested
     * element. If there are multiple elements that match, this will
     * return an array of those objects.
     *
     * @param  string $var    The element to get the string value of.
     * @param  mixed  $unused This parameter is not used.
     * @return mixed The node's value, null, or an array of nodes.
     */
    public function __call($var, $unused)
    {
        $nodes = $this->_children($var);

        if (!$nodes) {
            return null;
        } elseif (count($nodes) > 1) {
            return $nodes;
        } else {
            return $nodes[0]->nodeValue;
        }
    }


    /**
     * Remove all children matching $var.
     *
     * @param  string $var
     * @return void
     */
    public function __unset($var)
    {
        $nodes = $this->_children($var);
        foreach ($nodes as $node) {
            $parent = $node->parentNode;
            $parent->removeChild($node);
        }
    }


    /**
     * Returns the nodeValue of this element when this object is used
     * in a string context.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->_element->nodeValue;
    }


    /**
     * Finds children with tagnames matching $var
     *
     * Similar to SimpleXML's children() method.
     *
     * @param  string $var Tagname to match, can be either namespace:tagName or just tagName.
     * @return array
     */
    protected function _children($var)
    {
        $found = array();

        // Look for access of the form {ns:var}.
        if (strpos($var, ':') !== false) {
            list($ns, $elt) = explode(':', $var, 2);
            foreach ($this->_element->childNodes as $child) {
                if ($child->localName == $elt && $child->prefix == $ns) {
                    $found[] = $child;
                }
            }
        } else {
            foreach ($this->_element->childNodes as $child) {
                if ($child->localName == $var) {
                    $found[] = $child;
                }
            }
        }

        return $found;
    }


    /**
     * Required by the ArrayAccess interface.
     *
     * @param  string $offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        if (strpos($offset, ':') !== false) {
            list($ns, $attr) = explode(':', $offset, 2);
            return $this->_element->hasAttributeNS(Zend_Feed::lookupNamespace($ns), $attr);
        } else {
            return $this->_element->hasAttribute($offset);
        }
    }


    /**
     * Required by the ArrayAccess interface.
     *
     * @param  string $offset
     * @return string
     */
    public function offsetGet($offset)
    {
        if (strpos($offset, ':') !== false) {
            list($ns, $attr) = explode(':', $offset, 2);
            return $this->_element->getAttributeNS(Zend_Feed::lookupNamespace($ns), $attr);
        } else {
            return $this->_element->getAttribute($offset);
        }
    }


    /**
     * Required by the ArrayAccess interface.
     *
     * @param  string $offset
     * @param  string $value
     * @return string
     */
    public function offsetSet($offset, $value)
    {
        $this->ensureAppended();

        if (strpos($offset, ':') !== false) {
            list($ns, $attr) = explode(':', $offset, 2);
            return $this->_element->setAttributeNS(Zend_Feed::lookupNamespace($ns), $attr, $value);
        } else {
            return $this->_element->setAttribute($offset, $value);
        }
    }


    /**
     * Required by the ArrayAccess interface.
     *
     * @param  string $offset
     * @return boolean
     */
    public function offsetUnset($offset)
    {
        if (strpos($offset, ':') !== false) {
            list($ns, $attr) = explode(':', $offset, 2);
            return $this->_element->removeAttributeNS(Zend_Feed::lookupNamespace($ns), $attr);
        } else {
            return $this->_element->removeAttribute($offset);
        }
    }

}
Feed/Exception.php000066600000002307151256604600010071 0ustar00<?php

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


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


/**
 * Feed exceptions
 *
 * Class to represent exceptions that occur during Feed operations.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Exception extends Zend_Exception
{}

Feed/Rss.php000066600000047472151256604600006716 0ustar00<?php

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


/**
 * @see Zend_Feed_Abstract
 */
require_once 'Zend/Feed/Abstract.php';

/**
 * @see Zend_Feed_Entry_Rss
 */
require_once 'Zend/Feed/Entry/Rss.php';


/**
 * RSS channel class
 *
 * The Zend_Feed_Rss class is a concrete subclass of
 * Zend_Feed_Abstract meant for representing RSS channels. It does not
 * add any methods to its parent, just provides a classname to check
 * against with the instanceof operator, and expects to be handling
 * RSS-formatted data instead of Atom.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Rss extends Zend_Feed_Abstract
{
    /**
     * The classname for individual channel elements.
     *
     * @var string
     */
    protected $_entryClassName = 'Zend_Feed_Entry_Rss';

    /**
     * The element name for individual channel elements (RSS <item>s).
     *
     * @var string
     */
    protected $_entryElementName = 'item';

    /**
     * The default namespace for RSS channels.
     *
     * @var string
     */
    protected $_defaultNamespace = 'rss';

    /**
     * Override Zend_Feed_Abstract to set up the $_element and $_entries aliases.
     *
     * @return void
     * @throws Zend_Feed_Exception
     */
    public function __wakeup()
    {
        parent::__wakeup();

        // Find the base channel element and create an alias to it.
        if ($this->_element->firstChild->nodeName == 'rdf:RDF') {
            $this->_element = $this->_element->firstChild;
        } else {
            $this->_element = $this->_element->getElementsByTagName('channel')->item(0);
        }
        if (!$this->_element) {
            /**
             * @see Zend_Feed_Exception
             */
            require_once 'Zend/Feed/Exception.php';
            throw new Zend_Feed_Exception('No root <channel> element found, cannot parse channel.');
        }

        // Find the entries and save a pointer to them for speed and
        // simplicity.
        $this->_buildEntryCache();
    }


    /**
     * Make accessing some individual elements of the channel easier.
     *
     * Special accessors 'item' and 'items' are provided so that if
     * you wish to iterate over an RSS channel's items, you can do so
     * using foreach ($channel->items as $item) or foreach
     * ($channel->item as $item).
     *
     * @param  string $var The property to access.
     * @return mixed
     */
    public function __get($var)
    {
        switch ($var) {
            case 'item':
                // fall through to the next case
            case 'items':
                return $this;

            default:
                return parent::__get($var);
        }
    }

    /**
     * Generate the header of the feed when working in write mode
     *
     * @param  array $array the data to use
     * @return DOMElement root node
     */
    protected function _mapFeedHeaders($array)
    {
        $channel = $this->_element->createElement('channel');

        $title = $this->_element->createElement('title');
        $title->appendChild($this->_element->createCDATASection($array->title));
        $channel->appendChild($title);

        $link = $this->_element->createElement('link', $array->link);
        $channel->appendChild($link);

        $desc = isset($array->description) ? $array->description : '';
        $description = $this->_element->createElement('description');
        $description->appendChild($this->_element->createCDATASection($desc));
        $channel->appendChild($description);

        $pubdate = isset($array->lastUpdate) ? $array->lastUpdate : time();
        $pubdate = $this->_element->createElement('pubDate', gmdate('r', $pubdate));
        
        $channel->appendChild($pubdate);

        if (isset($array->published)) {
            $lastBuildDate = $this->_element->createElement('lastBuildDate', gmdate('r', $array->published));
            $channel->appendChild($lastBuildDate);
        }

        $editor = '';
        if (!empty($array->email)) {
            $editor .= $array->email;
        }
        if (!empty($array->author)) {
            $editor .= ' (' . $array->author . ')';
        }
        if (!empty($editor)) {
            $author = $this->_element->createElement('managingEditor', ltrim($editor));
            $channel->appendChild($author);
        }
        if (isset($array->webmaster)) {
            $channel->appendChild($this->_element->createElement('webMaster', $array->webmaster));
        }

        if (!empty($array->copyright)) {
            $copyright = $this->_element->createElement('copyright', $array->copyright);
            $channel->appendChild($copyright);
        }

        if (isset($array->category)) {
            $category = $this->_element->createElement('category', $array->category);
            $channel->appendChild($category);
        }

        if (!empty($array->image)) {
            $image = $this->_element->createElement('image');
            $url = $this->_element->createElement('url', $array->image);
            $image->appendChild($url);
            $imagetitle = $this->_element->createElement('title', $array->title);
            $image->appendChild($imagetitle);
            $imagelink = $this->_element->createElement('link', $array->link);
            $image->appendChild($imagelink);

            $channel->appendChild($image);
        }

        $generator = !empty($array->generator) ? $array->generator : 'Zend_Feed';
        $generator = $this->_element->createElement('generator', $generator);
        $channel->appendChild($generator);

        if (!empty($array->language)) {
            $language = $this->_element->createElement('language', $array->language);
            $channel->appendChild($language);
        }

        $doc = $this->_element->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss');
        $channel->appendChild($doc);

        if (isset($array->cloud)) {
            $cloud = $this->_element->createElement('cloud');
            $cloud->setAttribute('domain', $array->cloud['uri']->getHost());
            $cloud->setAttribute('port', $array->cloud['uri']->getPort());
            $cloud->setAttribute('path', $array->cloud['uri']->getPath());
            $cloud->setAttribute('registerProcedure', $array->cloud['procedure']);
            $cloud->setAttribute('protocol', $array->cloud['protocol']);
            $channel->appendChild($cloud);
        }

        if (isset($array->ttl)) {
            $ttl = $this->_element->createElement('ttl', $array->ttl);
            $channel->appendChild($ttl);
        }

        if (isset($array->rating)) {
            $rating = $this->_element->createElement('rating', $array->rating);
            $channel->appendChild($rating);
        }

        if (isset($array->textInput)) {
            $textinput = $this->_element->createElement('textInput');
            $textinput->appendChild($this->_element->createElement('title', $array->textInput['title']));
            $textinput->appendChild($this->_element->createElement('description', $array->textInput['description']));
            $textinput->appendChild($this->_element->createElement('name', $array->textInput['name']));
            $textinput->appendChild($this->_element->createElement('link', $array->textInput['link']));
            $channel->appendChild($textinput);
        }

        if (isset($array->skipHours)) {
            $skipHours = $this->_element->createElement('skipHours');
            foreach ($array->skipHours as $hour) {
                $skipHours->appendChild($this->_element->createElement('hour', $hour));
            }
            $channel->appendChild($skipHours);
        }

        if (isset($array->skipDays)) {
            $skipDays = $this->_element->createElement('skipDays');
            foreach ($array->skipDays as $day) {
                $skipDays->appendChild($this->_element->createElement('day', $day));
            }
            $channel->appendChild($skipDays);
        }

        if (isset($array->itunes)) {
            $this->_buildiTunes($channel, $array);
        }

        return $channel;
    }

    /**
     * Adds the iTunes extensions to a root node
     *
     * @param  DOMElement $root
     * @param  array $array
     * @return void
     */
    private function _buildiTunes(DOMElement $root, $array)
    {
        /* author node */
        $author = '';
        if (isset($array->itunes->author)) {
            $author = $array->itunes->author;
        } elseif (isset($array->author)) {
            $author = $array->author;
        }
        if (!empty($author)) {
            $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:author', $author);
            $root->appendChild($node);
        }

        /* owner node */
        $author = '';
        $email = '';
        if (isset($array->itunes->owner)) {
            if (isset($array->itunes->owner['name'])) {
                $author = $array->itunes->owner['name'];
            }
            if (isset($array->itunes->owner['email'])) {
                $email = $array->itunes->owner['email'];
            }
        }
        if (empty($author) && isset($array->author)) {
            $author = $array->author;
        }
        if (empty($email) && isset($array->email)) {
            $email = $array->email;
        }
        if (!empty($author) || !empty($email)) {
            $owner = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:owner');
            if (!empty($author)) {
                $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:name', $author);
                $owner->appendChild($node);
            }
            if (!empty($email)) {
                $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:email', $email);
                $owner->appendChild($node);
            }
            $root->appendChild($owner);
        }
        $image = '';
        if (isset($array->itunes->image)) {
            $image = $array->itunes->image;
        } elseif (isset($array->image)) {
            $image = $array->image;
        }
        if (!empty($image)) {
            $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:image');
            $node->setAttribute('href', $image);
            $root->appendChild($node);
        }
        $subtitle = '';
        if (isset($array->itunes->subtitle)) {
            $subtitle = $array->itunes->subtitle;
        } elseif (isset($array->description)) {
            $subtitle = $array->description;
        }
        if (!empty($subtitle)) {
            $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:subtitle', $subtitle);
            $root->appendChild($node);
        }
        $summary = '';
        if (isset($array->itunes->summary)) {
            $summary = $array->itunes->summary;
        } elseif (isset($array->description)) {
            $summary = $array->description;
        }
        if (!empty($summary)) {
            $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:summary', $summary);
            $root->appendChild($node);
        }
        if (isset($array->itunes->block)) {
            $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:block', $array->itunes->block);
            $root->appendChild($node);
        }
        if (isset($array->itunes->explicit)) {
            $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:explicit', $array->itunes->explicit);
            $root->appendChild($node);
        }
        if (isset($array->itunes->keywords)) {
            $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:keywords', $array->itunes->keywords);
            $root->appendChild($node);
        }
        if (isset($array->itunes->new_feed_url)) {
            $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:new-feed-url', $array->itunes->new_feed_url);
            $root->appendChild($node);
        }
        if (isset($array->itunes->category)) {
            foreach ($array->itunes->category as $i => $category) {
                $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:category');
                $node->setAttribute('text', $category['main']);
                $root->appendChild($node);
                $add_end_category = false;
                if (!empty($category['sub'])) {
                    $add_end_category = true;
                    $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:category');
                    $node->setAttribute('text', $category['sub']);
                    $root->appendChild($node);
                }
                if ($i > 0 || $add_end_category) {
                    $node = $this->_element->createElementNS('http://www.itunes.com/DTDs/Podcast-1.0.dtd', 'itunes:category');
                    $root->appendChild($node);
                }
            }
        }
    }

    /**
     * Generate the entries of the feed when working in write mode
     *
     * The following nodes are constructed for each feed entry
     * <item>
     *    <title>entry title</title>
     *    <link>url to feed entry</link>
     *    <guid>url to feed entry</guid>
     *    <description>short text</description>
     *    <content:encoded>long version, can contain html</content:encoded>
     * </item>
     *
     * @param  DOMElement $root the root node to use
     * @param  array $array the data to use
     * @return void
     */
    protected function _mapFeedEntries(DOMElement $root, $array)
    {
        Zend_Feed::registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');

        foreach ($array as $dataentry) {
            $item = $this->_element->createElement('item');

            $title = $this->_element->createElement('title');
            $title->appendChild($this->_element->createCDATASection($dataentry->title));
            $item->appendChild($title);

            $link = $this->_element->createElement('link', $dataentry->link);
            $item->appendChild($link);

            if (isset($dataentry->guid)) {
                $guid = $this->_element->createElement('guid', $dataentry->guid);
                $item->appendChild($guid);
            }

            $description = $this->_element->createElement('description');
            $description->appendChild($this->_element->createCDATASection($dataentry->description));
            $item->appendChild($description);

            if (isset($dataentry->content)) {
                $content = $this->_element->createElement('content:encoded');
                $content->appendChild($this->_element->createCDATASection($dataentry->content));
                $item->appendChild($content);
            }

            $pubdate = isset($dataentry->lastUpdate) ? $dataentry->lastUpdate : time();
            $pubdate = $this->_element->createElement('pubDate', gmdate('r', $pubdate));
            $item->appendChild($pubdate);

            if (isset($dataentry->category)) {
                foreach ($dataentry->category as $category) {
                    $node = $this->_element->createElement('category', $category['term']);
                    if (isset($category['scheme'])) {
                        $node->setAttribute('domain', $category['scheme']);
                    }
                    $item->appendChild($node);
                }
            }

            if (isset($dataentry->source)) {
                $source = $this->_element->createElement('source', $dataentry->source['title']);
                $source->setAttribute('url', $dataentry->source['url']);
                $item->appendChild($source);
            }

            if (isset($dataentry->comments)) {
                $comments = $this->_element->createElement('comments', $dataentry->comments);
                $item->appendChild($comments);
            }
            if (isset($dataentry->commentRss)) {
                $comments = $this->_element->createElementNS('http://wellformedweb.org/CommentAPI/',
                                                             'wfw:commentRss',
                                                             $dataentry->commentRss);
                $item->appendChild($comments);
            }


            if (isset($dataentry->enclosure)) {
                foreach ($dataentry->enclosure as $enclosure) {
                    $node = $this->_element->createElement('enclosure');
                    $node->setAttribute('url', $enclosure['url']);
                    if (isset($enclosure['type'])) {
                        $node->setAttribute('type', $enclosure['type']);
                    }
                    if (isset($enclosure['length'])) {
                        $node->setAttribute('length', $enclosure['length']);
                    }
                    $item->appendChild($node);
                }
            }

            $root->appendChild($item);
        }
    }

    /**
     * Override Zend_Feed_Element to include <rss> root node
     *
     * @return string
     */
    public function saveXml()
    {
        // Return a complete document including XML prologue.
        $doc = new DOMDocument($this->_element->ownerDocument->version,
                               $this->_element->ownerDocument->actualEncoding);  
        $root = $doc->createElement('rss');

        // Use rss version 2.0
        $root->setAttribute('version', '2.0');
        $root->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom');
        // Content namespace
        $root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:content', 'http://purl.org/rss/1.0/modules/content/');
        $root->appendChild($doc->importNode($this->_element, true));

        // Append root node
        $doc->appendChild($root);
        
      

        // Format output
        $doc->formatOutput = true;

        return $doc->saveXML();
    }

    /**
     * Send feed to a http client with the correct header
     *
     * @return void
     * @throws Zend_Feed_Exception if headers have already been sent
     */
    public function send()
    {
        if (headers_sent()) {
            /**
             * @see Zend_Feed_Exception
             */
            require_once 'Zend/Feed/Exception.php';
            throw new Zend_Feed_Exception('Cannot send RSS because headers have already been sent.');
        }

        header('Content-Type: application/rss+xml; charset=' . $this->_element->ownerDocument->actualEncoding);

        echo $this->saveXml();
    }

}
Feed/Abstract.php000066600000016614151256604600007704 0ustar00<?php

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


/**
 * @see Zend_Feed_Element
 */
require_once 'Zend/Feed/Element.php';


/**
 * The Zend_Feed_Abstract class is an abstract class representing feeds.
 *
 * Zend_Feed_Abstract implements two core PHP 5 interfaces: ArrayAccess and
 * Iterator. In both cases the collection being treated as an array is
 * considered to be the entry collection, such that iterating over the
 * feed takes you through each of the feed.s entries.
 *
 * @category   Zend
 * @package    Zend_Feed
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Feed_Abstract extends Zend_Feed_Element implements Iterator
{
    /**
     * Current index on the collection of feed entries for the
     * Iterator implementation.
     *
     * @var integer
     */
    protected $_entryIndex = 0;

    /**
     * Cache of feed entries.
     *
     * @var array
     */
    protected $_entries;

    /**
     * Feed constructor
     *
     * The Zend_Feed_Abstract constructor takes the URI of a feed or a
     * feed represented as a string and loads it as XML.
     *
     * @param  string $uri The full URI of the feed to load, or NULL if not retrieved via HTTP or as an array.
     * @param  string $string The feed as a string, or NULL if retrieved via HTTP or as an array.
     * @param  Zend_Feed_Builder_Interface $builder The feed as a builder instance or NULL if retrieved as a string or via HTTP.
     * @return void
     * @throws Zend_Feed_Exception If loading the feed failed.
     */
    public function __construct($uri = null, $string = null, Zend_Feed_Builder_Interface $builder = null)
    {
        if ($uri !== null) {
            // Retrieve the feed via HTTP
            $client = Zend_Feed::getHttpClient();
            $client->setUri($uri);
            $response = $client->request('GET');
            if ($response->getStatus() !== 200) {
                /** 
                 * @see Zend_Feed_Exception
                 */
                require_once 'Zend/Feed/Exception.php';
                throw new Zend_Feed_Exception('Feed failed to load, got response code ' . $response->getStatus());
            }
            $this->_element = $response->getBody();
            $this->__wakeup();
        } elseif ($string !== null) {
            // Retrieve the feed from $string
            $this->_element = $string;
            $this->__wakeup();
        } else {
            // Generate the feed from the array
            $header = $builder->getHeader();
            $this->_element = new DOMDocument('1.0', $header['charset']);
            $root = $this->_mapFeedHeaders($header);
            $this->_mapFeedEntries($root, $builder->getEntries());
            $this->_element = $root;
            $this->_buildEntryCache();
        }
    }


    /**
     * Load the feed as an XML DOMDocument object
     *
     * @return void
     * @throws Zend_Feed_Exception
     */
    public function __wakeup()
    {
        @ini_set('track_errors', 1);
        $doc = new DOMDocument;
        $status = @$doc->loadXML($this->_element);
        @ini_restore('track_errors');

        if (!$status) {
            // prevent the class to generate an undefined variable notice (ZF-2590)
            if (!isset($php_errormsg)) {
                if (function_exists('xdebug_is_enabled')) {
                    $php_errormsg = '(error message not available, when XDebug is running)';
                } else {
                    $php_errormsg = '(error message not available)';
                }
            }
            
            /** 
             * @see Zend_Feed_Exception
             */
            require_once 'Zend/Feed/Exception.php';
            throw new Zend_Feed_Exception("DOMDocument cannot parse XML: $php_errormsg");
        }

        $this->_element = $doc;
    }


    /**
     * Prepare for serialiation
     *
     * @return array
     */
    public function __sleep()
    {
        $this->_element = $this->saveXML();

        return array('_element');
    }


    /**
     * Cache the individual feed elements so they don't need to be
     * searched for on every operation.
     *
     * @return void
     */
    protected function _buildEntryCache()
    {
        $this->_entries = array();
        foreach ($this->_element->childNodes as $child) {
            if ($child->localName == $this->_entryElementName) {
                $this->_entries[] = $child;
            }
        }
    }


    /**
     * Get the number of entries in this feed object.
     *
     * @return integer Entry count.
     */
    public function count()
    {
        return count($this->_entries);
    }


    /**
     * Required by the Iterator interface.
     *
     * @return void
     */
    public function rewind()
    {
        $this->_entryIndex = 0;
    }


    /**
     * Required by the Iterator interface.
     *
     * @return mixed The current row, or null if no rows.
     */
    public function current()
    {
        return new $this->_entryClassName(
            null,
            $this->_entries[$this->_entryIndex]);
    }


    /**
     * Required by the Iterator interface.
     *
     * @return mixed The current row number (starts at 0), or NULL if no rows
     */
    public function key()
    {
        return $this->_entryIndex;
    }


    /**
     * Required by the Iterator interface.
     *
     * @return mixed The next row, or null if no more rows.
     */
    public function next()
    {
        ++$this->_entryIndex;
    }


    /**
     * Required by the Iterator interface.
     *
     * @return boolean Whether the iteration is valid
     */
    public function valid()
    {
        return 0 <= $this->_entryIndex && $this->_entryIndex < $this->count();
    }

    /**
     * Generate the header of the feed when working in write mode
     *
     * @param  array $array the data to use
     * @return DOMElement root node
     */
    abstract protected function _mapFeedHeaders($array);

    /**
     * Generate the entries of the feed when working in write mode
     *
     * @param  DOMElement $root the root node to use
     * @param  array $array the data to use
     * @return DOMElement root node
     */
    abstract protected function _mapFeedEntries(DOMElement $root, $array);

    /**
     * Send feed to a http client with the correct header
     *
     * @throws Zend_Feed_Exception if headers have already been sent
     * @return void
     */
    abstract public function send();
}
Date/DateObject.php000066600000114450151256604600010154 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Date
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: DateObject.php 13319 2008-12-16 09:27:04Z thomas $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @category   Zend
 * @package    Zend_Date
 * @subpackage Zend_Date_DateObject
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Date_DateObject {

    /**
     * UNIX Timestamp
     */
    private   $_unixTimestamp;
    protected static $_cache         = null;
    protected static $_defaultOffset = 0;

    /**
     * active timezone
     */
    private   $_timezone    = 'UTC';
    private   $_offset      = 0;
    private   $_syncronised = 0;

    // turn off DST correction if UTC or GMT
    protected $_dst         = true;

    /**
     * Table of Monthdays
     */
    private static $_monthTable = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    /**
     * Table of Years
     */
    private static $_yearTable = array(
        1970 => 0,            1960 => -315619200,   1950 => -631152000,
        1940 => -946771200,   1930 => -1262304000,  1920 => -1577923200,
        1910 => -1893456000,  1900 => -2208988800,  1890 => -2524521600,
        1880 => -2840140800,  1870 => -3155673600,  1860 => -3471292800,
        1850 => -3786825600,  1840 => -4102444800,  1830 => -4417977600,
        1820 => -4733596800,  1810 => -5049129600,  1800 => -5364662400,
        1790 => -5680195200,  1780 => -5995814400,  1770 => -6311347200,
        1760 => -6626966400,  1750 => -6942499200,  1740 => -7258118400,
        1730 => -7573651200,  1720 => -7889270400,  1710 => -8204803200,
        1700 => -8520336000,  1690 => -8835868800,  1680 => -9151488000,
        1670 => -9467020800,  1660 => -9782640000,  1650 => -10098172800,
        1640 => -10413792000, 1630 => -10729324800, 1620 => -11044944000,
        1610 => -11360476800, 1600 => -11676096000);

    /**
     * Set this object to have a new UNIX timestamp.
     *
     * @param  string|integer  $timestamp  OPTIONAL timestamp; defaults to local time using time()
     * @return string|integer  old timestamp
     * @throws Zend_Date_Exception
     */
    protected function setUnixTimestamp($timestamp = null)
    {
        $old = $this->_unixTimestamp;

        if (is_numeric($timestamp)) {
            $this->_unixTimestamp = $timestamp;
        } else if ($timestamp === null) {
            $this->_unixTimestamp = time();
        } else {
            require_once 'Zend/Date/Exception.php';
            throw new Zend_Date_Exception('\'' . $timestamp . '\' is not a valid UNIX timestamp', $timestamp);
        }

        return $old;
    }

    /**
     * Returns this object's UNIX timestamp
     * A timestamp greater then the integer range will be returned as string
     * This function does not return the timestamp as object. Use copy() instead.
     *
     * @return  integer|string  timestamp
     */
    protected function getUnixTimestamp()
    {
        if ($this->_unixTimestamp === intval($this->_unixTimestamp)) {
            return (int) $this->_unixTimestamp;
        } else {
            return (string) $this->_unixTimestamp;
        }
    }

    /**
     * Internal function.
     * Returns time().  This method exists to allow unit tests to work-around methods that might otherwise
     * be hard-coded to use time().  For example, this makes it possible to test isYesterday() in Date.php.
     *
     * @param   integer  $sync      OPTIONAL time syncronisation value
     * @return  integer  timestamp
     */
    protected function _getTime($sync = null)
    {
        if ($sync !== null) {
            $this->_syncronised = round($sync);
        }
        return (time() + $this->_syncronised);
    }

    /**
     * Internal mktime function used by Zend_Date.
     * The timestamp returned by mktime() can exceed the precision of traditional UNIX timestamps,
     * by allowing PHP to auto-convert to using a float value.
     *
     * Returns a timestamp relative to 1970/01/01 00:00:00 GMT/UTC.
     * DST (Summer/Winter) is depriciated since php 5.1.0.
     * Year has to be 4 digits otherwise it would be recognised as
     * year 70 AD instead of 1970 AD as expected !!
     *
     * @param  integer  $hour
     * @param  integer  $minute
     * @param  integer  $second
     * @param  integer  $month
     * @param  integer  $day
     * @param  integer  $year
     * @param  boolean  $gmt     OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date
     * @return  integer|float  timestamp (number of seconds elapsed relative to 1970/01/01 00:00:00 GMT/UTC)
     */
    protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = false)
    {

        // complete date but in 32bit timestamp - use PHP internal
        if ((1901 < $year) and ($year < 2038)) {

            $oldzone = @date_default_timezone_get();
            // Timezone also includes DST settings, therefor substracting the GMT offset is not enough
            // We have to set the correct timezone to get the right value
            if (($this->_timezone != $oldzone) and ($gmt === false)) {
                date_default_timezone_set($this->_timezone);
            }
            $result = ($gmt) ? @gmmktime($hour, $minute, $second, $month, $day, $year)
                             :   @mktime($hour, $minute, $second, $month, $day, $year);
            date_default_timezone_set($oldzone);

            return $result;
        }

        if ($gmt !== true) {
            $second += $this->_offset;
        }

        if (isset(self::$_cache)) {
            $id = strtr('Zend_DateObject_mkTime_' . $this->_offset . '_' . $year.$month.$day.'_'.$hour.$minute.$second . '_'.(int)$gmt, '-','_');
            if ($result = self::$_cache->load($id)) {
                return unserialize($result);
            }
        }

        // date to integer
        $day   = intval($day);
        $month = intval($month);
        $year  = intval($year);

        // correct months > 12 and months < 1
        if ($month > 12) {
            $overlap = floor($month / 12);
            $year   += $overlap;
            $month  -= $overlap * 12;
        } else {
            $overlap = ceil((1 - $month) / 12);
            $year   -= $overlap;
            $month  += $overlap * 12;
        }

        $date = 0;
        if ($year >= 1970) {

            // Date is after UNIX epoch
            // go through leapyears
            // add months from latest given year
            for ($count = 1970; $count <= $year; $count++) {

                $leapyear = self::isYearLeapYear($count);
                if ($count < $year) {

                    $date += 365;
                    if ($leapyear === true) {
                        $date++;
                    }

                } else {

                    for ($mcount = 0; $mcount < ($month - 1); $mcount++) {
                        $date += self::$_monthTable[$mcount];
                        if (($leapyear === true) and ($mcount == 1)) {
                            $date++;
                        }

                    }
                }
            }

            $date += $day - 1;
            $date = (($date * 86400) + ($hour * 3600) + ($minute * 60) + $second);
        } else {

            // Date is before UNIX epoch
            // go through leapyears
            // add months from latest given year
            for ($count = 1969; $count >= $year; $count--) {

                $leapyear = self::isYearLeapYear($count);
                if ($count > $year)
                {
                    $date += 365;
                    if ($leapyear === true)
                        $date++;
                } else {

                    for ($mcount = 11; $mcount > ($month - 1); $mcount--) {
                        $date += self::$_monthTable[$mcount];
                        if (($leapyear === true) and ($mcount == 1)) {
                            $date++;
                        }

                    }
                }
            }

            $date += (self::$_monthTable[$month - 1] - $day);
            $date = -(($date * 86400) + (86400 - (($hour * 3600) + ($minute * 60) + $second)));

            // gregorian correction for 5.Oct.1582
            if ($date < -12220185600) {
                $date += 864000;
            } else if ($date < -12219321600) {
                $date  = -12219321600;
            }
        }

        if (isset(self::$_cache)) {
            self::$_cache->save( serialize($date), $id);
        }

        return $date;
    }

    /**
     * Returns true, if given $year is a leap year.
     *
     * @param  integer  $year
     * @return boolean  true, if year is leap year
     */
    protected static function isYearLeapYear($year)
    {
        // all leapyears can be divided through 4
        if (($year % 4) != 0) {
            return false;
        }

        // all leapyears can be divided through 400
        if ($year % 400 == 0) {
            return true;
        } else if (($year > 1582) and ($year % 100 == 0)) {
            return false;
        }

        return true;
    }

    /**
     * Internal mktime function used by Zend_Date for handling 64bit timestamps.
     *
     * Returns a formatted date for a given timestamp.
     *
     * @param  string   $format     format for output
     * @param  mixed    $timestamp
     * @param  boolean  $gmt        OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date
     * @return string
     */
    protected function date($format, $timestamp = null, $gmt = false)
    {
        $oldzone = @date_default_timezone_get();
        if ($this->_timezone != $oldzone) {
            date_default_timezone_set($this->_timezone);
        }
        if ($timestamp === null) {
            $result = ($gmt) ? @gmdate($format) : @date($format);
            date_default_timezone_set($oldzone);
            return $result;
        }

        if (abs($timestamp) <= 0x7FFFFFFF) {
            $result = ($gmt) ? @gmdate($format, $timestamp) : @date($format, $timestamp);
            date_default_timezone_set($oldzone);
            return $result;
        }

        $jump = false;
        if (isset(self::$_cache)) {
            $idstamp = strtr('Zend_DateObject_date_' . $this->_offset . '_'. $timestamp . '_'.(int)$gmt, '-','_');
            if ($result2 = self::$_cache->load($idstamp)) {
                $timestamp = unserialize($result2);
                $jump = true;
            }
        }

        // check on false or null alone failes
        if (empty($gmt) and empty($jump)) {
            $tempstamp = $timestamp;
            if ($tempstamp > 0) {
                while (abs($tempstamp) > 0x7FFFFFFF) {
                    $tempstamp -= (86400 * 23376);
                }
                $dst = date("I", $tempstamp);
                if ($dst === 1) {
                    $timestamp += 3600;
                }
                $temp = date('Z', $tempstamp);
                $timestamp += $temp;
            }

            if (isset(self::$_cache)) {
                self::$_cache->save( serialize($timestamp), $idstamp);
            }
        }


        if (($timestamp < 0) and ($gmt !== true)) {
            $timestamp -= $this->_offset;
        }
        date_default_timezone_set($oldzone);

        $date = $this->getDateParts($timestamp, true);
        $length = strlen($format);
        $output = '';

        for ($i = 0; $i < $length; $i++) {

            switch($format[$i]) {

                // day formats
                case 'd':  // day of month, 2 digits, with leading zero, 01 - 31
                    $output .= (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']);
                    break;

                case 'D':  // day of week, 3 letters, Mon - Sun
                    $output .= date('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday'])));
                    break;

                case 'j':  // day of month, without leading zero, 1 - 31
                    $output .= $date['mday'];
                    break;

                case 'l':  // day of week, full string name, Sunday - Saturday
                    $output .= date('l', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday'])));
                    break;

                case 'N':  // ISO 8601 numeric day of week, 1 - 7
                    $day = self::dayOfWeek($date['year'], $date['mon'], $date['mday']);
                    if ($day == 0) {
                        $day = 7;
                    }
                    $output .= $day;
                    break;

                case 'S':  // english suffix for day of month, st nd rd th
                    if (($date['mday'] % 10) == 1) {
                        $output .= 'st';
                    } else if ((($date['mday'] % 10) == 2) and ($date['mday'] != 12)) {
                        $output .= 'nd';
                    } else if (($date['mday'] % 10) == 3) {
                        $output .= 'rd';
                    } else {
                        $output .= 'th';
                    }
                    break;

                case 'w':  // numeric day of week, 0 - 6
                    $output .= self::dayOfWeek($date['year'], $date['mon'], $date['mday']);
                    break;

                case 'z':  // day of year, 0 - 365
                    $output .= $date['yday'];
                    break;


                // week formats
                case 'W':  // ISO 8601, week number of year
                    $output .= $this->weekNumber($date['year'], $date['mon'], $date['mday']);
                    break;


                // month formats
                case 'F':  // string month name, january - december
                    $output .= date('F', mktime(0, 0, 0, $date['mon'], 2, 1971));
                    break;

                case 'm':  // number of month, with leading zeros, 01 - 12
                    $output .= (($date['mon'] < 10) ? '0' . $date['mon'] : $date['mon']);
                    break;

                case 'M':  // 3 letter month name, Jan - Dec
                    $output .= date('M',mktime(0, 0, 0, $date['mon'], 2, 1971));
                    break;

                case 'n':  // number of month, without leading zeros, 1 - 12
                    $output .= $date['mon'];
                    break;

                case 't':  // number of day in month
                    $output .= self::$_monthTable[$date['mon'] - 1];
                    break;


                // year formats
                case 'L':  // is leap year ?
                    $output .= (self::isYearLeapYear($date['year'])) ? '1' : '0';
                    break;

                case 'o':  // ISO 8601 year number
                    $week = $this->weekNumber($date['year'], $date['mon'], $date['mday']);
                    if (($week > 50) and ($date['mon'] == 1)) {
                        $output .= ($date['year'] - 1);
                    } else {
                        $output .= $date['year'];
                    }
                    break;

                case 'Y':  // year number, 4 digits
                    $output .= $date['year'];
                    break;

                case 'y':  // year number, 2 digits
                    $output .= substr($date['year'], strlen($date['year']) - 2, 2);
                    break;


                // time formats
                case 'a':  // lower case am/pm
                    $output .= (($date['hours'] >= 12) ? 'pm' : 'am');
                    break;

                case 'A':  // upper case am/pm
                    $output .= (($date['hours'] >= 12) ? 'PM' : 'AM');
                    break;

                case 'B':  // swatch internet time
                    $dayseconds = ($date['hours'] * 3600) + ($date['minutes'] * 60) + $date['seconds'];
                    if ($gmt === true) {
                        $dayseconds += 3600;
                    }
                    $output .= (int) (($dayseconds % 86400) / 86.4);
                    break;

                case 'g':  // hours without leading zeros, 12h format
                    if ($date['hours'] > 12) {
                        $hour = $date['hours'] - 12;
                    } else {
                        if ($date['hours'] == 0) {
                            $hour = '12';
                        } else {
                            $hour = $date['hours'];
                        }
                    }
                    $output .= $hour;
                    break;

                case 'G':  // hours without leading zeros, 24h format
                    $output .= $date['hours'];
                    break;

                case 'h':  // hours with leading zeros, 12h format
                    if ($date['hours'] > 12) {
                        $hour = $date['hours'] - 12;
                    } else {
                        if ($date['hours'] == 0) {
                            $hour = '12';
                        } else {
                            $hour = $date['hours'];
                        }
                    }
                    $output .= (($hour < 10) ? '0'.$hour : $hour);
                    break;

                case 'H':  // hours with leading zeros, 24h format
                    $output .= (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']);
                    break;

                case 'i':  // minutes with leading zeros
                    $output .= (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']);
                    break;

                case 's':  // seconds with leading zeros
                    $output .= (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']);
                    break;


                // timezone formats
                case 'e':  // timezone identifier
                    if ($gmt === true) {
                        $output .= gmdate('e', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    } else {
                        $output .=   date('e', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    }
                    break;

                case 'I':  // daylight saving time or not
                    if ($gmt === true) {
                        $output .= gmdate('I', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    } else {
                        $output .=   date('I', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    }
                    break;

                case 'O':  // difference to GMT in hours
                    $gmtstr = ($gmt === true) ? 0 : $this->_offset;
                    $output .= sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36);
                    break;

                case 'P':  // difference to GMT with colon
                    $gmtstr = ($gmt === true) ? 0 : $this->_offset;
                    $gmtstr = sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36);
                    $output = $output . substr($gmtstr, 0, 3) . ':' . substr($gmtstr, 3);
                    break;

                case 'T':  // timezone settings
                    if ($gmt === true) {
                        $output .= gmdate('T', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    } else {
                        $output .=   date('T', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    }
                    break;

                case 'Z':  // timezone offset in seconds
                    $output .= ($gmt === true) ? 0 : -$this->_offset;
                    break;


                // complete time formats
                case 'c':  // ISO 8601 date format
                    $difference = $this->_offset;
                    $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36);
                    $output .= $date['year'] . '-'
                             . (($date['mon']     < 10) ? '0' . $date['mon']     : $date['mon'])     . '-'
                             . (($date['mday']    < 10) ? '0' . $date['mday']    : $date['mday'])    . 'T'
                             . (($date['hours']   < 10) ? '0' . $date['hours']   : $date['hours'])   . ':'
                             . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':'
                             . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds'])
                             . $difference;
                    break;

                case 'r':  // RFC 2822 date format
                    $difference = $this->_offset;
                    $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36);
                    $output .= gmdate('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday']))) . ', '
                             . (($date['mday']    < 10) ? '0' . $date['mday']    : $date['mday'])    . ' '
                             . date('M', mktime(0, 0, 0, $date['mon'], 2, 1971)) . ' '
                             . $date['year'] . ' '
                             . (($date['hours']   < 10) ? '0' . $date['hours']   : $date['hours'])   . ':'
                             . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':'
                             . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']) . ' '
                             . $difference;
                    break;

                case 'U':  // Unix timestamp
                    $output .= $timestamp;
                    break;


                // special formats
                case "\\":  // next letter to print with no format
                    $i++;
                    if ($i < $length) {
                        $output .= $format[$i];
                    }
                    break;

                default:  // letter is no format so add it direct
                    $output .= $format[$i];
                    break;
            }
        }

        return (string) $output;
    }

    /**
     * Returns the day of week for a Gregorian calendar date.
     * 0 = sunday, 6 = saturday
     *
     * @param  integer  $year
     * @param  integer  $month
     * @param  integer  $day
     * @return integer  dayOfWeek
     */
    protected static function dayOfWeek($year, $month, $day)
    {
        if ((1901 < $year) and ($year < 2038)) {
            return (int) date('w', mktime(0, 0, 0, $month, $day, $year));
        }

        // gregorian correction
        $correction = 0;
        if (($year < 1582) or (($year == 1582) and (($month < 10) or (($month == 10) && ($day < 15))))) {
            $correction = 3;
        }

        if ($month > 2) {
            $month -= 2;
        } else {
            $month += 10;
            $year--;
        }

        $day  = floor((13 * $month - 1) / 5) + $day + ($year % 100) + floor(($year % 100) / 4);
        $day += floor(($year / 100) / 4) - 2 * floor($year / 100) + 77 + $correction;

        return (int) ($day - 7 * floor($day / 7));
    }

    /**
     * Internal getDateParts function for handling 64bit timestamps, similar to:
     * http://www.php.net/getdate
     *
     * Returns an array of date parts for $timestamp, relative to 1970/01/01 00:00:00 GMT/UTC.
     *
     * $fast specifies ALL date parts should be returned (slower)
     * Default is false, and excludes $dayofweek, weekday, month and timestamp from parts returned.
     *
     * @param   mixed    $timestamp
     * @param   boolean  $fast   OPTIONAL defaults to fast (false), resulting in fewer date parts
     * @return  array
     */
    protected function getDateParts($timestamp = null, $fast = null)
    {

        // actual timestamp
        if ($timestamp === null) {
            return getdate();
        }

        // 32bit timestamp
        if (abs($timestamp) <= 0x7FFFFFFF) {
            return @getdate($timestamp);
        }

        if (isset(self::$_cache)) {
            $id = strtr('Zend_DateObject_getDateParts_' . $timestamp.'_'.(int)$fast, '-','_');
            if ($result = self::$_cache->load($id)) {
                return unserialize($result);
            }
        }

        $otimestamp = $timestamp;
        $numday = 0;
        $month = 0;
        // gregorian correction
        if ($timestamp < -12219321600) {
            $timestamp -= 864000;
        }

        // timestamp lower 0
        if ($timestamp < 0) {
            $sec = 0;
            $act = 1970;

            // iterate through 10 years table, increasing speed
            foreach(self::$_yearTable as $year => $seconds) {
                if ($timestamp >= $seconds) {
                    $i = $act;
                    break;
                }
                $sec = $seconds;
                $act = $year;
            }

            $timestamp -= $sec;
            if (!isset($i)) {
                $i = $act;
            }

            // iterate the max last 10 years
            do {
                --$i;
                $day = $timestamp;

                $timestamp += 31536000;
                $leapyear = self::isYearLeapYear($i);
                if ($leapyear === true) {
                    $timestamp += 86400;
                }

                if ($timestamp >= 0) {
                    $year = $i;
                    break;
                }
            } while ($timestamp < 0);

            $secondsPerYear = 86400 * ($leapyear ? 366 : 365) + $day;

            $timestamp = $day;
            // iterate through months
            for ($i = 12; --$i >= 0;) {
                $day = $timestamp;

                $timestamp += self::$_monthTable[$i] * 86400;
                if (($leapyear === true) and ($i == 1)) {
                    $timestamp += 86400;
                }

                if ($timestamp >= 0) {
                    $month  = $i;
                    $numday = self::$_monthTable[$i];
                    if (($leapyear === true) and ($i == 1)) {
                        ++$numday;
                    }
                    break;
                }
            }

            $timestamp  = $day;
            $numberdays = $numday + ceil(($timestamp + 1) / 86400);

            $timestamp += ($numday - $numberdays + 1) * 86400;
            $hours      = floor($timestamp / 3600);
        } else {

            // iterate through years
            for ($i = 1970;;$i++) {
                $day = $timestamp;

                $timestamp -= 31536000;
                $leapyear = self::isYearLeapYear($i);
                if ($leapyear === true) {
                    $timestamp -= 86400;
                }

                if ($timestamp < 0) {
                    $year = $i;
                    break;
                }
            }

            $secondsPerYear = $day;

            $timestamp = $day;
            // iterate through months
            for ($i = 0; $i <= 11; $i++) {
                $day = $timestamp;
                $timestamp -= self::$_monthTable[$i] * 86400;

                if (($leapyear === true) and ($i == 1)) {
                    $timestamp -= 86400;
                }

                if ($timestamp < 0) {
                    $month  = $i;
                    $numday = self::$_monthTable[$i];
                    if (($leapyear === true) and ($i == 1)) {
                        ++$numday;
                    }
                    break;
                }
            }

            $timestamp  = $day;
            $numberdays = ceil(($timestamp + 1) / 86400);
            $timestamp  = $timestamp - ($numberdays - 1) * 86400;
            $hours = floor($timestamp / 3600);
        }

        $timestamp -= $hours * 3600;

        $month  += 1;
        $minutes = floor($timestamp / 60);
        $seconds = $timestamp - $minutes * 60;

        if ($fast === true) {
            $array = array(
                'seconds' => $seconds,
                'minutes' => $minutes,
                'hours'   => $hours,
                'mday'    => $numberdays,
                'mon'     => $month,
                'year'    => $year,
                'yday'    => floor($secondsPerYear / 86400),
            );
        } else {

            $dayofweek = self::dayOfWeek($year, $month, $numberdays);
            $array = array(
                    'seconds' => $seconds,
                    'minutes' => $minutes,
                    'hours'   => $hours,
                    'mday'    => $numberdays,
                    'wday'    => $dayofweek,
                    'mon'     => $month,
                    'year'    => $year,
                    'yday'    => floor($secondsPerYear / 86400),
                    'weekday' => gmdate('l', 86400 * (3 + $dayofweek)),
                    'month'   => gmdate('F', mktime(0, 0, 0, $month, 1, 1971)),
                    0         => $otimestamp
            );
        }

        if (isset(self::$_cache)) {
            self::$_cache->save( serialize($array), $id);
        }

        return $array;
    }

    /**
     * Internal getWeekNumber function for handling 64bit timestamps
     *
     * Returns the ISO 8601 week number of a given date
     *
     * @param  integer  $year
     * @param  integer  $month
     * @param  integer  $day
     * @return integer
     */
    protected function weekNumber($year, $month, $day)
    {
        if ((1901 < $year) and ($year < 2038)) {
            return (int) date('W', mktime(0, 0, 0, $month, $day, $year));
        }

        $dayofweek = self::dayOfWeek($year, $month, $day);
        $firstday  = self::dayOfWeek($year, 1, 1);
        if (($month == 1) and (($firstday < 1) or ($firstday > 4)) and ($day < 4)) {
            $firstday  = self::dayOfWeek($year - 1, 1, 1);
            $month     = 12;
            $day       = 31;

        } else if (($month == 12) and ((self::dayOfWeek($year + 1, 1, 1) < 5) and
                   (self::dayOfWeek($year + 1, 1, 1) > 0))) {
            return 1;
        }

        return intval (((self::dayOfWeek($year, 1, 1) < 5) and (self::dayOfWeek($year, 1, 1) > 0)) +
               4 * ($month - 1) + (2 * ($month - 1) + ($day - 1) + $firstday - $dayofweek + 6) * 36 / 256);
    }

    /**
     * Internal _range function
     * Sets the value $a to be in the range of [0, $b]
     *
     * @param float $a - value to correct
     * @param float $b - maximum range to set
     */
    private function _range($a, $b) {
        while ($a < 0) {
            $a += $b;
        }
        while ($a >= $b) {
            $a -= $b;
        }
        return $a;
    }

    /**
     * Calculates the sunrise or sunset based on a location
     *
     * @param  array  $location  Location for calculation MUST include 'latitude', 'longitude', 'horizon'
     * @param  bool   $horizon   true: sunrise; false: sunset
     * @return mixed  - false: midnight sun, integer:
     */
    protected function calcSun($location, $horizon, $rise = false)
    {
        // timestamp within 32bit
        if (abs($this->_unixTimestamp) <= 0x7FFFFFFF) {
            if ($rise === false) {
                return date_sunset($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'],
                                   $location['longitude'], 90 + $horizon, $this->_offset / 3600);
            }
            return date_sunrise($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'],
                                $location['longitude'], 90 + $horizon, $this->_offset / 3600);
        }

        // self calculation - timestamp bigger than 32bit
        // fix circle values
        $quarterCircle      = 0.5 * M_PI;
        $halfCircle         =       M_PI;
        $threeQuarterCircle = 1.5 * M_PI;
        $fullCircle         = 2   * M_PI;

        // radiant conversion for coordinates
        $radLatitude  = $location['latitude']   * $halfCircle / 180;
        $radLongitude = $location['longitude']  * $halfCircle / 180;

        // get solar coordinates
        $tmpRise       = $rise ? $quarterCircle : $threeQuarterCircle;
        $radDay        = $this->date('z',$this->_unixTimestamp) + ($tmpRise - $radLongitude) / $fullCircle;

        // solar anomoly and longitude
        $solAnomoly    = $radDay * 0.017202 - 0.0574039;
        $solLongitude  = $solAnomoly + 0.0334405 * sin($solAnomoly);
        $solLongitude += 4.93289 + 3.49066E-4 * sin(2 * $solAnomoly);

        // get quadrant
        $solLongitude = $this->_range($solLongitude, $fullCircle);

        if (($solLongitude / $quarterCircle) - intval($solLongitude / $quarterCircle) == 0) {
            $solLongitude += 4.84814E-6;
        }

        // solar ascension
        $solAscension = sin($solLongitude) / cos($solLongitude);
        $solAscension = atan2(0.91746 * $solAscension, 1);

        // adjust quadrant
        if ($solLongitude > $threeQuarterCircle) {
            $solAscension += $fullCircle;
        } else if ($solLongitude > $quarterCircle) {
            $solAscension += $halfCircle;
        }

        // solar declination
        $solDeclination  = 0.39782 * sin($solLongitude);
        $solDeclination /=  sqrt(-$solDeclination * $solDeclination + 1);
        $solDeclination  = atan2($solDeclination, 1);

        $solHorizon = $horizon - sin($solDeclination) * sin($radLatitude);
        $solHorizon /= cos($solDeclination) * cos($radLatitude);

        // midnight sun, always night
        if (abs($solHorizon) > 1) {
            return false;
        }

        $solHorizon /= sqrt(-$solHorizon * $solHorizon + 1);
        $solHorizon  = $quarterCircle - atan2($solHorizon, 1);

        if ($rise) {
            $solHorizon = $fullCircle - $solHorizon;
        }

        // time calculation
        $localTime     = $solHorizon + $solAscension - 0.0172028 * $radDay - 1.73364;
        $universalTime = $localTime - $radLongitude;

        // determinate quadrant
        $universalTime = $this->_range($universalTime, $fullCircle);

        // radiant to hours
        $universalTime *= 24 / $fullCircle;

        // convert to time
        $hour = intval($universalTime);
        $universalTime    = ($universalTime - $hour) * 60;
        $min  = intval($universalTime);
        $universalTime    = ($universalTime - $min) * 60;
        $sec  = intval($universalTime);

        return $this->mktime($hour, $min, $sec, $this->date('m', $this->_unixTimestamp),
                             $this->date('j', $this->_unixTimestamp), $this->date('Y', $this->_unixTimestamp),
                             -1, true);
    }

    /**
     * Sets a new timezone for calculation of $this object's gmt offset.
     * For a list of supported timezones look here: http://php.net/timezones
     * If no timezone can be detected or the given timezone is wrong UTC will be set.
     *
     * @param  string  $zone      OPTIONAL timezone for date calculation; defaults to date_default_timezone_get()
     * @return Zend_Date_DateObject Provides fluent interface
     * @throws Zend_Date_Exception
     */
    public function setTimezone($zone = null)
    {
        $oldzone = @date_default_timezone_get();
        if ($zone === null) {
            $zone = $oldzone;
        }

        // throw an error on false input, but only if the new date extension is available
        if (function_exists('timezone_open')) {
            if (!@timezone_open($zone)) {
                require_once 'Zend/Date/Exception.php';
                throw new Zend_Date_Exception("timezone ($zone) is not a known timezone", $zone);
            }
        }
        // this can generate an error if the date extension is not available and a false timezone is given
        $result = @date_default_timezone_set($zone);
        if ($result === true) {
            $this->_offset   = mktime(0, 0, 0, 1, 2, 1970) - gmmktime(0, 0, 0, 1, 2, 1970);
            $this->_timezone = $zone;
        }
        date_default_timezone_set($oldzone);

        if (($zone == 'UTC') or ($zone == 'GMT')) {
            $this->_dst = false;
        } else {
            $this->_dst = true;
        }

        return $this;
    }

    /**
     * Return the timezone of $this object.
     * The timezone is initially set when the object is instantiated.
     *
     * @return  string  actual set timezone string
     */
    public function getTimezone()
    {
        return $this->_timezone;
    }

    /**
     * Return the offset to GMT of $this object's timezone.
     * The offset to GMT is initially set when the object is instantiated using the currently,
     * in effect, default timezone for PHP functions.
     *
     * @return  integer  seconds difference between GMT timezone and timezone when object was instantiated
     */
    public function getGmtOffset()
    {
        return $this->_offset;
    }
}
OpenId/Provider.php000066600000066041151256604600010245 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_OpenId
 * @subpackage Zend_OpenId_Provider
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Provider.php 12507 2008-11-10 16:29:09Z matthew $
 */

/**
 * @see Zend_OpenId
 */
require_once "Zend/OpenId.php";

/**
 * @see Zend_OpenId_Extension
 */
require_once "Zend/OpenId/Extension.php";

/**
 * OpenID provider (server) implementation
 *
 * @category   Zend
 * @package    Zend_OpenId
 * @subpackage Zend_OpenId_Provider
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_OpenId_Provider
{

    /**
     * Reference to an implementation of storage object
     *
     * @var Zend_OpenId_Provider_Storage $_storage
     */
    private $_storage;

    /**
     * Reference to an implementation of user object
     *
     * @var Zend_OpenId_Provider_User $_user
     */
    private $_user;

    /**
     * Time to live of association session in secconds
     *
     * @var integer $_sessionTtl
     */
    private $_sessionTtl;

    /**
     * URL to peform interactive user login
     *
     * @var string $_loginUrl
     */
    private $_loginUrl;

    /**
     * URL to peform interactive validation of consumer by user
     *
     * @var string $_trustUrl
     */
    private $_trustUrl;

    /**
     * The OP Endpoint URL
     *
     * @var string $_opEndpoint
     */
    private $_opEndpoint;

    /**
     * Constructs a Zend_OpenId_Provider object with given parameters.
     *
     * @param string $loginUrl is an URL that provides login screen for
     *  end-user (by default it is the same URL with additional GET variable
     *  openid.action=login)
     * @param string $trustUrl is an URL that shows a question if end-user
     *  trust to given consumer (by default it is the same URL with additional
     *  GET variable openid.action=trust)
     * @param Zend_OpenId_Provider_User $user is an object for communication
     *  with User-Agent and store information about logged-in user (it is a
     *  Zend_OpenId_Provider_User_Session object by default)
     * @param Zend_OpenId_Provider_Storage $storage is an object for keeping
     *  persistent database (it is a Zend_OpenId_Provider_Storage_File object
     *  by default)
     * @param integer $sessionTtl is a default time to live for association
     *   session in seconds (1 hour by default). Consumer must reestablish
     *   association after that time.
     */
    public function __construct($loginUrl = null,
                                $trustUrl = null,
                                Zend_OpenId_Provider_User $user = null,
                                Zend_OpenId_Provider_Storage $storage = null,
                                $sessionTtl = 3600)
    {
        if ($loginUrl === null) {
            $loginUrl = Zend_OpenId::selfUrl() . '?openid.action=login';
        } else {
            $loginUrl = Zend_OpenId::absoluteUrl($loginUrl);
        }
        $this->_loginUrl = $loginUrl;
        if ($trustUrl === null) {
            $trustUrl = Zend_OpenId::selfUrl() . '?openid.action=trust';
        } else {
            $trustUrl = Zend_OpenId::absoluteUrl($trustUrl);
        }
        $this->_trustUrl = $trustUrl;
        if ($user === null) {
            require_once "Zend/OpenId/Provider/User/Session.php";
            $this->_user = new Zend_OpenId_Provider_User_Session();
        } else {
            $this->_user = $user;
        }
        if ($storage === null) {
            require_once "Zend/OpenId/Provider/Storage/File.php";
            $this->_storage = new Zend_OpenId_Provider_Storage_File();
        } else {
            $this->_storage = $storage;
        }
        $this->_sessionTtl = $sessionTtl;
    }

    /**
     * Sets the OP Endpoint URL
     *
     * @param string $url the OP Endpoint URL
     * @return null
     */
    public function setOpEndpoint($url)
    {
        $this->_opEndpoint = $url;
    }

    /**
     * Registers a new user with given $id and $password
     * Returns true in case of success and false if user with given $id already
     * exists
     *
     * @param string $id user identity URL
     * @param string $password encoded user password
     * @return bool
     */
    public function register($id, $password)
    {
        if (!Zend_OpenId::normalize($id) || empty($id)) {
            return false;
        }
        return $this->_storage->addUser($id, md5($id.$password));
    }

    /**
     * Returns true if user with given $id exists and false otherwise
     *
     * @param string $id user identity URL
     * @return bool
     */
    public function hasUser($id) {
        if (!Zend_OpenId::normalize($id)) {
            return false;
        }
        return $this->_storage->hasUser($id);
    }

    /**
     * Performs login of user with given $id and $password
     * Returns true in case of success and false otherwise
     *
     * @param string $id user identity URL
     * @param string $password user password
     * @return bool
     */
    public function login($id, $password)
    {
        if (!Zend_OpenId::normalize($id)) {
            return false;
        }
        if (!$this->_storage->checkUser($id, md5($id.$password))) {
            return false;
        }
        $this->_user->setLoggedInUser($id);
        return true;
    }

    /**
     * Performs logout. Clears information about logged in user.
     *
     * @return void
     */
    public function logout()
    {
        $this->_user->delLoggedInUser();
        return true;
    }

    /**
     * Returns identity URL of current logged in user or false
     *
     * @return mixed
     */
    public function getLoggedInUser() {
        return $this->_user->getLoggedInUser();
    }

    /**
     * Retrieve consumer's root URL from request query.
     * Returns URL or false in case of failure
     *
     * @param array $params query arguments
     * @return mixed
     */
    public function getSiteRoot($params)
    {
        $version = 1.1;
        if (isset($params['openid_ns']) &&
            $params['openid_ns'] == Zend_OpenId::NS_2_0) {
            $version = 2.0;
        }
        if ($version >= 2.0 && isset($params['openid_realm'])) {
            $root = $params['openid_realm'];
        } else if ($version < 2.0 && isset($params['openid_trust_root'])) {
            $root = $params['openid_trust_root'];
        } else if (isset($params['openid_return_to'])) {
            $root = $params['openid_return_to'];
        } else {
            return false;
        }
        if (Zend_OpenId::normalizeUrl($root) && !empty($root)) {
            return $root;
        }
        return false;
    }

    /**
     * Allows consumer with given root URL to authenticate current logged
     * in user. Returns true on success and false on error.
     *
     * @param string $root root URL
     * @param mixed $extensions extension object or array of extensions objects
     * @return bool
     */
    public function allowSite($root, $extensions=null)
    {
        $id = $this->getLoggedInUser();
        if ($id === false) {
            return false;
        }
        if ($extensions !== null) {
            $data = array();
            Zend_OpenId_Extension::forAll($extensions, 'getTrustData', $data);
        } else {
            $data = true;
        }
        $this->_storage->addSite($id, $root, $data);
        return true;
    }

    /**
     * Prohibit consumer with given root URL to authenticate current logged
     * in user. Returns true on success and false on error.
     *
     * @param string $root root URL
     * @return bool
     */
    public function denySite($root)
    {
        $id = $this->getLoggedInUser();
        if ($id === false) {
            return false;
        }
        $this->_storage->addSite($id, $root, false);
        return true;
    }

    /**
     * Delete consumer with given root URL from known sites of current logged
     * in user. Next time this consumer will try to authenticate the user,
     * Provider will ask user's confirmation.
     * Returns true on success and false on error.
     *
     * @param string $root root URL
     * @return bool
     */
    public function delSite($root)
    {
        $id = $this->getLoggedInUser();
        if ($id === false) {
            return false;
        }
        $this->_storage->addSite($id, $root, null);
        return true;
    }

    /**
     * Returns list of known consumers for current logged in user or false
     * if he is not logged in.
     *
     * @return mixed
     */
    public function getTrustedSites()
    {
        $id = $this->getLoggedInUser();
        if ($id === false) {
            return false;
        }
        return $this->_storage->getTrustedSites($id);
    }

    /**
     * Handles HTTP request from consumer
     *
     * @param array $params GET or POST variables. If this parameter is omited
     *  or set to null, then $_GET or $_POST superglobal variable is used
     *  according to REQUEST_METHOD.
     * @param mixed $extensions extension object or array of extensions objects
     * @param Zend_Controller_Response_Abstract $response an optional response
     *  object to perform HTTP or HTML form redirection
     * @return mixed
     */
    public function handle($params=null, $extensions=null,
                           Zend_Controller_Response_Abstract $response = null)
    {
        if ($params === null) {
            if ($_SERVER["REQUEST_METHOD"] == "GET") {
                $params = $_GET;
            } else if ($_SERVER["REQUEST_METHOD"] == "POST") {
                $params = $_POST;
            } else {
                return false;
            }
        }
        $version = 1.1;
        if (isset($params['openid_ns']) &&
            $params['openid_ns'] == Zend_OpenId::NS_2_0) {
            $version = 2.0;
        }
        if (isset($params['openid_mode'])) {
            if ($params['openid_mode'] == 'associate') {
                $response = $this->_associate($version, $params);
                $ret = '';
                foreach ($response as $key => $val) {
                    $ret .= $key . ':' . $val . "\n";
                }
                return $ret;
            } else if ($params['openid_mode'] == 'checkid_immediate') {
                $ret = $this->_checkId($version, $params, 1, $extensions, $response);
                if (is_bool($ret)) return $ret;
                if (!empty($params['openid_return_to'])) {
                    Zend_OpenId::redirect($params['openid_return_to'], $ret, $response);
                }
                return true;
            } else if ($params['openid_mode'] == 'checkid_setup') {
                $ret = $this->_checkId($version, $params, 0, $extensions, $response);
                if (is_bool($ret)) return $ret;
                if (!empty($params['openid_return_to'])) {
                    Zend_OpenId::redirect($params['openid_return_to'], $ret, $response);
                }
                return true;
            } else if ($params['openid_mode'] == 'check_authentication') {
                $response = $this->_checkAuthentication($version, $params);
                $ret = '';
                foreach ($response as $key => $val) {
                    $ret .= $key . ':' . $val . "\n";
                }
                return $ret;
            }
        }
        return false;
    }

    /**
     * Generates a secret key for given hash function, returns RAW key or false
     * if function is not supported
     *
     * @param string $func hash function (sha1 or sha256)
     * @return mixed
     */
    protected function _genSecret($func)
    {
        if ($func == 'sha1') {
            $macLen = 20; /* 160 bit */
        } else if ($func == 'sha256') {
            $macLen = 32; /* 256 bit */
        } else {
            return false;
        }
        return Zend_OpenId::randomBytes($macLen);
    }

    /**
     * Processes association request from OpenID consumerm generates secret
     * shared key and send it back using Diffie-Hellman encruption.
     * Returns array of variables to push back to consumer.
     *
     * @param float $version OpenID version
     * @param array $params GET or POST request variables
     * @return array
     */
    protected function _associate($version, $params)
    {
        $ret = array();

        if ($version >= 2.0) {
            $ret['ns'] = Zend_OpenId::NS_2_0;
        }

        if (isset($params['openid_assoc_type']) &&
            $params['openid_assoc_type'] == 'HMAC-SHA1') {
            $macFunc = 'sha1';
        } else if (isset($params['openid_assoc_type']) &&
            $params['openid_assoc_type'] == 'HMAC-SHA256' &&
            $version >= 2.0) {
            $macFunc = 'sha256';
        } else {
            $ret['error'] = 'Wrong "openid.assoc_type"';
            $ret['error-code'] = 'unsupported-type';
            return $ret;
        }

        $ret['assoc_type'] = $params['openid_assoc_type'];

        $secret = $this->_genSecret($macFunc);

        if (empty($params['openid_session_type']) ||
            $params['openid_session_type'] == 'no-encryption') {
            $ret['mac_key'] = base64_encode($secret);
        } else if (isset($params['openid_session_type']) &&
            $params['openid_session_type'] == 'DH-SHA1') {
            $dhFunc = 'sha1';
        } else if (isset($params['openid_session_type']) &&
            $params['openid_session_type'] == 'DH-SHA256' &&
            $version >= 2.0) {
            $dhFunc = 'sha256';
        } else {
            $ret['error'] = 'Wrong "openid.session_type"';
            $ret['error-code'] = 'unsupported-type';
            return $ret;
        }

        if (isset($params['openid_session_type'])) {
            $ret['session_type'] = $params['openid_session_type'];
        }

        if (isset($dhFunc)) {
            if (empty($params['openid_dh_consumer_public'])) {
                $ret['error'] = 'Wrong "openid.dh_consumer_public"';
                return $ret;
            }
            if (empty($params['openid_dh_gen'])) {
                $g = pack('H*', Zend_OpenId::DH_G);
            } else {
                $g = base64_decode($params['openid_dh_gen']);
            }
            if (empty($params['openid_dh_modulus'])) {
                $p = pack('H*', Zend_OpenId::DH_P);
            } else {
                $p = base64_decode($params['openid_dh_modulus']);
            }

            $dh = Zend_OpenId::createDhKey($p, $g);
            $dh_details = Zend_OpenId::getDhKeyDetails($dh);

            $sec = Zend_OpenId::computeDhSecret(
                base64_decode($params['openid_dh_consumer_public']), $dh);
            if ($sec === false) {
                $ret['error'] = 'Wrong "openid.session_type"';
                $ret['error-code'] = 'unsupported-type';
                return $ret;
            }
            $sec = Zend_OpenId::digest($dhFunc, $sec);
            $ret['dh_server_public'] = base64_encode(
                Zend_OpenId::btwoc($dh_details['pub_key']));
            $ret['enc_mac_key']      = base64_encode($secret ^ $sec);
        }

        $handle = uniqid();
        $expiresIn = $this->_sessionTtl;

        $ret['assoc_handle'] = $handle;
        $ret['expires_in'] = $expiresIn;

        $this->_storage->addAssociation($handle,
            $macFunc, $secret, time() + $expiresIn);

        return $ret;
    }

    /**
     * Performs authentication (or authentication check).
     *
     * @param float $version OpenID version
     * @param array $params GET or POST request variables
     * @param bool $immediate enables or disables interaction with user
     * @param mixed $extensions extension object or array of extensions objects
     * @param Zend_Controller_Response_Abstract $response
     * @return array
     */
    protected function _checkId($version, $params, $immediate, $extensions=null,
        Zend_Controller_Response_Abstract $response = null)
    {
        $ret = array();

        if ($version >= 2.0) {
            $ret['openid.ns'] = Zend_OpenId::NS_2_0;
        }
        $root = $this->getSiteRoot($params);
        if ($root === false) {
            return false;
        }

        if (isset($params['openid_identity']) &&
            !$this->_storage->hasUser($params['openid_identity'])) {
            $ret['openid.mode'] = ($immediate && $version >= 2.0) ? 'setup_needed': 'cancel';
            return $ret;
        }

        /* Check if user already logged in into the server */
        if (!isset($params['openid_identity']) ||
            $this->_user->getLoggedInUser() !== $params['openid_identity']) {
            $params2 = array();
            foreach ($params as $key => $val) {
                if (strpos($key, 'openid_ns_') === 0) {
                    $key = 'openid.ns.' . substr($key, strlen('openid_ns_'));
                } else if (strpos($key, 'openid_sreg_') === 0) {
                    $key = 'openid.sreg.' . substr($key, strlen('openid_sreg_'));
                } else if (strpos($key, 'openid_') === 0) {
                    $key = 'openid.' . substr($key, strlen('openid_'));
                }
                $params2[$key] = $val;
            }
            if ($immediate) {
                $params2['openid.mode'] = 'checkid_setup';
                $ret['openid.mode'] = ($version >= 2.0) ? 'setup_needed': 'id_res';
                $ret['openid.user_setup_url'] = $this->_loginUrl
                    . (strpos($this->_loginUrl, '?') === false ? '?' : '&')
                    . Zend_OpenId::paramsToQuery($params2);
                return $ret;
            } else {
                /* Redirect to Server Login Screen */
                Zend_OpenId::redirect($this->_loginUrl, $params2, $response);
                return true;
            }
        }

        if (!Zend_OpenId_Extension::forAll($extensions, 'parseRequest', $params)) {
            $ret['openid.mode'] = ($immediate && $version >= 2.0) ? 'setup_needed': 'cancel';
            return $ret;
        }

        /* Check if user trusts to the consumer */
        $trusted = null;
        $sites = $this->_storage->getTrustedSites($params['openid_identity']);
        if (isset($params['openid_return_to'])) {
            $root = $params['openid_return_to'];
        }
        if (isset($sites[$root])) {
            $trusted = $sites[$root];
        } else {
            foreach ($sites as $site => $t) {
                if (strpos($root, $site) === 0) {
                    $trusted = $t;
                    break;
                } else {
                    /* OpenID 2.0 (9.2) check for realm wild-card matching */
                    $n = strpos($site, '://*.');
                    if ($n != false) {
                        $regex = '/^'
                               . preg_quote(substr($site, 0, $n+3), '/')
                               . '[A-Za-z1-9_\.]+?'
                               . preg_quote(substr($site, $n+4), '/')
                               . '/';
                        if (preg_match($regex, $root)) {
                            $trusted = $t;
                            break;
                        }
                    }
                }
            }
        }

        if (is_array($trusted)) {
            if (!Zend_OpenId_Extension::forAll($extensions, 'checkTrustData', $trusted)) {
                $trusted = null;
            }
        }

        if ($trusted === false) {
            $ret['openid.mode'] = 'cancel';
            return $ret;
        } else if (is_null($trusted)) {
            /* Redirect to Server Trust Screen */
            $params2 = array();
            foreach ($params as $key => $val) {
                if (strpos($key, 'openid_ns_') === 0) {
                    $key = 'openid.ns.' . substr($key, strlen('openid_ns_'));
                } else if (strpos($key, 'openid_sreg_') === 0) {
                    $key = 'openid.sreg.' . substr($key, strlen('openid_sreg_'));
                } else if (strpos($key, 'openid_') === 0) {
                    $key = 'openid.' . substr($key, strlen('openid_'));
                }
                $params2[$key] = $val;
            }
            if ($immediate) {
                $params2['openid.mode'] = 'checkid_setup';
                $ret['openid.mode'] = ($version >= 2.0) ? 'setup_needed': 'id_res';
                $ret['openid.user_setup_url'] = $this->_trustUrl
                    . (strpos($this->_trustUrl, '?') === false ? '?' : '&')
                    . Zend_OpenId::paramsToQuery($params2);
                return $ret;
            } else {
                Zend_OpenId::redirect($this->_trustUrl, $params2, $response);
                return true;
            }
        }

        return $this->_respond($version, $ret, $params, $extensions);
    }

    /**
     * Perepares information to send back to consumer's authentication request,
     * signs it using shared secret and send back through HTTP redirection
     *
     * @param array $params GET or POST request variables
     * @param mixed $extensions extension object or array of extensions objects
     * @param Zend_Controller_Response_Abstract $response an optional response
     *  object to perform HTTP or HTML form redirection
     * @return bool
     */
    public function respondToConsumer($params, $extensions=null,
                           Zend_Controller_Response_Abstract $response = null)
    {
        $version = 1.1;
        if (isset($params['openid_ns']) &&
            $params['openid_ns'] == Zend_OpenId::NS_2_0) {
            $version = 2.0;
        }
        $ret = array();
        if ($version >= 2.0) {
            $ret['openid.ns'] = Zend_OpenId::NS_2_0;
        }
        $ret = $this->_respond($version, $ret, $params, $extensions);
        if (!empty($params['openid_return_to'])) {
            Zend_OpenId::redirect($params['openid_return_to'], $ret, $response);
        }
        return true;
    }

    /**
     * Perepares information to send back to consumer's authentication request
     * and signs it using shared secret.
     *
     * @param float $version OpenID protcol version
     * @param array $ret arguments to be send back to consumer
     * @param array $params GET or POST request variables
     * @param mixed $extensions extension object or array of extensions objects
     * @return array
     */
    protected function _respond($version, $ret, $params, $extensions=null)
    {
        if (empty($params['openid_assoc_handle']) ||
            !$this->_storage->getAssociation($params['openid_assoc_handle'],
                $macFunc, $secret, $expires)) {
            /* Use dumb mode */
            if (!empty($params['openid_assoc_handle'])) {
                $ret['openid.invalidate_handle'] = $params['openid_assoc_handle'];
            }
            $macFunc = $version >= 2.0 ? 'sha256' : 'sha1';
            $secret = $this->_genSecret($macFunc);
            $handle = uniqid();
            $expiresIn = $this->_sessionTtl;
            $this->_storage->addAssociation($handle,
                $macFunc, $secret, time() + $expiresIn);
            $ret['openid.assoc_handle'] = $handle;
        } else {
            $ret['openid.assoc_handle'] = $params['openid_assoc_handle'];
        }
        if (isset($params['openid_return_to'])) {
            $ret['openid.return_to'] = $params['openid_return_to'];
        }
        if (isset($params['openid_claimed_id'])) {
            $ret['openid.claimed_id'] = $params['openid_claimed_id'];
        }
        if (isset($params['openid_identity'])) {
            $ret['openid.identity'] = $params['openid_identity'];
        }

        if ($version >= 2.0) {
            if (!empty($this->_opEndpoint)) {
                $ret['openid.op_endpoint'] = $this->_opEndpoint;
            } else {
                $ret['openid.op_endpoint'] = Zend_OpenId::selfUrl();
            }
        }
        $ret['openid.response_nonce'] = gmdate('Y-m-d\TH:i:s\Z') . uniqid();
        $ret['openid.mode'] = 'id_res';

        Zend_OpenId_Extension::forAll($extensions, 'prepareResponse', $ret);

        $signed = '';
        $data = '';
        foreach ($ret as $key => $val) {
            if (strpos($key, 'openid.') === 0) {
                $key = substr($key, strlen('openid.'));
                if (!empty($signed)) {
                    $signed .= ',';
                }
                $signed .= $key;
                $data .= $key . ':' . $val . "\n";
            }
        }
        $signed .= ',signed';
        $data .= 'signed:' . $signed . "\n";
        $ret['openid.signed'] = $signed;

        $ret['openid.sig'] = base64_encode(
            Zend_OpenId::hashHmac($macFunc, $data, $secret));

        return $ret;
    }

    /**
     * Performs authentication validation for dumb consumers
     * Returns array of variables to push back to consumer.
     * It MUST contain 'is_valid' variable with value 'true' or 'false'.
     *
     * @param float $version OpenID version
     * @param array $params GET or POST request variables
     * @return array
     */
    protected function _checkAuthentication($version, $params)
    {
        $ret = array();
        if ($version >= 2.0) {
            $ret['ns'] = Zend_OpenId::NS_2_0;
        }
        $ret['openid.mode'] = 'id_res';

        if (empty($params['openid_assoc_handle']) ||
            empty($params['openid_signed']) ||
            empty($params['openid_sig']) ||
            !$this->_storage->getAssociation($params['openid_assoc_handle'],
                $macFunc, $secret, $expires)) {
            $ret['is_valid'] = 'false';
            return $ret;
        }

        $signed = explode(',', $params['openid_signed']);
        $data = '';
        foreach ($signed as $key) {
            $data .= $key . ':';
            if ($key == 'mode') {
                $data .= "id_res\n";
            } else {
                $data .= $params['openid_' . strtr($key,'.','_')]."\n";
            }
        }
        if (base64_decode($params['openid_sig']) ===
            Zend_OpenId::hashHmac($macFunc, $data, $secret)) {
            $ret['is_valid'] = 'true';
        } else {
            $ret['is_valid'] = 'false';
        }
        return $ret;
    }
}
OpenId/Consumer/Storage/File.php000066600000034657151256604600012541 0ustar00<?php

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

/**
 * @see Zend_OpenId_Consumer_Storage
 */
require_once "Zend/OpenId/Consumer/Storage.php";

/**
 * External storage implemmentation using serialized files
 *
 * @category   Zend
 * @package    Zend_OpenId
 * @subpackage Zend_OpenId_Consumer
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_OpenId_Consumer_Storage_File extends Zend_OpenId_Consumer_Storage
{

    /**
     * Directory name to store data files in
     *
     * @var string $_dir
     */
    private $_dir;

    /**
     * Constructs storage object and creates storage directory
     *
     * @param string $dir directory name to store data files in
     * @throws Zend_OpenId_Exception
     */
    public function __construct($dir = null)
    {
        if (is_null($dir)) {
            $tmp = getenv('TMP');
            if (empty($tmp)) {
                $tmp = getenv('TEMP');
                if (empty($tmp)) {
                    $tmp = "/tmp";
                }
            }
            $user = get_current_user();
            if (is_string($user) && !empty($user)) {
                $tmp .= '/' . $user;
            }
            $dir = $tmp . '/openid/consumer';
        }
        $this->_dir = $dir;
        if (!is_dir($this->_dir)) {
            if (!@mkdir($this->_dir, 0700, 1)) {
                /**
                 * @see Zend_OpenId_Exception
                 */
                require_once 'Zend/OpenId/Exception.php';
                throw new Zend_OpenId_Exception(
                    'Cannot access storage directory ' . $dir,
                    Zend_OpenId_Exception::ERROR_STORAGE);
            }
        }
        if (($f = fopen($this->_dir.'/assoc.lock', 'w+')) === null) {
            /**
             * @see Zend_OpenId_Exception
             */
            require_once 'Zend/OpenId/Exception.php';
            throw new Zend_OpenId_Exception(
                'Cannot create a lock file in the directory ' . $dir,
                Zend_OpenId_Exception::ERROR_STORAGE);
        }
        fclose($f);
        if (($f = fopen($this->_dir.'/discovery.lock', 'w+')) === null) {
            /**
             * @see Zend_OpenId_Exception
             */
            require_once 'Zend/OpenId/Exception.php';
            throw new Zend_OpenId_Exception(
                'Cannot create a lock file in the directory ' . $dir,
                Zend_OpenId_Exception::ERROR_STORAGE);
        }
        fclose($f);
        if (($f = fopen($this->_dir.'/nonce.lock', 'w+')) === null) {
            /**
             * @see Zend_OpenId_Exception
             */
            require_once 'Zend/OpenId/Exception.php';
            throw new Zend_OpenId_Exception(
                'Cannot create a lock file in the directory ' . $dir,
                Zend_OpenId_Exception::ERROR_STORAGE);
        }
        fclose($f);
    }

    /**
     * Stores information about association identified by $url/$handle
     *
     * @param string $url OpenID server URL
     * @param string $handle assiciation handle
     * @param string $macFunc HMAC function (sha1 or sha256)
     * @param string $secret shared secret
     * @param long $expires expiration UNIX time
     * @return bool
     */
    public function addAssociation($url, $handle, $macFunc, $secret, $expires)
    {
        $name1 = $this->_dir . '/assoc_url_' . md5($url);
        $name2 = $this->_dir . '/assoc_handle_' . md5($handle);
        $lock = @fopen($this->_dir . '/assoc.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name1, 'w+');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $data = serialize(array($url, $handle, $macFunc, $secret, $expires));
        fwrite($f, $data);
        if (function_exists('symlink')) {
            @unlink($name2);
            if (symlink($name1, $name2)) {
                fclose($f);
                fclose($lock);
                return true;
            }
        }
        $f2 = @fopen($name2, 'w+');
        if ($f2) {
            fwrite($f2, $data);
            fclose($f2);
            @unlink($name1);
            $ret = true;
        } else {
        	$ret = false;
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }

    /**
     * Gets information about association identified by $url
     * Returns true if given association found and not expired and false
     * otherwise
     *
     * @param string $url OpenID server URL
     * @param string &$handle assiciation handle
     * @param string &$macFunc HMAC function (sha1 or sha256)
     * @param string &$secret shared secret
     * @param long &$expires expiration UNIX time
     * @return bool
     */
    public function getAssociation($url, &$handle, &$macFunc, &$secret, &$expires)
    {
        $name1 = $this->_dir . '/assoc_url_' . md5($url);
        $lock = @fopen($this->_dir . '/assoc.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name1, 'r');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $ret = false;
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($storedUrl, $handle, $macFunc, $secret, $expires) = unserialize($data);
            if ($url === $storedUrl && $expires > time()) {
                $ret = true;
            } else {
                $name2 = $this->_dir . '/assoc_handle_' . md5($handle);
                fclose($f);
                @unlink($name2);
                @unlink($name1);
                fclose($lock);
                return false;
            }
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }

    /**
     * Gets information about association identified by $handle
     * Returns true if given association found and not expired and false
     * otherwise
     *
     * @param string $handle assiciation handle
     * @param string &$url OpenID server URL
     * @param string &$macFunc HMAC function (sha1 or sha256)
     * @param string &$secret shared secret
     * @param long &$expires expiration UNIX time
     * @return bool
     */
    public function getAssociationByHandle($handle, &$url, &$macFunc, &$secret, &$expires)
    {
        $name2 = $this->_dir . '/assoc_handle_' . md5($handle);
        $lock = @fopen($this->_dir . '/assoc.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name2, 'r');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $ret = false;
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($url, $storedHandle, $macFunc, $secret, $expires) = unserialize($data);
            if ($handle === $storedHandle && $expires > time()) {
                $ret = true;
            } else {
                fclose($f);
                @unlink($name2);
                $name1 = $this->_dir . '/assoc_url_' . md5($url);
                @unlink($name1);
                fclose($lock);
                return false;
            }
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }

    /**
     * Deletes association identified by $url
     *
     * @param string $url OpenID server URL
     * @return bool
     */
    public function delAssociation($url)
    {
        $name1 = $this->_dir . '/assoc_url_' . md5($url);
        $lock = @fopen($this->_dir . '/assoc.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name1, 'r');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($storedUrl, $handle, $macFunc, $secret, $expires) = unserialize($data);
            if ($url === $storedUrl) {
                $name2 = $this->_dir . '/assoc_handle_' . md5($handle);
                fclose($f);
                @unlink($name2);
                @unlink($name1);
                fclose($lock);
                return true;
            }
        }
        fclose($f);
        fclose($lock);
        return true;
    }

    /**
     * Stores information discovered from identity $id
     *
     * @param string $id identity
     * @param string $realId discovered real identity URL
     * @param string $server discovered OpenID server URL
     * @param float $version discovered OpenID protocol version
     * @param long $expires expiration UNIX time
     * @return bool
     */
    public function addDiscoveryInfo($id, $realId, $server, $version, $expires)
    {
        $name = $this->_dir . '/discovery_' . md5($id);
        $lock = @fopen($this->_dir . '/discovery.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'w+');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $data = serialize(array($id, $realId, $server, $version, $expires));
        fwrite($f, $data);
        fclose($f);
        fclose($lock);
        return true;
    }

    /**
     * Gets information discovered from identity $id
     * Returns true if such information exists and false otherwise
     *
     * @param string $id identity
     * @param string &$realId discovered real identity URL
     * @param string &$server discovered OpenID server URL
     * @param float &$version discovered OpenID protocol version
     * @param long &$expires expiration UNIX time
     * @return bool
     */
    public function getDiscoveryInfo($id, &$realId, &$server, &$version, &$expires)
    {
        $name = $this->_dir . '/discovery_' . md5($id);
        $lock = @fopen($this->_dir . '/discovery.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'r');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $ret = false;
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($storedId, $realId, $server, $version, $expires) = unserialize($data);
            if ($id === $storedId && $expires > time()) {
                $ret = true;
            } else {
                fclose($f);
                @unlink($name);
                fclose($lock);
                return false;
            }
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }

    /**
     * Removes cached information discovered from identity $id
     *
     * @param string $id identity
     * @return bool
     */
    public function delDiscoveryInfo($id)
    {
        $name = $this->_dir . '/discovery_' . md5($id);
        $lock = @fopen($this->_dir . '/discovery.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        @unlink($name);
        fclose($lock);
        return true;
    }

    /**
     * The function checks the uniqueness of openid.response_nonce
     *
     * @param string $provider openid.openid_op_endpoint field from authentication response
     * @param  string $nonce openid.response_nonce field from authentication response
     * @return bool
     */
    public function isUniqueNonce($provider, $nonce)
    {
        $name = $this->_dir . '/nonce_' . md5($provider.';'.$nonce);
        $lock = @fopen($this->_dir . '/nonce.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'x');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        fwrite($f, $provider.';'.$nonce);
        fclose($f);
        fclose($lock);
        return true;
    }

    /**
     * Removes data from the uniqueness database that is older then given date
     *
     * @param mixed $date date of expired data
     */
    public function purgeNonces($date=null)
    {
        $lock = @fopen($this->_dir . '/nonce.lock', 'w+');
        if ($lock !== false) {
            flock($lock, LOCK_EX);
        }
        if (!is_int($date) && !is_string($date)) {
            foreach (glob($this->_dir . '/nonce_*') as $name) {
                @unlink($name);
            }
        } else {
            if (is_string($date)) {
                $time = time($date);
            } else {
                $time = $date;
            }
            foreach (glob($this->_dir . '/nonce_*') as $name) {
                if (filemtime($name) < $time) {
                    @unlink($name);
                }
            }
        }
        if ($lock !== false) {
            fclose($lock);
        }
    }
}
OpenId/Provider/Storage/File.php000066600000027272151256604600012533 0ustar00<?php

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

/**
 * @see Zend_OpenId_Provider_Storage
 */
require_once "Zend/OpenId/Provider/Storage.php";

/**
 * External storage implemmentation using serialized files
 *
 * @category   Zend
 * @package    Zend_OpenId
 * @subpackage Zend_OpenId_Provider
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_OpenId_Provider_Storage_File extends Zend_OpenId_Provider_Storage
{

    /**
     * Directory name to store data files in
     *
     * @var string $_dir
     */
    private $_dir;

    /**
     * Constructs storage object and creates storage directory
     *
     * @param string $dir directory name to store data files in
     * @throws Zend_OpenId_Exception
     */
    public function __construct($dir = null)
    {
        if (is_null($dir)) {
            $tmp = getenv('TMP');
            if (empty($tmp)) {
                $tmp = getenv('TEMP');
                if (empty($tmp)) {
                    $tmp = "/tmp";
                }
            }
            $user = get_current_user();
            if (is_string($user) && !empty($user)) {
                $tmp .= '/' . $user;
            }
            $dir = $tmp . '/openid/provider';
        }
        $this->_dir = $dir;
        if (!is_dir($this->_dir)) {
            if (!@mkdir($this->_dir, 0700, 1)) {
                throw new Zend_OpenId_Exception(
                    "Cannot access storage directory $dir",
                    Zend_OpenId_Exception::ERROR_STORAGE);
            }
        }
        if (($f = fopen($this->_dir.'/assoc.lock', 'w+')) === null) {
            throw new Zend_OpenId_Exception(
                'Cannot create a lock file in the directory ' . $dir,
                Zend_OpenId_Exception::ERROR_STORAGE);
        }
        fclose($f);
        if (($f = fopen($this->_dir.'/user.lock', 'w+')) === null) {
            throw new Zend_OpenId_Exception(
                'Cannot create a lock file in the directory ' . $dir,
                Zend_OpenId_Exception::ERROR_STORAGE);
        }
        fclose($f);
    }

    /**
     * Stores information about session identified by $handle
     *
     * @param string $handle assiciation handle
     * @param string $macFunc HMAC function (sha1 or sha256)
     * @param string $secret shared secret
     * @param string $expires expiration UNIX time
     * @return bool
     */
    public function addAssociation($handle, $macFunc, $secret, $expires)
    {
        $name = $this->_dir . '/assoc_' . md5($handle);
        $lock = @fopen($this->_dir . '/assoc.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'w+');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $data = serialize(array($handle, $macFunc, $secret, $expires));
        fwrite($f, $data);
        fclose($f);
        fclose($lock);
        return true;
    }

    /**
     * Gets information about association identified by $handle
     * Returns true if given association found and not expired and false
     * otherwise
     *
     * @param string $handle assiciation handle
     * @param string &$macFunc HMAC function (sha1 or sha256)
     * @param string &$secret shared secret
     * @param string &$expires expiration UNIX time
     * @return bool
     */
    public function getAssociation($handle, &$macFunc, &$secret, &$expires)
    {
        $name = $this->_dir . '/assoc_' . md5($handle);
        $lock = @fopen($this->_dir . '/assoc.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'r');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $ret = false;
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($storedHandle, $macFunc, $secret, $expires) = unserialize($data);
            if ($handle === $storedHandle && $expires > time()) {
                $ret = true;
            } else {
                fclose($f);
                @unlink($name);
                fclose($lock);
                return false;
            }
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }

    /**
     * Removes information about association identified by $handle
     *
     * @param string $handle assiciation handle
     * @return bool
     */
    public function delAssociation($handle)
    {
        $name = $this->_dir . '/assoc_' . md5($handle);
        $lock = @fopen($this->_dir . '/assoc.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        @unlink($name);
        fclose($lock);
        return true;
    }

    /**
     * Register new user with given $id and $password
     * Returns true in case of success and false if user with given $id already
     * exists
     *
     * @param string $id user identity URL
     * @param string $password encoded user password
     * @return bool
     */
    public function addUser($id, $password)
    {
        $name = $this->_dir . '/user_' . md5($id);
        $lock = @fopen($this->_dir . '/user.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'x');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $data = serialize(array($id, $password, array()));
        fwrite($f, $data);
        fclose($f);
        fclose($lock);
        return true;
    }

    /**
     * Returns true if user with given $id exists and false otherwise
     *
     * @param string $id user identity URL
     * @return bool
     */
    public function hasUser($id)
    {
        $name = $this->_dir . '/user_' . md5($id);
        $lock = @fopen($this->_dir . '/user.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_SH)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'r');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $ret = false;
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($storedId, $storedPassword, $trusted) = unserialize($data);
            if ($id === $storedId) {
                $ret = true;
            }
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }

    /**
     * Verify if user with given $id exists and has specified $password
     *
     * @param string $id user identity URL
     * @param string $password user password
     * @return bool
     */
    public function checkUser($id, $password)
    {
        $name = $this->_dir . '/user_' . md5($id);
        $lock = @fopen($this->_dir . '/user.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_SH)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'r');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $ret = false;
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($storedId, $storedPassword, $trusted) = unserialize($data);
            if ($id === $storedId && $password === $storedPassword) {
                $ret = true;
            }
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }

    /**
     * Removes information abou specified user
     *
     * @param string $id user identity URL
     * @return bool
     */
    public function delUser($id)
    {
        $name = $this->_dir . '/user_' . md5($id);
        $lock = @fopen($this->_dir . '/user.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        @unlink($name);
        fclose($lock);
        return true;
    }

    /**
     * Returns array of all trusted/untrusted sites for given user identified
     * by $id
     *
     * @param string $id user identity URL
     * @return array
     */
    public function getTrustedSites($id)
    {
        $name = $this->_dir . '/user_' . md5($id);
        $lock = @fopen($this->_dir . '/user.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_SH)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'r');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $ret = false;
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($storedId, $storedPassword, $trusted) = unserialize($data);
            if ($id === $storedId) {
                $ret = $trusted;
            }
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }

    /**
     * Stores information about trusted/untrusted site for given user
     *
     * @param string $id user identity URL
     * @param string $site site URL
     * @param mixed $trusted trust data from extension or just a boolean value
     * @return bool
     */
    public function addSite($id, $site, $trusted)
    {
        $name = $this->_dir . '/user_' . md5($id);
        $lock = @fopen($this->_dir . '/user.lock', 'w+');
        if ($lock === false) {
            return false;
        }
        if (!flock($lock, LOCK_EX)) {
            fclose($lock);
            return false;
        }
        $f = @fopen($name, 'r+');
        if ($f === false) {
            fclose($lock);
            return false;
        }
        $ret = false;
        $data = stream_get_contents($f);
        if (!empty($data)) {
            list($storedId, $storedPassword, $sites) = unserialize($data);
            if ($id === $storedId) {
                if (is_null($trusted)) {
                    unset($sites[$site]);
                } else {
                    $sites[$site] = $trusted;
                }
                rewind($f);
                ftruncate($f, 0);
                $data = serialize(array($id, $storedPassword, $sites));
                fwrite($f, $data);
                $ret = true;
            }
        }
        fclose($f);
        fclose($lock);
        return $ret;
    }
}
Mail/Protocol/Smtp/Auth/Crammd5.php000066600000006307151256604600013073 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 * 
 * @category   Zend
 * @package    Zend_Mail
 * @subpackage Protocol
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Crammd5.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Mail_Protocol_Smtp
 */
require_once 'Zend/Mail/Protocol/Smtp.php';


/**
 * Performs CRAM-MD5 authentication
 *
 * @category   Zend
 * @package    Zend_Mail
 * @subpackage Protocol
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Mail_Protocol_Smtp_Auth_Crammd5 extends Zend_Mail_Protocol_Smtp
{
    /**
     * Constructor.
     *
     * @param  string $host   (Default: 127.0.0.1)
     * @param  int    $port   (Default: null)
     * @param  array  $config Auth-specific parameters
     * @return void
     */
    public function __construct($host = '127.0.0.1', $port = null, $config = null)
    {
        if (is_array($config)) {
            if (isset($config['username'])) {
                $this->_username = $config['username'];
            }
            if (isset($config['password'])) {
                $this->_password = $config['password'];
            }
        }

        parent::__construct($host, $port, $config);
    }


    /**
     * @todo Perform CRAM-MD5 authentication with supplied credentials
     *
     * @return void
     */
    public function auth()
    {
        // Ensure AUTH has not already been initiated.
        parent::auth();

        $this->_send('AUTH CRAM-MD5');
        $challenge = $this->_expect(334);
        $challenge = base64_decode($challenge);
        $digest = $this->_hmacMd5($this->_password, $challenge);
        $this->_send(base64_encode($this->_username . ' ' . $digest));
        $this->_expect(235);
        $this->_auth = true;
    }


    /**
     * Prepare CRAM-MD5 response to server's ticket
     *
     * @param  string $key   Challenge key (usually password)
     * @param  string $data  Challenge data
     * @param  string $block Length of blocks
     * @return string
     */
    protected function _hmacMd5($key, $data, $block = 64)
    {
        if (strlen($key) > 64) {
            $key = pack('H32', md5($key));
        } elseif (strlen($key) < 64) {
            $key = str_pad($key, $block, chr(0));
        }

        $k_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36), 64);
        $k_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64);

        $inner = pack('H32', md5($k_ipad . $data));
        $digest = md5($k_opad . $inner);

        return $digest;
    }
}
Mail/Protocol/Smtp/Auth/Login.php000066600000005072151256604600012651 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 * 
 * @category   Zend
 * @package    Zend_Mail
 * @subpackage Protocol
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Login.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Mail_Protocol_Smtp
 */
require_once 'Zend/Mail/Protocol/Smtp.php';


/**
 * Performs LOGIN authentication
 *
 * @category   Zend
 * @package    Zend_Mail
 * @subpackage Protocol
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Mail_Protocol_Smtp_Auth_Login extends Zend_Mail_Protocol_Smtp
{
    /**
     * LOGIN username
     *
     * @var string
     */
    protected $_username;


    /**
     * LOGIN password
     *
     * @var string
     */
    protected $_password;


    /**
     * Constructor.
     *
     * @param  string $host   (Default: 127.0.0.1)
     * @param  int    $port   (Default: null)
     * @param  array  $config Auth-specific parameters
     * @return void
     */
    public function __construct($host = '127.0.0.1', $port = null, $config = null)
    {
        if (is_array($config)) {
            if (isset($config['username'])) {
                $this->_username = $config['username'];
            }
            if (isset($config['password'])) {
                $this->_password = $config['password'];
            }
        }

        parent::__construct($host, $port, $config);
    }


    /**
     * Perform LOGIN authentication with supplied credentials
     *
     * @return void
     */
    public function auth()
    {
        // Ensure AUTH has not already been initiated.
        parent::auth();

        $this->_send('AUTH LOGIN');
        $this->_expect(334);
        $this->_send(base64_encode($this->_username));
        $this->_expect(334);
        $this->_send(base64_encode($this->_password));
        $this->_expect(235);
        $this->_auth = true;
    }
}
Mail/Protocol/Smtp/Auth/Plain.php000066600000005011151256604600012635 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 * 
 * @category   Zend
 * @package    Zend_Mail
 * @subpackage Protocol
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Plain.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Mail_Protocol_Smtp
 */
require_once 'Zend/Mail/Protocol/Smtp.php';


/**
 * Performs PLAIN authentication
 *
 * @category   Zend
 * @package    Zend_Mail
 * @subpackage Protocol
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Mail_Protocol_Smtp_Auth_Plain extends Zend_Mail_Protocol_Smtp
{
    /**
     * PLAIN username
     *
     * @var string
     */
    protected $_username;


    /**
     * PLAIN password
     *
     * @var string
     */
    protected $_password;


    /**
     * Constructor.
     *
     * @param  string $host   (Default: 127.0.0.1)
     * @param  int    $port   (Default: null)
     * @param  array  $config Auth-specific parameters
     * @return void
     */
    public function __construct($host = '127.0.0.1', $port = null, $config = null)
    {
        if (is_array($config)) {
            if (isset($config['username'])) {
                $this->_username = $config['username'];
            }
            if (isset($config['password'])) {
                $this->_password = $config['password'];
            }
        }

        parent::__construct($host, $port, $config);
    }


    /**
     * Perform PLAIN authentication with supplied credentials
     *
     * @return void
     */
    public function auth()
    {
        // Ensure AUTH has not already been initiated.
        parent::auth();

        $this->_send('AUTH PLAIN');
        $this->_expect(334);
        $this->_send(base64_encode(chr(0) . $this->_username . chr(0) . $this->_password));
        $this->_expect(235);
        $this->_auth = true;
    }
}
Mail/Storage/Writable/Interface.php000066600000007505151256604600013234 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 * 
 * @category   Zend
 * @package    Zend_Mail
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 9098 2008-03-30 19:29:10Z thomas $
 */


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

interface Zend_Mail_Storage_Writable_Interface
{
    /**
     * create a new folder
     *
     * This method also creates parent folders if necessary. Some mail storages may restrict, which folder
     * may be used as parent or which chars may be used in the folder name
     *
     * @param string                          $name         global name of folder, local name if $parentFolder is set
     * @param string|Zend_Mail_Storage_Folder $parentFolder parent folder for new folder, else root folder is parent
     * @return null
     * @throws Zend_Mail_Storage_Exception
     */
    public function createFolder($name, $parentFolder = null);

    /**
     * remove a folder
     *
     * @param string|Zend_Mail_Storage_Folder $name      name or instance of folder
     * @return null
     * @throws Zend_Mail_Storage_Exception
     */
    public function removeFolder($name);

    /**
     * rename and/or move folder
     *
     * The new name has the same restrictions as in createFolder()
     *
     * @param string|Zend_Mail_Storage_Folder $oldName name or instance of folder
     * @param string                          $newName new global name of folder
     * @return null
     * @throws Zend_Mail_Storage_Exception
     */
    public function renameFolder($oldName, $newName);

    /**
     * append a new message to mail storage
     *
     * @param  string|Zend_Mail_Message|Zend_Mime_Message $message message as string or instance of message class
     * @param  null|string|Zend_Mail_Storage_Folder       $folder  folder for new message, else current folder is taken
     * @param  null|array                                 $flags   set flags for new message, else a default set is used
     * @throws Zend_Mail_Storage_Exception
     */
    public function appendMessage($message, $folder = null, $flags = null);

    /**
     * copy an existing message
     *
     * @param  int                             $id     number of message
     * @param  string|Zend_Mail_Storage_Folder $folder name or instance of targer folder
     * @return null
     * @throws Zend_Mail_Storage_Exception
     */
    public function copyMessage($id, $folder);

    /**
     * move an existing message
     *
     * @param  int                             $id     number of message
     * @param  string|Zend_Mail_Storage_Folder $folder name or instance of targer folder
     * @return null
     * @throws Zend_Mail_Storage_Exception
     */
    public function moveMessage($id, $folder);

    /**
     * set flags for message
     *
     * NOTE: this method can't set the recent flag.
     *
     * @param  int   $id    number of message
     * @param  array $flags new flags for message
     * @throws Zend_Mail_Storage_Exception
     */
    public function setFlags($id, $flags);
}Ldap/Exception.php000066600000015602151256604600010110 0ustar00<?php

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

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

class Zend_Ldap_Exception extends Zend_Exception
{
    const LDAP_SUCCESS = 0x00;
    const LDAP_OPERATIONS_ERROR = 0x01;
    const LDAP_PROTOCOL_ERROR = 0x02;
    const LDAP_TIMELIMIT_EXCEEDED = 0x03;
    const LDAP_SIZELIMIT_EXCEEDED = 0x04;
    const LDAP_COMPARE_FALSE = 0x05;
    const LDAP_COMPARE_TRUE = 0x06;
    const LDAP_AUTH_METHOD_NOT_SUPPORTED = 0x07;
    const LDAP_STRONG_AUTH_REQUIRED = 0x08;
    const LDAP_PARTIAL_RESULTS = 0x09;
    const LDAP_REFERRAL = 0x0a;
    const LDAP_ADMINLIMIT_EXCEEDED = 0x0b;
    const LDAP_UNAVAILABLE_CRITICAL_EXTENSION = 0x0c;
    const LDAP_CONFIDENTIALITY_REQUIRED = 0x0d;
    const LDAP_SASL_BIND_IN_PROGRESS = 0x0e;
    const LDAP_NO_SUCH_ATTRIBUTE = 0x10;
    const LDAP_UNDEFINED_TYPE = 0x11;
    const LDAP_INAPPROPRIATE_MATCHING = 0x12;
    const LDAP_CONSTRAINT_VIOLATION = 0x13;
    const LDAP_TYPE_OR_VALUE_EXISTS = 0x14;
    const LDAP_INVALID_SYNTAX = 0x15;
    const LDAP_NO_SUCH_OBJECT = 0x20;
    const LDAP_ALIAS_PROBLEM = 0x21;
    const LDAP_INVALID_DN_SYNTAX = 0x22;
    const LDAP_IS_LEAF = 0x23;
    const LDAP_ALIAS_DEREF_PROBLEM = 0x24;
    const LDAP_PROXY_AUTHZ_FAILURE = 0x2F;
    const LDAP_INAPPROPRIATE_AUTH = 0x30;
    const LDAP_INVALID_CREDENTIALS = 0x31;
    const LDAP_INSUFFICIENT_ACCESS = 0x32;
    const LDAP_BUSY = 0x33;
    const LDAP_UNAVAILABLE = 0x34;
    const LDAP_UNWILLING_TO_PERFORM = 0x35;
    const LDAP_LOOP_DETECT = 0x36;
    const LDAP_NAMING_VIOLATION = 0x40;
    const LDAP_OBJECT_CLASS_VIOLATION = 0x41;
    const LDAP_NOT_ALLOWED_ON_NONLEAF = 0x42;
    const LDAP_NOT_ALLOWED_ON_RDN = 0x43;
    const LDAP_ALREADY_EXISTS = 0x44;
    const LDAP_NO_OBJECT_CLASS_MODS = 0x45;
    const LDAP_RESULTS_TOO_LARGE = 0x46;
    const LDAP_AFFECTS_MULTIPLE_DSAS = 0x47;
    const LDAP_OTHER = 0x50;
    const LDAP_SERVER_DOWN = 0x51;
    const LDAP_LOCAL_ERROR = 0x52;
    const LDAP_ENCODING_ERROR = 0x53;
    const LDAP_DECODING_ERROR = 0x54;
    const LDAP_TIMEOUT = 0x55;
    const LDAP_AUTH_UNKNOWN = 0x56;
    const LDAP_FILTER_ERROR = 0x57;
    const LDAP_USER_CANCELLED = 0x58;
    const LDAP_PARAM_ERROR = 0x59;
    const LDAP_NO_MEMORY = 0x5a;
    const LDAP_CONNECT_ERROR = 0x5b;
    const LDAP_NOT_SUPPORTED = 0x5c;
    const LDAP_CONTROL_NOT_FOUND = 0x5d;
    const LDAP_NO_RESULTS_RETURNED = 0x5e;
    const LDAP_MORE_RESULTS_TO_RETURN = 0x5f;
    const LDAP_CLIENT_LOOP = 0x60;
    const LDAP_REFERRAL_LIMIT_EXCEEDED = 0x61;
    const LDAP_CUP_RESOURCES_EXHAUSTED = 0x71;
    const LDAP_CUP_SECURITY_VIOLATION = 0x72;
    const LDAP_CUP_INVALID_DATA = 0x73;
    const LDAP_CUP_UNSUPPORTED_SCHEME = 0x74;
    const LDAP_CUP_RELOAD_REQUIRED = 0x75;
    const LDAP_CANCELLED = 0x76;
    const LDAP_NO_SUCH_OPERATION = 0x77;
    const LDAP_TOO_LATE = 0x78;
    const LDAP_CANNOT_CANCEL = 0x79;
    const LDAP_ASSERTION_FAILED = 0x7A;
    const LDAP_SYNC_REFRESH_REQUIRED = 0x1000;
    const LDAP_X_SYNC_REFRESH_REQUIRED = 0x4100;
    const LDAP_X_NO_OPERATION = 0x410e;
    const LDAP_X_ASSERTION_FAILED = 0x410f;
    const LDAP_X_NO_REFERRALS_FOUND = 0x4110;
    const LDAP_X_CANNOT_CHAIN = 0x4111;

    /* internal error code constants */

    const LDAP_X_DOMAIN_MISMATCH = 0x7001;

    /**
     * @param mixed $ldap A Zend_Ldap object or raw LDAP context resource
     * @param string $str An informtive exception message
     * @param int $code An LDAP error code
     */
    public function __construct($ldap = null, $str = null, $code = 0)
    {
        $resource = null;
        if (is_resource($ldap)) {
            $resource = $ldap;
        } else if (is_object($ldap)) {
            $resource = $ldap->getResource();
        }

        $message = '';
        if ($code === 0)
            $code = Zend_Ldap_Exception::getLdapCode($resource);
        if ($code)
            $message .= '0x' . dechex($code);
        if (is_resource($resource)) {

            /* The various error retrieval functions can return
             * different things so we just try to collect what we
             * can and eliminate dupes.
             */

            $estr1 = @ldap_error($resource);
            if ($code !== 0 && $estr1 === 'Success')
                $estr1 = @ldap_err2str($code);
            if ($estr1 !== $str)
                $this->_append($message, $estr1);

            @ldap_get_option($resource, LDAP_OPT_ERROR_STRING, $estr2);
            if ($estr2 !== $str && $estr2 !== $estr1)
                $this->_append($message, $estr2);
        }

        $this->_append($message, $str);

        parent::__construct($message, $code);
    }

    private function _append(&$message, $estr)
    {
        if ($estr) {
            if ($message)
                $message .= ': ';
            $message .= $estr;
        }
    }

    /**
     * @param mixed $ldap A Zend_Ldap object or raw LDAP context resource
     * @return int The current error code for the resource
     */
    public static function getLdapCode($ldap)
    {
        $resource = null;
        if (is_resource($ldap)) {
            $resource = $ldap;
        } else if (is_object($ldap)) {
            $resource = $ldap->getResource();
        }
        if (is_resource($resource)) {
            $ret = @ldap_get_option($resource, LDAP_OPT_ERROR_NUMBER, $err);
            if ($ret === true) {
                if ($err <= -1 && $err >= -17) {
                    /* For some reason draft-ietf-ldapext-ldap-c-api-xx.txt error
                     * codes in OpenLDAP are negative values from -1 to -17. 
                     */
                    $err = Zend_Ldap_Exception::LDAP_SERVER_DOWN + (-$err - 1);
                }
                return $err;
            }
        }
        return 0;
    }

    /**
     * @param string $message An informtive exception message
     *
     */
    public function setMessage($message)
    {
        $this->_message = $message;
    }

    /**
     * @return int The current error code for this exception
     */
    public function getErrorCode()
    {
        return $this->getCode();
    }
}
XmlRpc/Value/Exception.php000066600000002254151256604600011510 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_XmlRpc
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 9096 2008-03-30 19:04:05Z thomas $
 */


/**
 * Zend_XmlRpc_Exception
 */
require_once 'Zend/XmlRpc/Exception.php';


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

XmlRpc/Value/Integer.php000066600000003263151256604600011150 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_XmlRpc
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Integer.php 9095 2008-03-30 18:52:31Z thomas $
 */


/**
 * Zend_XmlRpc_Value_Scalar
 */
require_once 'Zend/XmlRpc/Value/Scalar.php';


/**
 * @category   Zend
 * @package    Zend_XmlRpc
 * @subpackage Value
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_XmlRpc_Value_Integer extends Zend_XmlRpc_Value_Scalar
{

    /**
     * Set the value of an integer native type
     *
     * @param int $value
     */
    public function __construct($value)
    {
        $this->_type = self::XMLRPC_TYPE_INTEGER;
        $this->_value = (int)$value;    // Make sure this value is integer
    }

    /**
     * Return the value of this object, convert the XML-RPC native integer value into a PHP integer
     *
     * @return int
     */
    public function getValue()
    {
        return $this->_value;
    }

}

XmlRpc/Response.php000066600000015031151256604600010271 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Zend_XmlRpc_Value
 */
require_once 'Zend/XmlRpc/Value.php';

/**
 * Zend_XmlRpc_Fault
 */
require_once 'Zend/XmlRpc/Fault.php';

/**
 * XmlRpc Response
 *
 * Container for accessing an XMLRPC return value and creating the XML response.
 *
 * @category Zend
 * @package  Zend_XmlRpc
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version $Id: Response.php 8064 2008-02-16 10:58:39Z thomas $
 */
class Zend_XmlRpc_Response
{
    /**
     * Return value
     * @var mixed
     */
    protected $_return;

    /**
     * Return type
     * @var string
     */
    protected $_type;

    /**
     * Response character encoding
     * @var string
     */
    protected $_encoding = 'UTF-8';

    /**
     * Fault, if response is a fault response
     * @var null|Zend_XmlRpc_Fault
     */
    protected $_fault = null;

    /**
     * Constructor
     *
     * Can optionally pass in the return value and type hinting; otherwise, the
     * return value can be set via {@link setReturnValue()}.
     *
     * @param mixed $return
     * @param string $type
     * @return void
     */
    public function __construct($return = null, $type = null)
    {
        $this->setReturnValue($return, $type);
    }

    /**
     * Set encoding to use in response
     *
     * @param string $encoding
     * @return Zend_XmlRpc_Response
     */
    public function setEncoding($encoding)
    {
        $this->_encoding = $encoding;
        return $this;
    }

    /**
     * Retrieve current response encoding
     *
     * @return string
     */
    public function getEncoding()
    {
        return $this->_encoding;
    }

    /**
     * Set the return value
     *
     * Sets the return value, with optional type hinting if provided.
     *
     * @param mixed $value
     * @param string $type
     * @return void
     */
    public function setReturnValue($value, $type = null)
    {
        $this->_return = $value;
        $this->_type = (string) $type;
    }

    /**
     * Retrieve the return value
     *
     * @return mixed
     */
    public function getReturnValue()
    {
        return $this->_return;
    }

    /**
     * Retrieve the XMLRPC value for the return value
     *
     * @return Zend_XmlRpc_Value
     */
    protected function _getXmlRpcReturn()
    {
        return Zend_XmlRpc_Value::getXmlRpcValue($this->_return);
    }

    /**
     * Is the response a fault response?
     *
     * @return boolean
     */
    public function isFault()
    {
        return $this->_fault instanceof Zend_XmlRpc_Fault;
    }

    /**
     * Returns the fault, if any.
     *
     * @return null|Zend_XmlRpc_Fault
     */
    public function getFault()
    {
        return $this->_fault;
    }

    /**
     * Load a response from an XML response
     *
     * Attempts to load a response from an XMLRPC response, autodetecting if it
     * is a fault response.
     *
     * @param string $response
     * @return boolean True if a valid XMLRPC response, false if a fault
     * response or invalid input
     */
    public function loadXml($response)
    {
        if (!is_string($response)) {
            $this->_fault = new Zend_XmlRpc_Fault(650);
            $this->_fault->setEncoding($this->getEncoding());
            return false;
        }

        try {
            $xml = @new SimpleXMLElement($response);
        } catch (Exception $e) {
            // Not valid XML
            $this->_fault = new Zend_XmlRpc_Fault(651);
            $this->_fault->setEncoding($this->getEncoding());
            return false;
        }

        if (!empty($xml->fault)) {
            // fault response
            $this->_fault = new Zend_XmlRpc_Fault();
            $this->_fault->setEncoding($this->getEncoding());
            $this->_fault->loadXml($response);
            return false;
        }

        if (empty($xml->params)) {
            // Invalid response
            $this->_fault = new Zend_XmlRpc_Fault(652);
            $this->_fault->setEncoding($this->getEncoding());
            return false;
        }

        try {
            if (!isset($xml->params) || !isset($xml->params->param) || !isset($xml->params->param->value)) {
                throw new Zend_XmlRpc_Value_Exception('Missing XML-RPC value in XML');
            }
            $valueXml = $xml->params->param->value->asXML();
            $valueXml = preg_replace('/<\?xml version=.*?\?>/i', '', $valueXml);
            $value = Zend_XmlRpc_Value::getXmlRpcValue(trim($valueXml), Zend_XmlRpc_Value::XML_STRING);
        } catch (Zend_XmlRpc_Value_Exception $e) {
            $this->_fault = new Zend_XmlRpc_Fault(653);
            $this->_fault->setEncoding($this->getEncoding());
            return false;
        }

        $this->setReturnValue($value->getValue());
        return true;
    }

    /**
     * Return response as XML
     *
     * @return string
     */
    public function saveXML()
    {
        $value = $this->_getXmlRpcReturn();
        $valueDOM = new DOMDocument('1.0', $this->getEncoding());
        $valueDOM->loadXML($value->saveXML());

        $dom      = new DOMDocument('1.0', $this->getEncoding());
        $response = $dom->appendChild($dom->createElement('methodResponse'));
        $params   = $response->appendChild($dom->createElement('params'));
        $param    = $params->appendChild($dom->createElement('param'));

        $param->appendChild($dom->importNode($valueDOM->documentElement, true));

        return $dom->saveXML();
    }

    /**
     * Return XML response
     *
     * @return string
     */
    public function __toString()
    {
        return $this->saveXML();
    }
}
Search/Lucene/Search/Weight/Term.php000066600000006174151256604600013261 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Weight */
require_once 'Zend/Search/Lucene/Search/Weight.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Weight_Term extends Zend_Search_Lucene_Search_Weight
{
    /**
     * IndexReader.
     *
     * @var Zend_Search_Lucene_Interface
     */
    private $_reader;

    /**
     * Term
     *
     * @var Zend_Search_Lucene_Index_Term
     */
    private $_term;

    /**
     * The query that this concerns.
     *
     * @var Zend_Search_Lucene_Search_Query
     */
    private $_query;

    /**
     * Score factor
     *
     * @var float
     */
    private $_idf;

    /**
     * Query weight
     *
     * @var float
     */
    private $_queryWeight;


    /**
     * Zend_Search_Lucene_Search_Weight_Term constructor
     * reader - index reader
     *
     * @param Zend_Search_Lucene_Index_Term   $term
     * @param Zend_Search_Lucene_Search_Query $query
     * @param Zend_Search_Lucene_Interface    $reader
     */
    public function __construct(Zend_Search_Lucene_Index_Term   $term,
                                Zend_Search_Lucene_Search_Query $query,
                                Zend_Search_Lucene_Interface    $reader)
    {
        $this->_term   = $term;
        $this->_query  = $query;
        $this->_reader = $reader;
    }


    /**
     * The sum of squared weights of contained query clauses.
     *
     * @return float
     */
    public function sumOfSquaredWeights()
    {
        // compute idf
        $this->_idf = $this->_reader->getSimilarity()->idf($this->_term, $this->_reader);

        // compute query weight
        $this->_queryWeight = $this->_idf * $this->_query->getBoost();

        // square it
        return $this->_queryWeight * $this->_queryWeight;
    }


    /**
     * Assigns the query normalization factor to this.
     *
     * @param float $queryNorm
     */
    public function normalize($queryNorm)
    {
        $this->_queryNorm = $queryNorm;

        // normalize query weight
        $this->_queryWeight *= $queryNorm;

        // idf for documents
        $this->_value = $this->_queryWeight * $this->_idf;
    }
}

Search/Lucene/Search/Weight/Empty.php000066600000003010151256604600013432 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Weight */
require_once 'Zend/Search/Lucene/Search/Weight.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Weight_Empty extends Zend_Search_Lucene_Search_Weight
{
    /**
     * The sum of squared weights of contained query clauses.
     *
     * @return float
     */
    public function sumOfSquaredWeights()
    {
        return 1;
    }


    /**
     * Assigns the query normalization factor to this.
     *
     * @param float $queryNorm
     */
    public function normalize($queryNorm)
    {
    }
}

Search/Lucene/Search/Weight/MultiTerm.php000066600000007157151256604600014276 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Weight */
require_once 'Zend/Search/Lucene/Search/Weight.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Weight_MultiTerm extends Zend_Search_Lucene_Search_Weight
{
    /**
     * IndexReader.
     *
     * @var Zend_Search_Lucene_Interface
     */
    private $_reader;

    /**
     * The query that this concerns.
     *
     * @var Zend_Search_Lucene_Search_Query
     */
    private $_query;

    /**
     * Query terms weights
     * Array of Zend_Search_Lucene_Search_Weight_Term
     *
     * @var array
     */
    private $_weights;


    /**
     * Zend_Search_Lucene_Search_Weight_MultiTerm constructor
     * query - the query that this concerns.
     * reader - index reader
     *
     * @param Zend_Search_Lucene_Search_Query $query
     * @param Zend_Search_Lucene_Interface    $reader
     */
    public function __construct(Zend_Search_Lucene_Search_Query $query,
                                Zend_Search_Lucene_Interface    $reader)
    {
        $this->_query   = $query;
        $this->_reader  = $reader;
        $this->_weights = array();

        $signs = $query->getSigns();

        foreach ($query->getTerms() as $id => $term) {
            if ($signs === null || $signs[$id] === null || $signs[$id]) {
                $this->_weights[$id] = new Zend_Search_Lucene_Search_Weight_Term($term, $query, $reader);
                $query->setWeight($id, $this->_weights[$id]);
            }
        }
    }


    /**
     * The weight for this query
     * Standard Weight::$_value is not used for boolean queries
     *
     * @return float
     */
    public function getValue()
    {
        return $this->_query->getBoost();
    }


    /**
     * The sum of squared weights of contained query clauses.
     *
     * @return float
     */
    public function sumOfSquaredWeights()
    {
        $sum = 0;
        foreach ($this->_weights as $weight) {
            // sum sub weights
            $sum += $weight->sumOfSquaredWeights();
        }

        // boost each sub-weight
        $sum *= $this->_query->getBoost() * $this->_query->getBoost();

        // check for empty query (like '-something -another')
        if ($sum == 0) {
            $sum = 1.0;
        }
        return $sum;
    }


    /**
     * Assigns the query normalization factor to this.
     *
     * @param float $queryNorm
     */
    public function normalize($queryNorm)
    {
        // incorporate boost
        $queryNorm *= $this->_query->getBoost();

        foreach ($this->_weights as $weight) {
            $weight->normalize($queryNorm);
        }
    }
}


Search/Lucene/Search/Weight/Boolean.php000066600000007017151256604600013726 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Weight */
require_once 'Zend/Search/Lucene/Search/Weight.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Weight_Boolean extends Zend_Search_Lucene_Search_Weight
{
    /**
     * IndexReader.
     *
     * @var Zend_Search_Lucene_Interface
     */
    private $_reader;

    /**
     * The query that this concerns.
     *
     * @var Zend_Search_Lucene_Search_Query
     */
    private $_query;

    /**
     * Queries weights
     * Array of Zend_Search_Lucene_Search_Weight
     *
     * @var array
     */
    private $_weights;


    /**
     * Zend_Search_Lucene_Search_Weight_Boolean constructor
     * query - the query that this concerns.
     * reader - index reader
     *
     * @param Zend_Search_Lucene_Search_Query $query
     * @param Zend_Search_Lucene_Interface    $reader
     */
    public function __construct(Zend_Search_Lucene_Search_Query $query,
                                Zend_Search_Lucene_Interface    $reader)
    {
        $this->_query   = $query;
        $this->_reader  = $reader;
        $this->_weights = array();

        $signs = $query->getSigns();

        foreach ($query->getSubqueries() as $num => $subquery) {
            if ($signs === null || $signs[$num] === null || $signs[$num]) {
                $this->_weights[$num] = $subquery->createWeight($reader);
            }
        }
    }


    /**
     * The weight for this query
     * Standard Weight::$_value is not used for boolean queries
     *
     * @return float
     */
    public function getValue()
    {
        return $this->_query->getBoost();
    }


    /**
     * The sum of squared weights of contained query clauses.
     *
     * @return float
     */
    public function sumOfSquaredWeights()
    {
        $sum = 0;
        foreach ($this->_weights as $weight) {
            // sum sub weights
            $sum += $weight->sumOfSquaredWeights();
        }

        // boost each sub-weight
        $sum *= $this->_query->getBoost() * $this->_query->getBoost();

        // check for empty query (like '-something -another')
        if ($sum == 0) {
            $sum = 1.0;
        }
        return $sum;
    }


    /**
     * Assigns the query normalization factor to this.
     *
     * @param float $queryNorm
     */
    public function normalize($queryNorm)
    {
        // incorporate boost
        $queryNorm *= $this->_query->getBoost();

        foreach ($this->_weights as $weight) {
            $weight->normalize($queryNorm);
        }
    }
}


Search/Lucene/Search/Weight/Phrase.php000066600000005457151256604600013577 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * Zend_Search_Lucene_Search_Weight
 */
require_once 'Zend/Search/Lucene/Search/Weight.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Weight_Phrase extends Zend_Search_Lucene_Search_Weight
{
    /**
     * IndexReader.
     *
     * @var Zend_Search_Lucene_Interface
     */
    private $_reader;

    /**
     * The query that this concerns.
     *
     * @var Zend_Search_Lucene_Search_Query_Phrase
     */
    private $_query;

    /**
     * Score factor
     *
     * @var float
     */
    private $_idf;

    /**
     * Zend_Search_Lucene_Search_Weight_Phrase constructor
     *
     * @param Zend_Search_Lucene_Search_Query_Phrase $query
     * @param Zend_Search_Lucene_Interface           $reader
     */
    public function __construct(Zend_Search_Lucene_Search_Query_Phrase $query,
                                Zend_Search_Lucene_Interface           $reader)
    {
        $this->_query  = $query;
        $this->_reader = $reader;
    }

    /**
     * The sum of squared weights of contained query clauses.
     *
     * @return float
     */
    public function sumOfSquaredWeights()
    {
        // compute idf
        $this->_idf = $this->_reader->getSimilarity()->idf($this->_query->getTerms(), $this->_reader);

        // compute query weight
        $this->_queryWeight = $this->_idf * $this->_query->getBoost();

        // square it
        return $this->_queryWeight * $this->_queryWeight;
    }


    /**
     * Assigns the query normalization factor to this.
     *
     * @param float $queryNorm
     */
    public function normalize($queryNorm)
    {
        $this->_queryNorm = $queryNorm;

        // normalize query weight
        $this->_queryWeight *= $queryNorm;

        // idf for documents
        $this->_value = $this->_queryWeight * $this->_idf;
    }
}


Search/Lucene/Search/Similarity/Default.php000066600000005312151256604600014626 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Similarity */
require_once 'Zend/Search/Lucene/Search/Similarity.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Similarity_Default extends Zend_Search_Lucene_Search_Similarity
{

    /**
     * Implemented as '1/sqrt(numTerms)'.
     *
     * @param string $fieldName
     * @param integer $numTerms
     * @return float
     */
    public function lengthNorm($fieldName, $numTerms)
    {
        if ($numTerms == 0) {
            return 1E10;
        }

        return 1.0/sqrt($numTerms);
    }

    /**
     * Implemented as '1/sqrt(sumOfSquaredWeights)'.
     *
     * @param float $sumOfSquaredWeights
     * @return float
     */
    public function queryNorm($sumOfSquaredWeights)
    {
        return 1.0/sqrt($sumOfSquaredWeights);
    }

    /**
     * Implemented as 'sqrt(freq)'.
     *
     * @param float $freq
     * @return float
     */
    public function tf($freq)
    {
        return sqrt($freq);
    }

    /**
     * Implemented as '1/(distance + 1)'.
     *
     * @param integer $distance
     * @return float
     */
    public function sloppyFreq($distance)
    {
        return 1.0/($distance + 1);
    }

    /**
     * Implemented as 'log(numDocs/(docFreq+1)) + 1'.
     *
     * @param integer $docFreq
     * @param integer $numDocs
     * @return float
     */
    public function idfFreq($docFreq, $numDocs)
    {
        return log($numDocs/(float)($docFreq+1)) + 1.0;
    }

    /**
     * Implemented as 'overlap/maxOverlap'.
     *
     * @param integer $overlap
     * @param integer $maxOverlap
     * @return float
     */
    public function coord($overlap, $maxOverlap)
    {
        return $overlap/(float)$maxOverlap;
    }
}
Search/Lucene/Search/QueryParserContext.php000066600000033033151256604600014744 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_FSM */
require_once 'Zend/Search/Lucene/FSM.php';

/** Zend_Search_Lucene_Index_Term */
require_once 'Zend/Search/Lucene/Index/Term.php';

/** Zend_Search_Lucene_Search_QueryToken */
require_once 'Zend/Search/Lucene/Search/QueryToken.php';

/** Zend_Search_Lucene_Search_Query_Term */
require_once 'Zend/Search/Lucene/Search/Query/Term.php';

/** Zend_Search_Lucene_Search_Query_MultiTerm */
require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';

/** Zend_Search_Lucene_Search_Query_Boolean */
require_once 'Zend/Search/Lucene/Search/Query/Boolean.php';

/** Zend_Search_Lucene_Search_Query_Phrase */
require_once 'Zend/Search/Lucene/Search/Query/Phrase.php';

/** Zend_Search_Lucene_Search_BooleanExpressionRecognizer */
require_once 'Zend/Search/Lucene/Search/BooleanExpressionRecognizer.php';

/** Zend_Search_Lucene_Search_QueryEntry */
require_once 'Zend/Search/Lucene/Search/QueryEntry.php';

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_QueryParserContext
{
    /**
     * Default field for the context.
     *
     * null means, that term should be searched through all fields
     * Zend_Search_Lucene_Search_Query::rewriteQuery($index) transletes such queries to several
     *
     * @var string|null
     */
    private $_defaultField;

    /**
     * Field specified for next entry
     *
     * @var string
     */
    private $_nextEntryField = null;

    /**
     * True means, that term is required.
     * False means, that term is prohibited.
     * null means, that term is neither prohibited, nor required
     *
     * @var boolean
     */
    private $_nextEntrySign = null;


    /**
     * Entries grouping mode
     */
    const GM_SIGNS   = 0;  // Signs mode: '+term1 term2 -term3 +(subquery1) -(subquery2)'
    const GM_BOOLEAN = 1;  // Boolean operators mode: 'term1 and term2  or  (subquery1) and not (subquery2)'

    /**
     * Grouping mode
     *
     * @var integer
     */
    private $_mode = null;

    /**
     * Entries signs.
     * Used in GM_SIGNS grouping mode
     *
     * @var arrays
     */
    private $_signs = array();

    /**
     * Query entries
     * Each entry is a Zend_Search_Lucene_Search_QueryEntry object or
     * boolean operator (Zend_Search_Lucene_Search_QueryToken class constant)
     *
     * @var array
     */
    private $_entries = array();

    /**
     * Query string encoding
     *
     * @var string
     */
    private $_encoding;


    /**
     * Context object constructor
     *
     * @param string $encoding
     * @param string|null $defaultField
     */
    public function __construct($encoding, $defaultField = null)
    {
        $this->_encoding     = $encoding;
        $this->_defaultField = $defaultField;
    }


    /**
     * Get context default field
     *
     * @return string|null
     */
    public function getField()
    {
        return ($this->_nextEntryField !== null)  ?  $this->_nextEntryField : $this->_defaultField;
    }

    /**
     * Set field for next entry
     *
     * @param string $field
     */
    public function setNextEntryField($field)
    {
        $this->_nextEntryField = $field;
    }


    /**
     * Set sign for next entry
     *
     * @param integer $sign
     * @throws Zend_Search_Lucene_Exception
     */
    public function setNextEntrySign($sign)
    {
        if ($this->_mode === self::GM_BOOLEAN) {
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('It\'s not allowed to mix boolean and signs styles in the same subquery.');
        }

        $this->_mode = self::GM_SIGNS;

        if ($sign == Zend_Search_Lucene_Search_QueryToken::TT_REQUIRED) {
            $this->_nextEntrySign = true;
        } else if ($sign == Zend_Search_Lucene_Search_QueryToken::TT_PROHIBITED) {
            $this->_nextEntrySign = false;
        } else {
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Unrecognized sign type.');
        }
    }


    /**
     * Add entry to a query
     *
     * @param Zend_Search_Lucene_Search_QueryEntry $entry
     */
    public function addEntry(Zend_Search_Lucene_Search_QueryEntry $entry)
    {
        if ($this->_mode !== self::GM_BOOLEAN) {
            $this->_signs[] = $this->_nextEntrySign;
        }

        $this->_entries[] = $entry;

        $this->_nextEntryField = null;
        $this->_nextEntrySign  = null;
    }


    /**
     * Process fuzzy search or proximity search modifier
     *
     * @throws Zend_Search_Lucene_Search_QueryParserException
     */
    public function processFuzzyProximityModifier($parameter = null)
    {
        // Check, that modifier has came just after word or phrase
        if ($this->_nextEntryField !== null  ||  $this->_nextEntrySign !== null) {
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('\'~\' modifier must follow word or phrase.');
        }

        $lastEntry = array_pop($this->_entries);

        if (!$lastEntry instanceof Zend_Search_Lucene_Search_QueryEntry) {
            // there are no entries or last entry is boolean operator
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('\'~\' modifier must follow word or phrase.');
        }

        $lastEntry->processFuzzyProximityModifier($parameter);

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

    /**
     * Set boost factor to the entry
     *
     * @param float $boostFactor
     */
    public function boost($boostFactor)
    {
        // Check, that modifier has came just after word or phrase
        if ($this->_nextEntryField !== null  ||  $this->_nextEntrySign !== null) {
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('\'^\' modifier must follow word, phrase or subquery.');
        }

        $lastEntry = array_pop($this->_entries);

        if (!$lastEntry instanceof Zend_Search_Lucene_Search_QueryEntry) {
            // there are no entries or last entry is boolean operator
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('\'^\' modifier must follow word, phrase or subquery.');
        }

        $lastEntry->boost($boostFactor);

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

    /**
     * Process logical operator
     *
     * @param integer $operator
     */
    public function addLogicalOperator($operator)
    {
        if ($this->_mode === self::GM_SIGNS) {
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('It\'s not allowed to mix boolean and signs styles in the same subquery.');
        }

        $this->_mode = self::GM_BOOLEAN;

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


    /**
     * Generate 'signs style' query from the context
     * '+term1 term2 -term3 +(<subquery1>) ...'
     *
     * @return Zend_Search_Lucene_Search_Query
     */
    public function _signStyleExpressionQuery()
    {
        $query = new Zend_Search_Lucene_Search_Query_Boolean();

        if (Zend_Search_Lucene_Search_QueryParser::getDefaultOperator() == Zend_Search_Lucene_Search_QueryParser::B_AND) {
            $defaultSign = true; // required
        } else {
            // Zend_Search_Lucene_Search_QueryParser::B_OR
            $defaultSign = null; // optional
        }

        foreach ($this->_entries as $entryId => $entry) {
            $sign = ($this->_signs[$entryId] !== null) ?  $this->_signs[$entryId] : $defaultSign;
            $query->addSubquery($entry->getQuery($this->_encoding), $sign);
        }

        return $query;
    }


    /**
     * Generate 'boolean style' query from the context
     * 'term1 and term2   or   term3 and (<subquery1>) and not (<subquery2>)'
     *
     * @return Zend_Search_Lucene_Search_Query
     * @throws Zend_Search_Lucene
     */
    private function _booleanExpressionQuery()
    {
        /**
         * We treat each level of an expression as a boolean expression in
         * a Disjunctive Normal Form
         *
         * AND operator has higher precedence than OR
         *
         * Thus logical query is a disjunction of one or more conjunctions of
         * one or more query entries
         */

        $expressionRecognizer = new Zend_Search_Lucene_Search_BooleanExpressionRecognizer();

        require_once 'Zend/Search/Lucene/Exception.php';
        try {
            foreach ($this->_entries as $entry) {
                if ($entry instanceof Zend_Search_Lucene_Search_QueryEntry) {
                    $expressionRecognizer->processLiteral($entry);
                } else {
                    switch ($entry) {
                        case Zend_Search_Lucene_Search_QueryToken::TT_AND_LEXEME:
                            $expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_AND_OPERATOR);
                            break;

                        case Zend_Search_Lucene_Search_QueryToken::TT_OR_LEXEME:
                            $expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_OR_OPERATOR);
                            break;

                        case Zend_Search_Lucene_Search_QueryToken::TT_NOT_LEXEME:
                            $expressionRecognizer->processOperator(Zend_Search_Lucene_Search_BooleanExpressionRecognizer::IN_NOT_OPERATOR);
                            break;

                        default:
                            throw new Zend_Search_Lucene('Boolean expression error. Unknown operator type.');
                    }
                }
            }

            $conjuctions = $expressionRecognizer->finishExpression();
        } catch (Zend_Search_Exception $e) {
            // throw new Zend_Search_Lucene_Search_QueryParserException('Boolean expression error. Error message: \'' .
            //                                                          $e->getMessage() . '\'.' );
            // It's query syntax error message and it should be user friendly. So FSM message is omitted
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('Boolean expression error.');
        }

        // Remove 'only negative' conjunctions
        foreach ($conjuctions as $conjuctionId => $conjuction) {
            $nonNegativeEntryFound = false;

            foreach ($conjuction as $conjuctionEntry) {
                if ($conjuctionEntry[1]) {
                    $nonNegativeEntryFound = true;
                    break;
                }
            }

            if (!$nonNegativeEntryFound) {
                unset($conjuctions[$conjuctionId]);
            }
        }


        $subqueries = array();
        foreach ($conjuctions as  $conjuction) {
            // Check, if it's a one term conjuction
            if (count($conjuction) == 1) {
                $subqueries[] = $conjuction[0][0]->getQuery($this->_encoding);
            } else {
                $subquery = new Zend_Search_Lucene_Search_Query_Boolean();

                foreach ($conjuction as $conjuctionEntry) {
                    $subquery->addSubquery($conjuctionEntry[0]->getQuery($this->_encoding), $conjuctionEntry[1]);
                }

                $subqueries[] = $subquery;
            }
        }

        if (count($subqueries) == 0) {
            return new Zend_Search_Lucene_Search_Query_Insignificant();
        }

        if (count($subqueries) == 1) {
            return $subqueries[0];
        }


        $query = new Zend_Search_Lucene_Search_Query_Boolean();

        foreach ($subqueries as $subquery) {
            // Non-requirered entry/subquery
            $query->addSubquery($subquery);
        }

        return $query;
    }

    /**
     * Generate query from current context
     *
     * @return Zend_Search_Lucene_Search_Query
     */
    public function getQuery()
    {
        if ($this->_mode === self::GM_BOOLEAN) {
            return $this->_booleanExpressionQuery();
        } else {
            return $this->_signStyleExpressionQuery();
        }
    }
}
Search/Lucene/Search/QueryParserException.php000066600000002363151256604600015260 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * Zend_Search_Lucene base exception
 */
require_once 'Zend/Search/Lucene/Exception.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 *
 * Special exception type, which may be used to intercept wrong user input
 */
class Zend_Search_Lucene_Search_QueryParserException extends Zend_Search_Lucene_Exception
{}

Search/Lucene/Search/Query/Empty.php000066600000007334151256604600013325 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';

/** Zend_Search_Lucene_Search_Weight_Empty */
require_once 'Zend/Search/Lucene/Search/Weight/Empty.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_Empty extends Zend_Search_Lucene_Search_Query
{
    /**
     * Re-write query into primitive queries in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        return $this;
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        // "Empty" query is a primitive query and don't need to be optimized
        return $this;
    }

    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        return new Zend_Search_Lucene_Search_Weight_Empty();
    }

    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        // Do nothing
    }

    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     */
    public function matchedDocs()
    {
        return array();
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        return 0;
    }

    /**
     * Return query terms
     *
     * @return array
     */
    public function getQueryTerms()
    {
        return array();
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        // Do nothing
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        return '<EmptyQuery>';
    }
}

Search/Lucene/Search/Query/MultiTerm.php000066600000047532151256604600014155 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';

/** Zend_Search_Lucene_Search_Weight_MultiTerm */
require_once 'Zend/Search/Lucene/Search/Weight/MultiTerm.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_MultiTerm extends Zend_Search_Lucene_Search_Query
{

    /**
     * Terms to find.
     * Array of Zend_Search_Lucene_Index_Term
     *
     * @var array
     */
    private $_terms = array();

    /**
     * Term signs.
     * If true then term is required.
     * If false then term is prohibited.
     * If null then term is neither prohibited, nor required
     *
     * If array is null then all terms are required
     *
     * @var array
     */
    private $_signs;

    /**
     * Result vector.
     *
     * @var array
     */
    private $_resVector = null;

    /**
     * Terms positions vectors.
     * Array of Arrays:
     * term1Id => (docId => freq, ...)
     * term2Id => (docId => freq, ...)
     *
     * @var array
     */
    private $_termsFreqs = array();


    /**
     * A score factor based on the fraction of all query terms
     * that a document contains.
     * float for conjunction queries
     * array of float for non conjunction queries
     *
     * @var mixed
     */
    private $_coord = null;


    /**
     * Terms weights
     * array of Zend_Search_Lucene_Search_Weight
     *
     * @var array
     */
    private $_weights = array();


    /**
     * Class constructor.  Create a new multi-term query object.
     *
     * if $signs array is omitted then all terms are required
     * it differs from addTerm() behavior, but should never be used
     *
     * @param array $terms    Array of Zend_Search_Lucene_Index_Term objects
     * @param array $signs    Array of signs.  Sign is boolean|null.
     * @throws Zend_Search_Lucene_Exception
     */
    public function __construct($terms = null, $signs = null)
    {
        if (is_array($terms)) {
            if (count($terms) > Zend_search_lucene::getTermsPerQueryLimit()) {
                throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
            }

            $this->_terms = $terms;

            $this->_signs = null;
            // Check if all terms are required
            if (is_array($signs)) {
                foreach ($signs as $sign ) {
                    if ($sign !== true) {
                        $this->_signs = $signs;
                        break;
                    }
                }
            }
        }
    }


    /**
     * Add a $term (Zend_Search_Lucene_Index_Term) to this query.
     *
     * The sign is specified as:
     *     TRUE  - term is required
     *     FALSE - term is prohibited
     *     NULL  - term is neither prohibited, nor required
     *
     * @param  Zend_Search_Lucene_Index_Term $term
     * @param  boolean|null $sign
     * @return void
     */
    public function addTerm(Zend_Search_Lucene_Index_Term $term, $sign = null) {
        if ($sign !== true || $this->_signs !== null) {       // Skip, if all terms are required
            if ($this->_signs === null) {                     // Check, If all previous terms are required
                $this->_signs = array();
                foreach ($this->_terms as $prevTerm) {
                    $this->_signs[] = true;
                }
            }
            $this->_signs[] = $sign;
        }

        $this->_terms[] = $term;
    }


    /**
     * Re-write query into primitive queries in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        if (count($this->_terms) == 0) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        }

        // Check, that all fields are qualified
        $allQualified = true;
        foreach ($this->_terms as $term) {
            if ($term->field === null) {
                $allQualified = false;
                break;
            }
        }

        if ($allQualified) {
            return $this;
        } else {
            /** transform multiterm query to boolean and apply rewrite() method to subqueries. */
            $query = new Zend_Search_Lucene_Search_Query_Boolean();
            $query->setBoost($this->getBoost());

            foreach ($this->_terms as $termId => $term) {
                $subquery = new Zend_Search_Lucene_Search_Query_Term($term);

                $query->addSubquery($subquery->rewrite($index),
                                    ($this->_signs === null)?  true : $this->_signs[$termId]);
            }

            return $query;
        }
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        $terms = $this->_terms;
        $signs = $this->_signs;

        foreach ($terms as $id => $term) {
            if (!$index->hasTerm($term)) {
                if ($signs === null  ||  $signs[$id] === true) {
                    // Term is required
                    return new Zend_Search_Lucene_Search_Query_Empty();
                } else {
                    // Term is optional or prohibited
                    // Remove it from terms and signs list
                    unset($terms[$id]);
                    unset($signs[$id]);
                }
            }
        }

        // Check if all presented terms are prohibited
        $allProhibited = true;
        if ($signs === null) {
            $allProhibited = false;
        } else {
            foreach ($signs as $sign) {
                if ($sign !== false) {
                    $allProhibited = false;
                    break;
                }
            }
        }
        if ($allProhibited) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        }

        /**
         * @todo make an optimization for repeated terms
         * (they may have different signs)
         */

        if (count($terms) == 1) {
            // It's already checked, that it's not a prohibited term

            // It's one term query with one required or optional element
            $optimizedQuery = new Zend_Search_Lucene_Search_Query_Term(reset($terms));
            $optimizedQuery->setBoost($this->getBoost());

            return $optimizedQuery;
        }

        if (count($terms) == 0) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        }

        $optimizedQuery = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $signs);
        $optimizedQuery->setBoost($this->getBoost());
        return $optimizedQuery;
    }


    /**
     * Returns query term
     *
     * @return array
     */
    public function getTerms()
    {
        return $this->_terms;
    }


    /**
     * Return terms signs
     *
     * @return array
     */
    public function getSigns()
    {
        return $this->_signs;
    }


    /**
     * Set weight for specified term
     *
     * @param integer $num
     * @param Zend_Search_Lucene_Search_Weight_Term $weight
     */
    public function setWeight($num, $weight)
    {
        $this->_weights[$num] = $weight;
    }


    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        $this->_weight = new Zend_Search_Lucene_Search_Weight_MultiTerm($this, $reader);
        return $this->_weight;
    }


    /**
     * Calculate result vector for Conjunction query
     * (like '+something +another')
     *
     * @param Zend_Search_Lucene_Interface $reader
     */
    private function _calculateConjunctionResult(Zend_Search_Lucene_Interface $reader)
    {
        $this->_resVector = null;

        if (count($this->_terms) == 0) {
            $this->_resVector = array();
        }

        // Order terms by selectivity
        $docFreqs = array();
        $ids      = array();
        foreach ($this->_terms as $id => $term) {
            $docFreqs[] = $reader->docFreq($term);
            $ids[]      = $id; // Used to keep original order for terms with the same selectivity and omit terms comparison
        }
        array_multisort($docFreqs, SORT_ASC, SORT_NUMERIC,
                        $ids,      SORT_ASC, SORT_NUMERIC,
                        $this->_terms);

        $docsFilter = new Zend_Search_Lucene_Index_DocsFilter();
        foreach ($this->_terms as $termId => $term) {
            $termDocs = $reader->termDocs($term, $docsFilter);
        }
        // Treat last retrieved docs vector as a result set
        // (filter collects data for other terms)
        $this->_resVector = array_flip($termDocs);

        foreach ($this->_terms as $termId => $term) {
            $this->_termsFreqs[$termId] = $reader->termFreqs($term, $docsFilter);
        }

        // ksort($this->_resVector, SORT_NUMERIC);
        // Docs are returned ordered. Used algorithms doesn't change elements order.
    }


    /**
     * Calculate result vector for non Conjunction query
     * (like '+something -another')
     *
     * @param Zend_Search_Lucene_Interface $reader
     */
    private function _calculateNonConjunctionResult(Zend_Search_Lucene_Interface $reader)
    {
        $requiredVectors      = array();
        $requiredVectorsSizes = array();
        $requiredVectorsIds   = array(); // is used to prevent arrays comparison

        $optional   = array();
        $prohibited = array();

        foreach ($this->_terms as $termId => $term) {
            $termDocs = array_flip($reader->termDocs($term));

            if ($this->_signs[$termId] === true) {
                // required
                $requiredVectors[]      = $termDocs;
                $requiredVectorsSizes[] = count($termDocs);
                $requiredVectorsIds[]   = $termId;
            } elseif ($this->_signs[$termId] === false) {
                // prohibited
                // array union
                $prohibited += $termDocs;
            } else {
                // neither required, nor prohibited
                // array union
                $optional += $termDocs;
            }

            $this->_termsFreqs[$termId] = $reader->termFreqs($term);
        }

        // sort resvectors in order of subquery cardinality increasing
        array_multisort($requiredVectorsSizes, SORT_ASC, SORT_NUMERIC,
                        $requiredVectorsIds,   SORT_ASC, SORT_NUMERIC,
                        $requiredVectors);

        $required = null;
        foreach ($requiredVectors as $nextResVector) {
            if($required === null) {
                $required = $nextResVector;
            } else {
                //$required = array_intersect_key($required, $nextResVector);

                /**
                 * This code is used as workaround for array_intersect_key() slowness problem.
                 */
                $updatedVector = array();
                foreach ($required as $id => $value) {
                    if (isset($nextResVector[$id])) {
                        $updatedVector[$id] = $value;
                    }
                }
                $required = $updatedVector;
            }

            if (count($required) == 0) {
                // Empty result set, we don't need to check other terms
                break;
            }
        }

        if ($required !== null) {
            $this->_resVector = $required;
        } else {
            $this->_resVector = $optional;
        }

        if (count($prohibited) != 0) {
            // $this->_resVector = array_diff_key($this->_resVector, $prohibited);

            /**
             * This code is used as workaround for array_diff_key() slowness problem.
             */
            if (count($this->_resVector) < count($prohibited)) {
                $updatedVector = $this->_resVector;
                foreach ($this->_resVector as $id => $value) {
                    if (isset($prohibited[$id])) {
                        unset($updatedVector[$id]);
                    }
                }
                $this->_resVector = $updatedVector;
            } else {
                $updatedVector = $this->_resVector;
                foreach ($prohibited as $id => $value) {
                    unset($updatedVector[$id]);
                }
                $this->_resVector = $updatedVector;
            }
        }

        ksort($this->_resVector, SORT_NUMERIC);
    }


    /**
     * Score calculator for conjunction queries (all terms are required)
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function _conjunctionScore($docId, Zend_Search_Lucene_Interface $reader)
    {
        if ($this->_coord === null) {
            $this->_coord = $reader->getSimilarity()->coord(count($this->_terms),
                                                            count($this->_terms) );
        }

        $score = 0.0;

        foreach ($this->_terms as $termId => $term) {
            /**
             * We don't need to check that term freq is not 0
             * Score calculation is performed only for matched docs
             */
            $score += $reader->getSimilarity()->tf($this->_termsFreqs[$termId][$docId]) *
                      $this->_weights[$termId]->getValue() *
                      $reader->norm($docId, $term->field);
        }

        return $score * $this->_coord * $this->getBoost();
    }


    /**
     * Score calculator for non conjunction queries (not all terms are required)
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function _nonConjunctionScore($docId, $reader)
    {
        if ($this->_coord === null) {
            $this->_coord = array();

            $maxCoord = 0;
            foreach ($this->_signs as $sign) {
                if ($sign !== false /* not prohibited */) {
                    $maxCoord++;
                }
            }

            for ($count = 0; $count <= $maxCoord; $count++) {
                $this->_coord[$count] = $reader->getSimilarity()->coord($count, $maxCoord);
            }
        }

        $score = 0.0;
        $matchedTerms = 0;
        foreach ($this->_terms as $termId=>$term) {
            // Check if term is
            if ($this->_signs[$termId] !== false &&        // not prohibited
                isset($this->_termsFreqs[$termId][$docId]) // matched
               ) {
                $matchedTerms++;

                /**
                 * We don't need to check that term freq is not 0
                 * Score calculation is performed only for matched docs
                 */
                $score +=
                      $reader->getSimilarity()->tf($this->_termsFreqs[$termId][$docId]) *
                      $this->_weights[$termId]->getValue() *
                      $reader->norm($docId, $term->field);
            }
        }

        return $score * $this->_coord[$matchedTerms] * $this->getBoost();
    }

    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        if ($this->_signs === null) {
            $this->_calculateConjunctionResult($reader);
        } else {
            $this->_calculateNonConjunctionResult($reader);
        }

        // Initialize weight if it's not done yet
        $this->_initWeight($reader);
    }

    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     */
    public function matchedDocs()
    {
        return $this->_resVector;
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        if (isset($this->_resVector[$docId])) {
            if ($this->_signs === null) {
                return $this->_conjunctionScore($docId, $reader);
            } else {
                return $this->_nonConjunctionScore($docId, $reader);
            }
        } else {
            return 0;
        }
    }

    /**
     * Return query terms
     *
     * @return array
     */
    public function getQueryTerms()
    {
        if ($this->_signs === null) {
            return $this->_terms;
        }

        $terms = array();

        foreach ($this->_signs as $id => $sign) {
            if ($sign !== false) {
                $terms[] = $this->_terms[$id];
            }
        }

        return $terms;
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        $words = array();

        if ($this->_signs === null) {
            foreach ($this->_terms as $term) {
                $words[] = $term->text;
            }
        } else {
            foreach ($this->_signs as $id => $sign) {
                if ($sign !== false) {
                    $words[] = $this->_terms[$id]->text;
                }
            }
        }

        $doc->highlight($words, $this->_getHighlightColor($colorIndex));
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        // It's used only for query visualisation, so we don't care about characters escaping

        $query = '';

        foreach ($this->_terms as $id => $term) {
            if ($id != 0) {
                $query .= ' ';
            }

            if ($this->_signs === null || $this->_signs[$id] === true) {
                $query .= '+';
            } else if ($this->_signs[$id] === false) {
                $query .= '-';
            }

            if ($term->field !== null) {
                $query .= $term->field . ':';
            }
            $query .= $term->text;
        }

        if ($this->getBoost() != 1) {
            $query = '(' . $query . ')^' . $this->getBoost();
        }

        return $query;
    }
}

Search/Lucene/Search/Query/Range.php000066600000024544151256604600013265 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';

/** Zend_Search_Lucene_Search_Query_MultiTerm */
require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_Range extends Zend_Search_Lucene_Search_Query
{
    /**
     * Lower term.
     *
     * @var Zend_Search_Lucene_Index_Term
     */
    private $_lowerTerm;

    /**
     * Upper term.
     *
     * @var Zend_Search_Lucene_Index_Term
     */
    private $_upperTerm;


    /**
     * Search field
     *
     * @var string
     */
    private $_field;

    /**
     * Inclusive
     *
     * @var boolean
     */
    private $_inclusive;

    /**
     * Matched terms.
     *
     * Matched terms list.
     * It's filled during the search (rewrite operation) and may be used for search result
     * post-processing
     *
     * Array of Zend_Search_Lucene_Index_Term objects
     *
     * @var array
     */
    private $_matches;


    /**
     * Zend_Search_Lucene_Search_Query_Range constructor.
     *
     * @param Zend_Search_Lucene_Index_Term|null $lowerTerm
     * @param Zend_Search_Lucene_Index_Term|null $upperTerm
     * @param boolean $inclusive
     * @throws Zend_Search_Lucene_Exception
     */
    public function __construct($lowerTerm, $upperTerm, $inclusive)
    {
        if ($lowerTerm === null  &&  $upperTerm === null) {
            throw new Zend_Search_Lucene_Exception('At least one term must be non-null');
        }
        if ($lowerTerm !== null  &&  $upperTerm !== null  &&  $lowerTerm->field != $upperTerm->field) {
            throw new Zend_Search_Lucene_Exception('Both terms must be for the same field');
        }

        $this->_field     = ($lowerTerm !== null)? $lowerTerm->field : $upperTerm->field;
        $this->_lowerTerm = $lowerTerm;
        $this->_upperTerm = $upperTerm;
        $this->_inclusive = $inclusive;
    }

    /**
     * Get query field name
     *
     * @return string|null
     */
    public function getField()
    {
        return $this->_field;
    }

    /**
     * Get lower term
     *
     * @return Zend_Search_Lucene_Index_Term|null
     */
    public function getLowerTerm()
    {
        return $this->_lowerTerm;
    }

    /**
     * Get upper term
     *
     * @return Zend_Search_Lucene_Index_Term|null
     */
    public function getUpperTerm()
    {
        return $this->_upperTerm;
    }

    /**
     * Get upper term
     *
     * @return boolean
     */
    public function isInclusive()
    {
        return $this->_inclusive;
    }

    /**
     * Re-write query into primitive queries in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        $this->_matches = array();

        if ($this->_field === null) {
            // Search through all fields
            $fields = $index->getFieldNames(true /* indexed fields list */);
        } else {
            $fields = array($this->_field);
        }

        $maxTerms = Zend_search_lucene::getTermsPerQueryLimit();
        foreach ($fields as $field) {
            $index->resetTermsStream();

            if ($this->_lowerTerm !== null) {
                $lowerTerm = new Zend_Search_Lucene_Index_Term($this->_lowerTerm->text, $field);

                $index->skipTo($lowerTerm);

                if (!$this->_inclusive  &&
                    $index->currentTerm() == $lowerTerm) {
                    // Skip lower term
                    $index->nextTerm();
                }
            } else {
                $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field));
            }


            if ($this->_upperTerm !== null) {
                // Walk up to the upper term
                $upperTerm = new Zend_Search_Lucene_Index_Term($this->_upperTerm->text, $field);

                while ($index->currentTerm() !== null          &&
                       $index->currentTerm()->field == $field  &&
                       $index->currentTerm()->text  <  $upperTerm->text) {
                    $this->_matches[] = $index->currentTerm();

                    if ($maxTerms != 0  &&  count($this->_matches) > $maxTerms) {
                        throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
                    }

                    $index->nextTerm();
                }

                if ($this->_inclusive  &&  $index->currentTerm() == $upperTerm) {
                    // Include upper term into result
                    $this->_matches[] = $upperTerm;
                }
            } else {
                // Walk up to the end of field data
                while ($index->currentTerm() !== null  &&  $index->currentTerm()->field == $field) {
                    $this->_matches[] = $index->currentTerm();

                    if ($maxTerms != 0  &&  count($this->_matches) > $maxTerms) {
                        throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
                    }

                    $index->nextTerm();
                }
            }

            $index->closeTermsStream();
        }

        if (count($this->_matches) == 0) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        } else if (count($this->_matches) == 1) {
            return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches));
        } else {
            $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();

            foreach ($this->_matches as $matchedTerm) {
                $rewrittenQuery->addTerm($matchedTerm);
            }

            return $rewrittenQuery;
        }
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Return query terms
     *
     * @return array
     * @throws Zend_Search_Lucene_Exception
     */
    public function getQueryTerms()
    {
        if ($this->_matches === null) {
            throw new Zend_Search_Lucene_Exception('Search has to be performed first to get matched terms');
        }

        return $this->_matches;
    }

    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     * @throws Zend_Search_Lucene_Exception
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)');
    }


    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     * @throws Zend_Search_Lucene_Exception
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     * @throws Zend_Search_Lucene_Exception
     */
    public function matchedDocs()
    {
        throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     * @throws Zend_Search_Lucene_Exception
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        throw new Zend_Search_Lucene_Exception('Range query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        $words = array();

        foreach ($this->_matches as $term) {
            $words[] = $term->text;
        }

        $doc->highlight($words, $this->_getHighlightColor($colorIndex));
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        // It's used only for query visualisation, so we don't care about characters escaping
        return (($this->_field === null)? '' : $this->_field . ':')
             . (($this->_inclusive)? '[' : '{')
             . (($this->_lowerTerm !== null)?  $this->_lowerTerm->text : 'null')
             . ' TO '
             . (($this->_upperTerm !== null)?  $this->_upperTerm->text : 'null')
             . (($this->_inclusive)? ']' : '}');
    }
}

Search/Lucene/Search/Query/Term.php000066600000014063151256604600013133 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';

/** Zend_Search_Lucene_Search_Weight_Term */
require_once 'Zend/Search/Lucene/Search/Weight/Term.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_Term extends Zend_Search_Lucene_Search_Query
{
    /**
     * Term to find.
     *
     * @var Zend_Search_Lucene_Index_Term
     */
    private $_term;

    /**
     * Documents vector.
     *
     * @var array
     */
    private $_docVector = null;

    /**
     * Term freqs vector.
     * array(docId => freq, ...)
     *
     * @var array
     */
    private $_termFreqs;


    /**
     * Zend_Search_Lucene_Search_Query_Term constructor
     *
     * @param Zend_Search_Lucene_Index_Term $term
     * @param boolean $sign
     */
    public function __construct(Zend_Search_Lucene_Index_Term $term)
    {
        $this->_term = $term;
    }

    /**
     * Re-write query into primitive queries in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        if ($this->_term->field != null) {
            return $this;
        } else {
            $query = new Zend_Search_Lucene_Search_Query_MultiTerm();
            $query->setBoost($this->getBoost());

            foreach ($index->getFieldNames(true) as $fieldName) {
                $term = new Zend_Search_Lucene_Index_Term($this->_term->text, $fieldName);

                $query->addTerm($term);
            }

            return $query->rewrite($index);
        }
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        // Check, that index contains specified term
        if (!$index->hasTerm($this->_term)) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        }

        return $this;
    }


    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        $this->_weight = new Zend_Search_Lucene_Search_Weight_Term($this->_term, $this, $reader);
        return $this->_weight;
    }

    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        $this->_docVector = array_flip($reader->termDocs($this->_term, $docsFilter));
        $this->_termFreqs = $reader->termFreqs($this->_term, $docsFilter);

        // Initialize weight if it's not done yet
        $this->_initWeight($reader);
    }

    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     */
    public function matchedDocs()
    {
        return $this->_docVector;
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        if (isset($this->_docVector[$docId])) {
            return $reader->getSimilarity()->tf($this->_termFreqs[$docId]) *
                   $this->_weight->getValue() *
                   $reader->norm($docId, $this->_term->field) *
                   $this->getBoost();
        } else {
            return 0;
        }
    }

    /**
     * Return query terms
     *
     * @return array
     */
    public function getQueryTerms()
    {
        return array($this->_term);
    }

    /**
     * Return query term
     *
     * @return Zend_Search_Lucene_Index_Term
     */
    public function getTerm()
    {
        return $this->_term;
    }

    /**
     * Returns query term
     *
     * @return array
     */
    public function getTerms()
    {
        return $this->_terms;
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        $doc->highlight($this->_term->text, $this->_getHighlightColor($colorIndex));
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        // It's used only for query visualisation, so we don't care about characters escaping
        return (($this->_term->field === null)? '':$this->_term->field . ':') . $this->_term->text;
    }
}

Search/Lucene/Search/Query/Phrase.php000066600000043011151256604600013441 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * Zend_Search_Lucene_Search_Query
 */
require_once 'Zend/Search/Lucene/Search/Query.php';

/**
 * Zend_Search_Lucene_Search_Weight_MultiTerm
 */
require_once 'Zend/Search/Lucene/Search/Weight/Phrase.php';


/**
 * A Query that matches documents containing a particular sequence of terms.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_Phrase extends Zend_Search_Lucene_Search_Query
{
    /**
     * Terms to find.
     * Array of Zend_Search_Lucene_Index_Term objects.
     *
     * @var array
     */
    private $_terms;

    /**
     * Term positions (relative positions of terms within the phrase).
     * Array of integers
     *
     * @var array
     */
    private $_offsets;

    /**
     * Sets the number of other words permitted between words in query phrase.
     * If zero, then this is an exact phrase search.  For larger values this works
     * like a WITHIN or NEAR operator.
     *
     * The slop is in fact an edit-distance, where the units correspond to
     * moves of terms in the query phrase out of position.  For example, to switch
     * the order of two words requires two moves (the first move places the words
     * atop one another), so to permit re-orderings of phrases, the slop must be
     * at least two.
     * More exact matches are scored higher than sloppier matches, thus search
     * results are sorted by exactness.
     *
     * The slop is zero by default, requiring exact matches.
     *
     * @var integer
     */
    private $_slop;

    /**
     * Result vector.
     *
     * @var array
     */
    private $_resVector = null;

    /**
     * Terms positions vectors.
     * Array of Arrays:
     * term1Id => (docId => array( pos1, pos2, ... ), ...)
     * term2Id => (docId => array( pos1, pos2, ... ), ...)
     *
     * @var array
     */
    private $_termsPositions = array();

    /**
     * Class constructor.  Create a new prase query.
     *
     * @param string $field    Field to search.
     * @param array  $terms    Terms to search Array of strings.
     * @param array  $offsets  Relative term positions. Array of integers.
     * @throws Zend_Search_Lucene_Exception
     */
    public function __construct($terms = null, $offsets = null, $field = null)
    {
        $this->_slop = 0;

        if (is_array($terms)) {
            $this->_terms = array();
            foreach ($terms as $termId => $termText) {
                $this->_terms[$termId] = ($field !== null)? new Zend_Search_Lucene_Index_Term($termText, $field):
                                                            new Zend_Search_Lucene_Index_Term($termText);
            }
        } else if ($terms === null) {
            $this->_terms = array();
        } else {
            throw new Zend_Search_Lucene_Exception('terms argument must be array of strings or null');
        }

        if (is_array($offsets)) {
            if (count($this->_terms) != count($offsets)) {
                throw new Zend_Search_Lucene_Exception('terms and offsets arguments must have the same size.');
            }
            $this->_offsets = $offsets;
        } else if ($offsets === null) {
            $this->_offsets = array();
            foreach ($this->_terms as $termId => $term) {
                $position = count($this->_offsets);
                $this->_offsets[$termId] = $position;
            }
        } else {
            throw new Zend_Search_Lucene_Exception('offsets argument must be array of strings or null');
        }
    }

    /**
     * Set slop
     *
     * @param integer $slop
     */
    public function setSlop($slop)
    {
        $this->_slop = $slop;
    }


    /**
     * Get slop
     *
     * @return integer
     */
    public function getSlop()
    {
        return $this->_slop;
    }


    /**
     * Adds a term to the end of the query phrase.
     * The relative position of the term is specified explicitly or the one immediately
     * after the last term added.
     *
     * @param Zend_Search_Lucene_Index_Term $term
     * @param integer $position
     */
    public function addTerm(Zend_Search_Lucene_Index_Term $term, $position = null) {
        if ((count($this->_terms) != 0)&&(end($this->_terms)->field != $term->field)) {
            throw new Zend_Search_Lucene_Exception('All phrase terms must be in the same field: ' .
                                                   $term->field . ':' . $term->text);
        }

        $this->_terms[] = $term;
        if ($position !== null) {
            $this->_offsets[] = $position;
        } else if (count($this->_offsets) != 0) {
            $this->_offsets[] = end($this->_offsets) + 1;
        } else {
            $this->_offsets[] = 0;
        }
    }


    /**
     * Re-write query into primitive queries in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        if (count($this->_terms) == 0) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        } else if ($this->_terms[0]->field !== null) {
            return $this;
        } else {
            $query = new Zend_Search_Lucene_Search_Query_Boolean();
            $query->setBoost($this->getBoost());

            foreach ($index->getFieldNames(true) as $fieldName) {
                $subquery = new Zend_Search_Lucene_Search_Query_Phrase();
                $subquery->setSlop($this->getSlop());

                foreach ($this->_terms as $termId => $term) {
                    $qualifiedTerm = new Zend_Search_Lucene_Index_Term($term->text, $fieldName);

                    $subquery->addTerm($qualifiedTerm, $this->_offsets[$termId]);
                }

                $query->addSubquery($subquery);
            }

            return $query;
        }
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        // Check, that index contains all phrase terms
        foreach ($this->_terms as $term) {
            if (!$index->hasTerm($term)) {
                return new Zend_Search_Lucene_Search_Query_Empty();
            }
        }

        if (count($this->_terms) == 1) {
            // It's one term query
            $optimizedQuery = new Zend_Search_Lucene_Search_Query_Term(reset($this->_terms));
            $optimizedQuery->setBoost($this->getBoost());

            return $optimizedQuery;
        }

        if (count($this->_terms) == 0) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        }


        return $this;
    }

    /**
     * Returns query term
     *
     * @return array
     */
    public function getTerms()
    {
        return $this->_terms;
    }


    /**
     * Set weight for specified term
     *
     * @param integer $num
     * @param Zend_Search_Lucene_Search_Weight_Term $weight
     */
    public function setWeight($num, $weight)
    {
        $this->_weights[$num] = $weight;
    }


    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        $this->_weight = new Zend_Search_Lucene_Search_Weight_Phrase($this, $reader);
        return $this->_weight;
    }


    /**
     * Score calculator for exact phrase queries (terms sequence is fixed)
     *
     * @param integer $docId
     * @return float
     */
    public function _exactPhraseFreq($docId)
    {
        $freq = 0;

        // Term Id with lowest cardinality
        $lowCardTermId = null;

        // Calculate $lowCardTermId
        foreach ($this->_terms as $termId => $term) {
            if ($lowCardTermId === null ||
                count($this->_termsPositions[$termId][$docId]) <
                count($this->_termsPositions[$lowCardTermId][$docId]) ) {
                    $lowCardTermId = $termId;
                }
        }

        // Walk through positions of the term with lowest cardinality
        foreach ($this->_termsPositions[$lowCardTermId][$docId] as $lowCardPos) {
            // We expect phrase to be found
            $freq++;

            // Walk through other terms
            foreach ($this->_terms as $termId => $term) {
                if ($termId != $lowCardTermId) {
                    $expectedPosition = $lowCardPos +
                                            ($this->_offsets[$termId] -
                                             $this->_offsets[$lowCardTermId]);

                    if (!in_array($expectedPosition, $this->_termsPositions[$termId][$docId])) {
                        $freq--;  // Phrase wasn't found.
                        break;
                    }
                }
            }
        }

        return $freq;
    }

    /**
     * Score calculator for sloppy phrase queries (terms sequence is fixed)
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function _sloppyPhraseFreq($docId, Zend_Search_Lucene_Interface $reader)
    {
        $freq = 0;

        $phraseQueue = array();
        $phraseQueue[0] = array(); // empty phrase
        $lastTerm = null;

        // Walk through the terms to create phrases.
        foreach ($this->_terms as $termId => $term) {
            $queueSize = count($phraseQueue);
            $firstPass = true;

            // Walk through the term positions.
            // Each term position produces a set of phrases.
            foreach ($this->_termsPositions[$termId][$docId] as $termPosition ) {
                if ($firstPass) {
                    for ($count = 0; $count < $queueSize; $count++) {
                        $phraseQueue[$count][$termId] = $termPosition;
                    }
                } else {
                    for ($count = 0; $count < $queueSize; $count++) {
                        if ($lastTerm !== null &&
                            abs( $termPosition - $phraseQueue[$count][$lastTerm] -
                                 ($this->_offsets[$termId] - $this->_offsets[$lastTerm])) > $this->_slop) {
                            continue;
                        }

                        $newPhraseId = count($phraseQueue);
                        $phraseQueue[$newPhraseId]          = $phraseQueue[$count];
                        $phraseQueue[$newPhraseId][$termId] = $termPosition;
                    }

                }

                $firstPass = false;
            }
            $lastTerm = $termId;
        }


        foreach ($phraseQueue as $phrasePos) {
            $minDistance = null;

            for ($shift = -$this->_slop; $shift <= $this->_slop; $shift++) {
                $distance = 0;
                $start = reset($phrasePos) - reset($this->_offsets) + $shift;

                foreach ($this->_terms as $termId => $term) {
                    $distance += abs($phrasePos[$termId] - $this->_offsets[$termId] - $start);

                    if($distance > $this->_slop) {
                        break;
                    }
                }

                if ($minDistance === null || $distance < $minDistance) {
                    $minDistance = $distance;
                }
            }

            if ($minDistance <= $this->_slop) {
                $freq += $reader->getSimilarity()->sloppyFreq($minDistance);
            }
        }

        return $freq;
    }

    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        $this->_resVector = null;

        if (count($this->_terms) == 0) {
            $this->_resVector = array();
        }

        $resVectors      = array();
        $resVectorsSizes = array();
        $resVectorsIds   = array(); // is used to prevent arrays comparison
        foreach ($this->_terms as $termId => $term) {
            $resVectors[]      = array_flip($reader->termDocs($term));
            $resVectorsSizes[] = count(end($resVectors));
            $resVectorsIds[]   = $termId;

            $this->_termsPositions[$termId] = $reader->termPositions($term);
        }
        // sort resvectors in order of subquery cardinality increasing
        array_multisort($resVectorsSizes, SORT_ASC, SORT_NUMERIC,
                        $resVectorsIds,   SORT_ASC, SORT_NUMERIC,
                        $resVectors);

        foreach ($resVectors as $nextResVector) {
            if($this->_resVector === null) {
                $this->_resVector = $nextResVector;
            } else {
                //$this->_resVector = array_intersect_key($this->_resVector, $nextResVector);

                /**
                 * This code is used as workaround for array_intersect_key() slowness problem.
                 */
                $updatedVector = array();
                foreach ($this->_resVector as $id => $value) {
                    if (isset($nextResVector[$id])) {
                        $updatedVector[$id] = $value;
                    }
                }
                $this->_resVector = $updatedVector;
            }

            if (count($this->_resVector) == 0) {
                // Empty result set, we don't need to check other terms
                break;
            }
        }

        // ksort($this->_resVector, SORT_NUMERIC);
        // Docs are returned ordered. Used algorithm doesn't change elements order.

        // Initialize weight if it's not done yet
        $this->_initWeight($reader);
    }

    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     */
    public function matchedDocs()
    {
        return $this->_resVector;
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        if (isset($this->_resVector[$docId])) {
            if ($this->_slop == 0) {
                $freq = $this->_exactPhraseFreq($docId);
            } else {
                $freq = $this->_sloppyPhraseFreq($docId, $reader);
            }

            if ($freq != 0) {
                $tf = $reader->getSimilarity()->tf($freq);
                $weight = $this->_weight->getValue();
                $norm = $reader->norm($docId, reset($this->_terms)->field);

                return $tf * $weight * $norm * $this->getBoost();
            }

            // Included in result, but culculated freq is zero
            return 0;
        } else {
            return 0;
        }
    }

    /**
     * Return query terms
     *
     * @return array
     */
    public function getQueryTerms()
    {
        return $this->_terms;
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        $words = array();
        foreach ($this->_terms as $term) {
            $words[] = $term->text;
        }

        $doc->highlight($words, $this->_getHighlightColor($colorIndex));
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        // It's used only for query visualisation, so we don't care about characters escaping

        $query = '';

        if (isset($this->_terms[0]) && $this->_terms[0]->field !== null) {
            $query .= $this->_terms[0]->field . ':';
        }

        $query .= '"';

        foreach ($this->_terms as $id => $term) {
            if ($id != 0) {
                $query .= ' ';
            }
            $query .= $term->text;
        }

        $query .= '"';

        if ($this->_slop != 0) {
            $query .= '~' . $this->_slop;
        }

        return $query;
    }
}

Search/Lucene/Search/Query/Fuzzy.php000066600000037233151256604600013357 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';

/** Zend_Search_Lucene_Search_Query_MultiTerm */
require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_Fuzzy extends Zend_Search_Lucene_Search_Query
{
    /** Default minimum similarity */
    const DEFAULT_MIN_SIMILARITY = 0.5;

    /**
     * Maximum number of matched terms.
     * Apache Lucene defines this limitation as boolean query maximum number of clauses:
     * org.apache.lucene.search.BooleanQuery.getMaxClauseCount()
     */
    const MAX_CLAUSE_COUNT = 1024;

    /**
     * Array of precalculated max distances
     *
     * keys are integers representing a word size
     */
    private $_maxDistances = array();

    /**
     * Base searching term.
     *
     * @var Zend_Search_Lucene_Index_Term
     */
    private $_term;

    /**
     * A value between 0 and 1 to set the required similarity
     *  between the query term and the matching terms. For example, for a
     *  _minimumSimilarity of 0.5 a term of the same length
     *  as the query term is considered similar to the query term if the edit distance
     *  between both terms is less than length(term)*0.5
     *
     * @var float
     */
    private $_minimumSimilarity;

    /**
     * The length of common (non-fuzzy) prefix
     *
     * @var integer
     */
    private $_prefixLength;

    /**
     * Matched terms.
     *
     * Matched terms list.
     * It's filled during the search (rewrite operation) and may be used for search result
     * post-processing
     *
     * Array of Zend_Search_Lucene_Index_Term objects
     *
     * @var array
     */
    private $_matches = null;

    /**
     * Matched terms scores
     *
     * @var array
     */
    private $_scores = null;

    /**
     * Array of the term keys.
     * Used to sort terms in alphabetical order if terms have the same socres
     *
     * @var array
     */
    private $_termKeys = null;

    /**
     * Default non-fuzzy prefix length
     *
     * @var integer
     */
    private static $_defaultPrefixLength = 3;

    /**
     * Zend_Search_Lucene_Search_Query_Wildcard constructor.
     *
     * @param Zend_Search_Lucene_Index_Term $pattern
     * @throws Zend_Search_Lucene_Exception
     */
    public function __construct(Zend_Search_Lucene_Index_Term $term, $minimumSimilarity = self::DEFAULT_MIN_SIMILARITY, $prefixLength = null)
    {
        if ($minimumSimilarity < 0) {
            throw new Zend_Search_Lucene_Exception('minimumSimilarity cannot be less than 0');
        }
        if ($minimumSimilarity >= 1) {
            throw new Zend_Search_Lucene_Exception('minimumSimilarity cannot be greater than or equal to 1');
        }
        if ($prefixLength < 0) {
            throw new Zend_Search_Lucene_Exception('prefixLength cannot be less than 0');
        }

        $this->_term              = $term;
        $this->_minimumSimilarity = $minimumSimilarity;
        $this->_prefixLength      = ($prefixLength !== null)? $prefixLength : self::$_defaultPrefixLength;
    }

    /**
     * Get default non-fuzzy prefix length
     *
     * @return integer
     */
    public static function getDefaultPrefixLength()
    {
        return self::$_defaultPrefixLength;
    }

    /**
     * Set default non-fuzzy prefix length
     *
     * @param integer $defaultPrefixLength
     */
    public static function setDefaultPrefixLength($defaultPrefixLength)
    {
        self::$_defaultPrefixLength = $defaultPrefixLength;
    }

    /**
     * Calculate maximum distance for specified word length
     *
     * @param integer $prefixLength
     * @param integer $termLength
     * @param integer $length
     * @return integer
     */
    private function _calculateMaxDistance($prefixLength, $termLength, $length)
    {
        $this->_maxDistances[$length] = (int) ((1 - $this->_minimumSimilarity)*(min($termLength, $length) + $prefixLength));
        return $this->_maxDistances[$length];
    }

    /**
     * Re-write query into primitive queries in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     * @throws Zend_Search_Lucene_Exception
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        $this->_matches  = array();
        $this->_scores   = array();
        $this->_termKeys = array();

        if ($this->_term->field === null) {
            // Search through all fields
            $fields = $index->getFieldNames(true /* indexed fields list */);
        } else {
            $fields = array($this->_term->field);
        }

        $prefix           = Zend_Search_Lucene_Index_Term::getPrefix($this->_term->text, $this->_prefixLength);
        $prefixByteLength = strlen($prefix);
        $prefixUtf8Length = Zend_Search_Lucene_Index_Term::getLength($prefix);

        $termLength       = Zend_Search_Lucene_Index_Term::getLength($this->_term->text);

        $termRest         = substr($this->_term->text, $prefixByteLength);
        // we calculate length of the rest in bytes since levenshtein() is not UTF-8 compatible
        $termRestLength   = strlen($termRest);

        $scaleFactor = 1/(1 - $this->_minimumSimilarity);

        $maxTerms = Zend_search_lucene::getTermsPerQueryLimit();
        foreach ($fields as $field) {
            $index->resetTermsStream();

            if ($prefix != '') {
                $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field));

                while ($index->currentTerm() !== null          &&
                       $index->currentTerm()->field == $field  &&
                       substr($index->currentTerm()->text, 0, $prefixByteLength) == $prefix) {
                    // Calculate similarity
                    $target = substr($index->currentTerm()->text, $prefixByteLength);

                    $maxDistance = isset($this->_maxDistances[strlen($target)])?
                                       $this->_maxDistances[strlen($target)] :
                                       $this->_calculateMaxDistance($prefixUtf8Length, $termRestLength, strlen($target));

                    if ($termRestLength == 0) {
                        // we don't have anything to compare.  That means if we just add
                        // the letters for current term we get the new word
                        $similarity = (($prefixUtf8Length == 0)? 0 : 1 - strlen($target)/$prefixUtf8Length);
                    } else if (strlen($target) == 0) {
                        $similarity = (($prefixUtf8Length == 0)? 0 : 1 - $termRestLength/$prefixUtf8Length);
                    } else if ($maxDistance < abs($termRestLength - strlen($target))){
                        //just adding the characters of term to target or vice-versa results in too many edits
                        //for example "pre" length is 3 and "prefixes" length is 8.  We can see that
                        //given this optimal circumstance, the edit distance cannot be less than 5.
                        //which is 8-3 or more precisesly abs(3-8).
                        //if our maximum edit distance is 4, then we can discard this word
                        //without looking at it.
                        $similarity = 0;
                    } else {
                        $similarity = 1 - levenshtein($termRest, $target)/($prefixUtf8Length + min($termRestLength, strlen($target)));
                    }

                    if ($similarity > $this->_minimumSimilarity) {
                        $this->_matches[]  = $index->currentTerm();
                        $this->_termKeys[] = $index->currentTerm()->key();
                        $this->_scores[]   = ($similarity - $this->_minimumSimilarity)*$scaleFactor;

                        if ($maxTerms != 0  &&  count($this->_matches) > $maxTerms) {
                            throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
                        }
                    }

                    $index->nextTerm();
                }
            } else {
                $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field));

                while ($index->currentTerm() !== null  &&  $index->currentTerm()->field == $field) {
                    // Calculate similarity
                    $target = $index->currentTerm()->text;

                    $maxDistance = isset($this->_maxDistances[strlen($target)])?
                                       $this->_maxDistances[strlen($target)] :
                                       $this->_calculateMaxDistance(0, $termRestLength, strlen($target));

                    if ($maxDistance < abs($termRestLength - strlen($target))){
                        //just adding the characters of term to target or vice-versa results in too many edits
                        //for example "pre" length is 3 and "prefixes" length is 8.  We can see that
                        //given this optimal circumstance, the edit distance cannot be less than 5.
                        //which is 8-3 or more precisesly abs(3-8).
                        //if our maximum edit distance is 4, then we can discard this word
                        //without looking at it.
                        $similarity = 0;
                    } else {
                        $similarity = 1 - levenshtein($termRest, $target)/min($termRestLength, strlen($target));
                    }

                    if ($similarity > $this->_minimumSimilarity) {
                        $this->_matches[]  = $index->currentTerm();
                        $this->_termKeys[] = $index->currentTerm()->key();
                        $this->_scores[]   = ($similarity - $this->_minimumSimilarity)*$scaleFactor;

                        if ($maxTerms != 0  &&  count($this->_matches) > $maxTerms) {
                            throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
                        }
                    }

                    $index->nextTerm();
                }
            }

            $index->closeTermsStream();
        }

        if (count($this->_matches) == 0) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        } else if (count($this->_matches) == 1) {
            return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches));
        } else {
            $rewrittenQuery = new Zend_Search_Lucene_Search_Query_Boolean();

            array_multisort($this->_scores,   SORT_DESC, SORT_NUMERIC,
                            $this->_termKeys, SORT_ASC,  SORT_STRING,
                            $this->_matches);

            $termCount = 0;
            foreach ($this->_matches as $id => $matchedTerm) {
                $subquery = new Zend_Search_Lucene_Search_Query_Term($matchedTerm);
                $subquery->setBoost($this->_scores[$id]);

                $rewrittenQuery->addSubquery($subquery);

                $termCount++;
                if ($termCount >= self::MAX_CLAUSE_COUNT) {
                    break;
                }
            }

            return $rewrittenQuery;
        }
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Return query terms
     *
     * @return array
     * @throws Zend_Search_Lucene_Exception
     */
    public function getQueryTerms()
    {
        if ($this->_matches === null) {
            throw new Zend_Search_Lucene_Exception('Search has to be performed first to get matched terms');
        }

        return $this->_matches;
    }

    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     * @throws Zend_Search_Lucene_Exception
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }


    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     * @throws Zend_Search_Lucene_Exception
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     * @throws Zend_Search_Lucene_Exception
     */
    public function matchedDocs()
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     * @throws Zend_Search_Lucene_Exception
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        $words = array();

        foreach ($this->_matches as $term) {
            $words[] = $term->text;
        }

        $doc->highlight($words, $this->_getHighlightColor($colorIndex));
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        // It's used only for query visualisation, so we don't care about characters escaping
        return (($this->_term->field === null)? '' : $this->_term->field . ':')
             . $this->_term->text . '~'
             . (($this->_minimumSimilarity != self::DEFAULT_MIN_SIMILARITY)? round($this->_minimumSimilarity, 4) : '');
    }
}

Search/Lucene/Search/Query/Insignificant.php000066600000007414151256604600015013 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';

/** Zend_Search_Lucene_Search_Weight_Empty */
require_once 'Zend/Search/Lucene/Search/Weight/Empty.php';


/**
 * The insignificant query returns empty result, but doesn't limit result set as a part of other queries
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_Insignificant extends Zend_Search_Lucene_Search_Query
{
    /**
     * Re-write query into primitive queries in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        return $this;
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        return $this;
    }

    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        return new Zend_Search_Lucene_Search_Weight_Empty();
    }

    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        // Do nothing
    }

    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     */
    public function matchedDocs()
    {
        return array();
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        return 0;
    }

    /**
     * Return query terms
     *
     * @return array
     */
    public function getQueryTerms()
    {
        return array();
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        // Do nothing
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        return '<InsignificantQuery>';
    }
}

Search/Lucene/Search/Query/Wildcard.php000066600000025623151256604600013761 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';

/** Zend_Search_Lucene_Search_Query_MultiTerm */
require_once 'Zend/Search/Lucene/Search/Query/MultiTerm.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_Wildcard extends Zend_Search_Lucene_Search_Query
{
    /**
     * Search pattern.
     *
     * Field has to be fully specified or has to be null
     * Text may contain '*' or '?' symbols
     *
     * @var Zend_Search_Lucene_Index_Term
     */
    private $_pattern;

    /**
     * Matched terms.
     *
     * Matched terms list.
     * It's filled during the search (rewrite operation) and may be used for search result
     * post-processing
     *
     * Array of Zend_Search_Lucene_Index_Term objects
     *
     * @var array
     */
    private $_matches = null;

    /**
     * Minimum term prefix length (number of minimum non-wildcard characters)
     *
     * @var integer
     */
    private static $_minPrefixLength = 3;

    /**
     * Zend_Search_Lucene_Search_Query_Wildcard constructor.
     *
     * @param Zend_Search_Lucene_Index_Term $pattern
     */
    public function __construct(Zend_Search_Lucene_Index_Term $pattern)
    {
        $this->_pattern = $pattern;
    }

    /**
     * Get minimum prefix length
     *
     * @return integer
     */
    public static function getMinPrefixLength()
    {
    	return self::$_minPrefixLength;
    }

    /**
     * Set minimum prefix length
     *
     * @param integer $minPrefixLength
     */
    public static function setMinPrefixLength($minPrefixLength)
    {
    	self::$_minPrefixLength = $minPrefixLength;
    }

    /**
     * Get terms prefix
     *
     * @param string $word
     * @return string
     */
    private static function _getPrefix($word)
    {
        $questionMarkPosition = strpos($word, '?');
        $astrericPosition     = strpos($word, '*');

        if ($questionMarkPosition !== false) {
            if ($astrericPosition !== false) {
                return substr($word, 0, min($questionMarkPosition, $astrericPosition));
            }

            return substr($word, 0, $questionMarkPosition);
        } else if ($astrericPosition !== false) {
            return substr($word, 0, $astrericPosition);
        }

        return $word;
    }

    /**
     * Re-write query into primitive queries in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     * @throws Zend_Search_Lucene_Exception
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        $this->_matches = array();

        if ($this->_pattern->field === null) {
            // Search through all fields
            $fields = $index->getFieldNames(true /* indexed fields list */);
        } else {
            $fields = array($this->_pattern->field);
        }

        $prefix          = self::_getPrefix($this->_pattern->text);
        $prefixLength    = strlen($prefix);
        $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/';

        if ($prefixLength < self::$_minPrefixLength) {
        	throw new Zend_Search_Lucene_Exception('At least ' . self::$_minPrefixLength . ' non-wildcard terms are required.');
        }

        /** @todo check for PCRE unicode support may be performed through Zend_Environment in some future */
        if (@preg_match('/\pL/u', 'a') == 1) {
            // PCRE unicode support is turned on
            // add Unicode modifier to the match expression
            $matchExpression .= 'u';
        }

        $maxTerms = Zend_search_lucene::getTermsPerQueryLimit();
        foreach ($fields as $field) {
            $index->resetTermsStream();

            if ($prefix != '') {
                $index->skipTo(new Zend_Search_Lucene_Index_Term($prefix, $field));

                while ($index->currentTerm() !== null          &&
                       $index->currentTerm()->field == $field  &&
                       substr($index->currentTerm()->text, 0, $prefixLength) == $prefix) {
                    if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
                        $this->_matches[] = $index->currentTerm();

                        if ($maxTerms != 0  &&  count($this->_matches) > $maxTerms) {
                        	throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
                        }
                    }

                    $index->nextTerm();
                }
            } else {
                $index->skipTo(new Zend_Search_Lucene_Index_Term('', $field));

                while ($index->currentTerm() !== null  &&  $index->currentTerm()->field == $field) {
                    if (preg_match($matchExpression, $index->currentTerm()->text) === 1) {
                        $this->_matches[] = $index->currentTerm();

                        if ($maxTerms != 0  &&  count($this->_matches) > $maxTerms) {
                            throw new Zend_Search_Lucene_Exception('Terms per query limit is reached.');
                        }
                    }

                    $index->nextTerm();
                }
            }

            $index->closeTermsStream();
        }

        if (count($this->_matches) == 0) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        } else if (count($this->_matches) == 1) {
            return new Zend_Search_Lucene_Search_Query_Term(reset($this->_matches));
        } else {
            $rewrittenQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();

            foreach ($this->_matches as $matchedTerm) {
                $rewrittenQuery->addTerm($matchedTerm);
            }

            return $rewrittenQuery;
        }
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }


    /**
     * Returns query pattern
     *
     * @return Zend_Search_Lucene_Index_Term
     */
    public function getPattern()
    {
        return $this->_pattern;
    }


    /**
     * Return query terms
     *
     * @return array
     * @throws Zend_Search_Lucene_Exception
     */
    public function getQueryTerms()
    {
        if ($this->_matches === null) {
            throw new Zend_Search_Lucene_Exception('Search has to be performed first to get matched terms');
        }

        return $this->_matches;
    }

    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     * @throws Zend_Search_Lucene_Exception
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }


    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     * @throws Zend_Search_Lucene_Exception
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     * @throws Zend_Search_Lucene_Exception
     */
    public function matchedDocs()
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     * @throws Zend_Search_Lucene_Exception
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        throw new Zend_Search_Lucene_Exception('Wildcard query should not be directly used for search. Use $query->rewrite($index)');
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        $words = array();

        $matchExpression = '/^' . str_replace(array('\\?', '\\*'), array('.', '.*') , preg_quote($this->_pattern->text, '/')) . '$/';
        if (@preg_match('/\pL/u', 'a') == 1) {
            // PCRE unicode support is turned on
            // add Unicode modifier to the match expression
            $matchExpression .= 'u';
        }

        $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($doc->getFieldUtf8Value('body'), 'UTF-8');
        foreach ($tokens as $token) {
            if (preg_match($matchExpression, $token->getTermText()) === 1) {
                $words[] = $token->getTermText();
            }
        }

        $doc->highlight($words, $this->_getHighlightColor($colorIndex));
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        // It's used only for query visualisation, so we don't care about characters escaping
        return (($this->_pattern->field === null)? '' : $this->_pattern->field . ':') . $this->_pattern->text;
    }
}

Search/Lucene/Search/Query/Boolean.php000066600000065650151256604600013613 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Search_Query */
require_once 'Zend/Search/Lucene/Search/Query.php';

/** Zend_Search_Lucene_Search_Weight_Boolean */
require_once 'Zend/Search/Lucene/Search/Weight/Boolean.php';


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_Query_Boolean extends Zend_Search_Lucene_Search_Query
{

    /**
     * Subqueries
     * Array of Zend_Search_Lucene_Search_Query
     *
     * @var array
     */
    private $_subqueries = array();

    /**
     * Subqueries signs.
     * If true then subquery is required.
     * If false then subquery is prohibited.
     * If null then subquery is neither prohibited, nor required
     *
     * If array is null then all subqueries are required
     *
     * @var array
     */
    private $_signs = array();

    /**
     * Result vector.
     *
     * @var array
     */
    private $_resVector = null;

    /**
     * A score factor based on the fraction of all query subqueries
     * that a document contains.
     * float for conjunction queries
     * array of float for non conjunction queries
     *
     * @var mixed
     */
    private $_coord = null;


    /**
     * Class constructor.  Create a new Boolean query object.
     *
     * if $signs array is omitted then all subqueries are required
     * it differs from addSubquery() behavior, but should never be used
     *
     * @param array $subqueries    Array of Zend_Search_Search_Query objects
     * @param array $signs    Array of signs.  Sign is boolean|null.
     * @return void
     */
    public function __construct($subqueries = null, $signs = null)
    {
        if (is_array($subqueries)) {
            $this->_subqueries = $subqueries;

            $this->_signs = null;
            // Check if all subqueries are required
            if (is_array($signs)) {
                foreach ($signs as $sign ) {
                    if ($sign !== true) {
                        $this->_signs = $signs;
                        break;
                    }
                }
            }
        }
    }


    /**
     * Add a $subquery (Zend_Search_Lucene_Search_Query) to this query.
     *
     * The sign is specified as:
     *     TRUE  - subquery is required
     *     FALSE - subquery is prohibited
     *     NULL  - subquery is neither prohibited, nor required
     *
     * @param  Zend_Search_Lucene_Search_Query $subquery
     * @param  boolean|null $sign
     * @return void
     */
    public function addSubquery(Zend_Search_Lucene_Search_Query $subquery, $sign=null) {
        if ($sign !== true || $this->_signs !== null) {       // Skip, if all subqueries are required
            if ($this->_signs === null) {                     // Check, If all previous subqueries are required
                $this->_signs = array();
                foreach ($this->_subqueries as $prevSubquery) {
                    $this->_signs[] = true;
                }
            }
            $this->_signs[] = $sign;
        }

        $this->_subqueries[] = $subquery;
    }

    /**
     * Re-write queries into primitive queries
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function rewrite(Zend_Search_Lucene_Interface $index)
    {
        $query = new Zend_Search_Lucene_Search_Query_Boolean();
        $query->setBoost($this->getBoost());

        foreach ($this->_subqueries as $subqueryId => $subquery) {
            $query->addSubquery($subquery->rewrite($index),
                                ($this->_signs === null)?  true : $this->_signs[$subqueryId]);
        }

        return $query;
    }

    /**
     * Optimize query in the context of specified index
     *
     * @param Zend_Search_Lucene_Interface $index
     * @return Zend_Search_Lucene_Search_Query
     */
    public function optimize(Zend_Search_Lucene_Interface $index)
    {
        $subqueries = array();
        $signs      = array();

        // Optimize all subqueries
        foreach ($this->_subqueries as $id => $subquery) {
            $subqueries[] = $subquery->optimize($index);
            $signs[]      = ($this->_signs === null)? true : $this->_signs[$id];
        }

        // Remove insignificant subqueries
        foreach ($subqueries as $id => $subquery) {
            if ($subquery instanceof Zend_Search_Lucene_Search_Query_Insignificant) {
                // Insignificant subquery has to be removed anyway
                unset($subqueries[$id]);
                unset($signs[$id]);
            }
        }
        if (count($subqueries) == 0) {
            // Boolean query doesn't has non-insignificant subqueries
            return new Zend_Search_Lucene_Search_Query_Insignificant();
        }
        // Check if all non-insignificant subqueries are prohibited
        $allProhibited = true;
        foreach ($signs as $sign) {
            if ($sign !== false) {
                $allProhibited = false;
                break;
            }
        }
        if ($allProhibited) {
            return new Zend_Search_Lucene_Search_Query_Insignificant();
        }


        // Check for empty subqueries
        foreach ($subqueries as $id => $subquery) {
            if ($subquery instanceof Zend_Search_Lucene_Search_Query_Empty) {
                if ($signs[$id] === true) {
                    // Matching is required, but is actually empty
                    return new Zend_Search_Lucene_Search_Query_Empty();
                } else {
                    // Matching is optional or prohibited, but is empty
                    // Remove it from subqueries and signs list
                    unset($subqueries[$id]);
                    unset($signs[$id]);
                }
            }
        }

        // Check, if reduced subqueries list is empty
        if (count($subqueries) == 0) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        }

        // Check if all non-empty subqueries are prohibited
        $allProhibited = true;
        foreach ($signs as $sign) {
            if ($sign !== false) {
                $allProhibited = false;
                break;
            }
        }
        if ($allProhibited) {
            return new Zend_Search_Lucene_Search_Query_Empty();
        }


        // Check, if reduced subqueries list has only one entry
        if (count($subqueries) == 1) {
            // It's a query with only one required or optional clause
            // (it's already checked, that it's not a prohibited clause)

            if ($this->getBoost() == 1) {
                return reset($subqueries);
            }

            $optimizedQuery = clone reset($subqueries);
            $optimizedQuery->setBoost($optimizedQuery->getBoost()*$this->getBoost());

            return $optimizedQuery;
        }


        // Prepare first candidate for optimized query
        $optimizedQuery = new Zend_Search_Lucene_Search_Query_Boolean($subqueries, $signs);
        $optimizedQuery->setBoost($this->getBoost());


        $terms        = array();
        $tsigns       = array();
        $boostFactors = array();

        // Try to decompose term and multi-term subqueries
        foreach ($subqueries as $id => $subquery) {
            if ($subquery instanceof Zend_Search_Lucene_Search_Query_Term) {
                $terms[]        = $subquery->getTerm();
                $tsigns[]       = $signs[$id];
                $boostFactors[] = $subquery->getBoost();

                // remove subquery from a subqueries list
                unset($subqueries[$id]);
                unset($signs[$id]);
           } else if ($subquery instanceof Zend_Search_Lucene_Search_Query_MultiTerm) {
                $subTerms = $subquery->getTerms();
                $subSigns = $subquery->getSigns();

                if ($signs[$id] === true) {
                    // It's a required multi-term subquery.
                    // Something like '... +(+term1 -term2 term3 ...) ...'

                    // Multi-term required subquery can be decomposed only if it contains
                    // required terms and doesn't contain prohibited terms:
                    // ... +(+term1 term2 ...) ... => ... +term1 term2 ...
                    //
                    // Check this
                    $hasRequired   = false;
                    $hasProhibited = false;
                    if ($subSigns === null) {
                        // All subterms are required
                        $hasRequired = true;
                    } else {
                        foreach ($subSigns as $sign) {
                            if ($sign === true) {
                                $hasRequired   = true;
                            } else if ($sign === false) {
                                $hasProhibited = true;
                                break;
                            }
                        }
                    }
                    // Continue if subquery has prohibited terms or doesn't have required terms
                    if ($hasProhibited  ||  !$hasRequired) {
                        continue;
                    }

                    foreach ($subTerms as $termId => $term) {
                        $terms[]        = $term;
                        $tsigns[]       = ($subSigns === null)? true : $subSigns[$termId];
                        $boostFactors[] = $subquery->getBoost();
                    }

                    // remove subquery from a subqueries list
                    unset($subqueries[$id]);
                    unset($signs[$id]);

                } else { // $signs[$id] === null  ||  $signs[$id] === false
                    // It's an optional or prohibited multi-term subquery.
                    // Something like '... (+term1 -term2 term3 ...) ...'
                    // or
                    // something like '... -(+term1 -term2 term3 ...) ...'

                    // Multi-term optional and required subqueries can be decomposed
                    // only if all terms are optional.
                    //
                    // Check if all terms are optional.
                    $onlyOptional = true;
                    if ($subSigns === null) {
                        // All subterms are required
                        $onlyOptional = false;
                    } else {
                        foreach ($subSigns as $sign) {
                            if ($sign !== null) {
                                $onlyOptional = false;
                                break;
                            }
                        }
                    }

                    // Continue if non-optional terms are presented in this multi-term subquery
                    if (!$onlyOptional) {
                        continue;
                    }

                    foreach ($subTerms as $termId => $term) {
                        $terms[]  = $term;
                        $tsigns[] = ($signs[$id] === null)? null  /* optional */ :
                                                            false /* prohibited */;
                        $boostFactors[] = $subquery->getBoost();
                    }

                    // remove subquery from a subqueries list
                    unset($subqueries[$id]);
                    unset($signs[$id]);
                }
            }
        }


        // Check, if there are no decomposed subqueries
        if (count($terms) == 0 ) {
            // return prepared candidate
            return $optimizedQuery;
        }


        // Check, if all subqueries have been decomposed and all terms has the same boost factor
        if (count($subqueries) == 0  &&  count(array_unique($boostFactors)) == 1) {
            $optimizedQuery = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $tsigns);
            $optimizedQuery->setBoost(reset($boostFactors)*$this->getBoost());

            return $optimizedQuery;
        }


        // This boolean query can't be transformed to Term/MultiTerm query and still contains
        // several subqueries

        // Separate prohibited terms
        $prohibitedTerms        = array();
        foreach ($terms as $id => $term) {
            if ($tsigns[$id] === false) {
                $prohibitedTerms[]        = $term;

                unset($terms[$id]);
                unset($tsigns[$id]);
                unset($boostFactors[$id]);
            }
        }

        if (count($terms) == 1) {
            $clause = new Zend_Search_Lucene_Search_Query_Term(reset($terms));
            $clause->setBoost(reset($boostFactors));

            $subqueries[] = $clause;
            $signs[]      = reset($tsigns);

            // Clear terms list
            $terms = array();
        } else if (count($terms) > 1  &&  count(array_unique($boostFactors)) == 1) {
            $clause = new Zend_Search_Lucene_Search_Query_MultiTerm($terms, $tsigns);
            $clause->setBoost(reset($boostFactors));

            $subqueries[] = $clause;
            // Clause sign is 'required' if clause contains required terms. 'Optional' otherwise.
            $signs[]      = (in_array(true, $tsigns))? true : null;

            // Clear terms list
            $terms = array();
        }

        if (count($prohibitedTerms) == 1) {
            // (boost factors are not significant for prohibited clauses)
            $subqueries[] = new Zend_Search_Lucene_Search_Query_Term(reset($prohibitedTerms));
            $signs[]      = false;

            // Clear prohibited terms list
            $prohibitedTerms = array();
        } else if (count($prohibitedTerms) > 1) {
            // prepare signs array
            $prohibitedSigns = array();
            foreach ($prohibitedTerms as $id => $term) {
                // all prohibited term are grouped as optional into multi-term query
                $prohibitedSigns[$id] = null;
            }

            // (boost factors are not significant for prohibited clauses)
            $subqueries[] = new Zend_Search_Lucene_Search_Query_MultiTerm($prohibitedTerms, $prohibitedSigns);
            // Clause sign is 'prohibited'
            $signs[]      = false;

            // Clear terms list
            $prohibitedTerms = array();
        }

        /** @todo Group terms with the same boost factors together */

        // Check, that all terms are processed
        // Replace candidate for optimized query
        if (count($terms) == 0  &&  count($prohibitedTerms) == 0) {
            $optimizedQuery = new Zend_Search_Lucene_Search_Query_Boolean($subqueries, $signs);
            $optimizedQuery->setBoost($this->getBoost());
        }

        return $optimizedQuery;
    }

    /**
     * Returns subqueries
     *
     * @return array
     */
    public function getSubqueries()
    {
        return $this->_subqueries;
    }


    /**
     * Return subqueries signs
     *
     * @return array
     */
    public function getSigns()
    {
        return $this->_signs;
    }


    /**
     * Constructs an appropriate Weight implementation for this query.
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @return Zend_Search_Lucene_Search_Weight
     */
    public function createWeight(Zend_Search_Lucene_Interface $reader)
    {
        $this->_weight = new Zend_Search_Lucene_Search_Weight_Boolean($this, $reader);
        return $this->_weight;
    }


    /**
     * Calculate result vector for Conjunction query
     * (like '<subquery1> AND <subquery2> AND <subquery3>')
     */
    private function _calculateConjunctionResult()
    {
        $this->_resVector = null;

        if (count($this->_subqueries) == 0) {
            $this->_resVector = array();
        }

        $resVectors      = array();
        $resVectorsSizes = array();
        $resVectorsIds   = array(); // is used to prevent arrays comparison
        foreach ($this->_subqueries as $subqueryId => $subquery) {
            $resVectors[]      = $subquery->matchedDocs();
            $resVectorsSizes[] = count(end($resVectors));
            $resVectorsIds[]   = $subqueryId;
        }
        // sort resvectors in order of subquery cardinality increasing
        array_multisort($resVectorsSizes, SORT_ASC, SORT_NUMERIC,
                        $resVectorsIds,   SORT_ASC, SORT_NUMERIC,
                        $resVectors);

        foreach ($resVectors as $nextResVector) {
            if($this->_resVector === null) {
                $this->_resVector = $nextResVector;
            } else {
                //$this->_resVector = array_intersect_key($this->_resVector, $nextResVector);

                /**
                 * This code is used as workaround for array_intersect_key() slowness problem.
                 */
                $updatedVector = array();
                foreach ($this->_resVector as $id => $value) {
                    if (isset($nextResVector[$id])) {
                        $updatedVector[$id] = $value;
                    }
                }
                $this->_resVector = $updatedVector;
            }

            if (count($this->_resVector) == 0) {
                // Empty result set, we don't need to check other terms
                break;
            }
        }

        // ksort($this->_resVector, SORT_NUMERIC);
        // Used algorithm doesn't change elements order
    }


    /**
     * Calculate result vector for non Conjunction query
     * (like '<subquery1> AND <subquery2> AND NOT <subquery3> OR <subquery4>')
     */
    private function _calculateNonConjunctionResult()
    {
        $requiredVectors      = array();
        $requiredVectorsSizes = array();
        $requiredVectorsIds   = array(); // is used to prevent arrays comparison

        $optional = array();

        foreach ($this->_subqueries as $subqueryId => $subquery) {
            if ($this->_signs[$subqueryId] === true) {
                // required
                $requiredVectors[]      = $subquery->matchedDocs();
                $requiredVectorsSizes[] = count(end($requiredVectors));
                $requiredVectorsIds[]   = $subqueryId;
            } elseif ($this->_signs[$subqueryId] === false) {
                // prohibited
                // Do nothing. matchedDocs() may include non-matching id's
                // Calculating prohibited vector may take significant time, but do not affect the result
                // Skipped.
            } else {
                // neither required, nor prohibited
                // array union
                $optional += $subquery->matchedDocs();
            }
        }

        // sort resvectors in order of subquery cardinality increasing
        array_multisort($requiredVectorsSizes, SORT_ASC, SORT_NUMERIC,
                        $requiredVectorsIds,   SORT_ASC, SORT_NUMERIC,
                        $requiredVectors);

        $required = null;
        foreach ($requiredVectors as $nextResVector) {
            if($required === null) {
                $required = $nextResVector;
            } else {
                //$required = array_intersect_key($required, $nextResVector);

                /**
                 * This code is used as workaround for array_intersect_key() slowness problem.
                 */
                $updatedVector = array();
                foreach ($required as $id => $value) {
                    if (isset($nextResVector[$id])) {
                        $updatedVector[$id] = $value;
                    }
                }
                $required = $updatedVector;
            }

            if (count($required) == 0) {
                // Empty result set, we don't need to check other terms
                break;
            }
        }


        if ($required !== null) {
            $this->_resVector = &$required;
        } else {
            $this->_resVector = &$optional;
        }

        ksort($this->_resVector, SORT_NUMERIC);
    }


    /**
     * Score calculator for conjunction queries (all subqueries are required)
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function _conjunctionScore($docId, Zend_Search_Lucene_Interface $reader)
    {
        if ($this->_coord === null) {
            $this->_coord = $reader->getSimilarity()->coord(count($this->_subqueries),
                                                            count($this->_subqueries) );
        }

        $score = 0;

        foreach ($this->_subqueries as $subquery) {
            $subscore = $subquery->score($docId, $reader);

            if ($subscore == 0) {
                return 0;
            }

            $score += $subquery->score($docId, $reader) * $this->_coord;
        }

        return $score * $this->_coord * $this->getBoost();
    }


    /**
     * Score calculator for non conjunction queries (not all subqueries are required)
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function _nonConjunctionScore($docId, Zend_Search_Lucene_Interface $reader)
    {
        if ($this->_coord === null) {
            $this->_coord = array();

            $maxCoord = 0;
            foreach ($this->_signs as $sign) {
                if ($sign !== false /* not prohibited */) {
                    $maxCoord++;
                }
            }

            for ($count = 0; $count <= $maxCoord; $count++) {
                $this->_coord[$count] = $reader->getSimilarity()->coord($count, $maxCoord);
            }
        }

        $score = 0;
        $matchedSubqueries = 0;
        foreach ($this->_subqueries as $subqueryId => $subquery) {
            $subscore = $subquery->score($docId, $reader);

            // Prohibited
            if ($this->_signs[$subqueryId] === false && $subscore != 0) {
                return 0;
            }

            // is required, but doen't match
            if ($this->_signs[$subqueryId] === true &&  $subscore == 0) {
                return 0;
            }

            if ($subscore != 0) {
                $matchedSubqueries++;
                $score += $subscore;
            }
        }

        return $score * $this->_coord[$matchedSubqueries] * $this->getBoost();
    }

    /**
     * Execute query in context of index reader
     * It also initializes necessary internal structures
     *
     * @param Zend_Search_Lucene_Interface $reader
     * @param Zend_Search_Lucene_Index_DocsFilter|null $docsFilter
     */
    public function execute(Zend_Search_Lucene_Interface $reader, $docsFilter = null)
    {
        // Initialize weight if it's not done yet
        $this->_initWeight($reader);

        if ($docsFilter === null) {
            // Create local documents filter if it's not provided by upper query
            $docsFilter = new Zend_Search_Lucene_Index_DocsFilter();
        }

        foreach ($this->_subqueries as $subqueryId => $subquery) {
            if ($this->_signs == null  ||  $this->_signs[$subqueryId] === true) {
                // Subquery is required
                $subquery->execute($reader, $docsFilter);
            } else {
                $subquery->execute($reader);
            }
        }

        if ($this->_signs === null) {
            $this->_calculateConjunctionResult();
        } else {
            $this->_calculateNonConjunctionResult();
        }
    }



    /**
     * Get document ids likely matching the query
     *
     * It's an array with document ids as keys (performance considerations)
     *
     * @return array
     */
    public function matchedDocs()
    {
        return $this->_resVector;
    }

    /**
     * Score specified document
     *
     * @param integer $docId
     * @param Zend_Search_Lucene_Interface $reader
     * @return float
     */
    public function score($docId, Zend_Search_Lucene_Interface $reader)
    {
        if (isset($this->_resVector[$docId])) {
            if ($this->_signs === null) {
                return $this->_conjunctionScore($docId, $reader);
            } else {
                return $this->_nonConjunctionScore($docId, $reader);
            }
        } else {
            return 0;
        }
    }

    /**
     * Return query terms
     *
     * @return array
     */
    public function getQueryTerms()
    {
        $terms = array();

        foreach ($this->_subqueries as $id => $subquery) {
            if ($this->_signs === null  ||  $this->_signs[$id] !== false) {
                $terms = array_merge($terms, $subquery->getQueryTerms());
            }
        }

        return $terms;
    }

    /**
     * Highlight query terms
     *
     * @param integer &$colorIndex
     * @param Zend_Search_Lucene_Document_Html $doc
     */
    public function highlightMatchesDOM(Zend_Search_Lucene_Document_Html $doc, &$colorIndex)
    {
        foreach ($this->_subqueries as $id => $subquery) {
            if ($this->_signs === null  ||  $this->_signs[$id] !== false) {
                $subquery->highlightMatchesDOM($doc, $colorIndex);
            }
        }
    }

    /**
     * Print a query
     *
     * @return string
     */
    public function __toString()
    {
        // It's used only for query visualisation, so we don't care about characters escaping

        $query = '';

        foreach ($this->_subqueries as $id => $subquery) {
            if ($id != 0) {
                $query .= ' ';
            }

            if ($this->_signs === null || $this->_signs[$id] === true) {
                $query .= '+';
            } else if ($this->_signs[$id] === false) {
                $query .= '-';
            }

            $query .= '(' . $subquery->__toString() . ')';

            if ($subquery->getBoost() != 1) {
                $query .= '^' . round($subquery->getBoost(), 4);
            }
        }

        return $query;
    }
}

Search/Lucene/Search/QueryEntry/Subquery.php000066600000004431151256604600015063 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_Index_Term */
require_once 'Zend/Search/Lucene/Index/Term.php';

/** Zend_Search_Lucene_Search_QueryEntry */
require_once 'Zend/Search/Lucene/Search/QueryEntry.php';

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_QueryEntry_Subquery extends Zend_Search_Lucene_Search_QueryEntry
{
    /**
     * Query
     *
     * @var Zend_Search_Lucene_Search_Query
     */
    private $_query;

    /**
     * Object constractor
     *
     * @param Zend_Search_Lucene_Search_Query $query
     */
    public function __construct(Zend_Search_Lucene_Search_Query $query)
    {
        $this->_query = $query;
    }

    /**
     * Process modifier ('~')
     *
     * @param mixed $parameter
     * @throws Zend_Search_Lucene_Search_QueryParserException
     */
    public function processFuzzyProximityModifier($parameter = null)
    {
        require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
        throw new Zend_Search_Lucene_Search_QueryParserException('\'~\' sign must follow term or phrase');
    }


    /**
     * Transform entry to a subquery
     *
     * @param string $encoding
     * @return Zend_Search_Lucene_Search_Query
     */
    public function getQuery($encoding)
    {
        $this->_query->setBoost($this->_boost);

        return $this->_query;
    }
}
Search/Lucene/Search/QueryEntry/Term.php000066600000014274151256604600014161 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_Index_Term */
require_once 'Zend/Search/Lucene/Index/Term.php';

/** Zend_Search_Lucene_Search_QueryEntry */
require_once 'Zend/Search/Lucene/Search/QueryEntry.php';

/** Zend_Search_Lucene_Analysis_Analyzer */
require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_QueryEntry_Term extends Zend_Search_Lucene_Search_QueryEntry
{
    /**
     * Term value
     *
     * @var string
     */
    private $_term;

    /**
     * Field
     *
     * @var string|null
     */
    private $_field;


    /**
     * Fuzzy search query
     *
     * @var boolean
     */
    private $_fuzzyQuery = false;

    /**
     * Similarity
     *
     * @var float
     */
    private $_similarity = 1.;


    /**
     * Object constractor
     *
     * @param string $term
     * @param string $field
     */
    public function __construct($term, $field)
    {
        $this->_term  = $term;
        $this->_field = $field;
    }

    /**
     * Process modifier ('~')
     *
     * @param mixed $parameter
     */
    public function processFuzzyProximityModifier($parameter = null)
    {
        $this->_fuzzyQuery = true;

        if ($parameter !== null) {
            $this->_similarity = $parameter;
        } else {
            $this->_similarity = Zend_Search_Lucene_Search_Query_Fuzzy::DEFAULT_MIN_SIMILARITY;
        }
    }

    /**
     * Transform entry to a subquery
     *
     * @param string $encoding
     * @return Zend_Search_Lucene_Search_Query
     * @throws Zend_Search_Lucene_Search_QueryParserException
     */
    public function getQuery($encoding)
    {
        if (strpos($this->_term, '?') !== false || strpos($this->_term, '*') !== false) {
            if ($this->_fuzzyQuery) {
                require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
                throw new Zend_Search_Lucene_Search_QueryParserException('Fuzzy search is not supported for terms with wildcards.');
            }

            $pattern = '';

            $subPatterns = explode('*', $this->_term);

            $astericFirstPass = true;
            foreach ($subPatterns as $subPattern) {
                if (!$astericFirstPass) {
                    $pattern .= '*';
                } else {
                    $astericFirstPass = false;
                }

                $subPatternsL2 = explode('?', $subPattern);

                $qMarkFirstPass = true;
                foreach ($subPatternsL2 as $subPatternL2) {
                    if (!$qMarkFirstPass) {
                        $pattern .= '?';
                    } else {
                        $qMarkFirstPass = false;
                    }

                    $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($subPatternL2, $encoding);
                    if (count($tokens) > 1) {
                        require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
                        throw new Zend_Search_Lucene_Search_QueryParserException('Wildcard search is supported only for non-multiple word terms');
                    }

                    foreach ($tokens as $token) {
                        $pattern .= $token->getTermText();
                    }
                }
            }

            $term  = new Zend_Search_Lucene_Index_Term($pattern, $this->_field);
            $query = new Zend_Search_Lucene_Search_Query_Wildcard($term);
            $query->setBoost($this->_boost);

            return $query;
        }

        $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_term, $encoding);

        if (count($tokens) == 0) {
            return new Zend_Search_Lucene_Search_Query_Insignificant();
        }

        if (count($tokens) == 1  && !$this->_fuzzyQuery) {
            $term  = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field);
            $query = new Zend_Search_Lucene_Search_Query_Term($term);
            $query->setBoost($this->_boost);

            return $query;
        }

        if (count($tokens) == 1  && $this->_fuzzyQuery) {
            $term  = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field);
            $query = new Zend_Search_Lucene_Search_Query_Fuzzy($term, $this->_similarity);
            $query->setBoost($this->_boost);

            return $query;
        }

        if ($this->_fuzzyQuery) {
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('Fuzzy search is supported only for non-multiple word terms');
        }

        //It's not empty or one term query
        $query = new Zend_Search_Lucene_Search_Query_MultiTerm();

        /**
         * @todo Process $token->getPositionIncrement() to support stemming, synonyms and other
         * analizer design features
         */
        foreach ($tokens as $token) {
            $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $this->_field);
            $query->addTerm($term, true); // all subterms are required
        }

        $query->setBoost($this->_boost);

        return $query;
    }
}
Search/Lucene/Search/QueryEntry/Phrase.php000066600000007712151256604600014473 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_Index_Term */
require_once 'Zend/Search/Lucene/Index/Term.php';

/** Zend_Search_Lucene_Search_QueryEntry */
require_once 'Zend/Search/Lucene/Search/QueryEntry.php';

/** Zend_Search_Lucene_Analysis_Analyzer */
require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Search_QueryEntry_Phrase extends Zend_Search_Lucene_Search_QueryEntry
{
    /**
     * Phrase value
     *
     * @var string
     */
    private $_phrase;

    /**
     * Field
     *
     * @var string|null
     */
    private $_field;


    /**
     * Proximity phrase query
     *
     * @var boolean
     */
    private $_proximityQuery = false;

    /**
     * Words distance, used for proximiti queries
     *
     * @var integer
     */
    private $_wordsDistance = 0;


    /**
     * Object constractor
     *
     * @param string $phrase
     * @param string $field
     */
    public function __construct($phrase, $field)
    {
        $this->_phrase = $phrase;
        $this->_field  = $field;
    }

    /**
     * Process modifier ('~')
     *
     * @param mixed $parameter
     */
    public function processFuzzyProximityModifier($parameter = null)
    {
        $this->_proximityQuery = true;

        if ($parameter !== null) {
            $this->_wordsDistance = $parameter;
        }
    }

    /**
     * Transform entry to a subquery
     *
     * @param string $encoding
     * @return Zend_Search_Lucene_Search_Query
     * @throws Zend_Search_Lucene_Search_QueryParserException
     */
    public function getQuery($encoding)
    {
        if (strpos($this->_phrase, '?') !== false || strpos($this->_phrase, '*') !== false) {
            require_once 'Zend/Search/Lucene/Search/QueryParserException.php';
            throw new Zend_Search_Lucene_Search_QueryParserException('Wildcards are only allowed in a single terms.');
        }

        $tokens = Zend_Search_Lucene_Analysis_Analyzer::getDefault()->tokenize($this->_phrase, $encoding);

        if (count($tokens) == 0) {
            return new Zend_Search_Lucene_Search_Query_Insignificant();
        }

        if (count($tokens) == 1) {
            $term  = new Zend_Search_Lucene_Index_Term($tokens[0]->getTermText(), $this->_field);
            $query = new Zend_Search_Lucene_Search_Query_Term($term);
            $query->setBoost($this->_boost);

            return $query;
        }

        //It's not empty or one term query
        $position = -1;
        $query = new Zend_Search_Lucene_Search_Query_Phrase();
        foreach ($tokens as $token) {
            $position += $token->getPositionIncrement();
            $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $this->_field);
            $query->addTerm($term, $position);
        }

        if ($this->_proximityQuery) {
            $query->setSlop($this->_wordsDistance);
        }

        $query->setBoost($this->_boost);

        return $query;
    }
}
Search/Lucene/Index/Writer.php000066600000106707151256604600012244 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter */
require_once 'Zend/Search/Lucene/Index/SegmentWriter/DocumentWriter.php';

/** Zend_Search_Lucene_Index_SegmentInfo */
require_once 'Zend/Search/Lucene/Index/SegmentInfo.php';

/** Zend_Search_Lucene_Index_SegmentMerger */
require_once 'Zend/Search/Lucene/Index/SegmentMerger.php';

/** Zend_Search_Lucene_LockManager */
require_once 'Zend/Search/Lucene/LockManager.php';



/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Index_Writer
{
    /**
     * @todo Implement Analyzer substitution
     * @todo Implement Zend_Search_Lucene_Storage_DirectoryRAM and Zend_Search_Lucene_Storage_FileRAM to use it for
     *       temporary index files
     * @todo Directory lock processing
     */

    /**
     * Number of documents required before the buffered in-memory
     * documents are written into a new Segment
     *
     * Default value is 10
     *
     * @var integer
     */
    public $maxBufferedDocs = 10;

    /**
     * Largest number of documents ever merged by addDocument().
     * Small values (e.g., less than 10,000) are best for interactive indexing,
     * as this limits the length of pauses while indexing to a few seconds.
     * Larger values are best for batched indexing and speedier searches.
     *
     * Default value is PHP_INT_MAX
     *
     * @var integer
     */
    public $maxMergeDocs = PHP_INT_MAX;

    /**
     * Determines how often segment indices are merged by addDocument().
     *
     * With smaller values, less RAM is used while indexing,
     * and searches on unoptimized indices are faster,
     * but indexing speed is slower.
     *
     * With larger values, more RAM is used during indexing,
     * and while searches on unoptimized indices are slower,
     * indexing is faster.
     *
     * Thus larger values (> 10) are best for batch index creation,
     * and smaller values (< 10) for indices that are interactively maintained.
     *
     * Default value is 10
     *
     * @var integer
     */
    public $mergeFactor = 10;

    /**
     * File system adapter.
     *
     * @var Zend_Search_Lucene_Storage_Directory
     */
    private $_directory = null;


    /**
     * Changes counter.
     *
     * @var integer
     */
    private $_versionUpdate = 0;

    /**
     * List of the segments, created by index writer
     * Array of Zend_Search_Lucene_Index_SegmentInfo objects
     *
     * @var array
     */
    private $_newSegments = array();

    /**
     * List of segments to be deleted on commit
     *
     * @var array
     */
    private $_segmentsToDelete = array();

    /**
     * Current segment to add documents
     *
     * @var Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter
     */
    private $_currentSegment = null;

    /**
     * Array of Zend_Search_Lucene_Index_SegmentInfo objects for this index.
     *
     * It's a reference to the corresponding Zend_Search_Lucene::$_segmentInfos array
     *
     * @var array Zend_Search_Lucene_Index_SegmentInfo
     */
    private $_segmentInfos;

    /**
     * Index target format version
     *
     * @var integer
     */
    private $_targetFormatVersion;

    /**
     * List of indexfiles extensions
     *
     * @var array
     */
    private static $_indexExtensions = array('.cfs' => '.cfs',
                                             '.cfx' => '.cfx',
                                             '.fnm' => '.fnm',
                                             '.fdx' => '.fdx',
                                             '.fdt' => '.fdt',
                                             '.tis' => '.tis',
                                             '.tii' => '.tii',
                                             '.frq' => '.frq',
                                             '.prx' => '.prx',
                                             '.tvx' => '.tvx',
                                             '.tvd' => '.tvd',
                                             '.tvf' => '.tvf',
                                             '.del' => '.del',
                                             '.sti' => '.sti' );


    /**
     * Create empty index
     *
     * @param Zend_Search_Lucene_Storage_Directory $directory
     * @param integer $generation
     * @param integer $nameCount
     */
    public static function createIndex(Zend_Search_Lucene_Storage_Directory $directory, $generation, $nameCount)
    {
        if ($generation == 0) {
            // Create index in pre-2.1 mode
            foreach ($directory->fileList() as $file) {
                if ($file == 'deletable' ||
                    $file == 'segments'  ||
                    isset(self::$_indexExtensions[ substr($file, strlen($file)-4)]) ||
                    preg_match('/\.f\d+$/i', $file) /* matches <segment_name>.f<decimal_nmber> file names */) {
                        $directory->deleteFile($file);
                    }
            }

            $segmentsFile = $directory->createFile('segments');
            $segmentsFile->writeInt((int)0xFFFFFFFF);

            // write version (is initialized by current time
            // $segmentsFile->writeLong((int)microtime(true));
            $version = microtime(true);
            $segmentsFile->writeInt((int)($version/((double)0xFFFFFFFF + 1)));
            $segmentsFile->writeInt((int)($version & 0xFFFFFFFF));

            // write name counter
            $segmentsFile->writeInt($nameCount);
            // write segment counter
            $segmentsFile->writeInt(0);

            $deletableFile = $directory->createFile('deletable');
            // write counter
            $deletableFile->writeInt(0);
        } else {
            $genFile = $directory->createFile('segments.gen');

            $genFile->writeInt((int)0xFFFFFFFE);
            // Write generation two times
            $genFile->writeLong($generation);
            $genFile->writeLong($generation);

            $segmentsFile = $directory->createFile(Zend_Search_Lucene::getSegmentFileName($generation));
            $segmentsFile->writeInt((int)0xFFFFFFFD);

            // write version (is initialized by current time
            // $segmentsFile->writeLong((int)microtime(true));
            $version = microtime(true);
            $segmentsFile->writeInt((int)($version/((double)0xFFFFFFFF + 1)));
            $segmentsFile->writeInt((int)($version & 0xFFFFFFFF));

            // write name counter
            $segmentsFile->writeInt($nameCount);
            // write segment counter
            $segmentsFile->writeInt(0);
        }
    }

    /**
     * Open the index for writing
     *
     * @param Zend_Search_Lucene_Storage_Directory $directory
     * @param array $segmentInfos
     * @param integer $targetFormatVersion
     * @param Zend_Search_Lucene_Storage_File $cleanUpLock
     */
    public function __construct(Zend_Search_Lucene_Storage_Directory $directory, &$segmentInfos, $targetFormatVersion)
    {
        $this->_directory           = $directory;
        $this->_segmentInfos        = &$segmentInfos;
        $this->_targetFormatVersion = $targetFormatVersion;
    }

    /**
     * Adds a document to this index.
     *
     * @param Zend_Search_Lucene_Document $document
     */
    public function addDocument(Zend_Search_Lucene_Document $document)
    {
        if ($this->_currentSegment === null) {
            $this->_currentSegment =
                new Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter($this->_directory, $this->_newSegmentName());
        }
        $this->_currentSegment->addDocument($document);

        if ($this->_currentSegment->count() >= $this->maxBufferedDocs) {
            $this->commit();
        }

        $this->_maybeMergeSegments();

        $this->_versionUpdate++;
    }


    /**
     * Check if we have anything to merge
     *
     * @return boolean
     */
    private function _hasAnythingToMerge()
    {
        $segmentSizes = array();
        foreach ($this->_segmentInfos as $segName => $segmentInfo) {
            $segmentSizes[$segName] = $segmentInfo->count();
        }

        $mergePool   = array();
        $poolSize    = 0;
        $sizeToMerge = $this->maxBufferedDocs;
        asort($segmentSizes, SORT_NUMERIC);
        foreach ($segmentSizes as $segName => $size) {
            // Check, if segment comes into a new merging block
            while ($size >= $sizeToMerge) {
                // Merge previous block if it's large enough
                if ($poolSize >= $sizeToMerge) {
                    return true;
                }
                $mergePool   = array();
                $poolSize    = 0;

                $sizeToMerge *= $this->mergeFactor;

                if ($sizeToMerge > $this->maxMergeDocs) {
                    return false;
                }
            }

            $mergePool[] = $this->_segmentInfos[$segName];
            $poolSize += $size;
        }

        if ($poolSize >= $sizeToMerge) {
            return true;
        }

        return false;
    }

    /**
     * Merge segments if necessary
     */
    private function _maybeMergeSegments()
    {
        if (Zend_Search_Lucene_LockManager::obtainOptimizationLock($this->_directory) === false) {
            return;
        }

        if (!$this->_hasAnythingToMerge()) {
            Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory);
            return;
        }

        // Update segments list to be sure all segments are not merged yet by another process
        //
        // Segment merging functionality is concentrated in this class and surrounded
        // by optimization lock obtaining/releasing.
        // _updateSegments() refreshes segments list from the latest index generation.
        // So only new segments can be added to the index while we are merging some already existing
        // segments.
        // Newly added segments will be also included into the index by the _updateSegments() call
        // either by another process or by the current process with the commit() call at the end of _mergeSegments() method.
        // That's guaranteed by the serialisation of _updateSegments() execution using exclusive locks.
        $this->_updateSegments();

        // Perform standard auto-optimization procedure
        $segmentSizes = array();
        foreach ($this->_segmentInfos as $segName => $segmentInfo) {
            $segmentSizes[$segName] = $segmentInfo->count();
        }

        $mergePool   = array();
        $poolSize    = 0;
        $sizeToMerge = $this->maxBufferedDocs;
        asort($segmentSizes, SORT_NUMERIC);
        foreach ($segmentSizes as $segName => $size) {
            // Check, if segment comes into a new merging block
            while ($size >= $sizeToMerge) {
                // Merge previous block if it's large enough
                if ($poolSize >= $sizeToMerge) {
                    $this->_mergeSegments($mergePool);
                }
                $mergePool   = array();
                $poolSize    = 0;

                $sizeToMerge *= $this->mergeFactor;

                if ($sizeToMerge > $this->maxMergeDocs) {
                    Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory);
                    return;
                }
            }

            $mergePool[] = $this->_segmentInfos[$segName];
            $poolSize += $size;
        }

        if ($poolSize >= $sizeToMerge) {
            $this->_mergeSegments($mergePool);
        }

        Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory);
    }

    /**
     * Merge specified segments
     *
     * $segments is an array of SegmentInfo objects
     *
     * @param array $segments
     */
    private function _mergeSegments($segments)
    {
        $newName = $this->_newSegmentName();
        $merger = new Zend_Search_Lucene_Index_SegmentMerger($this->_directory,
                                                             $newName);
        foreach ($segments as $segmentInfo) {
            $merger->addSource($segmentInfo);
            $this->_segmentsToDelete[$segmentInfo->getName()] = $segmentInfo->getName();
        }

        $newSegment = $merger->merge();
        if ($newSegment !== null) {
            $this->_newSegments[$newSegment->getName()] = $newSegment;
        }

        $this->commit();
    }

    /**
     * Update segments file by adding current segment to a list
     *
     * @throws Zend_Search_Lucene_Exception
     */
    private function _updateSegments()
    {
        // Get an exclusive index lock
        Zend_Search_Lucene_LockManager::obtainWriteLock($this->_directory);

        // Write down changes for the segments
        foreach ($this->_segmentInfos as $segInfo) {
            $segInfo->writeChanges();
        }


        $generation = Zend_Search_Lucene::getActualGeneration($this->_directory);
        $segmentsFile   = $this->_directory->getFileObject(Zend_Search_Lucene::getSegmentFileName($generation), false);
        $newSegmentFile = $this->_directory->createFile(Zend_Search_Lucene::getSegmentFileName(++$generation), false);

        try {
            $genFile = $this->_directory->getFileObject('segments.gen', false);
        } catch (Zend_Search_Lucene_Exception $e) {
            if (strpos($e->getMessage(), 'is not readable') !== false) {
                $genFile = $this->_directory->createFile('segments.gen');
            } else {
                throw $e;
            }
        }

        $genFile->writeInt((int)0xFFFFFFFE);
        // Write generation (first copy)
        $genFile->writeLong($generation);

        try {
            // Write format marker
            if ($this->_targetFormatVersion == Zend_Search_lucene::FORMAT_2_1) {
                $newSegmentFile->writeInt((int)0xFFFFFFFD);
            } else if ($this->_targetFormatVersion == Zend_Search_lucene::FORMAT_2_3) {
                $newSegmentFile->writeInt((int)0xFFFFFFFC);
            }

            // Read src file format identifier
            $format = $segmentsFile->readInt();
            if ($format == (int)0xFFFFFFFF) {
                $srcFormat = Zend_Search_Lucene::FORMAT_PRE_2_1;
            } else if ($format == (int)0xFFFFFFFD) {
                $srcFormat = Zend_Search_Lucene::FORMAT_2_1;
            } else if ($format == (int)0xFFFFFFFC) {
                $srcFormat = Zend_Search_Lucene::FORMAT_2_3;
            } else {
                throw new Zend_Search_Lucene_Exception('Unsupported segments file format');
            }

            // $version = $segmentsFile->readLong() + $this->_versionUpdate;
            // Process version on 32-bit platforms
            $versionHigh = $segmentsFile->readInt();
            $versionLow  = $segmentsFile->readInt();
            $version = $versionHigh * ((double)0xFFFFFFFF + 1) +
                       (($versionLow < 0)? (double)0xFFFFFFFF - (-1 - $versionLow) : $versionLow);
            $version += $this->_versionUpdate;
            $this->_versionUpdate = 0;
            $newSegmentFile->writeInt((int)($version/((double)0xFFFFFFFF + 1)));
            $newSegmentFile->writeInt((int)($version & 0xFFFFFFFF));

            // Write segment name counter
            $newSegmentFile->writeInt($segmentsFile->readInt());

            // Get number of segments offset
            $numOfSegmentsOffset = $newSegmentFile->tell();
            // Write dummy data (segment counter)
            $newSegmentFile->writeInt(0);

            // Read number of segemnts
            $segmentsCount = $segmentsFile->readInt();

            $segments = array();
            for ($count = 0; $count < $segmentsCount; $count++) {
                $segName = $segmentsFile->readString();
                $segSize = $segmentsFile->readInt();

                if ($srcFormat == Zend_Search_Lucene::FORMAT_PRE_2_1) {
                    // pre-2.1 index format
                    $delGenHigh        = 0;
                    $delGenLow         = 0;
                    $hasSingleNormFile = false;
                    $numField          = (int)0xFFFFFFFF;
                    $isCompoundByte    = 0;
                    $docStoreOptions   = null;
                } else {
                    //$delGen          = $segmentsFile->readLong();
                    $delGenHigh        = $segmentsFile->readInt();
                    $delGenLow         = $segmentsFile->readInt();

                    if ($srcFormat == Zend_Search_Lucene::FORMAT_2_3) {
                        $docStoreOffset = $segmentsFile->readInt();

                        if ($docStoreOffset != -1) {
                            $docStoreSegment        = $segmentsFile->readString();
                            $docStoreIsCompoundFile = $segmentsFile->readByte();

                            $docStoreOptions = array('offset'     => $docStoreOffset,
                                                     'segment'    => $docStoreSegment,
                                                     'isCompound' => ($docStoreIsCompoundFile == 1));
                        } else {
                            $docStoreOptions = null;
                        }
                    } else {
                        $docStoreOptions = null;
                    }

                    $hasSingleNormFile = $segmentsFile->readByte();
                    $numField          = $segmentsFile->readInt();

                    $normGens = array();
                    if ($numField != (int)0xFFFFFFFF) {
                        for ($count1 = 0; $count1 < $numField; $count1++) {
                            $normGens[] = $segmentsFile->readLong();
                        }
                    }
                    $isCompoundByte    = $segmentsFile->readByte();
                }

                if (!in_array($segName, $this->_segmentsToDelete)) {
                    // Load segment if necessary
                    if (!isset($this->_segmentInfos[$segName])) {
                        if (PHP_INT_SIZE > 4) {
                        	// 64-bit system
                        	$delGen = $delGenHigh << 32  |
                        	          $delGenLow;
                        } else {
                        	$delGen = $delGenHigh * ((double)0xFFFFFFFF + 1) +
                                         (($delGenLow < 0)? (double)0xFFFFFFFF - (-1 - $delGenLow) : $delGenLow);
                        }
                        if ($isCompoundByte == 0xFF) {
                            // The segment is not a compound file
                            $isCompound = false;
                        } else if ($isCompoundByte == 0x00) {
                            // The status is unknown
                            $isCompound = null;
                        } else if ($isCompoundByte == 0x01) {
                            // The segment is a compound file
                            $isCompound = true;
                        }

                        $this->_segmentInfos[$segName] =
                                    new Zend_Search_Lucene_Index_SegmentInfo($this->_directory,
                                                                             $segName,
                                                                             $segSize,
                                                                             $delGen,
                                                                             $docStoreOptions,
                                                                             $hasSingleNormFile,
                                                                             $isCompound);
                    } else {
                        // Retrieve actual deletions file generation number
                        $delGen = $this->_segmentInfos[$segName]->getDelGen();

                        if ($delGen >= 0) {
                            if (PHP_INT_SIZE > 4) {
                                // 64-bit system
                                $delGenHigh = $delGen >> 32  & 0xFFFFFFFF;
                                $delGenLow  = $delGen        & 0xFFFFFFFF;
                            } else {
                                $delGenHigh = (int)($delGen/((double)0xFFFFFFFF + 1));
                                $delGenLow  =(int)($delGen & 0xFFFFFFFF);
                            }
                        } else {
                            $delGenHigh = $delGenLow = (int)0xFFFFFFFF;
                        }
                    }

                    $newSegmentFile->writeString($segName);
                    $newSegmentFile->writeInt($segSize);
                    $newSegmentFile->writeInt($delGenHigh);
                    $newSegmentFile->writeInt($delGenLow);
                    if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) {
                        if ($docStoreOptions !== null) {
                            $newSegmentFile->writeInt($docStoreOffset);
                            $newSegmentFile->writeString($docStoreSegment);
                            $newSegmentFile->writeByte($docStoreIsCompoundFile);
                        } else {
                            // Set DocStoreOffset to -1
                            $newSegmentFile->writeInt((int)0xFFFFFFFF);
                        }
                    } else if ($docStoreOptions !== null) {
                        // Release index write lock
                        Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory);

                        throw new Zend_Search_Lucene_Exception('Index conversion to lower format version is not supported.');
                    }

                    $newSegmentFile->writeByte($hasSingleNormFile);
                    $newSegmentFile->writeInt($numField);
                    if ($numField != (int)0xFFFFFFFF) {
                        foreach ($normGens as $normGen) {
                            $newSegmentFile->writeLong($normGen);
                        }
                    }
                    $newSegmentFile->writeByte($isCompoundByte);

                    $segments[$segName] = $segSize;
                }
            }
            $segmentsFile->close();

            $segmentsCount = count($segments) + count($this->_newSegments);

            foreach ($this->_newSegments as $segName => $segmentInfo) {
                $newSegmentFile->writeString($segName);
                $newSegmentFile->writeInt($segmentInfo->count());

                // delete file generation: -1 (there is no delete file yet)
                $newSegmentFile->writeInt((int)0xFFFFFFFF);$newSegmentFile->writeInt((int)0xFFFFFFFF);
                if ($this->_targetFormatVersion == Zend_Search_Lucene::FORMAT_2_3) {
                    // docStoreOffset: -1 (segment doesn't use shared doc store)
                    $newSegmentFile->writeInt((int)0xFFFFFFFF);
                }
                // HasSingleNormFile
                $newSegmentFile->writeByte($segmentInfo->hasSingleNormFile());
                // NumField
                $newSegmentFile->writeInt((int)0xFFFFFFFF);
                // IsCompoundFile
                $newSegmentFile->writeByte($segmentInfo->isCompound() ? 1 : -1);

                $segments[$segmentInfo->getName()] = $segmentInfo->count();
                $this->_segmentInfos[$segName] = $segmentInfo;
            }
            $this->_newSegments = array();

            $newSegmentFile->seek($numOfSegmentsOffset);
            $newSegmentFile->writeInt($segmentsCount);  // Update segments count
            $newSegmentFile->close();
        } catch (Exception $e) {
            /** Restore previous index generation */
            $generation--;
            $genFile->seek(4, SEEK_SET);
            // Write generation number twice
            $genFile->writeLong($generation); $genFile->writeLong($generation);

            // Release index write lock
            Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory);

            // Throw the exception
            throw $e;
        }

        // Write generation (second copy)
        $genFile->writeLong($generation);


        // Check if another update or read process is not running now
        // If yes, skip clean-up procedure
        if (Zend_Search_Lucene_LockManager::escalateReadLock($this->_directory)) {
            /**
             * Clean-up directory
             */
            $filesToDelete = array();
            $filesTypes    = array();
            $filesNumbers  = array();

            // list of .del files of currently used segments
            // each segment can have several generations of .del files
            // only last should not be deleted
            $delFiles = array();

            foreach ($this->_directory->fileList() as $file) {
                if ($file == 'deletable') {
                    // 'deletable' file
                    $filesToDelete[] = $file;
                    $filesTypes[]    = 0; // delete this file first, since it's not used starting from Lucene v2.1
                    $filesNumbers[]  = 0;
                } else if ($file == 'segments') {
                    // 'segments' file
                    $filesToDelete[] = $file;
                    $filesTypes[]    = 1; // second file to be deleted "zero" version of segments file (Lucene pre-2.1)
                    $filesNumbers[]  = 0;
                } else if (preg_match('/^segments_[a-zA-Z0-9]+$/i', $file)) {
                    // 'segments_xxx' file
                    // Check if it's not a just created generation file
                    if ($file != Zend_Search_Lucene::getSegmentFileName($generation)) {
                        $filesToDelete[] = $file;
                        $filesTypes[]    = 2; // first group of files for deletions
                        $filesNumbers[]  = (int)base_convert(substr($file, 9), 36, 10); // ordered by segment generation numbers
                    }
                } else if (preg_match('/(^_([a-zA-Z0-9]+))\.f\d+$/i', $file, $matches)) {
                    // one of per segment files ('<segment_name>.f<decimal_number>')
                    // Check if it's not one of the segments in the current segments set
                    if (!isset($segments[$matches[1]])) {
                        $filesToDelete[] = $file;
                        $filesTypes[]    = 3; // second group of files for deletions
                        $filesNumbers[]  = (int)base_convert($matches[2], 36, 10); // order by segment number
                    }
                } else if (preg_match('/(^_([a-zA-Z0-9]+))(_([a-zA-Z0-9]+))\.del$/i', $file, $matches)) {
                    // one of per segment files ('<segment_name>_<del_generation>.del' where <segment_name> is '_<segment_number>')
                    // Check if it's not one of the segments in the current segments set
                    if (!isset($segments[$matches[1]])) {
                        $filesToDelete[] = $file;
                        $filesTypes[]    = 3; // second group of files for deletions
                        $filesNumbers[]  = (int)base_convert($matches[2], 36, 10); // order by segment number
                    } else {
                        $segmentNumber = (int)base_convert($matches[2], 36, 10);
                        $delGeneration = (int)base_convert($matches[4], 36, 10);
                        if (!isset($delFiles[$segmentNumber])) {
                            $delFiles[$segmentNumber] = array();
                        }
                        $delFiles[$segmentNumber][$delGeneration] = $file;
                    }
                } else if (isset(self::$_indexExtensions[substr($file, strlen($file)-4)])) {
                    // one of per segment files ('<segment_name>.<ext>')
                    $segmentName = substr($file, 0, strlen($file) - 4);
                    // Check if it's not one of the segments in the current segments set
                    if (!isset($segments[$segmentName])  &&
                        ($this->_currentSegment === null  ||  $this->_currentSegment->getName() != $segmentName)) {
                        $filesToDelete[] = $file;
                        $filesTypes[]    = 3; // second group of files for deletions
                        $filesNumbers[]  = (int)base_convert(substr($file, 1 /* skip '_' */, strlen($file)-5), 36, 10); // order by segment number
                    }
                }
            }

            $maxGenNumber = 0;
            // process .del files of currently used segments
            foreach ($delFiles as $segmentNumber => $segmentDelFiles) {
                ksort($delFiles[$segmentNumber], SORT_NUMERIC);
                array_pop($delFiles[$segmentNumber]); // remove last delete file generation from candidates for deleting

                end($delFiles[$segmentNumber]);
                $lastGenNumber = key($delFiles[$segmentNumber]);
                if ($lastGenNumber > $maxGenNumber) {
                    $maxGenNumber = $lastGenNumber;
                }
            }
            foreach ($delFiles as $segmentNumber => $segmentDelFiles) {
                foreach ($segmentDelFiles as $delGeneration => $file) {
                        $filesToDelete[] = $file;
                        $filesTypes[]    = 4; // third group of files for deletions
                        $filesNumbers[]  = $segmentNumber*$maxGenNumber + $delGeneration; // order by <segment_number>,<del_generation> pair
                }
            }

            // Reorder files for deleting
            array_multisort($filesTypes,    SORT_ASC, SORT_NUMERIC,
                            $filesNumbers,  SORT_ASC, SORT_NUMERIC,
                            $filesToDelete, SORT_ASC, SORT_STRING);

            foreach ($filesToDelete as $file) {
                try {
                    /** Skip shared docstore segments deleting */
                    /** @todo Process '.cfx' files to check if them are already unused */
                    if (substr($file, strlen($file)-4) != '.cfx') {
                        $this->_directory->deleteFile($file);
                    }
                } catch (Zend_Search_Lucene_Exception $e) {
                    if (strpos($e->getMessage(), 'Can\'t delete file') === false) {
                        // That's not "file is under processing or already deleted" exception
                        // Pass it through
                        throw $e;
                    }
                }
            }

            // Return read lock into the previous state
            Zend_Search_Lucene_LockManager::deEscalateReadLock($this->_directory);
        } else {
            // Only release resources if another index reader is running now
            foreach ($this->_segmentsToDelete as $segName) {
                foreach (self::$_indexExtensions as $ext) {
                    $this->_directory->purgeFile($segName . $ext);
                }
            }
        }

        // Clean-up _segmentsToDelete container
        $this->_segmentsToDelete = array();


        // Release index write lock
        Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory);

        // Remove unused segments from segments list
        foreach ($this->_segmentInfos as $segName => $segmentInfo) {
            if (!isset($segments[$segName])) {
                unset($this->_segmentInfos[$segName]);
            }
        }
    }

    /**
     * Commit current changes
     */
    public function commit()
    {
        if ($this->_currentSegment !== null) {
            $newSegment = $this->_currentSegment->close();
            if ($newSegment !== null) {
                $this->_newSegments[$newSegment->getName()] = $newSegment;
            }
            $this->_currentSegment = null;
        }

        $this->_updateSegments();
    }


    /**
     * Merges the provided indexes into this index.
     *
     * @param array $readers
     * @return void
     */
    public function addIndexes($readers)
    {
        /**
         * @todo implementation
         */
    }

    /**
     * Merges all segments together into new one
     *
     * Returns true on success and false if another optimization or auto-optimization process
     * is running now
     *
     * @return boolean
     */
    public function optimize()
    {
        if (Zend_Search_Lucene_LockManager::obtainOptimizationLock($this->_directory) === false) {
            return false;
        }

        // Update segments list to be sure all segments are not merged yet by another process
        //
        // Segment merging functionality is concentrated in this class and surrounded
        // by optimization lock obtaining/releasing.
        // _updateSegments() refreshes segments list from the latest index generation.
        // So only new segments can be added to the index while we are merging some already existing
        // segments.
        // Newly added segments will be also included into the index by the _updateSegments() call
        // either by another process or by the current process with the commit() call at the end of _mergeSegments() method.
        // That's guaranteed by the serialisation of _updateSegments() execution using exclusive locks.
        $this->_updateSegments();

        $this->_mergeSegments($this->_segmentInfos);

        Zend_Search_Lucene_LockManager::releaseOptimizationLock($this->_directory);

        return true;
    }

    /**
     * Get name for new segment
     *
     * @return string
     */
    private function _newSegmentName()
    {
        Zend_Search_Lucene_LockManager::obtainWriteLock($this->_directory);

        $generation = Zend_Search_Lucene::getActualGeneration($this->_directory);
        $segmentsFile = $this->_directory->getFileObject(Zend_Search_Lucene::getSegmentFileName($generation), false);

        $segmentsFile->seek(12); // 12 = 4 (int, file format marker) + 8 (long, index version)
        $segmentNameCounter = $segmentsFile->readInt();

        $segmentsFile->seek(12); // 12 = 4 (int, file format marker) + 8 (long, index version)
        $segmentsFile->writeInt($segmentNameCounter + 1);

        // Flash output to guarantee that wrong value will not be loaded between unlock and
        // return (which calls $segmentsFile destructor)
        $segmentsFile->flush();

        Zend_Search_Lucene_LockManager::releaseWriteLock($this->_directory);

        return '_' . base_convert($segmentNameCounter, 10, 36);
    }

}
Search/Lucene/Index/Term.php000066600000007343151256604600011673 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * A Term represents a word from text.  This is the unit of search.  It is
 * composed of two elements, the text of the word, as a string, and the name of
 * the field that the text occured in, an interned string.
 *
 * Note that terms may represent more than words from text fields, but also
 * things like dates, email addresses, urls, etc.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Index_Term
{
    /**
     * Field name or field number (depending from context)
     *
     * @var mixed
     */
    public $field;

    /**
     * Term value
     *
     * @var string
     */
    public $text;


    /**
     * Object constructor
     */
    public function __construct($text, $field = null)
    {
        $this->field = ($field === null)?  Zend_Search_Lucene::getDefaultSearchField() : $field;
        $this->text  = $text;
    }


    /**
     * Returns term key
     *
     * @return string
     */
    public function key()
    {
        return $this->field . chr(0) . $this->text;
    }

    /**
     * Get term prefix
     *
     * @param string $str
     * @param integer $length
     * @return string
     */
    public static function getPrefix($str, $length)
    {
        $prefixBytes = 0;
        $prefixChars = 0;
        while ($prefixBytes < strlen($str)  &&  $prefixChars < $length) {
            $charBytes = 1;
            if ((ord($str[$prefixBytes]) & 0xC0) == 0xC0) {
                $charBytes++;
                if (ord($str[$prefixBytes]) & 0x20 ) {
                    $charBytes++;
                    if (ord($str[$prefixBytes]) & 0x10 ) {
                        $charBytes++;
                    }
                }
            }

            if ($prefixBytes + $charBytes > strlen($str)) {
                // wrong character
                break;
            }

            $prefixChars++;
            $prefixBytes += $charBytes;
        }

        return substr($str, 0, $prefixBytes);
    }

    /**
     * Get UTF-8 string length
     *
     * @param string $str
     * @return string
     */
    public static function getLength($str)
    {
        $bytes = 0;
        $chars = 0;
        while ($bytes < strlen($str)) {
            $charBytes = 1;
            if ((ord($str[$bytes]) & 0xC0) == 0xC0) {
                $charBytes++;
                if (ord($str[$bytes]) & 0x20 ) {
                    $charBytes++;
                    if (ord($str[$bytes]) & 0x10 ) {
                        $charBytes++;
                    }
                }
            }

            if ($bytes + $charBytes > strlen($str)) {
                // wrong character
                break;
            }

            $chars++;
            $bytes += $charBytes;
        }

        return $chars;
    }
}

Search/Lucene/Index/DictionaryLoader.php000066600000024671151256604600014223 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Dictionary loader
 *
 * It's a dummy class which is created to encapsulate non-good structured code.
 * Manual "method inlining" is performed to increase dictionary index loading operation
 * which is major bottelneck for search performance.
 *
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Index_DictionaryLoader
{
    /**
     * Dictionary index loader.
     *
     * It takes a string which is actually <segment_name>.tii index file data and
     * returns two arrays - term and tremInfo lists.
     *
     * See Zend_Search_Lucene_Index_SegmintInfo class for details
     *
     * @param string $data
     * @return array
     * @throws Zend_Search_Lucene_Exception
     */
    public static function load($data)
    {
        $termDictionary = array();
        $termInfos      = array();
        $pos = 0;

        // $tiVersion = $tiiFile->readInt();
        $tiVersion = ord($data[0]) << 24 | ord($data[1]) << 16 | ord($data[2]) << 8  | ord($data[3]);
        $pos += 4;
        if ($tiVersion != (int)0xFFFFFFFE /* pre-2.1 format */ &&
            $tiVersion != (int)0xFFFFFFFD /* 2.1+ format    */) {
                require_once 'Zend/Search/Lucene/Exception.php';
                throw new Zend_Search_Lucene_Exception('Wrong TermInfoIndexFile file format');
        }

        // $indexTermCount = $tiiFile->readLong();
        if (PHP_INT_SIZE > 4) {
            $indexTermCount = ord($data[$pos]) << 56  |
                              ord($data[$pos+1]) << 48  |
                              ord($data[$pos+2]) << 40  |
                              ord($data[$pos+3]) << 32  |
                              ord($data[$pos+4]) << 24  |
                              ord($data[$pos+5]) << 16  |
                              ord($data[$pos+6]) << 8   |
                              ord($data[$pos+7]);
        } else {
            if ((ord($data[$pos])            != 0) ||
                (ord($data[$pos+1])          != 0) ||
                (ord($data[$pos+2])          != 0) ||
                (ord($data[$pos+3])          != 0) ||
                ((ord($data[$pos+4]) & 0x80) != 0)) {
                    require_once 'Zend/Search/Lucene/Exception.php';
                    throw new Zend_Search_Lucene_Exception('Largest supported segment size (for 32-bit mode) is 2Gb');
                 }

            $indexTermCount = ord($data[$pos+4]) << 24  |
                              ord($data[$pos+5]) << 16  |
                              ord($data[$pos+6]) << 8   |
                              ord($data[$pos+7]);
        }
        $pos += 8;

        //                  $tiiFile->readInt();  // IndexInterval
        $pos += 4;

        // $skipInterval   = $tiiFile->readInt();
        $skipInterval = ord($data[$pos]) << 24 | ord($data[$pos+1]) << 16 | ord($data[$pos+2]) << 8  | ord($data[$pos+3]);
        $pos += 4;
        if ($indexTermCount < 1) {
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Wrong number of terms in a term dictionary index');
        }

        if ($tiVersion == (int)0xFFFFFFFD /* 2.1+ format */) {
            /* Skip MaxSkipLevels value */
            $pos += 4;
        }

        $prevTerm     = '';
        $freqPointer  =  0;
        $proxPointer  =  0;
        $indexPointer =  0;
        for ($count = 0; $count < $indexTermCount; $count++) {
            //$termPrefixLength = $tiiFile->readVInt();
            $nbyte = ord($data[$pos++]);
            $termPrefixLength = $nbyte & 0x7F;
            for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
                $nbyte = ord($data[$pos++]);
                $termPrefixLength |= ($nbyte & 0x7F) << $shift;
            }

            // $termSuffix       = $tiiFile->readString();
            $nbyte = ord($data[$pos++]);
            $len = $nbyte & 0x7F;
            for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
                $nbyte = ord($data[$pos++]);
                $len |= ($nbyte & 0x7F) << $shift;
            }
            if ($len == 0) {
                $termSuffix = '';
            } else {
                $termSuffix = substr($data, $pos, $len);
                $pos += $len;
                for ($count1 = 0; $count1 < $len; $count1++ ) {
                    if (( ord($termSuffix[$count1]) & 0xC0 ) == 0xC0) {
                        $addBytes = 1;
                        if (ord($termSuffix[$count1]) & 0x20 ) {
                            $addBytes++;

                            // Never used for Java Lucene created index.
                            // Java2 doesn't encode strings in four bytes
                            if (ord($termSuffix[$count1]) & 0x10 ) {
                                $addBytes++;
                            }
                        }
                        $termSuffix .= substr($data, $pos, $addBytes);
                        $pos += $addBytes;
                        $len += $addBytes;

                        // Check for null character. Java2 encodes null character
                        // in two bytes.
                        if (ord($termSuffix[$count1]) == 0xC0 &&
                            ord($termSuffix[$count1+1]) == 0x80   ) {
                            $termSuffix[$count1] = 0;
                            $termSuffix = substr($termSuffix,0,$count1+1)
                                        . substr($termSuffix,$count1+2);
                        }
                        $count1 += $addBytes;
                    }
                }
            }

            // $termValue        = Zend_Search_Lucene_Index_Term::getPrefix($prevTerm, $termPrefixLength) . $termSuffix;
            $pb = 0; $pc = 0;
            while ($pb < strlen($prevTerm)  &&  $pc < $termPrefixLength) {
                $charBytes = 1;
                if ((ord($prevTerm[$pb]) & 0xC0) == 0xC0) {
                    $charBytes++;
                    if (ord($prevTerm[$pb]) & 0x20 ) {
                        $charBytes++;
                        if (ord($prevTerm[$pb]) & 0x10 ) {
                            $charBytes++;
                        }
                    }
                }

                if ($pb + $charBytes > strlen($data)) {
                    // wrong character
                    break;
                }

                $pc++;
                $pb += $charBytes;
            }
            $termValue = substr($prevTerm, 0, $pb) . $termSuffix;

            // $termFieldNum     = $tiiFile->readVInt();
            $nbyte = ord($data[$pos++]);
            $termFieldNum = $nbyte & 0x7F;
            for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
                $nbyte = ord($data[$pos++]);
                $termFieldNum |= ($nbyte & 0x7F) << $shift;
            }

            // $docFreq          = $tiiFile->readVInt();
            $nbyte = ord($data[$pos++]);
            $docFreq = $nbyte & 0x7F;
            for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
                $nbyte = ord($data[$pos++]);
                $docFreq |= ($nbyte & 0x7F) << $shift;
            }

            // $freqPointer     += $tiiFile->readVInt();
            $nbyte = ord($data[$pos++]);
            $vint = $nbyte & 0x7F;
            for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
                $nbyte = ord($data[$pos++]);
                $vint |= ($nbyte & 0x7F) << $shift;
            }
            $freqPointer += $vint;

            // $proxPointer     += $tiiFile->readVInt();
            $nbyte = ord($data[$pos++]);
            $vint = $nbyte & 0x7F;
            for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
                $nbyte = ord($data[$pos++]);
                $vint |= ($nbyte & 0x7F) << $shift;
            }
            $proxPointer += $vint;

            if( $docFreq >= $skipInterval ) {
                // $skipDelta = $tiiFile->readVInt();
                $nbyte = ord($data[$pos++]);
                $vint = $nbyte & 0x7F;
                for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
                    $nbyte = ord($data[$pos++]);
                    $vint |= ($nbyte & 0x7F) << $shift;
                }
                $skipDelta = $vint;
            } else {
                $skipDelta = 0;
            }

            // $indexPointer += $tiiFile->readVInt();
            $nbyte = ord($data[$pos++]);
            $vint = $nbyte & 0x7F;
            for ($shift=7; ($nbyte & 0x80) != 0; $shift += 7) {
                $nbyte = ord($data[$pos++]);
                $vint |= ($nbyte & 0x7F) << $shift;
            }
            $indexPointer += $vint;


            // $this->_termDictionary[] =  new Zend_Search_Lucene_Index_Term($termValue, $termFieldNum);
            $termDictionary[] = array($termFieldNum, $termValue);

            $termInfos[] =
                 // new Zend_Search_Lucene_Index_TermInfo($docFreq, $freqPointer, $proxPointer, $skipDelta, $indexPointer);
                 array($docFreq, $freqPointer, $proxPointer, $skipDelta, $indexPointer);

            $prevTerm = $termValue;
        }

        // Check special index entry mark
        if ($termDictionary[0][0] != (int)0xFFFFFFFF) {
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Wrong TermInfoIndexFile file format');
        } else if (PHP_INT_SIZE > 4){
            // Treat 64-bit 0xFFFFFFFF as -1
            $termDictionary[0][0] = -1;
        }

        return array(&$termDictionary, &$termInfos);
    }
}

Search/Lucene/Index/SegmentWriter/DocumentWriter.php000066600000017641151256604600016540 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_Analysis_Analyzer */
require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';

/** Zend_Search_Lucene_Index_SegmentWriter */
require_once 'Zend/Search/Lucene/Index/SegmentWriter.php';

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Index_SegmentWriter_DocumentWriter extends Zend_Search_Lucene_Index_SegmentWriter
{
    /**
     * Term Dictionary
     * Array of the Zend_Search_Lucene_Index_Term objects
     * Corresponding Zend_Search_Lucene_Index_TermInfo object stored in the $_termDictionaryInfos
     *
     * @var array
     */
    protected $_termDictionary;

    /**
     * Documents, which contain the term
     *
     * @var array
     */
    protected $_termDocs;

    /**
     * Object constructor.
     *
     * @param Zend_Search_Lucene_Storage_Directory $directory
     * @param string $name
     */
    public function __construct(Zend_Search_Lucene_Storage_Directory $directory, $name)
    {
        parent::__construct($directory, $name);

        $this->_termDocs       = array();
        $this->_termDictionary = array();
    }


    /**
     * Adds a document to this segment.
     *
     * @param Zend_Search_Lucene_Document $document
     * @throws Zend_Search_Lucene_Exception
     */
    public function addDocument(Zend_Search_Lucene_Document $document)
    {
        $storedFields = array();
        $docNorms     = array();
        $similarity   = Zend_Search_Lucene_Search_Similarity::getDefault();

        foreach ($document->getFieldNames() as $fieldName) {
            $field = $document->getField($fieldName);
            $this->addField($field);

            if ($field->storeTermVector) {
                /**
                 * @todo term vector storing support
                 */
                require_once 'Zend/Search/Lucene/Exception.php';
                throw new Zend_Search_Lucene_Exception('Store term vector functionality is not supported yet.');
            }

            if ($field->isIndexed) {
                if ($field->isTokenized) {
                    $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
                    $analyzer->setInput($field->value, $field->encoding);

                    $position     = 0;
                    $tokenCounter = 0;
                    while (($token = $analyzer->nextToken()) !== null) {
                        $tokenCounter++;

                        $term = new Zend_Search_Lucene_Index_Term($token->getTermText(), $field->name);
                        $termKey = $term->key();

                        if (!isset($this->_termDictionary[$termKey])) {
                            // New term
                            $this->_termDictionary[$termKey] = $term;
                            $this->_termDocs[$termKey] = array();
                            $this->_termDocs[$termKey][$this->_docCount] = array();
                        } else if (!isset($this->_termDocs[$termKey][$this->_docCount])) {
                            // Existing term, but new term entry
                            $this->_termDocs[$termKey][$this->_docCount] = array();
                        }
                        $position += $token->getPositionIncrement();
                        $this->_termDocs[$termKey][$this->_docCount][] = $position;
                    }

                    $docNorms[$field->name] = chr($similarity->encodeNorm( $similarity->lengthNorm($field->name,
                                                                                                   $tokenCounter)*
                                                                           $document->boost*
                                                                           $field->boost ));
                } else {
                    $term = new Zend_Search_Lucene_Index_Term($field->getUtf8Value(), $field->name);
                    $termKey = $term->key();

                    if (!isset($this->_termDictionary[$termKey])) {
                        // New term
                        $this->_termDictionary[$termKey] = $term;
                        $this->_termDocs[$termKey] = array();
                        $this->_termDocs[$termKey][$this->_docCount] = array();
                    } else if (!isset($this->_termDocs[$termKey][$this->_docCount])) {
                        // Existing term, but new term entry
                        $this->_termDocs[$termKey][$this->_docCount] = array();
                    }
                    $this->_termDocs[$termKey][$this->_docCount][] = 0; // position

                    $docNorms[$field->name] = chr($similarity->encodeNorm( $similarity->lengthNorm($field->name, 1)*
                                                                           $document->boost*
                                                                           $field->boost ));
                }
            }

            if ($field->isStored) {
                $storedFields[] = $field;
            }
        }


        foreach ($this->_fields as $fieldName => $field) {
            if (!$field->isIndexed) {
                continue;
            }

            if (!isset($this->_norms[$fieldName])) {
                $this->_norms[$fieldName] = str_repeat(chr($similarity->encodeNorm( $similarity->lengthNorm($fieldName, 0) )),
                                                       $this->_docCount);
            }

            if (isset($docNorms[$fieldName])){
                $this->_norms[$fieldName] .= $docNorms[$fieldName];
            } else {
                $this->_norms[$fieldName] .= chr($similarity->encodeNorm( $similarity->lengthNorm($fieldName, 0) ));
            }
        }

        $this->addStoredFields($storedFields);
    }


    /**
     * Dump Term Dictionary (.tis) and Term Dictionary Index (.tii) segment files
     */
    protected function _dumpDictionary()
    {
        ksort($this->_termDictionary, SORT_STRING);

        $this->initializeDictionaryFiles();

        foreach ($this->_termDictionary as $termId => $term) {
            $this->addTerm($term, $this->_termDocs[$termId]);
        }

        $this->closeDictionaryFiles();
    }


    /**
     * Close segment, write it to disk and return segment info
     *
     * @return Zend_Search_Lucene_Index_SegmentInfo
     */
    public function close()
    {
        if ($this->_docCount == 0) {
            return null;
        }

        $this->_dumpFNM();
        $this->_dumpDictionary();

        $this->_generateCFS();

        return new Zend_Search_Lucene_Index_SegmentInfo($this->_directory,
                                                        $this->_name,
                                                        $this->_docCount,
                                                        -1,
                                                        null,
                                                        true,
                                                        true);
    }

}

Search/Lucene/Index/SegmentWriter/StreamWriter.php000066600000006000151256604600016200 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_Index_SegmentInfo */
require_once 'Zend/Search/Lucene/Index/SegmentInfo.php';

/** Zend_Search_Lucene_Index_SegmentWriter */
require_once 'Zend/Search/Lucene/Index/SegmentWriter.php';

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Index_SegmentWriter_StreamWriter extends Zend_Search_Lucene_Index_SegmentWriter
{
    /**
     * Object constructor.
     *
     * @param Zend_Search_Lucene_Storage_Directory $directory
     * @param string $name
     */
    public function __construct(Zend_Search_Lucene_Storage_Directory $directory, $name)
    {
        parent::__construct($directory, $name);
    }


    /**
     * Create stored fields files and open them for write
     */
    public function createStoredFieldsFiles()
    {
        $this->_fdxFile = $this->_directory->createFile($this->_name . '.fdx');
        $this->_fdtFile = $this->_directory->createFile($this->_name . '.fdt');

        $this->_files[] = $this->_name . '.fdx';
        $this->_files[] = $this->_name . '.fdt';
    }

    public function addNorm($fieldName, $normVector)
    {
        if (isset($this->_norms[$fieldName])) {
            $this->_norms[$fieldName] .= $normVector;
        } else {
            $this->_norms[$fieldName] = $normVector;
        }
    }

    /**
     * Close segment, write it to disk and return segment info
     *
     * @return Zend_Search_Lucene_Index_SegmentInfo
     */
    public function close()
    {
        if ($this->_docCount == 0) {
            return null;
        }

        $this->_dumpFNM();
        $this->_generateCFS();

        return new Zend_Search_Lucene_Index_SegmentInfo($this->_directory,
                                                        $this->_name,
                                                        $this->_docCount,
                                                        -1,
                                                        null,
                                                        true,
                                                        true);
    }
}

Search/Lucene/Index/TermInfo.php000066600000004122151256604600012477 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * A Zend_Search_Lucene_Index_TermInfo represents a record of information stored for a term.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Index
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Index_TermInfo
{
    /**
     * The number of documents which contain the term.
     *
     * @var integer
     */
    public $docFreq;

    /**
     * Data offset in a Frequencies file.
     *
     * @var integer
     */
    public $freqPointer;

    /**
     * Data offset in a Positions file.
     *
     * @var integer
     */
    public $proxPointer;

    /**
     * ScipData offset in a Frequencies file.
     *
     * @var integer
     */
    public $skipOffset;

    /**
     * Term offset of the _next_ term in a TermDictionary file.
     * Used only for Term Index
     *
     * @var integer
     */
    public $indexPointer;

    public function __construct($docFreq, $freqPointer, $proxPointer, $skipOffset, $indexPointer = null)
    {
        $this->docFreq      = $docFreq;
        $this->freqPointer  = $freqPointer;
        $this->proxPointer  = $proxPointer;
        $this->skipOffset   = $skipOffset;
        $this->indexPointer = $indexPointer;
    }
}

Search/Lucene/Storage/File/Filesystem.php000066600000013560151256604600014322 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_Storage_File */
require_once 'Zend/Search/Lucene/Storage/File.php';

/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Storage_File_Filesystem extends Zend_Search_Lucene_Storage_File
{
    /**
     * Resource of the open file
     *
     * @var resource
     */
    protected $_fileHandle;


    /**
     * Class constructor.  Open the file.
     *
     * @param string $filename
     * @param string $mode
     */
    public function __construct($filename, $mode='r+b')
    {
        global $php_errormsg;

        if (strpos($mode, 'w') === false  &&  !is_readable($filename)) {
            // opening for reading non-readable file
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('File \'' . $filename . '\' is not readable.');
        }

        $trackErrors = ini_get('track_errors');
        ini_set('track_errors', '1');

        $this->_fileHandle = @fopen($filename, $mode);

        if ($this->_fileHandle === false) {
            ini_set('track_errors', $trackErrors);
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception($php_errormsg);
        }

        ini_set('track_errors', $trackErrors);
    }

    /**
     * Sets the file position indicator and advances the file pointer.
     * The new position, measured in bytes from the beginning of the file,
     * is obtained by adding offset to the position specified by whence,
     * whose values are defined as follows:
     * SEEK_SET - Set position equal to offset bytes.
     * SEEK_CUR - Set position to current location plus offset.
     * SEEK_END - Set position to end-of-file plus offset. (To move to
     * a position before the end-of-file, you need to pass a negative value
     * in offset.)
     * SEEK_CUR is the only supported offset type for compound files
     *
     * Upon success, returns 0; otherwise, returns -1
     *
     * @param integer $offset
     * @param integer $whence
     * @return integer
     */
    public function seek($offset, $whence=SEEK_SET)
    {
        return fseek($this->_fileHandle, $offset, $whence);
    }


    /**
     * Get file position.
     *
     * @return integer
     */
    public function tell()
    {
        return ftell($this->_fileHandle);
    }

    /**
     * Flush output.
     *
     * Returns true on success or false on failure.
     *
     * @return boolean
     */
    public function flush()
    {
        return fflush($this->_fileHandle);
    }

    /**
     * Close File object
     */
    public function close()
    {
        if ($this->_fileHandle !== null ) {
            @fclose($this->_fileHandle);
            $this->_fileHandle = null;
        }
    }

    /**
     * Get the size of the already opened file
     *
     * @return integer
     */
    public function size()
    {
        $position = ftell($this->_fileHandle);
        fseek($this->_fileHandle, 0, SEEK_END);
        $size = ftell($this->_fileHandle);
        fseek($this->_fileHandle,$position);

        return $size;
    }

    /**
     * Read a $length bytes from the file and advance the file pointer.
     *
     * @param integer $length
     * @return string
     */
    protected function _fread($length=1)
    {
        if ($length == 0) {
            return '';
        }

        if ($length < 1024) {
            return fread($this->_fileHandle, $length);
        }

        $data = '';
        while ( $length > 0 && ($nextBlock = fread($this->_fileHandle, $length)) != false ) {
            $data .= $nextBlock;
            $length -= strlen($nextBlock);
        }
        return $data;
    }


    /**
     * Writes $length number of bytes (all, if $length===null) to the end
     * of the file.
     *
     * @param string $data
     * @param integer $length
     */
    protected function _fwrite($data, $length=null)
    {
        if ($length === null ) {
            fwrite($this->_fileHandle, $data);
        } else {
            fwrite($this->_fileHandle, $data, $length);
        }
    }

    /**
     * Lock file
     *
     * Lock type may be a LOCK_SH (shared lock) or a LOCK_EX (exclusive lock)
     *
     * @param integer $lockType
     * @param boolean $nonBlockingLock
     * @return boolean
     */
    public function lock($lockType, $nonBlockingLock = false)
    {
        if ($nonBlockingLock) {
            return flock($this->_fileHandle, $lockType | LOCK_NB);
        } else {
            return flock($this->_fileHandle, $lockType);
        }
    }

    /**
     * Unlock file
     *
     * Returns true on success
     *
     * @return boolean
     */
    public function unlock()
    {
        if ($this->_fileHandle !== null ) {
            return flock($this->_fileHandle, LOCK_UN);
        } else {
            return true;
        }
    }
}

Search/Lucene/Storage/Directory/Filesystem.php000066600000024475151256604600015416 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Storage_Directory */
require_once 'Zend/Search/Lucene/Storage/Directory.php';

/** Zend_Search_Lucene_Storage_File_Filesystem */
require_once 'Zend/Search/Lucene/Storage/File/Filesystem.php';


/**
 * FileSystem implementation of Directory abstraction.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Storage
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Storage_Directory_Filesystem extends Zend_Search_Lucene_Storage_Directory
{
    /**
     * Filesystem path to the directory
     *
     * @var string
     */
    protected $_dirPath = null;

    /**
     * Cache for Zend_Search_Lucene_Storage_File_Filesystem objects
     * Array: filename => Zend_Search_Lucene_Storage_File object
     *
     * @var array
     * @throws Zend_Search_Lucene_Exception
     */
    protected $_fileHandlers;

    /**
     * Default file permissions
     *
     * @var integer
     */
    protected static $_defaultFilePermissions = 0666;


    /**
     * Get default file permissions
     *
     * @return integer
     */
    public static function getDefaultFilePermissions()
    {
        return self::$_defaultFilePermissions;
    }

    /**
     * Set default file permissions
     *
     * @param integer $mode
     */
    public static function setDefaultFilePermissions($mode)
    {
        self::$_defaultFilePermissions = $mode;
    }


    /**
     * Utility function to recursive directory creation
     *
     * @param string $dir
     * @param integer $mode
     * @param boolean $recursive
     * @return boolean
     */

    public static function mkdirs($dir, $mode = 0777, $recursive = true)
    {
        if (is_null($dir) || $dir === '') {
            return false;
        }
        if (is_dir($dir) || $dir === '/') {
            return true;
        }
        if (self::mkdirs(dirname($dir), $mode, $recursive)) {
            return mkdir($dir, $mode);
        }
        return false;
    }


    /**
     * Object constructor
     * Checks if $path is a directory or tries to create it.
     *
     * @param string $path
     * @throws Zend_Search_Lucene_Exception
     */
    public function __construct($path)
    {
        if (!is_dir($path)) {
            if (file_exists($path)) {
                require_once 'Zend/Search/Lucene/Exception.php';
                throw new Zend_Search_Lucene_Exception('Path exists, but it\'s not a directory');
            } else {
                if (!self::mkdirs($path)) {
                    require_once 'Zend/Search/Lucene/Exception.php';
                    throw new Zend_Search_Lucene_Exception("Can't create directory '$path'.");
                }
            }
        }
        $this->_dirPath = $path;
        $this->_fileHandlers = array();
    }


    /**
     * Closes the store.
     *
     * @return void
     */
    public function close()
    {
        foreach ($this->_fileHandlers as $fileObject) {
            $fileObject->close();
        }

        $this->_fileHandlers = array();
    }


    /**
     * Returns an array of strings, one for each file in the directory.
     *
     * @return array
     */
    public function fileList()
    {
        $result = array();

        $dirContent = opendir( $this->_dirPath );
        while (($file = readdir($dirContent)) !== false) {
            if (($file == '..')||($file == '.'))   continue;

            if( !is_dir($this->_dirPath . '/' . $file) ) {
                $result[] = $file;
            }
        }
        closedir($dirContent);

        return $result;
    }

    /**
     * Creates a new, empty file in the directory with the given $filename.
     *
     * @param string $filename
     * @return Zend_Search_Lucene_Storage_File
     * @throws Zend_Search_Lucene_Exception
     */
    public function createFile($filename)
    {
        if (isset($this->_fileHandlers[$filename])) {
            $this->_fileHandlers[$filename]->close();
        }
        unset($this->_fileHandlers[$filename]);
        $this->_fileHandlers[$filename] = new Zend_Search_Lucene_Storage_File_Filesystem($this->_dirPath . '/' . $filename, 'w+b');

        // Set file permissions, but don't care about any possible failures, since file may be already
        // created by anther user which has to care about right permissions
        @chmod($this->_dirPath . '/' . $filename, self::$_defaultFilePermissions);

        return $this->_fileHandlers[$filename];
    }


    /**
     * Removes an existing $filename in the directory.
     *
     * @param string $filename
     * @return void
     * @throws Zend_Search_Lucene_Exception
     */
    public function deleteFile($filename)
    {
        if (isset($this->_fileHandlers[$filename])) {
            $this->_fileHandlers[$filename]->close();
        }
        unset($this->_fileHandlers[$filename]);

        global $php_errormsg;
        $trackErrors = ini_get('track_errors'); ini_set('track_errors', '1');
        if (!@unlink($this->_dirPath . '/' . $filename)) {
            ini_set('track_errors', $trackErrors);
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Can\'t delete file: ' . $php_errormsg);
        }
        ini_set('track_errors', $trackErrors);
    }

    /**
     * Purge file if it's cached by directory object
     *
     * Method is used to prevent 'too many open files' error
     *
     * @param string $filename
     * @return void
     */
    public function purgeFile($filename)
    {
        if (isset($this->_fileHandlers[$filename])) {
            $this->_fileHandlers[$filename]->close();
        }
        unset($this->_fileHandlers[$filename]);
    }


    /**
     * Returns true if a file with the given $filename exists.
     *
     * @param string $filename
     * @return boolean
     */
    public function fileExists($filename)
    {
        return isset($this->_fileHandlers[$filename]) ||
               file_exists($this->_dirPath . '/' . $filename);
    }


    /**
     * Returns the length of a $filename in the directory.
     *
     * @param string $filename
     * @return integer
     */
    public function fileLength($filename)
    {
        if (isset( $this->_fileHandlers[$filename] )) {
            return $this->_fileHandlers[$filename]->size();
        }
        return filesize($this->_dirPath .'/'. $filename);
    }


    /**
     * Returns the UNIX timestamp $filename was last modified.
     *
     * @param string $filename
     * @return integer
     */
    public function fileModified($filename)
    {
        return filemtime($this->_dirPath .'/'. $filename);
    }


    /**
     * Renames an existing file in the directory.
     *
     * @param string $from
     * @param string $to
     * @return void
     * @throws Zend_Search_Lucene_Exception
     */
    public function renameFile($from, $to)
    {
        global $php_errormsg;

        if (isset($this->_fileHandlers[$from])) {
            $this->_fileHandlers[$from]->close();
        }
        unset($this->_fileHandlers[$from]);

        if (isset($this->_fileHandlers[$to])) {
            $this->_fileHandlers[$to]->close();
        }
        unset($this->_fileHandlers[$to]);

        if (file_exists($this->_dirPath . '/' . $to)) {
            if (!unlink($this->_dirPath . '/' . $to)) {
                require_once 'Zend/Search/Lucene/Exception.php';
                throw new Zend_Search_Lucene_Exception('Delete operation failed');
            }
        }

        $trackErrors = ini_get('track_errors');
        ini_set('track_errors', '1');

        $success = @rename($this->_dirPath . '/' . $from, $this->_dirPath . '/' . $to);
        if (!$success) {
            ini_set('track_errors', $trackErrors);
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception($php_errormsg);
        }

        ini_set('track_errors', $trackErrors);

        return $success;
    }


    /**
     * Sets the modified time of $filename to now.
     *
     * @param string $filename
     * @return void
     */
    public function touchFile($filename)
    {
        return touch($this->_dirPath .'/'. $filename);
    }


    /**
     * Returns a Zend_Search_Lucene_Storage_File object for a given $filename in the directory.
     *
     * If $shareHandler option is true, then file handler can be shared between File Object
     * requests. It speed-ups performance, but makes problems with file position.
     * Shared handler are good for short atomic requests.
     * Non-shared handlers are useful for stream file reading (especial for compound files).
     *
     * @param string $filename
     * @param boolean $shareHandler
     * @return Zend_Search_Lucene_Storage_File
     */
    public function getFileObject($filename, $shareHandler = true)
    {
        $fullFilename = $this->_dirPath . '/' . $filename;

        if (!$shareHandler) {
            return new Zend_Search_Lucene_Storage_File_Filesystem($fullFilename);
        }

        if (isset( $this->_fileHandlers[$filename] )) {
            $this->_fileHandlers[$filename]->seek(0);
            return $this->_fileHandlers[$filename];
        }

        $this->_fileHandlers[$filename] = new Zend_Search_Lucene_Storage_File_Filesystem($fullFilename);
        return $this->_fileHandlers[$filename];
    }
}

Search/Lucene/Analysis/Analyzer/Common/TextNum/CaseInsensitive.php000066600000003004151256604610021204 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum.php';

/** Zend_Search_Lucene_Analysis_TokenFilter_LowerCase */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter/LowerCase.php';


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


class Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive extends Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum
{
    public function __construct()
    {
        $this->addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCase());
    }
}

Search/Lucene/Analysis/Analyzer/Common/Text/CaseInsensitive.php000066600000002770151256604610020535 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer_Common_Text */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Text.php';

/** Zend_Search_Lucene_Analysis_TokenFilter_LowerCase */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter/LowerCase.php';


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


class Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive extends Zend_Search_Lucene_Analysis_Analyzer_Common_Text
{
    public function __construct()
    {
        $this->addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCase());
    }
}

Search/Lucene/Analysis/Analyzer/Common/Text.php000066600000005245151256604610015441 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer_Common */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common.php';


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

class Zend_Search_Lucene_Analysis_Analyzer_Common_Text extends Zend_Search_Lucene_Analysis_Analyzer_Common
{
    /**
     * Current position in a stream
     *
     * @var integer
     */
    private $_position;

    /**
     * Reset token stream
     */
    public function reset()
    {
        $this->_position = 0;

        if ($this->_input === null) {
            return;
        }

        // convert input into ascii
        if (PHP_OS != 'AIX') {
            $this->_input = iconv($this->_encoding, 'ASCII//TRANSLIT', $this->_input);
        }
        $this->_encoding = 'ASCII';
    }

    /**
     * Tokenization stream API
     * Get next token
     * Returns null at the end of stream
     *
     * @return Zend_Search_Lucene_Analysis_Token|null
     */
    public function nextToken()
    {
        if ($this->_input === null) {
            return null;
        }


        do {
            if (! preg_match('/[a-zA-Z]+/', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_position)) {
                // It covers both cases a) there are no matches (preg_match(...) === 0)
                // b) error occured (preg_match(...) === FALSE)
                return null;
            }

            $str = $match[0][0];
            $pos = $match[0][1];
            $endpos = $pos + strlen($str);

            $this->_position = $endpos;

            $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($str, $pos, $endpos));
        } while ($token === null); // try again if token is skipped

        return $token;
    }
}

Search/Lucene/Analysis/Analyzer/Common/Utf8Num.php000066600000007774151256604610016034 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer_Common */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common.php';


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

class Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num extends Zend_Search_Lucene_Analysis_Analyzer_Common
{
    /**
     * Current char position in an UTF-8 stream
     *
     * @var integer
     */
    private $_position;

    /**
     * Current binary position in an UTF-8 stream
     *
     * @var integer
     */
    private $_bytePosition;

    /**
     * Object constructor
     *
     * @throws Zend_Search_Lucene_Exception
     */
    public function __construct()
    {
        if (@preg_match('/\pL/u', 'a') != 1) {
            // PCRE unicode support is turned off
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Utf8Num analyzer needs PCRE unicode support to be enabled.');
        }
    }

    /**
     * Reset token stream
     */
    public function reset()
    {
        $this->_position     = 0;
        $this->_bytePosition = 0;

        // convert input into UTF-8
        if (strcasecmp($this->_encoding, 'utf8' ) != 0  &&
            strcasecmp($this->_encoding, 'utf-8') != 0 ) {
                $this->_input = iconv($this->_encoding, 'UTF-8', $this->_input);
                $this->_encoding = 'UTF-8';
        }
    }

    /**
     * Tokenization stream API
     * Get next token
     * Returns null at the end of stream
     *
     * @return Zend_Search_Lucene_Analysis_Token|null
     */
    public function nextToken()
    {
        if ($this->_input === null) {
            return null;
        }

        do {
            if (! preg_match('/[\p{L}\p{N}]+/u', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_bytePosition)) {
                // It covers both cases a) there are no matches (preg_match(...) === 0)
                // b) error occured (preg_match(...) === FALSE)
                return null;
            }

            // matched string
            $matchedWord = $match[0][0];
            
            // binary position of the matched word in the input stream
            $binStartPos = $match[0][1];
            
            // character position of the matched word in the input stream
            $startPos = $this->_position + 
                        iconv_strlen(substr($this->_input,
                                            $this->_bytePosition,
                                            $binStartPos - $this->_bytePosition),
                                     'UTF-8');
            // character postion of the end of matched word in the input stream
            $endPos = $startPos + iconv_strlen($matchedWord, 'UTF-8');

            $this->_bytePosition = $binStartPos + strlen($matchedWord);
            $this->_position     = $endPos;

            $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($matchedWord, $startPos, $endPos));
        } while ($token === null); // try again if token is skipped

        return $token;
    }
}

Search/Lucene/Analysis/Analyzer/Common/Utf8/CaseInsensitive.php000066600000003047151256604610020435 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8 */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8.php';

/** Zend_Search_Lucene_Analysis_TokenFilter_LowerCaseUtf8 */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter/LowerCaseUtf8.php';


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


class Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive extends Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8 
{
    public function __construct()
    {
        parent::__construct();

        $this->addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCaseUtf8());
    }
}

Search/Lucene/Analysis/Analyzer/Common/TextNum.php000066600000005251151256604610016116 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer_Common */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common.php';


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

class Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum extends Zend_Search_Lucene_Analysis_Analyzer_Common
{
    /**
     * Current position in a stream
     *
     * @var integer
     */
    private $_position;

    /**
     * Reset token stream
     */
    public function reset()
    {
        $this->_position = 0;

        if ($this->_input === null) {
            return;
        }

        // convert input into ascii
        if (PHP_OS != 'AIX') {
            $this->_input = iconv($this->_encoding, 'ASCII//TRANSLIT', $this->_input);
        }
        $this->_encoding = 'ASCII';
    }

    /**
     * Tokenization stream API
     * Get next token
     * Returns null at the end of stream
     *
     * @return Zend_Search_Lucene_Analysis_Token|null
     */
    public function nextToken()
    {
        if ($this->_input === null) {
            return null;
        }

        do {
            if (! preg_match('/[a-zA-Z0-9]+/', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_position)) {
                // It covers both cases a) there are no matches (preg_match(...) === 0)
                // b) error occured (preg_match(...) === FALSE)
                return null;
            }

            $str = $match[0][0];
            $pos = $match[0][1];
            $endpos = $pos + strlen($str);

            $this->_position = $endpos;

            $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($str, $pos, $endpos));
        } while ($token === null); // try again if token is skipped

        return $token;
    }
}

Search/Lucene/Analysis/Analyzer/Common/Utf8.php000066600000007765151256604610015354 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer_Common */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common.php';


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

class Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8 extends Zend_Search_Lucene_Analysis_Analyzer_Common
{
    /**
     * Current char position in an UTF-8 stream
     *
     * @var integer
     */
    private $_position;

    /**
     * Current binary position in an UTF-8 stream
     *
     * @var integer
     */
    private $_bytePosition;
    
    /**
     * Object constructor
     *
     * @throws Zend_Search_Lucene_Exception
     */
    public function __construct()
    {
        if (@preg_match('/\pL/u', 'a') != 1) {
            // PCRE unicode support is turned off
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Utf8 analyzer needs PCRE unicode support to be enabled.');
        }
    }

    /**
     * Reset token stream
     */
    public function reset()
    {
        $this->_position     = 0;
        $this->_bytePosition = 0;

        // convert input into UTF-8
        if (strcasecmp($this->_encoding, 'utf8' ) != 0  &&
            strcasecmp($this->_encoding, 'utf-8') != 0 ) {
                $this->_input = iconv($this->_encoding, 'UTF-8', $this->_input);
                $this->_encoding = 'UTF-8';
        }
    }

    /**
     * Tokenization stream API
     * Get next token
     * Returns null at the end of stream
     *
     * @return Zend_Search_Lucene_Analysis_Token|null
     */
    public function nextToken()
    {
        if ($this->_input === null) {
            return null;
        }

        do {
            if (! preg_match('/[\p{L}]+/u', $this->_input, $match, PREG_OFFSET_CAPTURE, $this->_bytePosition)) {
                // It covers both cases a) there are no matches (preg_match(...) === 0)
                // b) error occured (preg_match(...) === FALSE)
                return null;
            }

            // matched string
            $matchedWord = $match[0][0];
            
            // binary position of the matched word in the input stream
            $binStartPos = $match[0][1];
            
            // character position of the matched word in the input stream
            $startPos = $this->_position + 
                        iconv_strlen(substr($this->_input,
                                            $this->_bytePosition,
                                            $binStartPos - $this->_bytePosition),
                                     'UTF-8');
            // character postion of the end of matched word in the input stream
            $endPos = $startPos + iconv_strlen($matchedWord, 'UTF-8');

            $this->_bytePosition = $binStartPos + strlen($matchedWord);
            $this->_position     = $endPos;

            $token = $this->normalize(new Zend_Search_Lucene_Analysis_Token($matchedWord, $startPos, $endPos));
        } while ($token === null); // try again if token is skipped

        return $token;
    }
}

Search/Lucene/Analysis/Analyzer/Common/Utf8Num/CaseInsensitive.php000066600000003062151256604610021112 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num.php';

/** Zend_Search_Lucene_Analysis_TokenFilter_LowerCaseUtf8 */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter/LowerCaseUtf8.php';


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


class Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num_CaseInsensitive extends Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num
{
    public function __construct()
    {
        parent::__construct();

        $this->addFilter(new Zend_Search_Lucene_Analysis_TokenFilter_LowerCaseUtf8());
    }
}

Search/Lucene/Analysis/Analyzer/Common.php000066600000005102151256604610014505 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Analyzer */
require_once 'Zend/Search/Lucene/Analysis/Analyzer.php';


/**
 * Common implementation of the Zend_Search_Lucene_Analysis_Analyzer interface.
 * There are several standard standard subclasses provided by Zend_Search_Lucene/Analysis
 * subpackage: Zend_Search_Lucene_Analysis_Analyzer_Common_Text, ZSearchHTMLAnalyzer, ZSearchXMLAnalyzer.
 *
 * @todo ZSearchHTMLAnalyzer and ZSearchXMLAnalyzer implementation
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Search_Lucene_Analysis_Analyzer_Common extends Zend_Search_Lucene_Analysis_Analyzer
{
    /**
     * The set of Token filters applied to the Token stream.
     * Array of Zend_Search_Lucene_Analysis_TokenFilter objects.
     *
     * @var array
     */
    private $_filters = array();

    /**
     * Add Token filter to the Analyzer
     *
     * @param Zend_Search_Lucene_Analysis_TokenFilter $filter
     */
    public function addFilter(Zend_Search_Lucene_Analysis_TokenFilter $filter)
    {
        $this->_filters[] = $filter;
    }

    /**
     * Apply filters to the token. Can return null when the token was removed.
     *
     * @param Zend_Search_Lucene_Analysis_Token $token
     * @return Zend_Search_Lucene_Analysis_Token
     */
    public function normalize(Zend_Search_Lucene_Analysis_Token $token)
    {
        foreach ($this->_filters as $filter) {
            $token = $filter->normalize($token);

            // resulting token can be null if the filter removes it
            if (is_null($token)) {
                return null;
            }
        }

        return $token;
    }
}

Search/Lucene/Analysis/Analyzer.php000066600000012351151256604610013261 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Token */
require_once 'Zend/Search/Lucene/Analysis/Token.php';

/** Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8 */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8.php';

/** Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8/CaseInsensitive.php';

/** Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num.php';

/** Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8Num_CaseInsensitive */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Utf8Num/CaseInsensitive.php';

/** Zend_Search_Lucene_Analysis_Analyzer_Common_Text */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Text.php';

/** Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/Text/CaseInsensitive.php';

/** Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum.php';

/** Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive */
require_once 'Zend/Search/Lucene/Analysis/Analyzer/Common/TextNum/CaseInsensitive.php';

/** Zend_Search_Lucene_Analysis_TokenFilter_StopWords */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter/StopWords.php';

/** Zend_Search_Lucene_Analysis_TokenFilter_ShortWords */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter/ShortWords.php';


/**
 * An Analyzer is used to analyze text.
 * It thus represents a policy for extracting index terms from text.
 *
 * Note:
 * Lucene Java implementation is oriented to streams. It provides effective work
 * with a huge documents (more then 20Mb).
 * But engine itself is not oriented such documents.
 * Thus Zend_Search_Lucene analysis API works with data strings and sets (arrays).
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

abstract class Zend_Search_Lucene_Analysis_Analyzer
{
    /**
     * The Analyzer implementation used by default.
     *
     * @var Zend_Search_Lucene_Analysis_Analyzer
     */
    private static $_defaultImpl;

    /**
     * Input string
     *
     * @var string
     */
    protected $_input = null;

    /**
     * Input string encoding
     *
     * @var string
     */
    protected $_encoding = '';

    /**
     * Tokenize text to a terms
     * Returns array of Zend_Search_Lucene_Analysis_Token objects
     *
     * Tokens are returned in UTF-8 (internal Zend_Search_Lucene encoding)
     *
     * @param string $data
     * @return array
     */
    public function tokenize($data, $encoding = '')
    {
        $this->setInput($data, $encoding);

        $tokenList = array();
        while (($nextToken = $this->nextToken()) !== null) {
            $tokenList[] = $nextToken;
        }

        return $tokenList;
    }


    /**
     * Tokenization stream API
     * Set input
     *
     * @param string $data
     */
    public function setInput($data, $encoding = '')
    {
        $this->_input    = $data;
        $this->_encoding = $encoding;
        $this->reset();
    }

    /**
     * Reset token stream
     */
    abstract public function reset();

    /**
     * Tokenization stream API
     * Get next token
     * Returns null at the end of stream
     *
     * Tokens are returned in UTF-8 (internal Zend_Search_Lucene encoding)
     *
     * @return Zend_Search_Lucene_Analysis_Token|null
     */
    abstract public function nextToken();




    /**
     * Set the default Analyzer implementation used by indexing code.
     *
     * @param Zend_Search_Lucene_Analysis_Analyzer $similarity
     */
    public static function setDefault(Zend_Search_Lucene_Analysis_Analyzer $analyzer)
    {
        self::$_defaultImpl = $analyzer;
    }


    /**
     * Return the default Analyzer implementation used by indexing code.
     *
     * @return Zend_Search_Lucene_Analysis_Analyzer
     */
    public static function getDefault()
    {
        if (!self::$_defaultImpl instanceof Zend_Search_Lucene_Analysis_Analyzer) {
            self::$_defaultImpl = new Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive();
        }

        return self::$_defaultImpl;
    }
}

Search/Lucene/Analysis/TokenFilter/LowerCase.php000066600000003574151256604610015615 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_TokenFilter */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter.php';


/**
 * Lower case Token filter.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

class Zend_Search_Lucene_Analysis_TokenFilter_LowerCase extends Zend_Search_Lucene_Analysis_TokenFilter
{
    /**
     * Normalize Token or remove it (if null is returned)
     *
     * @param Zend_Search_Lucene_Analysis_Token $srcToken
     * @return Zend_Search_Lucene_Analysis_Token
     */
    public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken)
    {
        $newToken = new Zend_Search_Lucene_Analysis_Token(
                                     strtolower( $srcToken->getTermText() ),
                                     $srcToken->getStartOffset(),
                                     $srcToken->getEndOffset());

        $newToken->setPositionIncrement($srcToken->getPositionIncrement());

        return $newToken;
    }
}

Search/Lucene/Analysis/TokenFilter/ShortWords.php000066600000004104151256604610016035 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_TokenFilter */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter.php';


/**
 * Token filter that removes short words. What is short word can be configured with constructor.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

class Zend_Search_Lucene_Analysis_TokenFilter_ShortWords extends Zend_Search_Lucene_Analysis_TokenFilter
{
    /**
     * Minimum allowed term length
     * @var integer
     */
    private $length;

    /**
     * Constructs new instance of this filter.
     *
     * @param integer $short  minimum allowed length of term which passes this filter (default 2)
     */
    public function __construct($length = 2) {
        $this->length = $length;
    }

    /**
     * Normalize Token or remove it (if null is returned)
     *
     * @param Zend_Search_Lucene_Analysis_Token $srcToken
     * @return Zend_Search_Lucene_Analysis_Token
     */
    public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken) {
        if (strlen($srcToken->getTermText()) < $this->length) {
            return null;
        } else {
            return $srcToken;
        }
    }
}

Search/Lucene/Analysis/TokenFilter/StopWords.php000066600000007031151256604610015665 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_Analysis_TokenFilter */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter.php';

/**
 * Token filter that removes stop words. These words must be provided as array (set), example:
 * $stopwords = array('the' => 1, 'an' => '1');
 *
 * We do recommend to provide all words in lowercase and concatenate this class after the lowercase filter.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

class Zend_Search_Lucene_Analysis_TokenFilter_StopWords extends Zend_Search_Lucene_Analysis_TokenFilter
{
    /**
     * Stop Words
     * @var array
     */
    private $_stopSet;

    /**
     * Constructs new instance of this filter.
     *
     * @param array $stopwords array (set) of words that will be filtered out
     */
    public function __construct($stopwords = array()) {
        $this->_stopSet = array_flip($stopwords);
    }

    /**
     * Normalize Token or remove it (if null is returned)
     *
     * @param Zend_Search_Lucene_Analysis_Token $srcToken
     * @return Zend_Search_Lucene_Analysis_Token
     */
    public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken) {
        if (array_key_exists($srcToken->getTermText(), $this->_stopSet)) {
            return null;
        } else {
            return $srcToken;
        }
    }

    /**
     * Fills stopwords set from a text file. Each line contains one stopword, lines with '#' in the first
     * column are ignored (as comments).
     *
     * You can call this method one or more times. New stopwords are always added to current set.
     *
     * @param string $filepath full path for text file with stopwords
     * @throws Zend_Search_Exception When the file doesn`t exists or is not readable.
     */
    public function loadFromFile($filepath = null) {
        if (! $filepath || ! file_exists($filepath)) {
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('You have to provide valid file path');
        }
        $fd = fopen($filepath, "r");
        if (! $fd) {
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Cannot open file ' . $filepath);
        }
        while (!feof ($fd)) {
            $buffer = trim(fgets($fd));
            if (strlen($buffer) > 0 && $buffer[0] != '#') {
                $this->_stopSet[$buffer] = 1;
            }
        }
        if (!fclose($fd)) {
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Cannot close file ' . $filepath);
        }
    }
}

Search/Lucene/Analysis/TokenFilter/LowerCaseUtf8.php000066600000004432151256604610016356 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_TokenFilter */
require_once 'Zend/Search/Lucene/Analysis/TokenFilter.php';


/**
 * Lower case Token filter.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

class Zend_Search_Lucene_Analysis_TokenFilter_LowerCaseUtf8 extends Zend_Search_Lucene_Analysis_TokenFilter
{
    /**
     * Object constructor
     */
    public function __construct()
    {
        if (!function_exists('mb_strtolower')) {
            // mbstring extension is disabled
            require_once 'Zend/Search/Lucene/Exception.php';
            throw new Zend_Search_Lucene_Exception('Utf8 compatible lower case filter needs mbstring extension to be enabled.');
        }
    }
    
    /**
     * Normalize Token or remove it (if null is returned)
     *
     * @param Zend_Search_Lucene_Analysis_Token $srcToken
     * @return Zend_Search_Lucene_Analysis_Token
     */
    public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken)
    {
        $newToken = new Zend_Search_Lucene_Analysis_Token(
                                     mb_strtolower($srcToken->getTermText(), 'UTF-8'),
                                     $srcToken->getStartOffset(),
                                     $srcToken->getEndOffset());

        $newToken->setPositionIncrement($srcToken->getPositionIncrement());

        return $newToken;
    }
}

Search/Lucene/Analysis/Token.php000066600000010353151256604610012554 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Analysis_Token
{
    /**
     * The text of the term.
     *
     * @var string
     */
    private $_termText;

    /**
     * Start in source text.
     *
     * @var integer
     */
    private $_startOffset;

    /**
     * End in source text
     *
     * @var integer
     */
    private $_endOffset;

    /**
     * The position of this token relative to the previous Token.
     *
     * The default value is one.
     *
     * Some common uses for this are:
     * Set it to zero to put multiple terms in the same position.  This is
     * useful if, e.g., a word has multiple stems.  Searches for phrases
     * including either stem will match.  In this case, all but the first stem's
     * increment should be set to zero: the increment of the first instance
     * should be one.  Repeating a token with an increment of zero can also be
     * used to boost the scores of matches on that token.
     *
     * Set it to values greater than one to inhibit exact phrase matches.
     * If, for example, one does not want phrases to match across removed stop
     * words, then one could build a stop word filter that removes stop words and
     * also sets the increment to the number of stop words removed before each
     * non-stop word.  Then exact phrase queries will only match when the terms
     * occur with no intervening stop words.
     *
     * @var integer
     */
    private $_positionIncrement;


    /**
     * Object constructor
     *
     * @param string  $text
     * @param integer $start
     * @param integer $end
     * @param string  $type
     */
    public function __construct($text, $start, $end)
    {
        $this->_termText    = $text;
        $this->_startOffset = $start;
        $this->_endOffset   = $end;

        $this->_positionIncrement = 1;
    }


    /**
     * positionIncrement setter
     *
     * @param integer $positionIncrement
     */
    public function setPositionIncrement($positionIncrement)
    {
        $this->_positionIncrement = $positionIncrement;
    }

    /**
     * Returns the position increment of this Token.
     *
     * @return integer
     */
    public function getPositionIncrement()
    {
        return $this->_positionIncrement;
    }

    /**
     * Returns the Token's term text.
     *
     * @return string
     */
    public function getTermText()
    {
        return $this->_termText;
    }

    /**
     * Returns this Token's starting offset, the position of the first character
     * corresponding to this token in the source text.
     *
     * Note:
     * The difference between getEndOffset() and getStartOffset() may not be equal
     * to strlen(Zend_Search_Lucene_Analysis_Token::getTermText()), as the term text may have been altered
     * by a stemmer or some other filter.
     *
     * @return integer
     */
    public function getStartOffset()
    {
        return $this->_startOffset;
    }

    /**
     * Returns this Token's ending offset, one greater than the position of the
     * last character corresponding to this token in the source text.
     *
     * @return integer
     */
    public function getEndOffset()
    {
        return $this->_endOffset;
    }
}

Search/Lucene/Analysis/TokenFilter.php000066600000002764151256604610013731 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Analysis_Token */
require_once 'Zend/Search/Lucene/Analysis/Token.php';


/**
 * Token filter converts (normalizes) Token ore removes it from a token stream.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Analysis
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

abstract class Zend_Search_Lucene_Analysis_TokenFilter
{
    /**
     * Normalize Token or remove it (if null is returned)
     *
     * @param Zend_Search_Lucene_Analysis_Token $srcToken
     * @return Zend_Search_Lucene_Analysis_Token
     */
    abstract public function normalize(Zend_Search_Lucene_Analysis_Token $srcToken);
}

Search/Lucene/Document/Xlsx.php000066600000022153151256604610012426 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Document_OpenXml */
require_once 'Zend/Search/Lucene/Document/OpenXml.php';

if (class_exists('ZipArchive', false)) {

/**
 * Xlsx document.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Document_Xlsx extends Zend_Search_Lucene_Document_OpenXml
{
    /**
     * Xml Schema - SpreadsheetML
     *
     * @var string
     */
    const SCHEMA_SPREADSHEETML = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main';

    /**
     * Xml Schema - DrawingML
     *
     * @var string
     */
    const SCHEMA_DRAWINGML = 'http://schemas.openxmlformats.org/drawingml/2006/main';

    /**
     * Xml Schema - Shared Strings
     *
     * @var string
     */
    const SCHEMA_SHAREDSTRINGS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings';

    /**
     * Xml Schema - Worksheet relation
     *
     * @var string
     */
    const SCHEMA_WORKSHEETRELATION = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet';

    /**
     * Xml Schema - Slide notes relation
     *
     * @var string
     */
    const SCHEMA_SLIDENOTESRELATION = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide';

    /**
     * Object constructor
     *
     * @param string  $fileName
     * @param boolean $storeContent
     */
    private function __construct($fileName, $storeContent)
    {
        // Document data holders
        $sharedStrings = array();
        $worksheets = array();
        $documentBody = array();
        $coreProperties = array();

        // Open OpenXML package
        $package = new ZipArchive();
        $package->open($fileName);

        // Read relations and search for officeDocument
        $relations = simplexml_load_string($package->getFromName("_rels/.rels"));
        foreach ($relations->Relationship as $rel) {
            if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) {
                // Found office document! Read relations for workbook...
                $workbookRelations = simplexml_load_string($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/_rels/" . basename($rel["Target"]) . ".rels")) );
                $workbookRelations->registerXPathNamespace("rel", Zend_Search_Lucene_Document_OpenXml::SCHEMA_RELATIONSHIP);

                // Read shared strings
                $sharedStringsPath = $workbookRelations->xpath("rel:Relationship[@Type='" . Zend_Search_Lucene_Document_Xlsx::SCHEMA_SHAREDSTRINGS . "']");
                $sharedStringsPath = (string)$sharedStringsPath[0]['Target'];
                $xmlStrings = simplexml_load_string($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . $sharedStringsPath)) );
                if (isset($xmlStrings) && isset($xmlStrings->si)) {
                    foreach ($xmlStrings->si as $val) {
                        if (isset($val->t)) {
                            $sharedStrings[] = (string)$val->t;
                        } elseif (isset($val->r)) {
                            $sharedStrings[] = $this->_parseRichText($val);
                        }
                    }
                }

                // Loop relations for workbook and extract worksheets...
                foreach ($workbookRelations->Relationship as $workbookRelation) {
                    if ($workbookRelation["Type"] == Zend_Search_Lucene_Document_Xlsx::SCHEMA_WORKSHEETRELATION) {
                        $worksheets[ str_replace( 'rId', '', (string)$workbookRelation["Id"]) ] = simplexml_load_string(
                            $package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($workbookRelation["Target"]) . "/" . basename($workbookRelation["Target"])) )
                        );
                    }
                }

                break;
            }
        }

        // Sort worksheets
        ksort($worksheets);

        // Extract contents from worksheets
        foreach ($worksheets as $sheetKey => $worksheet) {
            foreach ($worksheet->sheetData->row as $row) {
                foreach ($row->c as $c) {
                    // Determine data type
                    $dataType = (string)$c["t"];
                    switch ($dataType) {
                        case "s":
                            // Value is a shared string
                            if ((string)$c->v != '') {
                                $value = $sharedStrings[intval($c->v)];
                            } else {
                                $value = '';
                            }

                            break;

                        case "b":
                            // Value is boolean
                            $value = (string)$c->v;
                            if ($value == '0') {
                                $value = false;
                            } else if ($value == '1') {
                                $value = true;
                            } else {
                                $value = (bool)$c->v;
                            }

                            break;

                        case "inlineStr":
                            // Value is rich text inline
                            $value = $this->_parseRichText($c->is);

                            break;

                        case "e":
                            // Value is an error message
                            if ((string)$c->v != '') {
                                $value = (string)$c->v;
                            } else {
                                $value = '';
                            }

                            break;

                        default:
                            // Value is a string
                            $value = (string)$c->v;

                            // Check for numeric values
                            if (is_numeric($value) && $dataType != 's') {
                                if ($value == (int)$value) $value = (int)$value;
                                elseif ($value == (float)$value) $value = (float)$value;
                                elseif ($value == (double)$value) $value = (double)$value;
                            }
                    }

                    $documentBody[] = $value;
                }
            }
        }

        // Read core properties
        $coreProperties = $this->extractMetaData($package);

        // Close file
        $package->close();

        // Store filename
        $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName, 'UTF-8'));

        // Store contents
        if ($storeContent) {
            $this->addField(Zend_Search_Lucene_Field::Text('body', implode(' ', $documentBody), 'UTF-8'));
        } else {
            $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode(' ', $documentBody), 'UTF-8'));
        }

        // Store meta data properties
        foreach ($coreProperties as $key => $value)
        {
            $this->addField(Zend_Search_Lucene_Field::Text($key, $value, 'UTF-8'));
        }

        // Store title (if not present in meta data)
        if (!isset($coreProperties['title']))
        {
            $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName, 'UTF-8'));
        }
    }

    /**
     * Parse rich text XML
     *
     * @param SimpleXMLElement $is
     * @return string
     */
    private function _parseRichText($is = null) {
        $value = array();

        if (isset($is->t)) {
            $value[] = (string)$is->t;
        } else {
            foreach ($is->r as $run) {
                $value[] = (string)$run->t;
            }
        }

        return implode('', $value);
    }

    /**
     * Load Xlsx document from a file
     *
     * @param string  $fileName
     * @param boolean $storeContent
     * @return Zend_Search_Lucene_Document_Xlsx
     */
    public static function loadXlsxFile($fileName, $storeContent = false)
    {
        return new Zend_Search_Lucene_Document_Xlsx($fileName, $storeContent);
    }
}

} // end if (class_exists('ZipArchive'))
Search/Lucene/Document/Html.php000066600000023662151256604610012402 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Document */
require_once 'Zend/Search/Lucene/Document.php';


/**
 * HTML document.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Document_Html extends Zend_Search_Lucene_Document
{
    /**
     * List of document links
     *
     * @var array
     */
    private $_links = array();

    /**
     * List of document header links
     *
     * @var array
     */
    private $_headerLinks = array();

    /**
     * Stored DOM representation
     *
     * @var DOMDocument
     */
    private $_doc;

    /**
     * Exclud nofollow links flag
     *
     * If true then links with rel='nofollow' attribute are not included into
     * document links.
     *
     * @var boolean
     */
    private static $_excludeNoFollowLinks = false;

    /**
     * Object constructor
     *
     * @param string  $data
     * @param boolean $isFile
     * @param boolean $storeContent
     */
    private function __construct($data, $isFile, $storeContent)
    {
        $this->_doc = new DOMDocument();
        $this->_doc->substituteEntities = true;

        if ($isFile) {
            $htmlData = file_get_contents($data);
        } else {
            $htmlData = $data;
        }
        @$this->_doc->loadHTML($htmlData);

        $xpath = new DOMXPath($this->_doc);

        $docTitle = '';
        $titleNodes = $xpath->query('/html/head/title');
        foreach ($titleNodes as $titleNode) {
            // title should always have only one entry, but we process all nodeset entries
            $docTitle .= $titleNode->nodeValue . ' ';
        }
        $this->addField(Zend_Search_Lucene_Field::Text('title', $docTitle, $this->_doc->actualEncoding));

        $metaNodes = $xpath->query('/html/head/meta[@name]');
        foreach ($metaNodes as $metaNode) {
            $this->addField(Zend_Search_Lucene_Field::Text($metaNode->getAttribute('name'),
                                                           $metaNode->getAttribute('content'),
                                                           $this->_doc->actualEncoding));
        }

        $docBody = '';
        $bodyNodes = $xpath->query('/html/body');
        foreach ($bodyNodes as $bodyNode) {
            // body should always have only one entry, but we process all nodeset entries
            $this->_retrieveNodeText($bodyNode, $docBody);
        }
        if ($storeContent) {
            $this->addField(Zend_Search_Lucene_Field::Text('body', $docBody, $this->_doc->actualEncoding));
        } else {
            $this->addField(Zend_Search_Lucene_Field::UnStored('body', $docBody, $this->_doc->actualEncoding));
        }

        $linkNodes = $this->_doc->getElementsByTagName('a');
        foreach ($linkNodes as $linkNode) {
            if (($href = $linkNode->getAttribute('href')) != '' &&
                (!self::$_excludeNoFollowLinks  ||  strtolower($linkNode->getAttribute('rel')) != 'nofollow' )
               ) {
                $this->_links[] = $href;
            }
        }
        $this->_links = array_unique($this->_links);

        $linkNodes = $xpath->query('/html/head/link');
        foreach ($linkNodes as $linkNode) {
            if (($href = $linkNode->getAttribute('href')) != '') {
                $this->_headerLinks[] = $href;
            }
        }
        $this->_headerLinks = array_unique($this->_headerLinks);
    }

    /**
     * Set exclude nofollow links flag
     *
     * @param boolean $newValue
     */
    public static function setExcludeNoFollowLinks($newValue)
    {
        self::$_excludeNoFollowLinks = $newValue;
    }

    /**
     * Get exclude nofollow links flag
     *
     * @return boolean
     */
    public static function getExcludeNoFollowLinks()
    {
        return self::$_excludeNoFollowLinks;
    }

    /**
     * Get node text
     *
     * We should exclude scripts, which may be not included into comment tags, CDATA sections,
     *
     * @param DOMNode $node
     * @param string &$text
     */
    private function _retrieveNodeText(DOMNode $node, &$text)
    {
        if ($node->nodeType == XML_TEXT_NODE) {
            $text .= $node->nodeValue ;
            $text .= ' ';
        } else if ($node->nodeType == XML_ELEMENT_NODE  &&  $node->nodeName != 'script') {
            foreach ($node->childNodes as $childNode) {
                $this->_retrieveNodeText($childNode, $text);
            }
        }
    }

    /**
     * Get document HREF links
     *
     * @return array
     */
    public function getLinks()
    {
        return $this->_links;
    }

    /**
     * Get document header links
     *
     * @return array
     */
    public function getHeaderLinks()
    {
        return $this->_headerLinks;
    }

    /**
     * Load HTML document from a string
     *
     * @param string $data
     * @param boolean $storeContent
     * @return Zend_Search_Lucene_Document_Html
     */
    public static function loadHTML($data, $storeContent = false)
    {
        return new Zend_Search_Lucene_Document_Html($data, false, $storeContent);
    }

    /**
     * Load HTML document from a file
     *
     * @param string $file
     * @param boolean $storeContent
     * @return Zend_Search_Lucene_Document_Html
     */
    public static function loadHTMLFile($file, $storeContent = false)
    {
        return new Zend_Search_Lucene_Document_Html($file, true, $storeContent);
    }


    /**
     * Highlight text in text node
     *
     * @param DOMText $node
     * @param array   $wordsToHighlight
     * @param string  $color
     */
    public function _highlightTextNode(DOMText $node, $wordsToHighlight, $color)
    {
        $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
        $analyzer->setInput($node->nodeValue, $this->_doc->encoding);

        $matchedTokens = array();

        while (($token = $analyzer->nextToken()) !== null) {
            if (isset($wordsToHighlight[$token->getTermText()])) {
                $matchedTokens[] = $token;
            }
        }

        if (count($matchedTokens) == 0) {
            return;
        }

        $matchedTokens = array_reverse($matchedTokens);

        foreach ($matchedTokens as $token) {
            // Cut text after matched token
            $node->splitText($token->getEndOffset());

            // Cut matched node
            $matchedWordNode = $node->splitText($token->getStartOffset());

            $highlightedNode = $this->_doc->createElement('b', $matchedWordNode->nodeValue);
            $highlightedNode->setAttribute('style', 'color:black;background-color:' . $color);

            $node->parentNode->replaceChild($highlightedNode, $matchedWordNode);
        }
    }


    /**
     * highlight words in content of the specified node
     *
     * @param DOMNode $contextNode
     * @param array $wordsToHighlight
     * @param string $color
     */
    public function _highlightNode(DOMNode $contextNode, $wordsToHighlight, $color)
    {
        $textNodes = array();

        if (!$contextNode->hasChildNodes()) {
            return;
        }

        foreach ($contextNode->childNodes as $childNode) {
            if ($childNode->nodeType == XML_TEXT_NODE) {
                // process node later to leave childNodes structure untouched
                $textNodes[] = $childNode;
            } else {
                // Skip script nodes
                if ($childNode->nodeName != 'script') {
                    $this->_highlightNode($childNode, $wordsToHighlight, $color);
                }
            }
        }

        foreach ($textNodes as $textNode) {
            $this->_highlightTextNode($textNode, $wordsToHighlight, $color);
        }
    }



    /**
     * Highlight text with specified color
     *
     * @param string|array $words
     * @param string $color
     * @return string
     */
    public function highlight($words, $color = '#66ffff')
    {
        if (!is_array($words)) {
            $words = array($words);
        }
        $wordsToHighlight = array();

        $analyzer = Zend_Search_Lucene_Analysis_Analyzer::getDefault();
        foreach ($words as $wordString) {
            $wordsToHighlight = array_merge($wordsToHighlight, $analyzer->tokenize($wordString));
        }

        if (count($wordsToHighlight) == 0) {
            return $this->_doc->saveHTML();
        }

        $wordsToHighlightFlipped = array();
        foreach ($wordsToHighlight as $id => $token) {
            $wordsToHighlightFlipped[$token->getTermText()] = $id;
        }

        $xpath = new DOMXPath($this->_doc);

        $matchedNodes = $xpath->query("/html/body");
        foreach ($matchedNodes as $matchedNode) {
            $this->_highlightNode($matchedNode, $wordsToHighlightFlipped, $color);
        }

    }

    /**
     * Get HTML
     *
     * @return string
     */
    public function getHTML()
    {
        return $this->_doc->saveHTML();
    }
}

Search/Lucene/Document/Docx.php000066600000012276151256604610012372 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Search_Lucene_Document_OpenXml */
require_once 'Zend/Search/Lucene/Document/OpenXml.php';

if (class_exists('ZipArchive', false)) {

/**
 * Docx document.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Document_Docx extends Zend_Search_Lucene_Document_OpenXml {
    /**
     * Xml Schema - WordprocessingML
     *
     * @var string
     */
    const SCHEMA_WORDPROCESSINGML = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';

    /**
     * Object constructor
     *
     * @param string  $fileName
     * @param boolean $storeContent
     */
    private function __construct($fileName, $storeContent) {
        // Document data holders
        $documentBody = array();
        $coreProperties = array();

        // Open OpenXML package
        $package = new ZipArchive();
        $package->open($fileName);

        // Read relations and search for officeDocument
        $relations = simplexml_load_string($package->getFromName('_rels/.rels'));
        foreach($relations->Relationship as $rel) {
            if ($rel ["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) {
                // Found office document! Read in contents...
                $contents = simplexml_load_string($package->getFromName(
                                                                $this->absoluteZipPath(dirname($rel['Target'])
                                                              . '/'
                                                              . basename($rel['Target']))
                                                                       ));

                $contents->registerXPathNamespace('w', Zend_Search_Lucene_Document_Docx::SCHEMA_WORDPROCESSINGML);
                $paragraphs = $contents->xpath('//w:body/w:p');

                foreach ($paragraphs as $paragraph) {
                    $runs = $paragraph->xpath('.//w:r/*[name() = "w:t" or name() = "w:br"]');

                    if ($runs === false) {
                    	// Paragraph doesn't contain any text or breaks
                    	continue;
                    }

                    foreach ($runs as $run) {
                     if ($run->getName() == 'br') {
                         // Break element
                         $documentBody[] = ' ';
                     } else {
                     	$documentBody[] = (string)$run;
                     }
                    }

                    // Add space after each paragraph. So they are not bound together.
                    $documentBody[] = ' ';
                }

                break;
            }
        }

        // Read core properties
        $coreProperties = $this->extractMetaData($package);

        // Close file
        $package->close();

        // Store filename
        $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName, 'UTF-8'));

        // Store contents
        if ($storeContent) {
            $this->addField(Zend_Search_Lucene_Field::Text('body', implode('', $documentBody), 'UTF-8'));
        } else {
            $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode('', $documentBody), 'UTF-8'));
        }

        // Store meta data properties
        foreach ($coreProperties as $key => $value) {
            $this->addField(Zend_Search_Lucene_Field::Text($key, $value, 'UTF-8'));
        }

        // Store title (if not present in meta data)
        if (! isset($coreProperties['title'])) {
            $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName, 'UTF-8'));
        }
    }

    /**
     * Load Docx document from a file
     *
     * @param string  $fileName
     * @param boolean $storeContent
     * @return Zend_Search_Lucene_Document_Docx
     * @throws Zend_Search_Lucene_Document_Exception
     */
    public static function loadDocxFile($fileName, $storeContent = false) {
        if (!is_readable($fileName)) {
        	require_once 'Zend/Search/Lucene/Document/Exception.php';
        	throw new Zend_Search_Lucene_Document_Exception('Provided file \'' . $fileName . '\' is not readable.');
        }

    	return new Zend_Search_Lucene_Document_Docx($fileName, $storeContent);
    }
}

} // end if (class_exists('ZipArchive'))
Search/Lucene/Document/Exception.php000066600000002143151256604610013423 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * Framework base exception
 */
require_once 'Zend/Search/Lucene/Exception.php';


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

Search/Lucene/Document/Pptx.php000066600000016411151256604610012423 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Document_OpenXml */
require_once 'Zend/Search/Lucene/Document/OpenXml.php';

if (class_exists('ZipArchive', false)) {

/**
 * Pptx document.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Search_Lucene_Document_Pptx extends Zend_Search_Lucene_Document_OpenXml
{
    /**
     * Xml Schema - PresentationML
     *
     * @var string
     */
    const SCHEMA_PRESENTATIONML = 'http://schemas.openxmlformats.org/presentationml/2006/main';

    /**
     * Xml Schema - DrawingML
     *
     * @var string
     */
    const SCHEMA_DRAWINGML = 'http://schemas.openxmlformats.org/drawingml/2006/main';

    /**
     * Xml Schema - Slide relation
     *
     * @var string
     */
    const SCHEMA_SLIDERELATION = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide';

    /**
     * Xml Schema - Slide notes relation
     *
     * @var string
     */
    const SCHEMA_SLIDENOTESRELATION = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide';

    /**
     * Object constructor
     *
     * @param string  $fileName
     * @param boolean $storeContent
     */
    private function __construct($fileName, $storeContent)
    {
        // Document data holders
        $slides = array();
        $slideNotes = array();
        $documentBody = array();
        $coreProperties = array();

        // Open OpenXML package
        $package = new ZipArchive();
        $package->open($fileName);

        // Read relations and search for officeDocument
        $relations = simplexml_load_string($package->getFromName("_rels/.rels"));
        foreach ($relations->Relationship as $rel) {
            if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) {
                // Found office document! Search for slides...
                $slideRelations = simplexml_load_string($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/_rels/" . basename($rel["Target"]) . ".rels")) );
                foreach ($slideRelations->Relationship as $slideRel) {
                    if ($slideRel["Type"] == Zend_Search_Lucene_Document_Pptx::SCHEMA_SLIDERELATION) {
                        // Found slide!
                        $slides[ str_replace( 'rId', '', (string)$slideRel["Id"] ) ] = simplexml_load_string(
                            $package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($slideRel["Target"]) . "/" . basename($slideRel["Target"])) )
                        );

                        // Search for slide notes
                        $slideNotesRelations = simplexml_load_string($package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($slideRel["Target"]) . "/_rels/" . basename($slideRel["Target"]) . ".rels")) );
                        foreach ($slideNotesRelations->Relationship as $slideNoteRel) {
                            if ($slideNoteRel["Type"] == Zend_Search_Lucene_Document_Pptx::SCHEMA_SLIDENOTESRELATION) {
                                // Found slide notes!
                                $slideNotes[ str_replace( 'rId', '', (string)$slideRel["Id"] ) ] = simplexml_load_string(
                                    $package->getFromName( $this->absoluteZipPath(dirname($rel["Target"]) . "/" . dirname($slideRel["Target"]) . "/" . dirname($slideNoteRel["Target"]) . "/" . basename($slideNoteRel["Target"])) )
                                );

                                break;
                            }
                        }
                    }
                }

                break;
            }
        }

        // Sort slides
        ksort($slides);
        ksort($slideNotes);

        // Extract contents from slides
        foreach ($slides as $slideKey => $slide) {
            // Register namespaces
            $slide->registerXPathNamespace("p", Zend_Search_Lucene_Document_Pptx::SCHEMA_PRESENTATIONML);
            $slide->registerXPathNamespace("a", Zend_Search_Lucene_Document_Pptx::SCHEMA_DRAWINGML);

            // Fetch all text
            $textElements = $slide->xpath('//a:t');
            foreach ($textElements as $textElement) {
                $documentBody[] = (string)$textElement;
            }

            // Extract contents from slide notes
            if (isset($slideNotes[$slideKey])) {
                // Fetch slide note
                $slideNote = $slideNotes[$slideKey];

                // Register namespaces
                $slideNote->registerXPathNamespace("p", Zend_Search_Lucene_Document_Pptx::SCHEMA_PRESENTATIONML);
                $slideNote->registerXPathNamespace("a", Zend_Search_Lucene_Document_Pptx::SCHEMA_DRAWINGML);

                // Fetch all text
                $textElements = $slideNote->xpath('//a:t');
                foreach ($textElements as $textElement) {
                    $documentBody[] = (string)$textElement;
                }
            }
        }

        // Read core properties
        $coreProperties = $this->extractMetaData($package);

        // Close file
        $package->close();

        // Store filename
        $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName, 'UTF-8'));

            // Store contents
        if ($storeContent) {
            $this->addField(Zend_Search_Lucene_Field::Text('body', implode(' ', $documentBody), 'UTF-8'));
        } else {
            $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode(' ', $documentBody), 'UTF-8'));
        }

        // Store meta data properties
        foreach ($coreProperties as $key => $value)
        {
            $this->addField(Zend_Search_Lucene_Field::Text($key, $value, 'UTF-8'));
        }

        // Store title (if not present in meta data)
        if (!isset($coreProperties['title']))
        {
            $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName, 'UTF-8'));
        }
    }

    /**
     * Load Pptx document from a file
     *
     * @param string  $fileName
     * @param boolean $storeContent
     * @return Zend_Search_Lucene_Document_Pptx
     */
    public static function loadPptxFile($fileName, $storeContent = false)
    {
        return new Zend_Search_Lucene_Document_Pptx($fileName, $storeContent);
    }
}

} // end if (class_exists('ZipArchive'))
Search/Lucene/Document/OpenXml.php000066600000010461151256604610013051 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Search_Lucene_Document */
require_once 'Zend/Search/Lucene/Document.php';

if (class_exists('ZipArchive', false)) {

/**
 * OpenXML document.
 *
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Document
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Search_Lucene_Document_OpenXml extends Zend_Search_Lucene_Document
{
    /**
     * Xml Schema - Relationships
     *
     * @var string
     */
    const SCHEMA_RELATIONSHIP = 'http://schemas.openxmlformats.org/package/2006/relationships';

    /**
     * Xml Schema - Office document
     *
     * @var string
     */
    const SCHEMA_OFFICEDOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument';

    /**
     * Xml Schema - Core properties
     *
     * @var string
     */
    const SCHEMA_COREPROPERTIES = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties';

    /**
     * Xml Schema - Dublin Core
     *
     * @var string
     */
    const SCHEMA_DUBLINCORE = 'http://purl.org/dc/elements/1.1/';

    /**
     * Xml Schema - Dublin Core Terms
     *
     * @var string
     */
    const SCHEMA_DUBLINCORETERMS = 'http://purl.org/dc/terms/';

    /**
     * Extract metadata from document
     *
     * @param ZipArchive $package    ZipArchive OpenXML package
     * @return array    Key-value pairs containing document meta data
     */
    protected function extractMetaData(ZipArchive $package)
    {
        // Data holders
        $coreProperties = array();
        
        // Read relations and search for core properties
        $relations = simplexml_load_string($package->getFromName("_rels/.rels"));
        foreach ($relations->Relationship as $rel) {
            if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) {
                // Found core properties! Read in contents...
                $contents = simplexml_load_string(
                    $package->getFromName(dirname($rel["Target"]) . "/" . basename($rel["Target"]))
                );

                foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORE) as $child) {
                    $coreProperties[$child->getName()] = (string)$child;
                }
                foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) as $child) {
                    $coreProperties[$child->getName()] = (string)$child;
                }
                foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORETERMS) as $child) {
                    $coreProperties[$child->getName()] = (string)$child;
                }
            }
        }
        
        return $coreProperties;
    }
    
    /**
     * Determine absolute zip path
     *
     * @param string $path
     * @return string
     */
    protected function absoluteZipPath($path) {
        $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = array();
        foreach ($parts as $part) {
            if ('.' == $part) continue;
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return implode('/', $absolutes);
    }
}

} // end if (class_exists('ZipArchive'))
Search/Exception.php000066600000002051151256604610010430 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Search
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * Framework base exception
 */
require_once 'Zend/Exception.php';


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

Http/Cookie.php000066600000022507151256604610007425 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Http
 * @subpackage Cookie
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com/)
 * @version    $Id: Cookie.php 14130 2009-02-21 11:24:22Z yoshida@zend.co.jp $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

require_once 'Zend/Uri/Http.php';

/**
 * Zend_Http_Cookie is a class describing an HTTP cookie and all it's parameters.
 *
 * Zend_Http_Cookie is a class describing an HTTP cookie and all it's parameters. The
 * class also enables validating whether the cookie should be sent to the server in
 * a specified scenario according to the request URI, the expiry time and whether
 * session cookies should be used or not. Generally speaking cookies should be
 * contained in a Cookiejar object, or instantiated manually and added to an HTTP
 * request.
 *
 * See http://wp.netscape.com/newsref/std/cookie_spec.html for some specs.
 *
 * @category    Zend
 * @package     Zend_Http
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com/)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Http_Cookie
{
    /**
     * Cookie name
     *
     * @var string
     */
    protected $name;

    /**
     * Cookie value
     *
     * @var string
     */
    protected $value;

    /**
     * Cookie expiry date
     *
     * @var int
     */
    protected $expires;

    /**
     * Cookie domain
     *
     * @var string
     */
    protected $domain;

    /**
     * Cookie path
     *
     * @var string
     */
    protected $path;

    /**
     * Whether the cookie is secure or not
     *
     * @var boolean
     */
    protected $secure;

    /**
     * Cookie object constructor
     *
     * @todo Add validation of each one of the parameters (legal domain, etc.)
     *
     * @param string $name
     * @param string $value
     * @param string $domain
     * @param int $expires
     * @param string $path
     * @param bool $secure
     */
    public function __construct($name, $value, $domain, $expires = null, $path = null, $secure = false)
    {
        if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
            require_once 'Zend/Http/Exception.php';
            throw new Zend_Http_Exception("Cookie name cannot contain these characters: =,; \\t\\r\\n\\013\\014 ({$name})");
        }

        if (! $this->name = (string) $name) {
            require_once 'Zend/Http/Exception.php';
            throw new Zend_Http_Exception('Cookies must have a name');
        }

        if (! $this->domain = (string) $domain) {
            require_once 'Zend/Http/Exception.php';
            throw new Zend_Http_Exception('Cookies must have a domain');
        }

        $this->value = (string) $value;
        $this->expires = ($expires === null ? null : (int) $expires);
        $this->path = ($path ? $path : '/');
        $this->secure = $secure;
    }

    /**
     * Get Cookie name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Get cookie value
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Get cookie domain
     *
     * @return string
     */
    public function getDomain()
    {
        return $this->domain;
    }

    /**
     * Get the cookie path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Get the expiry time of the cookie, or null if no expiry time is set
     *
     * @return int|null
     */
    public function getExpiryTime()
    {
        return $this->expires;
    }

    /**
     * Check whether the cookie should only be sent over secure connections
     *
     * @return boolean
     */
    public function isSecure()
    {
        return $this->secure;
    }

    /**
     * Check whether the cookie has expired
     *
     * Always returns false if the cookie is a session cookie (has no expiry time)
     *
     * @param int $now Timestamp to consider as "now"
     * @return boolean
     */
    public function isExpired($now = null)
    {
        if ($now === null) $now = time();
        if (is_int($this->expires) && $this->expires < $now) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Check whether the cookie is a session cookie (has no expiry time set)
     *
     * @return boolean
     */
    public function isSessionCookie()
    {
        return ($this->expires === null);
    }

    /**
     * Checks whether the cookie should be sent or not in a specific scenario
     *
     * @param string|Zend_Uri_Http $uri URI to check against (secure, domain, path)
     * @param boolean $matchSessionCookies Whether to send session cookies
     * @param int $now Override the current time when checking for expiry time
     * @return boolean
     */
    public function match($uri, $matchSessionCookies = true, $now = null)
    {
        if (is_string ($uri)) {
            $uri = Zend_Uri_Http::factory($uri);
        }

        // Make sure we have a valid Zend_Uri_Http object
        if (! ($uri->valid() && ($uri->getScheme() == 'http' || $uri->getScheme() =='https'))) {
            require_once 'Zend/Http/Exception.php';
            throw new Zend_Http_Exception('Passed URI is not a valid HTTP or HTTPS URI');
        }

        // Check that the cookie is secure (if required) and not expired
        if ($this->secure && $uri->getScheme() != 'https') return false;
        if ($this->isExpired($now)) return false;
        if ($this->isSessionCookie() && ! $matchSessionCookies) return false;

        // Validate domain and path
        // Domain is validated using tail match, while path is validated using head match
        $domain_preg = preg_quote($this->getDomain(), "/");
        if (! preg_match("/{$domain_preg}$/", $uri->getHost())) return false;
        $path_preg = preg_quote($this->getPath(), "/");
        if (! preg_match("/^{$path_preg}/", $uri->getPath())) return false;

        // If we didn't die until now, return true.
        return true;
    }

    /**
     * Get the cookie as a string, suitable for sending as a "Cookie" header in an
     * HTTP request
     *
     * @return string
     */
    public function __toString()
    {
        return $this->name . '=' . urlencode($this->value) . ';';
    }

    /**
     * Generate a new Cookie object from a cookie string
     * (for example the value of the Set-Cookie HTTP header)
     *
     * @param string $cookieStr
     * @param Zend_Uri_Http|string $ref_uri Reference URI for default values (domain, path)
     * @return Zend_Http_Cookie A new Zend_Http_Cookie object or false on failure.
     */
    public static function fromString($cookieStr, $ref_uri = null)
    {
        // Set default values
        if (is_string($ref_uri)) {
            $ref_uri = Zend_Uri_Http::factory($ref_uri);
        }

        $name    = '';
        $value   = '';
        $domain  = '';
        $path    = '';
        $expires = null;
        $secure  = false;
        $parts   = explode(';', $cookieStr);

        // If first part does not include '=', fail
        if (strpos($parts[0], '=') === false) return false;

        // Get the name and value of the cookie
        list($name, $value) = explode('=', trim(array_shift($parts)), 2);
        $name  = trim($name);
        $value = urldecode(trim($value));

        // Set default domain and path
        if ($ref_uri instanceof Zend_Uri_Http) {
            $domain = $ref_uri->getHost();
            $path = $ref_uri->getPath();
            $path = substr($path, 0, strrpos($path, '/'));
        }

        // Set other cookie parameters
        foreach ($parts as $part) {
            $part = trim($part);
            if (strtolower($part) == 'secure') {
                $secure = true;
                continue;
            }

            $keyValue = explode('=', $part, 2);
            if (count($keyValue) == 2) {
                list($k, $v) = $keyValue;
                switch (strtolower($k))    {
                    case 'expires':
                        $expires = strtotime($v);
                        break;
                    case 'path':
                        $path = $v;
                        break;
                    case 'domain':
                        $domain = $v;
                        break;
                    default:
                        break;
                }
            }
        }

        if ($name !== '') {
            return new self($name, $value, $domain, $expires, $path, $secure);
        } else {
            return false;
        }
    }
}
Http/Client/Adapter/Socket.php000066600000030666151256604610012247 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Http
 * @subpackage Client_Adapter
 * @version    $Id: Socket.php 13014 2008-12-04 12:07:05Z yoshida@zend.co.jp $
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

require_once 'Zend/Uri/Http.php';
require_once 'Zend/Http/Client/Adapter/Interface.php';

/**
 * A sockets based (stream_socket_client) adapter class for Zend_Http_Client. Can be used
 * on almost every PHP environment, and does not require any special extensions.
 *
 * @category   Zend
 * @package    Zend_Http
 * @subpackage Client_Adapter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Http_Client_Adapter_Socket implements Zend_Http_Client_Adapter_Interface
{
    /**
     * The socket for server connection
     *
     * @var resource|null
     */
    protected $socket = null;

    /**
     * What host/port are we connected to?
     *
     * @var array
     */
    protected $connected_to = array(null, null);

    /**
     * Parameters array
     *
     * @var array
     */
    protected $config = array(
        'persistent'    => false,
        'ssltransport'  => 'ssl',
        'sslcert'       => null,
        'sslpassphrase' => null
    );

    /**
     * Request method - will be set by write() and might be used by read()
     *
     * @var string
     */
    protected $method = null;

    /**
     * Adapter constructor, currently empty. Config is set using setConfig()
     *
     */
    public function __construct()
    {
    }

    /**
     * Set the configuration array for the adapter
     *
     * @param array $config
     */
    public function setConfig($config = array())
    {
        if (! is_array($config)) {
            require_once 'Zend/Http/Client/Adapter/Exception.php';
            throw new Zend_Http_Client_Adapter_Exception(
                '$concig expects an array, ' . gettype($config) . ' recieved.');
        }

        foreach ($config as $k => $v) {
            $this->config[strtolower($k)] = $v;
        }
    }

    /**
     * Connect to the remote server
     *
     * @param string  $host
     * @param int     $port
     * @param boolean $secure
     * @param int     $timeout
     */
    public function connect($host, $port = 80, $secure = false)
    {
        // If the URI should be accessed via SSL, prepend the Hostname with ssl://
        $host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;

        // If we are connected to the wrong host, disconnect first
        if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
            if (is_resource($this->socket)) $this->close();
        }

        // Now, if we are not connected, connect
        if (! is_resource($this->socket) || ! $this->config['keepalive']) {
            $context = stream_context_create();
            if ($secure) {
                if ($this->config['sslcert'] !== null) {
                    if (! stream_context_set_option($context, 'ssl', 'local_cert',
                                                    $this->config['sslcert'])) {
                        require_once 'Zend/Http/Client/Adapter/Exception.php';
                        throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
                    }
                }
                if ($this->config['sslpassphrase'] !== null) {
                    if (! stream_context_set_option($context, 'ssl', 'passphrase',
                                                    $this->config['sslpassphrase'])) {
                        require_once 'Zend/Http/Client/Adapter/Exception.php';
                        throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
                    }
                }
            }

            $flags = STREAM_CLIENT_CONNECT;
            if ($this->config['persistent']) $flags |= STREAM_CLIENT_PERSISTENT;
             $errno = $errstr = '';
            $this->socket = @stream_socket_client($host . ':' . $port,
                                                  $errno,
                                                  $errstr,
                                                  (int) $this->config['timeout'],
                                                  $flags,
                                                  $context);
            if (! $this->socket) {
                $this->close();
                require_once 'Zend/Http/Client/Adapter/Exception.php';
                throw new Zend_Http_Client_Adapter_Exception(
                    'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
            }

            // Set the stream timeout
            if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
                require_once 'Zend/Http/Client/Adapter/Exception.php';
                throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
            }

            // Update connected_to
            $this->connected_to = array($host, $port);
        }
    }

    /**
     * Send request to the remote server
     *
     * @param string        $method
     * @param Zend_Uri_Http $uri
     * @param string        $http_ver
     * @param array         $headers
     * @param string        $body
     * @return string Request as string
     */
    public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
    {
        // Make sure we're properly connected
        if (! $this->socket) {
            require_once 'Zend/Http/Client/Adapter/Exception.php';
            throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are not connected');
        }

        $host = $uri->getHost();
        $host = (strtolower($uri->getScheme()) == 'https' ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
        if ($this->connected_to[0] != $host || $this->connected_to[1] != $uri->getPort()) {
            require_once 'Zend/Http/Client/Adapter/Exception.php';
            throw new Zend_Http_Client_Adapter_Exception('Trying to write but we are connected to the wrong host');
        }

        // Save request method for later
        $this->method = $method;

        // Build request headers
        $path = $uri->getPath();
        if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
        $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
        foreach ($headers as $k => $v) {
            if (is_string($k)) $v = ucfirst($k) . ": $v";
            $request .= "$v\r\n";
        }

        // Add the request body
        $request .= "\r\n" . $body;

        // Send the request
        if (! @fwrite($this->socket, $request)) {
            require_once 'Zend/Http/Client/Adapter/Exception.php';
            throw new Zend_Http_Client_Adapter_Exception('Error writing request to server');
        }

        return $request;
    }

    /**
     * Read response from server
     *
     * @return string
     */
    public function read()
    {
        // First, read headers only
        $response = '';
        $gotStatus = false;
        while (($line = @fgets($this->socket)) !== false) {
            $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
            if ($gotStatus) {
                $response .= $line;
                if (rtrim($line) === '') break;
            }
        }

        $statusCode = Zend_Http_Response::extractCode($response);

        // Handle 100 and 101 responses internally by restarting the read again
        if ($statusCode == 100 || $statusCode == 101) return $this->read();

        /**
         * Responses to HEAD requests and 204 or 304 responses are not expected
         * to have a body - stop reading here
         */
        if ($statusCode == 304 || $statusCode == 204 ||
            $this->method == Zend_Http_Client::HEAD) return $response;

        // Check headers to see what kind of connection / transfer encoding we have
        $headers = Zend_Http_Response::extractHeaders($response);

        // If we got a 'transfer-encoding: chunked' header
        if (isset($headers['transfer-encoding'])) {
            if ($headers['transfer-encoding'] == 'chunked') {
                do {
                    $line  = @fgets($this->socket);
                    $chunk = $line;

                    // Figure out the next chunk size
                    $chunksize = trim($line);
                    if (! ctype_xdigit($chunksize)) {
                        $this->close();
                        require_once 'Zend/Http/Client/Adapter/Exception.php';
                        throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' .
                            $chunksize . '" unable to read chunked body');
                    }

                    // Convert the hexadecimal value to plain integer
                    $chunksize = hexdec($chunksize);

                    // Read chunk
                    $left_to_read = $chunksize;
                    while ($left_to_read > 0) {
                        $line = @fread($this->socket, $left_to_read);
                        if ($line === false || strlen($line) === 0)
                        {
                            break;
                        } else {
                            $chunk .= $line;
                            $left_to_read -= strlen($line);
                        }

                        // Break if the connection ended prematurely
                        if (feof($this->socket)) break;
                    }

                    $chunk .= @fgets($this->socket);
                    $response .= $chunk;
                } while ($chunksize > 0);

            } else {
                throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' .
                    $headers['transfer-encoding'] . '" transfer encoding');
            }

        // Else, if we got the content-length header, read this number of bytes
        } elseif (isset($headers['content-length'])) {
            $left_to_read = $headers['content-length'];
            $chunk = '';
            while ($left_to_read > 0) {
                $chunk = @fread($this->socket, $left_to_read);
                if ($chunk === false || strlen($chunk) === 0)
                {
                    break;
                } else {
                    $left_to_read -= strlen($chunk);
                    $response .= $chunk;
                }

                // Break if the connection ended prematurely
                if (feof($this->socket)) break;
            }

        // Fallback: just read the response until EOF
        } else {
        	do {
        		$buff = @fread($this->socket, 8192);
        		if ($buff === false || strlen($buff) === 0)
        		{
        			break;
        		} else {
                    $response .= $buff;
        		}
        	} while (feof($this->socket) === false);

            $this->close();
        }

        // Close the connection if requested to do so by the server
        if (isset($headers['connection']) && $headers['connection'] == 'close') {
            $this->close();
        }

        return $response;
    }

    /**
     * Close the connection to the server
     *
     */
    public function close()
    {
        if (is_resource($this->socket)) @fclose($this->socket);
        $this->socket = null;
        $this->connected_to = array(null, null);
    }

    /**
     * Destructor: make sure the socket is disconnected
     *
     * If we are in persistent TCP mode, will not close the connection
     *
     */
    public function __destruct()
    {
        if (! $this->config['persistent']) {
            if ($this->socket) $this->close();
        }
    }
}
Http/Client/Adapter/Test.php000066600000013015151256604610011723 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Http
 * @subpackage Client_Adapter
 * @version    $Id: Test.php 12104 2008-10-23 22:36:28Z shahar $
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

require_once 'Zend/Uri/Http.php';
require_once 'Zend/Http/Response.php';
require_once 'Zend/Http/Client/Adapter/Interface.php';

/**
 * A testing-purposes adapter.
 *
 * Should be used to test all components that rely on Zend_Http_Client,
 * without actually performing an HTTP request. You should instantiate this
 * object manually, and then set it as the client's adapter. Then, you can
 * set the expected response using the setResponse() method.
 *
 * @category   Zend
 * @package    Zend_Http
 * @subpackage Client_Adapter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Http_Client_Adapter_Test implements Zend_Http_Client_Adapter_Interface
{
    /**
     * Parameters array
     *
     * @var array
     */
    protected $config = array();

    /**
     * Buffer of responses to be returned by the read() method.  Can be
     * set using setResponse() and addResponse().
     *
     * @var array
     */
    protected $responses = array("HTTP/1.1 400 Bad Request\r\n\r\n");

    /**
     * Current position in the response buffer
     *
     * @var integer
     */
    protected $responseIndex = 0;

    /**
     * Adapter constructor, currently empty. Config is set using setConfig()
     *
     */
    public function __construct()
    { }

    /**
     * Set the configuration array for the adapter
     *
     * @param array $config
     */
    public function setConfig($config = array())
    {
        if (! is_array($config)) {
            require_once 'Zend/Http/Client/Adapter/Exception.php';
            throw new Zend_Http_Client_Adapter_Exception(
                '$config expects an array, ' . gettype($config) . ' recieved.');
        }

        foreach ($config as $k => $v) {
            $this->config[strtolower($k)] = $v;
        }
    }

    /**
     * Connect to the remote server
     *
     * @param string  $host
     * @param int     $port
     * @param boolean $secure
     * @param int     $timeout
     */
    public function connect($host, $port = 80, $secure = false)
    { }

    /**
     * Send request to the remote server
     *
     * @param string        $method
     * @param Zend_Uri_Http $uri
     * @param string        $http_ver
     * @param array         $headers
     * @param string        $body
     * @return string Request as string
     */
    public function write($method, $uri, $http_ver = '1.1', $headers = array(), $body = '')
    {
        $host = $uri->getHost();
            $host = (strtolower($uri->getScheme()) == 'https' ? 'sslv2://' . $host : $host);

        // Build request headers
        $path = $uri->getPath();
        if ($uri->getQuery()) $path .= '?' . $uri->getQuery();
        $request = "{$method} {$path} HTTP/{$http_ver}\r\n";
        foreach ($headers as $k => $v) {
            if (is_string($k)) $v = ucfirst($k) . ": $v";
            $request .= "$v\r\n";
        }

        // Add the request body
        $request .= "\r\n" . $body;

        // Do nothing - just return the request as string

        return $request;
    }

    /**
     * Return the response set in $this->setResponse()
     *
     * @return string
     */
    public function read()
    {
        if ($this->responseIndex >= count($this->responses)) {
            $this->responseIndex = 0;
        }
        return $this->responses[$this->responseIndex++];
    }

    /**
     * Close the connection (dummy)
     *
     */
    public function close()
    { }

    /**
     * Set the HTTP response(s) to be returned by this adapter
     *
     * @param Zend_Http_Response|array|string $response
     */
    public function setResponse($response)
    {
        if ($response instanceof Zend_Http_Response) {
            $response = $response->asString();
        }

        $this->responses = (array)$response;
        $this->responseIndex = 0;
    }

    /**
     * Add another response to the response buffer.
     *
     * @param string $response
     */
    public function addResponse($response)
    {
        $this->responses[] = $response;
    }

    /**
     * Sets the position of the response buffer.  Selects which
     * response will be returned on the next call to read().
     *
     * @param integer $index
     */
    public function setResponseIndex($index)
    {
        if ($index < 0 || $index >= count($this->responses)) {
            require_once 'Zend/Http/Client/Adapter/Exception.php';
            throw new Zend_Http_Client_Adapter_Exception(
                'Index out of range of response buffer size');
        }
        $this->responseIndex = $index;
    }
}
Log/Exception.php000066600000002226151256604610007750 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Log
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 */

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

/**
 * @category   Zend
 * @package    Zend_Log
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 */
class Zend_Log_Exception extends Zend_Exception
{}
Pdf/FileParser/Font/OpenType/TrueType.php000066600000004670151256604610014275 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage FileParser
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_FileParser_Font_OpenType */
require_once 'Zend/Pdf/FileParser/Font/OpenType.php';


/**
 * Parses an OpenType font file containing TrueType outlines.
 *
 * @package    Zend_Pdf
 * @subpackage FileParser
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_FileParser_Font_OpenType_TrueType extends Zend_Pdf_FileParser_Font_OpenType
{
  /**** Public Interface ****/


  /* Concrete Class Implementation */

    /**
     * Verifies that the font file actually contains TrueType outlines.
     *
     * @throws Zend_Pdf_Exception
     */
    public function screen()
    {
        if ($this->_isScreened) {
            return;
        }

        parent::screen();

        switch ($this->_readScalerType()) {
            case 0x00010000:    // version 1.0 - Windows TrueType signature
                break;

            case 0x74727565:    // 'true' - Macintosh TrueType signature
                break;

            default:
                throw new Zend_Pdf_Exception('Not a TrueType font file',
                                             Zend_Pdf_Exception::WRONG_FONT_TYPE);
        }

        $this->fontType = Zend_Pdf_Font::TYPE_TRUETYPE;
        $this->_isScreened = true;
    }

    /**
     * Reads and parses the TrueType font data from the file on disk.
     *
     * @throws Zend_Pdf_Exception
     */
    public function parse()
    {
        if ($this->_isParsed) {
            return;
        }

        parent::parse();

        /* There is nothing additional to parse for TrueType fonts at this time.
         */

        $this->_isParsed = true;
    }
}
Pdf/FileParser/Image/Png.php000066600000026261151256604610011611 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage FileParser
 * @copyright  Copyright (c) 2006 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_FileParser_Image */
require_once 'Zend/Pdf/FileParser/Image.php';


/**
 * Abstract base class for Image file parsers.
 *
 * @package    Zend_Pdf
 * @subpackage FileParser
 * @copyright  Copyright (c) 2006 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_FileParser_Image_Png extends Zend_Pdf_FileParser_Image
{
     protected $_isPNG;
     protected $_width;
     protected $_height;
     protected $_bits;
     protected $_color;
     protected $_compression;
     protected $_preFilter;
     protected $_interlacing;

     protected $_imageData;
     protected $_paletteData;
     protected $_transparencyData;

  /**** Public Interface ****/

     public function getWidth() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_width;
     }

     public function getHeight() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_width;
     }

     public function getBitDepth() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_bits;
     }

     public function getColorSpace() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_color;
     }

     public function getCompressionStrategy() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_compression;
     }

     public function getPaethFilter() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_preFilter;
     }

     public function getInterlacingMode() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_interlacing;
     }

     public function getRawImageData() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_imageData;
     }

     public function getRawPaletteData() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_paletteData;
     }

     public function getRawTransparencyData() {
          if(!$this->_isParsed) {
               $this->parse();
          }
          return $this->_transparencyData;
     }

  /* Semi-Concrete Class Implementation */

    /**
     * Verifies that the image file is in the expected format.
     *
     * @throws Zend_Pdf_Exception
     */
    public function screen()
    {
         if ($this->_isScreened) {
             return;
         }
         return $this->_checkSignature();
    }

    /**
     * Reads and parses the image data from the file on disk.
     *
     * @throws Zend_Pdf_Exception
     */
    public function parse()
    {
        if ($this->_isParsed) {
            return;
        }

        /* Screen the font file first, if it hasn't been done yet.
        */
        $this->screen();

        $this->_parseIHDRChunk();
        $this->_parseChunks();
    }


    protected function _parseSignature() {
         $this->moveToOffset(1); //Skip the first byte (%)
         if('PNG' != $this->readBytes(3)) {
               $this->_isPNG = false;
         } else {
               $this->_isPNG = true;
         }
    }

    protected function _checkSignature() {
         if(!isset($this->_isPNG)) {
              $this->_parseSignature();
         }
         return $this->_isPNG;
    }

    protected function _parseChunks() {
         $this->moveToOffset(33); //Variable chunks start at the end of IHDR

         //Start processing chunks. If there are no more bytes to read parsing is complete.
         $size = $this->getSize();
         while($size - $this->getOffset() >= 8) {
              $chunkLength = $this->readUInt(4);
              if($chunkLength < 0 || ($chunkLength + $this->getOffset() + 4) > $size) {
                   throw new Zend_Pdf_Exception("PNG Corrupt: Invalid Chunk Size In File.");
              }

              $chunkType = $this->readBytes(4);
              $offset = $this->getOffset();

              //If we know how to process the chunk, do it here, else ignore the chunk and move on to the next
              switch($chunkType) {
                   case 'IDAT': // This chunk may appear more than once. It contains the actual image data.
                       $this->_parseIDATChunk($offset, $chunkLength);
                       break;

                   case 'PLTE': // This chunk contains the image palette.
                       $this->_parsePLTEChunk($offset, $chunkLength);
                       break;

                   case 'tRNS': // This chunk contains non-alpha channel transparency data
                       $this->_parseTRNSChunk($offset, $chunkLength);
                       break;

                   case 'IEND':
                       break 2; //End the loop too

                   //@TODO Implement the rest of the PNG chunks. (There are many not implemented here)
              }
              if($offset + $chunkLength + 4 < $size) {
                  $this->moveToOffset($offset + $chunkLength + 4); //Skip past the data finalizer. (Don't rely on the parse to leave the offsets correct)
              }
         }
         if(empty($this->_imageData)) {
              throw new Zend_Pdf_Exception ( "This PNG is corrupt. All png must contain IDAT chunks." );
         }
    }

    protected function _parseIHDRChunk() {
         $this->moveToOffset(12); //IHDR must always start at offset 12 and run for 17 bytes
         if(!$this->readBytes(4) == 'IHDR') {
              throw new Zend_Pdf_Exception( "This PNG is corrupt. The first chunk in a PNG file must be IHDR." );
         }
         $this->_width = $this->readUInt(4);
         $this->_height = $this->readUInt(4);
         $this->_bits = $this->readInt(1);
         $this->_color = $this->readInt(1);
         $this->_compression = $this->readInt(1);
         $this->_preFilter = $this->readInt(1);
         $this->_interlacing = $this->readInt(1);
         if($this->_interlacing != Zend_Pdf_Image::PNG_INTERLACING_DISABLED) {
              throw new Zend_Pdf_Exception( "Only non-interlaced images are currently supported." );
         }
    }

    protected function _parseIDATChunk($chunkOffset, $chunkLength) {
         $this->moveToOffset($chunkOffset);
         if(!isset($this->_imageData)) {
              $this->_imageData = $this->readBytes($chunkLength);
         } else {
              $this->_imageData .= $this->readBytes($chunkLength);
         }
    }

    protected function _parsePLTEChunk($chunkOffset, $chunkLength) {
         $this->moveToOffset($chunkOffset);
         $this->_paletteData = $this->readBytes($chunkLength);
    }

    protected function _parseTRNSChunk($chunkOffset, $chunkLength) {
         $this->moveToOffset($chunkOffset);

         //Processing of tRNS data varies dependending on the color depth

         switch($this->_color) {
             case Zend_Pdf_Image::PNG_CHANNEL_GRAY:
                  $baseColor = $this->readInt(1);
                  $this->_transparencyData = array($baseColor, $baseColor);
                  break;

             case Zend_Pdf_Image::PNG_CHANNEL_RGB:

                  //@TODO Fix this hack.
                  //This parser cheats and only uses the lsb's (and only works with < 16 bit depth images)

                  /*
                       From the standard:

                       For color type 2 (truecolor), the tRNS chunk contains a single RGB color value, stored in the format:

                       Red:   2 bytes, range 0 .. (2^bitdepth)-1
                       Green: 2 bytes, range 0 .. (2^bitdepth)-1
                       Blue:  2 bytes, range 0 .. (2^bitdepth)-1

                       (If the image bit depth is less than 16, the least significant bits are used and the others are 0.)
                       Pixels of the specified color value are to be treated as transparent (equivalent to alpha value 0);
                       all other pixels are to be treated as fully opaque (alpha value 2bitdepth-1).

                  */

                  $red = $this->readInt(1);
                  $this->skipBytes(1);
                  $green = $this->readInt(1);
                  $this->skipBytes(1);
                  $blue = $this->readInt(1);

                  $this->_transparencyData = array($red, $red, $green, $green, $blue, $blue);

                  break;

             case Zend_Pdf_Image::PNG_CHANNEL_INDEXED:

                  //@TODO Fix this hack.
                  //This parser cheats too. It only masks the first color in the palette.

                  /*
                       From the standard:

                       For color type 3 (indexed color), the tRNS chunk contains a series of one-byte alpha values, corresponding to entries in the PLTE chunk:

                          Alpha for palette index 0:  1 byte
                          Alpha for palette index 1:  1 byte
                          ...etc...

                       Each entry indicates that pixels of the corresponding palette index must be treated as having the specified alpha value.
                       Alpha values have the same interpretation as in an 8-bit full alpha channel: 0 is fully transparent, 255 is fully opaque,
                       regardless of image bit depth. The tRNS chunk must not contain more alpha values than there are palette entries,
                       but tRNS can contain fewer values than there are palette entries. In this case, the alpha value for all remaining palette
                       entries is assumed to be 255. In the common case in which only palette index 0 need be made transparent, only a one-byte
                       tRNS chunk is needed.

                  */

                  $tmpData = $this->readBytes($chunkLength);
                  if(($trnsIdx = strpos($tmpData, chr(0))) !== false) {
                       $this->_transparencyData = array($trnsIdx, $trnsIdx);
                  }

                  break;

             case Zend_Pdf_Image::PNG_CHANNEL_GRAY_ALPHA:
                  //Fall through to the next case
             case Zend_Pdf_Image::PING_CHANNEL_RGB_ALPHA:
                  throw new Zend_Pdf_Exception( "tRNS chunk illegal for Alpha Channel Images" );
                  break;
         }
    }
}


Pdf/UpdateInfoContainer.php000066600000005650151256604610011707 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Element */
require_once 'Zend/Pdf/Element.php';

/** Zend_Pdf_Element_Object */
require_once 'Zend/Pdf/Element/Object.php';

/** Zend_Memory */
require_once 'Zend/Memory.php';


/**
 * Container which collects updated object info.
 *
 * @package    Zend_Pdf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_UpdateInfoContainer
{
    /**
     * Object number
     *
     * @var integer
     */
    private $_objNum;

    /**
     * Generation number
     *
     * @var integer
     */
    private $_genNum;


    /**
     * Flag, which signals, that object is free
     *
     * @var boolean
     */
    private $_isFree;

    /**
     * String representation of the object
     *
     * @var Zend_Memory_Container|null
     */
    private $_dump = null;

    /**
     * Object constructor
     *
     * @param integer $objCount
     */
    public function __construct($objNum, $genNum, $isFree, $dump = null)
    {
        $this->_objNum = $objNum;
        $this->_genNum = $genNum;
        $this->_isFree = $isFree;

        if ($dump !== null) {
            if (strlen($dump) > 1024) {
                $this->_dump = Zend_Pdf::getMemoryManager()->create($dump);
            } else {
                $this->_dump = $dump;
            }
        }
    }


    /**
     * Get object number
     *
     * @return integer
     */
    public function getObjNum()
    {
        return $this->_objNum;
    }

    /**
     * Get generation number
     *
     * @return integer
     */
    public function getGenNum()
    {
        return $this->_genNum;
    }

    /**
     * Check, that object is free
     *
     * @return boolean
     */
    public function isFree()
    {
        return $this->_isFree;
    }

    /**
     * Get string representation of the object
     *
     * @return string
     */
    public function getObjectDump()
    {
        if ($this->_dump === null) {
            return '';
        }

        if (is_string($this->_dump)) {
            return $this->_dump;
        }

        return $this->_dump->getRef();
    }
}

Pdf/Font.php000066600000060160151256604610006711 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_FileParserDataSource */
require_once 'Zend/Pdf/FileParserDataSource.php';

/** Zend_Pdf_FileParserDataSource_File */
require_once 'Zend/Pdf/FileParserDataSource/File.php';

/** Zend_Pdf_FileParserDataSource_String */
require_once 'Zend/Pdf/FileParserDataSource/String.php';

/** Zend_Pdf_FileParser_Font_OpenType_TrueType */
require_once 'Zend/Pdf/FileParser/Font/OpenType/TrueType.php';

/** Zend_Pdf_Resource_Font_Simple_Parsed_TrueType */
require_once 'Zend/Pdf/Resource/Font/Simple/Parsed/TrueType.php';

/** Zend_Pdf_Resource_Font_Type0 */
require_once 'Zend/Pdf/Resource/Font/Type0.php';

/** Zend_Pdf_Resource_Font_CidFont_TrueType */
require_once 'Zend/Pdf/Resource/Font/CidFont/TrueType.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_Courier */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/Courier.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_CourierBold */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/CourierBold.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_CourierBoldOblique */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/CourierBoldOblique.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_CourierOblique */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/CourierOblique.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_Helvetica */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/Helvetica.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_HelveticaBold */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBold.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_HelveticaBoldOblique */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/HelveticaBoldOblique.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_HelveticaOblique */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/HelveticaOblique.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_Symbol */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/Symbol.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_TimesBold */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/TimesBold.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_TimesBoldItalic */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/TimesBoldItalic.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_TimesItalic */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/TimesItalic.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_TimesRoman */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/TimesRoman.php';

/** Zend_Pdf_Resource_Font_Simple_Standard_ZapfDingbats */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard/ZapfDingbats.php';

/** Zend_Pdf_Resource_Font_Extracted */
require_once 'Zend/Pdf/Resource/Font/Extracted.php';


/**
 * Abstract factory class which vends {@link Zend_Pdf_Resource_Font} objects.
 *
 * Font objects themselves are normally instantiated through the factory methods
 * {@link fontWithName()} or {@link fontWithPath()}.
 *
 * This class is also the home for font-related constants because the name of
 * the true base class ({@link Zend_Pdf_Resource_Font}) is not intuitive for the
 * end user.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Pdf_Font
{
  /**** Class Constants ****/


  /* Font Types */

    /**
     * Unknown font type.
     */
    const TYPE_UNKNOWN = 0;

    /**
     * One of the standard 14 PDF fonts.
     */
    const TYPE_STANDARD = 1;

    /**
     * A PostScript Type 1 font.
     */
    const TYPE_TYPE_1 = 2;

    /**
     * A TrueType font or an OpenType font containing TrueType outlines.
     */
    const TYPE_TRUETYPE = 3;

    /**
     * Type 0 composite font.
     */
    const TYPE_TYPE_0 = 4;
    
    /**
     * CID font containing a PostScript Type 1 font.
     * These fonts are used only to construct Type 0 composite fonts and can't be used directly
     */
    const TYPE_CIDFONT_TYPE_0 = 5;

    /**
     * CID font containing a TrueType font or an OpenType font containing TrueType outlines.
     * These fonts are used only to construct Type 0 composite fonts and can't be used directly
     */
    const TYPE_CIDFONT_TYPE_2 = 6;
    

  /* Names of the Standard 14 PDF Fonts */

    /**
     * Name of the standard PDF font Courier.
     */
    const FONT_COURIER = 'Courier';

    /**
     * Name of the bold style of the standard PDF font Courier.
     */
    const FONT_COURIER_BOLD = 'Courier-Bold';

    /**
     * Name of the italic style of the standard PDF font Courier.
     */
    const FONT_COURIER_OBLIQUE = 'Courier-Oblique';

    /**
     * Convenience constant for a common misspelling of
     * {@link FONT_COURIER_OBLIQUE}.
     */
    const FONT_COURIER_ITALIC = 'Courier-Oblique';

    /**
     * Name of the bold and italic style of the standard PDF font Courier.
     */
    const FONT_COURIER_BOLD_OBLIQUE = 'Courier-BoldOblique';

    /**
     * Convenience constant for a common misspelling of
     * {@link FONT_COURIER_BOLD_OBLIQUE}.
     */
    const FONT_COURIER_BOLD_ITALIC = 'Courier-BoldOblique';

    /**
     * Name of the standard PDF font Helvetica.
     */
    const FONT_HELVETICA = 'Helvetica';

    /**
     * Name of the bold style of the standard PDF font Helvetica.
     */
    const FONT_HELVETICA_BOLD = 'Helvetica-Bold';

    /**
     * Name of the italic style of the standard PDF font Helvetica.
     */
    const FONT_HELVETICA_OBLIQUE = 'Helvetica-Oblique';

    /**
     * Convenience constant for a common misspelling of
     * {@link FONT_HELVETICA_OBLIQUE}.
     */
    const FONT_HELVETICA_ITALIC = 'Helvetica-Oblique';

    /**
     * Name of the bold and italic style of the standard PDF font Helvetica.
     */
    const FONT_HELVETICA_BOLD_OBLIQUE = 'Helvetica-BoldOblique';

    /**
     * Convenience constant for a common misspelling of
     * {@link FONT_HELVETICA_BOLD_OBLIQUE}.
     */
    const FONT_HELVETICA_BOLD_ITALIC = 'Helvetica-BoldOblique';

    /**
     * Name of the standard PDF font Symbol.
     */
    const FONT_SYMBOL = 'Symbol';

    /**
     * Name of the standard PDF font Times.
     */
    const FONT_TIMES_ROMAN = 'Times-Roman';

    /**
     * Convenience constant for a common misspelling of
     * {@link FONT_TIMES_ROMAN}.
     */
    const FONT_TIMES = 'Times-Roman';

    /**
     * Name of the bold style of the standard PDF font Times.
     */
    const FONT_TIMES_BOLD = 'Times-Bold';

    /**
     * Name of the italic style of the standard PDF font Times.
     */
    const FONT_TIMES_ITALIC = 'Times-Italic';

    /**
     * Name of the bold and italic style of the standard PDF font Times.
     */
    const FONT_TIMES_BOLD_ITALIC = 'Times-BoldItalic';

    /**
     * Name of the standard PDF font Zapf Dingbats.
     */
    const FONT_ZAPFDINGBATS = 'ZapfDingbats';


  /* Font Name String Types */

    /**
     * Full copyright notice for the font.
     */
    const NAME_COPYRIGHT =  0;

    /**
     * Font family name. Used to group similar styles of fonts together.
     */
    const NAME_FAMILY =  1;

    /**
     * Font style within the font family. Examples: Regular, Italic, Bold, etc.
     */
    const NAME_STYLE =  2;

    /**
     * Unique font identifier.
     */
    const NAME_ID =  3;

    /**
     * Full font name. Usually a combination of the {@link NAME_FAMILY} and
     * {@link NAME_STYLE} strings.
     */
    const NAME_FULL =  4;

    /**
     * Version number of the font.
     */
    const NAME_VERSION =  5;

    /**
     * PostScript name for the font. This is the name used to identify fonts
     * internally and within the PDF file.
     */
    const NAME_POSTSCRIPT =  6;

    /**
     * Font trademark notice. This is distinct from the {@link NAME_COPYRIGHT}.
     */
    const NAME_TRADEMARK =  7;

    /**
     * Name of the font manufacturer.
     */
    const NAME_MANUFACTURER =  8;

    /**
     * Name of the designer of the font.
     */
    const NAME_DESIGNER =  9;

    /**
     * Description of the font. May contain revision information, usage
     * recommendations, features, etc.
     */
    const NAME_DESCRIPTION = 10;

    /**
     * URL of the font vendor. Some fonts may contain a unique serial number
     * embedded in this URL, which is used for licensing.
     */
    const NAME_VENDOR_URL = 11;

    /**
     * URL of the font designer ({@link NAME_DESIGNER}).
     */
    const NAME_DESIGNER_URL = 12;

    /**
     * Plain language licensing terms for the font.
     */
    const NAME_LICENSE = 13;

    /**
     * URL of more detailed licensing information for the font.
     */
    const NAME_LICENSE_URL = 14;

    /**
     * Preferred font family. Used by some fonts to work around a Microsoft
     * Windows limitation where only four fonts styles can share the same
     * {@link NAME_FAMILY} value.
     */
    const NAME_PREFERRED_FAMILY = 16;

    /**
     * Preferred font style. A more descriptive string than {@link NAME_STYLE}.
     */
    const NAME_PREFERRED_STYLE = 17;

    /**
     * Suggested text to use as a representative sample of the font.
     */
    const NAME_SAMPLE_TEXT = 19;

    /**
     * PostScript CID findfont name.
     */
    const NAME_CID_NAME = 20;


  /* Font Weights */

    /**
     * Thin font weight.
     */
    const WEIGHT_THIN = 100;

    /**
     * Extra-light (Ultra-light) font weight.
     */
    const WEIGHT_EXTRA_LIGHT = 200;

    /**
     * Light font weight.
     */
    const WEIGHT_LIGHT = 300;

    /**
     * Normal (Regular) font weight.
     */
    const WEIGHT_NORMAL = 400;

    /**
     * Medium font weight.
     */
    const WEIGHT_MEDIUM = 500;

    /**
     * Semi-bold (Demi-bold) font weight.
     */
    const WEIGHT_SEMI_BOLD = 600;

    /**
     * Bold font weight.
     */
    const WEIGHT_BOLD = 700;

    /**
     * Extra-bold (Ultra-bold) font weight.
     */
    const WEIGHT_EXTRA_BOLD = 800;

    /**
     * Black (Heavy) font weight.
     */
    const WEIGHT_BLACK = 900;


  /* Font Widths */

    /**
     * Ultra-condensed font width. Typically 50% of normal.
     */
    const WIDTH_ULTRA_CONDENSED = 1;

    /**
     * Extra-condensed font width. Typically 62.5% of normal.
     */
    const WIDTH_EXTRA_CONDENSED = 2;

    /**
     * Condensed font width. Typically 75% of normal.
     */
    const WIDTH_CONDENSED = 3;

    /**
     * Semi-condensed font width. Typically 87.5% of normal.
     */
    const WIDTH_SEMI_CONDENSED = 4;

    /**
     * Normal (Medium) font width.
     */
    const WIDTH_NORMAL = 5;

    /**
     * Semi-expanded font width. Typically 112.5% of normal.
     */
    const WIDTH_SEMI_EXPANDED = 6;

    /**
     * Expanded font width. Typically 125% of normal.
     */
    const WIDTH_EXPANDED = 7;

    /**
     * Extra-expanded font width. Typically 150% of normal.
     */
    const WIDTH_EXTRA_EXPANDED = 8;

    /**
     * Ultra-expanded font width. Typically 200% of normal.
     */
    const WIDTH_ULTRA_EXPANDED = 9;


  /* Font Embedding Options */

    /**
     * Do not embed the font in the PDF document.
     */
    const EMBED_DONT_EMBED = 0x01;

    /**
     * Embed, but do not subset the font in the PDF document.
     */
    const EMBED_DONT_SUBSET = 0x02;

    /**
     * Embed, but do not compress the font in the PDF document.
     */
    const EMBED_DONT_COMPRESS = 0x04;

    /**
     * Suppress the exception normally thrown if the font cannot be embedded
     * due to its copyright bits being set.
     */
    const EMBED_SUPPRESS_EMBED_EXCEPTION = 0x08;



  /**** Class Variables ****/


    /**
     * Array whose keys are the unique PostScript names of instantiated fonts.
     * The values are the font objects themselves.
     * @var array
     */
    private static $_fontNames = array();

    /**
     * Array whose keys are the md5 hash of the full paths on disk for parsed
     * fonts. The values are the font objects themselves.
     * @var array
     */
    private static $_fontFilePaths = array();



  /**** Public Interface ****/


  /* Factory Methods */

    /**
     * Returns a {@link Zend_Pdf_Resource_Font} object by full name.
     *
     * This is the preferred method to obtain one of the standard 14 PDF fonts.
     *
     * The result of this method is cached, preventing unnecessary duplication
     * of font objects. Repetitive calls for a font with the same name will
     * return the same object.
     *
     * The $embeddingOptions parameter allows you to set certain flags related
     * to font embedding. You may combine options by OR-ing them together. See
     * the EMBED_ constants defined in {@link Zend_Pdf_Font} for the list of
     * available options and their descriptions. Note that this value is only
     * used when creating a font for the first time. If a font with the same
     * name already exists, you will get that object and the options you specify
     * here will be ignored. This is because fonts are only embedded within the
     * PDF file once.
     *
     * If the font name supplied does not match the name of a previously
     * instantiated object and it is not one of the 14 standard PDF fonts, an
     * exception will be thrown.
     *
     * @param string $name Full PostScript name of font.
     * @param integer $embeddingOptions (optional) Options for font embedding.
     * @return Zend_Pdf_Resource_Font
     * @throws Zend_Pdf_Exception
     */
    public static function fontWithName($name, $embeddingOptions = 0)
        {
        /* First check the cache. Don't duplicate font objects.
         */
        if (isset(Zend_Pdf_Font::$_fontNames[$name])) {
            return Zend_Pdf_Font::$_fontNames[$name];
        }

        /**
         * @todo It would be cool to be able to have a mapping of font names to
         *   file paths in a configuration file for frequently used custom
         *   fonts. This would allow a user to use custom fonts without having
         *   to hard-code file paths all over the place. Table this idea until
         *   {@link Zend_Config} is ready.
         */

        /* Not an existing font and no mapping in the config file. Check to see
         * if this is one of the standard 14 PDF fonts.
         */
        switch ($name) {
            case Zend_Pdf_Font::FONT_COURIER:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_Courier();
                break;

            case Zend_Pdf_Font::FONT_COURIER_BOLD:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_CourierBold();
                break;

            case Zend_Pdf_Font::FONT_COURIER_OBLIQUE:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_CourierOblique();
                break;

            case Zend_Pdf_Font::FONT_COURIER_BOLD_OBLIQUE:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_CourierBoldOblique();
                break;

            case Zend_Pdf_Font::FONT_HELVETICA:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_Helvetica();
                break;

            case Zend_Pdf_Font::FONT_HELVETICA_BOLD:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_HelveticaBold();
                break;

            case Zend_Pdf_Font::FONT_HELVETICA_OBLIQUE:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_HelveticaOblique();
                break;

            case Zend_Pdf_Font::FONT_HELVETICA_BOLD_OBLIQUE:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_HelveticaBoldOblique();
                break;

            case Zend_Pdf_Font::FONT_SYMBOL:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_Symbol();
                break;

            case Zend_Pdf_Font::FONT_TIMES_ROMAN:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_TimesRoman();
                break;

            case Zend_Pdf_Font::FONT_TIMES_BOLD:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_TimesBold();
                break;

            case Zend_Pdf_Font::FONT_TIMES_ITALIC:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_TimesItalic();
                break;

            case Zend_Pdf_Font::FONT_TIMES_BOLD_ITALIC:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_TimesBoldItalic();
                break;

            case Zend_Pdf_Font::FONT_ZAPFDINGBATS:
                $font = new Zend_Pdf_Resource_Font_Simple_Standard_ZapfDingbats();
                break;

            default:
                throw new Zend_Pdf_Exception("Unknown font name: $name",
                                             Zend_Pdf_Exception::BAD_FONT_NAME);
        }

        /* Add this new font to the cache array and return it for use.
         */
        Zend_Pdf_Font::$_fontNames[$name] = $font;
        return $font;
    }

    /**
     * Returns a {@link Zend_Pdf_Resource_Font} object by file path.
     *
     * The result of this method is cached, preventing unnecessary duplication
     * of font objects. Repetitive calls for the font with the same path will
     * return the same object.
     *
     * The $embeddingOptions parameter allows you to set certain flags related
     * to font embedding. You may combine options by OR-ing them together. See
     * the EMBED_ constants defined in {@link Zend_Pdf_Font} for the list of
     * available options and their descriptions. Note that this value is only
     * used when creating a font for the first time. If a font with the same
     * name already exists, you will get that object and the options you specify
     * here will be ignored. This is because fonts are only embedded within the
     * PDF file once.
     *
     * If the file path supplied does not match the path of a previously
     * instantiated object or the font type cannot be determined, an exception
     * will be thrown.
     *
     * @param string $filePath Full path to the font file.
     * @param integer $embeddingOptions (optional) Options for font embedding.
     * @return Zend_Pdf_Resource_Font
     * @throws Zend_Pdf_Exception
     */
    public static function fontWithPath($filePath, $embeddingOptions = 0)
    {
        /* First check the cache. Don't duplicate font objects.
         */
        $filePathKey = md5($filePath);
        if (isset(Zend_Pdf_Font::$_fontFilePaths[$filePathKey])) {
            return Zend_Pdf_Font::$_fontFilePaths[$filePathKey];
        }

        /* Create a file parser data source object for this file. File path and
         * access permission checks are handled here.
         */
        $dataSource = new Zend_Pdf_FileParserDataSource_File($filePath);

        /* Attempt to determine the type of font. We can't always trust file
         * extensions, but try that first since it's fastest.
         */
        $fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

        /* If it turns out that the file is named improperly and we guess the
         * wrong type, we'll get null instead of a font object.
         */
        switch ($fileExtension) {
            case 'ttf':
                $font = Zend_Pdf_Font::_extractTrueTypeFont($dataSource, $embeddingOptions);
                break;

            default:
                /* Unrecognized extension. Try to determine the type by actually
                 * parsing it below.
                 */
                $font = null;
                break;
        }


        if (is_null($font)) {
            /* There was no match for the file extension or the extension was
             * wrong. Attempt to detect the type of font by actually parsing it.
             * We'll do the checks in order of most likely format to try to
             * reduce the detection time.
             */

            // OpenType

            // TrueType
            if ((is_null($font)) && ($fileExtension != 'ttf')) {
                $font = Zend_Pdf_Font::_extractTrueTypeFont($dataSource, $embeddingOptions);
            }

            // Type 1 PostScript

            // Mac OS X dfont

            // others?
        }


        /* Done with the data source object.
         */
        $dataSource = null;

        if (! is_null($font)) {
            /* Parsing was successful. Add this font instance to the cache arrays
             * and return it for use.
             */
            $fontName = $font->getFontName(Zend_Pdf_Font::NAME_POSTSCRIPT, '', '');
            Zend_Pdf_Font::$_fontNames[$fontName] = $font;
            $filePathKey = md5($filePath);
            Zend_Pdf_Font::$_fontFilePaths[$filePathKey] = $font;
            return $font;

        } else {
            /* The type of font could not be determined. Give up.
             */
            throw new Zend_Pdf_Exception("Cannot determine font type: $filePath",
                                         Zend_Pdf_Exception::CANT_DETERMINE_FONT_TYPE);
         }

    }



  /**** Internal Methods ****/


  /* Font Extraction Methods */

    /**
     * Attempts to extract a TrueType font from the data source.
     *
     * If the font parser throws an exception that suggests the data source
     * simply doesn't contain a TrueType font, catches it and returns null. If
     * an exception is thrown that suggests the TrueType font is corrupt or
     * otherwise unusable, throws that exception. If successful, returns the
     * font object.
     *
     * @param Zend_Pdf_FileParserDataSource $dataSource
     * @param integer $embeddingOptions Options for font embedding.
     * @return Zend_Pdf_Resource_Font_OpenType_TrueType May also return null if
     *   the data source does not appear to contain a TrueType font.
     * @throws Zend_Pdf_Exception
     */
    protected static function _extractTrueTypeFont($dataSource, $embeddingOptions)
    {
        try {
            $fontParser = new Zend_Pdf_FileParser_Font_OpenType_TrueType($dataSource);
            
            $fontParser->parse();
            if ($fontParser->isAdobeLatinSubset) {
                $font = new Zend_Pdf_Resource_Font_Simple_Parsed_TrueType($fontParser, $embeddingOptions);
            } else {
                /* Use Composite Type 0 font which supports Unicode character mapping */
                $cidFont = new Zend_Pdf_Resource_Font_CidFont_TrueType($fontParser, $embeddingOptions);
                $font    = new Zend_Pdf_Resource_Font_Type0($cidFont);
            }
        } catch (Zend_Pdf_Exception $exception) {
            /* The following exception codes suggest that this isn't really a
             * TrueType font. If we caught such an exception, simply return
             * null. For all other cases, it probably is a TrueType font but has
             * a problem; throw the exception again.
             */
            $fontParser = null;
            switch ($exception->getCode()) {
                case Zend_Pdf_Exception::WRONG_FONT_TYPE:    // break intentionally omitted
                case Zend_Pdf_Exception::BAD_TABLE_COUNT:    // break intentionally omitted
                case Zend_Pdf_Exception::BAD_MAGIC_NUMBER:
                    return null;

                default:
                    throw $exception;
            }
        }
        return $font;
    }

}
Pdf/Resource/Font.php000066600000036750151256604610010510 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource */
require_once 'Zend/Pdf/Resource.php';

/** Zend_Pdf_Exception */
require_once 'Zend/Pdf/Exception.php';


/**
 * Abstract class which manages PDF fonts.
 *
 * Defines the public interface and creates shared storage for concrete
 * subclasses which are responsible for generating the font's information
 * dictionaries, mapping characters to glyphs, and providing both overall font
 * and glyph-specific metric data.
 *
 * Font objects should be normally be obtained from the factory methods
 * {@link Zend_Pdf_Font::fontWithName} and {@link Zend_Pdf_Font::fontWithPath}.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Pdf_Resource_Font extends Zend_Pdf_Resource
{
  /**** Instance Variables ****/


    /**
     * The type of font. Use TYPE_ constants defined in {@link Zend_Pdf_Font}.
     * @var integer
     */
    protected $_fontType = Zend_Pdf_Font::TYPE_UNKNOWN;

    /**
     * Array containing descriptive names for the font. See {@link fontName()}.
     * @var array
     */
    protected $_fontNames = array();

    /**
     * Flag indicating whether or not this font is bold.
     * @var boolean
     */
    protected $_isBold = false;

    /**
     * Flag indicating whether or not this font is italic.
     * @var boolean
     */
    protected $_isItalic = false;

    /**
     * Flag indicating whether or not this font is monospaced.
     * @var boolean
     */
    protected $_isMonospace = false;

    /**
     * The position below the text baseline of the underline (in glyph units).
     * @var integer
     */
    protected $_underlinePosition = 0;

    /**
     * The thickness of the underline (in glyph units).
     * @var integer
     */
    protected $_underlineThickness = 0;

    /**
     * The position above the text baseline of the strikethrough (in glyph units).
     * @var integer
     */
    protected $_strikePosition = 0;

    /**
     * The thickness of the strikethrough (in glyph units).
     * @var integer
     */
    protected $_strikeThickness = 0;

    /**
     * Number of glyph units per em. See {@link getUnitsPerEm()}.
     * @var integer
     */
    protected $_unitsPerEm = 0;

    /**
     * Typographical ascent. See {@link getAscent()}.
     * @var integer
     */
    protected $_ascent = 0;

    /**
     * Typographical descent. See {@link getDescent()}.
     * @var integer
     */
    protected $_descent = 0;

    /**
     * Typographical line gap. See {@link getLineGap()}.
     * @var integer
     */
    protected $_lineGap = 0;



  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor.
     *
     */
    public function __construct()
    {
        parent::__construct(new Zend_Pdf_Element_Dictionary());
        $this->_resource->Type = new Zend_Pdf_Element_Name('Font');
    }


  /* Object Magic Methods */

    /**
     * Returns the full name of the font in the encoding method of the current
     * locale. Transliterates any characters that cannot be naturally
     * represented in that character set.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getFontName(Zend_Pdf_Font::NAME_FULL, '', '//TRANSLIT');
    }


  /* Accessors */

    /**
     * Returns the type of font.
     *
     * @return integer One of the TYPE_ constants defined in
     *   {@link Zend_Pdf_Font}.
     */
    public function getFontType()
    {
        return $this->_fontType;
    }

    /**
     * Returns the specified descriptive name for the font.
     *
     * The font name type is usually one of the following:
     * <ul>
     *  <li>{@link Zend_Pdf_Font::NAME_FULL}
     *  <li>{@link Zend_Pdf_Font::NAME_FAMILY}
     *  <li>{@link Zend_Pdf_Font::NAME_PREFERRED_FAMILY}
     *  <li>{@link Zend_Pdf_Font::NAME_STYLE}
     *  <li>{@link Zend_Pdf_Font::NAME_PREFERRED_STYLE}
     *  <li>{@link Zend_Pdf_Font::NAME_DESCRIPTION}
     *  <li>{@link Zend_Pdf_Font::NAME_SAMPLE_TEXT}
     *  <li>{@link Zend_Pdf_Font::NAME_ID}
     *  <li>{@link Zend_Pdf_Font::NAME_VERSION}
     *  <li>{@link Zend_Pdf_Font::NAME_POSTSCRIPT}
     *  <li>{@link Zend_Pdf_Font::NAME_CID_NAME}
     *  <li>{@link Zend_Pdf_Font::NAME_DESIGNER}
     *  <li>{@link Zend_Pdf_Font::NAME_DESIGNER_URL}
     *  <li>{@link Zend_Pdf_Font::NAME_MANUFACTURER}
     *  <li>{@link Zend_Pdf_Font::NAME_VENDOR_URL}
     *  <li>{@link Zend_Pdf_Font::NAME_COPYRIGHT}
     *  <li>{@link Zend_Pdf_Font::NAME_TRADEMARK}
     *  <li>{@link Zend_Pdf_Font::NAME_LICENSE}
     *  <li>{@link Zend_Pdf_Font::NAME_LICENSE_URL}
     * </ul>
     *
     * Note that not all names are available for all fonts. In addition, some
     * fonts may contain additional names, whose indicies are in the range
     * 256 to 32767 inclusive, which are used for certain font layout features.
     *
     * If the preferred language translation is not available, uses the first
     * available translation for the name, which is usually English.
     *
     * If the requested name does not exist, returns null.
     *
     * All names are stored internally as Unicode strings, using UTF-16BE
     * encoding. You may optionally supply a different resulting character set.
     *
     * @param integer $nameType Type of name requested.
     * @param mixed $language Preferred language (string) or array of languages
     *   in preferred order. Use the ISO 639 standard 2-letter language codes.
     * @param string $characterSet (optional) Desired resulting character set.
     *   You may use any character set supported by {@link iconv()};
     * @return string
     */
    public function getFontName($nameType, $language, $characterSet = null)
    {
        if (! isset($this->_fontNames[$nameType])) {
            return null;
        }
        $name = null;
        if (is_array($language)) {
            foreach ($language as $code) {
                if (isset($this->_fontNames[$nameType][$code])) {
                    $name = $this->_fontNames[$nameType][$code];
                    break;
                }
            }
        } else {
            if (isset($this->_fontNames[$nameType][$language])) {
                $name = $this->_fontNames[$nameType][$language];
            }
        }
        /* If the preferred language could not be found, use whatever is first.
         */
        if (is_null($name)) {
            $names = $this->_fontNames[$nameType];
            $name  = reset($names);
        }
        /* Convert the character set if requested.
         */
        if ((! is_null($characterSet)) && ($characterSet != 'UTF-16BE') && PHP_OS != 'AIX') { // AIX knows not this charset
            $name = iconv('UTF-16BE', $characterSet, $name);
        }
        return $name;
    }

    /**
     * Returns whole set of font names.
     * 
     * @return array
     */
    public function getFontNames()
    {
        return $this->_fontNames;
    }
    
    /**
     * Returns true if font is bold.
     *
     * @return boolean
     */
    public function isBold()
    {
        return $this->_isBold;
    }

    /**
     * Returns true if font is italic.
     *
     * @return boolean
     */
    public function isItalic()
    {
        return $this->_isItalic;
    }
    
    /**
     * Returns true if font is monospace.
     *
     * @return boolean
     */
    public function isMonospace()
    {
        return $this->_isMonospace;
    }

    /**
     * Returns the suggested position below the text baseline of the underline
     * in glyph units.
     *
     * This value is usually negative.
     *
     * @return integer
     */
    public function getUnderlinePosition()
    {
        return $this->_underlinePosition;
    }

    /**
     * Returns the suggested line thickness of the underline in glyph units.
     *
     * @return integer
     */
    public function getUnderlineThickness()
    {
        return $this->_underlineThickness;
    }

    /**
     * Returns the suggested position above the text baseline of the
     * strikethrough in glyph units.
     *
     * @return integer
     */
    public function getStrikePosition()
    {
        return $this->_strikePosition;
    }

    /**
     * Returns the suggested line thickness of the strikethrough in glyph units.
     *
     * @return integer
     */
    public function getStrikeThickness()
    {
        return $this->_strikeThickness;
    }

    /**
     * Returns the number of glyph units per em.
     *
     * Used to convert glyph space to user space. Frequently used in conjunction
     * with {@link widthsForGlyphs()} to calculate the with of a run of text.
     *
     * @return integer
     */
    public function getUnitsPerEm()
    {
        return $this->_unitsPerEm;
    }

    /**
     * Returns the typographic ascent in font glyph units.
     *
     * The typographic ascent is the distance from the font's baseline to the
     * top of the text frame. It is frequently used to locate the initial
     * baseline for a paragraph of text inside a given rectangle.
     *
     * @return integer
     */
    public function getAscent()
    {
        return $this->_ascent;
    }

    /**
     * Returns the typographic descent in font glyph units.
     *
     * The typographic descent is the distance below the font's baseline to the
     * bottom of the text frame. It is always negative.
     *
     * @return integer
     */
    public function getDescent()
    {
        return $this->_descent;
    }

    /**
     * Returns the typographic line gap in font glyph units.
     *
     * The typographic line gap is the distance between the bottom of the text
     * frame of one line to the top of the text frame of the next. It is
     * typically combined with the typographical ascent and descent to determine
     * the font's total line height (or leading).
     *
     * @return integer
     */
    public function getLineGap()
    {
        return $this->_lineGap;
    }

    /**
     * Returns the suggested line height (or leading) in font glyph units.
     *
     * This value is determined by adding together the values of the typographic
     * ascent, descent, and line gap. This value yields the suggested line
     * spacing as determined by the font developer.
     *
     * It should be noted that this is only a guideline; layout engines will
     * frequently modify this value to achieve special effects such as double-
     * spacing.
     *
     * @return integer
     */
    public function getLineHeight()
    {
        return $this->_ascent - $this->_descent + $this->_lineGap;
    }


  /* Information and Conversion Methods */

    /**
     * Returns an array of glyph numbers corresponding to the Unicode characters.
     *
     * If a particular character doesn't exist in this font, the special 'missing
     * character glyph' will be substituted.
     *
     * See also {@link glyphNumberForCharacter()}.
     *
     * @param array $characterCodes Array of Unicode character codes (code points).
     * @return array Array of glyph numbers.
     */
    abstract public function glyphNumbersForCharacters($characterCodes);

    /**
     * Returns the glyph number corresponding to the Unicode character.
     *
     * If a particular character doesn't exist in this font, the special 'missing
     * character glyph' will be substituted.
     *
     * See also {@link glyphNumbersForCharacters()} which is optimized for bulk
     * operations.
     *
     * @param integer $characterCode Unicode character code (code point).
     * @return integer Glyph number.
     */
    abstract public function glyphNumberForCharacter($characterCode);

    /**
     * Returns a number between 0 and 1 inclusive that indicates the percentage
     * of characters in the string which are covered by glyphs in this font.
     *
     * Since no one font will contain glyphs for the entire Unicode character
     * range, this method can be used to help locate a suitable font when the
     * actual contents of the string are not known.
     *
     * Note that some fonts lie about the characters they support. Additionally,
     * fonts don't usually contain glyphs for control characters such as tabs
     * and line breaks, so it is rare that you will get back a full 1.0 score.
     * The resulting value should be considered informational only.
     *
     * @param string $string
     * @param string $charEncoding (optional) Character encoding of source text.
     *   If omitted, uses 'current locale'.
     * @return float
     */
    abstract public function getCoveredPercentage($string, $charEncoding = '');

    /**
     * Returns the widths of the glyphs.
     *
     * The widths are expressed in the font's glyph space. You are responsible
     * for converting to user space as necessary. See {@link unitsPerEm()}.
     *
     * See also {@link widthForGlyph()}.
     *
     * @param array $glyphNumbers Array of glyph numbers.
     * @return array Array of glyph widths (integers).
     * @throws Zend_Pdf_Exception
     */
    abstract public function widthsForGlyphs($glyphNumbers);

    /**
     * Returns the width of the glyph.
     *
     * Like {@link widthsForGlyphs()} but used for one glyph at a time.
     *
     * @param integer $glyphNumber
     * @return integer
     * @throws Zend_Pdf_Exception
     */
    abstract public function widthForGlyph($glyphNumber);

    /**
     * Convert string to the font encoding.
     * 
     * The method is used to prepare string for text drawing operators 
     *
     * @param string $string
     * @param string $charEncoding Character encoding of source text.
     * @return string
     */
    abstract public function encodeString($string, $charEncoding);

    /**
     * Convert string from the font encoding.
     *
     * The method is used to convert strings retrieved from existing content streams
     *
     * @param string $string
     * @param string $charEncoding Character encoding of resulting text.
     * @return string
     */
    abstract public function decodeString($string, $charEncoding);



  /**** Internal Methods ****/


    /**
     * If the font's glyph space is not 1000 units per em, converts the value.
     *
     * @internal
     * @param integer $value
     * @return integer
     */
    public function toEmSpace($value)
    {
        if ($this->_unitsPerEm == 1000) {
            return $value;
        }
        return ceil(($value / $this->_unitsPerEm) * 1000);    // always round up
    }
}

Pdf/Resource/Font/CidFont/TrueType.php000066600000006632151256604610013613 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_CidFont */
require_once 'Zend/Pdf/Resource/Font/CidFont.php';

/** Zend_Pdf_Resource_Font_FontDescriptor */
require_once 'Zend/Pdf/Resource/Font/FontDescriptor.php';


/**
 * Type 2 CIDFonts implementation
 *
 * For Type 2, the CIDFont program is actually a TrueType font program, which has
 * no native notion of CIDs. In a TrueType font program, glyph descriptions are
 * identified by glyph index values. Glyph indices are internal to the font and are not
 * defined consistently from one font to another. Instead, a TrueType font program
 * contains a 'cmap' table that provides mappings directly from character codes to
 * glyph indices for one or more predefined encodings.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_CidFont_TrueType extends Zend_Pdf_Resource_Font_CidFont
{
    /**
     * Object constructor
     * 
     * @todo Joing this class with Zend_Pdf_Resource_Font_Simple_Parsed_TrueType 
     *
     * @param Zend_Pdf_FileParser_Font_OpenType_TrueType $fontParser Font parser
     *   object containing parsed TrueType file.
     * @param integer $embeddingOptions Options for font embedding.
     * @throws Zend_Pdf_Exception
     */
    public function __construct(Zend_Pdf_FileParser_Font_OpenType_TrueType $fontParser, $embeddingOptions)
    {
        parent::__construct($fontParser, $embeddingOptions);

        $this->_fontType = Zend_Pdf_Font::TYPE_CIDFONT_TYPE_2;

        $this->_resource->Subtype  = new Zend_Pdf_Element_Name('CIDFontType2');
        
        $fontDescriptor = Zend_Pdf_Resource_Font_FontDescriptor::factory($this, $fontParser, $embeddingOptions);
        $this->_resource->FontDescriptor = $this->_objectFactory->newObject($fontDescriptor);

        /* Prepare CIDToGIDMap */
        // Initialize 128K string of null characters (65536 2 byte integers)
        $cidToGidMapData = str_repeat("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 8192);
        // Fill the index
        $charGlyphs = $this->_cmap->getCoveredCharactersGlyphs();
        foreach ($charGlyphs as $charCode => $glyph) {
            $cidToGidMapData[$charCode*2    ] = chr($glyph >> 8);
            $cidToGidMapData[$charCode*2 + 1] = chr($glyph & 0xFF);
        }
        // Store CIDToGIDMap within compressed stream object
        $cidToGidMap = $this->_objectFactory->newStreamObject($cidToGidMapData);
        $cidToGidMap->dictionary->Filter = new Zend_Pdf_Element_Name('FlateDecode');
        $this->_resource->CIDToGIDMap = $cidToGidMap;
    }

}
Pdf/Resource/Font/Simple/Parsed.php000066600000007070151256604610013150 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple */
require_once 'Zend/Pdf/Resource/Font/Simple.php';

/** Zend_Pdf_FileParser_Font_OpenType */
require_once 'Zend/Pdf/FileParser/Font/OpenType.php';


/**
 * Parsed and (optionaly) embedded fonts implementation
 *
 * OpenType fonts can contain either TrueType or PostScript Type 1 outlines.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Pdf_Resource_Font_Simple_Parsed extends Zend_Pdf_Resource_Font_Simple
{
    /**
     * Object constructor
     *
     * @param Zend_Pdf_FileParser_Font_OpenType $fontParser Font parser object containing OpenType file.
     * @throws Zend_Pdf_Exception
     */
    public function __construct(Zend_Pdf_FileParser_Font_OpenType $fontParser)
    {
        parent::__construct();
        
        
        $fontParser->parse();

        /* Object properties */

        $this->_fontNames = $fontParser->names;

        $this->_isBold       = $fontParser->isBold;
        $this->_isItalic     = $fontParser->isItalic;
        $this->_isMonospaced = $fontParser->isMonospaced;

        $this->_underlinePosition  = $fontParser->underlinePosition;
        $this->_underlineThickness = $fontParser->underlineThickness;
        $this->_strikePosition     = $fontParser->strikePosition;
        $this->_strikeThickness    = $fontParser->strikeThickness;

        $this->_unitsPerEm = $fontParser->unitsPerEm;

        $this->_ascent  = $fontParser->ascent;
        $this->_descent = $fontParser->descent;
        $this->_lineGap = $fontParser->lineGap;

        $this->_glyphWidths       = $fontParser->glyphWidths;
        $this->_missingGlyphWidth = $this->_glyphWidths[0];


        $this->_cmap = $fontParser->cmap;


        /* Resource dictionary */

        $baseFont = $this->getFontName(Zend_Pdf_Font::NAME_POSTSCRIPT, 'en', 'UTF-8');
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name($baseFont);

        $this->_resource->FirstChar = new Zend_Pdf_Element_Numeric(0);
        $this->_resource->LastChar  = new Zend_Pdf_Element_Numeric(count($this->_glyphWidths) - 1);

        /* Now convert the scalar glyph widths to Zend_Pdf_Element_Numeric objects.
         */
        $pdfWidths = array();
        foreach ($this->_glyphWidths as $width) {
            $pdfWidths[] = new Zend_Pdf_Element_Numeric($this->toEmSpace($width));
        }
        /* Create the Zend_Pdf_Element_Array object and add it to the font's
         * object factory and resource dictionary.
         */
        $widthsArrayElement = new Zend_Pdf_Element_Array($pdfWidths);
        $widthsObject = $this->_objectFactory->newObject($widthsArrayElement);
        $this->_resource->Widths = $widthsObject;
    }

}
Pdf/Resource/Font/Simple/Standard.php000066600000006230151256604610013467 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple */
require_once 'Zend/Pdf/Resource/Font/Simple.php';


/**
 * Abstract class definition for the standard 14 Type 1 PDF fonts.
 *
 * The standard 14 PDF fonts are guaranteed to be availble in any PDF viewer
 * implementation. As such, they do not require much data for the font's
 * resource dictionary. The majority of the data provided by subclasses is for
 * the benefit of our own layout code.
 *
 * The standard fonts and the corresponding subclasses that manage them:
 * <ul>
 *  <li>Courier - {@link Zend_Pdf_Resource_Font_Simple_Standard_Courier}
 *  <li>Courier-Bold - {@link Zend_Pdf_Resource_Font_Simple_Standard_CourierBold}
 *  <li>Courier-Oblique - {@link Zend_Pdf_Resource_Font_Simple_Standard_CourierOblique}
 *  <li>Courier-BoldOblique - {@link Zend_Pdf_Resource_Font_Simple_Standard_CourierBoldOblique}
 *  <li>Helvetica - {@link Zend_Pdf_Resource_Font_Simple_Standard_Helvetica}
 *  <li>Helvetica-Bold - {@link Zend_Pdf_Resource_Font_Simple_Standard_HelveticaBold}
 *  <li>Helvetica-Oblique - {@link Zend_Pdf_Resource_Font_Simple_Standard_HelveticaOblique}
 *  <li>Helvetica-BoldOblique - {@link Zend_Pdf_Resource_Font_Simple_Standard_HelveticaBoldOblique}
 *  <li>Symbol - {@link Zend_Pdf_Resource_Font_Simple_Standard_Symbol}
 *  <li>Times - {@link Zend_Pdf_Resource_Font_Simple_Standard_Times}
 *  <li>Times-Bold - {@link Zend_Pdf_Resource_Font_Simple_Standard_TimesBold}
 *  <li>Times-Italic - {@link Zend_Pdf_Resource_Font_Simple_Standard_TimesItalic}
 *  <li>Times-BoldItalic - {@link Zend_Pdf_Resource_Font_Simple_Standard_TimesBoldItalic}
 *  <li>ZapfDingbats - {@link Zend_Pdf_Resource_Font_Simple_Standard_ZapfDingbats}
 * </ul>
 *
 * Font objects should be normally be obtained from the factory methods
 * {@link Zend_Pdf_Font::fontWithName} and {@link Zend_Pdf_Font::fontWithPath}.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Pdf_Resource_Font_Simple_Standard extends Zend_Pdf_Resource_Font_Simple
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        $this->_fontType = Zend_Pdf_Font::TYPE_STANDARD;

        parent::__construct();
        $this->_resource->Subtype  = new Zend_Pdf_Element_Name('Type1');
    }

}
Pdf/Resource/Font/Simple/Parsed/TrueType.php000066600000004327151256604610014733 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Parsed */
require_once 'Zend/Pdf/Resource/Font/Simple/Parsed.php';

/** Zend_Pdf_Resource_Font_FontDescriptor */
require_once 'Zend/Pdf/Resource/Font/FontDescriptor.php';



/**
 * TrueType fonts implementation
 *
 * Font objects should be normally be obtained from the factory methods
 * {@link Zend_Pdf_Font::fontWithName} and {@link Zend_Pdf_Font::fontWithPath}.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Parsed_TrueType extends Zend_Pdf_Resource_Font_Simple_Parsed
{
    /**
     * Object constructor
     *
     * @param Zend_Pdf_FileParser_Font_OpenType_TrueType $fontParser Font parser
     *   object containing parsed TrueType file.
     * @param integer $embeddingOptions Options for font embedding.
     * @throws Zend_Pdf_Exception
     */
    public function __construct(Zend_Pdf_FileParser_Font_OpenType_TrueType $fontParser, $embeddingOptions)
    {
        parent::__construct($fontParser, $embeddingOptions);

        $this->_fontType = Zend_Pdf_Font::TYPE_TRUETYPE;

        $this->_resource->Subtype  = new Zend_Pdf_Element_Name('TrueType');

        $fontDescriptor = Zend_Pdf_Resource_Font_FontDescriptor::factory($this, $fontParser, $embeddingOptions);
        $this->_resource->FontDescriptor = $this->_objectFactory->newObject($fontDescriptor);
    }

}
Pdf/Resource/Font/Simple/Standard/Symbol.php000066600000064225151256604610014744 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Symbol.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_Symbol extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Instance Variables ****/


    /**
     * Array for conversion from local encoding to special font encoding.
     * See {@link encodeString()}.
     * @var array
     */
    protected $_toFontEncoding = array(
            0x20 => "\x20",   0x21 => "\x21", 0x2200 => "\x22",   0x23 => "\x23",
          0x2203 => "\x24",   0x25 => "\x25",   0x26 => "\x26", 0x220b => "\x27",
            0x28 => "\x28",   0x29 => "\x29", 0x2217 => "\x2a",   0x2b => "\x2b",
            0x2c => "\x2c", 0x2212 => "\x2d",   0x2e => "\x2e",   0x2f => "\x2f",
            0x30 => "\x30",   0x31 => "\x31",   0x32 => "\x32",   0x33 => "\x33",
            0x34 => "\x34",   0x35 => "\x35",   0x36 => "\x36",   0x37 => "\x37",
            0x38 => "\x38",   0x39 => "\x39",   0x3a => "\x3a",   0x3b => "\x3b",
            0x3c => "\x3c",   0x3d => "\x3d",   0x3e => "\x3e",   0x3f => "\x3f",
          0x2245 => "\x40", 0x0391 => "\x41", 0x0392 => "\x42", 0x03a7 => "\x43",
          0x2206 => "\x44", 0x0395 => "\x45", 0x03a6 => "\x46", 0x0393 => "\x47",
          0x0397 => "\x48", 0x0399 => "\x49", 0x03d1 => "\x4a", 0x039a => "\x4b",
          0x039b => "\x4c", 0x039c => "\x4d", 0x039d => "\x4e", 0x039f => "\x4f",
          0x03a0 => "\x50", 0x0398 => "\x51", 0x03a1 => "\x52", 0x03a3 => "\x53",
          0x03a4 => "\x54", 0x03a5 => "\x55", 0x03c2 => "\x56", 0x2126 => "\x57",
          0x039e => "\x58", 0x03a8 => "\x59", 0x0396 => "\x5a",   0x5b => "\x5b",
          0x2234 => "\x5c",   0x5d => "\x5d", 0x22a5 => "\x5e",   0x5f => "\x5f",
          0xf8e5 => "\x60", 0x03b1 => "\x61", 0x03b2 => "\x62", 0x03c7 => "\x63",
          0x03b4 => "\x64", 0x03b5 => "\x65", 0x03c6 => "\x66", 0x03b3 => "\x67",
          0x03b7 => "\x68", 0x03b9 => "\x69", 0x03d5 => "\x6a", 0x03ba => "\x6b",
          0x03bb => "\x6c",   0xb5 => "\x6d", 0x03bd => "\x6e", 0x03bf => "\x6f",
          0x03c0 => "\x70", 0x03b8 => "\x71", 0x03c1 => "\x72", 0x03c3 => "\x73",
          0x03c4 => "\x74", 0x03c5 => "\x75", 0x03d6 => "\x76", 0x03c9 => "\x77",
          0x03be => "\x78", 0x03c8 => "\x79", 0x03b6 => "\x7a",   0x7b => "\x7b",
            0x7c => "\x7c",   0x7d => "\x7d", 0x223c => "\x7e", 0x20ac => "\xa0",
          0x03d2 => "\xa1", 0x2032 => "\xa2", 0x2264 => "\xa3", 0x2044 => "\xa4",
          0x221e => "\xa5", 0x0192 => "\xa6", 0x2663 => "\xa7", 0x2666 => "\xa8",
          0x2665 => "\xa9", 0x2660 => "\xaa", 0x2194 => "\xab", 0x2190 => "\xac",
          0x2191 => "\xad", 0x2192 => "\xae", 0x2193 => "\xaf",   0xb0 => "\xb0",
            0xb1 => "\xb1", 0x2033 => "\xb2", 0x2265 => "\xb3",   0xd7 => "\xb4",
          0x221d => "\xb5", 0x2202 => "\xb6", 0x2022 => "\xb7",   0xf7 => "\xb8",
          0x2260 => "\xb9", 0x2261 => "\xba", 0x2248 => "\xbb", 0x2026 => "\xbc",
          0xf8e6 => "\xbd", 0xf8e7 => "\xbe", 0x21b5 => "\xbf", 0x2135 => "\xc0",
          0x2111 => "\xc1", 0x211c => "\xc2", 0x2118 => "\xc3", 0x2297 => "\xc4",
          0x2295 => "\xc5", 0x2205 => "\xc6", 0x2229 => "\xc7", 0x222a => "\xc8",
          0x2283 => "\xc9", 0x2287 => "\xca", 0x2284 => "\xcb", 0x2282 => "\xcc",
          0x2286 => "\xcd", 0x2208 => "\xce", 0x2209 => "\xcf", 0x2220 => "\xd0",
          0x2207 => "\xd1", 0xf6da => "\xd2", 0xf6d9 => "\xd3", 0xf6db => "\xd4",
          0x220f => "\xd5", 0x221a => "\xd6", 0x22c5 => "\xd7",   0xac => "\xd8",
          0x2227 => "\xd9", 0x2228 => "\xda", 0x21d4 => "\xdb", 0x21d0 => "\xdc",
          0x21d1 => "\xdd", 0x21d2 => "\xde", 0x21d3 => "\xdf", 0x25ca => "\xe0",
          0x2329 => "\xe1", 0xf8e8 => "\xe2", 0xf8e9 => "\xe3", 0xf8ea => "\xe4",
          0x2211 => "\xe5", 0xf8eb => "\xe6", 0xf8ec => "\xe7", 0xf8ed => "\xe8",
          0xf8ee => "\xe9", 0xf8ef => "\xea", 0xf8f0 => "\xeb", 0xf8f1 => "\xec",
          0xf8f2 => "\xed", 0xf8f3 => "\xee", 0xf8f4 => "\xef", 0x232a => "\xf1",
          0x222b => "\xf2", 0x2320 => "\xf3", 0xf8f5 => "\xf4", 0x2321 => "\xf5",
          0xf8f6 => "\xf6", 0xf8f7 => "\xf7", 0xf8f8 => "\xf8", 0xf8f9 => "\xf9",
          0xf8fa => "\xfa", 0xf8fb => "\xfb", 0xf8fc => "\xfc", 0xf8fd => "\xfd",
          0xf8fe => "\xfe");

    /**
     * Array for conversion from special font encoding to local encoding.
     * See {@link decodeString()}.
     * @var array
     */
    protected $_fromFontEncoding = array(
            0x20 => "\x00\x20",   0x21 => "\x00\x21",   0x22 => "\x22\x00",
            0x23 => "\x00\x23",   0x24 => "\x22\x03",   0x25 => "\x00\x25",
            0x26 => "\x00\x26",   0x27 => "\x22\x0b",   0x28 => "\x00\x28",
            0x29 => "\x00\x29",   0x2a => "\x22\x17",   0x2b => "\x00\x2b",
            0x2c => "\x00\x2c",   0x2d => "\x22\x12",   0x2e => "\x00\x2e",
            0x2f => "\x00\x2f",   0x30 => "\x00\x30",   0x31 => "\x00\x31",
            0x32 => "\x00\x32",   0x33 => "\x00\x33",   0x34 => "\x00\x34",
            0x35 => "\x00\x35",   0x36 => "\x00\x36",   0x37 => "\x00\x37",
            0x38 => "\x00\x38",   0x39 => "\x00\x39",   0x3a => "\x00\x3a",
            0x3b => "\x00\x3b",   0x3c => "\x00\x3c",   0x3d => "\x00\x3d",
            0x3e => "\x00\x3e",   0x3f => "\x00\x3f",   0x40 => "\x22\x45",
            0x41 => "\x03\x91",   0x42 => "\x03\x92",   0x43 => "\x03\xa7",
            0x44 => "\x22\x06",   0x45 => "\x03\x95",   0x46 => "\x03\xa6",
            0x47 => "\x03\x93",   0x48 => "\x03\x97",   0x49 => "\x03\x99",
            0x4a => "\x03\xd1",   0x4b => "\x03\x9a",   0x4c => "\x03\x9b",
            0x4d => "\x03\x9c",   0x4e => "\x03\x9d",   0x4f => "\x03\x9f",
            0x50 => "\x03\xa0",   0x51 => "\x03\x98",   0x52 => "\x03\xa1",
            0x53 => "\x03\xa3",   0x54 => "\x03\xa4",   0x55 => "\x03\xa5",
            0x56 => "\x03\xc2",   0x57 => "\x21\x26",   0x58 => "\x03\x9e",
            0x59 => "\x03\xa8",   0x5a => "\x03\x96",   0x5b => "\x00\x5b",
            0x5c => "\x22\x34",   0x5d => "\x00\x5d",   0x5e => "\x22\xa5",
            0x5f => "\x00\x5f",   0x60 => "\xf8\xe5",   0x61 => "\x03\xb1",
            0x62 => "\x03\xb2",   0x63 => "\x03\xc7",   0x64 => "\x03\xb4",
            0x65 => "\x03\xb5",   0x66 => "\x03\xc6",   0x67 => "\x03\xb3",
            0x68 => "\x03\xb7",   0x69 => "\x03\xb9",   0x6a => "\x03\xd5",
            0x6b => "\x03\xba",   0x6c => "\x03\xbb",   0x6d => "\x00\xb5",
            0x6e => "\x03\xbd",   0x6f => "\x03\xbf",   0x70 => "\x03\xc0",
            0x71 => "\x03\xb8",   0x72 => "\x03\xc1",   0x73 => "\x03\xc3",
            0x74 => "\x03\xc4",   0x75 => "\x03\xc5",   0x76 => "\x03\xd6",
            0x77 => "\x03\xc9",   0x78 => "\x03\xbe",   0x79 => "\x03\xc8",
            0x7a => "\x03\xb6",   0x7b => "\x00\x7b",   0x7c => "\x00\x7c",
            0x7d => "\x00\x7d",   0x7e => "\x22\x3c",   0xa0 => "\x20\xac",
            0xa1 => "\x03\xd2",   0xa2 => "\x20\x32",   0xa3 => "\x22\x64",
            0xa4 => "\x20\x44",   0xa5 => "\x22\x1e",   0xa6 => "\x01\x92",
            0xa7 => "\x26\x63",   0xa8 => "\x26\x66",   0xa9 => "\x26\x65",
            0xaa => "\x26\x60",   0xab => "\x21\x94",   0xac => "\x21\x90",
            0xad => "\x21\x91",   0xae => "\x21\x92",   0xaf => "\x21\x93",
            0xb0 => "\x00\xb0",   0xb1 => "\x00\xb1",   0xb2 => "\x20\x33",
            0xb3 => "\x22\x65",   0xb4 => "\x00\xd7",   0xb5 => "\x22\x1d",
            0xb6 => "\x22\x02",   0xb7 => "\x20\x22",   0xb8 => "\x00\xf7",
            0xb9 => "\x22\x60",   0xba => "\x22\x61",   0xbb => "\x22\x48",
            0xbc => "\x20\x26",   0xbd => "\xf8\xe6",   0xbe => "\xf8\xe7",
            0xbf => "\x21\xb5",   0xc0 => "\x21\x35",   0xc1 => "\x21\x11",
            0xc2 => "\x21\x1c",   0xc3 => "\x21\x18",   0xc4 => "\x22\x97",
            0xc5 => "\x22\x95",   0xc6 => "\x22\x05",   0xc7 => "\x22\x29",
            0xc8 => "\x22\x2a",   0xc9 => "\x22\x83",   0xca => "\x22\x87",
            0xcb => "\x22\x84",   0xcc => "\x22\x82",   0xcd => "\x22\x86",
            0xce => "\x22\x08",   0xcf => "\x22\x09",   0xd0 => "\x22\x20",
            0xd1 => "\x22\x07",   0xd2 => "\xf6\xda",   0xd3 => "\xf6\xd9",
            0xd4 => "\xf6\xdb",   0xd5 => "\x22\x0f",   0xd6 => "\x22\x1a",
            0xd7 => "\x22\xc5",   0xd8 => "\x00\xac",   0xd9 => "\x22\x27",
            0xda => "\x22\x28",   0xdb => "\x21\xd4",   0xdc => "\x21\xd0",
            0xdd => "\x21\xd1",   0xde => "\x21\xd2",   0xdf => "\x21\xd3",
            0xe0 => "\x25\xca",   0xe1 => "\x23\x29",   0xe2 => "\xf8\xe8",
            0xe3 => "\xf8\xe9",   0xe4 => "\xf8\xea",   0xe5 => "\x22\x11",
            0xe6 => "\xf8\xeb",   0xe7 => "\xf8\xec",   0xe8 => "\xf8\xed",
            0xe9 => "\xf8\xee",   0xea => "\xf8\xef",   0xeb => "\xf8\xf0",
            0xec => "\xf8\xf1",   0xed => "\xf8\xf2",   0xee => "\xf8\xf3",
            0xef => "\xf8\xf4",   0xf1 => "\x23\x2a",   0xf2 => "\x22\x2b",
            0xf3 => "\x23\x20",   0xf4 => "\xf8\xf5",   0xf5 => "\x23\x21",
            0xf6 => "\xf8\xf6",   0xf7 => "\xf8\xf7",   0xf8 => "\xf8\xf8",
            0xf9 => "\xf8\xf9",   0xfa => "\xf8\xfa",   0xfb => "\xf8\xfb",
            0xfc => "\xf8\xfc",   0xfd => "\xf8\xfd",   0xfe => "\xf8\xfe",
        );



  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x37\x00\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00"
          . "\x20\x00\x53\x00\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00"
          . "\x20\x00\x49\x00\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00"
          . "\x72\x00\x61\x00\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x41\x00"
          . "\x6c\x00\x6c\x00\x20\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00"
          . "\x73\x00\x20\x00\x72\x00\x65\x00\x73\x00\x65\x00\x72\x00\x76\x00"
          . "\x65\x00\x64\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x53\x00\x79\x00\x6d\x00\x62\x00\x6f\x00\x6c";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x36\x00\x34";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x53\x00\x79\x00\x6d\x00\x62\x00\x6f\x00\x6c\x00\x20\x00\x4d\x00"
          . "\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x31\x00\x2e\x00\x30\x00\x30\x00\x38";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x53\x00\x79\x00\x6d\x00\x62\x00\x6f\x00\x6c";

        $this->_isBold = false;
        $this->_isItalic = false;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 1000;
        $this->_descent = 0;
        $this->_lineGap = 200;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 =>   0xfa,   0x02 => 0x014d,   0x03 => 0x02c9,
            0x04 => 0x01f4,   0x05 => 0x0225,   0x06 => 0x0341,   0x07 => 0x030a,
            0x08 => 0x01b7,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x01f4,
            0x0c => 0x0225,   0x0d =>   0xfa,   0x0e => 0x0225,   0x0f =>   0xfa,
            0x10 => 0x0116,   0x11 => 0x01f4,   0x12 => 0x01f4,   0x13 => 0x01f4,
            0x14 => 0x01f4,   0x15 => 0x01f4,   0x16 => 0x01f4,   0x17 => 0x01f4,
            0x18 => 0x01f4,   0x19 => 0x01f4,   0x1a => 0x01f4,   0x1b => 0x0116,
            0x1c => 0x0116,   0x1d => 0x0225,   0x1e => 0x0225,   0x1f => 0x0225,
            0x20 => 0x01bc,   0x21 => 0x0225,   0x22 => 0x02d2,   0x23 => 0x029b,
            0x24 => 0x02d2,   0x25 => 0x0264,   0x26 => 0x0263,   0x27 => 0x02fb,
            0x28 => 0x025b,   0x29 => 0x02d2,   0x2a => 0x014d,   0x2b => 0x0277,
            0x2c => 0x02d2,   0x2d => 0x02ae,   0x2e => 0x0379,   0x2f => 0x02d2,
            0x30 => 0x02d2,   0x31 => 0x0300,   0x32 => 0x02e5,   0x33 => 0x022c,
            0x34 => 0x0250,   0x35 => 0x0263,   0x36 => 0x02b2,   0x37 => 0x01b7,
            0x38 => 0x0300,   0x39 => 0x0285,   0x3a => 0x031b,   0x3b => 0x0263,
            0x3c => 0x014d,   0x3d => 0x035f,   0x3e => 0x014d,   0x3f => 0x0292,
            0x40 => 0x01f4,   0x41 => 0x01f4,   0x42 => 0x0277,   0x43 => 0x0225,
            0x44 => 0x0225,   0x45 => 0x01ee,   0x46 => 0x01b7,   0x47 => 0x0209,
            0x48 => 0x019b,   0x49 => 0x025b,   0x4a => 0x0149,   0x4b => 0x025b,
            0x4c => 0x0225,   0x4d => 0x0225,   0x4e => 0x0240,   0x4f => 0x0209,
            0x50 => 0x0225,   0x51 => 0x0225,   0x52 => 0x0209,   0x53 => 0x0225,
            0x54 => 0x025b,   0x55 => 0x01b7,   0x56 => 0x0240,   0x57 => 0x02c9,
            0x58 => 0x02ae,   0x59 => 0x01ed,   0x5a => 0x02ae,   0x5b => 0x01ee,
            0x5c => 0x01e0,   0x5d =>   0xc8,   0x5e => 0x01e0,   0x5f => 0x0225,
            0x60 => 0x02ee,   0x61 => 0x026c,   0x62 =>   0xf7,   0x63 => 0x0225,
            0x64 =>   0xa7,   0x65 => 0x02c9,   0x66 => 0x01f4,   0x67 => 0x02f1,
            0x68 => 0x02f1,   0x69 => 0x02f1,   0x6a => 0x02f1,   0x6b => 0x0412,
            0x6c => 0x03db,   0x6d => 0x025b,   0x6e => 0x03db,   0x6f => 0x025b,
            0x70 => 0x0190,   0x71 => 0x0225,   0x72 => 0x019b,   0x73 => 0x0225,
            0x74 => 0x0225,   0x75 => 0x02c9,   0x76 => 0x01ee,   0x77 => 0x01cc,
            0x78 => 0x0225,   0x79 => 0x0225,   0x7a => 0x0225,   0x7b => 0x0225,
            0x7c => 0x03e8,   0x7d => 0x025b,   0x7e => 0x03e8,   0x7f => 0x0292,
            0x80 => 0x0337,   0x81 => 0x02ae,   0x82 => 0x031b,   0x83 => 0x03db,
            0x84 => 0x0300,   0x85 => 0x0300,   0x86 => 0x0337,   0x87 => 0x0300,
            0x88 => 0x0300,   0x89 => 0x02c9,   0x8a => 0x02c9,   0x8b => 0x02c9,
            0x8c => 0x02c9,   0x8d => 0x02c9,   0x8e => 0x02c9,   0x8f => 0x02c9,
            0x90 => 0x0300,   0x91 => 0x02c9,   0x92 => 0x0316,   0x93 => 0x0316,
            0x94 => 0x037a,   0x95 => 0x0337,   0x96 => 0x0225,   0x97 =>   0xfa,
            0x98 => 0x02c9,   0x99 => 0x025b,   0x9a => 0x025b,   0x9b => 0x0412,
            0x9c => 0x03db,   0x9d => 0x025b,   0x9e => 0x03db,   0x9f => 0x025b,
            0xa0 => 0x01ee,   0xa1 => 0x0149,   0xa2 => 0x0316,   0xa3 => 0x0316,
            0xa4 => 0x0312,   0xa5 => 0x02c9,   0xa6 => 0x0180,   0xa7 => 0x0180,
            0xa8 => 0x0180,   0xa9 => 0x0180,   0xaa => 0x0180,   0xab => 0x0180,
            0xac => 0x01ee,   0xad => 0x01ee,   0xae => 0x01ee,   0xaf => 0x01ee,
            0xb0 => 0x0149,   0xb1 => 0x0112,   0xb2 => 0x02ae,   0xb3 => 0x02ae,
            0xb4 => 0x02ae,   0xb5 => 0x0180,   0xb6 => 0x0180,   0xb7 => 0x0180,
            0xb8 => 0x0180,   0xb9 => 0x0180,   0xba => 0x0180,   0xbb => 0x01ee,
            0xbc => 0x01ee,   0xbd => 0x01ee,   0xbe => 0x0316);

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02, 0x2200 =>   0x03,   0x23 =>   0x04,
          0x2203 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x220b =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a, 0x2217 =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d, 0x2212 =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
          0x2245 =>   0x21, 0x0391 =>   0x22, 0x0392 =>   0x23, 0x03a7 =>   0x24,
          0x2206 =>   0x25, 0x0395 =>   0x26, 0x03a6 =>   0x27, 0x0393 =>   0x28,
          0x0397 =>   0x29, 0x0399 =>   0x2a, 0x03d1 =>   0x2b, 0x039a =>   0x2c,
          0x039b =>   0x2d, 0x039c =>   0x2e, 0x039d =>   0x2f, 0x039f =>   0x30,
          0x03a0 =>   0x31, 0x0398 =>   0x32, 0x03a1 =>   0x33, 0x03a3 =>   0x34,
          0x03a4 =>   0x35, 0x03a5 =>   0x36, 0x03c2 =>   0x37, 0x2126 =>   0x38,
          0x039e =>   0x39, 0x03a8 =>   0x3a, 0x0396 =>   0x3b,   0x5b =>   0x3c,
          0x2234 =>   0x3d,   0x5d =>   0x3e, 0x22a5 =>   0x3f,   0x5f =>   0x40,
          0xf8e5 =>   0x41, 0x03b1 =>   0x42, 0x03b2 =>   0x43, 0x03c7 =>   0x44,
          0x03b4 =>   0x45, 0x03b5 =>   0x46, 0x03c6 =>   0x47, 0x03b3 =>   0x48,
          0x03b7 =>   0x49, 0x03b9 =>   0x4a, 0x03d5 =>   0x4b, 0x03ba =>   0x4c,
          0x03bb =>   0x4d,   0xb5 =>   0x4e, 0x03bd =>   0x4f, 0x03bf =>   0x50,
          0x03c0 =>   0x51, 0x03b8 =>   0x52, 0x03c1 =>   0x53, 0x03c3 =>   0x54,
          0x03c4 =>   0x55, 0x03c5 =>   0x56, 0x03d6 =>   0x57, 0x03c9 =>   0x58,
          0x03be =>   0x59, 0x03c8 =>   0x5a, 0x03b6 =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e, 0x223c =>   0x5f, 0x20ac =>   0x60,
          0x03d2 =>   0x61, 0x2032 =>   0x62, 0x2264 =>   0x63, 0x2044 =>   0x64,
          0x221e =>   0x65, 0x0192 =>   0x66, 0x2663 =>   0x67, 0x2666 =>   0x68,
          0x2665 =>   0x69, 0x2660 =>   0x6a, 0x2194 =>   0x6b, 0x2190 =>   0x6c,
          0x2191 =>   0x6d, 0x2192 =>   0x6e, 0x2193 =>   0x6f,   0xb0 =>   0x70,
            0xb1 =>   0x71, 0x2033 =>   0x72, 0x2265 =>   0x73,   0xd7 =>   0x74,
          0x221d =>   0x75, 0x2202 =>   0x76, 0x2022 =>   0x77,   0xf7 =>   0x78,
          0x2260 =>   0x79, 0x2261 =>   0x7a, 0x2248 =>   0x7b, 0x2026 =>   0x7c,
          0xf8e6 =>   0x7d, 0xf8e7 =>   0x7e, 0x21b5 =>   0x7f, 0x2135 =>   0x80,
          0x2111 =>   0x81, 0x211c =>   0x82, 0x2118 =>   0x83, 0x2297 =>   0x84,
          0x2295 =>   0x85, 0x2205 =>   0x86, 0x2229 =>   0x87, 0x222a =>   0x88,
          0x2283 =>   0x89, 0x2287 =>   0x8a, 0x2284 =>   0x8b, 0x2282 =>   0x8c,
          0x2286 =>   0x8d, 0x2208 =>   0x8e, 0x2209 =>   0x8f, 0x2220 =>   0x90,
          0x2207 =>   0x91, 0xf6da =>   0x92, 0xf6d9 =>   0x93, 0xf6db =>   0x94,
          0x220f =>   0x95, 0x221a =>   0x96, 0x22c5 =>   0x97,   0xac =>   0x98,
          0x2227 =>   0x99, 0x2228 =>   0x9a, 0x21d4 =>   0x9b, 0x21d0 =>   0x9c,
          0x21d1 =>   0x9d, 0x21d2 =>   0x9e, 0x21d3 =>   0x9f, 0x25ca =>   0xa0,
          0x2329 =>   0xa1, 0xf8e8 =>   0xa2, 0xf8e9 =>   0xa3, 0xf8ea =>   0xa4,
          0x2211 =>   0xa5, 0xf8eb =>   0xa6, 0xf8ec =>   0xa7, 0xf8ed =>   0xa8,
          0xf8ee =>   0xa9, 0xf8ef =>   0xaa, 0xf8f0 =>   0xab, 0xf8f1 =>   0xac,
          0xf8f2 =>   0xad, 0xf8f3 =>   0xae, 0xf8f4 =>   0xaf, 0x232a =>   0xb0,
          0x222b =>   0xb1, 0x2320 =>   0xb2, 0xf8f5 =>   0xb3, 0x2321 =>   0xb4,
          0xf8f6 =>   0xb5, 0xf8f7 =>   0xb6, 0xf8f8 =>   0xb7, 0xf8f9 =>   0xb8,
          0xf8fa =>   0xb9, 0xf8fb =>   0xba, 0xf8fc =>   0xbb, 0xf8fd =>   0xbc,
          0xf8fe =>   0xbd, 0xf8ff =>   0xbe);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Symbol');

        /* This font has a built-in custom character encoding method. Don't
         * override with WinAnsi like the other built-in fonts or else it will
         * not work as expected.
         */
        $this->_resource->Encoding = null;
    }


  /* Information and Conversion Methods */

    /**
     * Convert string encoding from local encoding to font encoding. Overridden
     * to defeat the conversion behavior for this ornamental font.
     *
     * @param string $string
     * @param string $charEncoding Character encoding of source text.
     * @return string
     */
    public function encodeString($string, $charEncoding)
    {
        /* This isn't the optimal time to perform this conversion, but it must
         * live here until the remainder of the layout code is completed. This,
         * and the $charEncoding parameter, will go away soon...
         */
        if ($charEncoding != 'UTF-16BE') {
            $string = iconv($charEncoding, 'UTF-16BE', $string);
        }
        /**
         * @todo Properly handle characters encoded as surrogate pairs.
         */
        $encodedString = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $characterCode = (ord($string[$i++]) << 8) | ord($string[$i]);
            if (isset($this->_toFontEncoding[$characterCode])) {
                $encodedString .= $this->_toFontEncoding[$characterCode];
            } else {
                /* For now, mimic the behavior in Zend_Pdf_Font::encodeString()
                 * where unknown characters are removed completely. This is not
                 * perfect, but we should be consistent. In a future revision,
                 * we will use the well-known substitution character 0x1a
                 * (Control-Z).
                 */
            }
        }
        return $encodedString;
    }

    /**
     * Convert string encoding from font encoding to local encoding. Overridden
     * to defeat the conversion behavior for this ornamental font.
     *
     * @param string $string
     * @param string $charEncoding Character encoding of resulting text.
     * @return string
     */
    public function decodeString($string, $charEncoding)
    {
        $decodedString = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $characterCode = ord($string[$i]);
            if (isset($this->_fromFontEncoding[$characterCode])) {
                $decodedString .= $this->_fromFontEncoding[$characterCode];
            } else {
                /* For now, mimic the behavior in Zend_Pdf_Font::encodeString()
                 * where unknown characters are removed completely. This is not
                 * perfect, but we should be consistent. In a future revision,
                 * we will use the Unicode substitution character (U+FFFD).
                 */
            }
        }
        if ($charEncoding != 'UTF-16BE') {
            $decodedString = iconv('UTF-16BE', $charEncoding, $decodedString);
        }
        return $decodedString;
    }

    /**
     * Converts a Latin-encoded string that fakes the font's internal encoding
     * to the proper Unicode characters, in UTF-16BE encoding.
     *
     * Used to maintain backwards compatibility with the 20 year-old legacy
     * method of using this font, which is still employed by recent versions of
     * some popular word processors.
     *
     * Note that using this method adds overhead due to the additional
     * character conversion. Don't use this for new code; it is more efficient
     * to use the appropriate Unicode characters directly.
     *
     * @param string $string
     * @param string $charEncoding (optional) Character encoding of source
     *   string. Defaults to current locale.
     * @return string
     */
    public function toUnicode($string, $charEncoding = '')
    {
        /* When using these faked strings, the closest match to the font's
         * internal encoding is ISO-8859-1.
         */
        if ($charEncoding != 'ISO-8859-1') {
            $string = iconv($charEncoding, 'ISO-8859-1', $string);
        }
        return $this->decodeString($string, 'UTF-16BE');
    }

}
Pdf/Resource/Font/Simple/Standard/CourierBold.php000066600000044302151256604610015702 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Courier-Bold.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_CourierBold extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x39\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x30\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x31\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x33\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x37\x00\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00"
          . "\x20\x00\x53\x00\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00"
          . "\x20\x00\x49\x00\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00"
          . "\x72\x00\x61\x00\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00"
          . "\x41\x00\x6c\x00\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x73\x00\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00"
          . "\x76\x00\x65\x00\x64\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x34\x00\x38";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72\x00\x2d\x00"
          . "\x42\x00\x6f\x00\x6c\x00\x64\x00\x20\x00\x42\x00\x6f\x00\x6c\x00"
          . "\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x33\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72\x00\x2d\x00"
          . "\x42\x00\x6f\x00\x6c\x00\x64";

        $this->_isBold = true;
        $this->_isItalic = false;
        $this->_isMonospaced = true;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 629;
        $this->_descent = -157;
        $this->_lineGap = 414;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0258,   0x02 => 0x0258,   0x03 => 0x0258,
            0x04 => 0x0258,   0x05 => 0x0258,   0x06 => 0x0258,   0x07 => 0x0258,
            0x08 => 0x0258,   0x09 => 0x0258,   0x0a => 0x0258,   0x0b => 0x0258,
            0x0c => 0x0258,   0x0d => 0x0258,   0x0e => 0x0258,   0x0f => 0x0258,
            0x10 => 0x0258,   0x11 => 0x0258,   0x12 => 0x0258,   0x13 => 0x0258,
            0x14 => 0x0258,   0x15 => 0x0258,   0x16 => 0x0258,   0x17 => 0x0258,
            0x18 => 0x0258,   0x19 => 0x0258,   0x1a => 0x0258,   0x1b => 0x0258,
            0x1c => 0x0258,   0x1d => 0x0258,   0x1e => 0x0258,   0x1f => 0x0258,
            0x20 => 0x0258,   0x21 => 0x0258,   0x22 => 0x0258,   0x23 => 0x0258,
            0x24 => 0x0258,   0x25 => 0x0258,   0x26 => 0x0258,   0x27 => 0x0258,
            0x28 => 0x0258,   0x29 => 0x0258,   0x2a => 0x0258,   0x2b => 0x0258,
            0x2c => 0x0258,   0x2d => 0x0258,   0x2e => 0x0258,   0x2f => 0x0258,
            0x30 => 0x0258,   0x31 => 0x0258,   0x32 => 0x0258,   0x33 => 0x0258,
            0x34 => 0x0258,   0x35 => 0x0258,   0x36 => 0x0258,   0x37 => 0x0258,
            0x38 => 0x0258,   0x39 => 0x0258,   0x3a => 0x0258,   0x3b => 0x0258,
            0x3c => 0x0258,   0x3d => 0x0258,   0x3e => 0x0258,   0x3f => 0x0258,
            0x40 => 0x0258,   0x41 => 0x0258,   0x42 => 0x0258,   0x43 => 0x0258,
            0x44 => 0x0258,   0x45 => 0x0258,   0x46 => 0x0258,   0x47 => 0x0258,
            0x48 => 0x0258,   0x49 => 0x0258,   0x4a => 0x0258,   0x4b => 0x0258,
            0x4c => 0x0258,   0x4d => 0x0258,   0x4e => 0x0258,   0x4f => 0x0258,
            0x50 => 0x0258,   0x51 => 0x0258,   0x52 => 0x0258,   0x53 => 0x0258,
            0x54 => 0x0258,   0x55 => 0x0258,   0x56 => 0x0258,   0x57 => 0x0258,
            0x58 => 0x0258,   0x59 => 0x0258,   0x5a => 0x0258,   0x5b => 0x0258,
            0x5c => 0x0258,   0x5d => 0x0258,   0x5e => 0x0258,   0x5f => 0x0258,
            0x60 => 0x0258,   0x61 => 0x0258,   0x62 => 0x0258,   0x63 => 0x0258,
            0x64 => 0x0258,   0x65 => 0x0258,   0x66 => 0x0258,   0x67 => 0x0258,
            0x68 => 0x0258,   0x69 => 0x0258,   0x6a => 0x0258,   0x6b => 0x0258,
            0x6c => 0x0258,   0x6d => 0x0258,   0x6e => 0x0258,   0x6f => 0x0258,
            0x70 => 0x0258,   0x71 => 0x0258,   0x72 => 0x0258,   0x73 => 0x0258,
            0x74 => 0x0258,   0x75 => 0x0258,   0x76 => 0x0258,   0x77 => 0x0258,
            0x78 => 0x0258,   0x79 => 0x0258,   0x7a => 0x0258,   0x7b => 0x0258,
            0x7c => 0x0258,   0x7d => 0x0258,   0x7e => 0x0258,   0x7f => 0x0258,
            0x80 => 0x0258,   0x81 => 0x0258,   0x82 => 0x0258,   0x83 => 0x0258,
            0x84 => 0x0258,   0x85 => 0x0258,   0x86 => 0x0258,   0x87 => 0x0258,
            0x88 => 0x0258,   0x89 => 0x0258,   0x8a => 0x0258,   0x8b => 0x0258,
            0x8c => 0x0258,   0x8d => 0x0258,   0x8e => 0x0258,   0x8f => 0x0258,
            0x90 => 0x0258,   0x91 => 0x0258,   0x92 => 0x0258,   0x93 => 0x0258,
            0x94 => 0x0258,   0x95 => 0x0258,   0x96 => 0x0258,   0x97 => 0x0258,
            0x98 => 0x0258,   0x99 => 0x0258,   0x9a => 0x0258,   0x9b => 0x0258,
            0x9c => 0x0258,   0x9d => 0x0258,   0x9e => 0x0258,   0x9f => 0x0258,
            0xa0 => 0x0258,   0xa1 => 0x0258,   0xa2 => 0x0258,   0xa3 => 0x0258,
            0xa4 => 0x0258,   0xa5 => 0x0258,   0xa6 => 0x0258,   0xa7 => 0x0258,
            0xa8 => 0x0258,   0xa9 => 0x0258,   0xaa => 0x0258,   0xab => 0x0258,
            0xac => 0x0258,   0xad => 0x0258,   0xae => 0x0258,   0xaf => 0x0258,
            0xb0 => 0x0258,   0xb1 => 0x0258,   0xb2 => 0x0258,   0xb3 => 0x0258,
            0xb4 => 0x0258,   0xb5 => 0x0258,   0xb6 => 0x0258,   0xb7 => 0x0258,
            0xb8 => 0x0258,   0xb9 => 0x0258,   0xba => 0x0258,   0xbb => 0x0258,
            0xbc => 0x0258,   0xbd => 0x0258,   0xbe => 0x0258,   0xbf => 0x0258,
            0xc0 => 0x0258,   0xc1 => 0x0258,   0xc2 => 0x0258,   0xc3 => 0x0258,
            0xc4 => 0x0258,   0xc5 => 0x0258,   0xc6 => 0x0258,   0xc7 => 0x0258,
            0xc8 => 0x0258,   0xc9 => 0x0258,   0xca => 0x0258,   0xcb => 0x0258,
            0xcc => 0x0258,   0xcd => 0x0258,   0xce => 0x0258,   0xcf => 0x0258,
            0xd0 => 0x0258,   0xd1 => 0x0258,   0xd2 => 0x0258,   0xd3 => 0x0258,
            0xd4 => 0x0258,   0xd5 => 0x0258,   0xd6 => 0x0258,   0xd7 => 0x0258,
            0xd8 => 0x0258,   0xd9 => 0x0258,   0xda => 0x0258,   0xdb => 0x0258,
            0xdc => 0x0258,   0xdd => 0x0258,   0xde => 0x0258,   0xdf => 0x0258,
            0xe0 => 0x0258,   0xe1 => 0x0258,   0xe2 => 0x0258,   0xe3 => 0x0258,
            0xe4 => 0x0258,   0xe5 => 0x0258,   0xe6 => 0x0258,   0xe7 => 0x0258,
            0xe8 => 0x0258,   0xe9 => 0x0258,   0xea => 0x0258,   0xeb => 0x0258,
            0xec => 0x0258,   0xed => 0x0258,   0xee => 0x0258,   0xef => 0x0258,
            0xf0 => 0x0258,   0xf1 => 0x0258,   0xf2 => 0x0258,   0xf3 => 0x0258,
            0xf4 => 0x0258,   0xf5 => 0x0258,   0xf6 => 0x0258,   0xf7 => 0x0258,
            0xf8 => 0x0258,   0xf9 => 0x0258,   0xfa => 0x0258,   0xfb => 0x0258,
            0xfc => 0x0258,   0xfd => 0x0258,   0xfe => 0x0258,   0xff => 0x0258,
          0x0100 => 0x0258, 0x0101 => 0x0258, 0x0102 => 0x0258, 0x0103 => 0x0258,
          0x0104 => 0x0258, 0x0105 => 0x0258, 0x0106 => 0x0258, 0x0107 => 0x0258,
          0x0108 => 0x0258, 0x0109 => 0x0258, 0x010a => 0x0258, 0x010b => 0x0258,
          0x010c => 0x0258, 0x010d => 0x0258, 0x010e => 0x0258, 0x010f => 0x0258,
          0x0110 => 0x0258, 0x0111 => 0x0258, 0x0112 => 0x0258, 0x0113 => 0x0258,
          0x0114 => 0x0258, 0x0115 => 0x0258, 0x0116 => 0x0258, 0x0117 => 0x0258,
          0x0118 => 0x0258, 0x0119 => 0x0258, 0x011a => 0x0258, 0x011b => 0x0258,
          0x011c => 0x0258, 0x011d => 0x0258, 0x011e => 0x0258, 0x011f => 0x0258,
          0x0120 => 0x0258, 0x0121 => 0x0258, 0x0122 => 0x0258, 0x0123 => 0x0258,
          0x0124 => 0x0258, 0x0125 => 0x0258, 0x0126 => 0x0258, 0x0127 => 0x0258,
          0x0128 => 0x0258, 0x0129 => 0x0258, 0x012a => 0x0258, 0x012b => 0x0258,
          0x012c => 0x0258, 0x012d => 0x0258, 0x012e => 0x0258, 0x012f => 0x0258,
          0x0130 => 0x0258, 0x0131 => 0x0258, 0x0132 => 0x0258, 0x0133 => 0x0258,
          0x0134 => 0x0258, 0x0135 => 0x0258, 0x0136 => 0x0258, 0x0137 => 0x0258,
          0x0138 => 0x0258, 0x0139 => 0x0258, 0x013a => 0x0258, 0x013b => 0x0258,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Courier-Bold');
    }

}
Pdf/Resource/Font/Simple/Standard/CourierBoldOblique.php000066600000044526151256604610017233 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Courier-BoldOblique.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_CourierBoldOblique extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x39\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x30\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x31\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x33\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x37\x00\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00"
          . "\x20\x00\x53\x00\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00"
          . "\x20\x00\x49\x00\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00"
          . "\x72\x00\x61\x00\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00"
          . "\x41\x00\x6c\x00\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x73\x00\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00"
          . "\x76\x00\x65\x00\x64\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x34\x00\x39";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72\x00\x2d\x00"
          . "\x42\x00\x6f\x00\x6c\x00\x64\x00\x4f\x00\x62\x00\x6c\x00\x69\x00"
          . "\x71\x00\x75\x00\x65\x00\x20\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x33\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72\x00\x2d\x00"
          . "\x42\x00\x6f\x00\x6c\x00\x64\x00\x4f\x00\x62\x00\x6c\x00\x69\x00"
          . "\x71\x00\x75\x00\x65";

        $this->_isBold = true;
        $this->_isItalic = true;
        $this->_isMonospaced = true;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 629;
        $this->_descent = -157;
        $this->_lineGap = 414;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0258,   0x02 => 0x0258,   0x03 => 0x0258,
            0x04 => 0x0258,   0x05 => 0x0258,   0x06 => 0x0258,   0x07 => 0x0258,
            0x08 => 0x0258,   0x09 => 0x0258,   0x0a => 0x0258,   0x0b => 0x0258,
            0x0c => 0x0258,   0x0d => 0x0258,   0x0e => 0x0258,   0x0f => 0x0258,
            0x10 => 0x0258,   0x11 => 0x0258,   0x12 => 0x0258,   0x13 => 0x0258,
            0x14 => 0x0258,   0x15 => 0x0258,   0x16 => 0x0258,   0x17 => 0x0258,
            0x18 => 0x0258,   0x19 => 0x0258,   0x1a => 0x0258,   0x1b => 0x0258,
            0x1c => 0x0258,   0x1d => 0x0258,   0x1e => 0x0258,   0x1f => 0x0258,
            0x20 => 0x0258,   0x21 => 0x0258,   0x22 => 0x0258,   0x23 => 0x0258,
            0x24 => 0x0258,   0x25 => 0x0258,   0x26 => 0x0258,   0x27 => 0x0258,
            0x28 => 0x0258,   0x29 => 0x0258,   0x2a => 0x0258,   0x2b => 0x0258,
            0x2c => 0x0258,   0x2d => 0x0258,   0x2e => 0x0258,   0x2f => 0x0258,
            0x30 => 0x0258,   0x31 => 0x0258,   0x32 => 0x0258,   0x33 => 0x0258,
            0x34 => 0x0258,   0x35 => 0x0258,   0x36 => 0x0258,   0x37 => 0x0258,
            0x38 => 0x0258,   0x39 => 0x0258,   0x3a => 0x0258,   0x3b => 0x0258,
            0x3c => 0x0258,   0x3d => 0x0258,   0x3e => 0x0258,   0x3f => 0x0258,
            0x40 => 0x0258,   0x41 => 0x0258,   0x42 => 0x0258,   0x43 => 0x0258,
            0x44 => 0x0258,   0x45 => 0x0258,   0x46 => 0x0258,   0x47 => 0x0258,
            0x48 => 0x0258,   0x49 => 0x0258,   0x4a => 0x0258,   0x4b => 0x0258,
            0x4c => 0x0258,   0x4d => 0x0258,   0x4e => 0x0258,   0x4f => 0x0258,
            0x50 => 0x0258,   0x51 => 0x0258,   0x52 => 0x0258,   0x53 => 0x0258,
            0x54 => 0x0258,   0x55 => 0x0258,   0x56 => 0x0258,   0x57 => 0x0258,
            0x58 => 0x0258,   0x59 => 0x0258,   0x5a => 0x0258,   0x5b => 0x0258,
            0x5c => 0x0258,   0x5d => 0x0258,   0x5e => 0x0258,   0x5f => 0x0258,
            0x60 => 0x0258,   0x61 => 0x0258,   0x62 => 0x0258,   0x63 => 0x0258,
            0x64 => 0x0258,   0x65 => 0x0258,   0x66 => 0x0258,   0x67 => 0x0258,
            0x68 => 0x0258,   0x69 => 0x0258,   0x6a => 0x0258,   0x6b => 0x0258,
            0x6c => 0x0258,   0x6d => 0x0258,   0x6e => 0x0258,   0x6f => 0x0258,
            0x70 => 0x0258,   0x71 => 0x0258,   0x72 => 0x0258,   0x73 => 0x0258,
            0x74 => 0x0258,   0x75 => 0x0258,   0x76 => 0x0258,   0x77 => 0x0258,
            0x78 => 0x0258,   0x79 => 0x0258,   0x7a => 0x0258,   0x7b => 0x0258,
            0x7c => 0x0258,   0x7d => 0x0258,   0x7e => 0x0258,   0x7f => 0x0258,
            0x80 => 0x0258,   0x81 => 0x0258,   0x82 => 0x0258,   0x83 => 0x0258,
            0x84 => 0x0258,   0x85 => 0x0258,   0x86 => 0x0258,   0x87 => 0x0258,
            0x88 => 0x0258,   0x89 => 0x0258,   0x8a => 0x0258,   0x8b => 0x0258,
            0x8c => 0x0258,   0x8d => 0x0258,   0x8e => 0x0258,   0x8f => 0x0258,
            0x90 => 0x0258,   0x91 => 0x0258,   0x92 => 0x0258,   0x93 => 0x0258,
            0x94 => 0x0258,   0x95 => 0x0258,   0x96 => 0x0258,   0x97 => 0x0258,
            0x98 => 0x0258,   0x99 => 0x0258,   0x9a => 0x0258,   0x9b => 0x0258,
            0x9c => 0x0258,   0x9d => 0x0258,   0x9e => 0x0258,   0x9f => 0x0258,
            0xa0 => 0x0258,   0xa1 => 0x0258,   0xa2 => 0x0258,   0xa3 => 0x0258,
            0xa4 => 0x0258,   0xa5 => 0x0258,   0xa6 => 0x0258,   0xa7 => 0x0258,
            0xa8 => 0x0258,   0xa9 => 0x0258,   0xaa => 0x0258,   0xab => 0x0258,
            0xac => 0x0258,   0xad => 0x0258,   0xae => 0x0258,   0xaf => 0x0258,
            0xb0 => 0x0258,   0xb1 => 0x0258,   0xb2 => 0x0258,   0xb3 => 0x0258,
            0xb4 => 0x0258,   0xb5 => 0x0258,   0xb6 => 0x0258,   0xb7 => 0x0258,
            0xb8 => 0x0258,   0xb9 => 0x0258,   0xba => 0x0258,   0xbb => 0x0258,
            0xbc => 0x0258,   0xbd => 0x0258,   0xbe => 0x0258,   0xbf => 0x0258,
            0xc0 => 0x0258,   0xc1 => 0x0258,   0xc2 => 0x0258,   0xc3 => 0x0258,
            0xc4 => 0x0258,   0xc5 => 0x0258,   0xc6 => 0x0258,   0xc7 => 0x0258,
            0xc8 => 0x0258,   0xc9 => 0x0258,   0xca => 0x0258,   0xcb => 0x0258,
            0xcc => 0x0258,   0xcd => 0x0258,   0xce => 0x0258,   0xcf => 0x0258,
            0xd0 => 0x0258,   0xd1 => 0x0258,   0xd2 => 0x0258,   0xd3 => 0x0258,
            0xd4 => 0x0258,   0xd5 => 0x0258,   0xd6 => 0x0258,   0xd7 => 0x0258,
            0xd8 => 0x0258,   0xd9 => 0x0258,   0xda => 0x0258,   0xdb => 0x0258,
            0xdc => 0x0258,   0xdd => 0x0258,   0xde => 0x0258,   0xdf => 0x0258,
            0xe0 => 0x0258,   0xe1 => 0x0258,   0xe2 => 0x0258,   0xe3 => 0x0258,
            0xe4 => 0x0258,   0xe5 => 0x0258,   0xe6 => 0x0258,   0xe7 => 0x0258,
            0xe8 => 0x0258,   0xe9 => 0x0258,   0xea => 0x0258,   0xeb => 0x0258,
            0xec => 0x0258,   0xed => 0x0258,   0xee => 0x0258,   0xef => 0x0258,
            0xf0 => 0x0258,   0xf1 => 0x0258,   0xf2 => 0x0258,   0xf3 => 0x0258,
            0xf4 => 0x0258,   0xf5 => 0x0258,   0xf6 => 0x0258,   0xf7 => 0x0258,
            0xf8 => 0x0258,   0xf9 => 0x0258,   0xfa => 0x0258,   0xfb => 0x0258,
            0xfc => 0x0258,   0xfd => 0x0258,   0xfe => 0x0258,   0xff => 0x0258,
          0x0100 => 0x0258, 0x0101 => 0x0258, 0x0102 => 0x0258, 0x0103 => 0x0258,
          0x0104 => 0x0258, 0x0105 => 0x0258, 0x0106 => 0x0258, 0x0107 => 0x0258,
          0x0108 => 0x0258, 0x0109 => 0x0258, 0x010a => 0x0258, 0x010b => 0x0258,
          0x010c => 0x0258, 0x010d => 0x0258, 0x010e => 0x0258, 0x010f => 0x0258,
          0x0110 => 0x0258, 0x0111 => 0x0258, 0x0112 => 0x0258, 0x0113 => 0x0258,
          0x0114 => 0x0258, 0x0115 => 0x0258, 0x0116 => 0x0258, 0x0117 => 0x0258,
          0x0118 => 0x0258, 0x0119 => 0x0258, 0x011a => 0x0258, 0x011b => 0x0258,
          0x011c => 0x0258, 0x011d => 0x0258, 0x011e => 0x0258, 0x011f => 0x0258,
          0x0120 => 0x0258, 0x0121 => 0x0258, 0x0122 => 0x0258, 0x0123 => 0x0258,
          0x0124 => 0x0258, 0x0125 => 0x0258, 0x0126 => 0x0258, 0x0127 => 0x0258,
          0x0128 => 0x0258, 0x0129 => 0x0258, 0x012a => 0x0258, 0x012b => 0x0258,
          0x012c => 0x0258, 0x012d => 0x0258, 0x012e => 0x0258, 0x012f => 0x0258,
          0x0130 => 0x0258, 0x0131 => 0x0258, 0x0132 => 0x0258, 0x0133 => 0x0258,
          0x0134 => 0x0258, 0x0135 => 0x0258, 0x0136 => 0x0258, 0x0137 => 0x0258,
          0x0138 => 0x0258, 0x0139 => 0x0258, 0x013a => 0x0258, 0x013b => 0x0258,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Courier-BoldOblique');
    }

}
Pdf/Resource/Font/Simple/Standard/TimesItalic.php000066600000045633151256604610015710 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Times-Italic.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_TimesItalic extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x33\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x37\x00"
          . "\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00\x20\x00\x53\x00"
          . "\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00\x20\x00\x49\x00"
          . "\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00\x72\x00\x61\x00"
          . "\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00\x41\x00\x6c\x00"
          . "\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00\x74\x00\x73\x00"
          . "\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00\x76\x00\x65\x00"
          . "\x64\x00\x2e\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x20\x00"
          . "\x69\x00\x73\x00\x20\x00\x61\x00\x20\x00\x74\x00\x72\x00\x61\x00"
          . "\x64\x00\x65\x00\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00"
          . "\x66\x00\x20\x00\x4c\x00\x69\x00\x6e\x00\x6f\x00\x74\x00\x79\x00"
          . "\x70\x00\x65\x00\x2d\x00\x48\x00\x65\x00\x6c\x00\x6c\x00\x20\x00"
          . "\x41\x00\x47\x00\x20\x00\x61\x00\x6e\x00\x64\x00\x2f\x00\x6f\x00"
          . "\x72\x00\x20\x00\x69\x00\x74\x00\x73\x00\x20\x00\x73\x00\x75\x00"
          . "\x62\x00\x73\x00\x69\x00\x64\x00\x69\x00\x61\x00\x72\x00\x69\x00"
          . "\x65\x00\x73\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x36\x00\x37";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x2d\x00\x49\x00\x74\x00"
          . "\x61\x00\x6c\x00\x69\x00\x63\x00\x20\x00\x4d\x00\x65\x00\x64\x00"
          . "\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x2d\x00\x49\x00\x74\x00"
          . "\x61\x00\x6c\x00\x69\x00\x63";

        $this->_isBold = false;
        $this->_isItalic = true;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 683;
        $this->_descent = -217;
        $this->_lineGap = 300;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 =>   0xfa,   0x02 => 0x014d,   0x03 => 0x01a4,
            0x04 => 0x01f4,   0x05 => 0x01f4,   0x06 => 0x0341,   0x07 => 0x030a,
            0x08 => 0x014d,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x01f4,
            0x0c => 0x02a3,   0x0d =>   0xfa,   0x0e => 0x014d,   0x0f =>   0xfa,
            0x10 => 0x0116,   0x11 => 0x01f4,   0x12 => 0x01f4,   0x13 => 0x01f4,
            0x14 => 0x01f4,   0x15 => 0x01f4,   0x16 => 0x01f4,   0x17 => 0x01f4,
            0x18 => 0x01f4,   0x19 => 0x01f4,   0x1a => 0x01f4,   0x1b => 0x014d,
            0x1c => 0x014d,   0x1d => 0x02a3,   0x1e => 0x02a3,   0x1f => 0x02a3,
            0x20 => 0x01f4,   0x21 => 0x0398,   0x22 => 0x0263,   0x23 => 0x0263,
            0x24 => 0x029b,   0x25 => 0x02d2,   0x26 => 0x0263,   0x27 => 0x0263,
            0x28 => 0x02d2,   0x29 => 0x02d2,   0x2a => 0x014d,   0x2b => 0x01bc,
            0x2c => 0x029b,   0x2d => 0x022c,   0x2e => 0x0341,   0x2f => 0x029b,
            0x30 => 0x02d2,   0x31 => 0x0263,   0x32 => 0x02d2,   0x33 => 0x0263,
            0x34 => 0x01f4,   0x35 => 0x022c,   0x36 => 0x02d2,   0x37 => 0x0263,
            0x38 => 0x0341,   0x39 => 0x0263,   0x3a => 0x022c,   0x3b => 0x022c,
            0x3c => 0x0185,   0x3d => 0x0116,   0x3e => 0x0185,   0x3f => 0x01a6,
            0x40 => 0x01f4,   0x41 => 0x014d,   0x42 => 0x01f4,   0x43 => 0x01f4,
            0x44 => 0x01bc,   0x45 => 0x01f4,   0x46 => 0x01bc,   0x47 => 0x0116,
            0x48 => 0x01f4,   0x49 => 0x01f4,   0x4a => 0x0116,   0x4b => 0x0116,
            0x4c => 0x01bc,   0x4d => 0x0116,   0x4e => 0x02d2,   0x4f => 0x01f4,
            0x50 => 0x01f4,   0x51 => 0x01f4,   0x52 => 0x01f4,   0x53 => 0x0185,
            0x54 => 0x0185,   0x55 => 0x0116,   0x56 => 0x01f4,   0x57 => 0x01bc,
            0x58 => 0x029b,   0x59 => 0x01bc,   0x5a => 0x01bc,   0x5b => 0x0185,
            0x5c => 0x0190,   0x5d => 0x0113,   0x5e => 0x0190,   0x5f => 0x021d,
            0x60 => 0x0185,   0x61 => 0x01f4,   0x62 => 0x01f4,   0x63 =>   0xa7,
            0x64 => 0x01f4,   0x65 => 0x01f4,   0x66 => 0x01f4,   0x67 => 0x01f4,
            0x68 =>   0xd6,   0x69 => 0x022c,   0x6a => 0x01f4,   0x6b => 0x014d,
            0x6c => 0x014d,   0x6d => 0x01f4,   0x6e => 0x01f4,   0x6f => 0x01f4,
            0x70 => 0x01f4,   0x71 => 0x01f4,   0x72 =>   0xfa,   0x73 => 0x020b,
            0x74 => 0x015e,   0x75 => 0x014d,   0x76 => 0x022c,   0x77 => 0x022c,
            0x78 => 0x01f4,   0x79 => 0x0379,   0x7a => 0x03e8,   0x7b => 0x01f4,
            0x7c => 0x014d,   0x7d => 0x014d,   0x7e => 0x014d,   0x7f => 0x014d,
            0x80 => 0x014d,   0x81 => 0x014d,   0x82 => 0x014d,   0x83 => 0x014d,
            0x84 => 0x014d,   0x85 => 0x014d,   0x86 => 0x014d,   0x87 => 0x014d,
            0x88 => 0x014d,   0x89 => 0x0379,   0x8a => 0x0379,   0x8b => 0x0114,
            0x8c => 0x022c,   0x8d => 0x02d2,   0x8e => 0x03b0,   0x8f => 0x0136,
            0x90 => 0x029b,   0x91 => 0x0116,   0x92 => 0x0116,   0x93 => 0x01f4,
            0x94 => 0x029b,   0x95 => 0x01f4,   0x96 => 0x014d,   0x97 => 0x01bc,
            0x98 => 0x01f4,   0x99 => 0x01f4,   0x9a => 0x01bc,   0x9b => 0x022c,
            0x9c => 0x02a3,   0x9d => 0x022c,   0x9e => 0x0263,   0x9f => 0x01f4,
            0xa0 => 0x02d2,   0xa1 => 0x01bc,   0xa2 => 0x0185,   0xa3 => 0x01bc,
            0xa4 => 0x02d2,   0xa5 => 0x02d2,   0xa6 => 0x01f4,   0xa7 => 0x02d2,
            0xa8 => 0x01f4,   0xa9 => 0x0263,   0xaa => 0x02d2,   0xab =>   0xfa,
            0xac => 0x02f8,   0xad => 0x0263,   0xae => 0x01bc,   0xaf => 0x01f4,
            0xb0 => 0x029b,   0xb1 => 0x0116,   0xb2 => 0x01f4,   0xb3 => 0x022c,
            0xb4 => 0x029b,   0xb5 => 0x01f4,   0xb6 => 0x0263,   0xb7 => 0x0185,
            0xb8 => 0x0185,   0xb9 => 0x0116,   0xba => 0x01d7,   0xbb => 0x0263,
            0xbc => 0x02d2,   0xbd => 0x01f4,   0xbe => 0x01f4,   0xbf => 0x0263,
            0xc0 => 0x0185,   0xc1 => 0x01bc,   0xc2 => 0x022c,   0xc3 => 0x0263,
            0xc4 => 0x02d2,   0xc5 => 0x0263,   0xc6 => 0x01f4,   0xc7 => 0x0220,
            0xc8 => 0x02d2,   0xc9 => 0x01f4,   0xca => 0x012c,   0xcb => 0x02d2,
            0xcc => 0x0263,   0xcd => 0x0263,   0xce => 0x02a3,   0xcf => 0x01f4,
            0xd0 => 0x022c,   0xd1 => 0x01dc,   0xd2 => 0x01bc,   0xd3 => 0x029b,
            0xd4 => 0x0116,   0xd5 => 0x0263,   0xd6 => 0x01f4,   0xd7 => 0x01bc,
            0xd8 => 0x01bc,   0xd9 => 0x01f4,   0xda => 0x01f4,   0xdb => 0x029b,
            0xdc => 0x014d,   0xdd => 0x02a3,   0xde => 0x0113,   0xdf => 0x02f8,
            0xe0 => 0x02d2,   0xe1 => 0x014d,   0xe2 => 0x0258,   0xe3 => 0x0263,
            0xe4 => 0x0185,   0xe5 => 0x01f4,   0xe6 => 0x022c,   0xe7 => 0x022c,
            0xe8 => 0x0225,   0xe9 => 0x02d2,   0xea => 0x029b,   0xeb => 0x0116,
            0xec => 0x012c,   0xed => 0x01bc,   0xee => 0x02d2,   0xef => 0x0263,
            0xf0 => 0x0263,   0xf1 => 0x01bc,   0xf2 => 0x0185,   0xf3 => 0x0116,
            0xf4 => 0x02d2,   0xf5 => 0x01f4,   0xf6 => 0x01f4,   0xf7 => 0x0185,
            0xf8 => 0x0116,   0xf9 => 0x02d2,   0xfa => 0x02d2,   0xfb => 0x0264,
            0xfc => 0x01f4,   0xfd => 0x012c,   0xfe => 0x02d2,   0xff => 0x01f4,
          0x0100 => 0x0116, 0x0101 => 0x01f4, 0x0102 => 0x0263, 0x0103 => 0x01f4,
          0x0104 => 0x02ee, 0x0105 => 0x01f4, 0x0106 => 0x012c, 0x0107 => 0x029b,
          0x0108 => 0x022c, 0x0109 => 0x03d4, 0x010a => 0x01bc, 0x010b => 0x014d,
          0x010c => 0x014d, 0x010d => 0x0263, 0x010e => 0x02ee, 0x010f => 0x0225,
          0x0110 => 0x01f4, 0x0111 => 0x01f4, 0x0112 => 0x02d2, 0x0113 => 0x0263,
          0x0114 => 0x01bc, 0x0115 => 0x01f4, 0x0116 => 0x02ee, 0x0117 => 0x01f4,
          0x0118 => 0x01f4, 0x0119 => 0x02d2, 0x011a => 0x0190, 0x011b => 0x01f4,
          0x011c => 0x029b, 0x011d => 0x01f4, 0x011e => 0x01c5, 0x011f => 0x02d2,
          0x0120 => 0x0185, 0x0121 => 0x029b, 0x0122 => 0x01f4, 0x0123 => 0x0263,
          0x0124 => 0x022c, 0x0125 => 0x0263, 0x0126 => 0x0263, 0x0127 => 0x0263,
          0x0128 => 0x02d2, 0x0129 => 0x0185, 0x012a => 0x0263, 0x012b => 0x014d,
          0x012c => 0x01bc, 0x012d => 0x02a3, 0x012e => 0x014d, 0x012f => 0x01f4,
          0x0130 => 0x0116, 0x0131 => 0x02a3, 0x0132 => 0x01f4, 0x0133 => 0x01f4,
          0x0134 => 0x0225, 0x0135 => 0x01f4, 0x0136 => 0x01f4, 0x0137 => 0x0185,
          0x0138 => 0x01f4, 0x0139 => 0x012c, 0x013a => 0x0116, 0x013b => 0x01f4,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Times-Italic');
    }

}
Pdf/Resource/Font/Simple/Standard/CourierOblique.php000066600000044533151256604610016430 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Courier-Oblique.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_CourierOblique extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x39\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x30\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x31\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x32\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x33\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x37\x00"
          . "\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00\x20\x00\x53\x00"
          . "\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00\x20\x00\x49\x00"
          . "\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00\x72\x00\x61\x00"
          . "\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00\x41\x00\x6c\x00"
          . "\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00\x74\x00\x73\x00"
          . "\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00\x76\x00\x65\x00"
          . "\x64\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x35\x00\x31";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72\x00\x2d\x00"
          . "\x4f\x00\x62\x00\x6c\x00\x69\x00\x71\x00\x75\x00\x65\x00\x20\x00"
          . "\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x33\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72\x00\x2d\x00"
          . "\x4f\x00\x62\x00\x6c\x00\x69\x00\x71\x00\x75\x00\x65";

        $this->_isBold = false;
        $this->_isItalic = true;
        $this->_isMonospaced = true;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 629;
        $this->_descent = -157;
        $this->_lineGap = 414;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0258,   0x02 => 0x0258,   0x03 => 0x0258,
            0x04 => 0x0258,   0x05 => 0x0258,   0x06 => 0x0258,   0x07 => 0x0258,
            0x08 => 0x0258,   0x09 => 0x0258,   0x0a => 0x0258,   0x0b => 0x0258,
            0x0c => 0x0258,   0x0d => 0x0258,   0x0e => 0x0258,   0x0f => 0x0258,
            0x10 => 0x0258,   0x11 => 0x0258,   0x12 => 0x0258,   0x13 => 0x0258,
            0x14 => 0x0258,   0x15 => 0x0258,   0x16 => 0x0258,   0x17 => 0x0258,
            0x18 => 0x0258,   0x19 => 0x0258,   0x1a => 0x0258,   0x1b => 0x0258,
            0x1c => 0x0258,   0x1d => 0x0258,   0x1e => 0x0258,   0x1f => 0x0258,
            0x20 => 0x0258,   0x21 => 0x0258,   0x22 => 0x0258,   0x23 => 0x0258,
            0x24 => 0x0258,   0x25 => 0x0258,   0x26 => 0x0258,   0x27 => 0x0258,
            0x28 => 0x0258,   0x29 => 0x0258,   0x2a => 0x0258,   0x2b => 0x0258,
            0x2c => 0x0258,   0x2d => 0x0258,   0x2e => 0x0258,   0x2f => 0x0258,
            0x30 => 0x0258,   0x31 => 0x0258,   0x32 => 0x0258,   0x33 => 0x0258,
            0x34 => 0x0258,   0x35 => 0x0258,   0x36 => 0x0258,   0x37 => 0x0258,
            0x38 => 0x0258,   0x39 => 0x0258,   0x3a => 0x0258,   0x3b => 0x0258,
            0x3c => 0x0258,   0x3d => 0x0258,   0x3e => 0x0258,   0x3f => 0x0258,
            0x40 => 0x0258,   0x41 => 0x0258,   0x42 => 0x0258,   0x43 => 0x0258,
            0x44 => 0x0258,   0x45 => 0x0258,   0x46 => 0x0258,   0x47 => 0x0258,
            0x48 => 0x0258,   0x49 => 0x0258,   0x4a => 0x0258,   0x4b => 0x0258,
            0x4c => 0x0258,   0x4d => 0x0258,   0x4e => 0x0258,   0x4f => 0x0258,
            0x50 => 0x0258,   0x51 => 0x0258,   0x52 => 0x0258,   0x53 => 0x0258,
            0x54 => 0x0258,   0x55 => 0x0258,   0x56 => 0x0258,   0x57 => 0x0258,
            0x58 => 0x0258,   0x59 => 0x0258,   0x5a => 0x0258,   0x5b => 0x0258,
            0x5c => 0x0258,   0x5d => 0x0258,   0x5e => 0x0258,   0x5f => 0x0258,
            0x60 => 0x0258,   0x61 => 0x0258,   0x62 => 0x0258,   0x63 => 0x0258,
            0x64 => 0x0258,   0x65 => 0x0258,   0x66 => 0x0258,   0x67 => 0x0258,
            0x68 => 0x0258,   0x69 => 0x0258,   0x6a => 0x0258,   0x6b => 0x0258,
            0x6c => 0x0258,   0x6d => 0x0258,   0x6e => 0x0258,   0x6f => 0x0258,
            0x70 => 0x0258,   0x71 => 0x0258,   0x72 => 0x0258,   0x73 => 0x0258,
            0x74 => 0x0258,   0x75 => 0x0258,   0x76 => 0x0258,   0x77 => 0x0258,
            0x78 => 0x0258,   0x79 => 0x0258,   0x7a => 0x0258,   0x7b => 0x0258,
            0x7c => 0x0258,   0x7d => 0x0258,   0x7e => 0x0258,   0x7f => 0x0258,
            0x80 => 0x0258,   0x81 => 0x0258,   0x82 => 0x0258,   0x83 => 0x0258,
            0x84 => 0x0258,   0x85 => 0x0258,   0x86 => 0x0258,   0x87 => 0x0258,
            0x88 => 0x0258,   0x89 => 0x0258,   0x8a => 0x0258,   0x8b => 0x0258,
            0x8c => 0x0258,   0x8d => 0x0258,   0x8e => 0x0258,   0x8f => 0x0258,
            0x90 => 0x0258,   0x91 => 0x0258,   0x92 => 0x0258,   0x93 => 0x0258,
            0x94 => 0x0258,   0x95 => 0x0258,   0x96 => 0x0258,   0x97 => 0x0258,
            0x98 => 0x0258,   0x99 => 0x0258,   0x9a => 0x0258,   0x9b => 0x0258,
            0x9c => 0x0258,   0x9d => 0x0258,   0x9e => 0x0258,   0x9f => 0x0258,
            0xa0 => 0x0258,   0xa1 => 0x0258,   0xa2 => 0x0258,   0xa3 => 0x0258,
            0xa4 => 0x0258,   0xa5 => 0x0258,   0xa6 => 0x0258,   0xa7 => 0x0258,
            0xa8 => 0x0258,   0xa9 => 0x0258,   0xaa => 0x0258,   0xab => 0x0258,
            0xac => 0x0258,   0xad => 0x0258,   0xae => 0x0258,   0xaf => 0x0258,
            0xb0 => 0x0258,   0xb1 => 0x0258,   0xb2 => 0x0258,   0xb3 => 0x0258,
            0xb4 => 0x0258,   0xb5 => 0x0258,   0xb6 => 0x0258,   0xb7 => 0x0258,
            0xb8 => 0x0258,   0xb9 => 0x0258,   0xba => 0x0258,   0xbb => 0x0258,
            0xbc => 0x0258,   0xbd => 0x0258,   0xbe => 0x0258,   0xbf => 0x0258,
            0xc0 => 0x0258,   0xc1 => 0x0258,   0xc2 => 0x0258,   0xc3 => 0x0258,
            0xc4 => 0x0258,   0xc5 => 0x0258,   0xc6 => 0x0258,   0xc7 => 0x0258,
            0xc8 => 0x0258,   0xc9 => 0x0258,   0xca => 0x0258,   0xcb => 0x0258,
            0xcc => 0x0258,   0xcd => 0x0258,   0xce => 0x0258,   0xcf => 0x0258,
            0xd0 => 0x0258,   0xd1 => 0x0258,   0xd2 => 0x0258,   0xd3 => 0x0258,
            0xd4 => 0x0258,   0xd5 => 0x0258,   0xd6 => 0x0258,   0xd7 => 0x0258,
            0xd8 => 0x0258,   0xd9 => 0x0258,   0xda => 0x0258,   0xdb => 0x0258,
            0xdc => 0x0258,   0xdd => 0x0258,   0xde => 0x0258,   0xdf => 0x0258,
            0xe0 => 0x0258,   0xe1 => 0x0258,   0xe2 => 0x0258,   0xe3 => 0x0258,
            0xe4 => 0x0258,   0xe5 => 0x0258,   0xe6 => 0x0258,   0xe7 => 0x0258,
            0xe8 => 0x0258,   0xe9 => 0x0258,   0xea => 0x0258,   0xeb => 0x0258,
            0xec => 0x0258,   0xed => 0x0258,   0xee => 0x0258,   0xef => 0x0258,
            0xf0 => 0x0258,   0xf1 => 0x0258,   0xf2 => 0x0258,   0xf3 => 0x0258,
            0xf4 => 0x0258,   0xf5 => 0x0258,   0xf6 => 0x0258,   0xf7 => 0x0258,
            0xf8 => 0x0258,   0xf9 => 0x0258,   0xfa => 0x0258,   0xfb => 0x0258,
            0xfc => 0x0258,   0xfd => 0x0258,   0xfe => 0x0258,   0xff => 0x0258,
          0x0100 => 0x0258, 0x0101 => 0x0258, 0x0102 => 0x0258, 0x0103 => 0x0258,
          0x0104 => 0x0258, 0x0105 => 0x0258, 0x0106 => 0x0258, 0x0107 => 0x0258,
          0x0108 => 0x0258, 0x0109 => 0x0258, 0x010a => 0x0258, 0x010b => 0x0258,
          0x010c => 0x0258, 0x010d => 0x0258, 0x010e => 0x0258, 0x010f => 0x0258,
          0x0110 => 0x0258, 0x0111 => 0x0258, 0x0112 => 0x0258, 0x0113 => 0x0258,
          0x0114 => 0x0258, 0x0115 => 0x0258, 0x0116 => 0x0258, 0x0117 => 0x0258,
          0x0118 => 0x0258, 0x0119 => 0x0258, 0x011a => 0x0258, 0x011b => 0x0258,
          0x011c => 0x0258, 0x011d => 0x0258, 0x011e => 0x0258, 0x011f => 0x0258,
          0x0120 => 0x0258, 0x0121 => 0x0258, 0x0122 => 0x0258, 0x0123 => 0x0258,
          0x0124 => 0x0258, 0x0125 => 0x0258, 0x0126 => 0x0258, 0x0127 => 0x0258,
          0x0128 => 0x0258, 0x0129 => 0x0258, 0x012a => 0x0258, 0x012b => 0x0258,
          0x012c => 0x0258, 0x012d => 0x0258, 0x012e => 0x0258, 0x012f => 0x0258,
          0x0130 => 0x0258, 0x0131 => 0x0258, 0x0132 => 0x0258, 0x0133 => 0x0258,
          0x0134 => 0x0258, 0x0135 => 0x0258, 0x0136 => 0x0258, 0x0137 => 0x0258,
          0x0138 => 0x0258, 0x0139 => 0x0258, 0x013a => 0x0258, 0x013b => 0x0258,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Courier-Oblique');
    }

}
Pdf/Resource/Font/Simple/Standard/HelveticaOblique.php000066600000046052151256604610016722 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Helvetica-Oblique.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_HelveticaOblique extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x37\x00\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00"
          . "\x20\x00\x53\x00\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00"
          . "\x20\x00\x49\x00\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00"
          . "\x72\x00\x61\x00\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00"
          . "\x41\x00\x6c\x00\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x73\x00\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00"
          . "\x76\x00\x65\x00\x64\x00\x2e\x00\x48\x00\x65\x00\x6c\x00\x76\x00"
          . "\x65\x00\x74\x00\x69\x00\x63\x00\x61\x00\x20\x00\x69\x00\x73\x00"
          . "\x20\x00\x61\x00\x20\x00\x74\x00\x72\x00\x61\x00\x64\x00\x65\x00"
          . "\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00\x66\x00\x20\x00"
          . "\x4c\x00\x69\x00\x6e\x00\x6f\x00\x74\x00\x79\x00\x70\x00\x65\x00"
          . "\x2d\x00\x48\x00\x65\x00\x6c\x00\x6c\x00\x20\x00\x41\x00\x47\x00"
          . "\x20\x00\x61\x00\x6e\x00\x64\x00\x2f\x00\x6f\x00\x72\x00\x20\x00"
          . "\x69\x00\x74\x00\x73\x00\x20\x00\x73\x00\x75\x00\x62\x00\x73\x00"
          . "\x69\x00\x64\x00\x69\x00\x61\x00\x72\x00\x69\x00\x65\x00\x73\x00"
          . "\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x35\x00\x35";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61\x00\x2d\x00\x4f\x00\x62\x00\x6c\x00\x69\x00\x71\x00\x75\x00"
          . "\x65\x00\x20\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61\x00\x2d\x00\x4f\x00\x62\x00\x6c\x00\x69\x00\x71\x00\x75\x00"
          . "\x65";

        $this->_isBold = false;
        $this->_isItalic = true;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 718;
        $this->_descent = -207;
        $this->_lineGap = 275;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0116,   0x02 => 0x0116,   0x03 => 0x0163,
            0x04 => 0x022c,   0x05 => 0x022c,   0x06 => 0x0379,   0x07 => 0x029b,
            0x08 =>   0xde,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x0185,
            0x0c => 0x0248,   0x0d => 0x0116,   0x0e => 0x014d,   0x0f => 0x0116,
            0x10 => 0x0116,   0x11 => 0x022c,   0x12 => 0x022c,   0x13 => 0x022c,
            0x14 => 0x022c,   0x15 => 0x022c,   0x16 => 0x022c,   0x17 => 0x022c,
            0x18 => 0x022c,   0x19 => 0x022c,   0x1a => 0x022c,   0x1b => 0x0116,
            0x1c => 0x0116,   0x1d => 0x0248,   0x1e => 0x0248,   0x1f => 0x0248,
            0x20 => 0x022c,   0x21 => 0x03f7,   0x22 => 0x029b,   0x23 => 0x029b,
            0x24 => 0x02d2,   0x25 => 0x02d2,   0x26 => 0x029b,   0x27 => 0x0263,
            0x28 => 0x030a,   0x29 => 0x02d2,   0x2a => 0x0116,   0x2b => 0x01f4,
            0x2c => 0x029b,   0x2d => 0x022c,   0x2e => 0x0341,   0x2f => 0x02d2,
            0x30 => 0x030a,   0x31 => 0x029b,   0x32 => 0x030a,   0x33 => 0x02d2,
            0x34 => 0x029b,   0x35 => 0x0263,   0x36 => 0x02d2,   0x37 => 0x029b,
            0x38 => 0x03b0,   0x39 => 0x029b,   0x3a => 0x029b,   0x3b => 0x0263,
            0x3c => 0x0116,   0x3d => 0x0116,   0x3e => 0x0116,   0x3f => 0x01d5,
            0x40 => 0x022c,   0x41 =>   0xde,   0x42 => 0x022c,   0x43 => 0x022c,
            0x44 => 0x01f4,   0x45 => 0x022c,   0x46 => 0x022c,   0x47 => 0x0116,
            0x48 => 0x022c,   0x49 => 0x022c,   0x4a =>   0xde,   0x4b =>   0xde,
            0x4c => 0x01f4,   0x4d =>   0xde,   0x4e => 0x0341,   0x4f => 0x022c,
            0x50 => 0x022c,   0x51 => 0x022c,   0x52 => 0x022c,   0x53 => 0x014d,
            0x54 => 0x01f4,   0x55 => 0x0116,   0x56 => 0x022c,   0x57 => 0x01f4,
            0x58 => 0x02d2,   0x59 => 0x01f4,   0x5a => 0x01f4,   0x5b => 0x01f4,
            0x5c => 0x014e,   0x5d => 0x0104,   0x5e => 0x014e,   0x5f => 0x0248,
            0x60 => 0x014d,   0x61 => 0x022c,   0x62 => 0x022c,   0x63 =>   0xa7,
            0x64 => 0x022c,   0x65 => 0x022c,   0x66 => 0x022c,   0x67 => 0x022c,
            0x68 =>   0xbf,   0x69 => 0x014d,   0x6a => 0x022c,   0x6b => 0x014d,
            0x6c => 0x014d,   0x6d => 0x01f4,   0x6e => 0x01f4,   0x6f => 0x022c,
            0x70 => 0x022c,   0x71 => 0x022c,   0x72 => 0x0116,   0x73 => 0x0219,
            0x74 => 0x015e,   0x75 =>   0xde,   0x76 => 0x014d,   0x77 => 0x014d,
            0x78 => 0x022c,   0x79 => 0x03e8,   0x7a => 0x03e8,   0x7b => 0x0263,
            0x7c => 0x014d,   0x7d => 0x014d,   0x7e => 0x014d,   0x7f => 0x014d,
            0x80 => 0x014d,   0x81 => 0x014d,   0x82 => 0x014d,   0x83 => 0x014d,
            0x84 => 0x014d,   0x85 => 0x014d,   0x86 => 0x014d,   0x87 => 0x014d,
            0x88 => 0x014d,   0x89 => 0x03e8,   0x8a => 0x03e8,   0x8b => 0x0172,
            0x8c => 0x022c,   0x8d => 0x030a,   0x8e => 0x03e8,   0x8f => 0x016d,
            0x90 => 0x0379,   0x91 => 0x0116,   0x92 =>   0xde,   0x93 => 0x0263,
            0x94 => 0x03b0,   0x95 => 0x0263,   0x96 => 0x0116,   0x97 => 0x022c,
            0x98 => 0x022c,   0x99 => 0x022c,   0x9a => 0x022c,   0x9b => 0x029b,
            0x9c => 0x0248,   0x9d => 0x029b,   0x9e => 0x029b,   0x9f => 0x022c,
            0xa0 => 0x02d2,   0xa1 => 0x01f4,   0xa2 => 0x01f4,   0xa3 => 0x022c,
            0xa4 => 0x02d2,   0xa5 => 0x02d2,   0xa6 => 0x022c,   0xa7 => 0x02d2,
            0xa8 => 0x022c,   0xa9 => 0x029b,   0xaa => 0x02d2,   0xab =>   0xfa,
            0xac => 0x02e1,   0xad => 0x029b,   0xae => 0x01f4,   0xaf => 0x022c,
            0xb0 => 0x02d2,   0xb1 =>   0xde,   0xb2 => 0x022c,   0xb3 => 0x0263,
            0xb4 => 0x02d2,   0xb5 => 0x022c,   0xb6 => 0x029b,   0xb7 => 0x01f4,
            0xb8 => 0x01f4,   0xb9 => 0x0116,   0xba => 0x01d7,   0xbb => 0x02d2,
            0xbc => 0x030a,   0xbd => 0x022c,   0xbe => 0x022c,   0xbf => 0x029b,
            0xc0 => 0x014d,   0xc1 => 0x01f4,   0xc2 => 0x0263,   0xc3 => 0x029b,
            0xc4 => 0x030a,   0xc5 => 0x02d2,   0xc6 => 0x029b,   0xc7 => 0x0283,
            0xc8 => 0x02d2,   0xc9 => 0x022c,   0xca => 0x014d,   0xcb => 0x030a,
            0xcc => 0x029b,   0xcd => 0x029b,   0xce => 0x0248,   0xcf => 0x022c,
            0xd0 => 0x0263,   0xd1 => 0x01dc,   0xd2 => 0x01f4,   0xd3 => 0x02d2,
            0xd4 => 0x0116,   0xd5 => 0x029b,   0xd6 => 0x022c,   0xd7 => 0x022c,
            0xd8 => 0x01f4,   0xd9 => 0x022c,   0xda => 0x022c,   0xdb => 0x02d2,
            0xdc => 0x0116,   0xdd => 0x0248,   0xde => 0x0104,   0xdf => 0x02e1,
            0xe0 => 0x030a,   0xe1 => 0x0116,   0xe2 => 0x0258,   0xe3 => 0x029b,
            0xe4 => 0x014d,   0xe5 => 0x022c,   0xe6 => 0x0263,   0xe7 => 0x0263,
            0xe8 => 0x0225,   0xe9 => 0x02d2,   0xea => 0x02d2,   0xeb =>   0xde,
            0xec => 0x013d,   0xed => 0x022c,   0xee => 0x02d2,   0xef => 0x029b,
            0xf0 => 0x029b,   0xf1 => 0x022c,   0xf2 => 0x01f4,   0xf3 =>   0xde,
            0xf4 => 0x030a,   0xf5 => 0x022c,   0xf6 => 0x022c,   0xf7 => 0x01f4,
            0xf8 => 0x0116,   0xf9 => 0x030a,   0xfa => 0x02d2,   0xfb => 0x0264,
            0xfc => 0x022c,   0xfd => 0x014d,   0xfe => 0x030a,   0xff => 0x022c,
          0x0100 => 0x0116, 0x0101 => 0x022c, 0x0102 => 0x029b, 0x0103 => 0x022c,
          0x0104 => 0x0342, 0x0105 => 0x029b, 0x0106 => 0x012b, 0x0107 => 0x029b,
          0x0108 => 0x022c, 0x0109 => 0x03e8, 0x010a => 0x022c, 0x010b => 0x0116,
          0x010c => 0x0116, 0x010d => 0x022c, 0x010e => 0x0342, 0x010f => 0x0225,
          0x0110 => 0x022c, 0x0111 => 0x022c, 0x0112 => 0x02d2, 0x0113 => 0x029b,
          0x0114 => 0x022c, 0x0115 => 0x022c, 0x0116 => 0x0342, 0x0117 => 0x029b,
          0x0118 => 0x029b, 0x0119 => 0x030a, 0x011a => 0x0190, 0x011b => 0x022c,
          0x011c => 0x02d2, 0x011d => 0x022c, 0x011e => 0x01c5, 0x011f => 0x02d2,
          0x0120 => 0x014d, 0x0121 => 0x02d2, 0x0122 => 0x022c, 0x0123 => 0x02d2,
          0x0124 => 0x022c, 0x0125 => 0x029b, 0x0126 => 0x029b, 0x0127 => 0x029b,
          0x0128 => 0x030a, 0x0129 => 0x01f4, 0x012a => 0x029b, 0x012b => 0x0116,
          0x012c => 0x01f4, 0x012d => 0x0248, 0x012e => 0x0116, 0x012f => 0x022c,
          0x0130 => 0x0116, 0x0131 => 0x0248, 0x0132 => 0x022c, 0x0133 => 0x022c,
          0x0134 => 0x0225, 0x0135 => 0x022c, 0x0136 => 0x022c, 0x0137 => 0x01f4,
          0x0138 => 0x022c, 0x0139 => 0x014d, 0x013a => 0x0116, 0x013b => 0x022c,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Helvetica-Oblique');
    }

}
Pdf/Resource/Font/Simple/Standard/TimesBoldItalic.php000066600000045706151256604610016512 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Times-BoldItalic.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_TimesBoldItalic extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x33\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x37\x00"
          . "\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00\x20\x00\x53\x00"
          . "\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00\x20\x00\x49\x00"
          . "\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00\x72\x00\x61\x00"
          . "\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00\x41\x00\x6c\x00"
          . "\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00\x74\x00\x73\x00"
          . "\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00\x76\x00\x65\x00"
          . "\x64\x00\x2e\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x20\x00"
          . "\x69\x00\x73\x00\x20\x00\x61\x00\x20\x00\x74\x00\x72\x00\x61\x00"
          . "\x64\x00\x65\x00\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00"
          . "\x66\x00\x20\x00\x4c\x00\x69\x00\x6e\x00\x6f\x00\x74\x00\x79\x00"
          . "\x70\x00\x65\x00\x2d\x00\x48\x00\x65\x00\x6c\x00\x6c\x00\x20\x00"
          . "\x41\x00\x47\x00\x20\x00\x61\x00\x6e\x00\x64\x00\x2f\x00\x6f\x00"
          . "\x72\x00\x20\x00\x69\x00\x74\x00\x73\x00\x20\x00\x73\x00\x75\x00"
          . "\x62\x00\x73\x00\x69\x00\x64\x00\x69\x00\x61\x00\x72\x00\x69\x00"
          . "\x65\x00\x73\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x36\x00\x36";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x2d\x00\x42\x00\x6f\x00"
          . "\x6c\x00\x64\x00\x49\x00\x74\x00\x61\x00\x6c\x00\x69\x00\x63\x00"
          . "\x20\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x2d\x00\x42\x00\x6f\x00"
          . "\x6c\x00\x64\x00\x49\x00\x74\x00\x61\x00\x6c\x00\x69\x00\x63";

        $this->_isBold = true;
        $this->_isItalic = true;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 683;
        $this->_descent = -217;
        $this->_lineGap = 300;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 =>   0xfa,   0x02 => 0x0185,   0x03 => 0x022b,
            0x04 => 0x01f4,   0x05 => 0x01f4,   0x06 => 0x0341,   0x07 => 0x030a,
            0x08 => 0x014d,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x01f4,
            0x0c => 0x023a,   0x0d =>   0xfa,   0x0e => 0x014d,   0x0f =>   0xfa,
            0x10 => 0x0116,   0x11 => 0x01f4,   0x12 => 0x01f4,   0x13 => 0x01f4,
            0x14 => 0x01f4,   0x15 => 0x01f4,   0x16 => 0x01f4,   0x17 => 0x01f4,
            0x18 => 0x01f4,   0x19 => 0x01f4,   0x1a => 0x01f4,   0x1b => 0x014d,
            0x1c => 0x014d,   0x1d => 0x023a,   0x1e => 0x023a,   0x1f => 0x023a,
            0x20 => 0x01f4,   0x21 => 0x0340,   0x22 => 0x029b,   0x23 => 0x029b,
            0x24 => 0x029b,   0x25 => 0x02d2,   0x26 => 0x029b,   0x27 => 0x029b,
            0x28 => 0x02d2,   0x29 => 0x030a,   0x2a => 0x0185,   0x2b => 0x01f4,
            0x2c => 0x029b,   0x2d => 0x0263,   0x2e => 0x0379,   0x2f => 0x02d2,
            0x30 => 0x02d2,   0x31 => 0x0263,   0x32 => 0x02d2,   0x33 => 0x029b,
            0x34 => 0x022c,   0x35 => 0x0263,   0x36 => 0x02d2,   0x37 => 0x029b,
            0x38 => 0x0379,   0x39 => 0x029b,   0x3a => 0x0263,   0x3b => 0x0263,
            0x3c => 0x014d,   0x3d => 0x0116,   0x3e => 0x014d,   0x3f => 0x023a,
            0x40 => 0x01f4,   0x41 => 0x014d,   0x42 => 0x01f4,   0x43 => 0x01f4,
            0x44 => 0x01bc,   0x45 => 0x01f4,   0x46 => 0x01bc,   0x47 => 0x014d,
            0x48 => 0x01f4,   0x49 => 0x022c,   0x4a => 0x0116,   0x4b => 0x0116,
            0x4c => 0x01f4,   0x4d => 0x0116,   0x4e => 0x030a,   0x4f => 0x022c,
            0x50 => 0x01f4,   0x51 => 0x01f4,   0x52 => 0x01f4,   0x53 => 0x0185,
            0x54 => 0x0185,   0x55 => 0x0116,   0x56 => 0x022c,   0x57 => 0x01bc,
            0x58 => 0x029b,   0x59 => 0x01f4,   0x5a => 0x01bc,   0x5b => 0x0185,
            0x5c => 0x015c,   0x5d =>   0xdc,   0x5e => 0x015c,   0x5f => 0x023a,
            0x60 => 0x0185,   0x61 => 0x01f4,   0x62 => 0x01f4,   0x63 =>   0xa7,
            0x64 => 0x01f4,   0x65 => 0x01f4,   0x66 => 0x01f4,   0x67 => 0x01f4,
            0x68 => 0x0116,   0x69 => 0x01f4,   0x6a => 0x01f4,   0x6b => 0x014d,
            0x6c => 0x014d,   0x6d => 0x022c,   0x6e => 0x022c,   0x6f => 0x01f4,
            0x70 => 0x01f4,   0x71 => 0x01f4,   0x72 =>   0xfa,   0x73 => 0x01f4,
            0x74 => 0x015e,   0x75 => 0x014d,   0x76 => 0x01f4,   0x77 => 0x01f4,
            0x78 => 0x01f4,   0x79 => 0x03e8,   0x7a => 0x03e8,   0x7b => 0x01f4,
            0x7c => 0x014d,   0x7d => 0x014d,   0x7e => 0x014d,   0x7f => 0x014d,
            0x80 => 0x014d,   0x81 => 0x014d,   0x82 => 0x014d,   0x83 => 0x014d,
            0x84 => 0x014d,   0x85 => 0x014d,   0x86 => 0x014d,   0x87 => 0x014d,
            0x88 => 0x014d,   0x89 => 0x03e8,   0x8a => 0x03b0,   0x8b => 0x010a,
            0x8c => 0x0263,   0x8d => 0x02d2,   0x8e => 0x03b0,   0x8f => 0x012c,
            0x90 => 0x02d2,   0x91 => 0x0116,   0x92 => 0x0116,   0x93 => 0x01f4,
            0x94 => 0x02d2,   0x95 => 0x01f4,   0x96 => 0x0185,   0x97 => 0x01bc,
            0x98 => 0x01f4,   0x99 => 0x022c,   0x9a => 0x01bc,   0x9b => 0x0263,
            0x9c => 0x023a,   0x9d => 0x0263,   0x9e => 0x029b,   0x9f => 0x01f4,
            0xa0 => 0x02d2,   0xa1 => 0x01bc,   0xa2 => 0x0185,   0xa3 => 0x01bc,
            0xa4 => 0x02d2,   0xa5 => 0x02d2,   0xa6 => 0x01f4,   0xa7 => 0x02d2,
            0xa8 => 0x022c,   0xa9 => 0x029b,   0xaa => 0x02d2,   0xab =>   0xfa,
            0xac => 0x02eb,   0xad => 0x029b,   0xae => 0x01bc,   0xaf => 0x01f4,
            0xb0 => 0x02d2,   0xb1 => 0x0116,   0xb2 => 0x01f4,   0xb3 => 0x0263,
            0xb4 => 0x029b,   0xb5 => 0x01f4,   0xb6 => 0x029b,   0xb7 => 0x0185,
            0xb8 => 0x0185,   0xb9 => 0x0116,   0xba => 0x01ee,   0xbb => 0x029b,
            0xbc => 0x02d2,   0xbd => 0x022c,   0xbe => 0x01f4,   0xbf => 0x029b,
            0xc0 => 0x0185,   0xc1 => 0x01bc,   0xc2 => 0x0263,   0xc3 => 0x0263,
            0xc4 => 0x02d2,   0xc5 => 0x029b,   0xc6 => 0x022c,   0xc7 => 0x0260,
            0xc8 => 0x02d2,   0xc9 => 0x022c,   0xca => 0x012c,   0xcb => 0x02d2,
            0xcc => 0x029b,   0xcd => 0x029b,   0xce => 0x023a,   0xcf => 0x022c,
            0xd0 => 0x0263,   0xd1 => 0x01ee,   0xd2 => 0x01bc,   0xd3 => 0x02d2,
            0xd4 => 0x0116,   0xd5 => 0x029b,   0xd6 => 0x01f4,   0xd7 => 0x01bc,
            0xd8 => 0x01bc,   0xd9 => 0x022c,   0xda => 0x022c,   0xdb => 0x02d2,
            0xdc => 0x0185,   0xdd => 0x023a,   0xde =>   0xdc,   0xdf => 0x02eb,
            0xe0 => 0x02d2,   0xe1 => 0x0185,   0xe2 => 0x0258,   0xe3 => 0x029b,
            0xe4 => 0x0185,   0xe5 => 0x01f4,   0xe6 => 0x0263,   0xe7 => 0x0263,
            0xe8 => 0x0225,   0xe9 => 0x02d2,   0xea => 0x029b,   0xeb => 0x0116,
            0xec => 0x016e,   0xed => 0x01bc,   0xee => 0x02d2,   0xef => 0x029b,
            0xf0 => 0x029b,   0xf1 => 0x01bc,   0xf2 => 0x0185,   0xf3 => 0x0116,
            0xf4 => 0x02d2,   0xf5 => 0x01f4,   0xf6 => 0x01f4,   0xf7 => 0x0185,
            0xf8 => 0x0116,   0xf9 => 0x02d2,   0xfa => 0x02d2,   0xfb => 0x0264,
            0xfc => 0x01f4,   0xfd => 0x012c,   0xfe => 0x02d2,   0xff => 0x0240,
          0x0100 => 0x0116, 0x0101 => 0x01f4, 0x0102 => 0x029b, 0x0103 => 0x01f4,
          0x0104 => 0x02ee, 0x0105 => 0x022c, 0x0106 => 0x017e, 0x0107 => 0x029b,
          0x0108 => 0x0263, 0x0109 => 0x03e8, 0x010a => 0x01bc, 0x010b => 0x0185,
          0x010c => 0x0185, 0x010d => 0x0263, 0x010e => 0x02ee, 0x010f => 0x0225,
          0x0110 => 0x01f4, 0x0111 => 0x022c, 0x0112 => 0x02d2, 0x0113 => 0x029b,
          0x0114 => 0x01bc, 0x0115 => 0x01f4, 0x0116 => 0x02ee, 0x0117 => 0x022c,
          0x0118 => 0x022c, 0x0119 => 0x02d2, 0x011a => 0x0190, 0x011b => 0x01f4,
          0x011c => 0x029b, 0x011d => 0x022c, 0x011e => 0x0225, 0x011f => 0x02d2,
          0x0120 => 0x0185, 0x0121 => 0x02d2, 0x0122 => 0x01f4, 0x0123 => 0x029b,
          0x0124 => 0x0263, 0x0125 => 0x029b, 0x0126 => 0x029b, 0x0127 => 0x029b,
          0x0128 => 0x02d2, 0x0129 => 0x0185, 0x012a => 0x029b, 0x012b => 0x0185,
          0x012c => 0x01f4, 0x012d => 0x025e, 0x012e => 0x0185, 0x012f => 0x022c,
          0x0130 => 0x0116, 0x0131 => 0x025e, 0x0132 => 0x01f4, 0x0133 => 0x022c,
          0x0134 => 0x0225, 0x0135 => 0x01f4, 0x0136 => 0x01f4, 0x0137 => 0x0185,
          0x0138 => 0x022c, 0x0139 => 0x012c, 0x013a => 0x0116, 0x013b => 0x01f4,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Times-BoldItalic');
    }

}
Pdf/Resource/Font/Simple/Standard/Helvetica.php000066600000045564151256604610015410 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Helvetica.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_Helvetica extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x37\x00\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00"
          . "\x20\x00\x53\x00\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00"
          . "\x20\x00\x49\x00\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00"
          . "\x72\x00\x61\x00\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00"
          . "\x41\x00\x6c\x00\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x73\x00\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00"
          . "\x76\x00\x65\x00\x64\x00\x2e\x00\x48\x00\x65\x00\x6c\x00\x76\x00"
          . "\x65\x00\x74\x00\x69\x00\x63\x00\x61\x00\x20\x00\x69\x00\x73\x00"
          . "\x20\x00\x61\x00\x20\x00\x74\x00\x72\x00\x61\x00\x64\x00\x65\x00"
          . "\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00\x66\x00\x20\x00"
          . "\x4c\x00\x69\x00\x6e\x00\x6f\x00\x74\x00\x79\x00\x70\x00\x65\x00"
          . "\x2d\x00\x48\x00\x65\x00\x6c\x00\x6c\x00\x20\x00\x41\x00\x47\x00"
          . "\x20\x00\x61\x00\x6e\x00\x64\x00\x2f\x00\x6f\x00\x72\x00\x20\x00"
          . "\x69\x00\x74\x00\x73\x00\x20\x00\x73\x00\x75\x00\x62\x00\x73\x00"
          . "\x69\x00\x64\x00\x69\x00\x61\x00\x72\x00\x69\x00\x65\x00\x73\x00"
          . "\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x35\x00\x34";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61\x00\x20\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61";

        $this->_isBold = false;
        $this->_isItalic = false;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 718;
        $this->_descent = -207;
        $this->_lineGap = 275;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0116,   0x02 => 0x0116,   0x03 => 0x0163,
            0x04 => 0x022c,   0x05 => 0x022c,   0x06 => 0x0379,   0x07 => 0x029b,
            0x08 =>   0xde,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x0185,
            0x0c => 0x0248,   0x0d => 0x0116,   0x0e => 0x014d,   0x0f => 0x0116,
            0x10 => 0x0116,   0x11 => 0x022c,   0x12 => 0x022c,   0x13 => 0x022c,
            0x14 => 0x022c,   0x15 => 0x022c,   0x16 => 0x022c,   0x17 => 0x022c,
            0x18 => 0x022c,   0x19 => 0x022c,   0x1a => 0x022c,   0x1b => 0x0116,
            0x1c => 0x0116,   0x1d => 0x0248,   0x1e => 0x0248,   0x1f => 0x0248,
            0x20 => 0x022c,   0x21 => 0x03f7,   0x22 => 0x029b,   0x23 => 0x029b,
            0x24 => 0x02d2,   0x25 => 0x02d2,   0x26 => 0x029b,   0x27 => 0x0263,
            0x28 => 0x030a,   0x29 => 0x02d2,   0x2a => 0x0116,   0x2b => 0x01f4,
            0x2c => 0x029b,   0x2d => 0x022c,   0x2e => 0x0341,   0x2f => 0x02d2,
            0x30 => 0x030a,   0x31 => 0x029b,   0x32 => 0x030a,   0x33 => 0x02d2,
            0x34 => 0x029b,   0x35 => 0x0263,   0x36 => 0x02d2,   0x37 => 0x029b,
            0x38 => 0x03b0,   0x39 => 0x029b,   0x3a => 0x029b,   0x3b => 0x0263,
            0x3c => 0x0116,   0x3d => 0x0116,   0x3e => 0x0116,   0x3f => 0x01d5,
            0x40 => 0x022c,   0x41 =>   0xde,   0x42 => 0x022c,   0x43 => 0x022c,
            0x44 => 0x01f4,   0x45 => 0x022c,   0x46 => 0x022c,   0x47 => 0x0116,
            0x48 => 0x022c,   0x49 => 0x022c,   0x4a =>   0xde,   0x4b =>   0xde,
            0x4c => 0x01f4,   0x4d =>   0xde,   0x4e => 0x0341,   0x4f => 0x022c,
            0x50 => 0x022c,   0x51 => 0x022c,   0x52 => 0x022c,   0x53 => 0x014d,
            0x54 => 0x01f4,   0x55 => 0x0116,   0x56 => 0x022c,   0x57 => 0x01f4,
            0x58 => 0x02d2,   0x59 => 0x01f4,   0x5a => 0x01f4,   0x5b => 0x01f4,
            0x5c => 0x014e,   0x5d => 0x0104,   0x5e => 0x014e,   0x5f => 0x0248,
            0x60 => 0x014d,   0x61 => 0x022c,   0x62 => 0x022c,   0x63 =>   0xa7,
            0x64 => 0x022c,   0x65 => 0x022c,   0x66 => 0x022c,   0x67 => 0x022c,
            0x68 =>   0xbf,   0x69 => 0x014d,   0x6a => 0x022c,   0x6b => 0x014d,
            0x6c => 0x014d,   0x6d => 0x01f4,   0x6e => 0x01f4,   0x6f => 0x022c,
            0x70 => 0x022c,   0x71 => 0x022c,   0x72 => 0x0116,   0x73 => 0x0219,
            0x74 => 0x015e,   0x75 =>   0xde,   0x76 => 0x014d,   0x77 => 0x014d,
            0x78 => 0x022c,   0x79 => 0x03e8,   0x7a => 0x03e8,   0x7b => 0x0263,
            0x7c => 0x014d,   0x7d => 0x014d,   0x7e => 0x014d,   0x7f => 0x014d,
            0x80 => 0x014d,   0x81 => 0x014d,   0x82 => 0x014d,   0x83 => 0x014d,
            0x84 => 0x014d,   0x85 => 0x014d,   0x86 => 0x014d,   0x87 => 0x014d,
            0x88 => 0x014d,   0x89 => 0x03e8,   0x8a => 0x03e8,   0x8b => 0x0172,
            0x8c => 0x022c,   0x8d => 0x030a,   0x8e => 0x03e8,   0x8f => 0x016d,
            0x90 => 0x0379,   0x91 => 0x0116,   0x92 =>   0xde,   0x93 => 0x0263,
            0x94 => 0x03b0,   0x95 => 0x0263,   0x96 => 0x0116,   0x97 => 0x022c,
            0x98 => 0x022c,   0x99 => 0x022c,   0x9a => 0x022c,   0x9b => 0x029b,
            0x9c => 0x0248,   0x9d => 0x029b,   0x9e => 0x029b,   0x9f => 0x022c,
            0xa0 => 0x02d2,   0xa1 => 0x01f4,   0xa2 => 0x01f4,   0xa3 => 0x022c,
            0xa4 => 0x02d2,   0xa5 => 0x02d2,   0xa6 => 0x022c,   0xa7 => 0x02d2,
            0xa8 => 0x022c,   0xa9 => 0x029b,   0xaa => 0x02d2,   0xab =>   0xfa,
            0xac => 0x02e1,   0xad => 0x029b,   0xae => 0x01f4,   0xaf => 0x022c,
            0xb0 => 0x02d2,   0xb1 =>   0xde,   0xb2 => 0x022c,   0xb3 => 0x0263,
            0xb4 => 0x02d2,   0xb5 => 0x022c,   0xb6 => 0x029b,   0xb7 => 0x01f4,
            0xb8 => 0x01f4,   0xb9 => 0x0116,   0xba => 0x01d7,   0xbb => 0x02d2,
            0xbc => 0x030a,   0xbd => 0x022c,   0xbe => 0x022c,   0xbf => 0x029b,
            0xc0 => 0x014d,   0xc1 => 0x01f4,   0xc2 => 0x0263,   0xc3 => 0x029b,
            0xc4 => 0x030a,   0xc5 => 0x02d2,   0xc6 => 0x029b,   0xc7 => 0x0283,
            0xc8 => 0x02d2,   0xc9 => 0x022c,   0xca => 0x014d,   0xcb => 0x030a,
            0xcc => 0x029b,   0xcd => 0x029b,   0xce => 0x0248,   0xcf => 0x022c,
            0xd0 => 0x0263,   0xd1 => 0x01dc,   0xd2 => 0x01f4,   0xd3 => 0x02d2,
            0xd4 => 0x0116,   0xd5 => 0x029b,   0xd6 => 0x022c,   0xd7 => 0x022c,
            0xd8 => 0x01f4,   0xd9 => 0x022c,   0xda => 0x022c,   0xdb => 0x02d2,
            0xdc => 0x0116,   0xdd => 0x0248,   0xde => 0x0104,   0xdf => 0x02e1,
            0xe0 => 0x030a,   0xe1 => 0x0116,   0xe2 => 0x0258,   0xe3 => 0x029b,
            0xe4 => 0x014d,   0xe5 => 0x022c,   0xe6 => 0x0263,   0xe7 => 0x0263,
            0xe8 => 0x0225,   0xe9 => 0x02d2,   0xea => 0x02d2,   0xeb =>   0xde,
            0xec => 0x013d,   0xed => 0x022c,   0xee => 0x02d2,   0xef => 0x029b,
            0xf0 => 0x029b,   0xf1 => 0x022c,   0xf2 => 0x01f4,   0xf3 =>   0xde,
            0xf4 => 0x030a,   0xf5 => 0x022c,   0xf6 => 0x022c,   0xf7 => 0x01f4,
            0xf8 => 0x0116,   0xf9 => 0x030a,   0xfa => 0x02d2,   0xfb => 0x0264,
            0xfc => 0x022c,   0xfd => 0x014d,   0xfe => 0x030a,   0xff => 0x022c,
          0x0100 => 0x0116, 0x0101 => 0x022c, 0x0102 => 0x029b, 0x0103 => 0x022c,
          0x0104 => 0x0342, 0x0105 => 0x029b, 0x0106 => 0x012b, 0x0107 => 0x029b,
          0x0108 => 0x022c, 0x0109 => 0x03e8, 0x010a => 0x022c, 0x010b => 0x0116,
          0x010c => 0x0116, 0x010d => 0x022c, 0x010e => 0x0342, 0x010f => 0x0225,
          0x0110 => 0x022c, 0x0111 => 0x022c, 0x0112 => 0x02d2, 0x0113 => 0x029b,
          0x0114 => 0x022c, 0x0115 => 0x022c, 0x0116 => 0x0342, 0x0117 => 0x029b,
          0x0118 => 0x029b, 0x0119 => 0x030a, 0x011a => 0x0190, 0x011b => 0x022c,
          0x011c => 0x02d2, 0x011d => 0x022c, 0x011e => 0x01c5, 0x011f => 0x02d2,
          0x0120 => 0x014d, 0x0121 => 0x02d2, 0x0122 => 0x022c, 0x0123 => 0x02d2,
          0x0124 => 0x022c, 0x0125 => 0x029b, 0x0126 => 0x029b, 0x0127 => 0x029b,
          0x0128 => 0x030a, 0x0129 => 0x01f4, 0x012a => 0x029b, 0x012b => 0x0116,
          0x012c => 0x01f4, 0x012d => 0x0248, 0x012e => 0x0116, 0x012f => 0x022c,
          0x0130 => 0x0116, 0x0131 => 0x0248, 0x0132 => 0x022c, 0x0133 => 0x022c,
          0x0134 => 0x0225, 0x0135 => 0x022c, 0x0136 => 0x022c, 0x0137 => 0x01f4,
          0x0138 => 0x022c, 0x0139 => 0x014d, 0x013a => 0x0116, 0x013b => 0x022c,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Helvetica');
    }

}
Pdf/Resource/Font/Simple/Standard/ZapfDingbats.php000066600000070336151256604610016053 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font ZapfDingbats.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_ZapfDingbats extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Instance Variables ****/


    /**
     * Array for conversion from local encoding to special font encoding.
     * See {@link encodeString()}.
     * @var array
     */
    protected $_toFontEncoding = array(
            0x20 => "\x20", 0x2701 => "\x21", 0x2702 => "\x22", 0x2703 => "\x23",
          0x2704 => "\x24", 0x260e => "\x25", 0x2706 => "\x26", 0x2707 => "\x27",
          0x2708 => "\x28", 0x2709 => "\x29", 0x261b => "\x2a", 0x261e => "\x2b",
          0x270c => "\x2c", 0x270d => "\x2d", 0x270e => "\x2e", 0x270f => "\x2f",
          0x2710 => "\x30", 0x2711 => "\x31", 0x2712 => "\x32", 0x2713 => "\x33",
          0x2714 => "\x34", 0x2715 => "\x35", 0x2716 => "\x36", 0x2717 => "\x37",
          0x2718 => "\x38", 0x2719 => "\x39", 0x271a => "\x3a", 0x271b => "\x3b",
          0x271c => "\x3c", 0x271d => "\x3d", 0x271e => "\x3e", 0x271f => "\x3f",
          0x2720 => "\x40", 0x2721 => "\x41", 0x2722 => "\x42", 0x2723 => "\x43",
          0x2724 => "\x44", 0x2725 => "\x45", 0x2726 => "\x46", 0x2727 => "\x47",
          0x2605 => "\x48", 0x2729 => "\x49", 0x272a => "\x4a", 0x272b => "\x4b",
          0x272c => "\x4c", 0x272d => "\x4d", 0x272e => "\x4e", 0x272f => "\x4f",
          0x2730 => "\x50", 0x2731 => "\x51", 0x2732 => "\x52", 0x2733 => "\x53",
          0x2734 => "\x54", 0x2735 => "\x55", 0x2736 => "\x56", 0x2737 => "\x57",
          0x2738 => "\x58", 0x2739 => "\x59", 0x273a => "\x5a", 0x273b => "\x5b",
          0x273c => "\x5c", 0x273d => "\x5d", 0x273e => "\x5e", 0x273f => "\x5f",
          0x2740 => "\x60", 0x2741 => "\x61", 0x2742 => "\x62", 0x2743 => "\x63",
          0x2744 => "\x64", 0x2745 => "\x65", 0x2746 => "\x66", 0x2747 => "\x67",
          0x2748 => "\x68", 0x2749 => "\x69", 0x274a => "\x6a", 0x274b => "\x6b",
          0x25cf => "\x6c", 0x274d => "\x6d", 0x25a0 => "\x6e", 0x274f => "\x6f",
          0x2750 => "\x70", 0x2751 => "\x71", 0x2752 => "\x72", 0x25b2 => "\x73",
          0x25bc => "\x74", 0x25c6 => "\x75", 0x2756 => "\x76", 0x25d7 => "\x77",
          0x2758 => "\x78", 0x2759 => "\x79", 0x275a => "\x7a", 0x275b => "\x7b",
          0x275c => "\x7c", 0x275d => "\x7d", 0x275e => "\x7e", 0x2768 => "\x80",
          0x2769 => "\x81", 0x276a => "\x82", 0x276b => "\x83", 0x276c => "\x84",
          0x276d => "\x85", 0x276e => "\x86", 0x276f => "\x87", 0x2770 => "\x88",
          0x2771 => "\x89", 0x2772 => "\x8a", 0x2773 => "\x8b", 0x2774 => "\x8c",
          0x2775 => "\x8d", 0x2761 => "\xa1", 0x2762 => "\xa2", 0x2763 => "\xa3",
          0x2764 => "\xa4", 0x2765 => "\xa5", 0x2766 => "\xa6", 0x2767 => "\xa7",
          0x2663 => "\xa8", 0x2666 => "\xa9", 0x2665 => "\xaa", 0x2660 => "\xab",
          0x2460 => "\xac", 0x2461 => "\xad", 0x2462 => "\xae", 0x2463 => "\xaf",
          0x2464 => "\xb0", 0x2465 => "\xb1", 0x2466 => "\xb2", 0x2467 => "\xb3",
          0x2468 => "\xb4", 0x2469 => "\xb5", 0x2776 => "\xb6", 0x2777 => "\xb7",
          0x2778 => "\xb8", 0x2779 => "\xb9", 0x277a => "\xba", 0x277b => "\xbb",
          0x277c => "\xbc", 0x277d => "\xbd", 0x277e => "\xbe", 0x277f => "\xbf",
          0x2780 => "\xc0", 0x2781 => "\xc1", 0x2782 => "\xc2", 0x2783 => "\xc3",
          0x2784 => "\xc4", 0x2785 => "\xc5", 0x2786 => "\xc6", 0x2787 => "\xc7",
          0x2788 => "\xc8", 0x2789 => "\xc9", 0x278a => "\xca", 0x278b => "\xcb",
          0x278c => "\xcc", 0x278d => "\xcd", 0x278e => "\xce", 0x278f => "\xcf",
          0x2790 => "\xd0", 0x2791 => "\xd1", 0x2792 => "\xd2", 0x2793 => "\xd3",
          0x2794 => "\xd4", 0x2192 => "\xd5", 0x2194 => "\xd6", 0x2195 => "\xd7",
          0x2798 => "\xd8", 0x2799 => "\xd9", 0x279a => "\xda", 0x279b => "\xdb",
          0x279c => "\xdc", 0x279d => "\xdd", 0x279e => "\xde", 0x279f => "\xdf",
          0x27a0 => "\xe0", 0x27a1 => "\xe1", 0x27a2 => "\xe2", 0x27a3 => "\xe3",
          0x27a4 => "\xe4", 0x27a5 => "\xe5", 0x27a6 => "\xe6", 0x27a7 => "\xe7",
          0x27a8 => "\xe8", 0x27a9 => "\xe9", 0x27aa => "\xea", 0x27ab => "\xeb",
          0x27ac => "\xec", 0x27ad => "\xed", 0x27ae => "\xee", 0x27af => "\xef",
          0x27b1 => "\xf1", 0x27b2 => "\xf2", 0x27b3 => "\xf3", 0x27b4 => "\xf4",
          0x27b5 => "\xf5", 0x27b6 => "\xf6", 0x27b7 => "\xf7", 0x27b8 => "\xf8",
          0x27b9 => "\xf9", 0x27ba => "\xfa", 0x27bb => "\xfb", 0x27bc => "\xfc",
          0x27bd => "\xfd", 0x27be => "\xfe");

    /**
     * Array for conversion from special font encoding to local encoding.
     * See {@link decodeString()}.
     * @var array
     */
    protected $_fromFontEncoding = array(
            0x20 => "\x00\x20",   0x21 => "\x27\x01",   0x22 => "\x27\x02",
            0x23 => "\x27\x03",   0x24 => "\x27\x04",   0x25 => "\x26\x0e",
            0x26 => "\x27\x06",   0x27 => "\x27\x07",   0x28 => "\x27\x08",
            0x29 => "\x27\x09",   0x2a => "\x26\x1b",   0x2b => "\x26\x1e",
            0x2c => "\x27\x0c",   0x2d => "\x27\x0d",   0x2e => "\x27\x0e",
            0x2f => "\x27\x0f",   0x30 => "\x27\x10",   0x31 => "\x27\x11",
            0x32 => "\x27\x12",   0x33 => "\x27\x13",   0x34 => "\x27\x14",
            0x35 => "\x27\x15",   0x36 => "\x27\x16",   0x37 => "\x27\x17",
            0x38 => "\x27\x18",   0x39 => "\x27\x19",   0x3a => "\x27\x1a",
            0x3b => "\x27\x1b",   0x3c => "\x27\x1c",   0x3d => "\x27\x1d",
            0x3e => "\x27\x1e",   0x3f => "\x27\x1f",   0x40 => "\x27\x20",
            0x41 => "\x27\x21",   0x42 => "\x27\x22",   0x43 => "\x27\x23",
            0x44 => "\x27\x24",   0x45 => "\x27\x25",   0x46 => "\x27\x26",
            0x47 => "\x27\x27",   0x48 => "\x26\x05",   0x49 => "\x27\x29",
            0x4a => "\x27\x2a",   0x4b => "\x27\x2b",   0x4c => "\x27\x2c",
            0x4d => "\x27\x2d",   0x4e => "\x27\x2e",   0x4f => "\x27\x2f",
            0x50 => "\x27\x30",   0x51 => "\x27\x31",   0x52 => "\x27\x32",
            0x53 => "\x27\x33",   0x54 => "\x27\x34",   0x55 => "\x27\x35",
            0x56 => "\x27\x36",   0x57 => "\x27\x37",   0x58 => "\x27\x38",
            0x59 => "\x27\x39",   0x5a => "\x27\x3a",   0x5b => "\x27\x3b",
            0x5c => "\x27\x3c",   0x5d => "\x27\x3d",   0x5e => "\x27\x3e",
            0x5f => "\x27\x3f",   0x60 => "\x27\x40",   0x61 => "\x27\x41",
            0x62 => "\x27\x42",   0x63 => "\x27\x43",   0x64 => "\x27\x44",
            0x65 => "\x27\x45",   0x66 => "\x27\x46",   0x67 => "\x27\x47",
            0x68 => "\x27\x48",   0x69 => "\x27\x49",   0x6a => "\x27\x4a",
            0x6b => "\x27\x4b",   0x6c => "\x25\xcf",   0x6d => "\x27\x4d",
            0x6e => "\x25\xa0",   0x6f => "\x27\x4f",   0x70 => "\x27\x50",
            0x71 => "\x27\x51",   0x72 => "\x27\x52",   0x73 => "\x25\xb2",
            0x74 => "\x25\xbc",   0x75 => "\x25\xc6",   0x76 => "\x27\x56",
            0x77 => "\x25\xd7",   0x78 => "\x27\x58",   0x79 => "\x27\x59",
            0x7a => "\x27\x5a",   0x7b => "\x27\x5b",   0x7c => "\x27\x5c",
            0x7d => "\x27\x5d",   0x7e => "\x27\x5e",   0x80 => "\x27\x68",
            0x81 => "\x27\x69",   0x82 => "\x27\x6a",   0x83 => "\x27\x6b",
            0x84 => "\x27\x6c",   0x85 => "\x27\x6d",   0x86 => "\x27\x6e",
            0x87 => "\x27\x6f",   0x88 => "\x27\x70",   0x89 => "\x27\x71",
            0x8a => "\x27\x72",   0x8b => "\x27\x73",   0x8c => "\x27\x74",
            0x8d => "\x27\x75",   0xa1 => "\x27\x61",   0xa2 => "\x27\x62",
            0xa3 => "\x27\x63",   0xa4 => "\x27\x64",   0xa5 => "\x27\x65",
            0xa6 => "\x27\x66",   0xa7 => "\x27\x67",   0xa8 => "\x26\x63",
            0xa9 => "\x26\x66",   0xaa => "\x26\x65",   0xab => "\x26\x60",
            0xac => "\x24\x60",   0xad => "\x24\x61",   0xae => "\x24\x62",
            0xaf => "\x24\x63",   0xb0 => "\x24\x64",   0xb1 => "\x24\x65",
            0xb2 => "\x24\x66",   0xb3 => "\x24\x67",   0xb4 => "\x24\x68",
            0xb5 => "\x24\x69",   0xb6 => "\x27\x76",   0xb7 => "\x27\x77",
            0xb8 => "\x27\x78",   0xb9 => "\x27\x79",   0xba => "\x27\x7a",
            0xbb => "\x27\x7b",   0xbc => "\x27\x7c",   0xbd => "\x27\x7d",
            0xbe => "\x27\x7e",   0xbf => "\x27\x7f",   0xc0 => "\x27\x80",
            0xc1 => "\x27\x81",   0xc2 => "\x27\x82",   0xc3 => "\x27\x83",
            0xc4 => "\x27\x84",   0xc5 => "\x27\x85",   0xc6 => "\x27\x86",
            0xc7 => "\x27\x87",   0xc8 => "\x27\x88",   0xc9 => "\x27\x89",
            0xca => "\x27\x8a",   0xcb => "\x27\x8b",   0xcc => "\x27\x8c",
            0xcd => "\x27\x8d",   0xce => "\x27\x8e",   0xcf => "\x27\x8f",
            0xd0 => "\x27\x90",   0xd1 => "\x27\x91",   0xd2 => "\x27\x92",
            0xd3 => "\x27\x93",   0xd4 => "\x27\x94",   0xd5 => "\x21\x92",
            0xd6 => "\x21\x94",   0xd7 => "\x21\x95",   0xd8 => "\x27\x98",
            0xd9 => "\x27\x99",   0xda => "\x27\x9a",   0xdb => "\x27\x9b",
            0xdc => "\x27\x9c",   0xdd => "\x27\x9d",   0xde => "\x27\x9e",
            0xdf => "\x27\x9f",   0xe0 => "\x27\xa0",   0xe1 => "\x27\xa1",
            0xe2 => "\x27\xa2",   0xe3 => "\x27\xa3",   0xe4 => "\x27\xa4",
            0xe5 => "\x27\xa5",   0xe6 => "\x27\xa6",   0xe7 => "\x27\xa7",
            0xe8 => "\x27\xa8",   0xe9 => "\x27\xa9",   0xea => "\x27\xaa",
            0xeb => "\x27\xab",   0xec => "\x27\xac",   0xed => "\x27\xad",
            0xee => "\x27\xae",   0xef => "\x27\xaf",   0xf1 => "\x27\xb1",
            0xf2 => "\x27\xb2",   0xf3 => "\x27\xb3",   0xf4 => "\x27\xb4",
            0xf5 => "\x27\xb5",   0xf6 => "\x27\xb6",   0xf7 => "\x27\xb7",
            0xf8 => "\x27\xb8",   0xf9 => "\x27\xb9",   0xfa => "\x27\xba",
            0xfb => "\x27\xbb",   0xfc => "\x27\xbc",   0xfd => "\x27\xbd",
            0xfe => "\x27\xbe");



  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x38\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x37\x00\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00"
          . "\x20\x00\x53\x00\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00"
          . "\x20\x00\x49\x00\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00"
          . "\x72\x00\x61\x00\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x41\x00"
          . "\x6c\x00\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00\x74\x00"
          . "\x73\x00\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00\x76\x00"
          . "\x65\x00\x64\x00\x2e\x00\x49\x00\x54\x00\x43\x00\x20\x00\x5a\x00"
          . "\x61\x00\x70\x00\x66\x00\x20\x00\x44\x00\x69\x00\x6e\x00\x67\x00"
          . "\x62\x00\x61\x00\x74\x00\x73\x00\x20\x00\x69\x00\x73\x00\x20\x00"
          . "\x61\x00\x20\x00\x72\x00\x65\x00\x67\x00\x69\x00\x73\x00\x74\x00"
          . "\x65\x00\x72\x00\x65\x00\x64\x00\x20\x00\x74\x00\x72\x00\x61\x00"
          . "\x64\x00\x65\x00\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00"
          . "\x66\x00\x20\x00\x49\x00\x6e\x00\x74\x00\x65\x00\x72\x00\x6e\x00"
          . "\x61\x00\x74\x00\x69\x00\x6f\x00\x6e\x00\x61\x00\x6c\x00\x20\x00"
          . "\x54\x00\x79\x00\x70\x00\x65\x00\x66\x00\x61\x00\x63\x00\x65\x00"
          . "\x20\x00\x43\x00\x6f\x00\x72\x00\x70\x00\x6f\x00\x72\x00\x61\x00"
          . "\x74\x00\x69\x00\x6f\x00\x6e\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x5a\x00\x61\x00\x70\x00\x66\x00\x44\x00\x69\x00\x6e\x00\x67\x00"
          . "\x62\x00\x61\x00\x74\x00\x73";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x38\x00\x32";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x5a\x00\x61\x00\x70\x00\x66\x00\x44\x00\x69\x00\x6e\x00\x67\x00"
          . "\x62\x00\x61\x00\x74\x00\x73\x00\x20\x00\x4d\x00\x65\x00\x64\x00"
          . "\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x5a\x00\x61\x00\x70\x00\x66\x00\x44\x00\x69\x00\x6e\x00\x67\x00"
          . "\x62\x00\x61\x00\x74\x00\x73";

        $this->_isBold = false;
        $this->_isItalic = false;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 1000;
        $this->_descent = 0;
        $this->_lineGap = 200;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0116,   0x02 => 0x03ce,   0x03 => 0x03c1,
            0x04 => 0x03ce,   0x05 => 0x03d4,   0x06 => 0x02cf,   0x07 => 0x0315,
            0x08 => 0x0316,   0x09 => 0x0317,   0x0a => 0x02b2,   0x0b => 0x03c0,
            0x0c => 0x03ab,   0x0d => 0x0225,   0x0e => 0x0357,   0x0f => 0x038f,
            0x10 => 0x03a5,   0x11 => 0x038f,   0x12 => 0x03b1,   0x13 => 0x03ce,
            0x14 => 0x02f3,   0x15 => 0x034e,   0x16 => 0x02fa,   0x17 => 0x02f9,
            0x18 => 0x023b,   0x19 => 0x02a5,   0x1a => 0x02fb,   0x1b => 0x02f8,
            0x1c => 0x02f7,   0x1d => 0x02f2,   0x1e => 0x01ee,   0x1f => 0x0228,
            0x20 => 0x0219,   0x21 => 0x0241,   0x22 => 0x02b4,   0x23 => 0x0312,
            0x24 => 0x0314,   0x25 => 0x0314,   0x26 => 0x0316,   0x27 => 0x0319,
            0x28 => 0x031a,   0x29 => 0x0330,   0x2a => 0x0337,   0x2b => 0x0315,
            0x2c => 0x0349,   0x2d => 0x0337,   0x2e => 0x0341,   0x2f => 0x0330,
            0x30 => 0x033f,   0x31 => 0x039b,   0x32 => 0x02e8,   0x33 => 0x02d3,
            0x34 => 0x02ed,   0x35 => 0x0316,   0x36 => 0x0318,   0x37 => 0x02b7,
            0x38 => 0x0308,   0x39 => 0x0300,   0x3a => 0x0318,   0x3b => 0x02f7,
            0x3c => 0x02c3,   0x3d => 0x02c4,   0x3e => 0x02aa,   0x3f => 0x02bd,
            0x40 => 0x033a,   0x41 => 0x032f,   0x42 => 0x0315,   0x43 => 0x0315,
            0x44 => 0x02c3,   0x45 => 0x02af,   0x46 => 0x02b8,   0x47 => 0x02b1,
            0x48 => 0x0312,   0x49 => 0x0313,   0x4a => 0x02c9,   0x4b => 0x0317,
            0x4c => 0x0311,   0x4d => 0x0317,   0x4e => 0x0369,   0x4f => 0x02f9,
            0x50 => 0x02fa,   0x51 => 0x02fa,   0x52 => 0x02f7,   0x53 => 0x02f7,
            0x54 => 0x037c,   0x55 => 0x037c,   0x56 => 0x0314,   0x57 => 0x0310,
            0x58 => 0x01b6,   0x59 =>   0x8a,   0x5a => 0x0115,   0x5b => 0x019f,
            0x5c => 0x0188,   0x5d => 0x0188,   0x5e => 0x029c,   0x5f => 0x029c,
            0x60 => 0x0186,   0x61 => 0x0186,   0x62 => 0x013d,   0x63 => 0x013d,
            0x64 => 0x0114,   0x65 => 0x0114,   0x66 => 0x01fd,   0x67 => 0x01fd,
            0x68 => 0x019a,   0x69 => 0x019a,   0x6a =>   0xea,   0x6b =>   0xea,
            0x6c => 0x014e,   0x6d => 0x014e,   0x6e => 0x02dc,   0x6f => 0x0220,
            0x70 => 0x0220,   0x71 => 0x038e,   0x72 => 0x029b,   0x73 => 0x02f8,
            0x74 => 0x02f8,   0x75 => 0x0308,   0x76 => 0x0253,   0x77 => 0x02b6,
            0x78 => 0x0272,   0x79 => 0x0314,   0x7a => 0x0314,   0x7b => 0x0314,
            0x7c => 0x0314,   0x7d => 0x0314,   0x7e => 0x0314,   0x7f => 0x0314,
            0x80 => 0x0314,   0x81 => 0x0314,   0x82 => 0x0314,   0x83 => 0x0314,
            0x84 => 0x0314,   0x85 => 0x0314,   0x86 => 0x0314,   0x87 => 0x0314,
            0x88 => 0x0314,   0x89 => 0x0314,   0x8a => 0x0314,   0x8b => 0x0314,
            0x8c => 0x0314,   0x8d => 0x0314,   0x8e => 0x0314,   0x8f => 0x0314,
            0x90 => 0x0314,   0x91 => 0x0314,   0x92 => 0x0314,   0x93 => 0x0314,
            0x94 => 0x0314,   0x95 => 0x0314,   0x96 => 0x0314,   0x97 => 0x0314,
            0x98 => 0x0314,   0x99 => 0x0314,   0x9a => 0x0314,   0x9b => 0x0314,
            0x9c => 0x0314,   0x9d => 0x0314,   0x9e => 0x0314,   0x9f => 0x0314,
            0xa0 => 0x0314,   0xa1 => 0x037e,   0xa2 => 0x0346,   0xa3 => 0x03f8,
            0xa4 => 0x01ca,   0xa5 => 0x02ec,   0xa6 => 0x039c,   0xa7 => 0x02ec,
            0xa8 => 0x0396,   0xa9 => 0x039f,   0xaa => 0x03a0,   0xab => 0x03a0,
            0xac => 0x0342,   0xad => 0x0369,   0xae => 0x033c,   0xaf => 0x039c,
            0xb0 => 0x039c,   0xb1 => 0x0395,   0xb2 => 0x03a2,   0xb3 => 0x03a3,
            0xb4 => 0x01cf,   0xb5 => 0x0373,   0xb6 => 0x0344,   0xb7 => 0x0344,
            0xb8 => 0x0363,   0xb9 => 0x0363,   0xba => 0x02b8,   0xbb => 0x02b8,
            0xbc => 0x036a,   0xbd => 0x036a,   0xbe => 0x02f8,   0xbf => 0x03b2,
            0xc0 => 0x0303,   0xc1 => 0x0361,   0xc2 => 0x0303,   0xc3 => 0x0378,
            0xc4 => 0x03c7,   0xc5 => 0x0378,   0xc6 => 0x033f,   0xc7 => 0x0369,
            0xc8 => 0x039f,   0xc9 => 0x03ca,   0xca => 0x0396);

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01, 0x2701 =>   0x02, 0x2702 =>   0x03, 0x2703 =>   0x04,
          0x2704 =>   0x05, 0x260e =>   0x06, 0x2706 =>   0x07, 0x2707 =>   0x08,
          0x2708 =>   0x09, 0x2709 =>   0x0a, 0x261b =>   0x0b, 0x261e =>   0x0c,
          0x270c =>   0x0d, 0x270d =>   0x0e, 0x270e =>   0x0f, 0x270f =>   0x10,
          0x2710 =>   0x11, 0x2711 =>   0x12, 0x2712 =>   0x13, 0x2713 =>   0x14,
          0x2714 =>   0x15, 0x2715 =>   0x16, 0x2716 =>   0x17, 0x2717 =>   0x18,
          0x2718 =>   0x19, 0x2719 =>   0x1a, 0x271a =>   0x1b, 0x271b =>   0x1c,
          0x271c =>   0x1d, 0x271d =>   0x1e, 0x271e =>   0x1f, 0x271f =>   0x20,
          0x2720 =>   0x21, 0x2721 =>   0x22, 0x2722 =>   0x23, 0x2723 =>   0x24,
          0x2724 =>   0x25, 0x2725 =>   0x26, 0x2726 =>   0x27, 0x2727 =>   0x28,
          0x2605 =>   0x29, 0x2729 =>   0x2a, 0x272a =>   0x2b, 0x272b =>   0x2c,
          0x272c =>   0x2d, 0x272d =>   0x2e, 0x272e =>   0x2f, 0x272f =>   0x30,
          0x2730 =>   0x31, 0x2731 =>   0x32, 0x2732 =>   0x33, 0x2733 =>   0x34,
          0x2734 =>   0x35, 0x2735 =>   0x36, 0x2736 =>   0x37, 0x2737 =>   0x38,
          0x2738 =>   0x39, 0x2739 =>   0x3a, 0x273a =>   0x3b, 0x273b =>   0x3c,
          0x273c =>   0x3d, 0x273d =>   0x3e, 0x273e =>   0x3f, 0x273f =>   0x40,
          0x2740 =>   0x41, 0x2741 =>   0x42, 0x2742 =>   0x43, 0x2743 =>   0x44,
          0x2744 =>   0x45, 0x2745 =>   0x46, 0x2746 =>   0x47, 0x2747 =>   0x48,
          0x2748 =>   0x49, 0x2749 =>   0x4a, 0x274a =>   0x4b, 0x274b =>   0x4c,
          0x25cf =>   0x4d, 0x274d =>   0x4e, 0x25a0 =>   0x4f, 0x274f =>   0x50,
          0x2750 =>   0x51, 0x2751 =>   0x52, 0x2752 =>   0x53, 0x25b2 =>   0x54,
          0x25bc =>   0x55, 0x25c6 =>   0x56, 0x2756 =>   0x57, 0x25d7 =>   0x58,
          0x2758 =>   0x59, 0x2759 =>   0x5a, 0x275a =>   0x5b, 0x275b =>   0x5c,
          0x275c =>   0x5d, 0x275d =>   0x5e, 0x275e =>   0x5f, 0x2768 =>   0x60,
          0x2769 =>   0x61, 0x276a =>   0x62, 0x276b =>   0x63, 0x276c =>   0x64,
          0x276d =>   0x65, 0x276e =>   0x66, 0x276f =>   0x67, 0x2770 =>   0x68,
          0x2771 =>   0x69, 0x2772 =>   0x6a, 0x2773 =>   0x6b, 0x2774 =>   0x6c,
          0x2775 =>   0x6d, 0x2761 =>   0x6e, 0x2762 =>   0x6f, 0x2763 =>   0x70,
          0x2764 =>   0x71, 0x2765 =>   0x72, 0x2766 =>   0x73, 0x2767 =>   0x74,
          0x2663 =>   0x75, 0x2666 =>   0x76, 0x2665 =>   0x77, 0x2660 =>   0x78,
          0x2460 =>   0x79, 0x2461 =>   0x7a, 0x2462 =>   0x7b, 0x2463 =>   0x7c,
          0x2464 =>   0x7d, 0x2465 =>   0x7e, 0x2466 =>   0x7f, 0x2467 =>   0x80,
          0x2468 =>   0x81, 0x2469 =>   0x82, 0x2776 =>   0x83, 0x2777 =>   0x84,
          0x2778 =>   0x85, 0x2779 =>   0x86, 0x277a =>   0x87, 0x277b =>   0x88,
          0x277c =>   0x89, 0x277d =>   0x8a, 0x277e =>   0x8b, 0x277f =>   0x8c,
          0x2780 =>   0x8d, 0x2781 =>   0x8e, 0x2782 =>   0x8f, 0x2783 =>   0x90,
          0x2784 =>   0x91, 0x2785 =>   0x92, 0x2786 =>   0x93, 0x2787 =>   0x94,
          0x2788 =>   0x95, 0x2789 =>   0x96, 0x278a =>   0x97, 0x278b =>   0x98,
          0x278c =>   0x99, 0x278d =>   0x9a, 0x278e =>   0x9b, 0x278f =>   0x9c,
          0x2790 =>   0x9d, 0x2791 =>   0x9e, 0x2792 =>   0x9f, 0x2793 =>   0xa0,
          0x2794 =>   0xa1, 0x2192 =>   0xa2, 0x2194 =>   0xa3, 0x2195 =>   0xa4,
          0x2798 =>   0xa5, 0x2799 =>   0xa6, 0x279a =>   0xa7, 0x279b =>   0xa8,
          0x279c =>   0xa9, 0x279d =>   0xaa, 0x279e =>   0xab, 0x279f =>   0xac,
          0x27a0 =>   0xad, 0x27a1 =>   0xae, 0x27a2 =>   0xaf, 0x27a3 =>   0xb0,
          0x27a4 =>   0xb1, 0x27a5 =>   0xb2, 0x27a6 =>   0xb3, 0x27a7 =>   0xb4,
          0x27a8 =>   0xb5, 0x27a9 =>   0xb6, 0x27aa =>   0xb7, 0x27ab =>   0xb8,
          0x27ac =>   0xb9, 0x27ad =>   0xba, 0x27ae =>   0xbb, 0x27af =>   0xbc,
          0x27b1 =>   0xbd, 0x27b2 =>   0xbe, 0x27b3 =>   0xbf, 0x27b4 =>   0xc0,
          0x27b5 =>   0xc1, 0x27b6 =>   0xc2, 0x27b7 =>   0xc3, 0x27b8 =>   0xc4,
          0x27b9 =>   0xc5, 0x27ba =>   0xc6, 0x27bb =>   0xc7, 0x27bc =>   0xc8,
          0x27bd =>   0xc9, 0x27be =>   0xca);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('ZapfDingbats');

        /* This font has a built-in custom character encoding method. Don't
         * override with WinAnsi like the other built-in fonts or else it will
         * not work as expected.
         */
        $this->_resource->Encoding = null;
    }


  /* Information and Conversion Methods */

    /**
     * Convert string encoding from local encoding to font encoding. Overridden
     * to defeat the conversion behavior for this ornamental font.
     *
     * @param string $string
     * @param string $charEncoding Character encoding of source text.
     * @return string
     */
    public function encodeString($string, $charEncoding)
    {
        /* This isn't the optimal time to perform this conversion, but it must
         * live here until the remainder of the layout code is completed. This,
         * and the $charEncoding parameter, will go away soon...
         */
        if ($charEncoding != 'UTF-16BE') {
            $string = iconv($charEncoding, 'UTF-16BE', $string);
        }
        /**
         * @todo Properly handle characters encoded as surrogate pairs.
         */
        $encodedString = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $characterCode = (ord($string[$i++]) << 8) | ord($string[$i]);
            if (isset($this->_toFontEncoding[$characterCode])) {
                $encodedString .= $this->_toFontEncoding[$characterCode];
            } else {
                /* For now, mimic the behavior in Zend_Pdf_Font::encodeString()
                 * where unknown characters are removed completely. This is not
                 * perfect, but we should be consistent. In a future revision,
                 * we will use the well-known substitution character 0x1a
                 * (Control-Z).
                 */
            }
        }
        return $encodedString;
    }

    /**
     * Convert string encoding from font encoding to local encoding. Overridden
     * to defeat the conversion behavior for this ornamental font.
     *
     * @param string $string
     * @param string $charEncoding Character encoding of resulting text.
     * @return string
     */
    public function decodeString($string, $charEncoding)
    {
        $decodedString = '';
        for ($i = 0; $i < strlen($string); $i++) {
            $characterCode = ord($string[$i]);
            if (isset($this->_fromFontEncoding[$characterCode])) {
                $decodedString .= $this->_fromFontEncoding[$characterCode];
            } else {
                /* For now, mimic the behavior in Zend_Pdf_Font::encodeString()
                 * where unknown characters are removed completely. This is not
                 * perfect, but we should be consistent. In a future revision,
                 * we will use the Unicode substitution character (U+FFFD).
                 */
            }
        }
        if ($charEncoding != 'UTF-16BE') {
            $decodedString = iconv('UTF-16BE', $charEncoding, $decodedString);
        }
        return $decodedString;
    }

    /**
     * Converts a Latin-encoded string that fakes the font's internal encoding
     * to the proper Unicode characters, in UTF-16BE encoding.
     *
     * Used to maintain backwards compatibility with the 20 year-old legacy
     * method of using this font, which is still employed by recent versions of
     * some popular word processors.
     *
     * Note that using this method adds overhead due to the additional
     * character conversion. Don't use this for new code; it is more efficient
     * to use the appropriate Unicode characters directly.
     *
     * @param string $string
     * @param string $charEncoding (optional) Character encoding of source
     *   string. Defaults to current locale.
     * @return string
     */
    public function toUnicode($string, $charEncoding = '')
    {
        /* When using these faked strings, the closest match to the font's
         * internal encoding is ISO-8859-1.
         */
        if ($charEncoding != 'ISO-8859-1') {
            $string = iconv($charEncoding, 'ISO-8859-1', $string);
        }
        return $this->decodeString($string, 'UTF-16BE');
    }

}
Pdf/Resource/Font/Simple/Standard/HelveticaBoldOblique.php000066600000046145151256604610017526 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Helvetica-BoldOblique.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_HelveticaBoldOblique extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x37\x00\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00"
          . "\x20\x00\x53\x00\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00"
          . "\x20\x00\x49\x00\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00"
          . "\x72\x00\x61\x00\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00"
          . "\x41\x00\x6c\x00\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x73\x00\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00"
          . "\x76\x00\x65\x00\x64\x00\x2e\x00\x48\x00\x65\x00\x6c\x00\x76\x00"
          . "\x65\x00\x74\x00\x69\x00\x63\x00\x61\x00\x20\x00\x69\x00\x73\x00"
          . "\x20\x00\x61\x00\x20\x00\x74\x00\x72\x00\x61\x00\x64\x00\x65\x00"
          . "\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00\x66\x00\x20\x00"
          . "\x4c\x00\x69\x00\x6e\x00\x6f\x00\x74\x00\x79\x00\x70\x00\x65\x00"
          . "\x2d\x00\x48\x00\x65\x00\x6c\x00\x6c\x00\x20\x00\x41\x00\x47\x00"
          . "\x20\x00\x61\x00\x6e\x00\x64\x00\x2f\x00\x6f\x00\x72\x00\x20\x00"
          . "\x69\x00\x74\x00\x73\x00\x20\x00\x73\x00\x75\x00\x62\x00\x73\x00"
          . "\x69\x00\x64\x00\x69\x00\x61\x00\x72\x00\x69\x00\x65\x00\x73\x00"
          . "\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x35\x00\x33";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61\x00\x2d\x00\x42\x00\x6f\x00\x6c\x00\x64\x00\x4f\x00\x62\x00"
          . "\x6c\x00\x69\x00\x71\x00\x75\x00\x65\x00\x20\x00\x42\x00\x6f\x00"
          . "\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61\x00\x2d\x00\x42\x00\x6f\x00\x6c\x00\x64\x00\x4f\x00\x62\x00"
          . "\x6c\x00\x69\x00\x71\x00\x75\x00\x65";

        $this->_isBold = true;
        $this->_isItalic = true;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 718;
        $this->_descent = -207;
        $this->_lineGap = 275;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0116,   0x02 => 0x014d,   0x03 => 0x01da,
            0x04 => 0x022c,   0x05 => 0x022c,   0x06 => 0x0379,   0x07 => 0x02d2,
            0x08 => 0x0116,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x0185,
            0x0c => 0x0248,   0x0d => 0x0116,   0x0e => 0x014d,   0x0f => 0x0116,
            0x10 => 0x0116,   0x11 => 0x022c,   0x12 => 0x022c,   0x13 => 0x022c,
            0x14 => 0x022c,   0x15 => 0x022c,   0x16 => 0x022c,   0x17 => 0x022c,
            0x18 => 0x022c,   0x19 => 0x022c,   0x1a => 0x022c,   0x1b => 0x014d,
            0x1c => 0x014d,   0x1d => 0x0248,   0x1e => 0x0248,   0x1f => 0x0248,
            0x20 => 0x0263,   0x21 => 0x03cf,   0x22 => 0x02d2,   0x23 => 0x02d2,
            0x24 => 0x02d2,   0x25 => 0x02d2,   0x26 => 0x029b,   0x27 => 0x0263,
            0x28 => 0x030a,   0x29 => 0x02d2,   0x2a => 0x0116,   0x2b => 0x022c,
            0x2c => 0x02d2,   0x2d => 0x0263,   0x2e => 0x0341,   0x2f => 0x02d2,
            0x30 => 0x030a,   0x31 => 0x029b,   0x32 => 0x030a,   0x33 => 0x02d2,
            0x34 => 0x029b,   0x35 => 0x0263,   0x36 => 0x02d2,   0x37 => 0x029b,
            0x38 => 0x03b0,   0x39 => 0x029b,   0x3a => 0x029b,   0x3b => 0x0263,
            0x3c => 0x014d,   0x3d => 0x0116,   0x3e => 0x014d,   0x3f => 0x0248,
            0x40 => 0x022c,   0x41 => 0x0116,   0x42 => 0x022c,   0x43 => 0x0263,
            0x44 => 0x022c,   0x45 => 0x0263,   0x46 => 0x022c,   0x47 => 0x014d,
            0x48 => 0x0263,   0x49 => 0x0263,   0x4a => 0x0116,   0x4b => 0x0116,
            0x4c => 0x022c,   0x4d => 0x0116,   0x4e => 0x0379,   0x4f => 0x0263,
            0x50 => 0x0263,   0x51 => 0x0263,   0x52 => 0x0263,   0x53 => 0x0185,
            0x54 => 0x022c,   0x55 => 0x014d,   0x56 => 0x0263,   0x57 => 0x022c,
            0x58 => 0x030a,   0x59 => 0x022c,   0x5a => 0x022c,   0x5b => 0x01f4,
            0x5c => 0x0185,   0x5d => 0x0118,   0x5e => 0x0185,   0x5f => 0x0248,
            0x60 => 0x014d,   0x61 => 0x022c,   0x62 => 0x022c,   0x63 =>   0xa7,
            0x64 => 0x022c,   0x65 => 0x022c,   0x66 => 0x022c,   0x67 => 0x022c,
            0x68 =>   0xee,   0x69 => 0x01f4,   0x6a => 0x022c,   0x6b => 0x014d,
            0x6c => 0x014d,   0x6d => 0x0263,   0x6e => 0x0263,   0x6f => 0x022c,
            0x70 => 0x022c,   0x71 => 0x022c,   0x72 => 0x0116,   0x73 => 0x022c,
            0x74 => 0x015e,   0x75 => 0x0116,   0x76 => 0x01f4,   0x77 => 0x01f4,
            0x78 => 0x022c,   0x79 => 0x03e8,   0x7a => 0x03e8,   0x7b => 0x0263,
            0x7c => 0x014d,   0x7d => 0x014d,   0x7e => 0x014d,   0x7f => 0x014d,
            0x80 => 0x014d,   0x81 => 0x014d,   0x82 => 0x014d,   0x83 => 0x014d,
            0x84 => 0x014d,   0x85 => 0x014d,   0x86 => 0x014d,   0x87 => 0x014d,
            0x88 => 0x014d,   0x89 => 0x03e8,   0x8a => 0x03e8,   0x8b => 0x0172,
            0x8c => 0x0263,   0x8d => 0x030a,   0x8e => 0x03e8,   0x8f => 0x016d,
            0x90 => 0x0379,   0x91 => 0x0116,   0x92 => 0x0116,   0x93 => 0x0263,
            0x94 => 0x03b0,   0x95 => 0x0263,   0x96 => 0x0116,   0x97 => 0x022c,
            0x98 => 0x022c,   0x99 => 0x0263,   0x9a => 0x022c,   0x9b => 0x029b,
            0x9c => 0x0248,   0x9d => 0x029b,   0x9e => 0x02d2,   0x9f => 0x022c,
            0xa0 => 0x02d2,   0xa1 => 0x022c,   0xa2 => 0x022c,   0xa3 => 0x022c,
            0xa4 => 0x02d2,   0xa5 => 0x02d2,   0xa6 => 0x022c,   0xa7 => 0x02d2,
            0xa8 => 0x0263,   0xa9 => 0x029b,   0xaa => 0x02d2,   0xab =>   0xfa,
            0xac => 0x02e1,   0xad => 0x029b,   0xae => 0x022c,   0xaf => 0x022c,
            0xb0 => 0x02d2,   0xb1 => 0x0116,   0xb2 => 0x022c,   0xb3 => 0x0263,
            0xb4 => 0x02d2,   0xb5 => 0x022c,   0xb6 => 0x029b,   0xb7 => 0x022c,
            0xb8 => 0x022c,   0xb9 => 0x0116,   0xba => 0x01ee,   0xbb => 0x02d2,
            0xbc => 0x030a,   0xbd => 0x0263,   0xbe => 0x022c,   0xbf => 0x02d2,
            0xc0 => 0x0185,   0xc1 => 0x022c,   0xc2 => 0x0263,   0xc3 => 0x029b,
            0xc4 => 0x030a,   0xc5 => 0x02d2,   0xc6 => 0x029b,   0xc7 => 0x02e7,
            0xc8 => 0x02d2,   0xc9 => 0x0263,   0xca => 0x014d,   0xcb => 0x030a,
            0xcc => 0x02d2,   0xcd => 0x02d2,   0xce => 0x0248,   0xcf => 0x0263,
            0xd0 => 0x0263,   0xd1 => 0x01ee,   0xd2 => 0x022c,   0xd3 => 0x02d2,
            0xd4 => 0x0116,   0xd5 => 0x029b,   0xd6 => 0x022c,   0xd7 => 0x022c,
            0xd8 => 0x022c,   0xd9 => 0x0263,   0xda => 0x0263,   0xdb => 0x02d2,
            0xdc => 0x0116,   0xdd => 0x0248,   0xde => 0x0118,   0xdf => 0x02e1,
            0xe0 => 0x030a,   0xe1 => 0x0116,   0xe2 => 0x0258,   0xe3 => 0x029b,
            0xe4 => 0x0185,   0xe5 => 0x0263,   0xe6 => 0x0263,   0xe7 => 0x0263,
            0xe8 => 0x0225,   0xe9 => 0x02d2,   0xea => 0x02d2,   0xeb => 0x0116,
            0xec => 0x0185,   0xed => 0x022c,   0xee => 0x02d2,   0xef => 0x02d2,
            0xf0 => 0x02d2,   0xf1 => 0x022c,   0xf2 => 0x01f4,   0xf3 => 0x0116,
            0xf4 => 0x030a,   0xf5 => 0x0263,   0xf6 => 0x022c,   0xf7 => 0x022c,
            0xf8 => 0x0116,   0xf9 => 0x030a,   0xfa => 0x02d2,   0xfb => 0x0264,
            0xfc => 0x0263,   0xfd => 0x014d,   0xfe => 0x030a,   0xff => 0x0263,
          0x0100 => 0x0116, 0x0101 => 0x0263, 0x0102 => 0x029b, 0x0103 => 0x0263,
          0x0104 => 0x0342, 0x0105 => 0x029b, 0x0106 => 0x0190, 0x0107 => 0x02d2,
          0x0108 => 0x0263, 0x0109 => 0x03e8, 0x010a => 0x022c, 0x010b => 0x0116,
          0x010c => 0x0116, 0x010d => 0x0263, 0x010e => 0x0342, 0x010f => 0x0225,
          0x0110 => 0x0263, 0x0111 => 0x0263, 0x0112 => 0x02d2, 0x0113 => 0x029b,
          0x0114 => 0x022c, 0x0115 => 0x0263, 0x0116 => 0x0342, 0x0117 => 0x029b,
          0x0118 => 0x029b, 0x0119 => 0x030a, 0x011a => 0x0190, 0x011b => 0x0263,
          0x011c => 0x02d2, 0x011d => 0x0263, 0x011e => 0x0225, 0x011f => 0x02d2,
          0x0120 => 0x0185, 0x0121 => 0x02d2, 0x0122 => 0x0263, 0x0123 => 0x02d2,
          0x0124 => 0x0263, 0x0125 => 0x02d2, 0x0126 => 0x02d2, 0x0127 => 0x02d2,
          0x0128 => 0x030a, 0x0129 => 0x01f4, 0x012a => 0x029b, 0x012b => 0x0116,
          0x012c => 0x022c, 0x012d => 0x0248, 0x012e => 0x0116, 0x012f => 0x0263,
          0x0130 => 0x014d, 0x0131 => 0x0248, 0x0132 => 0x0263, 0x0133 => 0x0263,
          0x0134 => 0x0225, 0x0135 => 0x0263, 0x0136 => 0x0263, 0x0137 => 0x01f4,
          0x0138 => 0x0263, 0x0139 => 0x014d, 0x013a => 0x0116, 0x013b => 0x022c,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Helvetica-BoldOblique');
    }

}
Pdf/Resource/Font/Simple/Standard/TimesRoman.php000066600000045571151256604610015560 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Times-Roman.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_TimesRoman extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x33\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x37\x00"
          . "\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00\x20\x00\x53\x00"
          . "\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00\x20\x00\x49\x00"
          . "\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00\x72\x00\x61\x00"
          . "\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00\x41\x00\x6c\x00"
          . "\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00\x74\x00\x73\x00"
          . "\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00\x76\x00\x65\x00"
          . "\x64\x00\x2e\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x20\x00"
          . "\x69\x00\x73\x00\x20\x00\x61\x00\x20\x00\x74\x00\x72\x00\x61\x00"
          . "\x64\x00\x65\x00\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00"
          . "\x66\x00\x20\x00\x4c\x00\x69\x00\x6e\x00\x6f\x00\x74\x00\x79\x00"
          . "\x70\x00\x65\x00\x2d\x00\x48\x00\x65\x00\x6c\x00\x6c\x00\x20\x00"
          . "\x41\x00\x47\x00\x20\x00\x61\x00\x6e\x00\x64\x00\x2f\x00\x6f\x00"
          . "\x72\x00\x20\x00\x69\x00\x74\x00\x73\x00\x20\x00\x73\x00\x75\x00"
          . "\x62\x00\x73\x00\x69\x00\x64\x00\x69\x00\x61\x00\x72\x00\x69\x00"
          . "\x65\x00\x73\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x52\x00\x6f\x00\x6d\x00\x61\x00\x6e";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x36\x00\x38";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x2d\x00\x52\x00\x6f\x00"
          . "\x6d\x00\x61\x00\x6e\x00\x20\x00\x52\x00\x6f\x00\x6d\x00\x61\x00"
          . "\x6e";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x2d\x00\x52\x00\x6f\x00"
          . "\x6d\x00\x61\x00\x6e";

        $this->_isBold = false;
        $this->_isItalic = false;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 683;
        $this->_descent = -217;
        $this->_lineGap = 300;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 =>   0xfa,   0x02 => 0x014d,   0x03 => 0x0198,
            0x04 => 0x01f4,   0x05 => 0x01f4,   0x06 => 0x0341,   0x07 => 0x030a,
            0x08 => 0x014d,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x01f4,
            0x0c => 0x0234,   0x0d =>   0xfa,   0x0e => 0x014d,   0x0f =>   0xfa,
            0x10 => 0x0116,   0x11 => 0x01f4,   0x12 => 0x01f4,   0x13 => 0x01f4,
            0x14 => 0x01f4,   0x15 => 0x01f4,   0x16 => 0x01f4,   0x17 => 0x01f4,
            0x18 => 0x01f4,   0x19 => 0x01f4,   0x1a => 0x01f4,   0x1b => 0x0116,
            0x1c => 0x0116,   0x1d => 0x0234,   0x1e => 0x0234,   0x1f => 0x0234,
            0x20 => 0x01bc,   0x21 => 0x0399,   0x22 => 0x02d2,   0x23 => 0x029b,
            0x24 => 0x029b,   0x25 => 0x02d2,   0x26 => 0x0263,   0x27 => 0x022c,
            0x28 => 0x02d2,   0x29 => 0x02d2,   0x2a => 0x014d,   0x2b => 0x0185,
            0x2c => 0x02d2,   0x2d => 0x0263,   0x2e => 0x0379,   0x2f => 0x02d2,
            0x30 => 0x02d2,   0x31 => 0x022c,   0x32 => 0x02d2,   0x33 => 0x029b,
            0x34 => 0x022c,   0x35 => 0x0263,   0x36 => 0x02d2,   0x37 => 0x02d2,
            0x38 => 0x03b0,   0x39 => 0x02d2,   0x3a => 0x02d2,   0x3b => 0x0263,
            0x3c => 0x014d,   0x3d => 0x0116,   0x3e => 0x014d,   0x3f => 0x01d5,
            0x40 => 0x01f4,   0x41 => 0x014d,   0x42 => 0x01bc,   0x43 => 0x01f4,
            0x44 => 0x01bc,   0x45 => 0x01f4,   0x46 => 0x01bc,   0x47 => 0x014d,
            0x48 => 0x01f4,   0x49 => 0x01f4,   0x4a => 0x0116,   0x4b => 0x0116,
            0x4c => 0x01f4,   0x4d => 0x0116,   0x4e => 0x030a,   0x4f => 0x01f4,
            0x50 => 0x01f4,   0x51 => 0x01f4,   0x52 => 0x01f4,   0x53 => 0x014d,
            0x54 => 0x0185,   0x55 => 0x0116,   0x56 => 0x01f4,   0x57 => 0x01f4,
            0x58 => 0x02d2,   0x59 => 0x01f4,   0x5a => 0x01f4,   0x5b => 0x01bc,
            0x5c => 0x01e0,   0x5d =>   0xc8,   0x5e => 0x01e0,   0x5f => 0x021d,
            0x60 => 0x014d,   0x61 => 0x01f4,   0x62 => 0x01f4,   0x63 =>   0xa7,
            0x64 => 0x01f4,   0x65 => 0x01f4,   0x66 => 0x01f4,   0x67 => 0x01f4,
            0x68 =>   0xb4,   0x69 => 0x01bc,   0x6a => 0x01f4,   0x6b => 0x014d,
            0x6c => 0x014d,   0x6d => 0x022c,   0x6e => 0x022c,   0x6f => 0x01f4,
            0x70 => 0x01f4,   0x71 => 0x01f4,   0x72 =>   0xfa,   0x73 => 0x01c5,
            0x74 => 0x015e,   0x75 => 0x014d,   0x76 => 0x01bc,   0x77 => 0x01bc,
            0x78 => 0x01f4,   0x79 => 0x03e8,   0x7a => 0x03e8,   0x7b => 0x01bc,
            0x7c => 0x014d,   0x7d => 0x014d,   0x7e => 0x014d,   0x7f => 0x014d,
            0x80 => 0x014d,   0x81 => 0x014d,   0x82 => 0x014d,   0x83 => 0x014d,
            0x84 => 0x014d,   0x85 => 0x014d,   0x86 => 0x014d,   0x87 => 0x014d,
            0x88 => 0x014d,   0x89 => 0x03e8,   0x8a => 0x0379,   0x8b => 0x0114,
            0x8c => 0x0263,   0x8d => 0x02d2,   0x8e => 0x0379,   0x8f => 0x0136,
            0x90 => 0x029b,   0x91 => 0x0116,   0x92 => 0x0116,   0x93 => 0x01f4,
            0x94 => 0x02d2,   0x95 => 0x01f4,   0x96 => 0x014d,   0x97 => 0x01bc,
            0x98 => 0x01bc,   0x99 => 0x01f4,   0x9a => 0x01bc,   0x9b => 0x02d2,
            0x9c => 0x0234,   0x9d => 0x02d2,   0x9e => 0x02d2,   0x9f => 0x01bc,
            0xa0 => 0x02d2,   0xa1 => 0x01f4,   0xa2 => 0x0185,   0xa3 => 0x01bc,
            0xa4 => 0x02d2,   0xa5 => 0x02d2,   0xa6 => 0x01bc,   0xa7 => 0x02d2,
            0xa8 => 0x01f4,   0xa9 => 0x0263,   0xaa => 0x02d2,   0xab =>   0xfa,
            0xac => 0x02f8,   0xad => 0x0263,   0xae => 0x01bc,   0xaf => 0x01bc,
            0xb0 => 0x02d2,   0xb1 => 0x0116,   0xb2 => 0x01bc,   0xb3 => 0x0263,
            0xb4 => 0x029b,   0xb5 => 0x01bc,   0xb6 => 0x0263,   0xb7 => 0x0185,
            0xb8 => 0x0185,   0xb9 => 0x0116,   0xba => 0x01d7,   0xbb => 0x029b,
            0xbc => 0x02d2,   0xbd => 0x01f4,   0xbe => 0x01bc,   0xbf => 0x02d2,
            0xc0 => 0x014d,   0xc1 => 0x01bc,   0xc2 => 0x0263,   0xc3 => 0x022c,
            0xc4 => 0x02d2,   0xc5 => 0x029b,   0xc6 => 0x022c,   0xc7 => 0x024c,
            0xc8 => 0x02d2,   0xc9 => 0x01f4,   0xca => 0x012c,   0xcb => 0x02d2,
            0xcc => 0x02d2,   0xcd => 0x02d2,   0xce => 0x0234,   0xcf => 0x01f4,
            0xd0 => 0x0263,   0xd1 => 0x01dc,   0xd2 => 0x01f4,   0xd3 => 0x02d2,
            0xd4 => 0x0116,   0xd5 => 0x0263,   0xd6 => 0x01bc,   0xd7 => 0x01bc,
            0xd8 => 0x01bc,   0xd9 => 0x01f4,   0xda => 0x01f4,   0xdb => 0x02d2,
            0xdc => 0x014d,   0xdd => 0x0234,   0xde =>   0xc8,   0xdf => 0x02f8,
            0xe0 => 0x02d2,   0xe1 => 0x014d,   0xe2 => 0x0258,   0xe3 => 0x0263,
            0xe4 => 0x014d,   0xe5 => 0x01f4,   0xe6 => 0x0263,   0xe7 => 0x0263,
            0xe8 => 0x0225,   0xe9 => 0x02d2,   0xea => 0x029b,   0xeb => 0x0116,
            0xec => 0x0146,   0xed => 0x01bc,   0xee => 0x02d2,   0xef => 0x02d2,
            0xf0 => 0x02d2,   0xf1 => 0x01bc,   0xf2 => 0x01bc,   0xf3 => 0x0116,
            0xf4 => 0x02d2,   0xf5 => 0x01f4,   0xf6 => 0x01bc,   0xf7 => 0x0185,
            0xf8 => 0x0116,   0xf9 => 0x02d2,   0xfa => 0x02d2,   0xfb => 0x0264,
            0xfc => 0x01f4,   0xfd => 0x012c,   0xfe => 0x02d2,   0xff => 0x01f4,
          0x0100 => 0x0116, 0x0101 => 0x01f4, 0x0102 => 0x0263, 0x0103 => 0x01f4,
          0x0104 => 0x02ee, 0x0105 => 0x022c, 0x0106 => 0x0158, 0x0107 => 0x02d2,
          0x0108 => 0x0263, 0x0109 => 0x03d4, 0x010a => 0x01bc, 0x010b => 0x014d,
          0x010c => 0x014d, 0x010d => 0x0263, 0x010e => 0x02ee, 0x010f => 0x0225,
          0x0110 => 0x01f4, 0x0111 => 0x01f4, 0x0112 => 0x02d2, 0x0113 => 0x0263,
          0x0114 => 0x01bc, 0x0115 => 0x01f4, 0x0116 => 0x02ee, 0x0117 => 0x022c,
          0x0118 => 0x022c, 0x0119 => 0x02d2, 0x011a => 0x0190, 0x011b => 0x01f4,
          0x011c => 0x029b, 0x011d => 0x01f4, 0x011e => 0x01c5, 0x011f => 0x02d2,
          0x0120 => 0x014d, 0x0121 => 0x02d2, 0x0122 => 0x01f4, 0x0123 => 0x029b,
          0x0124 => 0x0263, 0x0125 => 0x02d2, 0x0126 => 0x02d2, 0x0127 => 0x02d2,
          0x0128 => 0x02d2, 0x0129 => 0x01bc, 0x012a => 0x0263, 0x012b => 0x014d,
          0x012c => 0x01f4, 0x012d => 0x0234, 0x012e => 0x014d, 0x012f => 0x01f4,
          0x0130 => 0x0116, 0x0131 => 0x0234, 0x0132 => 0x01f4, 0x0133 => 0x01f4,
          0x0134 => 0x0225, 0x0135 => 0x01f4, 0x0136 => 0x01f4, 0x0137 => 0x01bc,
          0x0138 => 0x01f4, 0x0139 => 0x012c, 0x013a => 0x0116, 0x013b => 0x01f4,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Times-Roman');
    }

}
Pdf/Resource/Font/Simple/Standard/Courier.php000066600000044245151256604610015107 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Courier.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_Courier extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x39\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x30\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x31\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x32\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x33\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x37\x00"
          . "\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00\x20\x00\x53\x00"
          . "\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00\x20\x00\x49\x00"
          . "\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00\x72\x00\x61\x00"
          . "\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00\x41\x00\x6c\x00"
          . "\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00\x74\x00\x73\x00"
          . "\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00\x76\x00\x65\x00"
          . "\x64\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x35\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72\x00\x20\x00"
          . "\x4d\x00\x65\x00\x64\x00\x69\x00\x75\x00\x6d";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x33\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x43\x00\x6f\x00\x75\x00\x72\x00\x69\x00\x65\x00\x72";

        $this->_isBold = false;
        $this->_isItalic = false;
        $this->_isMonospaced = true;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 629;
        $this->_descent = -157;
        $this->_lineGap = 414;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0258,   0x02 => 0x0258,   0x03 => 0x0258,
            0x04 => 0x0258,   0x05 => 0x0258,   0x06 => 0x0258,   0x07 => 0x0258,
            0x08 => 0x0258,   0x09 => 0x0258,   0x0a => 0x0258,   0x0b => 0x0258,
            0x0c => 0x0258,   0x0d => 0x0258,   0x0e => 0x0258,   0x0f => 0x0258,
            0x10 => 0x0258,   0x11 => 0x0258,   0x12 => 0x0258,   0x13 => 0x0258,
            0x14 => 0x0258,   0x15 => 0x0258,   0x16 => 0x0258,   0x17 => 0x0258,
            0x18 => 0x0258,   0x19 => 0x0258,   0x1a => 0x0258,   0x1b => 0x0258,
            0x1c => 0x0258,   0x1d => 0x0258,   0x1e => 0x0258,   0x1f => 0x0258,
            0x20 => 0x0258,   0x21 => 0x0258,   0x22 => 0x0258,   0x23 => 0x0258,
            0x24 => 0x0258,   0x25 => 0x0258,   0x26 => 0x0258,   0x27 => 0x0258,
            0x28 => 0x0258,   0x29 => 0x0258,   0x2a => 0x0258,   0x2b => 0x0258,
            0x2c => 0x0258,   0x2d => 0x0258,   0x2e => 0x0258,   0x2f => 0x0258,
            0x30 => 0x0258,   0x31 => 0x0258,   0x32 => 0x0258,   0x33 => 0x0258,
            0x34 => 0x0258,   0x35 => 0x0258,   0x36 => 0x0258,   0x37 => 0x0258,
            0x38 => 0x0258,   0x39 => 0x0258,   0x3a => 0x0258,   0x3b => 0x0258,
            0x3c => 0x0258,   0x3d => 0x0258,   0x3e => 0x0258,   0x3f => 0x0258,
            0x40 => 0x0258,   0x41 => 0x0258,   0x42 => 0x0258,   0x43 => 0x0258,
            0x44 => 0x0258,   0x45 => 0x0258,   0x46 => 0x0258,   0x47 => 0x0258,
            0x48 => 0x0258,   0x49 => 0x0258,   0x4a => 0x0258,   0x4b => 0x0258,
            0x4c => 0x0258,   0x4d => 0x0258,   0x4e => 0x0258,   0x4f => 0x0258,
            0x50 => 0x0258,   0x51 => 0x0258,   0x52 => 0x0258,   0x53 => 0x0258,
            0x54 => 0x0258,   0x55 => 0x0258,   0x56 => 0x0258,   0x57 => 0x0258,
            0x58 => 0x0258,   0x59 => 0x0258,   0x5a => 0x0258,   0x5b => 0x0258,
            0x5c => 0x0258,   0x5d => 0x0258,   0x5e => 0x0258,   0x5f => 0x0258,
            0x60 => 0x0258,   0x61 => 0x0258,   0x62 => 0x0258,   0x63 => 0x0258,
            0x64 => 0x0258,   0x65 => 0x0258,   0x66 => 0x0258,   0x67 => 0x0258,
            0x68 => 0x0258,   0x69 => 0x0258,   0x6a => 0x0258,   0x6b => 0x0258,
            0x6c => 0x0258,   0x6d => 0x0258,   0x6e => 0x0258,   0x6f => 0x0258,
            0x70 => 0x0258,   0x71 => 0x0258,   0x72 => 0x0258,   0x73 => 0x0258,
            0x74 => 0x0258,   0x75 => 0x0258,   0x76 => 0x0258,   0x77 => 0x0258,
            0x78 => 0x0258,   0x79 => 0x0258,   0x7a => 0x0258,   0x7b => 0x0258,
            0x7c => 0x0258,   0x7d => 0x0258,   0x7e => 0x0258,   0x7f => 0x0258,
            0x80 => 0x0258,   0x81 => 0x0258,   0x82 => 0x0258,   0x83 => 0x0258,
            0x84 => 0x0258,   0x85 => 0x0258,   0x86 => 0x0258,   0x87 => 0x0258,
            0x88 => 0x0258,   0x89 => 0x0258,   0x8a => 0x0258,   0x8b => 0x0258,
            0x8c => 0x0258,   0x8d => 0x0258,   0x8e => 0x0258,   0x8f => 0x0258,
            0x90 => 0x0258,   0x91 => 0x0258,   0x92 => 0x0258,   0x93 => 0x0258,
            0x94 => 0x0258,   0x95 => 0x0258,   0x96 => 0x0258,   0x97 => 0x0258,
            0x98 => 0x0258,   0x99 => 0x0258,   0x9a => 0x0258,   0x9b => 0x0258,
            0x9c => 0x0258,   0x9d => 0x0258,   0x9e => 0x0258,   0x9f => 0x0258,
            0xa0 => 0x0258,   0xa1 => 0x0258,   0xa2 => 0x0258,   0xa3 => 0x0258,
            0xa4 => 0x0258,   0xa5 => 0x0258,   0xa6 => 0x0258,   0xa7 => 0x0258,
            0xa8 => 0x0258,   0xa9 => 0x0258,   0xaa => 0x0258,   0xab => 0x0258,
            0xac => 0x0258,   0xad => 0x0258,   0xae => 0x0258,   0xaf => 0x0258,
            0xb0 => 0x0258,   0xb1 => 0x0258,   0xb2 => 0x0258,   0xb3 => 0x0258,
            0xb4 => 0x0258,   0xb5 => 0x0258,   0xb6 => 0x0258,   0xb7 => 0x0258,
            0xb8 => 0x0258,   0xb9 => 0x0258,   0xba => 0x0258,   0xbb => 0x0258,
            0xbc => 0x0258,   0xbd => 0x0258,   0xbe => 0x0258,   0xbf => 0x0258,
            0xc0 => 0x0258,   0xc1 => 0x0258,   0xc2 => 0x0258,   0xc3 => 0x0258,
            0xc4 => 0x0258,   0xc5 => 0x0258,   0xc6 => 0x0258,   0xc7 => 0x0258,
            0xc8 => 0x0258,   0xc9 => 0x0258,   0xca => 0x0258,   0xcb => 0x0258,
            0xcc => 0x0258,   0xcd => 0x0258,   0xce => 0x0258,   0xcf => 0x0258,
            0xd0 => 0x0258,   0xd1 => 0x0258,   0xd2 => 0x0258,   0xd3 => 0x0258,
            0xd4 => 0x0258,   0xd5 => 0x0258,   0xd6 => 0x0258,   0xd7 => 0x0258,
            0xd8 => 0x0258,   0xd9 => 0x0258,   0xda => 0x0258,   0xdb => 0x0258,
            0xdc => 0x0258,   0xdd => 0x0258,   0xde => 0x0258,   0xdf => 0x0258,
            0xe0 => 0x0258,   0xe1 => 0x0258,   0xe2 => 0x0258,   0xe3 => 0x0258,
            0xe4 => 0x0258,   0xe5 => 0x0258,   0xe6 => 0x0258,   0xe7 => 0x0258,
            0xe8 => 0x0258,   0xe9 => 0x0258,   0xea => 0x0258,   0xeb => 0x0258,
            0xec => 0x0258,   0xed => 0x0258,   0xee => 0x0258,   0xef => 0x0258,
            0xf0 => 0x0258,   0xf1 => 0x0258,   0xf2 => 0x0258,   0xf3 => 0x0258,
            0xf4 => 0x0258,   0xf5 => 0x0258,   0xf6 => 0x0258,   0xf7 => 0x0258,
            0xf8 => 0x0258,   0xf9 => 0x0258,   0xfa => 0x0258,   0xfb => 0x0258,
            0xfc => 0x0258,   0xfd => 0x0258,   0xfe => 0x0258,   0xff => 0x0258,
          0x0100 => 0x0258, 0x0101 => 0x0258, 0x0102 => 0x0258, 0x0103 => 0x0258,
          0x0104 => 0x0258, 0x0105 => 0x0258, 0x0106 => 0x0258, 0x0107 => 0x0258,
          0x0108 => 0x0258, 0x0109 => 0x0258, 0x010a => 0x0258, 0x010b => 0x0258,
          0x010c => 0x0258, 0x010d => 0x0258, 0x010e => 0x0258, 0x010f => 0x0258,
          0x0110 => 0x0258, 0x0111 => 0x0258, 0x0112 => 0x0258, 0x0113 => 0x0258,
          0x0114 => 0x0258, 0x0115 => 0x0258, 0x0116 => 0x0258, 0x0117 => 0x0258,
          0x0118 => 0x0258, 0x0119 => 0x0258, 0x011a => 0x0258, 0x011b => 0x0258,
          0x011c => 0x0258, 0x011d => 0x0258, 0x011e => 0x0258, 0x011f => 0x0258,
          0x0120 => 0x0258, 0x0121 => 0x0258, 0x0122 => 0x0258, 0x0123 => 0x0258,
          0x0124 => 0x0258, 0x0125 => 0x0258, 0x0126 => 0x0258, 0x0127 => 0x0258,
          0x0128 => 0x0258, 0x0129 => 0x0258, 0x012a => 0x0258, 0x012b => 0x0258,
          0x012c => 0x0258, 0x012d => 0x0258, 0x012e => 0x0258, 0x012f => 0x0258,
          0x0130 => 0x0258, 0x0131 => 0x0258, 0x0132 => 0x0258, 0x0133 => 0x0258,
          0x0134 => 0x0258, 0x0135 => 0x0258, 0x0136 => 0x0258, 0x0137 => 0x0258,
          0x0138 => 0x0258, 0x0139 => 0x0258, 0x013a => 0x0258, 0x013b => 0x0258,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Courier');
    }

}
Pdf/Resource/Font/Simple/Standard/HelveticaBold.php000066600000045701151256604610016202 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Helvetica-Bold.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_HelveticaBold extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x37\x00\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00"
          . "\x20\x00\x53\x00\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00"
          . "\x20\x00\x49\x00\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00"
          . "\x72\x00\x61\x00\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00"
          . "\x41\x00\x6c\x00\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x73\x00\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00"
          . "\x76\x00\x65\x00\x64\x00\x2e\x00\x48\x00\x65\x00\x6c\x00\x76\x00"
          . "\x65\x00\x74\x00\x69\x00\x63\x00\x61\x00\x20\x00\x69\x00\x73\x00"
          . "\x20\x00\x61\x00\x20\x00\x74\x00\x72\x00\x61\x00\x64\x00\x65\x00"
          . "\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00\x66\x00\x20\x00"
          . "\x4c\x00\x69\x00\x6e\x00\x6f\x00\x74\x00\x79\x00\x70\x00\x65\x00"
          . "\x2d\x00\x48\x00\x65\x00\x6c\x00\x6c\x00\x20\x00\x41\x00\x47\x00"
          . "\x20\x00\x61\x00\x6e\x00\x64\x00\x2f\x00\x6f\x00\x72\x00\x20\x00"
          . "\x69\x00\x74\x00\x73\x00\x20\x00\x73\x00\x75\x00\x62\x00\x73\x00"
          . "\x69\x00\x64\x00\x69\x00\x61\x00\x72\x00\x69\x00\x65\x00\x73\x00"
          . "\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x35\x00\x32";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61\x00\x2d\x00\x42\x00\x6f\x00\x6c\x00\x64\x00\x20\x00\x42\x00"
          . "\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x48\x00\x65\x00\x6c\x00\x76\x00\x65\x00\x74\x00\x69\x00\x63\x00"
          . "\x61\x00\x2d\x00\x42\x00\x6f\x00\x6c\x00\x64";

        $this->_isBold = true;
        $this->_isItalic = false;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 718;
        $this->_descent = -207;
        $this->_lineGap = 275;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 => 0x0116,   0x02 => 0x014d,   0x03 => 0x01da,
            0x04 => 0x022c,   0x05 => 0x022c,   0x06 => 0x0379,   0x07 => 0x02d2,
            0x08 => 0x0116,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x0185,
            0x0c => 0x0248,   0x0d => 0x0116,   0x0e => 0x014d,   0x0f => 0x0116,
            0x10 => 0x0116,   0x11 => 0x022c,   0x12 => 0x022c,   0x13 => 0x022c,
            0x14 => 0x022c,   0x15 => 0x022c,   0x16 => 0x022c,   0x17 => 0x022c,
            0x18 => 0x022c,   0x19 => 0x022c,   0x1a => 0x022c,   0x1b => 0x014d,
            0x1c => 0x014d,   0x1d => 0x0248,   0x1e => 0x0248,   0x1f => 0x0248,
            0x20 => 0x0263,   0x21 => 0x03cf,   0x22 => 0x02d2,   0x23 => 0x02d2,
            0x24 => 0x02d2,   0x25 => 0x02d2,   0x26 => 0x029b,   0x27 => 0x0263,
            0x28 => 0x030a,   0x29 => 0x02d2,   0x2a => 0x0116,   0x2b => 0x022c,
            0x2c => 0x02d2,   0x2d => 0x0263,   0x2e => 0x0341,   0x2f => 0x02d2,
            0x30 => 0x030a,   0x31 => 0x029b,   0x32 => 0x030a,   0x33 => 0x02d2,
            0x34 => 0x029b,   0x35 => 0x0263,   0x36 => 0x02d2,   0x37 => 0x029b,
            0x38 => 0x03b0,   0x39 => 0x029b,   0x3a => 0x029b,   0x3b => 0x0263,
            0x3c => 0x014d,   0x3d => 0x0116,   0x3e => 0x014d,   0x3f => 0x0248,
            0x40 => 0x022c,   0x41 => 0x0116,   0x42 => 0x022c,   0x43 => 0x0263,
            0x44 => 0x022c,   0x45 => 0x0263,   0x46 => 0x022c,   0x47 => 0x014d,
            0x48 => 0x0263,   0x49 => 0x0263,   0x4a => 0x0116,   0x4b => 0x0116,
            0x4c => 0x022c,   0x4d => 0x0116,   0x4e => 0x0379,   0x4f => 0x0263,
            0x50 => 0x0263,   0x51 => 0x0263,   0x52 => 0x0263,   0x53 => 0x0185,
            0x54 => 0x022c,   0x55 => 0x014d,   0x56 => 0x0263,   0x57 => 0x022c,
            0x58 => 0x030a,   0x59 => 0x022c,   0x5a => 0x022c,   0x5b => 0x01f4,
            0x5c => 0x0185,   0x5d => 0x0118,   0x5e => 0x0185,   0x5f => 0x0248,
            0x60 => 0x014d,   0x61 => 0x022c,   0x62 => 0x022c,   0x63 =>   0xa7,
            0x64 => 0x022c,   0x65 => 0x022c,   0x66 => 0x022c,   0x67 => 0x022c,
            0x68 =>   0xee,   0x69 => 0x01f4,   0x6a => 0x022c,   0x6b => 0x014d,
            0x6c => 0x014d,   0x6d => 0x0263,   0x6e => 0x0263,   0x6f => 0x022c,
            0x70 => 0x022c,   0x71 => 0x022c,   0x72 => 0x0116,   0x73 => 0x022c,
            0x74 => 0x015e,   0x75 => 0x0116,   0x76 => 0x01f4,   0x77 => 0x01f4,
            0x78 => 0x022c,   0x79 => 0x03e8,   0x7a => 0x03e8,   0x7b => 0x0263,
            0x7c => 0x014d,   0x7d => 0x014d,   0x7e => 0x014d,   0x7f => 0x014d,
            0x80 => 0x014d,   0x81 => 0x014d,   0x82 => 0x014d,   0x83 => 0x014d,
            0x84 => 0x014d,   0x85 => 0x014d,   0x86 => 0x014d,   0x87 => 0x014d,
            0x88 => 0x014d,   0x89 => 0x03e8,   0x8a => 0x03e8,   0x8b => 0x0172,
            0x8c => 0x0263,   0x8d => 0x030a,   0x8e => 0x03e8,   0x8f => 0x016d,
            0x90 => 0x0379,   0x91 => 0x0116,   0x92 => 0x0116,   0x93 => 0x0263,
            0x94 => 0x03b0,   0x95 => 0x0263,   0x96 => 0x0116,   0x97 => 0x022c,
            0x98 => 0x022c,   0x99 => 0x0263,   0x9a => 0x022c,   0x9b => 0x029b,
            0x9c => 0x0248,   0x9d => 0x029b,   0x9e => 0x02d2,   0x9f => 0x022c,
            0xa0 => 0x02d2,   0xa1 => 0x022c,   0xa2 => 0x022c,   0xa3 => 0x022c,
            0xa4 => 0x02d2,   0xa5 => 0x02d2,   0xa6 => 0x022c,   0xa7 => 0x02d2,
            0xa8 => 0x0263,   0xa9 => 0x029b,   0xaa => 0x02d2,   0xab =>   0xfa,
            0xac => 0x02e1,   0xad => 0x029b,   0xae => 0x022c,   0xaf => 0x022c,
            0xb0 => 0x02d2,   0xb1 => 0x0116,   0xb2 => 0x022c,   0xb3 => 0x0263,
            0xb4 => 0x02d2,   0xb5 => 0x022c,   0xb6 => 0x029b,   0xb7 => 0x022c,
            0xb8 => 0x022c,   0xb9 => 0x0116,   0xba => 0x01ee,   0xbb => 0x02d2,
            0xbc => 0x030a,   0xbd => 0x0263,   0xbe => 0x022c,   0xbf => 0x02d2,
            0xc0 => 0x0185,   0xc1 => 0x022c,   0xc2 => 0x0263,   0xc3 => 0x029b,
            0xc4 => 0x030a,   0xc5 => 0x02d2,   0xc6 => 0x029b,   0xc7 => 0x02e7,
            0xc8 => 0x02d2,   0xc9 => 0x0263,   0xca => 0x014d,   0xcb => 0x030a,
            0xcc => 0x02d2,   0xcd => 0x02d2,   0xce => 0x0248,   0xcf => 0x0263,
            0xd0 => 0x0263,   0xd1 => 0x01ee,   0xd2 => 0x022c,   0xd3 => 0x02d2,
            0xd4 => 0x0116,   0xd5 => 0x029b,   0xd6 => 0x022c,   0xd7 => 0x022c,
            0xd8 => 0x022c,   0xd9 => 0x0263,   0xda => 0x0263,   0xdb => 0x02d2,
            0xdc => 0x0116,   0xdd => 0x0248,   0xde => 0x0118,   0xdf => 0x02e1,
            0xe0 => 0x030a,   0xe1 => 0x0116,   0xe2 => 0x0258,   0xe3 => 0x029b,
            0xe4 => 0x0185,   0xe5 => 0x0263,   0xe6 => 0x0263,   0xe7 => 0x0263,
            0xe8 => 0x0225,   0xe9 => 0x02d2,   0xea => 0x02d2,   0xeb => 0x0116,
            0xec => 0x0185,   0xed => 0x022c,   0xee => 0x02d2,   0xef => 0x02d2,
            0xf0 => 0x02d2,   0xf1 => 0x022c,   0xf2 => 0x01f4,   0xf3 => 0x0116,
            0xf4 => 0x030a,   0xf5 => 0x0263,   0xf6 => 0x022c,   0xf7 => 0x022c,
            0xf8 => 0x0116,   0xf9 => 0x030a,   0xfa => 0x02d2,   0xfb => 0x0264,
            0xfc => 0x0263,   0xfd => 0x014d,   0xfe => 0x030a,   0xff => 0x0263,
          0x0100 => 0x0116, 0x0101 => 0x0263, 0x0102 => 0x029b, 0x0103 => 0x0263,
          0x0104 => 0x0342, 0x0105 => 0x029b, 0x0106 => 0x0190, 0x0107 => 0x02d2,
          0x0108 => 0x0263, 0x0109 => 0x03e8, 0x010a => 0x022c, 0x010b => 0x0116,
          0x010c => 0x0116, 0x010d => 0x0263, 0x010e => 0x0342, 0x010f => 0x0225,
          0x0110 => 0x0263, 0x0111 => 0x0263, 0x0112 => 0x02d2, 0x0113 => 0x029b,
          0x0114 => 0x022c, 0x0115 => 0x0263, 0x0116 => 0x0342, 0x0117 => 0x029b,
          0x0118 => 0x029b, 0x0119 => 0x030a, 0x011a => 0x0190, 0x011b => 0x0263,
          0x011c => 0x02d2, 0x011d => 0x0263, 0x011e => 0x0225, 0x011f => 0x02d2,
          0x0120 => 0x0185, 0x0121 => 0x02d2, 0x0122 => 0x0263, 0x0123 => 0x02d2,
          0x0124 => 0x0263, 0x0125 => 0x02d2, 0x0126 => 0x02d2, 0x0127 => 0x02d2,
          0x0128 => 0x030a, 0x0129 => 0x01f4, 0x012a => 0x029b, 0x012b => 0x0116,
          0x012c => 0x022c, 0x012d => 0x0248, 0x012e => 0x0116, 0x012f => 0x0263,
          0x0130 => 0x014d, 0x0131 => 0x0248, 0x0132 => 0x0263, 0x0133 => 0x0263,
          0x0134 => 0x0225, 0x0135 => 0x0263, 0x0136 => 0x0263, 0x0137 => 0x01f4,
          0x0138 => 0x0263, 0x0139 => 0x014d, 0x013a => 0x0116, 0x013b => 0x022c,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Helvetica-Bold');
    }

}
Pdf/Resource/Font/Simple/Standard/TimesBold.php000066600000045505151256604610015361 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Pdf_Resource_Font_Simple_Standard */
require_once 'Zend/Pdf/Resource/Font/Simple/Standard.php';


/**
 * Implementation for the standard PDF font Times-Bold.
 *
 * This class was generated automatically using the font information and metric
 * data contained in the Adobe Font Metric (AFM) files, available here:
 * {@link http://partners.adobe.com/public/developer/en/pdf/Core14_AFMs.zip}
 *
 * The PHP script used to generate this class can be found in the /tools
 * directory of the framework distribution. If you need to make modifications to
 * this class, chances are the same modifications are needed for the rest of the
 * standard fonts. You should modify the script and regenerate the classes
 * instead of changing this class file by hand.
 *
 * @package    Zend_Pdf
 * @subpackage Fonts
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Resource_Font_Simple_Standard_TimesBold extends Zend_Pdf_Resource_Font_Simple_Standard
{
  /**** Public Interface ****/


  /* Object Lifecycle */

    /**
     * Object constructor
     */
    public function __construct()
    {
        parent::__construct();


        /* Object properties */

        /* The font names are stored internally as Unicode UTF-16BE-encoded
         * strings. Since this information is static, save unnecessary trips
         * through iconv() and just use pre-encoded hexidecimal strings.
         */
        $this->_fontNames[Zend_Pdf_Font::NAME_COPYRIGHT]['en'] =
          "\x00\x43\x00\x6f\x00\x70\x00\x79\x00\x72\x00\x69\x00\x67\x00\x68\x00"
          . "\x74\x00\x20\x00\x28\x00\x63\x00\x29\x00\x20\x00\x31\x00\x39\x00"
          . "\x38\x00\x35\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x37\x00"
          . "\x2c\x00\x20\x00\x31\x00\x39\x00\x38\x00\x39\x00\x2c\x00\x20\x00"
          . "\x31\x00\x39\x00\x39\x00\x30\x00\x2c\x00\x20\x00\x31\x00\x39\x00"
          . "\x39\x00\x33\x00\x2c\x00\x20\x00\x31\x00\x39\x00\x39\x00\x37\x00"
          . "\x20\x00\x41\x00\x64\x00\x6f\x00\x62\x00\x65\x00\x20\x00\x53\x00"
          . "\x79\x00\x73\x00\x74\x00\x65\x00\x6d\x00\x73\x00\x20\x00\x49\x00"
          . "\x6e\x00\x63\x00\x6f\x00\x72\x00\x70\x00\x6f\x00\x72\x00\x61\x00"
          . "\x74\x00\x65\x00\x64\x00\x2e\x00\x20\x00\x20\x00\x41\x00\x6c\x00"
          . "\x6c\x00\x20\x00\x52\x00\x69\x00\x67\x00\x68\x00\x74\x00\x73\x00"
          . "\x20\x00\x52\x00\x65\x00\x73\x00\x65\x00\x72\x00\x76\x00\x65\x00"
          . "\x64\x00\x2e\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x20\x00"
          . "\x69\x00\x73\x00\x20\x00\x61\x00\x20\x00\x74\x00\x72\x00\x61\x00"
          . "\x64\x00\x65\x00\x6d\x00\x61\x00\x72\x00\x6b\x00\x20\x00\x6f\x00"
          . "\x66\x00\x20\x00\x4c\x00\x69\x00\x6e\x00\x6f\x00\x74\x00\x79\x00"
          . "\x70\x00\x65\x00\x2d\x00\x48\x00\x65\x00\x6c\x00\x6c\x00\x20\x00"
          . "\x41\x00\x47\x00\x20\x00\x61\x00\x6e\x00\x64\x00\x2f\x00\x6f\x00"
          . "\x72\x00\x20\x00\x69\x00\x74\x00\x73\x00\x20\x00\x73\x00\x75\x00"
          . "\x62\x00\x73\x00\x69\x00\x64\x00\x69\x00\x61\x00\x72\x00\x69\x00"
          . "\x65\x00\x73\x00\x2e";
        $this->_fontNames[Zend_Pdf_Font::NAME_FAMILY]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73";
        $this->_fontNames[Zend_Pdf_Font::NAME_STYLE]['en'] =
          "\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_ID]['en'] =
          "\x00\x34\x00\x33\x00\x30\x00\x36\x00\x35";
        $this->_fontNames[Zend_Pdf_Font::NAME_FULL]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x2d\x00\x42\x00\x6f\x00"
          . "\x6c\x00\x64\x00\x20\x00\x42\x00\x6f\x00\x6c\x00\x64";
        $this->_fontNames[Zend_Pdf_Font::NAME_VERSION]['en'] =
          "\x00\x30\x00\x30\x00\x32\x00\x2e\x00\x30\x00\x30\x00\x30";
        $this->_fontNames[Zend_Pdf_Font::NAME_POSTSCRIPT]['en'] =
          "\x00\x54\x00\x69\x00\x6d\x00\x65\x00\x73\x00\x2d\x00\x42\x00\x6f\x00"
          . "\x6c\x00\x64";

        $this->_isBold = true;
        $this->_isItalic = false;
        $this->_isMonospaced = false;

        $this->_underlinePosition = -100;
        $this->_underlineThickness = 50;
        $this->_strikePosition = 225;
        $this->_strikeThickness = 50;

        $this->_unitsPerEm = 1000;

        $this->_ascent  = 683;
        $this->_descent = -217;
        $this->_lineGap = 300;

        /* The glyph numbers assigned here are synthetic; they do not match the
         * actual glyph numbers used by the font. This is not a big deal though
         * since this data never makes it to the PDF file. It is only used
         * internally for layout calculations.
         */
        $this->_glyphWidths = array(
            0x00 => 0x01f4,   0x01 =>   0xfa,   0x02 => 0x014d,   0x03 => 0x022b,
            0x04 => 0x01f4,   0x05 => 0x01f4,   0x06 => 0x03e8,   0x07 => 0x0341,
            0x08 => 0x014d,   0x09 => 0x014d,   0x0a => 0x014d,   0x0b => 0x01f4,
            0x0c => 0x023a,   0x0d =>   0xfa,   0x0e => 0x014d,   0x0f =>   0xfa,
            0x10 => 0x0116,   0x11 => 0x01f4,   0x12 => 0x01f4,   0x13 => 0x01f4,
            0x14 => 0x01f4,   0x15 => 0x01f4,   0x16 => 0x01f4,   0x17 => 0x01f4,
            0x18 => 0x01f4,   0x19 => 0x01f4,   0x1a => 0x01f4,   0x1b => 0x014d,
            0x1c => 0x014d,   0x1d => 0x023a,   0x1e => 0x023a,   0x1f => 0x023a,
            0x20 => 0x01f4,   0x21 => 0x03a2,   0x22 => 0x02d2,   0x23 => 0x029b,
            0x24 => 0x02d2,   0x25 => 0x02d2,   0x26 => 0x029b,   0x27 => 0x0263,
            0x28 => 0x030a,   0x29 => 0x030a,   0x2a => 0x0185,   0x2b => 0x01f4,
            0x2c => 0x030a,   0x2d => 0x029b,   0x2e => 0x03b0,   0x2f => 0x02d2,
            0x30 => 0x030a,   0x31 => 0x0263,   0x32 => 0x030a,   0x33 => 0x02d2,
            0x34 => 0x022c,   0x35 => 0x029b,   0x36 => 0x02d2,   0x37 => 0x02d2,
            0x38 => 0x03e8,   0x39 => 0x02d2,   0x3a => 0x02d2,   0x3b => 0x029b,
            0x3c => 0x014d,   0x3d => 0x0116,   0x3e => 0x014d,   0x3f => 0x0245,
            0x40 => 0x01f4,   0x41 => 0x014d,   0x42 => 0x01f4,   0x43 => 0x022c,
            0x44 => 0x01bc,   0x45 => 0x022c,   0x46 => 0x01bc,   0x47 => 0x014d,
            0x48 => 0x01f4,   0x49 => 0x022c,   0x4a => 0x0116,   0x4b => 0x014d,
            0x4c => 0x022c,   0x4d => 0x0116,   0x4e => 0x0341,   0x4f => 0x022c,
            0x50 => 0x01f4,   0x51 => 0x022c,   0x52 => 0x022c,   0x53 => 0x01bc,
            0x54 => 0x0185,   0x55 => 0x014d,   0x56 => 0x022c,   0x57 => 0x01f4,
            0x58 => 0x02d2,   0x59 => 0x01f4,   0x5a => 0x01f4,   0x5b => 0x01bc,
            0x5c => 0x018a,   0x5d =>   0xdc,   0x5e => 0x018a,   0x5f => 0x0208,
            0x60 => 0x014d,   0x61 => 0x01f4,   0x62 => 0x01f4,   0x63 =>   0xa7,
            0x64 => 0x01f4,   0x65 => 0x01f4,   0x66 => 0x01f4,   0x67 => 0x01f4,
            0x68 => 0x0116,   0x69 => 0x01f4,   0x6a => 0x01f4,   0x6b => 0x014d,
            0x6c => 0x014d,   0x6d => 0x022c,   0x6e => 0x022c,   0x6f => 0x01f4,
            0x70 => 0x01f4,   0x71 => 0x01f4,   0x72 =>   0xfa,   0x73 => 0x021c,
            0x74 => 0x015e,   0x75 => 0x014d,   0x76 => 0x01f4,   0x77 => 0x01f4,
            0x78 => 0x01f4,   0x79 => 0x03e8,   0x7a => 0x03e8,   0x7b => 0x01f4,
            0x7c => 0x014d,   0x7d => 0x014d,   0x7e => 0x014d,   0x7f => 0x014d,
            0x80 => 0x014d,   0x81 => 0x014d,   0x82 => 0x014d,   0x83 => 0x014d,
            0x84 => 0x014d,   0x85 => 0x014d,   0x86 => 0x014d,   0x87 => 0x014d,
            0x88 => 0x014d,   0x89 => 0x03e8,   0x8a => 0x03e8,   0x8b => 0x012c,
            0x8c => 0x029b,   0x8d => 0x030a,   0x8e => 0x03e8,   0x8f => 0x014a,
            0x90 => 0x02d2,   0x91 => 0x0116,   0x92 => 0x0116,   0x93 => 0x01f4,
            0x94 => 0x02d2,   0x95 => 0x022c,   0x96 => 0x0185,   0x97 => 0x01bc,
            0x98 => 0x01f4,   0x99 => 0x022c,   0x9a => 0x01bc,   0x9b => 0x02d2,
            0x9c => 0x023a,   0x9d => 0x02d2,   0x9e => 0x02d2,   0x9f => 0x01f4,
            0xa0 => 0x02d2,   0xa1 => 0x01f4,   0xa2 => 0x0185,   0xa3 => 0x01bc,
            0xa4 => 0x02d2,   0xa5 => 0x02d2,   0xa6 => 0x01f4,   0xa7 => 0x02d2,
            0xa8 => 0x022c,   0xa9 => 0x029b,   0xaa => 0x02d2,   0xab =>   0xfa,
            0xac => 0x02eb,   0xad => 0x029b,   0xae => 0x01bc,   0xaf => 0x01f4,
            0xb0 => 0x02d2,   0xb1 => 0x0116,   0xb2 => 0x01f4,   0xb3 => 0x029b,
            0xb4 => 0x02d2,   0xb5 => 0x01f4,   0xb6 => 0x029b,   0xb7 => 0x0185,
            0xb8 => 0x0185,   0xb9 => 0x0116,   0xba => 0x01ee,   0xbb => 0x02d2,
            0xbc => 0x030a,   0xbd => 0x022c,   0xbe => 0x01f4,   0xbf => 0x02d2,
            0xc0 => 0x01bc,   0xc1 => 0x01bc,   0xc2 => 0x029b,   0xc3 => 0x0263,
            0xc4 => 0x030a,   0xc5 => 0x02d2,   0xc6 => 0x022c,   0xc7 => 0x02a0,
            0xc8 => 0x02d2,   0xc9 => 0x022c,   0xca => 0x012c,   0xcb => 0x030a,
            0xcc => 0x02d2,   0xcd => 0x02d2,   0xce => 0x023a,   0xcf => 0x022c,
            0xd0 => 0x029b,   0xd1 => 0x01ee,   0xd2 => 0x01f4,   0xd3 => 0x02d2,
            0xd4 => 0x0116,   0xd5 => 0x029b,   0xd6 => 0x01f4,   0xd7 => 0x01bc,
            0xd8 => 0x01bc,   0xd9 => 0x022c,   0xda => 0x022c,   0xdb => 0x02d2,
            0xdc => 0x0185,   0xdd => 0x023a,   0xde =>   0xdc,   0xdf => 0x02eb,
            0xe0 => 0x030a,   0xe1 => 0x0185,   0xe2 => 0x0258,   0xe3 => 0x029b,
            0xe4 => 0x01bc,   0xe5 => 0x01f4,   0xe6 => 0x029b,   0xe7 => 0x029b,
            0xe8 => 0x0225,   0xe9 => 0x02d2,   0xea => 0x02d2,   0xeb => 0x0116,
            0xec => 0x01a0,   0xed => 0x01bc,   0xee => 0x02d2,   0xef => 0x02d2,
            0xf0 => 0x02d2,   0xf1 => 0x01bc,   0xf2 => 0x01bc,   0xf3 => 0x0116,
            0xf4 => 0x030a,   0xf5 => 0x01f4,   0xf6 => 0x01f4,   0xf7 => 0x0185,
            0xf8 => 0x0116,   0xf9 => 0x030a,   0xfa => 0x02d2,   0xfb => 0x0264,
            0xfc => 0x022c,   0xfd => 0x012c,   0xfe => 0x030a,   0xff => 0x022c,
          0x0100 => 0x0116, 0x0101 => 0x01f4, 0x0102 => 0x029b, 0x0103 => 0x022c,
          0x0104 => 0x02ee, 0x0105 => 0x022c, 0x0106 => 0x018a, 0x0107 => 0x030a,
          0x0108 => 0x029b, 0x0109 => 0x03e8, 0x010a => 0x01bc, 0x010b => 0x0185,
          0x010c => 0x0185, 0x010d => 0x029b, 0x010e => 0x02ee, 0x010f => 0x0225,
          0x0110 => 0x01f4, 0x0111 => 0x022c, 0x0112 => 0x02d2, 0x0113 => 0x029b,
          0x0114 => 0x01bc, 0x0115 => 0x01f4, 0x0116 => 0x02ee, 0x0117 => 0x022c,
          0x0118 => 0x022c, 0x0119 => 0x030a, 0x011a => 0x0190, 0x011b => 0x01f4,
          0x011c => 0x02d2, 0x011d => 0x022c, 0x011e => 0x0225, 0x011f => 0x02d2,
          0x0120 => 0x01bc, 0x0121 => 0x02d2, 0x0122 => 0x01f4, 0x0123 => 0x02d2,
          0x0124 => 0x029b, 0x0125 => 0x02d2, 0x0126 => 0x02d2, 0x0127 => 0x02d2,
          0x0128 => 0x030a, 0x0129 => 0x01bc, 0x012a => 0x029b, 0x012b => 0x0185,
          0x012c => 0x022c, 0x012d => 0x023a, 0x012e => 0x0185, 0x012f => 0x022c,
          0x0130 => 0x014d, 0x0131 => 0x023a, 0x0132 => 0x01f4, 0x0133 => 0x022c,
          0x0134 => 0x0225, 0x0135 => 0x01f4, 0x0136 => 0x01f4, 0x0137 => 0x01bc,
          0x0138 => 0x022c, 0x0139 => 0x012c, 0x013a => 0x0116, 0x013b => 0x01f4,
        );

        /* The cmap table is similarly synthesized.
         */
        $cmapData = array(
            0x20 =>   0x01,   0x21 =>   0x02,   0x22 =>   0x03,   0x23 =>   0x04,
            0x24 =>   0x05,   0x25 =>   0x06,   0x26 =>   0x07, 0x2019 =>   0x08,
            0x28 =>   0x09,   0x29 =>   0x0a,   0x2a =>   0x0b,   0x2b =>   0x0c,
            0x2c =>   0x0d,   0x2d =>   0x0e,   0x2e =>   0x0f,   0x2f =>   0x10,
            0x30 =>   0x11,   0x31 =>   0x12,   0x32 =>   0x13,   0x33 =>   0x14,
            0x34 =>   0x15,   0x35 =>   0x16,   0x36 =>   0x17,   0x37 =>   0x18,
            0x38 =>   0x19,   0x39 =>   0x1a,   0x3a =>   0x1b,   0x3b =>   0x1c,
            0x3c =>   0x1d,   0x3d =>   0x1e,   0x3e =>   0x1f,   0x3f =>   0x20,
            0x40 =>   0x21,   0x41 =>   0x22,   0x42 =>   0x23,   0x43 =>   0x24,
            0x44 =>   0x25,   0x45 =>   0x26,   0x46 =>   0x27,   0x47 =>   0x28,
            0x48 =>   0x29,   0x49 =>   0x2a,   0x4a =>   0x2b,   0x4b =>   0x2c,
            0x4c =>   0x2d,   0x4d =>   0x2e,   0x4e =>   0x2f,   0x4f =>   0x30,
            0x50 =>   0x31,   0x51 =>   0x32,   0x52 =>   0x33,   0x53 =>   0x34,
            0x54 =>   0x35,   0x55 =>   0x36,   0x56 =>   0x37,   0x57 =>   0x38,
            0x58 =>   0x39,   0x59 =>   0x3a,   0x5a =>   0x3b,   0x5b =>   0x3c,
            0x5c =>   0x3d,   0x5d =>   0x3e,   0x5e =>   0x3f,   0x5f =>   0x40,
          0x2018 =>   0x41,   0x61 =>   0x42,   0x62 =>   0x43,   0x63 =>   0x44,
            0x64 =>   0x45,   0x65 =>   0x46,   0x66 =>   0x47,   0x67 =>   0x48,
            0x68 =>   0x49,   0x69 =>   0x4a,   0x6a =>   0x4b,   0x6b =>   0x4c,
            0x6c =>   0x4d,   0x6d =>   0x4e,   0x6e =>   0x4f,   0x6f =>   0x50,
            0x70 =>   0x51,   0x71 =>   0x52,   0x72 =>   0x53,   0x73 =>   0x54,
            0x74 =>   0x55,   0x75 =>   0x56,   0x76 =>   0x57,   0x77 =>   0x58,
            0x78 =>   0x59,   0x79 =>   0x5a,   0x7a =>   0x5b,   0x7b =>   0x5c,
            0x7c =>   0x5d,   0x7d =>   0x5e,   0x7e =>   0x5f,   0xa1 =>   0x60,
            0xa2 =>   0x61,   0xa3 =>   0x62, 0x2044 =>   0x63,   0xa5 =>   0x64,
          0x0192 =>   0x65,   0xa7 =>   0x66,   0xa4 =>   0x67,   0x27 =>   0x68,
          0x201c =>   0x69,   0xab =>   0x6a, 0x2039 =>   0x6b, 0x203a =>   0x6c,
          0xfb01 =>   0x6d, 0xfb02 =>   0x6e, 0x2013 =>   0x6f, 0x2020 =>   0x70,
          0x2021 =>   0x71,   0xb7 =>   0x72,   0xb6 =>   0x73, 0x2022 =>   0x74,
          0x201a =>   0x75, 0x201e =>   0x76, 0x201d =>   0x77,   0xbb =>   0x78,
          0x2026 =>   0x79, 0x2030 =>   0x7a,   0xbf =>   0x7b,   0x60 =>   0x7c,
            0xb4 =>   0x7d, 0x02c6 =>   0x7e, 0x02dc =>   0x7f,   0xaf =>   0x80,
          0x02d8 =>   0x81, 0x02d9 =>   0x82,   0xa8 =>   0x83, 0x02da =>   0x84,
            0xb8 =>   0x85, 0x02dd =>   0x86, 0x02db =>   0x87, 0x02c7 =>   0x88,
          0x2014 =>   0x89,   0xc6 =>   0x8a,   0xaa =>   0x8b, 0x0141 =>   0x8c,
            0xd8 =>   0x8d, 0x0152 =>   0x8e,   0xba =>   0x8f,   0xe6 =>   0x90,
          0x0131 =>   0x91, 0x0142 =>   0x92,   0xf8 =>   0x93, 0x0153 =>   0x94,
            0xdf =>   0x95,   0xcf =>   0x96,   0xe9 =>   0x97, 0x0103 =>   0x98,
          0x0171 =>   0x99, 0x011b =>   0x9a, 0x0178 =>   0x9b,   0xf7 =>   0x9c,
            0xdd =>   0x9d,   0xc2 =>   0x9e,   0xe1 =>   0x9f,   0xdb =>   0xa0,
            0xfd =>   0xa1, 0x0219 =>   0xa2,   0xea =>   0xa3, 0x016e =>   0xa4,
            0xdc =>   0xa5, 0x0105 =>   0xa6,   0xda =>   0xa7, 0x0173 =>   0xa8,
            0xcb =>   0xa9, 0x0110 =>   0xaa, 0xf6c3 =>   0xab,   0xa9 =>   0xac,
          0x0112 =>   0xad, 0x010d =>   0xae,   0xe5 =>   0xaf, 0x0145 =>   0xb0,
          0x013a =>   0xb1,   0xe0 =>   0xb2, 0x0162 =>   0xb3, 0x0106 =>   0xb4,
            0xe3 =>   0xb5, 0x0116 =>   0xb6, 0x0161 =>   0xb7, 0x015f =>   0xb8,
            0xed =>   0xb9, 0x25ca =>   0xba, 0x0158 =>   0xbb, 0x0122 =>   0xbc,
            0xfb =>   0xbd,   0xe2 =>   0xbe, 0x0100 =>   0xbf, 0x0159 =>   0xc0,
            0xe7 =>   0xc1, 0x017b =>   0xc2,   0xde =>   0xc3, 0x014c =>   0xc4,
          0x0154 =>   0xc5, 0x015a =>   0xc6, 0x010f =>   0xc7, 0x016a =>   0xc8,
          0x016f =>   0xc9,   0xb3 =>   0xca,   0xd2 =>   0xcb,   0xc0 =>   0xcc,
          0x0102 =>   0xcd,   0xd7 =>   0xce,   0xfa =>   0xcf, 0x0164 =>   0xd0,
          0x2202 =>   0xd1,   0xff =>   0xd2, 0x0143 =>   0xd3,   0xee =>   0xd4,
            0xca =>   0xd5,   0xe4 =>   0xd6,   0xeb =>   0xd7, 0x0107 =>   0xd8,
          0x0144 =>   0xd9, 0x016b =>   0xda, 0x0147 =>   0xdb,   0xcd =>   0xdc,
            0xb1 =>   0xdd,   0xa6 =>   0xde,   0xae =>   0xdf, 0x011e =>   0xe0,
          0x0130 =>   0xe1, 0x2211 =>   0xe2,   0xc8 =>   0xe3, 0x0155 =>   0xe4,
          0x014d =>   0xe5, 0x0179 =>   0xe6, 0x017d =>   0xe7, 0x2265 =>   0xe8,
            0xd0 =>   0xe9,   0xc7 =>   0xea, 0x013c =>   0xeb, 0x0165 =>   0xec,
          0x0119 =>   0xed, 0x0172 =>   0xee,   0xc1 =>   0xef,   0xc4 =>   0xf0,
            0xe8 =>   0xf1, 0x017a =>   0xf2, 0x012f =>   0xf3,   0xd3 =>   0xf4,
            0xf3 =>   0xf5, 0x0101 =>   0xf6, 0x015b =>   0xf7,   0xef =>   0xf8,
            0xd4 =>   0xf9,   0xd9 =>   0xfa, 0x2206 =>   0xfb,   0xfe =>   0xfc,
            0xb2 =>   0xfd,   0xd6 =>   0xfe,   0xb5 =>   0xff,   0xec => 0x0100,
          0x0151 => 0x0101, 0x0118 => 0x0102, 0x0111 => 0x0103,   0xbe => 0x0104,
          0x015e => 0x0105, 0x013e => 0x0106, 0x0136 => 0x0107, 0x0139 => 0x0108,
          0x2122 => 0x0109, 0x0117 => 0x010a,   0xcc => 0x010b, 0x012a => 0x010c,
          0x013d => 0x010d,   0xbd => 0x010e, 0x2264 => 0x010f,   0xf4 => 0x0110,
            0xf1 => 0x0111, 0x0170 => 0x0112,   0xc9 => 0x0113, 0x0113 => 0x0114,
          0x011f => 0x0115,   0xbc => 0x0116, 0x0160 => 0x0117, 0x0218 => 0x0118,
          0x0150 => 0x0119,   0xb0 => 0x011a,   0xf2 => 0x011b, 0x010c => 0x011c,
            0xf9 => 0x011d, 0x221a => 0x011e, 0x010e => 0x011f, 0x0157 => 0x0120,
            0xd1 => 0x0121,   0xf5 => 0x0122, 0x0156 => 0x0123, 0x013b => 0x0124,
            0xc3 => 0x0125, 0x0104 => 0x0126,   0xc5 => 0x0127,   0xd5 => 0x0128,
          0x017c => 0x0129, 0x011a => 0x012a, 0x012e => 0x012b, 0x0137 => 0x012c,
          0x2212 => 0x012d,   0xce => 0x012e, 0x0148 => 0x012f, 0x0163 => 0x0130,
            0xac => 0x0131,   0xf6 => 0x0132,   0xfc => 0x0133, 0x2260 => 0x0134,
          0x0123 => 0x0135,   0xf0 => 0x0136, 0x017e => 0x0137, 0x0146 => 0x0138,
            0xb9 => 0x0139, 0x012b => 0x013a, 0x20ac => 0x013b);
        $this->_cmap = Zend_Pdf_Cmap::cmapWithTypeData(
          Zend_Pdf_Cmap::TYPE_BYTE_ENCODING_STATIC, $cmapData);


        /* Resource dictionary */

        /* The resource dictionary for the standard fonts is sparse because PDF
         * viewers already have all of the metrics data. We only need to provide
         * the font name and encoding method.
         */
        $this->_resource->BaseFont = new Zend_Pdf_Element_Name('Times-Bold');
    }

}
Pdf/Filter/Compression/Flate.php000066600000005472151256604610012571 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_Pdf_Filter_Compression */
require_once 'Zend/Pdf/Filter/Compression.php';


/**
 * Flate stream filter
 *
 * @package    Zend_Pdf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_Filter_Compression_Flate extends Zend_Pdf_Filter_Compression
{
    /**
     * Encode data
     *
     * @param string $data
     * @param array $params
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public static function encode($data, $params = null)
    {
        if ($params != null) {
            $data = self::_applyEncodeParams($data, $params);
        }

        if (extension_loaded('zlib')) {
            $trackErrors = ini_get( "track_errors");
            ini_set('track_errors', '1');

            if (($output = @gzcompress($data)) === false) {
                ini_set('track_errors', $trackErrors);
                throw new Zend_Pdf_Exception($php_errormsg);
            }

            ini_set('track_errors', $trackErrors);
        } else {
            throw new Zend_Pdf_Exception('Not implemented yet. You have to use zlib extension.');
        }

        return $output;
    }

    /**
     * Decode data
     *
     * @param string $data
     * @param array $params
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public static function decode($data, $params = null)
    {
        global $php_errormsg;

        if (extension_loaded('zlib')) {
            $trackErrors = ini_get( "track_errors");
            ini_set('track_errors', '1');

            if (($output = @gzuncompress($data)) === false) {
                ini_set('track_errors', $trackErrors);
                throw new Zend_Pdf_Exception($php_errormsg);
            }

            ini_set('track_errors', $trackErrors);
        } else {
            throw new Zend_Pdf_Exception('Not implemented yet');
        }

        if ($params !== null) {
            return self::_applyDecodeParams($output, $params);
        } else {
            return $output;
        }
    }
}
Pdf/Color.php000066600000002747151256604610007070 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Pdf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * PDF provides a powerfull facilities for specifying the colors of graphics objects.
 * This class encapsulates color behaviour.
 *
 * Some colors interact with PDF document (create additional objects in a PDF),
 * others don't do it. That is defined in a subclasses.
 *
 * @package    Zend_Pdf
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Pdf_Color
{
    /**
     * Instructions, which can be directly inserted into content stream
     * to switch color.
     * Color set instructions differ for stroking and nonstroking operations.
     *
     * @param boolean $stroking
     * @return string
     */
    abstract public function instructions($stroking);
}

Paginator/ScrollingStyle/Jumping.php000066600000004210151256604610013576 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Paginator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Jumping.php 10013 2008-07-09 21:08:06Z norm2782 $
 */

/**
 * @see Zend_Paginator_ScrollingStyle_Interface
 */
require_once 'Zend/Paginator/ScrollingStyle/Interface.php';

/**
 * A scrolling style in which the cursor advances to the upper bound 
 * of the page range, the page range "jumps" to the next section, and 
 * the cursor moves back to the beginning of the range.
 * 
 * @category   Zend
 * @package    Zend_Paginator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Paginator_ScrollingStyle_Jumping implements Zend_Paginator_ScrollingStyle_Interface
{
    /**
     * Returns an array of "local" pages given a page number and range.
     * 
     * @param  Zend_Paginator $paginator
     * @param  integer $pageRange Unused
     * @return array
     */
    public function getPages(Zend_Paginator $paginator, $pageRange = null)
    {
        $pageRange  = $paginator->getPageRange();
        $pageNumber = $paginator->getCurrentPageNumber();
        
        $delta = $pageNumber % $pageRange;
        
        if ($delta == 0) {
            $delta = $pageRange;
        }

        $offset     = $pageNumber - $delta;
        $lowerBound = $offset + 1; 
        $upperBound = $offset + $pageRange;
        
        return $paginator->getPagesInRange($lowerBound, $upperBound); 
    }
}Paginator/ScrollingStyle/Sliding.php000066600000005261151256604610013565 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Paginator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Sliding.php 10013 2008-07-09 21:08:06Z norm2782 $
 */

/**
 * @see Zend_Paginator_ScrollingStyle_Interface
 */
require_once 'Zend/Paginator/ScrollingStyle/Interface.php';

/**
 * A Yahoo! Search-like scrolling style.  The cursor will advance to 
 * the middle of the range, then remain there until the user reaches 
 * the end of the page set, at which point it will continue on to 
 * the end of the range and the last page in the set.
 *
 * @link       http://search.yahoo.com/search?p=Zend+Framework
 * @category   Zend
 * @package    Zend_Paginator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Paginator_ScrollingStyle_Sliding implements Zend_Paginator_ScrollingStyle_Interface
{
    /**
     * Returns an array of "local" pages given a page number and range.
     * 
     * @param  Zend_Paginator $paginator
     * @param  integer $pageRange (Optional) Page range
     * @return array
     */
    public function getPages(Zend_Paginator $paginator, $pageRange = null)
    {
        if ($pageRange === null) {
            $pageRange = $paginator->getPageRange();
        }

        $pageNumber = $paginator->getCurrentPageNumber();
        $pageCount  = count($paginator);
        
        if ($pageRange > $pageCount) {
            $pageRange = $pageCount;
        }
        
        $delta = ceil($pageRange / 2);

        if ($pageNumber - $delta > $pageCount - $pageRange) {
            $lowerBound = $pageCount - $pageRange + 1;
            $upperBound = $pageCount; 
        } else {
            if ($pageNumber - $delta < 0) {
                $delta = $pageNumber;
            }
            
            $offset     = $pageNumber - $delta;
            $lowerBound = $offset + 1; 
            $upperBound = $offset + $pageRange;
        }

        return $paginator->getPagesInRange($lowerBound, $upperBound);
    }
}Paginator/ScrollingStyle/All.php000066600000003371151256604610012704 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Paginator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: All.php 10013 2008-07-09 21:08:06Z norm2782 $
 */

/**
 * @see Zend_Paginator_ScrollingStyle_Interface
 */
require_once 'Zend/Paginator/ScrollingStyle/Interface.php';

/**
 * A scrolling style that returns every page in the collection.  
 * Useful when it is necessary to make every page available at 
 * once--for example, when using a dropdown menu pagination control.
 * 
 * @category   Zend
 * @package    Zend_Paginator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Paginator_ScrollingStyle_All implements Zend_Paginator_ScrollingStyle_Interface
{
    /**
     * Returns an array of all pages given a page number and range.
     * 
     * @param  Zend_Paginator $paginator
     * @param  integer $pageRange Unused
     * @return array
     */
    public function getPages(Zend_Paginator $paginator, $pageRange = null)
    {
        return $paginator->getPagesInRange(1, $paginator->count());
    }
}Paginator/ScrollingStyle/Elastic.php000066600000004156151256604610013562 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Paginator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Elastic.php 10013 2008-07-09 21:08:06Z norm2782 $
 */

/**
 * @see Zend_Paginator_ScrollingStyle_Sliding
 */
require_once 'Zend/Paginator/ScrollingStyle/Sliding.php';

/**
 * A Google-like scrolling style.  Incrementally expands the range to about
 * twice the given page range, then behaves like a slider.  See the example
 * link.
 * 
 * @link       http://www.google.com/search?q=Zend+Framework
 * @category   Zend
 * @package    Zend_Paginator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Paginator_ScrollingStyle_Elastic extends Zend_Paginator_ScrollingStyle_Sliding
{
    /**
     * Returns an array of "local" pages given a page number and range.
     * 
     * @param  Zend_Paginator $paginator
     * @param  integer $pageRange Unused
     * @return array
     */
    public function getPages(Zend_Paginator $paginator, $pageRange = null)
    {
        $pageRange  = $paginator->getPageRange();
        $pageNumber = $paginator->getCurrentPageNumber();

        $originalPageRange = $pageRange;
        $pageRange         = $pageRange * 2 - 1;

        if ($originalPageRange + $pageNumber - 1 < $pageRange) {
            $pageRange = $originalPageRange + $pageNumber - 1;
        }
        
        return parent::getPages($paginator, $pageRange);
    }
}Session/SaveHandler/Interface.php000066600000004130151256604610013004 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Session
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 9133 2008-04-04 13:06:09Z darby $
 * @since      Preview Release 0.2
 */

/**
 * Zend_Session_SaveHandler_Interface
 *
 * @category   Zend
 * @package    Zend_Session
 * @subpackage SaveHandler
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @see        http://php.net/session_set_save_handler
 */
interface Zend_Session_SaveHandler_Interface
{

    /**
     * Open Session - retrieve resources
     *
     * @param string $save_path
     * @param string $name
     */
    public function open($save_path, $name);

    /**
     * Close Session - free resources
     *
     */
    public function close();

    /**
     * Read session data
     *
     * @param string $id
     */
    public function read($id);

    /**
     * Write Session - commit data to resource
     *
     * @param string $id
     * @param mixed $data
     */
    public function write($id, $data);

    /**
     * Destroy Session - remove data from resource for
     * given session id
     *
     * @param string $id
     */
    public function destroy($id);

    /**
     * Garbage Collection - remove old session data older
     * than $maxlifetime (in seconds)
     *
     * @param int $maxlifetime
     */
    public function gc($maxlifetime);

}
Validate/Hostname/Interface.php000066600000003562151256604610012504 0ustar00<?php

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


/**
 * @category   Zend
 * @package    Zend_Validate
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_Validate_Hostname_Interface
{

    /**
     * Returns UTF-8 characters allowed in DNS hostnames for the specified Top-Level-Domain
     *
     * UTF-8 characters should be written as four character hex codes \x{XXXX}
     * For example é (lowercase e with acute) is represented by the hex code \x{00E9}
     *
     * You only need to include lower-case equivalents of characters since the hostname
     * check is case-insensitive
     *
     * Please document the supported TLDs in the documentation file at:
     * manual/en/module_specs/Zend_Validate-Hostname.xml
     *
     * @see http://en.wikipedia.org/wiki/Internationalized_domain_name
     * @see http://www.iana.org/cctld/ Country-Code Top-Level Domains (TLDs)
     * @see http://www.columbia.edu/kermit/utf8-t1.html UTF-8 characters
     * @return string
     */
    static function getCharacters();

}View/Helper/FormTextarea.php000066600000005720151256604610012025 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * Abstract class for extension
 */
require_once 'Zend/View/Helper/FormElement.php';


/**
 * Helper to generate a "textarea" element
 *
 * @category   Zend
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_View_Helper_FormTextarea extends Zend_View_Helper_FormElement
{
    /**
     * The default number of rows for a textarea.
     *
     * @access public
     *
     * @var int
     */
    public $rows = 24;

    /**
     * The default number of columns for a textarea.
     *
     * @access public
     *
     * @var int
     */
    public $cols = 80;

    /**
     * Generates a 'textarea' element.
     *
     * @access public
     *
     * @param string|array $name If a string, the element name.  If an
     * array, all other parameters are ignored, and the array elements
     * are extracted in place of added parameters.
     *
     * @param mixed $value The element value.
     *
     * @param array $attribs Attributes for the element tag.
     *
     * @return string The element XHTML.
     */
    public function formTextarea($name, $value = null, $attribs = null)
    {
        $info = $this->_getInfo($name, $value, $attribs);
        extract($info); // name, value, attribs, options, listsep, disable

        // is it disabled?
        $disabled = '';
        if ($disable) {
            // disabled.
            $disabled = ' disabled="disabled"';
        }

        // Make sure that there are 'rows' and 'cols' values
        // as required by the spec.  noted by Orjan Persson.
        if (empty($attribs['rows'])) {
            $attribs['rows'] = (int) $this->rows;
        }
        if (empty($attribs['cols'])) {
            $attribs['cols'] = (int) $this->cols;
        }

        // build the element
        $xhtml = '<textarea name="' . $this->view->escape($name) . '"'
                . ' id="' . $this->view->escape($id) . '"'
                . $disabled
                . $this->_htmlAttribs($attribs) . '>'
                . $this->view->escape($value) . '</textarea>';

        return $xhtml;
    }
}
View/Helper/Placeholder/Registry/Exception.php000066600000002365151256604610015416 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_View_Exception */
require_once 'Zend/View/Exception.php';


/**
 * Exception for Zend_View_Helper_Placeholder_Registry class.
 *
 * @category   Zend
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_View_Helper_Placeholder_Registry_Exception extends Zend_View_Exception
{
}
View/Helper/Placeholder/Container.php000066600000002373151256604610013571 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Container.php 9099 2008-03-30 19:35:47Z thomas $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_View_Helper_Placeholder_Container_Abstract */
require_once 'Zend/View/Helper/Placeholder/Container/Abstract.php';

/**
 * Container for placeholder values
 *
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */ 
class Zend_View_Helper_Placeholder_Container extends Zend_View_Helper_Placeholder_Container_Abstract
{  
}
View/Helper/Placeholder/Registry.php000066600000011702151256604610013453 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Registry.php 9099 2008-03-30 19:35:47Z thomas $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Registry */
require_once 'Zend/Registry.php';

/** Zend_View_Helper_Placeholder_Container_Abstract */
require_once 'Zend/View/Helper/Placeholder/Container/Abstract.php';

/** Zend_View_Helper_Placeholder_Container */
require_once 'Zend/View/Helper/Placeholder/Container.php';

/**
 * Registry for placeholder containers
 *
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */ 
class Zend_View_Helper_Placeholder_Registry
{
    /**
     * Zend_Registry key under which placeholder registry exists
     * @const string
     */
    const REGISTRY_KEY = 'Zend_View_Helper_Placeholder_Registry';

    /**
     * Default container class
     * @var string
     */
    protected $_containerClass = 'Zend_View_Helper_Placeholder_Container';

    /**
     * Placeholder containers
     * @var array
     */
    protected $_items = array();

    /**
     * Retrieve or create registry instnace
     * 
     * @return void
     */
    public static function getRegistry()
    {
        if (Zend_Registry::isRegistered(self::REGISTRY_KEY)) {
            $registry = Zend_Registry::get(self::REGISTRY_KEY);
        } else {
            $registry = new self();
            Zend_Registry::set(self::REGISTRY_KEY, $registry);
        }

        return $registry;
    }

    /**
     * createContainer 
     * 
     * @param  string $key 
     * @param  array $value 
     * @return Zend_View_Helper_Placeholder_Container_Abstract
     */
    public function createContainer($key, array $value = array())
    {
        $key = (string) $key;

        $this->_items[$key] = new $this->_containerClass(array());
        return $this->_items[$key];
    }

    /**
     * Retrieve a placeholder container
     * 
     * @param  string $key 
     * @return Zend_View_Helper_Placeholder_Container_Abstract
     */
    public function getContainer($key)
    {
        $key = (string) $key;
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        }

        $container = $this->createContainer($key);

        return $container;
    }

    /**
     * Does a particular container exist?
     * 
     * @param  string $key 
     * @return bool
     */
    public function containerExists($key)
    {
        $key = (string) $key;
        $return =  array_key_exists($key, $this->_items);
        return $return;
    }

    /**
     * Set the container for an item in the registry
     * 
     * @param  string $key 
     * @param  Zend_View_Placeholder_Container_Abstract $container 
     * @return Zend_View_Placeholder_Registry
     */
    public function setContainer($key, Zend_View_Helper_Placeholder_Container_Abstract $container)
    {
        $key = (string) $key;
        $this->_items[$key] = $container;
        return $this;
    }

    /**
     * Delete a container
     * 
     * @param  string $key 
     * @return bool
     */
    public function deleteContainer($key)
    {
        $key = (string) $key;
        if (isset($this->_items[$key])) {
            unset($this->_items[$key]);
            return true;
        }

        return false;
    }

    /**
     * Set the container class to use
     * 
     * @param  string $name 
     * @return Zend_View_Helper_Placeholder_Registry
     */
    public function setContainerClass($name)
    {
        require_once 'Zend/Loader.php';
        Zend_Loader::loadClass($name);

        $reflection = new ReflectionClass($name);
        if (!$reflection->isSubclassOf(new ReflectionClass('Zend_View_Helper_Placeholder_Container_Abstract'))) {
            require_once 'Zend/View/Helper/Placeholder/Registry/Exception.php';
            throw new Zend_View_Helper_Placeholder_Registry_Exception('Invalid Container class specified');
        }

        $this->_containerClass = $name;
        return $this;
    }

    /**
     * Retrieve the container class
     * 
     * @return string
     */
    public function getContainerClass()
    {
        return $this->_containerClass;
    }
}
View/Helper/Placeholder/Container/Abstract.php000066600000023175151256604610015337 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Abstract.php 9099 2008-03-30 19:35:47Z thomas $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Abstract class representing container for placeholder values
 *
 * @package    Zend_View
 * @subpackage Helpers
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_View_Helper_Placeholder_Container_Abstract extends ArrayObject
{
    /**
     * Whether or not to override all contents of placeholder
     * @const string
     */
    const SET    = 'SET';

    /**
     * Whether or not to append contents to placeholder
     * @const string
     */
    const APPEND = 'APPEND';

    /**
     * Whether or not to prepend contents to placeholder
     * @const string
     */
    const PREPEND = 'PREPEND';

    /**
     * What text to prefix the placeholder with when rendering
     * @var string
     */
    protected $_prefix    = '';

    /**
     * What text to append the placeholder with when rendering
     * @var string
     */
    protected $_postfix   = '';

    /**
     * What string to use between individual items in the placeholder when rendering
     * @var string
     */
    protected $_separator = '';

    /**
     * What string to use as the indentation of output, this will typically be spaces. Eg: '    '
     * @var string
     */
    protected $_indent = '';
    
    /**
     * Whether or not we're already capturing for this given container
     * @var bool
     */
    protected $_captureLock = false;

    /**
     * What type of capture (overwrite (set), append, prepend) to use
     * @var string
     */
    protected $_captureType;

    /**
     * Key to which to capture content
     * @var string
     */
    protected $_captureKey;
    
    /**
     * Constructor - This is needed so that we can attach a class member as the ArrayObject container
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct(array(), parent::ARRAY_AS_PROPS);
    }
    
    /**
     * Set a single value
     *
     * @param  mixed $value
     * @return void
     */
    public function set($value)
    {
        $this->exchangeArray(array($value));
    }

    /**
     * Prepend a value to the top of the container
     * 
     * @param  mixed $value 
     * @return void
     */
    public function prepend($value)
    {
        $values = $this->getArrayCopy();
        array_unshift($values, $value);
        $this->exchangeArray($values);
    }

    /**
     * Retrieve container value
     *
     * If single element registered, returns that element; otherwise,
     * serializes to array.
     *
     * @return mixed
     */
    public function getValue()
    {
        if (1 == count($this)) {
            $keys = $this->getKeys();
            $key  = array_shift($keys);
            return $this[$key];
        }

        return $this->getArrayCopy();
    }

    /**
     * Set prefix for __toString() serialization
     *
     * @param  string $prefix
     * @return Zend_View_Helper_Placeholder_Container
     */
    public function setPrefix($prefix)
    {
        $this->_prefix = (string) $prefix;
        return $this;
    }

    /**
     * Retrieve prefix
     *
     * @return string
     */
    public function getPrefix()
    {
        return $this->_prefix;
    }

    /**
     * Set postfix for __toString() serialization
     *
     * @param  string $postfix
     * @return Zend_View_Helper_Placeholder_Container
     */
    public function setPostfix($postfix)
    {
        $this->_postfix = (string) $postfix;
        return $this;
    }

    /**
     * Retrieve postfix
     *
     * @return string
     */
    public function getPostfix()
    {
        return $this->_postfix;
    }

    /**
     * Set separator for __toString() serialization
     *
     * Used to implode elements in container
     *
     * @param  string $separator
     * @return Zend_View_Helper_Placeholder_Container
     */
    public function setSeparator($separator)
    {
        $this->_separator = (string) $separator;
        return $this;
    }

    /**
     * Retrieve separator
     *
     * @return string
     */
    public function getSeparator()
    {
        return $this->_separator;
    }

    /**
     * Set the indentation string for __toString() serialization,
     * optionally, if a number is passed, it will be the number of spaces
     *
     * @param  string|int $indent
     * @return Zend_View_Helper_Placeholder_Container_Abstract
     */
    public function setIndent($indent)
    {
        $this->_indent = $this->getWhitespace($indent);
        return $this;
    }

    /**
     * Retrieve indentation
     *
     * @return string
     */
    public function getIndent()
    {
        return $this->_indent;
    }

    /**
     * Retrieve whitespace representation of $indent
     * 
     * @param  int|string $indent 
     * @return string
     */
    public function getWhitespace($indent)
    {
        if (is_int($indent)) {
            $indent = str_repeat(' ', $indent);
        }

        return (string) $indent;
    }
   
    /**
     * Start capturing content to push into placeholder
     *
     * @param  int $type How to capture content into placeholder; append, prepend, or set
     * @return void
     * @throws Zend_View_Helper_Placeholder_Exception if nested captures detected
     */
    public function captureStart($type = Zend_View_Helper_Placeholder_Container_Abstract::APPEND, $key = null)
    {
        if ($this->_captureLock) {
            require_once 'Zend/View/Helper/Placeholder/Container/Exception.php';
            throw new Zend_View_Helper_Placeholder_Container_Exception('Cannot nest placeholder captures for the same placeholder');
        }

        $this->_captureLock = true;
        $this->_captureType = $type;
        if ((null !== $key) && is_scalar($key)) {
            $this->_captureKey = (string) $key;
        }
        ob_start();
    }

    /**
     * End content capture
     *
     * @return void
     */
    public function captureEnd()
    {
        $data               = ob_get_clean();
        $key                = null;
        $this->_captureLock = false;
        if (null !== $this->_captureKey) {
            $key = $this->_captureKey;
        }
        switch ($this->_captureType) {
            case self::SET:
                if (null !== $key) {
                    $this[$key] = $data;
                } else {
                    $this->exchangeArray(array($data));
                }
                break;
            case self::PREPEND:
                if (null !== $key) {
                    $array  = array($key => $data);
                    $values = $this->getArrayCopy();
                    $final  = $array + $values;
                    $this->exchangeArray($final);
                } else {
                    $this->prepend($data);
                }
                break;
            case self::APPEND:
            default:
                if (null !== $key) {
                    if (empty($this[$key])) {                                                       
                        $this[$key] = $data;                                                       
                    } else {                                                                       
                        $this[$key] .= $data;                                                      
                    }
                } else {
                    $this[$this->nextIndex()] = $data;
                }
                break;
        }
    }

    /**
     * Get keys
     * 
     * @return array
     */
    public function getKeys()
    {
        $array = $this->getArrayCopy();
        return array_keys($array);
    }

    /**
     * Next Index
     *
     * as defined by the PHP manual
     * @return int
     */
    public function nextIndex()
    {
        $keys = $this->getKeys();
        if (0 == count($keys)) {
            return 0;
        }

        return $nextIndex = max($keys) + 1;
    }
    
    /**
     * Render the placeholder
     *
     * @return string
     */
    public function toString($indent = null)
    {
        $indent = ($indent !== null) 
                ? $this->getWhitespace($indent) 
                : $this->getIndent();
        
        $items  = $this->getArrayCopy();
        $return = $indent 
                . $this->getPrefix()
                . implode($this->getSeparator(), $items)
                . $this->getPostfix();
        $return = preg_replace("/(\r\n?|\n)/", '$1' . $indent, $return);
        return $return;
    }

    /**
     * Serialize object to string
     *
     * @return string
     */
    public function __toString()
    {
        return $this->toString();
    }
}
View/Helper/Placeholder/Container/Exception.php000066600000002367151256604610015532 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/** Zend_View_Exception */
require_once 'Zend/View/Exception.php';


/**
 * Exception for Zend_View_Helper_Placeholder_Container class.
 *
 * @category   Zend
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_View_Helper_Placeholder_Container_Exception extends Zend_View_Exception
{
}
View/Helper/Placeholder/Container/Standalone.php000066600000017376151256604610015672 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Standalone.php 13198 2008-12-13 13:51:40Z matthew $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_View_Helper_Placeholder_Registry */
require_once 'Zend/View/Helper/Placeholder/Registry.php';

/** Zend_View_Helper_Abstract.php */
require_once 'Zend/View/Helper/Abstract.php';

/**
 * Base class for targetted placeholder helpers
 *
 * @package    Zend_View
 * @subpackage Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */ 
abstract class Zend_View_Helper_Placeholder_Container_Standalone extends Zend_View_Helper_Abstract implements IteratorAggregate, Countable, ArrayAccess
{  
    /**
     * @var Zend_View_Helper_Placeholder_Container_Abstract
     */
    protected $_container;

    /**
     * @var Zend_View_Helper_Placeholder_Registry
     */
    protected $_registry;

    /**
     * Registry key under which container registers itself
     * @var string
     */
    protected $_regKey;

    /**
     * Flag wheter to automatically escape output, must also be
     * enforced in the child class if __toString/toString is overriden
     * @var book
     */
    protected $_autoEscape = true;

    /**
     * Constructor
     * 
     * @return void
     */
    public function __construct()
    {
        $this->setRegistry(Zend_View_Helper_Placeholder_Registry::getRegistry());
        $this->setContainer($this->getRegistry()->getContainer($this->_regKey));
    }

    /**
     * Retrieve registry
     * 
     * @return Zend_View_Helper_Placeholder_Registry
     */
    public function getRegistry()
    {
        return $this->_registry;
    }

    /**
     * Set registry object 
     * 
     * @param  Zend_View_Helper_Placeholder_Registry $registry 
     * @return Zend_View_Helper_Placeholder_Container_Standalone
     */
    public function setRegistry(Zend_View_Helper_Placeholder_Registry $registry)
    {
        $this->_registry = $registry;
        return $this;
    }

    /**
     * Set whether or not auto escaping should be used
     * 
     * @param  bool $autoEscape whether or not to auto escape output
     * @return Zend_View_Helper_Placeholder_Container_Standalone
     */
    public function setAutoEscape($autoEscape = true)
    {
        $this->_autoEscape = ($autoEscape) ? true : false;
        return $this;
    }
    
    /**
     * Return whether autoEscaping is enabled or disabled
     *
     * return bool
     */
    public function getAutoEscape()
    {
        return $this->_autoEscape;
    }

    /**
     * Escape a string
     * 
     * @param  string $string 
     * @return string
     */
    protected function _escape($string)
    {
        if ($this->view instanceof Zend_View_Interface) {
            return $this->view->escape($string);
        }

        return htmlentities((string) $string, null, 'UTF-8');
    }

    /**
     * Set container on which to operate
     * 
     * @param  Zend_View_Helper_Placeholder_Container_Abstract $container 
     * @return Zend_View_Helper_Placeholder_Container_Standalone
     */
    public function setContainer(Zend_View_Helper_Placeholder_Container_Abstract $container)
    {
        $this->_container = $container;
        return $this;
    }

    /**
     * Retrieve placeholder container
     * 
     * @return Zend_View_Helper_Placeholder_Container_Abstract
     */
    public function getContainer()
    {
        return $this->_container;
    }

    /**
     * Overloading: set property value
     * 
     * @param  string $key 
     * @param  mixed $value 
     * @return void
     */
    public function __set($key, $value)
    {
        $container = $this->getContainer();
        $container[$key] = $value;
    }

    /**
     * Overloading: retrieve property
     * 
     * @param  string $key 
     * @return mixed
     */
    public function __get($key)
    {
        $container = $this->getContainer();
        if (isset($container[$key])) {
            return $container[$key];
        }

        return null;
    }

    /**
     * Overloading: check if property is set
     * 
     * @param  string $key 
     * @return bool
     */
    public function __isset($key)
    {
        $container = $this->getContainer();
        return isset($container[$key]);
    }

    /**
     * Overloading: unset property
     * 
     * @param  string $key 
     * @return void
     */
    public function __unset($key)
    {
        $container = $this->getContainer();
        if (isset($container[$key])) {
            unset($container[$key]);
        }
    }

    /**
     * Overload
     *
     * Proxy to container methods
     * 
     * @param  string $method 
     * @param  array $args 
     * @return mixed
     */
    public function __call($method, $args)
    {
        $container = $this->getContainer();
        if (method_exists($container, $method)) {
            $return = call_user_func_array(array($container, $method), $args);
            if ($return === $container) {
                // If the container is returned, we really want the current object
                return $this;
            }
            return $return;
        }

        require_once 'Zend/View/Exception.php';
        throw new Zend_View_Exception('Method "' . $method . '" does not exist');
    }

    /**
     * String representation
     * 
     * @return string
     */
    public function toString()
    {
        return $this->getContainer()->toString();
    }

    /**
     * Cast to string representation
     * 
     * @return string
     */
    public function __toString()
    {
        return $this->toString();
    }

    /**
     * Countable
     * 
     * @return int
     */
    public function count()
    {
        $container = $this->getContainer();
        return count($container);
    }

    /**
     * ArrayAccess: offsetExists
     * 
     * @param  string|int $offset 
     * @return bool
     */
    public function offsetExists($offset)
    {
        return $this->getContainer()->offsetExists($offset);
    }

    /**
     * ArrayAccess: offsetGet
     * 
     * @param  string|int $offset 
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return $this->getContainer()->offsetGet($offset);
    }

    /**
     * ArrayAccess: offsetSet
     * 
     * @param  string|int $offset 
     * @param  mixed $value 
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        return $this->getContainer()->offsetSet($offset, $value);
    }

    /**
     * ArrayAccess: offsetUnset
     * 
     * @param  string|int $offset 
     * @return void
     */
    public function offsetUnset($offset)
    {
        return $this->getContainer()->offsetUnset($offset);
    }

    /**
     * IteratorAggregate: get Iterator
     * 
     * @return Iterator
     */
    public function getIterator()
    {
        return $this->getContainer()->getIterator();
    }
}
Cache/Backend.php000066600000015322151256604610007624 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Backend
{
    /**
     * Frontend or Core directives
     *
     * =====> (int) lifetime :
     * - Cache lifetime (in seconds)
     * - If null, the cache is valid forever
     *
     * =====> (int) logging :
     * - if set to true, a logging is activated throw Zend_Log
     *
     * @var array directives
     */
    protected $_directives = array(
        'lifetime' => 3600,
        'logging'  => false,
        'logger'   => null
    );

    /**
     * Available options
     *
     * @var array available options
     */
    protected $_options = array();

    /**
     * Constructor
     *
     * @param  array $options Associative array of options
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct(array $options = array())
    {
        while (list($name, $value) = each($options)) {
            $this->setOption($name, $value);
        }
    }

    /**
     * Set the frontend directives
     *
     * @param  array $directives Assoc of directives
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function setDirectives($directives)
    {
        if (!is_array($directives)) Zend_Cache::throwException('Directives parameter must be an array');
        while (list($name, $value) = each($directives)) {
            if (!is_string($name)) {
                Zend_Cache::throwException("Incorrect option name : $name");
            }
            $name = strtolower($name);
            if (array_key_exists($name, $this->_directives)) {
                $this->_directives[$name] = $value;
            }

        }

        $this->_loggerSanity();
    }

    /**
     * Set an option
     *
     * @param  string $name
     * @param  mixed  $value
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function setOption($name, $value)
    {
        if (!is_string($name)) {
            Zend_Cache::throwException("Incorrect option name : $name");
        }
        $name = strtolower($name);
        if (array_key_exists($name, $this->_options)) {
            $this->_options[$name] = $value;
        }
    }

    /**
     * Get the life time
     *
     * if $specificLifetime is not false, the given specific life time is used
     * else, the global lifetime is used
     *
     * @param  int $specificLifetime
     * @return int Cache life time
     */
    public function getLifetime($specificLifetime)
    {
        if ($specificLifetime === false) {
            return $this->_directives['lifetime'];
        }
        return $specificLifetime;
    }

    /**
     * Return true if the automatic cleaning is available for the backend
     *
     * DEPRECATED : use getCapabilities() instead
     *
     * @deprecated
     * @return boolean
     */
    public function isAutomaticCleaningAvailable()
    {
        return true;
    }

    /**
     * Return a system-wide tmp directory
     *
     * @return string System-wide tmp directory
     */
    static function getTmpDir()
    {
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            // windows...
            foreach (array($_ENV, $_SERVER) as $tab) {
                foreach (array('TEMP', 'TMP', 'windir', 'SystemRoot') as $key) {
                    if (isset($tab[$key])) {
                        $result = $tab[$key];
                        if (($key == 'windir') or ($key == 'SystemRoot')) {
                            $result = $result . '\\temp';
                        }
                        return $result;
                    }
                }
            }
            return '\\temp';
        } else {
            // unix...
            if (isset($_ENV['TMPDIR']))    return $_ENV['TMPDIR'];
            if (isset($_SERVER['TMPDIR'])) return $_SERVER['TMPDIR'];
            return '/tmp';
        }
    }

    /**
     * Make sure if we enable logging that the Zend_Log class
     * is available.
     * Create a default log object if none is set.
     *
     * @throws Zend_Cache_Exception
     * @return void
     */
    protected function _loggerSanity()
    {
        if (!isset($this->_directives['logging']) || !$this->_directives['logging']) {
            return;
        }
        try {
            /**
             * @see Zend_Log
             */
            require_once 'Zend/Log.php';
        } catch (Zend_Exception $e) {
            Zend_Cache::throwException('Logging feature is enabled but the Zend_Log class is not available');
        }
        if (isset($this->_directives['logger'])) {
            if ($this->_directives['logger'] instanceof Zend_Log) {
                return;
            } else {
                Zend_Cache::throwException('Logger object is not an instance of Zend_Log class.');
            }
        }
        // Create a default logger to the standard output stream
        require_once 'Zend/Log/Writer/Stream.php';
        $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
        $this->_directives['logger'] = $logger;
    }

    /**
     * Log a message at the WARN (4) priority.
     *
     * @param  string $message
     * @throws Zend_Cache_Exception
     * @return void
     */
    protected function _log($message, $priority = 4)
    {
        if (!$this->_directives['logging']) {
            return;
        }

        if (!isset($this->_directives['logger'])) {
        	Zend_Cache::throwException('Logging is enabled but logger is not set.');
        }
        $logger = $this->_directives['logger'];
        if (!$logger instanceof Zend_Log) {
            Zend_Cache::throwException('Logger object is not an instance of Zend_Log class.');
        }
        $logger->log($message, $priority);
    }
}
Cache/Core.php000066600000053767151256604610007204 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Cache
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * @package    Zend_Cache
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Core
{
    /**
     * Backend Object
     *
     * @var object $_backend
     */
    protected $_backend = null;

    /**
     * Available options
     *
     * ====> (boolean) write_control :
     * - Enable / disable write control (the cache is read just after writing to detect corrupt entries)
     * - Enable write control will lightly slow the cache writing but not the cache reading
     * Write control can detect some corrupt cache files but maybe it's not a perfect control
     *
     * ====> (boolean) caching :
     * - Enable / disable caching
     * (can be very useful for the debug of cached scripts)
     *
     * =====> (string) cache_id_prefix :
     * - prefix for cache ids (namespace)
     *
     * ====> (boolean) automatic_serialization :
     * - Enable / disable automatic serialization
     * - It can be used to save directly datas which aren't strings (but it's slower)
     *
     * ====> (int) automatic_cleaning_factor :
     * - Disable / Tune the automatic cleaning process
     * - The automatic cleaning process destroy too old (for the given life time)
     *   cache files when a new cache file is written :
     *     0               => no automatic cache cleaning
     *     1               => systematic cache cleaning
     *     x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
     *
     * ====> (int) lifetime :
     * - Cache lifetime (in seconds)
     * - If null, the cache is valid forever.
     *
     * ====> (boolean) logging :
     * - If set to true, logging is activated (but the system is slower)
     *
     * ====> (boolean) ignore_user_abort
     * - If set to true, the core will set the ignore_user_abort PHP flag inside the
     *   save() method to avoid cache corruptions in some cases (default false)
     *
     * @var array $_options available options
     */
    protected $_options = array(
        'write_control'             => true,
        'caching'                   => true,
        'cache_id_prefix'           => null,
        'automatic_serialization'   => false,
        'automatic_cleaning_factor' => 10,
        'lifetime'                  => 3600,
        'logging'                   => false,
        'logger'                    => null,
        'ignore_user_abort'         => false
    );

    /**
     * Array of options which have to be transfered to backend
     *
     * @var array $_directivesList
     */
    protected static $_directivesList = array('lifetime', 'logging', 'logger');

    /**
     * Not used for the core, just a sort a hint to get a common setOption() method (for the core and for frontends)
     *
     * @var array $_specificOptions
     */
    protected $_specificOptions = array();

    /**
     * Last used cache id
     *
     * @var string $_lastId
     */
    private $_lastId = null;
    
    /**
     * True if the backend implements Zend_Cache_Backend_ExtendedInterface
     *
     * @var boolean $_extendedBackend
     */
    protected $_extendedBackend = false;

    /**
     * Array of capabilities of the backend (only if it implements Zend_Cache_Backend_ExtendedInterface)
     * 
     * @var array
     */
    protected $_backendCapabilities = array();
    
    /**
     * Constructor
     *
     * @param  array $options Associative array of options
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct(array $options = array())
    {
        while (list($name, $value) = each($options)) {
            $this->setOption($name, $value);
        }
        $this->_loggerSanity();
    }

    /**
     * Set the backend
     *
     * @param  object $backendObject
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function setBackend(Zend_Cache_Backend $backendObject)
    {
        $this->_backend= $backendObject;
        // some options (listed in $_directivesList) have to be given
        // to the backend too (even if they are not "backend specific")
        $directives = array();
        foreach (Zend_Cache_Core::$_directivesList as $directive) {
            $directives[$directive] = $this->_options[$directive];
        }
        $this->_backend->setDirectives($directives);
        if (in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_backend))) {
            $this->_extendedBackend = true;
            $this->_backendCapabilities = $this->_backend->getCapabilities();
        }
        
    }

    /**
     * Returns the backend
     *
     * @return object backend object
     */
    public function getBackend()
    {
        return $this->_backend;
    }

    /**
     * Public frontend to set an option
     *
     * There is an additional validation (relatively to the protected _setOption method)
     *
     * @param  string $name  Name of the option
     * @param  mixed  $value Value of the option
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function setOption($name, $value)
    {
        if (!is_string($name)) {
            Zend_Cache::throwException("Incorrect option name : $name");
        }
        $name = strtolower($name);
        if (array_key_exists($name, $this->_options)) {
            // This is a Core option
            $this->_setOption($name, $value);
            return;
        }
        if (array_key_exists($name, $this->_specificOptions)) {
            // This a specic option of this frontend
            $this->_specificOptions[$name] = $value;
            return;
        }
    }

    /**
     * Public frontend to get an option value
     *
     * @param  string $name  Name of the option
     * @throws Zend_Cache_Exception
     * @return mixed option value
     */
    public function getOption($name)
    {
        if (is_string($name)) {
            $name = strtolower($name);
            if (array_key_exists($name, $this->_options)) {
                // This is a Core option
                return $this->_options[$name];
            }
            if (array_key_exists($name, $this->_specificOptions)) {
                // This a specic option of this frontend
                return $this->_specificOptions[$name];
            }
        }
        Zend_Cache::throwException("Incorrect option name : $name");
    }

    /**
     * Set an option
     *
     * @param  string $name  Name of the option
     * @param  mixed  $value Value of the option
     * @throws Zend_Cache_Exception
     * @return void
     */
    private function _setOption($name, $value)
    {
        if (!is_string($name) || !array_key_exists($name, $this->_options)) {
            Zend_Cache::throwException("Incorrect option name : $name");
        }
        $this->_options[$name] = $value;
    }

    /**
     * Force a new lifetime
     *
     * The new value is set for the core/frontend but for the backend too (directive)
     *
     * @param  int $newLifetime New lifetime (in seconds)
     * @return void
     */
    public function setLifetime($newLifetime)
    {
        $this->_options['lifetime'] = $newLifetime;
        $this->_backend->setDirectives(array(
            'lifetime' => $newLifetime
        ));
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * @param  string  $id                     Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @param  boolean $doNotUnserialize       Do not serialize (even if automatic_serialization is true) => for internal use
     * @return mixed|false Cached datas
     */
    public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false)
    {
        if (!$this->_options['caching']) {
            return false;
        }
        $id = $this->_id($id); // cache id may need prefix
        $this->_lastId = $id;
        self::_validateIdOrTag($id);
        $data = $this->_backend->load($id, $doNotTestCacheValidity);
        if ($data===false) {
            // no cache available
            return false;
        }
        if ((!$doNotUnserialize) && $this->_options['automatic_serialization']) {
            // we need to unserialize before sending the result
            return unserialize($data);
        }
        return $data;
    }

    /**
     * Test if a cache is available for the given id
     *
     * @param  string $id Cache id
     * @return boolean True is a cache is available, false else
     */
    public function test($id)
    {
        if (!$this->_options['caching']) {
            return false;
        }
        $id = $this->_id($id); // cache id may need prefix
        self::_validateIdOrTag($id);
        $this->_lastId = $id;
        return $this->_backend->test($id);
    }

    /**
     * Save some data in a cache
     *
     * @param  mixed $data           Data to put in cache (can be another type than string if automatic_serialization is on)
     * @param  string $id             Cache id (if not set, the last cache id will be used)
     * @param  array $tags           Cache tags
     * @param  int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @param  int   $priority         integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends         
     * @throws Zend_Cache_Exception
     * @return boolean True if no problem
     */
    public function save($data, $id = null, $tags = array(), $specificLifetime = false, $priority = 8)
    {
        if (!$this->_options['caching']) {
            return true;
        }
        if (is_null($id)) {
            $id = $this->_lastId;
        } else {
            $id = $this->_id($id);
        }
        self::_validateIdOrTag($id);
        self::_validateTagsArray($tags);
        if ($this->_options['automatic_serialization']) {
            // we need to serialize datas before storing them
            $data = serialize($data);
        } else {
            if (!is_string($data)) {
                Zend_Cache::throwException("Datas must be string or set automatic_serialization = true");
            }
        }
        // automatic cleaning
        if ($this->_options['automatic_cleaning_factor'] > 0) {
            $rand = rand(1, $this->_options['automatic_cleaning_factor']);
            if ($rand==1) {
                if ($this->_extendedBackend) {
                    // New way
                    if ($this->_backendCapabilities['automatic_cleaning']) {
                        $this->clean(Zend_Cache::CLEANING_MODE_OLD);
                    } else {
                        $this->_log('Zend_Cache_Core::save() / automatic cleaning is not available/necessary with this backend');
                    }
                } else {
                    // Deprecated way (will be removed in next major version)
                    if (method_exists($this->_backend, 'isAutomaticCleaningAvailable') && ($this->_backend->isAutomaticCleaningAvailable())) {
                        $this->clean(Zend_Cache::CLEANING_MODE_OLD);
                    } else {
                        $this->_log('Zend_Cache_Core::save() / automatic cleaning is not available/necessary with this backend');
                    }
                }
            }
        }
        if ($this->_options['ignore_user_abort']) {
            $abort = ignore_user_abort(true);
        }
        if (($this->_extendedBackend) && ($this->_backendCapabilities['priority'])) {
            $result = $this->_backend->save($data, $id, $tags, $specificLifetime, $priority);
        } else {
            $result = $this->_backend->save($data, $id, $tags, $specificLifetime);
        }
        if ($this->_options['ignore_user_abort']) {
            ignore_user_abort($abort);
        }
        if (!$result) {
            // maybe the cache is corrupted, so we remove it !
            if ($this->_options['logging']) {
                $this->_log("Zend_Cache_Core::save() : impossible to save cache (id=$id)");
            }
            $this->remove($id);
            return false;
        }
        if ($this->_options['write_control']) {
            $data2 = $this->_backend->load($id, true);
            if ($data!=$data2) {
                $this->_log('Zend_Cache_Core::save() / write_control : written and read data do not match');
                $this->_backend->remove($id);
                return false;
            }
        }
        return true;
    }

    /**
     * Remove a cache
     *
     * @param  string $id Cache id to remove
     * @return boolean True if ok
     */
    public function remove($id)
    {
        if (!$this->_options['caching']) {
            return true;
        }
        $id = $this->_id($id); // cache id may need prefix
        self::_validateIdOrTag($id);
        return $this->_backend->remove($id);
    }

    /**
     * Clean cache entries
     *
     * Available modes are :
     * 'all' (default)  => remove all cache entries ($tags is not used)
     * 'old'            => remove too old cache entries ($tags is not used)
     * 'matchingTag'    => remove cache entries matching all given tags
     *                     ($tags can be an array of strings or a single string)
     * 'notMatchingTag' => remove cache entries not matching one of the given tags
     *                     ($tags can be an array of strings or a single string)
     * 'matchingAnyTag' => remove cache entries matching any given tags
     *                     ($tags can be an array of strings or a single string)
     *
     * @param  string       $mode
     * @param  array|string $tags
     * @throws Zend_Cache_Exception
     * @return boolean True if ok
     */
    public function clean($mode = 'all', $tags = array())
    {
        if (!$this->_options['caching']) {
            return true;
        }
        if (!in_array($mode, array(Zend_Cache::CLEANING_MODE_ALL,
                                   Zend_Cache::CLEANING_MODE_OLD,
                                   Zend_Cache::CLEANING_MODE_MATCHING_TAG,
                                   Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG,
                                   Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG))) {
            Zend_Cache::throwException('Invalid cleaning mode');
        }
        self::_validateTagsArray($tags);
        return $this->_backend->clean($mode, $tags);
    }
    
    /**
     * Return an array of stored cache ids which match given tags
     * 
     * In case of multiple tags, a logical AND is made between tags
     *
     * @param array $tags array of tags
     * @return array array of matching cache ids (string)
     */
    public function getIdsMatchingTags($tags = array())
    {
        if (!$this->_extendedBackend) {
            Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
        }
        if (!($this->_backendCapabilities['tags'])) {
            Zend_Cache::throwException('tags are not supported by the current backend');
        }
        return $this->_backend->getIdsMatchingTags($tags);
    }
    
    /**
     * Return an array of stored cache ids which don't match given tags
     * 
     * In case of multiple tags, a logical OR is made between tags
     *
     * @param array $tags array of tags
     * @return array array of not matching cache ids (string)
     */    
    public function getIdsNotMatchingTags($tags = array())
    {
        if (!$this->_extendedBackend) {
            Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
        }
        if (!($this->_backendCapabilities['tags'])) {
            Zend_Cache::throwException('tags are not supported by the current backend');
        }
        return $this->_backend->getIdsNotMatchingTags($tags);
    }
    
    /**
     * Return an array of stored cache ids
     * 
     * @return array array of stored cache ids (string)
     */
    public function getIds()
    {
        if (!$this->_extendedBackend) {
            Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
        }
        return $this->_backend->getIds();
    }
    
    /**
     * Return an array of stored tags
     *
     * @return array array of stored tags (string)
     */
    public function getTags()
    {
        if (!$this->_extendedBackend) {
            Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
        }
        if (!($this->_backendCapabilities['tags'])) {
            Zend_Cache::throwException('tags are not supported by the current backend');
        }
        return $this->_backend->getTags();        
    }
    
    /**
     * Return the filling percentage of the backend storage
     *
     * @return int integer between 0 and 100
     */
    public function getFillingPercentage()
    {
        if (!$this->_extendedBackend) {
            Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
        }
        return $this->_backend->getFillingPercentage();        
    }
    
    /**
     * Give (if possible) an extra lifetime to the given cache id
     *
     * @param string $id cache id
     * @param int $extraLifetime
     * @return boolean true if ok
     */
    public function touch($id, $extraLifetime)
    {
        if (!$this->_extendedBackend) {
            Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available');
        }
        return $this->_backend->touch($id, $extraLifetime);           
    }
    
    /**
     * Validate a cache id or a tag (security, reliable filenames, reserved prefixes...)
     *
     * Throw an exception if a problem is found
     *
     * @param  string $string Cache id or tag
     * @throws Zend_Cache_Exception
     * @return void
     */
    private static function _validateIdOrTag($string)
    {
        if (!is_string($string)) {
            Zend_Cache::throwException('Invalid id or tag : must be a string');
        }
        if (substr($string, 0, 9) == 'internal-') {
            Zend_Cache::throwException('"internal-*" ids or tags are reserved');
        }
        if (!preg_match('~^[\w]+$~D', $string)) {
            Zend_Cache::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]");
        }
    }

    /**
     * Validate a tags array (security, reliable filenames, reserved prefixes...)
     *
     * Throw an exception if a problem is found
     *
     * @param  array $tags Array of tags
     * @throws Zend_Cache_Exception
     * @return void
     */
    private static function _validateTagsArray($tags)
    {
        if (!is_array($tags)) {
            Zend_Cache::throwException('Invalid tags array : must be an array');
        }
        foreach($tags as $tag) {
            self::_validateIdOrTag($tag);
        }
        reset($tags);
    }

    /**
     * Make sure if we enable logging that the Zend_Log class
     * is available.
     * Create a default log object if none is set.
     *
     * @throws Zend_Cache_Exception
     * @return void
     */
    protected function _loggerSanity()
    {
        if (!isset($this->_options['logging']) || !$this->_options['logging']) {
            return;
        }

        if (isset($this->_options['logger']) && $this->_options['logger'] instanceof Zend_Log) {
            return;
        }

        // Create a default logger to the standard output stream
        require_once 'Zend/Log/Writer/Stream.php';
        $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
        $this->_options['logger'] = $logger;
    }

    /**
     * Log a message at the WARN (4) priority.
     *
     * @param string $message
     * @throws Zend_Cache_Exception
     * @return void
     */
    protected function _log($message, $priority = 4)
    {
        if (!$this->_options['logging']) {
            return;
        }
        if (!(isset($this->_options['logger']) || $this->_options['logger'] instanceof Zend_Log)) {
            Zend_Cache::throwException('Logging is enabled but logger is not set');
        }
        $logger = $this->_options['logger'];
        $logger->log($message, $priority);
    }

    /**
     * Make and return a cache id
     *
     * Checks 'cache_id_prefix' and returns new id with prefix or simply the id if null
     *
     * @param  string $id Cache id
     * @return string Cache id (with or without prefix)
     */
    private function _id($id)
    {
        if (!is_null($id) && isset($this->_options['cache_id_prefix'])) {
            return $this->_options['cache_id_prefix'] . $id; // return with prefix
        }
        return $id; // no prefix, just return the $id passed
    }

}
Soap/Wsdl/Strategy/Abstract.php000066600000003251151256604610012450 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Soap
 * @subpackage Wsdl
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/**
 * Abstract class for Zend_Soap_Wsdl_Strategy.
 *
 * @category   Zend
 * @package    Zend_Soap
 * @subpackage Wsdl
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Soap_Wsdl_Strategy_Abstract implements Zend_Soap_Wsdl_Strategy_Interface
{
    /**
     * Context object
     *
     * @var Zend_Soap_Wsdl
     */
    protected $_context;

    /**
     * Set the Zend_Soap_Wsdl Context object this strategy resides in.
     *
     * @param Zend_Soap_Wsdl $context
     * @return void
     */
    public function setContext(Zend_Soap_Wsdl $context)
    {
        $this->_context = $context;
    }

    /**
     * Return the current Zend_Soap_Wsdl context object
     *
     * @return Zend_Soap_Wsdl
     */
    public function getContext()
    {
        return $this->_context;
    }
}
Soap/Wsdl/Strategy/Interface.php000066600000002010151256604610012575 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Soap
 * @subpackage Wsdl
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */


interface Zend_Soap_Wsdl_Strategy_Interface
{
    public function setContext(Zend_Soap_Wsdl $context);

    /**
     * Create a complex type based on a strategy
     *
     * @param  string $type
     * @return string XSD type
     */
    public function addComplexType($type);
}Soap/Wsdl/Strategy/AnyType.php000066600000002317151256604610012300 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Soap
 * @subpackage Wsdl
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

class Zend_Soap_Wsdl_Strategy_AnyType implements Zend_Soap_Wsdl_Strategy_Interface
{
    /**
     * Not needed in this strategy.
     *
     * @param Zend_Soap_Wsdl $context
     */
    public function setContext(Zend_Soap_Wsdl $context)
    {
        
    }

    /**
     * Returns xsd:anyType regardless of the input.
     *
     * @param string $type
     * @return string
     */
    public function addComplexType($type)
    {
        return 'xsd:anyType';
    }
}Soap/AutoDiscover.php000066600000032253151256604610010605 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Soap
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: AutoDiscover.php 13636 2009-01-14 21:19:24Z beberlei $
 */

require_once 'Zend/Server/Interface.php';
require_once 'Zend/Soap/Wsdl.php';
require_once 'Zend/Server/Reflection.php';
require_once 'Zend/Server/Exception.php';
require_once 'Zend/Server/Abstract.php';
require_once 'Zend/Uri.php';

/**
 * Zend_Soap_AutoDiscover
 *
 * @category   Zend
 * @package    Zend_Soap
 */
class Zend_Soap_AutoDiscover implements Zend_Server_Interface {
    /**
     * @var Zend_Soap_Wsdl
     */
    protected $_wsdl = null;

    /**
     * @var Zend_Server_Reflection
     */
    protected $_reflection = null;

    /**
     * @var array
     */
    protected $_functions = array();

    /**
     * @var boolean
     */
    protected $_strategy;

    /**
     * Url where the WSDL file will be available at.
     *
     * @var WSDL Uri
     */
    protected $_uri;

    /**
     * Constructor
     *
     * @param boolean|string|Zend_Soap_Wsdl_Strategy_Interface $strategy
     * @param string|Zend_Uri $uri
     */
    public function __construct($strategy = true, $uri=null)
    {
        $this->_reflection = new Zend_Server_Reflection();
        $this->setComplexTypeStrategy($strategy);

        if($uri !== null) {
            $this->setUri($uri);
        }
    }

    /**
     * Set the location at which the WSDL file will be availabe.
     *
     * @see Zend_Soap_Exception
     * @throws Zend_Soap_AutoDiscover_Exception
     * @param  Zend_Uri|string $uri
     * @return Zend_Soap_AutoDiscover
     */
    public function setUri($uri)
    {
        if(is_string($uri)) {
            $uri = Zend_Uri::factory($uri);
        } else if(!($uri instanceof Zend_Uri)) {
            require_once "Zend/Soap/AutoDiscover/Exception.php";
            throw new Zend_Soap_AutoDiscover_Exception("No uri given to Zend_Soap_AutoDiscover::setUri as string or Zend_Uri instance.");
        }
        $this->_uri = $uri;

        // change uri in WSDL file also if existant
        if($this->_wsdl instanceof Zend_Soap_Wsdl) {
            $this->_wsdl->setUri($uri);
        }

        return $this;
    }

    /**
     * Return the current Uri that the SOAP WSDL Service will be located at.
     *
     * @return Zend_Uri
     */
    public function getUri()
    {
        if($this->_uri instanceof Zend_Uri) {
            $uri = $this->_uri;
        } else {
            $schema     = $this->getSchema();
            $host       = $this->getHostName();
            $scriptName = $this->getRequestUriWithoutParameters();
            $uri = Zend_Uri::factory($schema . '://' . $host . $scriptName);
            $this->setUri($uri);
        }
        return $uri;
    }

    /**
     * Detect and returns the current HTTP/HTTPS Schema
     *
     * @return string
     */
    protected function getSchema()
    {
        $schema = "http";
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
            $schema = 'https';
        }
        return $schema;
    }

    /**
     * Detect and return the current hostname
     *
     * @return string
     */
    protected function getHostName()
    {
        if(isset($_SERVER['HTTP_HOST'])) {
            $host = $_SERVER['HTTP_HOST'];
        } else {
            $host = $_SERVER['SERVER_NAME'];
        }
        return $host;
    }

    /**
     * Detect and return the current script name without parameters
     *
     * @return string
     */
    protected function getRequestUriWithoutParameters()
    {
        if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch
            $requestUri = $_SERVER['HTTP_X_REWRITE_URL'];
        } elseif (isset($_SERVER['REQUEST_URI'])) {
            $requestUri = $_SERVER['REQUEST_URI'];
        } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI
            $requestUri = $_SERVER['ORIG_PATH_INFO'];
        } else {
            $requestUri = $_SERVER['SCRIPT_NAME'];
        }
        if( ($pos = strpos($requestUri, "?")) !== false) {
            $requestUri = substr($requestUri, 0, $pos);
        }

        return $requestUri;
    }

    /**
     * Set the strategy that handles functions and classes that are added AFTER this call.
     *
     * @param  boolean|string|Zend_Soap_Wsdl_Strategy_Interface $strategy
     * @return Zend_Soap_AutoDiscover
     */
    public function setComplexTypeStrategy($strategy)
    {
        $this->_strategy = $strategy;
        if($this->_wsdl instanceof  Zend_Soap_Wsdl) {
            $this->_wsdl->setComplexTypeStrategy($strategy);
        }

        return $this;
    }

    /**
     * Set the Class the SOAP server will use
     *
     * @param string $class Class Name
     * @param string $namespace Class Namspace - Not Used
     * @param array $argv Arguments to instantiate the class - Not Used
     */
    public function setClass($class, $namespace = '', $argv = null)
    {
        $uri = $this->getUri();

        $wsdl = new Zend_Soap_Wsdl($class, $uri, $this->_strategy);

        $port = $wsdl->addPortType($class . 'Port');
        $binding = $wsdl->addBinding($class . 'Binding', 'tns:' .$class. 'Port');

        $wsdl->addSoapBinding($binding, 'rpc');
        $wsdl->addService($class . 'Service', $class . 'Port', 'tns:' . $class . 'Binding', $uri);
        foreach ($this->_reflection->reflectClass($class)->getMethods() as $method) {
            /* <wsdl:portType>'s */
            $portOperation = $wsdl->addPortOperation($port, $method->getName(), 'tns:' .$method->getName(). 'Request', 'tns:' .$method->getName(). 'Response');
            $desc = $method->getDescription();
            if (strlen($desc) > 0) {
                /** @todo check, what should be done for portoperation documentation */
                //$wsdl->addDocumentation($portOperation, $desc);
            }
            /* </wsdl:portType>'s */

            $this->_functions[] = $method->getName();

            $selectedPrototype = null;
            $maxNumArgumentsOfPrototype = -1;
            foreach ($method->getPrototypes() as $prototype) {
                $numParams = count($prototype->getParameters());
                if($numParams > $maxNumArgumentsOfPrototype) {
                    $maxNumArgumentsOfPrototype = $numParams;
                    $selectedPrototype = $prototype;
                }
            }

            if($selectedPrototype != null) {
                $prototype = $selectedPrototype;
                $args = array();
                foreach($prototype->getParameters() as $param) {
                    $args[$param->getName()] = $wsdl->getType($param->getType());
                }
                $message = $wsdl->addMessage($method->getName() . 'Request', $args);
                if (strlen($desc) > 0) {
                    //$wsdl->addDocumentation($message, $desc);
                }
                if ($prototype->getReturnType() != "void") {
                    $message = $wsdl->addMessage($method->getName() . 'Response', array($method->getName() . 'Return' => $wsdl->getType($prototype->getReturnType())));
                }

                /* <wsdl:binding>'s */
                $operation = $wsdl->addBindingOperation($binding, $method->getName(),  array('use' => 'encoded', 'encodingStyle' => "http://schemas.xmlsoap.org/soap/encoding/"), array('use' => 'encoded', 'encodingStyle' => "http://schemas.xmlsoap.org/soap/encoding/"));
                $wsdl->addSoapOperation($operation, $uri->getUri() . '#' .$method->getName());
                /* </wsdl:binding>'s */
            }
        }
        $this->_wsdl = $wsdl;
    }

    /**
     * Add a Single or Multiple Functions to the WSDL
     *
     * @param string $function Function Name
     * @param string $namespace Function namespace - Not Used
     */
    public function addFunction($function, $namespace = '')
    {
        static $port;
        static $operation;
        static $binding;

        if (!is_array($function)) {
            $function = (array) $function;
        }

        $uri = $this->getUri();

        if (!($this->_wsdl instanceof Zend_Soap_Wsdl)) {
            $parts = explode('.', basename($_SERVER['SCRIPT_NAME']));
            $name = $parts[0];
            $wsdl = new Zend_Soap_Wsdl($name, $uri, $this->_strategy);

            $port = $wsdl->addPortType($name . 'Port');
            $binding = $wsdl->addBinding($name . 'Binding', 'tns:' .$name. 'Port');

            $wsdl->addSoapBinding($binding, 'rpc');
            $wsdl->addService($name . 'Service', $name . 'Port', 'tns:' . $name . 'Binding', $uri);
        } else {
            $wsdl = $this->_wsdl;
        }

        foreach ($function as $func) {
            $method = $this->_reflection->reflectFunction($func);
            foreach ($method->getPrototypes() as $prototype) {
                $args = array();
                foreach ($prototype->getParameters() as $param) {
                    $args[$param->getName()] = $wsdl->getType($param->getType());
                }
                $message = $wsdl->addMessage($method->getName() . 'Request', $args);
                $desc = $method->getDescription();
                if (strlen($desc) > 0) {
                    //$wsdl->addDocumentation($message, $desc);
                }
                if ($prototype->getReturnType() != "void") {
                    $message = $wsdl->addMessage($method->getName() . 'Response', array($method->getName() . 'Return' => $wsdl->getType($prototype->getReturnType())));
                }
                 /* <wsdl:portType>'s */
                   $portOperation = $wsdl->addPortOperation($port, $method->getName(), 'tns:' .$method->getName(). 'Request', 'tns:' .$method->getName(). 'Response');
                if (strlen($desc) > 0) {
                    //$wsdl->addDocumentation($portOperation, $desc);
                }
                   /* </wsdl:portType>'s */

                /* <wsdl:binding>'s */
                $operation = $wsdl->addBindingOperation($binding, $method->getName(),  array('use' => 'encoded', 'encodingStyle' => "http://schemas.xmlsoap.org/soap/encoding/"), array('use' => 'encoded', 'encodingStyle' => "http://schemas.xmlsoap.org/soap/encoding/"));
                $wsdl->addSoapOperation($operation, $uri->getUri() . '#' .$method->getName());
                /* </wsdl:binding>'s */

                $this->_functions[] = $method->getName();

                // We will only add one prototype
                break;
            }
        }
        $this->_wsdl = $wsdl;
    }

    /**
     * Action to take when an error occurs
     *
     * @param string $fault
     * @param string|int $code
     */
    public function fault($fault = null, $code = null)
    {
        require_once "Zend/Soap/AutoDiscover/Exception.php";
        throw new Zend_Soap_AutoDiscover_Exception("Function has no use in AutoDiscover.");
    }

    /**
     * Handle the Request
     *
     * @param string $request A non-standard request - Not Used
     */
    public function handle($request = false)
    {
        if (!headers_sent()) {
            header('Content-Type: text/xml');
        }
        $this->_wsdl->dump();
    }

    /**
     * Return an array of functions in the WSDL
     *
     * @return array
     */
    public function getFunctions()
    {
        return $this->_functions;
    }

    /**
     * Load Functions
     *
     * @param unknown_type $definition
     */
    public function loadFunctions($definition)
    {
        require_once "Zend/Soap/AutoDiscover/Exception.php";
        throw new Zend_Soap_AutoDiscover_Exception("Function has no use in AutoDiscover.");
    }

    /**
     * Set Persistance
     *
     * @param int $mode
     */
    public function setPersistence($mode)
    {
        require_once "Zend/Soap/AutoDiscover/Exception.php";
        throw new Zend_Soap_AutoDiscover_Exception("Function has no use in AutoDiscover.");
    }

    /**
     * Returns an XSD Type for the given PHP type
     *
     * @param string $type PHP Type to get the XSD type for
     * @return string
     */
    public function getType($type)
    {
        if (!($this->_wsdl instanceof Zend_Soap_Wsdl)) {
            /** @todo Exception throwing may be more correct */

            // WSDL is not defined yet, so we can't recognize type in context of current service
            return '';
        } else {
            return $this->_wsdl->getType($type);
        }
    }
}

Soap/Client.php000066600000055116151256604610007417 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Soap
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Soap_Client_Exception */
require_once 'Zend/Soap/Client/Exception.php';

/** Zend_Soap_Server */
require_once 'Zend/Soap/Server.php';

/** Zend_Soap_Client_Local */
require_once 'Zend/Soap/Client/Local.php';

/** Zend_Soap_Client_Common */
require_once 'Zend/Soap/Client/Common.php';


/**
 * Zend_Soap_Client
 *
 * @category   Zend
 * @package    Zend_Soap
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Soap_Client
{
    /**
     * Encoding
     * @var string
     */
    protected $_encoding = 'UTF-8';

    /**
     * Array of SOAP type => PHP class pairings for handling return/incoming values
     * @var array
     */
    protected $_classmap = null;

    /**
     * Registered fault exceptions
     * @var array
     */
    protected $_faultExceptions = array();

    /**
     * SOAP version to use; SOAP_1_2 by default, to allow processing of headers
     * @var int
     */
    protected $_soapVersion = SOAP_1_2;

    /** Set of other SoapClient options */
    protected $_uri                 = null;
    protected $_location            = null;
    protected $_style               = null;
    protected $_use                 = null;
    protected $_login               = null;
    protected $_password            = null;
    protected $_proxy_host          = null;
    protected $_proxy_port          = null;
    protected $_proxy_login         = null;
    protected $_proxy_password      = null;
    protected $_local_cert          = null;
    protected $_passphrase          = null;
    protected $_compression         = null;
    protected $_connection_timeout  = null;

    /**
     * WSDL used to access server
     * It also defines Zend_Soap_Client working mode (WSDL vs non-WSDL)
     *
     * @var string
     */
    protected $_wsdl = null;

    /**
     * SoapClient object
     *
     * @var SoapClient
     */
    protected $_soapClient;

    /**
     * Last invoked method
     *
     * @var string
     */
    protected $_lastMethod = '';

    /**
     * Constructor
     *
     * @param string $wsdl
     * @param array $options
     */
    public function __construct($wsdl = null, $options = null)
    {
        if (!extension_loaded('soap')) {
            throw new Zend_Soap_Client_Exception('SOAP extension is not loaded.');
        }

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

    /**
     * Set wsdl
     *
     * @param string $wsdl
     * @return Zend_Soap_Client
     */
    public function setWsdl($wsdl)
    {
        $this->_wsdl = $wsdl;
        $this->_soapClient = null;

        return $this;
    }

    /**
     * Get wsdl
     *
     * @return string
     */
    public function getWsdl()
    {
        return $this->_wsdl;
    }

    /**
     * Set Options
     *
     * Allows setting options as an associative array of option => value pairs.
     *
     * @param  array $options
     * @return Zend_Soap_Client
     * @throws Zend_SoapClient_Exception
     */
    public function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            switch ($key) {
                case 'classmap':
                case 'classMap':
                    $this->setClassmap($value);
                    break;
                case 'encoding':
                    $this->setEncoding($value);
                    break;
                case 'soapVersion':
                case 'soap_version':
                    $this->setSoapVersion($value);
                    break;
                case 'wsdl':
                    $this->setWsdl($value);
                    break;
                case 'uri':
                    $this->setUri($value);
                    break;
                case 'location':
                    $this->setLocation($value);
                    break;
                case 'style':
                    $this->setStyle($value);
                    break;
                case 'use':
                    $this->setEncodingMethod($value);
                    break;
                case 'login':
                    $this->setHttpLogin($value);
                    break;
                case 'password':
                    $this->setHttpPassword($value);
                    break;
                case 'proxy_host':
                    $this->setProxyHost($value);
                    break;
                case 'proxy_port':
                    $this->setProxyPort($value);
                    break;
                case 'proxy_login':
                    $this->setProxyLogin($value);
                    break;
                case 'proxy_password':
                    $this->setProxyPassword($value);
                    break;
                case 'local_cert':
                    $this->setHttpsCertificate($value);
                    break;
                case 'passphrase':
                    $this->setHttpsCertPassphrase($value);
                    break;
                case 'compression':
                    $this->setCompressionOptions($value);
                    break;

                // Not used now
                // case 'connection_timeout':
                //     $this->_connection_timeout = $value;
                //    break;

                default:
                    throw new Zend_Soap_Client_Exception('Unknown SOAP client option');
                    break;
            }
        }

        return $this;
    }

    /**
     * Return array of options suitable for using with SoapClient constructor
     *
     * @return array
     */
    public function getOptions()
    {
        $options = array();

        $options['classmap']       = $this->getClassmap();
        $options['encoding']       = $this->getEncoding();
        $options['soap_version']   = $this->getSoapVersion();
        $options['wsdl']           = $this->getWsdl();
        $options['uri']            = $this->getUri();
        $options['location']       = $this->getLocation();
        $options['style']          = $this->getStyle();
        $options['use']            = $this->getEncodingMethod();
        $options['login']          = $this->getHttpLogin();
        $options['password']       = $this->getHttpPassword();
        $options['proxy_host']     = $this->getProxyHost();
        $options['proxy_port']     = $this->getProxyPort();
        $options['proxy_login']    = $this->getProxyLogin();
        $options['proxy_password'] = $this->getProxyPassword();
        $options['local_cert']     = $this->getHttpsCertificate();
        $options['passphrase']     = $this->getHttpsCertPassphrase();
        $options['compression']    = $this->getCompressionOptions();
//        $options['connection_timeout'] = $this->_connection_timeout;

        foreach ($options as $key => $value) {
            if ($value == null) {
                unset($options[$key]);
            }
        }

        return $options;
    }

    /**
     * Set SOAP version
     *
     * @param  int $version One of the SOAP_1_1 or SOAP_1_2 constants
     * @return Zend_Soap_Client
     * @throws Zend_Soap_Client_Exception with invalid soap version argument
     */
    public function setSoapVersion($version)
    {
        if (!in_array($version, array(SOAP_1_1, SOAP_1_2))) {
            throw new Zend_Soap_Client_Exception('Invalid soap version specified. Use SOAP_1_1 or SOAP_1_2 constants.');
        }
        $this->_soapVersion = $version;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Get SOAP version
     *
     * @return int
     */
    public function getSoapVersion()
    {
        return $this->_soapVersion;
    }

    /**
     * Set classmap
     *
     * @param  array $classmap
     * @return Zend_Soap_Client
     * @throws Zend_Soap_Client_Exception for any invalid class in the class map
     */
    public function setClassmap(array $classmap)
    {
        foreach ($classmap as $type => $class) {
            if (!class_exists($class)) {
                throw new Zend_Soap_Client_Exception('Invalid class in class map');
            }
        }

        $this->_classmap = $classmap;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Retrieve classmap
     *
     * @return mixed
     */
    public function getClassmap()
    {
        return $this->_classmap;
    }

    /**
     * Set encoding
     *
     * @param  string $encoding
     * @return Zend_Soap_Client
     * @throws Zend_Soap_Client_Exception with invalid encoding argument
     */
    public function setEncoding($encoding)
    {
        if (!is_string($encoding)) {
            throw new Zend_Soap_Client_Exception('Invalid encoding specified');
        }

        $this->_encoding = $encoding;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Get encoding
     *
     * @return string
     */
    public function getEncoding()
    {
        return $this->_encoding;
    }

    /**
     * Check for valid URN
     *
     * @param  string $urn
     * @return true
     * @throws Zend_Soap_Client_Exception on invalid URN
     */
    public function validateUrn($urn)
    {
        $segs = parse_url($urn);
        if (isset($segs['scheme'])) {
            return true;
        }

        throw new Zend_Soap_Client_Exception('Invalid URN');
    }

    /**
     * Set URI
     *
     * URI in Web Service the target namespace
     *
     * @param  string $uri
     * @return Zend_Soap_Client
     * @throws Zend_Soap_Client_Exception with invalid uri argument
     */
    public function setUri($uri)
    {
        $this->validateUrn($uri);
        $this->_uri = $uri;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Retrieve URI
     *
     * @return string
     */
    public function getUri()
    {
        return $this->_uri;
    }

    /**
     * Set Location
     *
     * URI in Web Service the target namespace
     *
     * @param  string $location
     * @return Zend_Soap_Client
     * @throws Zend_Soap_Client_Exception with invalid uri argument
     */
    public function setLocation($location)
    {
        $this->validateUrn($location);
        $this->_location = $location;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Retrieve URI
     *
     * @return string
     */
    public function getLocation()
    {
        return $this->_location;
    }

    /**
     * Set request style
     *
     * @param  int $style One of the SOAP_RPC or SOAP_DOCUMENT constants
     * @return Zend_Soap_Client
     * @throws Zend_Soap_Client_Exception with invalid style argument
     */
    public function setStyle($style)
    {
        if (!in_array($style, array(SOAP_RPC, SOAP_DOCUMENT))) {
            throw new Zend_Soap_Client_Exception('Invalid request style specified. Use SOAP_RPC or SOAP_DOCUMENT constants.');
        }

        $this->_style = $style;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Get request style
     *
     * @return int
     */
    public function getStyle()
    {
        return $this->_style;
    }

    /**
     * Set message encoding method
     *
     * @param  int $use One of the SOAP_ENCODED or SOAP_LITERAL constants
     * @return Zend_Soap_Client
     * @throws Zend_Soap_Client_Exception with invalid message encoding method argument
     */
    public function setEncodingMethod($use)
    {
        if (!in_array($use, array(SOAP_ENCODED, SOAP_LITERAL))) {
            throw new Zend_Soap_Client_Exception('Invalid message encoding method. Use SOAP_ENCODED or SOAP_LITERAL constants.');
        }

        $this->_use = $use;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Get message encoding method
     *
     * @return int
     */
    public function getEncodingMethod()
    {
        return $this->_use;
    }

    /**
     * Set HTTP login
     *
     * @param  string $login
     * @return Zend_Soap_Client
     */
    public function setHttpLogin($login)
    {
        $this->_login = $login;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Retrieve HTTP Login
     *
     * @return string
     */
    public function getHttpLogin()
    {
        return $this->_login;
    }

    /**
     * Set HTTP password
     *
     * @param  string $password
     * @return Zend_Soap_Client
     */
    public function setHttpPassword($password)
    {
        $this->_password = $password;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Retrieve HTTP Password
     *
     * @return string
     */
    public function getHttpPassword()
    {
        return $this->_password;
    }

    /**
     * Set proxy host
     *
     * @param  string $proxyHost
     * @return Zend_Soap_Client
     */
    public function setProxyHost($proxyHost)
    {
        $this->_proxy_host = $proxyHost;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Retrieve proxy host
     *
     * @return string
     */
    public function getProxyHost()
    {
        return $this->_proxy_host;
    }

    /**
     * Set proxy port
     *
     * @param  int $proxyPort
     * @return Zend_Soap_Client
     */
    public function setProxyPort($proxyPort)
    {
        $this->_proxy_port = (int)$proxyPort;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Retrieve proxy port
     *
     * @return int
     */
    public function getProxyPort()
    {
        return $this->_proxy_port;
    }

    /**
     * Set proxy login
     *
     * @param  string $proxyLogin
     * @return Zend_Soap_Client
     */
    public function setProxyLogin($proxyLogin)
    {
        $this->_proxy_login = $proxyLogin;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Retrieve proxy login
     *
     * @return string
     */
    public function getProxyLogin()
    {
        return $this->_proxy_login;
    }

    /**
     * Set proxy password
     *
     * @param  string $proxyLogin
     * @return Zend_Soap_Client
     */
    public function setProxyPassword($proxyPassword)
    {
        $this->_proxy_password = $proxyPassword;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Set HTTPS client certificate path
     *
     * @param  string $localCert local certificate path
     * @return Zend_Soap_Client
     * @throws Zend_Soap_Client_Exception with invalid local certificate path argument
     */
    public function setHttpsCertificate($localCert)
    {
        if (!is_readable($localCert)) {
            throw new Zend_Soap_Client_Exception('Invalid HTTPS client certificate path.');
        }

        $this->_local_cert = $localCert;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Get HTTPS client certificate path
     *
     * @return string
     */
    public function getHttpsCertificate()
    {
        return $this->_local_cert;
    }

    /**
     * Set HTTPS client certificate passphrase
     *
     * @param  string $passphrase
     * @return Zend_Soap_Client
     */
    public function setHttpsCertPassphrase($passphrase)
    {
        $this->_passphrase = $passphrase;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Get HTTPS client certificate passphrase
     *
     * @return string
     */
    public function getHttpsCertPassphrase()
    {
        return $this->_passphrase;
    }

    /**
     * Set compression options
     *
     * @param  int $compressionOptions
     * @return Zend_Soap_Client
     */
    public function setCompressionOptions($compressionOptions)
    {
        $this->_compression = $compressionOptions;

        $this->_soapClient = null;

        return $this;
    }

    /**
     * Get Compression options
     *
     * @return int
     */
    public function getCompressionOptions()
    {
        return $this->_compression;
    }

    /**
     * Retrieve proxy password
     *
     * @return string
     */
    public function getProxyPassword()
    {
        return $this->_proxy_password;
    }

    /**
     * Retrieve request XML
     *
     * @return string
     */
    public function getLastRequest()
    {
        if ($this->_soapClient !== null) {
            return $this->_soapClient->__getLastRequest();
        }

        return '';
    }

    /**
     * Get response XML
     *
     * @return string
     */
    public function getLastResponse()
    {
        if ($this->_soapClient !== null) {
            return $this->_soapClient->__getLastResponse();
        }

        return '';
    }

    /**
     * Retrieve request headers
     *
     * @return string
     */
    public function getLastRequestHeaders()
    {
        if ($this->_soapClient !== null) {
            return $this->_soapClient->__getLastRequestHeaders();
        }

        return '';
    }

    /**
     * Retrieve response headers
     *
     * @return string
     */
    public function getLastResponseHeaders()
    {
        if ($this->_soapClient !== null) {
            return $this->_soapClient->__getLastResponseHeaders();
        }

        return '';
    }

    /**
     * Retrieve last invoked method
     *
     * @return string
     */
    public function getLastMethod()
    {
        return $this->_lastMethod;
    }

    /**
     * Do request proxy method.
     *
     * May be overridden in subclasses
     *
     * @internal
     * @param Zend_Soap_Client_Common $client
     * @param string $request
     * @param string $location
     * @param string $action
     * @param int    $version
     * @param int    $one_way
     * @return mixed
     */
    public function _doRequest(Zend_Soap_Client_Common $client, $request, $location, $action, $version, $one_way = null)
    {
        // Perform request as is
        if ($one_way == null) {
            return call_user_func(array($client,'SoapClient::__doRequest'), $request, $location, $action, $version);
        } else {
            return call_user_func(array($client,'SoapClient::__doRequest'), $request, $location, $action, $version, $one_way);
        }
    }

    /**
     * Initialize SOAP Client object
     *
     * @throws Zend_Soap_Client_Exception
     */
    protected function _initSoapClientObject()
    {
        $wsdl = $this->getWsdl();
        $options = array_merge($this->getOptions(), array('trace' => true));


        if ($wsdl == null) {
            if (!isset($options['location'])) {
                throw new Zend_Soap_Client_Exception('\'location\' parameter is required in non-WSDL mode.');
            }
            if (!isset($options['uri'])) {
                throw new Zend_Soap_Client_Exception('\'uri\' parameter is required in non-WSDL mode.');
            }
        } else {
            if (isset($options['use'])) {
                throw new Zend_Soap_Client_Exception('\'use\' parameter only works in non-WSDL mode.');
            }
            if (isset($options['style'])) {
                throw new Zend_Soap_Client_Exception('\'style\' parameter only works in non-WSDL mode.');
            }
        }
        unset($options['wsdl']);

        $this->_soapClient = new Zend_Soap_Client_Common(array($this, '_doRequest'), $wsdl, $options);
    }


    /**
     * Perform arguments pre-processing
     *
     * My be overridden in descendant classes
     *
     * @param array $arguments
     */
    protected function _preProcessArguments($arguments)
    {
        // Do nothing
        return $arguments;
    }

    /**
     * Perform result pre-processing
     *
     * My be overridden in descendant classes
     *
     * @param array $arguments
     */
    protected function _preProcessResult($result)
    {
        // Do nothing
        return $result;
    }

    /**
     * Perform a SOAP call
     *
     * @param string $name
     * @param array  $arguments
     * @return mixed
     */
    public function __call($name, $arguments)
    {
        if ($this->_soapClient == null) {
            $this->_initSoapClientObject();
        }

        $this->_lastMethod = $name; 
        
        $result = call_user_func_array(array($this->_soapClient, $name), $this->_preProcessArguments($arguments));

        return $this->_preProcessResult($result);
    }


    /**
     * Return a list of available functions
     *
     * @return array
     * @throws Zend_Soap_Client_Exception
     */
    public function getFunctions()
    {
        if ($this->getWsdl() == null) {
            throw new Zend_Soap_Client_Exception('\'getFunctions\' method is available only in WSDL mode.');
        }

        if ($this->_soapClient == null) {
            $this->_initSoapClientObject();
        }

        return $this->_soapClient->__getFunctions();
    }


    /**
     * Get used types.
     *
     * @return array
     */

    /**
     * Return a list of SOAP types
     *
     * @return array
     * @throws Zend_Soap_Client_Exception
     */
    public function getTypes()
    {
        if ($this->getWsdl() == null) {
            throw new Zend_Soap_Client_Exception('\'getTypes\' method is available only in WSDL mode.');
        }

        if ($this->_soapClient == null) {
            $this->_initSoapClientObject();
        }

        return $this->_soapClient->__getTypes();
    }
}
Gdata/Books.php000066600000014424151256604610007371 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

require_once 'Zend/Gdata.php';

/**
 * @see Zend_Gdata_DublinCore
 */
require_once 'Zend/Gdata/DublinCore.php';

/**
 * @see Zend_Gdata_Books_CollectionEntry
 */
require_once 'Zend/Gdata/Books/CollectionEntry.php';

/**
 * @see Zend_Gdata_Books_CollectionFeed
 */
require_once 'Zend/Gdata/Books/CollectionFeed.php';

/**
 * @see Zend_Gdata_Books_VolumeEntry
 */
require_once 'Zend/Gdata/Books/VolumeEntry.php';

/**
 * @see Zend_Gdata_Books_VolumeFeed
 */
require_once 'Zend/Gdata/Books/VolumeFeed.php';

/**
 * Service class for interacting with the Books service
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Books extends Zend_Gdata
{
    const VOLUME_FEED_URI = 'http://books.google.com/books/feeds/volumes';
    const MY_LIBRARY_FEED_URI = 'http://books.google.com/books/feeds/users/me/collections/library/volumes';
    const MY_ANNOTATION_FEED_URI = 'http://books.google.com/books/feeds/users/me/volumes';
    const AUTH_SERVICE_NAME = 'print';

    /**
     * Namespaces used for Zend_Gdata_Books
     *
     * @var array
     */
    public static $namespaces = array(
        array('gbs', 'http://schemas.google.com/books/2008', 1, 0),
        array('dc', 'http://purl.org/dc/terms', 1, 0)
    );

    /**
     * Create Zend_Gdata_Books object
     *
     * @param Zend_Http_Client $client (optional) The HTTP client to use when
     *          when communicating with the Google servers.
     * @param string $applicationId The identity of the app in the form of Company-AppName-Version
     */
    public function __construct($client = null, $applicationId = 'MyCompany-MyApp-1.0')
    {
        $this->registerPackage('Zend_Gdata_Books');
        $this->registerPackage('Zend_Gdata_Books_Extension');
        parent::__construct($client, $applicationId);
        $this->_httpClient->setParameterPost('service', self::AUTH_SERVICE_NAME);
     }

    /**
     * Retrieves a feed of volumes.
     *
     * @param Zend_Gdata_Query|string|null $location (optional) The URL to
     *        query or a Zend_Gdata_Query object from which a URL can be
     *        determined.
     * @return Zend_Gdata_Books_VolumeFeed The feed of volumes found at the
     *         specified URL.
     */
    public function getVolumeFeed($location = null)
    {
        if ($location == null) {
            $uri = self::VOLUME_FEED_URI;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed');
    }

    /**
     * Retrieves a specific volume entry.
     *
     * @param string|null $volumeId The volumeId of interest.
     * @param Zend_Gdata_Query|string|null $location (optional) The URL to
     *        query or a Zend_Gdata_Query object from which a URL can be
     *        determined.
     * @return Zend_Gdata_Books_VolumeEntry The feed of volumes found at the
     *         specified URL.
     */
    public function getVolumeEntry($volumeId = null, $location = null)
    {
        if ($volumeId !== null) {
            $uri = self::VOLUME_FEED_URI . "/" . $volumeId;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getEntry($uri, 'Zend_Gdata_Books_VolumeEntry');
    }

    /**
     * Retrieves a feed of volumes, by default the User library feed.
     *
     * @param Zend_Gdata_Query|string|null $location (optional) The URL to
     *        query.
     * @return Zend_Gdata_Books_VolumeFeed The feed of volumes found at the
     *         specified URL.
     */
    public function getUserLibraryFeed($location = null)
    {
        if ($location == null) {
            $uri = self::MY_LIBRARY_FEED_URI;
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed');
    }

    /**
     * Retrieves a feed of volumes, by default the User annotation feed
     *
     * @param Zend_Gdata_Query|string|null $location (optional) The URL to
     *        query.
     * @return Zend_Gdata_Books_VolumeFeed The feed of volumes found at the
     *         specified URL.
     */
    public function getUserAnnotationFeed($location = null)
    {
        if ($location == null) {
            $uri = self::MY_ANNOTATION_FEED_URI;
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_Books_VolumeFeed');
    }

    /**
     * Insert a Volume / Annotation
     *
     * @param Zend_Gdata_Books_VolumeEntry $entry
     * @param Zend_Gdata_Query|string|null $location (optional) The URL to
     *        query
     * @return Zend_Gdata_Books_VolumeEntry The inserted volume entry.
     */
    public function insertVolume($entry, $location = null)
    {
        if ($location == null) {
            $uri = self::MY_LIBRARY_FEED_URI;
        } else {
            $uri = $location;
        }
        return parent::insertEntry(
            $entry, $uri, 'Zend_Gdata_Books_VolumeEntry');
    }

    /**
     * Delete a Volume
     *
     * @param Zend_Gdata_Books_VolumeEntry $entry
     * @return void
     */
    public function deleteVolume($entry)
    {
        $entry->delete();
    }

}
Gdata/Geo.php000066600000004167151256604610007031 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Geo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata
 */
require_once 'Zend/Gdata.php';

/**
 * Service class for interacting with the services which use the
 * GeoRSS + GML extensions.
 * @link http://georss.org/
 * @link http://www.opengis.net/gml/
 * @link http://code.google.com/apis/picasaweb/reference.html#georss_reference
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Geo
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Geo extends Zend_Gdata
{

    /**
     * Namespaces used for Zend_Gdata_Geo
     *
     * @var array
     */
    public static $namespaces = array(
        array('georss', 'http://www.georss.org/georss', 1, 0),
        array('gml', 'http://www.opengis.net/gml', 1, 0)
    );


    /**
     * Create Zend_Gdata_Geo object
     *
     * @param Zend_Http_Client $client (optional) The HTTP client to use when
     *          when communicating with the Google Apps servers.
     * @param string $applicationId The identity of the app in the form of Company-AppName-Version
     */
    public function __construct($client = null, $applicationId = 'MyCompany-MyApp-1.0')
    {
        $this->registerPackage('Zend_Gdata_Geo');
        $this->registerPackage('Zend_Gdata_Geo_Extension');
        parent::__construct($client, $applicationId);
    }

}
Gdata/YouTube/Extension/Status.php000066600000002663151256604610013151 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:status element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Status extends Zend_Gdata_Extension
{

    protected $_rootElement = 'status';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/AboutMe.php000066600000002666151256604610013225 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:aboutMe element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_AboutMe extends Zend_Gdata_Extension
{

    protected $_rootElement = 'aboutMe';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Link.php000066600000010272151256604610012556 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension_Link
 */
require_once 'Zend/Gdata/App/Extension/Link.php';

/**
 * @see Zend_Gdata_YouTube_Extension_Token
 */
require_once 'Zend/Gdata/YouTube/Extension/Token.php';


/**
 * Specialized Link class for use with YouTube. Enables use of yt extension elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Link extends Zend_Gdata_App_Extension_Link
{

    protected $_token = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_Link object.
     * @see Zend_Gdata_App_Extension_Link#__construct
     * @param Zend_Gdata_YouTube_Extension_Token $token
     */
    public function __construct($href = null, $rel = null, $type = null,
            $hrefLang = null, $title = null, $length = null, $token = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct($href, $rel, $type, $hrefLang, $title, $length);
        $this->_token = $token;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_token != null) {
            $element->appendChild($this->_token->getDOM($element->ownerDocument));
        }
        return $element;
    }

    /**
     * Creates individual Entry objects of the appropriate type and
     * stores them as members of this entry based upon DOM data.
     *
     * @param DOMNode $child The DOMNode to process
     */
    protected function takeChildFromDOM($child)
    {
        $absoluteNodeName = $child->namespaceURI . ':' . $child->localName;
        switch ($absoluteNodeName) {
        case $this->lookupNamespace('yt') . ':' . 'token':
            $token = new Zend_Gdata_YouTube_Extension_Token();
            $token->transferFromDOM($child);
            $this->_token = $token;
            break;
        default:
            parent::takeChildFromDOM($child);
            break;
        }
    }

    /**
     * Get the value for this element's token attribute.
     *
     * @return Zend_Gdata_YouTube_Extension_Token The token element.
     */
    public function getToken()
    {
        return $this->_token;
    }

    /**
     * Set the value for this element's token attribute.
     *
     * @param Zend_Gdata_YouTube_Extension_Token $value The desired value for this attribute.
     * @return Zend_YouTube_Extension_Link The element being modified.
     */
    public function setToken($value)
    {
        $this->_token = $value;
        return $this;
    }

    /**
    * Get the value of this element's token attribute.
    *
    * @return string The token's text value
    */
    public function getTokenValue()
    {
      return $this->getToken()->getText();
    }

}
Gdata/YouTube/Extension/Private.php000066600000005065151256604610013277 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:private element used by the YouTube data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Private extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'yt';
    protected $_rootElement = 'private';

    /**
     * Constructs a new Zend_Gdata_YouTube_Extension_Private object.
     */
    public function __construct()
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and valueare
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        parent::takeAttributeFromDOM($attribute);
    }

}
Gdata/YouTube/Extension/State.php000066600000013467151256604610012752 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:state element used by the YouTube data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_State extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'yt';
    protected $_rootElement = 'state';
    protected $_name = null;
    protected $_reasonCode = null;
    protected $_helpUrl = null;

    /**
     * Constructs a new Zend_Gdata_YouTube_Extension_State object.
     *
     * @param string $explanation(optional) The explanation of this state
     * @param string $name(optional) The name value
     * @param string $reasonCode(optional) The reasonCode value
     * @param string $helpUrl(optional) The helpUrl value
     */
    public function __construct($explanation = null, $name = null,
                                $reasonCode = null, $helpUrl = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $explanation;
        $this->_name = $name;
        $this->_reasonCode = $reasonCode;
        $this->_helpUrl = $reasonCode;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_name !== null) {
            $element->setAttribute('name', $this->_name);
        }
        if ($this->_reasonCode !== null) {
            $element->setAttribute('reasonCode', $this->_reasonCode);
        }
        if ($this->_helpUrl !== null) {
            $element->setAttribute('helpUrl', $this->_helpUrl);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and valueare
     * stored in an array.
     * TODO: Convert attributes to proper types
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'name':
            $this->_name = $attribute->nodeValue;
            break;
        case 'reasonCode':
            $this->_reasonCode = $attribute->nodeValue;
            break;
        case 'helpUrl':
            $this->_helpUrl = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's name attribute.
     *
     * @return int The value associated with this attribute.
     */
    public function getName()
    {
        return $this->_name;
    }

    /**
     * Set the value for this element's name attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_State The element being modified.
     */
    public function setName($value)
    {
        $this->_name = $value;
        return $this;
    }

    /**
     * Get the value for this element's reasonCode attribute.
     *
     * @return int The value associated with this attribute.
     */
    public function getReasonCode()
    {
        return $this->_reasonCode;
    }

    /**
     * Set the value for this element's reasonCode attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_State The element being modified.
     */
    public function setReasonCode($value)
    {
        $this->_reasonCode = $value;
        return $this;
    }

    /**
     * Get the value for this element's helpUrl attribute.
     *
     * @return int The value associated with this attribute.
     */
    public function getHelpUrl()
    {
        return $this->_helpUrl;
    }

    /**
     * Set the value for this element's helpUrl attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_State The element being modified.
     */
    public function setHelpUrl($value)
    {
        $this->_helpUrl = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     *
     * @return string
     */
    public function __toString()
    {
        return $this->_text;
    }

}
Gdata/YouTube/Extension/Statistics.php000066600000023421151256604610014013 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:statistics element used by the YouTube data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Statistics extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'yt';
    protected $_rootElement = 'statistics';

    /**
     * The videoWatchCount attribute specifies the number of videos
     * that a user has watched on YouTube. The videoWatchCount attribute
     * is only specified when the <yt:statistics> tag appears within a
     * user profile entry.
     *
     * @var integer
     */
    protected $_videoWatchCount = null;

    /**
     * When the viewCount attribute refers to a video entry, the attribute
     * specifies the number of times that the video has been viewed.
     * When the viewCount attribute refers to a user profile, the attribute
     * specifies the number of times that the user's profile has been
     * viewed.
     *
     * @var integer
     */
    protected $_viewCount = null;

    /**
     * The subscriberCount attribute specifies the number of YouTube users
     * who have subscribed to a particular user's YouTube channel.
     * The subscriberCount attribute is only specified when the
     * <yt:statistics> tag appears within a user profile entry.
     * 
     * @var integer
     */
    protected $_subscriberCount = null;

    /**
     * The lastWebAccess attribute indicates the most recent time that
     * a particular user used YouTube.
     *
     * @var string
     */
    protected $_lastWebAccess = null;

    /**
     * The favoriteCount attribute specifies the number of YouTube users
     * who have added a video to their list of favorite videos. The
     * favoriteCount attribute is only specified when the
     * <yt:statistics> tag appears within a video entry.
     *
     * @var integer
     */
    protected $_favoriteCount = null;

    /**
     * Constructs a new Zend_Gdata_YouTube_Extension_Statistics object.
     * @param string $viewCount(optional) The viewCount value
     * @param string $videoWatchCount(optional) The videoWatchCount value
     * @param string $subscriberCount(optional) The subscriberCount value
     * @param string $lastWebAccess(optional) The lastWebAccess value
     * @param string $favoriteCount(optional) The favoriteCount value
     */
    public function __construct($viewCount = null, $videoWatchCount = null,
        $subscriberCount = null, $lastWebAccess = null,
        $favoriteCount = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_viewCount = $viewCount;
        $this->_videoWatchCount = $videoWatchCount;
        $this->_subscriberCount = $subscriberCount;
        $this->_lastWebAccess = $lastWebAccess;
        $this->_favoriteCount = $favoriteCount;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_videoWatchCount !== null) {
            $element->setAttribute('watchCount', $this->_videoWatchCount);
        }
        if ($this->_viewCount !== null) {
            $element->setAttribute('viewCount', $this->_viewCount);
        }
        if ($this->_subscriberCount !== null) {
            $element->setAttribute('subscriberCount',
                $this->_subscriberCount);
        }
        if ($this->_lastWebAccess !== null) {
            $element->setAttribute('lastWebAccess',
                $this->_lastWebAccess);
        }
        if ($this->_favoriteCount !== null) {
            $element->setAttribute('favoriteCount',
                $this->_favoriteCount);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and valueare
     * stored in an array.
     * TODO: Convert attributes to proper types
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'videoWatchCount':
            $this->_videoWatchCount = $attribute->nodeValue;
            break;
        case 'viewCount':
            $this->_viewCount = $attribute->nodeValue;
            break;
        case 'subscriberCount':
            $this->_subscriberCount = $attribute->nodeValue;
            break;
        case 'lastWebAccess':
            $this->_lastWebAccess = $attribute->nodeValue;
            break;
        case 'favoriteCount':
            $this->_favoriteCount = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's viewCount attribute.
     *
     * @return int The value associated with this attribute.
     */
    public function getViewCount()
    {
        return $this->_viewCount;
    }

    /**
     * Set the value for this element's viewCount attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_Statistics The element being
     * modified.
     */
    public function setViewCount($value)
    {
        $this->_viewCount = $value;
        return $this;
    }

    /**
     * Get the value for this element's videoWatchCount attribute.
     *
     * @return int The value associated with this attribute.
     */
    public function getVideoWatchCount()
    {
        return $this->_videoWatchCount;
    }

    /**
     * Set the value for this element's videoWatchCount attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_Statistics The element being 
     * modified.
     */
    public function setVideoWatchCount($value)
    {
        $this->_videoWatchCount = $value;
        return $this;
    }

    /**
     * Get the value for this element's subscriberCount attribute.
     *
     * @return int The value associated with this attribute.
     */
    public function getSubscriberCount()
    {
        return $this->_subscriberCount;
    }

    /**
     * Set the value for this element's subscriberCount attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_Statistics The element being 
     * modified.
     */
    public function setSubscriberCount($value)
    {
        $this->_subscriberCount = $value;
        return $this;
    }

    /**
     * Get the value for this element's lastWebAccess attribute.
     *
     * @return int The value associated with this attribute.
     */
    public function getLastWebAccess()
    {
        return $this->_lastWebAccess;
    }

    /**
     * Set the value for this element's lastWebAccess attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_Statistics The element being 
     * modified.
     */
    public function setLastWebAccess($value)
    {
        $this->_lastWebAccess = $value;
        return $this;
    }

    /**
     * Get the value for this element's favoriteCount attribute.
     *
     * @return int The value associated with this attribute.
     */
    public function getFavoriteCount()
    {
        return $this->_favoriteCount;
    }

    /**
     * Set the value for this element's favoriteCount attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_Statistics The element being 
     * modified.
     */
    public function setFavoriteCount($value)
    {
        $this->_favoriteCount = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     *
     * @return string
     */
    public function __toString()
    {
        return 'View Count=' . $this->_viewCount .
            ' VideoWatchCount=' . $this->_videoWatchCount .
            ' SubscriberCount=' . $this->_subscriberCount .
            ' LastWebAccess=' . $this->_lastWebAccess .
            ' FavoriteCount=' . $this->_favoriteCount;
    }

}
Gdata/YouTube/Extension/FirstName.php000066600000002674151256604610013560 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:firstName element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_FirstName extends Zend_Gdata_Extension
{

    protected $_rootElement = 'firstName';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Occupation.php000066600000002677151256604610013777 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:occupation element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Occupation extends Zend_Gdata_Extension
{

    protected $_rootElement = 'occupation';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Token.php000066600000004304151256604610012740 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:token element used by the YouTube data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Token extends Zend_Gdata_App_Extension
{

    protected $_rootNamespace = 'yt';
    protected $_rootElement = 'token';

    /**
     * Constructs a new Zend_Gdata_YouTube_Extension_Token object.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        return $element;
    }

}
Gdata/YouTube/Extension/Position.php000066600000004646151256604610013475 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Data model class to represent a playlist item's position in the list (yt:position)
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Position extends Zend_Gdata_Extension
{

    protected $_rootElement = 'position';
    protected $_rootNamespace = 'yt';

    /**
     * Constructs a new Zend_Gdata_YouTube_Extension_Position object.
     *
     * @param string $value (optional) The 1-based position in the playlist
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $value;
    }

    /**
     * Get the value for the position in the playlist
     *
     * @return int The 1-based position in the playlist
     */
    public function getValue()
    {
        return $this->_text;
    }

    /**
     * Set the value for the position in the playlist
     *
     * @param int $value The 1-based position in the playlist
     * @return Zend_Gdata_Extension_Visibility The element being modified
     */
    public function setValue($value)
    {
        $this->_text = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getValue();
    }

}

Gdata/YouTube/Extension/Hobbies.php000066600000002666151256604610013244 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:hobbies element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Hobbies extends Zend_Gdata_Extension
{

    protected $_rootElement = 'hobbies';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Movies.php000066600000002663151256604610013130 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:movies element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Movies extends Zend_Gdata_Extension
{

    protected $_rootElement = 'movies';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Username.php000066600000002671151256604610013444 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:username element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Username extends Zend_Gdata_Extension
{

    protected $_rootElement = 'username';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Hometown.php000066600000002671151256604610013465 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:hometown element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Hometown extends Zend_Gdata_Extension
{

    protected $_rootElement = 'hometown';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Books.php000066600000002660151256604610012740 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:books element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Books extends Zend_Gdata_Extension
{

    protected $_rootElement = 'books';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Control.php000066600000010207151256604610013277 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension_Control
 */
require_once 'Zend/Gdata/App/Extension/Control.php';

/**
 * @see Zend_Gdata_YouTube_Extension_State
 */
require_once 'Zend/Gdata/YouTube/Extension/State.php';


/**
 * Specialized Control class for use with YouTube. Enables use of yt extension elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Control extends Zend_Gdata_App_Extension_Control
{

    protected $_state = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_Control object.
     * @see Zend_Gdata_App_Extension_Control#__construct
     * @param Zend_Gdata_App_Extension_Draft $draft
     * @param Zend_Gdata_YouTube_Extension_State $state
     */
    public function __construct($draft = null, $state = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct($draft);
        $this->_state = $state;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_state != null) {
            $element->appendChild($this->_state->getDOM($element->ownerDocument));
        }
        return $element;
    }

    /**
     * Creates individual Entry objects of the appropriate type and
     * stores them as members of this entry based upon DOM data.
     *
     * @param DOMNode $child The DOMNode to process
     */
    protected function takeChildFromDOM($child)
    {
        $absoluteNodeName = $child->namespaceURI . ':' . $child->localName;
        switch ($absoluteNodeName) {
        case $this->lookupNamespace('yt') . ':' . 'state':
            $state = new Zend_Gdata_YouTube_Extension_State();
            $state->transferFromDOM($child);
            $this->_state = $state;
            break;
        default:
            parent::takeChildFromDOM($child);
            break;
        }
    }

    /**
     * Get the value for this element's state attribute.
     *
     * @return Zend_Gdata_YouTube_Extension_State The state element.
     */
    public function getState()
    {
        return $this->_state;
    }

    /**
     * Set the value for this element's state attribute.
     *
     * @param Zend_Gdata_YouTube_Extension_State $value The desired value for this attribute.
     * @return Zend_YouTube_Extension_Control The element being modified.
     */
    public function setState($value)
    {
        $this->_state = $value;
        return $this;
    }

    /**
    * Get the value of this element's state attribute.
    *
    * @return string The state's text value
    */
    public function getStateValue()
    {
      return $this->getState()->getText();
    }

}
Gdata/YouTube/Extension/LastName.php000066600000002671151256604610013371 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:lastName element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_LastName extends Zend_Gdata_Extension
{

    protected $_rootElement = 'lastName';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Age.php000066600000002652151256604610012360 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:age element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Age extends Zend_Gdata_Extension
{

    protected $_rootElement = 'age';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Recorded.php000066600000002671151256604610013414 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:recorded element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Recorded extends Zend_Gdata_Extension
{

    protected $_rootElement = 'recorded';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/MediaCredit.php000066600000012103151256604610014026 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the YouTube specific media:credit element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_MediaCredit extends Zend_Gdata_Extension
{

    protected $_rootElement = 'credit';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_role = null;

    /**
     * @var string
     */
    protected $_scheme = null;

    /**
     * Represents the value of the yt:type attribute.
     *
     * Set to 'partner' if the uploader of this video is a YouTube
     * partner.
     *
     * @var string
     */
    protected $_yttype = null;

    /**
     * Creates an individual MediaCredit object.
     *
     * @param string $text
     * @param string $role
     * @param string $scheme
     */
    public function __construct($text = null, $role = null,  $scheme = null,
        $yttype = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_text = $text;
        $this->_role = $role;
        $this->_scheme = $scheme;
        $this->_yttype = $yttype;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_role !== null) {
            $element->setAttribute('role', $this->_role);
        }
        if ($this->_scheme !== null) {
            $element->setAttribute('scheme', $this->_scheme);
        }
        if ($this->_yttype !== null) {
            $element->setAttributeNS('http://gdata.youtube.com/schemas/2007',
                'yt:type', $this->_yttype);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
            case 'role':
                $this->_role = $attribute->nodeValue;
                break;
            case 'scheme':
                $this->_scheme = $attribute->nodeValue;
                break;
            case 'type':
                $this->_yttype = $attribute->nodeValue;
                break;
            default:
                parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getRole()
    {
        return $this->_role;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaCredit Provides a fluent
     *         interface
     */
    public function setRole($value)
    {
        $this->_role = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getScheme()
    {
        return $this->_scheme;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaCredit Provides a fluent
     *         interface
     */
    public function setScheme($value)
    {
        $this->_scheme = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getYTtype()
    {
        return $this->_yttype;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaCredit Provides a fluent
     *         interface
     */
    public function setYTtype($value)
    {
        $this->_yttype = $value;
        return $this;
    }

}Gdata/YouTube/Extension/Racy.php000066600000007320151256604610012557 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:racy element used by the YouTube data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Racy extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'yt';
    protected $_rootElement = 'racy';
    protected $_state = null;

    /**
     * Constructs a new Zend_Gdata_YouTube_Extension_Racy object.
     * @param bool $state(optional) The state value of the element.
     */
    public function __construct($state = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_state = $state;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_state !== null) {
            $element->setAttribute('state', $this->_state);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'state':
            $this->_state = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's state attribute.
     *
     * @return bool The value associated with this attribute.
     */
    public function getState()
    {
        return $this->_state;
    }

    /**
     * Set the value for this element's state attribute.
     *
     * @param bool $value The desired value for this attribute.
     * @return Zend_Gdata_YouTube_Extension_Racy The element being modified.
     */
    public function setState($value)
    {
        $this->_state = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     */
    public function __toString()
    {
        return $this->_state;
    }

}
Gdata/YouTube/Extension/MediaRating.php000066600000010176151256604610014050 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the media:rating element specific to YouTube.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_MediaRating extends Zend_Gdata_Extension
{

    protected $_rootElement = 'rating';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_scheme = null;

    /**
     * @var string
     */
    protected $_country = null;

    /**
     * Constructs a new MediaRating element
     *
     * @param string $text
     * @param string $scheme
     * @param string $country
     */
    public function __construct($text = null, $scheme = null, $country = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_scheme = $scheme;
        $this->_country = $country;
        $this->_text = $text;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     *         child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_scheme !== null) {
            $element->setAttribute('scheme', $this->_scheme);
        }
        if ($this->_country != null) {
            $element->setAttribute('country', $this->_country);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'scheme':
            $this->_scheme = $attribute->nodeValue;
            break;
        case 'country':
            $this->_country = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getScheme()
    {
        return $this->_scheme;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_YouTube_Extension_MediaRating Provides a fluent interface
     */
    public function setScheme($value)
    {
        $this->_scheme = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getCountry()
    {
        return $this->_country;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_YouTube_Extension_MediaRating Provides a fluent interface
     */
    public function setCountry($value)
    {
        $this->_country = $value;
        return $this;
    }


}
Gdata/YouTube/Extension/ReleaseDate.php000066600000002702151256604610014036 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:releaseDate element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_ReleaseDate extends Zend_Gdata_Extension
{

    protected $_rootElement = 'releaseDate';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/PlaylistTitle.php000066600000002710151256604610014462 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:playlistTitle element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_PlaylistTitle extends Zend_Gdata_Extension
{

    protected $_rootElement = 'playlistTitle';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Music.php000066600000002660151256604610012743 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:music element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Music extends Zend_Gdata_Extension
{

    protected $_rootElement = 'music';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Relationship.php000066600000002705151256604610014324 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:relationship element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Relationship extends Zend_Gdata_Extension
{

    protected $_rootElement = 'relationship';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/PlaylistId.php000066600000002677151256604610013751 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:playlistId element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_PlaylistId extends Zend_Gdata_Extension
{

    protected $_rootElement = 'playlistId';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/School.php000066600000002663151256604610013115 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:school element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_School extends Zend_Gdata_Extension
{

    protected $_rootElement = 'school';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/YouTube/Extension/Company.php000066600000002666151256604610013277 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the yt:company element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube_Extension_Company extends Zend_Gdata_Extension
{

    protected $_rootElement = 'company';
    protected $_rootNamespace = 'yt';

    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/Gapps/Extension/Name.php000066600000012523151256604610012220 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Gapps
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Gapps
 */
require_once 'Zend/Gdata/Gapps.php';

/**
 * Represents the apps:name element used by the Apps data API. This is used
 * to represent a user's full name. This class is usually contained within
 * instances of Zend_Gdata_Gapps_UserEntry.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Gapps
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Gapps_Extension_Name extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'apps';
    protected $_rootElement = 'name';

    /**
     * The associated user's family name.
     *
     * @var string
     */
    protected $_familyName = null;

    /**
     * The associated user's given name.
     *
     * @var string
     */
    protected $_givenName = null;

    /**
     * Constructs a new Zend_Gdata_Gapps_Extension_Name object.
     *
     * @param string $familyName (optional) The familyName to be set for this
     *          object.
     * @param string $givenName (optional) The givenName to be set for this
     *          object.
     */
    public function __construct($familyName = null, $givenName = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces);
        parent::__construct();
        $this->_familyName = $familyName;
        $this->_givenName = $givenName;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_familyName !== null) {
            $element->setAttribute('familyName', $this->_familyName);
        }
        if ($this->_givenName !== null) {
            $element->setAttribute('givenName', $this->_givenName);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'familyName':
            $this->_familyName = $attribute->nodeValue;
            break;
        case 'givenName':
            $this->_givenName = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's familyName attribute.
     *
     * @see setFamilyName
     * @return string The requested attribute.
     */
    public function getFamilyName()
    {
        return $this->_familyName;
    }

    /**
     * Set the value for this element's familyName attribute. This
     * represents a user's family name.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Gapps_Extension_Name Provides a fluent interface..
     */
    public function setFamilyName($value)
    {
        $this->_familyName = $value;
        return $this;
    }

    /**
     * Get the value for this element's givenName attribute.
     *
     * @see setGivenName
     * @return string The requested attribute.
     */
    public function getGivenName()
    {
        return $this->_givenName;
    }

    /**
     * Set the value for this element's givenName attribute. This
     * represents a user's given name.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Gapps_Extension_Name Provides a fluent interface.
     */
    public function setGivenName($value)
    {
        $this->_givenName = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     */
    public function __toString()
    {
        return $this->getGivenName() . ' ' . $this->getFamilyName();
    }

}
Gdata/Gapps/Extension/EmailList.php000066600000010432151256604610013220 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Gapps
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Gapps
 */
require_once 'Zend/Gdata/Gapps.php';

/**
 * Represents the apps:emailList element used by the Apps data API. This
 * class represents properties of an email list and is usually contained
 * within an instance of Zend_Gdata_Gapps_EmailListEntry.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Gapps
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Gapps_Extension_EmailList extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'apps';
    protected $_rootElement = 'emailList';

    /**
     * The name of the email list. This name is used as the email address
     * for this list.
     *
     * @var string
     */
    protected $_name = null;

    /**
     * Constructs a new Zend_Gdata_Gapps_Extension_EmailList object.
     *
     * @param string $name (optional) The name to be used for this email list.
     */
    public function __construct($name = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Gapps::$namespaces);
        parent::__construct();
        $this->_name = $name;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_name !== null) {
            $element->setAttribute('name', $this->_name);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'name':
            $this->_name = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's name attribute.
     *
     * @see setName
     * @return string The requested attribute.
     */
    public function getName()
    {
        return $this->_name;
    }

    /**
     * Set the value for this element's name attribute. This is the unique
     * name which will be used to identify this email list within this
     * domain, and will be used to form this email list's email address.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Gapps_Extension_EmailList The element being modified.
     */
    public function setName($value)
    {
        $this->_name = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getName();
    }

}
Gdata/Exif/Extension/ImageUniqueId.php000066600000003333151256604610013646 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Exif
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Exif
 */
require_once 'Zend/Gdata/Exif.php';

/**
 * Represents the exif:imageUniqueId element used by the Gdata Exif extensions.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Exif
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Exif_Extension_ImageUniqueId extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'exif';
    protected $_rootElement = 'imageUniqueID';

    /**
     * Constructs a new Zend_Gdata_Exif_Extension_ImageUniqueId object.
     *
     * @param string $text (optional) The value to use for this element.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Exif::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Exif/Extension/Time.php000066600000003267151256604610012064 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Exif
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Exif
 */
require_once 'Zend/Gdata/Exif.php';

/**
 * Represents the exif:time element used by the Gdata Exif extensions.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Exif
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Exif_Extension_Time extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'exif';
    protected $_rootElement = 'time';

    /**
     * Constructs a new Zend_Gdata_Exif_Extension_Time object.
     *
     * @param string $text (optional) The value to use for this element.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Exif::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Exif/Extension/Iso.php000066600000003263151256604610011714 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Exif
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Exif
 */
require_once 'Zend/Gdata/Exif.php';

/**
 * Represents the exif:iso element used by the Gdata Exif extensions.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Exif
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Exif_Extension_Iso extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'exif';
    protected $_rootElement = 'iso';

    /**
     * Constructs a new Zend_Gdata_Exif_Extension_Iso object.
     *
     * @param string $text (optional) The value to use for this element.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Exif::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/BytesUsed.php000066600000003404151256604610013447 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:bytesUsed element used by the API.
 * This indicates the number of bytes of storage used by an album.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_BytesUsed extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'bytesUsed';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_BytesUsed object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/CommentingEnabled.php000066600000003525151256604610015117 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:commentingEnabled element used by the API.
 * This class represents whether commenting is enabled for a given
 * entry.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_CommentingEnabled extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'commentingEnabled';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_CommentingEnabled object.
     *
     * @param string $text (optional) Whether commenting should be enabled
     *          or not.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Id.php000066600000003365151256604610012102 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:id element used by the API. This class
 * represents the unique ID assigned to an element by the servers.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Id extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'id';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Id object.
     *
     * @param string $text (optional) The ID being represented.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Name.php000066600000003341151256604610012420 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:name element used by the API.
 * This indicates the URL-usable name for an album.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Name extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'name';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Name object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Location.php000066600000003400151256604610013304 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:location element used by the API.
 * This indicates the number of bytes of storage used by an album.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Location extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'location';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Location object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/NumPhotosRemaining.php000066600000003443151256604610015331 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:numphotosremaining element used by the API.
 * This indicates the number of photos remaining in an album.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_NumPhotosRemaining extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'numphotosremaining';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_NumPhotosRemaining object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Timestamp.php000066600000003502151256604610013502 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:timestamp element used by the API.
 * The timestamp of a photo in milliseconds since January 1, 1970.
 * This date is either set externally or based on EXIF data.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Timestamp extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'timestamp';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Timestamp object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/AlbumId.php000066600000003521151256604610013055 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:albumid element used by the API. This
 * class represents the ID of an album and is usually contained
 * within an instance of Zend_Gdata_Photos_AlbumEntry or CommentEntry.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_AlbumId extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'albumid';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_AlbumId object.
     *
     * @param string $text (optional) The value to use for the Album ID.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Width.php000066600000003343151256604610012621 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:width element used by the API.
 * This indicates the width of a photo in pixels.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Width extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'width';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Width object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Access.php000066600000003436151256604610012746 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:access element used by the API.
 * This determines the visibility for an album, and can be either
 * the strings 'private' or 'public'.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Access extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'access';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Access object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Thumbnail.php000066600000003401151256604610013460 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:thumbnail element used by the API.
 * This class represents the URI for a thumbnail image.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Thumbnail extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'thumbnail';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Thumbnail object.
     *
     * @param string $text (optional) The thumbnail URI to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/CommentCount.php000066600000003571151256604610014160 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:commentCount element used by the API. This
 * class represents the number of comments attached to an entry and is usually contained
 * within an instance of Zend_Gdata_Photos_PhotoEntry or AlbumEntry.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_CommentCount extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'commentCount';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_CommentCount object.
     *
     * @param string $text (optional) The value to use for the count.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/QuotaLimit.php000066600000003434151256604610013633 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:quotaLimit element used by the API.
 * This class represents the number of bytes of storage available for
 * a user.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_QuotaLimit extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'quotaLimit';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_QuotaLimit object.
     *
     * @param string $text (optional) The value being represented.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Nickname.php000066600000003364151256604610013272 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:nickname element used by the API.
 * This class represents the nickname for a user.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Nickname extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'nickname';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Nickname object.
     *
     * @param string $text (optional) The value being represented.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/QuotaCurrent.php000066600000003432151256604610014175 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:quotaCurrent element used by the API.
 * This class represents the number of bytes of storage used by a user.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_QuotaCurrent extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'quotaCurrent';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_QuotaCurrent object.
     *
     * @param string $text (optional) The value being represented.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/User.php000066600000003342151256604610012457 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:user element used by the API.
 * This class represents the username for a user.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_User extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'user';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_User object.
     *
     * @param string $text (optional) The username to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/MaxPhotosPerAlbum.php000066600000003465151256604610015121 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:maxPhotosPerAlbum element used by the API.
 * This class represents the maximum number of photos allowed in an
 * album.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'maxPhotosPerAlbum';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum object.
     *
     * @param string $text (optional) The value being represented.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Weight.php000066600000003455151256604610012775 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:weight element used by the API.
 * This indicates the weight of a tag, based on the number of times
 * it appears in photos under the current element.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Weight extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'weight';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Weight object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/NumPhotos.php000066600000003365151256604610013502 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:numphotos element used by the API.
 * This indicates the number of photos in an album.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_NumPhotos extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'numphotos';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_NumPhotos object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Checksum.php000066600000003447151256604610013311 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:checksum element used by the API.
 * This is an optional field that can be used to store a photo's
 * checksum to ease duplicate checking.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Checksum extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'checksum';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Checksum object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Position.php000066600000003361151256604610013346 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:position element used by the API.
 * The ordinal position of a photo within an album.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Position extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'position';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Position object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Size.php000066600000003316151256604610012454 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:size element used by the API.
 * The size of a photo in bytes.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Size extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'size';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Size object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Height.php000066600000003331151256604610012747 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:height element used by the API.
 * The height of a photo in pixels.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Height extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'height';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Height object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Rotation.php000066600000003466151256604610013347 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:rotation element used by the API.
 * The rotation of a photo in degrees. Will only be shown if the
 * rotation has not already been applied to the image.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Rotation extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'rotation';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Rotation object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Version.php000066600000003420151256604610013163 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:version element used by the API.
 * This number is used for optimistic concurrency, and does not
 * increase linearly.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Version extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'version';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Version object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/PhotoId.php000066600000003265151256604610013113 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:id element used by the Picasa API.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_PhotoId extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'id';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_PhotoId object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/Extension/Client.php000066600000003425151256604610012761 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * @see Zend_Gdata_Photos
 */
require_once 'Zend/Gdata/Photos.php';

/**
 * Represents the gphoto:client element used by the API.
 * This is an optional field that can be used to indicate the
 * client which created a photo.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_Extension_Client extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'client';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_Client object.
     *
     * @param string $text (optional) The value to represent.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}
Gdata/Photos/UserEntry.php000066600000026475151256604610011541 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/Entry.php';

/**
 * @see Zend_Gdata_Gapps
 */
require_once 'Zend/Gdata/Gapps.php';

/**
 * @see Zend_Gdata_Photos_Extension_Nickname
 */
require_once 'Zend/Gdata/Photos/Extension/Nickname.php';

/**
 * @see Zend_Gdata_Photos_Extension_Thumbnail
 */
require_once 'Zend/Gdata/Photos/Extension/Thumbnail.php';

/**
 * @see Zend_Gdata_Photos_Extension_QuotaCurrent
 */
require_once 'Zend/Gdata/Photos/Extension/QuotaCurrent.php';

/**
 * @see Zend_Gdata_Photos_Extension_QuotaLimit
 */
require_once 'Zend/Gdata/Photos/Extension/QuotaLimit.php';

/**
 * @see Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum
 */
require_once 'Zend/Gdata/Photos/Extension/MaxPhotosPerAlbum.php';

/**
 * @see Zend_Gdata_Photos_Extension_User
 */
require_once 'Zend/Gdata/Photos/Extension/User.php';

/**
 * @see Zend_Gdata_App_Extension_Category
 */
require_once 'Zend/Gdata/App/Extension/Category.php';

/**
 * Data model class for a User Entry.
 *
 * To transfer user entries to and from the servers, including
 * creating new entries, refer to the service class,
 * Zend_Gdata_Photos.
 *
 * This class represents <atom:entry> in the Google Data protocol.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Photos_UserEntry extends Zend_Gdata_Entry
{

    protected $_entryClassName = 'Zend_Gdata_Photos_UserEntry';

    /**
     * gphoto:nickname element
     *
     * @var Zend_Gdata_Photos_Extension_Nickname
     */
    protected $_gphotoNickname = null;

    /**
     * gphoto:user element
     *
     * @var Zend_Gdata_Photos_Extension_User
     */
    protected $_gphotoUser = null;

    /**
     * gphoto:thumbnail element
     *
     * @var Zend_Gdata_Photos_Extension_Thumbnail
     */
    protected $_gphotoThumbnail = null;

    /**
     * gphoto:quotalimit element
     *
     * @var Zend_Gdata_Photos_Extension_QuotaLimit
     */
    protected $_gphotoQuotaLimit = null;

    /**
     * gphoto:quotacurrent element
     *
     * @var Zend_Gdata_Photos_Extension_QuotaCurrent
     */
    protected $_gphotoQuotaCurrent = null;

    /**
     * gphoto:maxPhotosPerAlbum element
     *
     * @var Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum
     */
    protected $_gphotoMaxPhotosPerAlbum = null;

    /**
     * Create a new instance.
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($element = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Photos::$namespaces);
        parent::__construct($element);

        $category = new Zend_Gdata_App_Extension_Category(
            'http://schemas.google.com/photos/2007#user',
            'http://schemas.google.com/g/2005#kind');
        $this->setCategory(array($category));
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     *          child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_gphotoNickname !== null) {
            $element->appendChild($this->_gphotoNickname->getDOM($element->ownerDocument));
        }
        if ($this->_gphotoThumbnail !== null) {
            $element->appendChild($this->_gphotoThumbnail->getDOM($element->ownerDocument));
        }
        if ($this->_gphotoUser !== null) {
            $element->appendChild($this->_gphotoUser->getDOM($element->ownerDocument));
        }
        if ($this->_gphotoQuotaCurrent !== null) {
            $element->appendChild($this->_gphotoQuotaCurrent->getDOM($element->ownerDocument));
        }
        if ($this->_gphotoQuotaLimit !== null) {
            $element->appendChild($this->_gphotoQuotaLimit->getDOM($element->ownerDocument));
        }
        if ($this->_gphotoMaxPhotosPerAlbum !== null) {
            $element->appendChild($this->_gphotoMaxPhotosPerAlbum->getDOM($element->ownerDocument));
        }
        return $element;
    }

    /**
     * Creates individual Entry objects of the appropriate type and
     * stores them as members of this entry based upon DOM data.
     *
     * @param DOMNode $child The DOMNode to process
     */
    protected function takeChildFromDOM($child)
    {
        $absoluteNodeName = $child->namespaceURI . ':' . $child->localName;

        switch ($absoluteNodeName) {
            case $this->lookupNamespace('gphoto') . ':' . 'nickname';
                $nickname = new Zend_Gdata_Photos_Extension_Nickname();
                $nickname->transferFromDOM($child);
                $this->_gphotoNickname = $nickname;
                break;
            case $this->lookupNamespace('gphoto') . ':' . 'thumbnail';
                $thumbnail = new Zend_Gdata_Photos_Extension_Thumbnail();
                $thumbnail->transferFromDOM($child);
                $this->_gphotoThumbnail = $thumbnail;
                break;
            case $this->lookupNamespace('gphoto') . ':' . 'user';
                $user = new Zend_Gdata_Photos_Extension_User();
                $user->transferFromDOM($child);
                $this->_gphotoUser = $user;
                break;
            case $this->lookupNamespace('gphoto') . ':' . 'quotacurrent';
                $quotaCurrent = new Zend_Gdata_Photos_Extension_QuotaCurrent();
                $quotaCurrent->transferFromDOM($child);
                $this->_gphotoQuotaCurrent = $quotaCurrent;
                break;
            case $this->lookupNamespace('gphoto') . ':' . 'quotalimit';
                $quotaLimit = new Zend_Gdata_Photos_Extension_QuotaLimit();
                $quotaLimit->transferFromDOM($child);
                $this->_gphotoQuotaLimit = $quotaLimit;
                break;
            case $this->lookupNamespace('gphoto') . ':' . 'maxPhotosPerAlbum';
                $maxPhotosPerAlbum = new Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum();
                $maxPhotosPerAlbum->transferFromDOM($child);
                $this->_gphotoMaxPhotosPerAlbum = $maxPhotosPerAlbum;
                break;
            default:
                parent::takeChildFromDOM($child);
                break;
        }
    }

    /**
     * Get the value for this element's gphoto:nickname attribute.
     *
     * @see setGphotoNickname
     * @return string The requested attribute.
     */
    public function getGphotoNickname()
    {
        return $this->_gphotoNickname;
    }

    /**
     * Set the value for this element's gphoto:nickname attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Photos_Extension_Nickname The element being modified.
     */
    public function setGphotoNickname($value)
    {
        $this->_gphotoNickname = $value;
        return $this;
    }

    /**
     * Get the value for this element's gphoto:thumbnail attribute.
     *
     * @see setGphotoThumbnail
     * @return string The requested attribute.
     */
    public function getGphotoThumbnail()
    {
        return $this->_gphotoThumbnail;
    }

    /**
     * Set the value for this element's gphoto:thumbnail attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Photos_Extension_Thumbnail The element being modified.
     */
    public function setGphotoThumbnail($value)
    {
        $this->_gphotoThumbnail = $value;
        return $this;
    }

    /**
     * Get the value for this element's gphoto:quotacurrent attribute.
     *
     * @see setGphotoQuotaCurrent
     * @return string The requested attribute.
     */
    public function getGphotoQuotaCurrent()
    {
        return $this->_gphotoQuotaCurrent;
    }

    /**
     * Set the value for this element's gphoto:quotacurrent attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Photos_Extension_QuotaCurrent The element being modified.
     */
    public function setGphotoQuotaCurrent($value)
    {
        $this->_gphotoQuotaCurrent = $value;
        return $this;
    }

    /**
     * Get the value for this element's gphoto:quotalimit attribute.
     *
     * @see setGphotoQuotaLimit
     * @return string The requested attribute.
     */
    public function getGphotoQuotaLimit()
    {
        return $this->_gphotoQuotaLimit;
    }

    /**
     * Set the value for this element's gphoto:quotalimit attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Photos_Extension_QuotaLimit The element being modified.
     */
    public function setGphotoQuotaLimit($value)
    {
        $this->_gphotoQuotaLimit = $value;
        return $this;
    }

    /**
     * Get the value for this element's gphoto:maxPhotosPerAlbum attribute.
     *
     * @see setGphotoMaxPhotosPerAlbum
     * @return string The requested attribute.
     */
    public function getGphotoMaxPhotosPerAlbum()
    {
        return $this->_gphotoMaxPhotosPerAlbum;
    }

    /**
     * Set the value for this element's gphoto:maxPhotosPerAlbum attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Photos_Extension_MaxPhotosPerAlbum The element being modified.
     */
    public function setGphotoMaxPhotosPerAlbum($value)
    {
        $this->_gphotoMaxPhotosPerAlbum = $value;
        return $this;
    }

    /**
     * Get the value for this element's gphoto:user attribute.
     *
     * @see setGphotoUser
     * @return string The requested attribute.
     */
    public function getGphotoUser()
    {
        return $this->_gphotoUser;
    }

    /**
     * Set the value for this element's gphoto:user attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Photos_Extension_User The element being modified.
     */
    public function setGphotoUser($value)
    {
        $this->_gphotoUser = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaRestriction.php000066600000010251151256604610014546 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:restriction element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaRestriction extends Zend_Gdata_Extension
{

    protected $_rootElement = 'restriction';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_relationship = null;

    /**
     * @var string
     */
    protected $_type = null;

    /**
     * Constructs a new MediaRestriction element
     *
     * @param string $text
     * @param string $relationship
     * @param string $type
     */
    public function __construct($text = null, $relationship = null,  $type = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_text = $text;
        $this->_relationship = $relationship;
        $this->_type = $type;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_relationship !== null) {
            $element->setAttribute('relationship', $this->_relationship);
        }
        if ($this->_type !== null) {
            $element->setAttribute('type', $this->_type);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'relationship':
            $this->_relationship = $attribute->nodeValue;
            break;
        case 'type':
            $this->_type = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getRelationship()
    {
        return $this->_relationship;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaRestriction Provides a fluent interface
     */
    public function setRelationship($value)
    {
        $this->_relationship = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaRestriction Provides a fluent interface
     */
    public function setType($value)
    {
        $this->_type = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaTitle.php000066600000006541151256604610013331 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:title element in MediaRSS
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaTitle extends Zend_Gdata_Extension
{

    protected $_rootElement = 'title';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_type = null;

    /**
     * Constructs a MediaTitle element
     *
     * @param string $text
     * @param string $type
     */
    public function __construct($text = null, $type = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_type = $type;
        $this->_text = $text;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_type !== null) {
            $element->setAttribute('type', $this->_type);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'type':
            $this->_type = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaTitle Provides a fluent interface
     */
    public function setType($value)
    {
        $this->_type = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaDescription.php000066600000006475151256604610014541 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:description element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaDescription extends Zend_Gdata_Extension
{

    protected $_rootElement = 'description';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_type = null;

    /**
     * @param string $text
     * @param string $type
     */
    public function __construct($text = null, $type = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_type = $type;
        $this->_text = $text;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_type !== null) {
            $element->setAttribute('type', $this->_type);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'type':
            $this->_type = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaDescription Provides a fluent interface
     */
    public function setType($value)
    {
        $this->_type = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaCategory.php000066600000010766151256604610014031 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:category element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaCategory extends Zend_Gdata_Extension
{

    protected $_rootElement = 'category';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_scheme = null;
    protected $_label = null;

    /**
     * Creates an individual MediaCategory object.
     *
     * @param string $text      Indication of the type and content of the media
     * @param string $scheme    URI that identifies the categorization scheme
     * @param string $label     Human-readable label to be displayed in applications
     */
    public function __construct($text = null, $scheme = null, $label = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_text = $text;
        $this->_scheme = $scheme;
        $this->_label = $label;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_scheme !== null) {
            $element->setAttribute('scheme', $this->_scheme);
        }
        if ($this->_label !== null) {
            $element->setAttribute('label', $this->_label);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'scheme':
            $this->_scheme = $attribute->nodeValue;
            break;
        case 'label':
            $this->_label = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Returns the URI that identifies the categorization scheme
     * Optional.
     *
     * @return string URI that identifies the categorization scheme
     */
    public function getScheme()
    {
        return $this->_scheme;
    }

    /**
     * @param string $value     URI that identifies the categorization scheme
     * @return Zend_Gdata_Media_Extension_MediaCategory Provides a fluent interface
     */
    public function setScheme($value)
    {
        $this->_scheme = $value;
        return $this;
    }

    /**
     * @return string Human-readable label to be displayed in applications
     */
    public function getLabel()
    {
        return $this->_label;
    }

    /**
     * @param string $value     Human-readable label to be displayed in applications
     * @return Zend_Gdata_Media_Extension_MediaCategory Provides a fluent interface
     */
    public function setLabel($value)
    {
        $this->_label = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaPlayer.php000066600000011221151256604610013473 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:player element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaPlayer extends Zend_Gdata_Extension
{

    protected $_rootElement = 'player';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_url = null;

    /**
     * @var int
     */
    protected $_width = null;

    /**
     * @var int
     */
    protected $_height = null;

    /**
     * Constructs a new MediaPlayer element
     *
     * @param string $url
     * @param int $width
     * @param int $height
     */
    public function __construct($url = null, $width = null, $height = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_url = $url;
        $this->_width = $width;
        $this->_height = $height;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_url !== null) {
            $element->setAttribute('url', $this->_url);
        }
        if ($this->_width !== null) {
            $element->setAttribute('width', $this->_width);
        }
        if ($this->_height !== null) {
            $element->setAttribute('height', $this->_height);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'url':
            $this->_url = $attribute->nodeValue;
            break;
        case 'width':
            $this->_width = $attribute->nodeValue;
            break;
        case 'height':
            $this->_height = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

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

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaPlayer Provides a fluent interface
     */
    public function setUrl($value)
    {
        $this->_url = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getWidth()
    {
        return $this->_width;
    }

    /**
     * @param int $value
     * @return Zend_Gdata_Media_Extension_MediaPlayer Provides a fluent interface
     */
    public function setWidth($value)
    {
        $this->_width = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getHeight()
    {
        return $this->_height;
    }

    /**
     * @param int $value
     * @return Zend_Gdata_Media_Extension_MediaPlayer Provides a fluent interface
     */
    public function setHeight($value)
    {
        $this->_height = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaContent.php000066600000031737151256604610013667 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the media:content element of Media RSS.
 * Represents media objects.  Multiple media objects representing
 * the same content can be represented using a
 * media:group (Zend_Gdata_Media_Extension_MediaGroup) element.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaContent extends Zend_Gdata_Extension
{
    protected $_rootElement = 'content';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_url = null;

    /**
     * @var int
     */
    protected $_fileSize = null;

    /**
     * @var string
     */
    protected $_type = null;

    /**
     * @var string
     */
    protected $_medium = null;

    /**
     * @var string
     */
    protected $_isDefault = null;

    /**
     * @var string
     */
    protected $_expression = null;

    /**
     * @var int
     */
    protected $_bitrate = null;

    /**
     * @var int
     */
    protected $_framerate = null;

    /**
     * @var int
     */
    protected $_samplingrate = null;

    /**
     * @var int
     */
    protected $_channels = null;

    /**
     * @var int
     */
    protected $_duration = null;

    /**
     * @var int
     */
    protected $_height = null;

    /**
     * @var int
     */
    protected $_width = null;

    /**
     * @var string
     */
    protected $_lang = null;

    /**
     * Creates an individual MediaContent object.
     */
    public function __construct($url = null, $fileSize = null, $type = null,
            $medium = null, $isDefault = null, $expression = null,
            $bitrate = null, $framerate = null, $samplingrate = null,
            $channels = null, $duration = null, $height = null, $width = null,
            $lang = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_url = $url;
        $this->_fileSize = $fileSize;
        $this->_type = $type;
        $this->_medium = $medium;
        $this->_isDefault = $isDefault;
        $this->_expression = $expression;
        $this->_bitrate = $bitrate;
        $this->_framerate = $framerate;
        $this->_samplingrate = $samplingrate;
        $this->_channels = $channels;
        $this->_duration = $duration;
        $this->_height = $height;
        $this->_width = $width;
        $this->_lang = $lang;
    }


    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_url !== null) {
            $element->setAttribute('url', $this->_url);
        }
        if ($this->_fileSize !== null) {
            $element->setAttribute('fileSize', $this->_fileSize);
        }
        if ($this->_type !== null) {
            $element->setAttribute('type', $this->_type);
        }
        if ($this->_medium !== null) {
            $element->setAttribute('medium', $this->_medium);
        }
        if ($this->_isDefault !== null) {
            $element->setAttribute('isDefault', $this->_isDefault);
        }
        if ($this->_expression !== null) {
            $element->setAttribute('expression', $this->_expression);
        }
        if ($this->_bitrate !== null) {
            $element->setAttribute('bitrate', $this->_bitrate);
        }
        if ($this->_framerate !== null) {
            $element->setAttribute('framerate', $this->_framerate);
        }
        if ($this->_samplingrate !== null) {
            $element->setAttribute('samplingrate', $this->_samplingrate);
        }
        if ($this->_channels !== null) {
            $element->setAttribute('channels', $this->_channels);
        }
        if ($this->_duration !== null) {
            $element->setAttribute('duration', $this->_duration);
        }
        if ($this->_height !== null) {
            $element->setAttribute('height', $this->_height);
        }
        if ($this->_width !== null) {
            $element->setAttribute('width', $this->_width);
        }
        if ($this->_lang !== null) {
            $element->setAttribute('lang', $this->_lang);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
            case 'url':
                $this->_url = $attribute->nodeValue;
                break;
            case 'fileSize':
                $this->_fileSize = $attribute->nodeValue;
                break;
            case 'type':
                $this->_type = $attribute->nodeValue;
                break;
            case 'medium':
                $this->_medium = $attribute->nodeValue;
                break;
            case 'isDefault':
                $this->_isDefault = $attribute->nodeValue;
                break;
            case 'expression':
                $this->_expression = $attribute->nodeValue;
                break;
            case 'bitrate':
                $this->_bitrate = $attribute->nodeValue;
                break;
            case 'framerate':
                $this->_framerate = $attribute->nodeValue;
                break;
            case 'samplingrate':
                $this->_samplingrate = $attribute->nodeValue;
                break;
            case 'channels':
                $this->_channels = $attribute->nodeValue;
                break;
            case 'duration':
                $this->_duration = $attribute->nodeValue;
                break;
            case 'height':
                $this->_height = $attribute->nodeValue;
                break;
            case 'width':
                $this->_width = $attribute->nodeValue;
                break;
            case 'lang':
                $this->_lang = $attribute->nodeValue;
                break;
            default:
                parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Returns the URL representing this MediaContent object
     *
     * @return string   The URL representing this MediaContent object.
     */
    public function __toString()
    {
        return $this->getUrl();
    }

    /**
     * @return string   The direct URL to the media object
     */
    public function getUrl()
    {
        return $this->_url;
    }

    /**
     * @param string $value     The direct URL to the media object
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setUrl($value)
    {
        $this->_url = $value;
        return $this;
    }

    /**
     * @return int  The size of the media in bytes
     */
    public function getFileSize()
    {
        return $this->_fileSize;
    }

    /**
     * @param int $value
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setFileSize($value)
    {
        $this->_fileSize = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setType($value)
    {
        $this->_type = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getMedium()
    {
        return $this->_medium;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setMedium($value)
    {
        $this->_medium = $value;
        return $this;
    }

    /**
     * @return bool
     */
    public function getIsDefault()
    {
        return $this->_isDefault;
    }

    /**
     * @param bool $value
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setIsDefault($value)
    {
        $this->_isDefault = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getExpression()
    {
        return $this->_expression;
    }

    /**
     * @param string
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setExpression($value)
    {
        $this->_expression = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getBitrate()
    {
        return $this->_bitrate;
    }

    /**
     * @param int
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setBitrate($value)
    {
        $this->_bitrate = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getFramerate()
    {
        return $this->_framerate;
    }

    /**
     * @param int
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setFramerate($value)
    {
        $this->_framerate = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getSamplingrate()
    {
        return $this->_samplingrate;
    }

    /**
     * @param int
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setSamplingrate($value)
    {
        $this->_samplingrate = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getChannels()
    {
        return $this->_channels;
    }

    /**
     * @param int
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setChannels($value)
    {
        $this->_channels = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getDuration()
    {
        return $this->_duration;
    }

    /**
     *
     * @param int
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setDuration($value)
    {
        $this->_duration = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getHeight()
    {
        return $this->_height;
    }

    /**
     * @param int
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setHeight($value)
    {
        $this->_height = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getWidth()
    {
        return $this->_width;
    }

    /**
     * @param int
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setWidth($value)
    {
        $this->_width = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getLang()
    {
        return $this->_lang;
    }

    /**
     * @param string
     * @return Zend_Gdata_Media_Extension_MediaContent  Provides a fluent interface
     */
    public function setLang($value)
    {
        $this->_lang = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaRating.php000066600000006572151256604610013500 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:rating element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaRating extends Zend_Gdata_Extension
{

    protected $_rootElement = 'rating';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_scheme = null;

    /**
     * Constructs a new MediaRating element
     *
     * @param string $text
     * @param string $scheme
     */
    public function __construct($text = null, $scheme = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_scheme = $scheme;
        $this->_text = $text;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_scheme !== null) {
            $element->setAttribute('scheme', $this->_scheme);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'scheme':
            $this->_scheme = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getScheme()
    {
        return $this->_scheme;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaRating Provides a fluent interface
     */
    public function setScheme($value)
    {
        $this->_scheme = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaCredit.php000066600000010074151256604610013456 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:credit element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaCredit extends Zend_Gdata_Extension
{

    protected $_rootElement = 'credit';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_role = null;

    /**
     * @var string
     */
    protected $_scheme = null;

    /**
     * Creates an individual MediaCredit object.
     *
     * @param string $text
     * @param string $role
     * @param string $scheme
     */
    public function __construct($text = null, $role = null,  $scheme = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_text = $text;
        $this->_role = $role;
        $this->_scheme = $scheme;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_role !== null) {
            $element->setAttribute('role', $this->_role);
        }
        if ($this->_scheme !== null) {
            $element->setAttribute('scheme', $this->_scheme);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'role':
            $this->_role = $attribute->nodeValue;
            break;
        case 'scheme':
            $this->_scheme = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getRole()
    {
        return $this->_role;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaCredit Provides a fluent interface
     */
    public function setRole($value)
    {
        $this->_role = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getScheme()
    {
        return $this->_scheme;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaCredit Provides a fluent interface
     */
    public function setScheme($value)
    {
        $this->_scheme = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaThumbnail.php000066600000012563151256604610014174 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:thumbnail element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaThumbnail extends Zend_Gdata_Extension
{

    protected $_rootElement = 'thumbnail';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_url = null;

    /**
     * @var int
     */
    protected $_width = null;

    /**
     * @var int
     */
    protected $_height = null;

    /**
     * @var string
     */
    protected $_time = null;

    /**
     * Constructs a new MediaThumbnail element
     *
     * @param string $url
     * @param int $width
     * @param int $height
     * @param string $time
     */
    public function __construct($url = null, $width = null, $height = null,
            $time = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_url = $url;
        $this->_width = $width;
        $this->_height = $height;
        $this->_time = $time ;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_url !== null) {
            $element->setAttribute('url', $this->_url);
        }
        if ($this->_width !== null) {
            $element->setAttribute('width', $this->_width);
        }
        if ($this->_height !== null) {
            $element->setAttribute('height', $this->_height);
        }
        if ($this->_time !== null) {
            $element->setAttribute('time', $this->_time);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'url':
            $this->_url = $attribute->nodeValue;
            break;
        case 'width':
            $this->_width = $attribute->nodeValue;
            break;
        case 'height':
            $this->_height = $attribute->nodeValue;
            break;
        case 'time':
            $this->_time = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

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

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaThumbnail Provides a fluent interface
     */
    public function setUrl($value)
    {
        $this->_url = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getWidth()
    {
        return $this->_width;
    }

    /**
     * @param int $value
     * @return Zend_Gdata_Media_Extension_MediaThumbnail Provides a fluent interface
     */
    public function setWidth($value)
    {
        $this->_width = $value;
        return $this;
    }

    /**
     * @return int
     */
    public function getHeight()
    {
        return $this->_height;
    }

    /**
     * @param int $value
     * @return Zend_Gdata_Media_Extension_MediaThumbnail Provides a fluent interface
     */
    public function setHeight($value)
    {
        $this->_height = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getTime()
    {
        return $this->_time;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaThumbnail Provides a fluent interface
     */
    public function setTime($value)
    {
        $this->_time = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaText.php000066600000012615151256604610013173 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:text element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaText extends Zend_Gdata_Extension
{

    protected $_rootElement = 'text';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_type = null;

    /**
     * @var string
     */
    protected $_lang = null;

    /**
     * @var string
     */
    protected $_start = null;

    /**
     * @var string
     */
    protected $_end = null;

    /**
     * Constructs a new MediaText element
     *
     * @param $text string
     * @param $type string
     * @param $lang string
     * @param $start string
     * @param $end string
     */
    public function __construct($text = null, $type = null, $lang = null,
            $start = null, $end = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_text = $text;
        $this->_type = $type;
        $this->_lang = $lang;
        $this->_start = $start;
        $this->_end = $end;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_type !== null) {
            $element->setAttribute('type', $this->_type);
        }
        if ($this->_lang !== null) {
            $element->setAttribute('lang', $this->_lang);
        }
        if ($this->_start !== null) {
            $element->setAttribute('start', $this->_start);
        }
        if ($this->_end !== null) {
            $element->setAttribute('end', $this->_end);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'type':
            $this->_type = $attribute->nodeValue;
            break;
        case 'lang':
            $this->_lang = $attribute->nodeValue;
            break;
        case 'start':
            $this->_start = $attribute->nodeValue;
            break;
        case 'end':
            $this->_end = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaText Provides a fluent interface
     */
    public function setType($value)
    {
        $this->_type = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getLang()
    {
        return $this->_lang;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaText Provides a fluent interface
     */
    public function setLang($value)
    {
        $this->_lang = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getStart()
    {
        return $this->_start;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaText Provides a fluent interface
     */
    public function setStart($value)
    {
        $this->_start = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getEnd()
    {
        return $this->_end;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaText Provides a fluent interface
     */
    public function setEnd($value)
    {
        $this->_end = $value;
        return $this;
    }
}
Gdata/Media/Extension/MediaHash.php000066600000006555151256604610013140 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:hash element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaHash extends Zend_Gdata_Extension
{

    protected $_rootElement = 'hash';
    protected $_rootNamespace = 'media';
    protected $_algo = null;

    /**
     * Constructs a new MediaHash element
     *
     * @param string $text
     * @param string $algo
     */
    public function __construct($text = null, $algo = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_text = $text;
        $this->_algo = $algo;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_algo !== null) {
            $element->setAttribute('algo', $this->_algo);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     * @throws Zend_Gdata_App_InvalidArgumentException
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'algo':
            $this->_algo = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string The algo
     */
    public function getAlgo()
    {
        return $this->_algo;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaHash Provides a fluent interface
     */
    public function setAlgo($value)
    {
        $this->_algo = $value;
        return $this;
    }

}
Gdata/Media/Extension/MediaKeywords.php000066600000002730151256604610014053 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:keywords element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaKeywords extends Zend_Gdata_Extension
{
    protected $_rootElement = 'keywords';
    protected $_rootNamespace = 'media';

    /**
     * Constructs a new MediaKeywords element
     */
    public function __construct()
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
    }

}
Gdata/Calendar/Extension/Timezone.php000066600000007372151256604610013577 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the gCal:timezone element used by the Calendar data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_Extension_Timezone extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gCal';
    protected $_rootElement = 'timezone';
    protected $_value = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_Timezone object.
     * @param string $value (optional) The text content of the element.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct();
        $this->_value = $value;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_value != null) {
            $element->setAttribute('value', $this->_value);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'value':
            $this->_value = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's value attribute.
     *
     * @return string The value associated with this attribute.
     */
    public function getValue()
    {
        return $this->_value;
    }

    /**
     * Set the value for this element's value attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Calendar_Extension_Timezone The element being modified.
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     */
    public function __toString()
    {
        return $this->getValue();
    }

}
Gdata/Calendar/Extension/Hidden.php000066600000010172151256604610013170 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the gCal:hidden element used by the Calendar data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_Extension_Hidden extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gCal';
    protected $_rootElement = 'hidden';
    protected $_value = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_Hidden object.
     * @param bool $value (optional) The value of the element.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct();
        $this->_value = $value;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_value !== null) {
            $element->setAttribute('value', ($this->_value ? "true" : "false"));
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'value':
            if ($attribute->nodeValue == "true") {
                $this->_value = true;
            }
            else if ($attribute->nodeValue == "false") {
                $this->_value = false;
            }
            else {
                require_once 'Zend/Gdata/App/InvalidArgumentException.php';
                throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value.");
            }
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's value attribute.
     *
     * @return string The requested attribute.
     */
    public function getValue()
    {
        return $this->_value;
    }

    /**
     * Set the value for this element's value attribute.
     *
     * @param bool $value The desired value for this attribute.
     * @return Zend_Gdata_Calendar_Extension_Hidden The element being modified.
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     */
    public function __toString()
    {
        return $this->_value;
    }

}

Gdata/Calendar/Extension/Color.php000066600000007430151256604610013056 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the gCal:color element used by the Calendar data API
 * to define the color of a calendar in the UI.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_Extension_Color extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gCal';
    protected $_rootElement = 'color';
    protected $_value = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_Color object.
     * @param string $value (optional) The text content of the element.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct();
        $this->_value = $value;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_value != null) {
            $element->setAttribute('value', $this->_value);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'value':
            $this->_value = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's value attribute.
     *
     * @return string The value associated with this attribute.
     */
    public function getValue()
    {
        return $this->_value;
    }

    /**
     * Set the value for this element's value attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Calendar_Extension_Color The element being modified.
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     */
    public function __toString()
    {
        return $this->_value;
    }

}
Gdata/Calendar/Extension/Selected.php000066600000010221151256604610013520 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the gCal:selected element used by the Calendar data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_Extension_Selected extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gCal';
    protected $_rootElement = 'selected';
    protected $_value = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_Selected object.
     * @param bool $value (optional) The value of the element.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct();
        $this->_value = $value;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_value !== null) {
            $element->setAttribute('value', ($this->_value ? "true" : "false"));
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'value':
            if ($attribute->nodeValue == "true") {
                $this->_value = true;
            }
            else if ($attribute->nodeValue == "false") {
                $this->_value = false;
            }
            else {
                require_once 'Zend/Gdata/App/InvalidArgumentException.php';
                throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value.");
            }
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's value attribute.
     *
     * @return bool The value associated with this attribute.
     */
    public function getValue()
    {
        return $this->_value;
    }

    /**
     * Set the value for this element's value attribute.
     *
     * @param bool $value The desired value for this attribute.
     * @return Zend_Gdata_Calendar_Extension_Selected The element being modified.
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     */
    public function __toString()
    {
        return $this->_value;
    }

}
Gdata/Calendar/Extension/WebContent.php000066600000012735151256604610014054 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the gCal:webContent element used by the Calendar data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_Extension_WebContent extends Zend_Gdata_App_Extension
{

    protected $_rootNamespace = 'gCal';
    protected $_rootElement = 'webContent';
    protected $_url = null;
    protected $_height = null;
    protected $_width = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_WebContent object.
     * @param string $url (optional) The value for this element's URL attribute.
     * @param string $height (optional) The value for this element's height attribute.
     * @param string $width (optional) The value for this element's width attribute.
     */
    public function __construct($url = null, $height = null, $width = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct();
        $this->_url = $url;
        $this->_height = $height;
        $this->_width = $width;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->url != null) {
            $element->setAttribute('url', $this->_url);
        }
        if ($this->height != null) {
            $element->setAttribute('height', $this->_height);
        }
        if ($this->width != null) {
            $element->setAttribute('width', $this->_width);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
                case 'url':
                        $this->_url = $attribute->nodeValue;
                        break;
                case 'height':
                        $this->_height = $attribute->nodeValue;
                        break;
                case 'width':
                        $this->_width = $attribute->nodeValue;
                        break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's URL attribute.
     *
     * @return string The desired value for this attribute.
     */
    public function getURL()
    {
        return $this->_url;
    }

    /**
     * Set the value for this element's URL attribute.
     *
     * @param bool $value The desired value for this attribute.
     * @return Zend_Gdata_Calendar_Extension_WebContent The element being modified.
     */
    public function setURL($value)
    {
        $this->_url = $value;
        return $this;
    }

    /**
     * Get the value for this element's height attribute.
     *
     * @return int The desired value for this attribute.
     */
    public function getHeight()
    {
        return $this->_height;
    }

    /**
     * Set the value for this element's height attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_Calendar_Extension_WebContent The element being modified.
     */
    public function setHeight($value)
    {
        $this->_height = $value;
        return $this;
    }

    /**
     * Get the value for this element's height attribute.
     *
     * @return int The desired value for this attribute.
     */
    public function getWidth()
    {
        return $this->_width;
    }

    /**
     * Set the value for this element's height attribute.
     *
     * @param int $value The desired value for this attribute.
     * @return Zend_Gdata_Calendar_Extension_WebContent The element being modified.
     */
    public function setWidth($value)
    {
        $this->_width = $value;
        return $this;
    }

}
Gdata/Calendar/Extension/Link.php000066600000010244151256604610012672 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Entry.php 3941 2007-03-14 21:36:13Z darby $
 */

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/App/Extension/Link.php';

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/Calendar/Extension/WebContent.php';


/**
 * Specialized Link class for use with Calendar. Enables use of gCal extension elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_Extension_Link extends Zend_Gdata_App_Extension_Link
{

    protected $_webContent = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_Link object.
     * @see Zend_Gdata_App_Extension_Link#__construct
     * @param Zend_Gdata_Calendar_Extension_Webcontent $webContent
     */
    public function __construct($href = null, $rel = null, $type = null,
            $hrefLang = null, $title = null, $length = null, $webContent = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct($href, $rel, $type, $hrefLang, $title, $length);
        $this->_webContent = $webContent;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_webContent != null) {
            $element->appendChild($this->_webContent->getDOM($element->ownerDocument));
        }
        return $element;
    }

    /**
     * Creates individual Entry objects of the appropriate type and
     * stores them as members of this entry based upon DOM data.
     *
     * @param DOMNode $child The DOMNode to process
     */
    protected function takeChildFromDOM($child)
    {
        $absoluteNodeName = $child->namespaceURI . ':' . $child->localName;
        switch ($absoluteNodeName) {
        case $this->lookupNamespace('gCal') . ':' . 'webContent':
            $webContent = new Zend_Gdata_Calendar_Extension_WebContent();
            $webContent->transferFromDOM($child);
            $this->_webContent = $webContent;
            break;
        default:
            parent::takeChildFromDOM($child);
            break;
        }
    }

    /**
     * Get the value for this element's WebContent attribute.
     *
     * @return Zend_Gdata_Calendar_Extension_Webcontent The WebContent value
     */
    public function getWebContent()
    {
        return $this->_webContent;
    }

    /**
     * Set the value for this element's WebContent attribute.
     *
     * @param Zend_Gdata_Calendar_Extension_WebContent $value The desired value for this attribute.
     * @return Zend_Calendar_Extension_Link The element being modified.  Provides a fluent interface.
     */
    public function setWebContent($value)
    {
        $this->_webContent = $value;
        return $this;
    }


}

Gdata/Calendar/Extension/SendEventNotifications.php000066600000010151151256604610016417 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Data model class to represent an entry's sendEventNotifications
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_Extension_SendEventNotifications extends Zend_Gdata_Extension
{
    protected $_rootNamespace = 'gCal';
    protected $_rootElement = 'sendEventNotifications';
    protected $_value = null;

    /**
     * Constructs a new Zend_Gdata_Extension_SendEventNotifications object.
     * @param bool $value (optional) SendEventNotifications value as URI.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct();
        $this->_value = $value;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_value !== null) {
            $element->setAttribute('value', ($this->_value ? "true" : "false"));
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'value':
            if ($attribute->nodeValue == "true") {
                $this->_value = true;
            }
            else if ($attribute->nodeValue == "false") {
                $this->_value = false;
            }
            else {
                throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value.");
            }
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's Value attribute.
     *
     * @return string The requested attribute.
     */
    public function getValue()
    {
        return $this->_value;
    }

    /**
     * Set the value for this element's Value attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Extension_SendEventNotifications The element being modified.
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     */
    public function __toString()
    {
        return $this->getValue();
    }

}

Gdata/Calendar/Extension/QuickAdd.php000066600000010125151256604610013460 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Represents the gCal:quickAdd element used by the Calendar data API
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Calendar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Calendar_Extension_QuickAdd extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gCal';
    protected $_rootElement = 'quickadd';
    protected $_value = null;

    /**
     * Constructs a new Zend_Gdata_Calendar_Extension_QuickAdd object.
     * @param string $value (optional) The text content of the element.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Calendar::$namespaces);
        parent::__construct();
        $this->_value = $value;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_value !== null) {
            $element->setAttribute('value', ($this->_value ? "true" : "false"));
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'value':
            if ($attribute->nodeValue == "true") {
                $this->_value = true;
            }
            else if ($attribute->nodeValue == "false") {
                $this->_value = false;
            }
            else {
                throw new Zend_Gdata_App_InvalidArgumentException("Expected 'true' or 'false' for gCal:selected#value.");
            }
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Get the value for this element's value attribute.
     *
     * @return string The value associated with this attribute.
     */
    public function getValue()
    {
        return $this->_value;
    }

    /**
     * Set the value for this element's value attribute.
     *
     * @param string $value The desired value for this attribute.
     * @return Zend_Gdata_Calendar_Extension_QuickAdd The element being modified.
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }

    /**
     * Magic toString method allows using this directly via echo
     * Works best in PHP >= 4.2.0
     */
    public function __toString()
    {
        return $this->getValue();
    }

}
Gdata/YouTube.php000066600000074567151256604610007726 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Media
 */
require_once 'Zend/Gdata/Media.php';

/**
 * @see Zend_Gdata_YouTube_VideoEntry
 */
require_once 'Zend/Gdata/YouTube/VideoEntry.php';

/**
 * @see Zend_Gdata_YouTube_VideoFeed
 */
require_once 'Zend/Gdata/YouTube/VideoFeed.php';

/**
 * @see Zend_Gdata_YouTube_CommentFeed
 */
require_once 'Zend/Gdata/YouTube/CommentFeed.php';

/**
 * @see Zend_Gdata_YouTube_PlaylistListFeed
 */
require_once 'Zend/Gdata/YouTube/PlaylistListFeed.php';

/**
 * @see Zend_Gdata_YouTube_SubscriptionFeed
 */
require_once 'Zend/Gdata/YouTube/SubscriptionFeed.php';

/**
 * @see Zend_Gdata_YouTube_ContactFeed
 */
require_once 'Zend/Gdata/YouTube/ContactFeed.php';

/**
 * @see Zend_Gdata_YouTube_PlaylistVideoFeed
 */
require_once 'Zend/Gdata/YouTube/PlaylistVideoFeed.php';

/**
 * @see Zend_Gdata_YouTube_ActivityFeed
 */
require_once 'Zend/Gdata/YouTube/ActivityFeed.php';

/**
 * @see Zend_Gdata_YouTube_InboxFeed
 */
require_once 'Zend/Gdata/YouTube/InboxFeed.php';


/**
 * Service class for interacting with the YouTube Data API.
 * @link http://code.google.com/apis/youtube/
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage YouTube
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_YouTube extends Zend_Gdata_Media
{

    const AUTH_SERVICE_NAME = 'youtube';
    const CLIENTLOGIN_URL = 'https://www.google.com/youtube/accounts/ClientLogin';

    const STANDARD_TOP_RATED_URI = 'http://gdata.youtube.com/feeds/standardfeeds/top_rated';
    const STANDARD_MOST_VIEWED_URI = 'http://gdata.youtube.com/feeds/standardfeeds/most_viewed';
    const STANDARD_RECENTLY_FEATURED_URI = 'http://gdata.youtube.com/feeds/standardfeeds/recently_featured';
    const STANDARD_WATCH_ON_MOBILE_URI = 'http://gdata.youtube.com/feeds/standardfeeds/watch_on_mobile';

    const STANDARD_TOP_RATED_URI_V2 =
        'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated';
    const STANDARD_MOST_VIEWED_URI_V2 =
        'http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed';
    const STANDARD_RECENTLY_FEATURED_URI_V2 =
        'http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured';
    const STANDARD_WATCH_ON_MOBILE_URI_V2 =
        'http://gdata.youtube.com/feeds/api/standardfeeds/watch_on_mobile';

    const USER_URI = 'http://gdata.youtube.com/feeds/api/users';
    const VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos';
    const PLAYLIST_REL = 'http://gdata.youtube.com/schemas/2007#playlist';
    const USER_UPLOADS_REL = 'http://gdata.youtube.com/schemas/2007#user.uploads';
    const USER_PLAYLISTS_REL = 'http://gdata.youtube.com/schemas/2007#user.playlists';
    const USER_SUBSCRIPTIONS_REL = 'http://gdata.youtube.com/schemas/2007#user.subscriptions';
    const USER_CONTACTS_REL = 'http://gdata.youtube.com/schemas/2007#user.contacts';
    const USER_FAVORITES_REL = 'http://gdata.youtube.com/schemas/2007#user.favorites';
    const VIDEO_RESPONSES_REL = 'http://gdata.youtube.com/schemas/2007#video.responses';
    const VIDEO_RATINGS_REL = 'http://gdata.youtube.com/schemas/2007#video.ratings';
    const VIDEO_COMPLAINTS_REL = 'http://gdata.youtube.com/schemas/2007#video.complaints';
    const ACTIVITY_FEED_URI = 'http://gdata.youtube.com/feeds/api/events';
    const FRIEND_ACTIVITY_FEED_URI =
        'http://gdata.youtube.com/feeds/api/users/default/friendsactivity';

    /**
     * The URI of the inbox feed for the currently authenticated user.
     *
     * @var string
     */
    const INBOX_FEED_URI =
        'http://gdata.youtube.com/feeds/api/users/default/inbox';

    /**
     * The maximum number of users for which activity can be requested for,
     * as enforced by the API.
     *
     * @var integer
     */
    const ACTIVITY_FEED_MAX_USERS = 20;

    /**
     * The suffix for a feed of favorites.
     *
     * @var string
     */
    const FAVORITES_URI_SUFFIX = 'favorites';

    /**
     * The suffix for the user's upload feed.
     *
     * @var string
     */
    const UPLOADS_URI_SUFFIX = 'uploads';

    /**
     * The suffix for a feed of video responses.
     *
     * @var string
     */
    const RESPONSES_URI_SUFFIX = 'responses';

    /**
     * The suffix for a feed of related videos.
     *
     * @var string
     */
    const RELATED_URI_SUFFIX = 'related';

    /**
     * The suffix for a feed of messages (inbox entries).
     *
     * @var string
     */
    const INBOX_URI_SUFFIX = 'inbox';

    /**
     * Namespaces used for Zend_Gdata_YouTube
     *
     * @var array
     */
    public static $namespaces = array(
        array('yt', 'http://gdata.youtube.com/schemas/2007', 1, 0),
        array('georss', 'http://www.georss.org/georss', 1, 0),
        array('gml', 'http://www.opengis.net/gml', 1, 0),
        array('media', 'http://search.yahoo.com/mrss/', 1, 0)
    );

    /**
     * Create Zend_Gdata_YouTube object
     *
     * @param Zend_Http_Client $client (optional) The HTTP client to use when
     *          when communicating with the Google servers.
     * @param string $applicationId The identity of the app in the form of
     *        Company-AppName-Version
     * @param string $clientId The clientId issued by the YouTube dashboard
     * @param string $developerKey The developerKey issued by the YouTube dashboard
     */
    public function __construct($client = null,
        $applicationId = 'MyCompany-MyApp-1.0', $clientId = null,
        $developerKey = null)
    {
        $this->registerPackage('Zend_Gdata_YouTube');
        $this->registerPackage('Zend_Gdata_YouTube_Extension');
        $this->registerPackage('Zend_Gdata_Media');
        $this->registerPackage('Zend_Gdata_Media_Extension');

        // NOTE This constructor no longer calls the parent constructor
        $this->setHttpClient($client, $applicationId, $clientId, $developerKey);
    }

    /**
     * Set the Zend_Http_Client object used for communication
     *
     * @param Zend_Http_Client $client The client to use for communication
     * @throws Zend_Gdata_App_HttpException
     * @return Zend_Gdata_App Provides a fluent interface
     */
    public function setHttpClient($client,
        $applicationId = 'MyCompany-MyApp-1.0', $clientId = null,
        $developerKey = null)
    {
        if ($client === null) {
            $client = new Zend_Http_Client();
        }
        if (!$client instanceof Zend_Http_Client) {
            require_once 'Zend/Gdata/App/HttpException.php';
            throw new Zend_Gdata_App_HttpException(
                'Argument is not an instance of Zend_Http_Client.');
        }

        if ($clientId != null) {
            $client->setHeaders('X-GData-Client', $clientId);
        }

        if ($developerKey != null) {
            $client->setHeaders('X-GData-Key', 'key='. $developerKey);
        }

        return parent::setHttpClient($client, $applicationId);
    }

    /**
     * Retrieves a feed of videos.
     *
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
     *         specified URL.
     */
    public function getVideoFeed($location = null)
    {
        if ($location == null) {
            $uri = self::VIDEO_URI;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }

    /**
     * Retrieves a specific video entry.
     *
     * @param mixed $videoId The ID of the video to retrieve.
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined.
     * @param boolean $fullEntry (optional) Retrieve the full metadata for the
     *         entry. Only possible if entry belongs to currently authenticated
     *         user. An exception will be thrown otherwise.
     * @throws Zend_Gdata_App_HttpException
     * @return Zend_Gdata_YouTube_VideoEntry The video entry found at the
     *         specified URL.
     */
    public function getVideoEntry($videoId = null, $location = null,
        $fullEntry = false)
    {
        if ($videoId !== null) {
            if ($fullEntry) {
                return $this->getFullVideoEntry($videoId);
            } else {
                $uri = self::VIDEO_URI . "/" . $videoId;
            }
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getEntry($uri, 'Zend_Gdata_YouTube_VideoEntry');
    }

    /**
     * Retrieves a video entry from the user's upload feed.
     *
     * @param mixed $videoID The ID of the video to retrieve.
     * @throws Zend_Gdata_App_HttpException
     * @return Zend_Gdata_YouTube_VideoEntry|null The video entry to be
     *          retrieved, or null if it was not found or the user requesting it
     *          did not have the appropriate permissions.
     */
    public function getFullVideoEntry($videoId)
    {
        $uri = self::USER_URI . "/default/" .
            self::UPLOADS_URI_SUFFIX . "/$videoId";
        return parent::getEntry($uri, 'Zend_Gdata_YouTube_VideoEntry');
    }

    /**
     * Retrieves a feed of videos related to the specified video ID.
     *
     * @param string $videoId The videoId of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
     *         specified URL.
     */
    public function getRelatedVideoFeed($videoId = null, $location = null)
    {
        if ($videoId !== null) {
            $uri = self::VIDEO_URI . "/" . $videoId . "/" .
                self::RELATED_URI_SUFFIX;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }

    /**
     * Retrieves a feed of video responses related to the specified video ID.
     *
     * @param string $videoId The videoId of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
     *         specified URL.
     */
    public function getVideoResponseFeed($videoId = null, $location = null)
    {
        if ($videoId !== null) {
            $uri = self::VIDEO_URI . "/" . $videoId . "/" .
                self::RESPONSES_URI_SUFFIX;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }

    /**
     * Retrieves a feed of comments related to the specified video ID.
     *
     * @param string $videoId The videoId of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_CommentFeed The feed of videos found at the
     *         specified URL.
     */
    public function getVideoCommentFeed($videoId = null, $location = null)
    {
        if ($videoId !== null) {
            $uri = self::VIDEO_URI . "/" . $videoId . "/comments";
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_CommentFeed');
    }

    /**
     * Retrieves a feed of comments related to the specified video ID.
     *
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_CommentFeed The feed of videos found at the
     *         specified URL.
     */
    public function getTopRatedVideoFeed($location = null)
    {
        $standardFeedUri = self::STANDARD_TOP_RATED_URI;

        if ($this->getMajorProtocolVersion() == 2) {
            $standardFeedUri = self::STANDARD_TOP_RATED_URI_V2;
        }

        if ($location == null) {
            $uri = $standardFeedUri;
        } else if ($location instanceof Zend_Gdata_Query) {
            if ($location instanceof Zend_Gdata_YouTube_VideoQuery) {
                if (!isset($location->url)) {
                    $location->setFeedType('top rated');
                }
            }
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }


    /**
     * Retrieves a feed of the most viewed videos.
     *
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
     *         specified URL.
     */
    public function getMostViewedVideoFeed($location = null)
    {
        $standardFeedUri = self::STANDARD_MOST_VIEWED_URI;

        if ($this->getMajorProtocolVersion() == 2) {
            $standardFeedUri = self::STANDARD_MOST_VIEWED_URI_V2;
        }

        if ($location == null) {
            $uri = $standardFeedUri;
        } else if ($location instanceof Zend_Gdata_Query) {
            if ($location instanceof Zend_Gdata_YouTube_VideoQuery) {
                if (!isset($location->url)) {
                    $location->setFeedType('most viewed');
                }
            }
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }

    /**
     * Retrieves a feed of recently featured videos.
     *
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
     *         specified URL.
     */
    public function getRecentlyFeaturedVideoFeed($location = null)
    {
        $standardFeedUri = self::STANDARD_RECENTLY_FEATURED_URI;

        if ($this->getMajorProtocolVersion() == 2) {
            $standardFeedUri = self::STANDARD_RECENTLY_FEATURED_URI_V2;
        }

        if ($location == null) {
            $uri = $standardFeedUri;
        } else if ($location instanceof Zend_Gdata_Query) {
            if ($location instanceof Zend_Gdata_YouTube_VideoQuery) {
                if (!isset($location->url)) {
                    $location->setFeedType('recently featured');
                }
            }
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }

    /**
     * Retrieves a feed of videos recently featured for mobile devices.
     * These videos will have RTSP links in the $entry->mediaGroup->content
     *
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_VideoFeed The feed of videos found at the
     *         specified URL.
     */
    public function getWatchOnMobileVideoFeed($location = null)
    {
        $standardFeedUri = self::STANDARD_WATCH_ON_MOBILE_URI;

        if ($this->getMajorProtocolVersion() == 2) {
            $standardFeedUri = self::STANDARD_WATCH_ON_MOBILE_URI_V2;
        }

        if ($location == null) {
            $uri = $standardFeedUri;
        } else if ($location instanceof Zend_Gdata_Query) {
            if ($location instanceof Zend_Gdata_YouTube_VideoQuery) {
                if (!isset($location->url)) {
                    $location->setFeedType('watch on mobile');
                }
            }
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }

    /**
     * Retrieves a feed which lists a user's playlist
     *
     * @param string $user (optional) The username of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_PlaylistListFeed The feed of playlists
     */
    public function getPlaylistListFeed($user = null, $location = null)
    {
        if ($user !== null) {
            $uri = self::USER_URI . '/' . $user . '/playlists';
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_PlaylistListFeed');
    }

    /**
     * Retrieves a feed of videos in a particular playlist
     *
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_PlaylistVideoFeed The feed of videos found at
     *         the specified URL.
     */
    public function getPlaylistVideoFeed($location)
    {
        if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_PlaylistVideoFeed');
    }

    /**
     * Retrieves a feed of a user's subscriptions
     *
     * @param string $user (optional) The username of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_SubscriptionListFeed The feed of subscriptions
     */
    public function getSubscriptionFeed($user = null, $location = null)
    {
        if ($user !== null) {
            $uri = self::USER_URI . '/' . $user . '/subscriptions';
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_SubscriptionFeed');
    }

    /**
     * Retrieves a feed of a user's contacts
     *
     * @param string $user (optional) The username of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_ContactFeed The feed of contacts
     */
    public function getContactFeed($user = null, $location = null)
    {
        if ($user !== null) {
            $uri = self::USER_URI . '/' . $user . '/contacts';
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_ContactFeed');
    }

    /**
     * Retrieves a user's uploads
     *
     * @param string $user (optional) The username of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_VideoFeed The videos uploaded by the user
     */
    public function getUserUploads($user = null, $location = null)
    {
        if ($user !== null) {
            $uri = self::USER_URI . '/' . $user . '/' .
                   self::UPLOADS_URI_SUFFIX;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }

    /**
     * Retrieves a user's favorites
     *
     * @param string $user (optional) The username of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_VideoFeed The videos favorited by the user
     */
    public function getUserFavorites($user = null, $location = null)
    {
        if ($user !== null) {
            $uri = self::USER_URI . '/' . $user . '/' .
                   self::FAVORITES_URI_SUFFIX;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getFeed($uri, 'Zend_Gdata_YouTube_VideoFeed');
    }

    /**
     * Retrieves a user's profile as an entry
     *
     * @param string $user (optional) The username of interest
     * @param mixed $location (optional) The URL to query or a
     *         Zend_Gdata_Query object from which a URL can be determined
     * @return Zend_Gdata_YouTube_UserProfileEntry The user profile entry
     */
    public function getUserProfile($user = null, $location = null)
    {
        if ($user !== null) {
            $uri = self::USER_URI . '/' . $user;
        } else if ($location instanceof Zend_Gdata_Query) {
            $uri = $location->getQueryUrl();
        } else {
            $uri = $location;
        }
        return parent::getEntry($uri, 'Zend_Gdata_YouTube_UserProfileEntry');
    }

    /**
     * Helper function for parsing a YouTube token response
     *
     * @param string $response The service response
     * @throws Zend_Gdata_App_Exception
     * @return array An array containing the token and URL
     */
    public static function parseFormUploadTokenResponse($response)
    {
        // Load the feed as an XML DOMDocument object
        @ini_set('track_errors', 1);
        $doc = new DOMDocument();
        $success = @$doc->loadXML($response);
        @ini_restore('track_errors');

        if (!$success) {
            require_once 'Zend/Gdata/App/Exception.php';
            throw new Zend_Gdata_App_Exception(
                "Zend_Gdata_YouTube::parseFormUploadTokenResponse - " .
                "DOMDocument cannot parse XML: $php_errormsg");
        }
        $responseElement = $doc->getElementsByTagName('response')->item(0);

        $urlText = null;
        $tokenText = null;
        if ($responseElement != null) {
            $urlElement =
                $responseElement->getElementsByTagName('url')->item(0);
            $tokenElement =
                $responseElement->getElementsByTagName('token')->item(0);

            if ($urlElement && $urlElement->hasChildNodes() &&
                $tokenElement && $tokenElement->hasChildNodes()) {

                $urlText = $urlElement->firstChild->nodeValue;
                $tokenText = $tokenElement->firstChild->nodeValue;
            }
        }

        if ($tokenText != null && $urlText != null) {
            return array('token' => $tokenText, 'url' => $urlText);
        } else {
            require_once 'Zend/Gdata/App/Exception.php';
            throw new Zend_Gdata_App_Exception(
                'Form upload token not found in response');
        }
    }

    /**
     * Retrieves a YouTube token
     *
     * @param Zend_Gdata_YouTube_VideoEntry $videoEntry The video entry
     * @param string $url The location as a string URL
     * @throws Zend_Gdata_App_Exception
     * @return array An array containing a token and URL
     */
    public function getFormUploadToken($videoEntry,
        $url='http://gdata.youtube.com/action/GetUploadToken')
    {
        if ($url != null && is_string($url)) {
            // $response is a Zend_Http_response object
            $response = $this->post($videoEntry, $url);
            return self::parseFormUploadTokenResponse($response->getBody());
        } else {
            require_once 'Zend/Gdata/App/HttpException.php';
            throw new Zend_Gdata_App_Exception(
                'Url must be provided as a string URL');
        }
    }

    /**
     * Retrieves the activity feed for users
     *
     * @param mixed $usernames A string identifying the usernames for which to
     *              retrieve activity for. This can also be a Zend_Gdata_Query
     *              object from which a URL can be determined.
     * @throws Zend_Gdata_App_VersionException if using version less than 2.
     * @return Zend_Gdata_YouTube_ActivityFeed
     */
    public function getActivityForUser($username)
    {
        if ($this->getMajorProtocolVersion() == 1) {
            require_once 'Zend/Gdata/App/VersionException.php';
            throw new Zend_Gdata_App_VersionException('User activity feeds ' .
                'are not available in API version 1.');
        }

        $uri = null;
        if ($username instanceof Zend_Gdata_Query) {
            $uri = $username->getQueryUrl();
        } else {
            if (count(explode(',', $username)) >
                self::ACTIVITY_FEED_MAX_USERS) {
                require_once 'Zend/Gdata/App/InvalidArgumentException.php';
                throw new Zend_Gdata_App_InvalidArgumentException(
                    'Activity feed can only retrieve for activity for up to ' .
                    self::ACTIVITY_FEED_MAX_USERS .  ' users per request');
            }
            $uri = self::ACTIVITY_FEED_URI . '?author=' . $username;
        }

        return parent::getFeed($uri, 'Zend_Gdata_YouTube_ActivityFeed');
    }

    /**
     * Retrieve the activity of the currently authenticated users friend.
     *
     * @throws Zend_Gdata_App_Exception if not logged in.
     * @return Zend_Gdata_YouTube_ActivityFeed
     */
    public function getFriendActivityForCurrentUser()
    {
        if (!$this->isAuthenticated()) {
            require_once 'Zend/Gdata/YouTube/App/Exception.php';
            throw new Zend_Gdata_App_Exception('You must be authenticated to ' .
                'use the getFriendActivityForCurrentUser function in Zend_' .
                'Gdata_YouTube.');
        }
        return parent::getFeed(self::FRIEND_ACTIVITY_FEED_URI,
            'Zend_Gdata_YouTube_ActivityFeed');
    }

    /**
     * Retrieve a feed of messages in the currently authenticated user's inbox.
     *
     * @throws Zend_Gdata_App_Exception if not logged in.
     * @return Zend_Gdata_YouTube_InboxFeed|null 
     */
    public function getInboxFeedForCurrentUser()
    {
        if (!$this->isAuthenticated()) {
            require_once 'Zend/Gdata/YouTube/App/Exception.php';
            throw new Zend_Gdata_App_Exception('You must be authenticated to ' .
                'use the getInboxFeedForCurrentUser function in Zend_' .
                'Gdata_YouTube.');
        }

        return parent::getFeed(self::INBOX_FEED_URI,
            'Zend_Gdata_YouTube_InboxFeed');
    }
    
    /**
     * Send a video message.
     *
     * Note: Either a Zend_Gdata_YouTube_VideoEntry or a valid video ID must
     * be provided.
     * 
     * @param string $body The body of the message
     * @param Zend_Gdata_YouTube_VideoEntry (optional) The video entry to send
     * @param string $videoId The id of the video to send
     * @param string $recipientUserName The username of the recipient
     * @throws Zend_Gdata_App_InvalidArgumentException if no valid
     *         Zend_Gdata_YouTube_VideoEntry or videoId were provided
     * @return Zend_Gdata_YouTube_InboxEntry|null The
     *         Zend_Gdata_YouTube_Inbox_Entry representing the sent message.
     *
     */
    public function sendVideoMessage($body, $videoEntry = null,
        $videoId = null, $recipientUserName)
    {
        if (!$videoId && !$videoEntry) {
            require_once 'Zend/Gdata/App/InvalidArgumentException.php';
            throw new Zend_Gdata_App_InvalidArgumentException(
                'Expecting either a valid videoID or a videoEntry object in ' .
                'Zend_Gdata_YouTube->sendVideoMessage().');
        }

        $messageEntry = new Zend_Gdata_YouTube_InboxEntry();
        
        if ($this->getMajorProtocolVersion() == null ||
            $this->getMajorProtocolVersion() == 1) {

            if (!$videoId) {
                $videoId = $videoEntry->getVideoId();
            } elseif (strlen($videoId) < 12) {
                //Append the full URI
                $videoId = self::VIDEO_URI . '/' . $videoId;
            }

            $messageEntry->setId($this->newId($videoId));
            // TODO there seems to be a bug where v1 inbox entries dont
            // retain their description...
            $messageEntry->setDescription(
                new Zend_Gdata_YouTube_Extension_Description($body));

        } else {
            if (!$videoId) {
                $videoId = $videoEntry->getVideoId();
                $videoId = substr($videoId, strrpos($videoId, ':'));
            }
            $messageEntry->setId($this->newId($videoId));
            $messageEntry->setSummary($this->newSummary($body));
        }

        $insertUrl = 'http://gdata.youtube.com/feeds/api/users/' .
            $recipientUserName . '/inbox';
        $response = $this->insertEntry($messageEntry, $insertUrl,
            'Zend_Gdata_YouTube_InboxEntry');
        return $response;
    }

}
Gdata/Books/Extension/Embeddability.php000066600000007221151256604610014100 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Describes an embeddability
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Books_Extension_Embeddability extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gbs';
    protected $_rootElement = 'embeddability';
    protected $_value = null;

    /**
     * Constructor for Zend_Gdata_Books_Extension_Embeddability which
     * Describes an embeddability.
     *
     * @param string|null $value A programmatic value representing the book's
     *        embeddability.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Books::$namespaces);
        parent::__construct();
        $this->_value = $value;
    }

    /**
     * Retrieves DOMElement which corresponds to this element and all
     * child properties. This is used to build this object back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistance.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc);
        if ($this->_value !== null) {
            $element->setAttribute('value', $this->_value);
        }
        return $element;
    }

    /**
     * Extracts XML attributes from the DOM and converts them to the
     * appropriate object members.
     *
     * @param DOMNode $attribute The DOMNode attribute to be handled.
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'value':
            $this->_value = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Returns the programmatic value that describes the embeddability of a
     * volume in Google Book Search
     *
     * @return string|null The value
     */
    public function getValue()
    {
        return $this->_value;
    }

    /**
     * Sets the programmatic value that describes the embeddability of a
     * volume in Google Book Search
     *
     * @param string|null $value Programmatic value that describes the
     *        embeddability of a volume in Google Book Search
     * @return Zend_Gdata_Books_Extension_Embeddability Provides a fluent
     *     interface
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }

}

Gdata/Books/Extension/Viewability.php000066600000007164151256604610013640 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Describes a viewability
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Books_Extension_Viewability extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'gbs';
    protected $_rootElement = 'viewability';
    protected $_value = null;

    /**
     * Constructor for Zend_Gdata_Books_Extension_Viewability which
     * Describes a viewability
     *
     * @param string|null $value A programmatic value representing the book's
     *        viewability mode.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Books::$namespaces);
        parent::__construct();
        $this->_value = $value;
    }

    /**
     * Retrieves DOMElement which corresponds to this element and all
     * child properties. This is used to build this object back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistance.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc);
        if ($this->_value !== null) {
            $element->setAttribute('value', $this->_value);
        }
        return $element;
    }

    /**
     * Extracts XML attributes from the DOM and converts them to the
     * appropriate object members.
     *
     * @param DOMNode $attribute The DOMNode attribute to be handled.
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'value':
            $this->_value = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Returns the programmatic value that describes the viewability of a volume
     * in Google Book Search
     *
     * @return string The value
     */
    public function getValue()
    {
        return $this->_value;
    }

    /**
     * Sets the programmatic value that describes the viewability of a volume in
     * Google Book Search
     *
     * @param string $value programmatic value that describes the viewability
     *     of a volume in Googl eBook Search
     * @return Zend_Gdata_Books_Extension_Viewability Provides a fluent
     *     interface
     */
    public function setValue($value)
    {
        $this->_value = $value;
        return $this;
    }


}

Gdata/Books/Extension/BooksCategory.php000066600000003603151256604610014115 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension_Category
 */
require_once 'Zend/Gdata/App/Extension/Category.php';

/**
 * Describes a books category
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Books_Extension_BooksCategory extends
    Zend_Gdata_App_Extension_Category
{

    /**
     * Constructor for Zend_Gdata_Books_Extension_BooksCategory which
     * Describes a books category
     *
     * @param string|null $term An identifier representing the category within
     *        the categorization scheme.
     * @param string|null $scheme A string containing a URI identifying the
     *        categorization scheme.
     * @param string|null $label A human-readable label for display in
     *        end-user applications.
     */
    public function __construct($term = null, $scheme = null, $label = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Books::$namespaces);
        parent::__construct($term, $scheme, $label);
    }

}
Gdata/Books/Extension/AnnotationLink.php000066600000004125151256604610014272 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Books_Extension_BooksLink
 */
require_once 'Zend/Gdata/Books/Extension/BooksLink.php';

/**
 * Describes an annotation link
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Books
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Books_Extension_AnnotationLink extends
    Zend_Gdata_Books_Extension_BooksLink
{

    /**
     * Constructor for Zend_Gdata_Books_Extension_AnnotationLink which
     * Describes an annotation link
     *
     * @param string|null $href Linked resource URI
     * @param string|null $rel Forward relationship
     * @param string|null $type Resource MIME type
     * @param string|null $hrefLang Resource language
     * @param string|null $title Human-readable resource title
     * @param string|null $length Resource length in octets
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($href = null, $rel = null, $type = null,
            $hrefLang = null, $title = null, $length = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Books::$namespaces);
        parent::__construct($href, $rel, $type, $hrefLang, $title, $length);
    }

}

Gdata/Spreadsheets/WorksheetEntry.php000066600000014017151256604610013741 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/Entry.php';

/**
 * @see Zend_Gdata_Spreadsheets_Extension_RowCount
 */
require_once 'Zend/Gdata/Spreadsheets/Extension/RowCount.php';

/**
 * @see Zend_Gdata_Spreadsheets_Extension_ColCount
 */
require_once 'Zend/Gdata/Spreadsheets/Extension/ColCount.php';

/**
 * Concrete class for working with Worksheet entries.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright    Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Spreadsheets_WorksheetEntry extends Zend_Gdata_Entry
{

    protected $_entryClassName = 'Zend_Gdata_Spreadsheets_WorksheetEntry';

    protected $_rowCount = null;
    protected $_colCount = null;

    /**
     * Constructs a new Zend_Gdata_Spreadsheets_WorksheetEntry object.
     *
     * @param DOMElement $element (optional) The DOMElement on which to base this object.
     */
    public function __construct($element = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces);
        parent::__construct($element);
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_rowCount != null) {
            $element->appendChild($this->_rowCount->getDOM($element->ownerDocument));
        }
        if ($this->_colCount != null) {
            $element->appendChild($this->_colCount->getDOM($element->ownerDocument));
        }
        return $element;
    }

    /**
     * Creates individual Entry objects of the appropriate type and
     * stores them in the $_entry array based upon DOM data.
     *
     * @param DOMNode $child The DOMNode to process
     */
    protected function takeChildFromDOM($child)
    {
        $absoluteNodeName = $child->namespaceURI . ':' . $child->localName;
        switch ($absoluteNodeName) {
            case $this->lookupNamespace('gs') . ':' . 'rowCount';
                $rowCount = new Zend_Gdata_Spreadsheets_Extension_RowCount();
                $rowCount->transferFromDOM($child);
                $this->_rowCount = $rowCount;
                break;
            case $this->lookupNamespace('gs') . ':' . 'colCount';
                $colCount = new Zend_Gdata_Spreadsheets_Extension_ColCount();
                $colCount->transferFromDOM($child);
                $this->_colCount = $colCount;
                break;
            default:
                parent::takeChildFromDOM($child);
                break;
        }
    }


    /**
     * Gets the row count for this entry.
     *
     * @return string The row count for the entry.
     */
    public function getRowCount()
    {
        return $this->_rowCount;
    }

    /**
     * Gets the column count for this entry.
     *
     * @return string The column count for the entry.
     */
    public function getColumnCount()
    {
        return $this->_colCount;
    }

    /**
     * Sets the row count for this entry.
     *
     * @param string $rowCount The new row count for the entry.
     */
    public function setRowCount($rowCount)
    {
        $this->_rowCount = $rowCount;
        return $this;
    }

    /**
     * Sets the column count for this entry.
     *
     * @param string $colCount The new column count for the entry.
     */
    public function setColumnCount($colCount)
    {
        $this->_colCount = $colCount;
        return $this;
    }

    /**
     * Returns the content of all rows as an associative array
     *
     * @return array An array of rows.  Each element of the array is an associative array of data
     */
    public function getContentsAsRows()
    {
        $service = new Zend_Gdata_Spreadsheets($this->getHttpClient());
        return $service->getSpreadsheetListFeedContents($this);
    }

    /**
     * Returns the content of all cells as an associative array, indexed
     * off the cell location  (ie 'A1', 'D4', etc).  Each element of
     * the array is an associative array with a 'value' and a 'function'.
     * Only non-empty cells are returned by default.  'range' is the
     * value of the 'range' query parameter specified at:
     * http://code.google.com/apis/spreadsheets/reference.html#cells_Parameters
     *
     * @param string $range The range of cells to retrieve
     * @param boolean $empty Whether to retrieve empty cells
     * @return array An associative array of cells
     */
    public function getContentsAsCells($range = null, $empty = false)
    {
        $service = new Zend_Gdata_Spreadsheets($this->getHttpClient());
        return $service->getSpreadsheetCellFeedContents($this, $range, $empty);
    }

}
Gdata/Spreadsheets/Extension/ColCount.php000066600000003414151256604610014445 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Entry.php 3941 2007-03-14 21:36:13Z darby $
 */

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/Entry.php';

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';


/**
 * Concrete class for working with colCount elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Spreadsheets_Extension_ColCount extends Zend_Gdata_Extension
{

    protected $_rootElement = 'colCount';
    protected $_rootNamespace = 'gs';

    /**
     * Constructs a new Zend_Gdata_Spreadsheets_Extension_ColCount element.
     * @param string $text (optional) Text contents of the element.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }
}
Gdata/Spreadsheets/Extension/Cell.php000066600000013110151256604610013570 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Entry.php 3941 2007-03-14 21:36:13Z darby $
 */

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/Entry.php';

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';


/**
 * Concrete class for working with cell elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Spreadsheets_Extension_Cell extends Zend_Gdata_Extension
{
    protected $_rootElement = 'cell';
    protected $_rootNamespace = 'gs';

    /**
     * The row attribute of this cell
     *
     * @var string
     */
    protected $_row = null;

    /**
     * The column attribute of this cell
     *
     * @var string
     */
    protected $_col = null;

    /**
     * The inputValue attribute of this cell
     *
     * @var string
     */
    protected $_inputValue = null;

    /**
     * The numericValue attribute of this cell
     *
     * @var string
     */
    protected $_numericValue = null;

    /**
     * Constructs a new Zend_Gdata_Spreadsheets_Extension_Cell element.
     *
     * @param string $text (optional) Text contents of the element.
     * @param string $row (optional) Row attribute of the element.
     * @param string $col (optional) Column attribute of the element.
     * @param string $inputValue (optional) Input value attribute of the element.
     * @param string $numericValue (optional) Numeric value attribute of the element.
     */
    public function __construct($text = null, $row = null, $col = null, $inputValue = null, $numericValue = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces);
        parent::__construct();
        $this->_text = $text;
        $this->_row = $row;
        $this->_col = $col;
        $this->_inputValue = $inputValue;
        $this->_numericValue = $numericValue;
    }

    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        $element->setAttribute('row', $this->_row);
        $element->setAttribute('col', $this->_col);
        if ($this->_inputValue) $element->setAttribute('inputValue', $this->_inputValue);
        if ($this->_numericValue) $element->setAttribute('numericValue', $this->_numericValue);
        return $element;
    }

    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'row':
            $this->_row = $attribute->nodeValue;
            break;
        case 'col':
            $this->_col = $attribute->nodeValue;
            break;
        case 'inputValue':
            $this->_inputValue = $attribute->nodeValue;
            break;
        case 'numericValue':
            $this->_numericValue = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * Gets the row attribute of the Cell element.
     * @return string Row of the Cell.
     */
    public function getRow()
    {
        return $this->_row;
    }

    /**
     * Gets the column attribute of the Cell element.
     * @return string Column of the Cell.
     */
    public function getColumn()
    {
        return $this->_col;
    }

    /**
     * Gets the input value attribute of the Cell element.
     * @return string Input value of the Cell.
     */
    public function getInputValue()
    {
        return $this->_inputValue;
    }

    /**
     * Gets the numeric value attribute of the Cell element.
     * @return string Numeric value of the Cell.
     */
    public function getNumericValue()
    {
        return $this->_numericValue;
    }

    /**
     * Sets the row attribute of the Cell element.
     * @param string $row New row of the Cell.
     */
    public function setRow($row)
    {
        $this->_row = $row;
        return $this;
    }

    /**
     * Sets the column attribute of the Cell element.
     * @param string $col New column of the Cell.
     */
    public function setColumn($col)
    {
        $this->_col = $col;
        return $this;
    }

    /**
     * Sets the input value attribute of the Cell element.
     * @param string $inputValue New input value of the Cell.
     */
    public function setInputValue($inputValue)
    {
        $this->_inputValue = $inputValue;
        return $this;
    }

    /**
     * Sets the numeric value attribute of the Cell element.
     * @param string $numericValue New numeric value of the Cell.
     */
    public function setNumericValue($numericValue)
    {
        $this->_numericValue = $numericValue;
    }

}
Gdata/Spreadsheets/Extension/Custom.php000066600000006005151256604610014170 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Entry.php 3941 2007-03-14 21:36:13Z darby $
 */

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/Entry.php';

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';


/**
 * Concrete class for working with custom gsx elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Spreadsheets_Extension_Custom extends Zend_Gdata_Extension
{
    // custom elements have custom names.
    protected $_rootElement = null; // The name of the column
    protected $_rootNamespace = 'gsx';

    /**
     * Constructs a new Zend_Gdata_Spreadsheets_Extension_Custom object.
     * @param string $column (optional) The column/tag name of the element.
     * @param string $value (optional) The text content of the element.
     */
    public function __construct($column = null, $value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces);
        parent::__construct();
        $this->_text = $value;
        $this->_rootElement = $column;
    }

    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        return $element;
    }

    /**
     * Transfers each child and attribute into member variables.
     * This is called when XML is received over the wire and the data
     * model needs to be built to represent this XML.
     *
     * @param DOMNode $node The DOMNode that represents this object's data
     */
    public function transferFromDOM($node)
    {
        parent::transferFromDOM($node);
        $this->_rootElement = $node->localName;
    }

    /**
     * Sets the column/tag name of the element.
     * @param string $column The new column name.
     */
    public function setColumnName($column)
    {
        $this->_rootElement = $column;
        return $this;
    }

    /**
     * Gets the column name of the element
     * @return string The column name.
     */
    public function getColumnName()
    {
        return $this->_rootElement;
    }

}
Gdata/Spreadsheets/Extension/RowCount.php000066600000003420151256604610014474 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Entry.php 3941 2007-03-14 21:36:13Z darby $
 */

/**
 * @see Zend_Gdata_Entry
 */
require_once 'Zend/Gdata/Entry.php';

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';


/**
 * Concrete class for working with RowCount elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Spreadsheets
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Spreadsheets_Extension_RowCount extends Zend_Gdata_Extension
{

    protected $_rootElement = 'rowCount';
    protected $_rootNamespace = 'gs';

    /**
     * Constructs a new Zend_Gdata_Spreadsheets_Extension_RowCount object.
     * @param string $text (optional) The text content of the element.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Spreadsheets::$namespaces);
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/Health/Extension/Ccr.php000066600000010450151256604610012177 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Health
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Ccr.php 13122 2008-12-10 02:45:49Z tjohns $
 */

/**
 * @see Zend_Gdata_App_Extension_Element
 */
require_once 'Zend/Gdata/App/Extension/Element.php';

/**
 * Concrete class for working with CCR elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Health
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Health_Extension_Ccr extends Zend_Gdata_App_Extension_Element
{
    protected $_rootNamespace = 'ccr';
    protected $_rootElement = 'ContinuityOfCareRecord';
    protected $_ccrDom = null;

    /**
     * Creates a Zend_Gdata_Health_Extension_Ccr entry, representing CCR data
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($element = null)
    {
        foreach (Zend_Gdata_Health::$namespaces as $nsPrefix => $nsUri) {
            $this->registerNamespace($nsPrefix, $nsUri);
        }
    }

    /**
     * Transfers each child and attribute into member variables.
     * This is called when XML is received over the wire and the data
     * model needs to be built to represent this XML.
     *
     * @param DOMNode $node The DOMNode that represents this object's data
     */
    public function transferFromDOM($node)
    {
        $this->_ccrDom = $node;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        if (is_null($doc)) {
            $doc = new DOMDocument('1.0', 'utf-8');
        }
        $domElement = $doc->importNode($this->_ccrDom, true);
        return $domElement;
    } 

    /**
     * Magic helper that allows drilling down and returning specific elements 
     * in the CCR. For example, to retrieve the users medications
     * (/ContinuityOfCareRecord/Body/Medications) from the entry's CCR, call
     * $entry->getCcr()->getMedications().  Similarly, getConditions() would
     * return extract the user's conditions.
     *
     * @param string $name Name of the function to call
     * @return array.<DOMElement> A list of the appropriate CCR data 
     */
    public function __call($name, $args)
    {
        $matches = array();

        if (substr($name, 0, 3) === 'get') {
            $category = substr($name, 3);

            switch ($category) {
                case 'Conditions':
                    $category = 'Problems';
                    break;
                case 'Allergies':
                    $category = 'Alerts';
                    break;
                case 'TestResults':
                    // TestResults is an alias for LabResults
                case 'LabResults':
                    $category = 'Results';
                    break;
                default:
                    // $category is already well formatted
            }

            return $this->_ccrDom->getElementsByTagNameNS($this->lookupNamespace('ccr'), $category);
        } else {
            return null;
        }
    }
}
Gdata/Gbase/Extension/BaseAttribute.php000066600000007262151256604610014051 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Gbase
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Entry.php 3941 2007-03-14 21:36:13Z darby $
 */

/**
 * @see Zend_Gdata_App_Extension_Element
 */
require_once 'Zend/Gdata/App/Extension/Element.php';

/**
 * Concrete class for working with ItemType elements.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Gbase
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Gbase_Extension_BaseAttribute extends Zend_Gdata_App_Extension_Element
{

    /**
     * Namespace for Google Base elements
     *
     * var @string
     */
    protected $_rootNamespace = 'g';

    /**
     * Create a new instance.
     *
     * @param string $name (optional) The name of the Base attribute
     * @param string $text (optional) The text value of the Base attribute
     * @param string $text (optional) The type of the Base attribute
     */
    public function __construct($name = null, $text = null, $type = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Gbase::$namespaces);
        if ($type !== null) {
          $attr = array('name' => 'type', 'value' => $type);
          $typeAttr = array('type' => $attr);
          $this->setExtensionAttributes($typeAttr);
        }
        parent::__construct($name,
                            $this->_rootNamespace,
                            $this->lookupNamespace($this->_rootNamespace),
                            $text);
    }

    /**
     * Get the name of the attribute
     *
     * @return attribute name The requested object.
     */
    public function getName() {
      return $this->_rootElement;
    }

    /**
     * Get the type of the attribute
     *
     * @return attribute type The requested object.
     */
    public function getType() {
      $typeAttr = $this->getExtensionAttributes();
      return $typeAttr['type']['value'];
    }

    /**
     * Set the 'name' of the Base attribute object:
     *     &lt;g:[$name] type='[$type]'&gt;[$value]&lt;/g:[$name]&gt;
     *
     * @param Zend_Gdata_App_Extension_Element $attribute The attribute object
     * @param string $name The name of the Base attribute
     * @return Zend_Gdata_Extension_ItemEntry Provides a fluent interface
     */
    public function setName($name) {
      $this->_rootElement = $name;
      return $this;
    }

    /**
     * Set the 'type' of the Base attribute object:
     *     &lt;g:[$name] type='[$type]'&gt;[$value]&lt;/g:[$name]&gt;
     *
     * @param Zend_Gdata_App_Extension_Element $attribute The attribute object
     * @param string $type The type of the Base attribute
     * @return Zend_Gdata_Extension_ItemEntry Provides a fluent interface
     */
    public function setType($type) {
      $attr = array('name' => 'type', 'value' => $type);
      $typeAttr = array('type' => $attr);
      $this->setExtensionAttributes($typeAttr);
      return $this;
    }

}
Gdata/App/Extension/Edited.php000066600000002505151256604610012203 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage App
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the app:edited element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage App
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_App_Extension_Edited extends Zend_Gdata_App_Extension
{

    protected $_rootElement = 'edited';

    public function __construct($text = null)
    {
        parent::__construct();
        $this->_text = $text;
    }

}
Gdata/App/Extension/Control.php000066600000005275151256604610012434 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage App
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * @see Zend_Gdata_App_Extension_Draft
 */
require_once 'Zend/Gdata/App/Extension/Draft.php';

/**
 * Represents the app:control element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage App
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_App_Extension_Control extends Zend_Gdata_App_Extension
{

    protected $_rootNamespace = 'app';
    protected $_rootElement = 'control';
    protected $_draft = null;

    public function __construct($draft = null)
    {
        parent::__construct();
        $this->_draft = $draft;
    }

    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_draft != null) {
            $element->appendChild($this->_draft->getDOM($element->ownerDocument));
        }
        return $element;
    }

    protected function takeChildFromDOM($child)
    {
        $absoluteNodeName = $child->namespaceURI . ':' . $child->localName;
        switch ($absoluteNodeName) {
        case $this->lookupNamespace('app') . ':' . 'draft':
            $draft = new Zend_Gdata_App_Extension_Draft();
            $draft->transferFromDOM($child);
            $this->_draft = $draft;
            break;
        default:
            parent::takeChildFromDOM($child);
            break;
        }
    }

    /**
     * @return Zend_Gdata_App_Extension_Draft
     */
    public function getDraft()
    {
        return $this->_draft;
    }

    /**
     * @param Zend_Gdata_App_Extension_Draft $value
     * @return Zend_Gdata_App_Entry Provides a fluent interface
     */
    public function setDraft($value)
    {
        $this->_draft = $value;
        return $this;
    }

}
Gdata/App/Extension/Element.php000066600000003434151256604610012400 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage App
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Class that represents elements which were not handled by other parsing
 * code in the library.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage App
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_App_Extension_Element extends Zend_Gdata_App_Extension
{

    public function __construct($rootElement=null, $rootNamespace=null, $rootNamespaceURI=null, $text=null){
        parent::__construct();
        $this->_rootElement = $rootElement;
        $this->_rootNamespace = $rootNamespace;
        $this->_rootNamespaceURI = $rootNamespaceURI;
        $this->_text = $text;
    }

    public function transferFromDOM($node)
    {
        parent::transferFromDOM($node);
        $this->_rootNamespace = null;
        $this->_rootNamespaceURI = $node->namespaceURI;
        $this->_rootElement = $node->localName;
    }

}
Gdata/DublinCore/Extension/Rights.php000066600000003365151256604610013560 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Information about rights held in and over the resource
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_DublinCore_Extension_Rights extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'dc';
    protected $_rootElement = 'rights';

    /**
     * Constructor for Zend_Gdata_DublinCore_Extension_Rights which
     * Information about rights held in and over the resource
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces);
        parent::__construct();
        $this->_text = $value;
    }

}
Gdata/DublinCore/Extension/Title.php000066600000003272151256604610013376 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Name given to the resource
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_DublinCore_Extension_Title extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'dc';
    protected $_rootElement = 'title';

    /**
     * Constructor for Zend_Gdata_DublinCore_Extension_Title which
     * Name given to the resource
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces);
        parent::__construct();
        $this->_text = $value;
    }

}
Gdata/DublinCore/Extension/Date.php000066600000003461151256604610013172 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Point or period of time associated with an event in the lifecycle of the
 * resource
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_DublinCore_Extension_Date extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'dc';
    protected $_rootElement = 'date';

    /**
     * Constructor for Zend_Gdata_DublinCore_Extension_Date which
     * Point or period of time associated with an event in the lifecycle of the
     * resource
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces);
        parent::__construct();
        $this->_text = $value;
    }

}
Gdata/DublinCore/Extension/Subject.php000066600000003266151256604610013717 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Topic of the resource
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_DublinCore_Extension_Subject extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'dc';
    protected $_rootElement = 'subject';

    /**
     * Constructor for Zend_Gdata_DublinCore_Extension_Subject which
     * Topic of the resource
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces);
        parent::__construct();
        $this->_text = $value;
    }

}
Gdata/DublinCore/Extension/Format.php000066600000003377151256604610013553 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * File format, physical medium, or dimensions of the resource
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_DublinCore_Extension_Format extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'dc';
    protected $_rootElement = 'format';

    /**
     * Constructor for Zend_Gdata_DublinCore_Extension_Format which
     * File format, physical medium, or dimensions of the resource
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces);
        parent::__construct();
        $this->_text = $value;
    }

}
Gdata/DublinCore/Extension/Language.php000066600000003277151256604610014045 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Language of the resource
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_DublinCore_Extension_Language extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'dc';
    protected $_rootElement = 'language';

    /**
     * Constructor for Zend_Gdata_DublinCore_Extension_Language which
     * Language of the resource
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces);
        parent::__construct();
        $this->_text = $value;
    }

}
Gdata/DublinCore/Extension/Publisher.php000066600000003372151256604610014253 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Gdata_Extension
 */
require_once 'Zend/Gdata/Extension.php';

/**
 * Entity responsible for making the resource available
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage DublinCore
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc.
 * (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_DublinCore_Extension_Publisher extends Zend_Gdata_Extension
{

    protected $_rootNamespace = 'dc';
    protected $_rootElement = 'publisher';

    /**
     * Constructor for Zend_Gdata_DublinCore_Extension_Publisher which
     * Entity responsible for making the resource available
     *
     * @param DOMElement $element (optional) DOMElement from which this
     *          object should be constructed.
     */
    public function __construct($value = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_DublinCore::$namespaces);
        parent::__construct();
        $this->_text = $value;
    }

}
ProgressBar/Adapter/Console.php000066600000033505151256604610012510 0ustar00<?php
/**
 * 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_ProgressBar
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Console.php 14112 2009-02-19 06:32:51Z yoshida@zend.co.jp $
 */

/**
 * @see Zend_ProgressBar_Adapter
 */
require_once 'Zend/ProgressBar/Adapter.php';

/**
 * Zend_ProgressBar_Adapter_Console offers a text-based progressbar for console
 * applications
 *
 * @category  Zend
 * @package   Zend_ProgressBar
 * @uses      Zend_ProgressBar_Adapter_Interface
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_ProgressBar_Adapter_Console extends Zend_ProgressBar_Adapter
{
    /**
     * Percentage value of the progress
     */
    const ELEMENT_PERCENT = 'ELEMENT_PERCENT';

    /**
     * Visual value of the progress
     */
    const ELEMENT_BAR = 'ELEMENT_BAR';

    /**
     * ETA of the progress
     */
    const ELEMENT_ETA = 'ELEMENT_ETA';

    /**
     * Text part of the progress
     */
    const ELEMENT_TEXT = 'ELEMENT_TEXT';

    /**
     * Finish action: End of Line
     */
    const FINISH_ACTION_EOL = 'FINISH_ACTION_EOL';

    /**
     * Finish action: Clear Line
     */
    const FINISH_ACTION_CLEAR_LINE = 'FINISH_ACTION_CLEAR_LINE';

    /**
     * Finish action: None
     */
    const FINISH_ACTION_NONE = 'FINISH_ACTION_NONE';

    /**
     * Width of the progressbar
     *
     * @var integer
     */
    protected $_width = null;

    /**
     * Elements to display
     *
     * @var array
     */
    protected $_elements = array(self::ELEMENT_PERCENT,
                                 self::ELEMENT_BAR,
                                 self::ELEMENT_ETA);

    /**
     * Which action to do at finish call
     *
     * @var string
     */
    protected $_finishAction = self::FINISH_ACTION_EOL;

    /**
     * Width of the bar element
     *
     * @var integer
     */
    protected $_barWidth;

    /**
     * Left character(s) within the bar
     *
     * @var string
     */
    protected $_barLeftChar = '#';

    /**
     * Indicator character(s) within the bar
     *
     * @var string
     */
    protected $_barIndicatorChar = '';

    /**
     * Right character(s) within the bar
     *
     * @var string
     */
    protected $_barRightChar = '-';

    /**
     * Stdout stream, when STDOUT is not defined (e.g. in CGI)
     *
     * @var resource
     */
    protected $_stdout = null;

    /**
     * Width of the text element
     *
     * @var string
     */
    protected $_textWidth = 20;

    /**
     * Wether the output started yet or not
     *
     * @var boolean
     */
    protected $_outputStarted = false;

    /**
     * Defined by Zend_ProgressBar_Adapter
     *
     * @param null|array|Zend_Config $options
     */
    public function __construct($options = null)
    {
        // If STDOUT isn't defined, open a local resource
        if (!defined('STDOUT')) {
            $this->_stdout = fopen('php://stdout', 'w');
        }

        // Call parent constructor with options
        parent::__construct($options);

        // Check if a width was set, else use auto width
        if ($this->_width === null) {
            $this->setWidth();
        }
    }

    /**
     * Close local stdout, when open
     */
    public function __destruct()
    {
        if ($this->_stdout !== null) {
            fclose($this->_stdout);
        }
    }

    /**
     * Set the width of the progressbar
     *
     * @param  integer $width
     * @return Zend_ProgressBar_Adapter_Console
     */
    public function setWidth($width = null)
    {
        if ($width === null || !is_integer($width)) {
            if (substr(PHP_OS, 0, 3) === 'WIN') {
                // We have to default to 79 on windows, because the windows
                // terminal always has a fixed width of 80 characters and the
                // cursor is counted to the line, else windows would line break
                // after every update.
                $this->_width = 79;
            } else {
                // Set the default width of 80
                $this->_width = 80;

                // Try to determine the width through stty
                if (preg_match('#\d+ (\d+)#', @shell_exec('stty size'), $match) === 1) {
                    $this->_width = (int) $match[1];
                } else if (preg_match('#columns = (\d+);#', @shell_exec('stty'), $match) === 1) {
                    $this->_width = (int) $match[1];
                }
            }
        } else {
            $this->_width = (int) $width;
        }

        $this->_calculateBarWidth();

        return $this;
    }

    /**
     * Set the elements to display with the progressbar
     *
     * @param  array $elements
     * @throws Zend_ProgressBar_Adapter_Exception When an invalid element is foudn in the array
     * @return Zend_ProgressBar_Adapter_Console
     */
    public function setElements(array $elements)
    {
        $allowedElements = array(self::ELEMENT_PERCENT,
                                 self::ELEMENT_BAR,
                                 self::ELEMENT_ETA,
                                 self::ELEMENT_TEXT);

        if (count(array_diff($elements, $allowedElements)) > 0) {
            require_once 'Zend/ProgressBar/Adapter/Exception.php';
            throw new Zend_ProgressBar_Adapter_Exception('Invalid element found in $elements array');
        }

        $this->_elements = $elements;

        $this->_calculateBarWidth();

        return $this;
    }

    /**
     * Set the left-hand character for the bar
     *
     * @param  string $char
     * @throws Zend_ProgressBar_Adapter_Exception When character is empty
     * @return Zend_ProgressBar_Adapter_Console
     */
    public function setBarLeftChar($char)
    {
        if (empty($char)) {
            require_once 'Zend/ProgressBar/Adapter/Exception.php';
            throw new Zend_ProgressBar_Adapter_Exception('Character may not be empty');
        }

        $this->_barLeftChar = (string) $char;

        return $this;
    }

    /**
     * Set the right-hand character for the bar
     *
     * @param  string $char
     * @throws Zend_ProgressBar_Adapter_Exception When character is empty
     * @return Zend_ProgressBar_Adapter_Console
     */
    public function setBarRightChar($char)
    {
        if (empty($char)) {
            require_once 'Zend/ProgressBar/Adapter/Exception.php';
            throw new Zend_ProgressBar_Adapter_Exception('Character may not be empty');
        }

        $this->_barRightChar = (string) $char;

        return $this;
    }

    /**
     * Set the indicator character for the bar
     *
     * @param  string $char
     * @return Zend_ProgressBar_Adapter_Console
     */
    public function setBarIndicatorChar($char)
    {
        $this->_barIndicatorChar = (string) $char;

        return $this;
    }

    /**
     * Set the width of the text element
     *
     * @param  integer $width
     * @return Zend_ProgressBar_Adapter_Console
     */
    public function setTextWidth($width)
    {
        $this->_textWidth = (int) $width;

        $this->_calculateBarWidth();

        return $this;
    }

    /**
     * Set the finish action
     *
     * @param  string $action
     * @throws Zend_ProgressBar_Adapter_Exception When an invalid action is specified
     * @return Zend_ProgressBar_Adapter_Console
     */
    public function setFinishAction($action)
    {
        $allowedActions = array(self::FINISH_ACTION_CLEAR_LINE,
                                self::FINISH_ACTION_EOL,
                                self::FINISH_ACTION_NONE);

        if (!in_array($action, $allowedActions)) {
            require_once 'Zend/ProgressBar/Adapter/Exception.php';
            throw new Zend_ProgressBar_Adapter_Exception('Invalid finish action specified');
        }

        $this->_finishAction = $action;

        return $this;
    }

    /**
     * Defined by Zend_ProgressBar_Adapter_Interface
     *
     * @param  float   $current       Current progress value
     * @param  float   $max           Max progress value
     * @param  float   $percent       Current percent value
     * @param  integer $timeTaken     Taken time in seconds
     * @param  integer $timeRemaining Remaining time in seconds
     * @param  string  $text          Status text
     * @return void
     */
    public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text)
    {
        // See if we must clear the line
        if ($this->_outputStarted) {
            $data = str_repeat("\x08", $this->_width);
        } else {
            $data = '';
            $this->_outputStarted = true;
        }

        // Build all elements
        $renderedElements = array();

        foreach ($this->_elements as $element) {
            switch ($element) {
                case self::ELEMENT_BAR:
                    $visualWidth = $this->_barWidth - 2;
                    $bar         = '[';

                    $indicatorWidth = strlen($this->_barIndicatorChar);

                    $doneWidth = min($visualWidth - $indicatorWidth, round($visualWidth * $percent));
                    if ($doneWidth > 0) {
                        $bar .= substr(str_repeat($this->_barLeftChar, ceil($doneWidth / strlen($this->_barLeftChar))), 0, $doneWidth);
                    }

                    $bar .= $this->_barIndicatorChar;

                    $leftWidth = $visualWidth - $doneWidth - $indicatorWidth;
                    if ($leftWidth > 0) {
                        $bar .= substr(str_repeat($this->_barRightChar, ceil($leftWidth / strlen($this->_barRightChar))), 0, $leftWidth);
                    }

                    $bar .= ']';

                    $renderedElements[] = $bar;
                    break;

                case self::ELEMENT_PERCENT:
                    $renderedElements[] = str_pad(round($percent * 100), 3, ' ', STR_PAD_LEFT) . '%';
                    break;

                case self::ELEMENT_ETA:
                    // In the first 5 seconds we don't get accurate results,
                    // this skipping technique is found in many progressbar
                    // implementations.
                    if ($timeTaken < 5) {
                        $renderedElements[] = str_repeat(' ', 12);
                        break;
                    }

                    if ($timeRemaining === null || $timeRemaining > 86400) {
                        $etaFormatted = '??:??:??';
                    } else {
                        $hours   = floor($timeRemaining / 3600);
                        $minutes = floor(($timeRemaining % 3600) / 60);
                        $seconds = ($timeRemaining % 3600 % 60);

                        $etaFormatted = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
                    }

                    $renderedElements[] = 'ETA ' . $etaFormatted;
                    break;

                case self::ELEMENT_TEXT:
                    $renderedElements[] = str_pad(substr($text, 0, $this->_textWidth), $this->_textWidth, ' ');
                    break;
            }
        }

        $data .= implode(' ', $renderedElements);

        // Output line data
        $this->_outputData($data);
    }

    /**
     * Defined by Zend_ProgressBar_Adapter_Interface
     *
     * @return void
     */
    public function finish()
    {
        switch ($this->_finishAction) {
            case self::FINISH_ACTION_EOL:
                $this->_outputData(PHP_EOL);
                break;

            case self::FINISH_ACTION_CLEAR_LINE:
                if ($this->_outputStarted) {
                    $data = str_repeat("\x08", $this->_width)
                          . str_repeat(' ', $this->_width)
                          . str_repeat("\x08", $this->_width);

                    $this->_outputData($data);
                }
                break;

            case self::FINISH_ACTION_NONE:
                break;
        }
    }

    /**
     * Calculate the bar width when other elements changed
     *
     * @return void
     */
    protected function _calculateBarWidth()
    {
        if (in_array(self::ELEMENT_BAR, $this->_elements)) {
            $barWidth = $this->_width;

            if (in_array(self::ELEMENT_PERCENT, $this->_elements)) {
                $barWidth -= 4;
            }

            if (in_array(self::ELEMENT_ETA, $this->_elements)) {
                $barWidth -= 12;
            }

            if (in_array(self::ELEMENT_TEXT, $this->_elements)) {
                $barWidth -= $this->_textWidth;
            }

            $this->_barWidth = $barWidth - (count($this->_elements) - 1);
        }
    }

    /**
     * Outputs given data to STDOUT.
     *
     * This split-off is required for unit-testing.
     *
     * @param  string $data
     * @return void
     */
    protected function _outputData($data)
    {
        if ($this->_stdout !== null) {
            fwrite($this->_stdout, $data);
        } else {
            fwrite(STDOUT, $data);
        }
    }
}Uri/Exception.php000066600000002165151256604610007770 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Uri
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: Exception.php 9656 2008-06-10 16:21:13Z dasprid $
 */

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

/**
 * Exceptions for Zend_Uri
 *
 * @category  Zend
 * @package   Zend_Uri
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Uri_Exception extends Zend_Exception
{
}
Uri/Http.php000066600000056132151256604610006754 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Uri
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: Http.php 12041 2008-10-20 22:13:01Z shahar $
 */

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

/**
 * @see Zend_Validate_Hostname
 */
require_once 'Zend/Validate/Hostname.php';

/**
 * HTTP(S) URI handler
 *
 * @category  Zend
 * @package   Zend_Uri
 * @uses      Zend_Uri
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Uri_Http extends Zend_Uri
{
    /**
     * Character classes for validation regular expressions
     */
    const CHAR_ALNUM    = 'A-Za-z0-9';
    const CHAR_MARK     = '-_.!~*\'()\[\]';
    const CHAR_RESERVED = ';\/?:@&=+$,';
    const CHAR_SEGMENT  = ':@&=+$,;';
    const CHAR_UNWISE   = '{}|\\\\^`';
    
    /**
     * HTTP username
     *
     * @var string
     */
    protected $_username = '';

    /**
     * HTTP password
     *
     * @var string
     */
    protected $_password = '';

    /**
     * HTTP host
     *
     * @var string
     */
    protected $_host = '';

    /**
     * HTTP post
     *
     * @var string
     */
    protected $_port = '';

    /**
     * HTTP part
     *
     * @var string
     */
    protected $_path = '';

    /**
     * HTTP query
     *
     * @var string
     */
    protected $_query = '';

    /**
     * HTTP fragment
     *
     * @var string
     */
    protected $_fragment = '';

    /**
     * Regular expression grammar rules for validation; values added by constructor
     *
     * @var array
     */
    protected $_regex = array();
    
    /**
     * Constructor accepts a string $scheme (e.g., http, https) and a scheme-specific part of the URI
     * (e.g., example.com/path/to/resource?query=param#fragment)
     *
     * @param  string $scheme         The scheme of the URI
     * @param  string $schemeSpecific The scheme-specific part of the URI
     * @throws Zend_Uri_Exception When the URI is not valid
     */
    protected function __construct($scheme, $schemeSpecific = '')
    {
        // Set the scheme
        $this->_scheme = $scheme;

        // Set up grammar rules for validation via regular expressions. These
        // are to be used with slash-delimited regular expression strings.
        
        // Escaped special characters (eg. '%25' for '%') 
        $this->_regex['escaped']    = '%[[:xdigit:]]{2}';
        
        // Unreserved characters
        $this->_regex['unreserved'] = '[' . self::CHAR_ALNUM . self::CHAR_MARK . ']';
        
        // Segment can use escaped, unreserved or a set of additional chars
        $this->_regex['segment']    = '(?:' . $this->_regex['escaped'] . '|[' .
            self::CHAR_ALNUM . self::CHAR_MARK . self::CHAR_SEGMENT . '])*';
        
        // Path can be a series of segmets char strings seperated by '/'
        $this->_regex['path']       = '(?:\/(?:' . $this->_regex['segment'] . ')?)+';
        
        // URI characters can be escaped, alphanumeric, mark or reserved chars
        $this->_regex['uric']       = '(?:' . $this->_regex['escaped'] . '|[' .  
            self::CHAR_ALNUM . self::CHAR_MARK . self::CHAR_RESERVED . 
            
        // If unwise chars are allowed, add them to the URI chars class
            (self::$_config['allow_unwise'] ? self::CHAR_UNWISE : '') . '])';
                                    
        // If no scheme-specific part was supplied, the user intends to create
        // a new URI with this object.  No further parsing is required.
        if (strlen($schemeSpecific) === 0) {
            return;
        }

        // Parse the scheme-specific URI parts into the instance variables.
        $this->_parseUri($schemeSpecific);

        // Validate the URI
        if ($this->valid() === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Invalid URI supplied');
        }
    }

    /**
     * Creates a Zend_Uri_Http from the given string
     *
     * @param  string $uri String to create URI from, must start with
     *                     'http://' or 'https://'
     * @throws InvalidArgumentException  When the given $uri is not a string or
     *                                   does not start with http:// or https://
     * @throws Zend_Uri_Exception        When the given $uri is invalid
     * @return Zend_Uri_Http
     */
    public static function fromString($uri)
    {
        if (is_string($uri) === false) {
            throw new InvalidArgumentException('$uri is not a string');
        }

        $uri            = explode(':', $uri, 2);
        $scheme         = strtolower($uri[0]);
        $schemeSpecific = isset($uri[1]) === true ? $uri[1] : '';

        if (in_array($scheme, array('http', 'https')) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("Invalid scheme: '$scheme'");
        }

        $schemeHandler = new Zend_Uri_Http($scheme, $schemeSpecific);
        return $schemeHandler;
    }

    /**
     * Parse the scheme-specific portion of the URI and place its parts into instance variables.
     *
     * @param  string $schemeSpecific The scheme-specific portion to parse
     * @throws Zend_Uri_Exception When scheme-specific decoposition fails
     * @throws Zend_Uri_Exception When authority decomposition fails
     * @return void
     */
    protected function _parseUri($schemeSpecific)
    {
        // High-level decomposition parser
        $pattern = '~^((//)([^/?#]*))([^?#]*)(\?([^#]*))?(#(.*))?$~';
        $status  = @preg_match($pattern, $schemeSpecific, $matches);
        if ($status === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Internal error: scheme-specific decomposition failed');
        }

        // Failed decomposition; no further processing needed
        if ($status === false) {
            return;
        }

        // Save URI components that need no further decomposition
        $this->_path     = isset($matches[4]) === true ? $matches[4] : '';
        $this->_query    = isset($matches[6]) === true ? $matches[6] : '';
        $this->_fragment = isset($matches[8]) === true ? $matches[8] : '';

        // Additional decomposition to get username, password, host, and port
        $combo   = isset($matches[3]) === true ? $matches[3] : '';
        $pattern = '~^(([^:@]*)(:([^@]*))?@)?([^:]+)(:(.*))?$~';
        $status  = @preg_match($pattern, $combo, $matches);
        if ($status === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Internal error: authority decomposition failed');
        }

        // Failed decomposition; no further processing needed
        if ($status === false) {
            return;
        }

        // Save remaining URI components
        $this->_username = isset($matches[2]) === true ? $matches[2] : '';
        $this->_password = isset($matches[4]) === true ? $matches[4] : '';
        $this->_host     = isset($matches[5]) === true ? $matches[5] : '';
        $this->_port     = isset($matches[7]) === true ? $matches[7] : '';

    }

    /**
     * Returns a URI based on current values of the instance variables. If any
     * part of the URI does not pass validation, then an exception is thrown.
     *
     * @throws Zend_Uri_Exception When one or more parts of the URI are invalid
     * @return string
     */
    public function getUri()
    {
        if ($this->valid() === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('One or more parts of the URI are invalid');
        }

        $password = strlen($this->_password) > 0 ? ":$this->_password" : '';
        $auth     = strlen($this->_username) > 0 ? "$this->_username$password@" : '';
        $port     = strlen($this->_port) > 0 ? ":$this->_port" : '';
        $query    = strlen($this->_query) > 0 ? "?$this->_query" : '';
        $fragment = strlen($this->_fragment) > 0 ? "#$this->_fragment" : '';

        return $this->_scheme
             . '://'
             . $auth
             . $this->_host
             . $port
             . $this->_path
             . $query
             . $fragment;
    }

    /**
     * Validate the current URI from the instance variables. Returns true if and only if all
     * parts pass validation.
     *
     * @return boolean
     */
    public function valid()
    {
        // Return true if and only if all parts of the URI have passed validation
        return $this->validateUsername()
           and $this->validatePassword()
           and $this->validateHost()
           and $this->validatePort()
           and $this->validatePath()
           and $this->validateQuery()
           and $this->validateFragment();
    }

    /**
     * Returns the username portion of the URL, or FALSE if none.
     *
     * @return string
     */
    public function getUsername()
    {
        return strlen($this->_username) > 0 ? $this->_username : false;
    }

    /**
     * Returns true if and only if the username passes validation. If no username is passed,
     * then the username contained in the instance variable is used.
     *
     * @param  string $username The HTTP username
     * @throws Zend_Uri_Exception When username validation fails
     * @return boolean
     * @link   http://www.faqs.org/rfcs/rfc2396.html
     */
    public function validateUsername($username = null)
    {
        if ($username === null) {
            $username = $this->_username;
        }

        // If the username is empty, then it is considered valid
        if (strlen($username) === 0) {
            return true;
        }

        // Check the username against the allowed values
        $status = @preg_match('/^(?:' . $this->_regex['escaped'] . '|[' .
            self::CHAR_ALNUM . self::CHAR_MARK . ';:&=+$,' . '])+$/', $username);
                            
        if ($status === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Internal error: username validation failed');
        }

        return $status === 1;
    }

    /**
     * Sets the username for the current URI, and returns the old username
     *
     * @param  string $username The HTTP username
     * @throws Zend_Uri_Exception When $username is not a valid HTTP username
     * @return string
     */
    public function setUsername($username)
    {
        if ($this->validateUsername($username) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("Username \"$username\" is not a valid HTTP username");
        }

        $oldUsername     = $this->_username;
        $this->_username = $username;

        return $oldUsername;
    }

    /**
     * Returns the password portion of the URL, or FALSE if none.
     *
     * @return string
     */
    public function getPassword()
    {
        return strlen($this->_password) > 0 ? $this->_password : false;
    }

    /**
     * Returns true if and only if the password passes validation. If no password is passed,
     * then the password contained in the instance variable is used.
     *
     * @param  string $password The HTTP password
     * @throws Zend_Uri_Exception When password validation fails
     * @return boolean
     * @link   http://www.faqs.org/rfcs/rfc2396.html
     */
    public function validatePassword($password = null)
    {
        if ($password === null) {
            $password = $this->_password;
        }

        // If the password is empty, then it is considered valid
        if (strlen($password) === 0) {
            return true;
        }

        // If the password is nonempty, but there is no username, then it is considered invalid
        if (strlen($password) > 0 and strlen($this->_username) === 0) {
            return false;
        }

        // Check the password against the allowed values
        $status = @preg_match('/^(?:' . $this->_regex['escaped'] . '|[' .
            self::CHAR_ALNUM . self::CHAR_MARK . ';:&=+$,' . '])+$/', $password);
            
        if ($status === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Internal error: password validation failed.');
        }

        return $status == 1;
    }

    /**
     * Sets the password for the current URI, and returns the old password
     *
     * @param  string $password The HTTP password
     * @throws Zend_Uri_Exception When $password is not a valid HTTP password
     * @return string
     */
    public function setPassword($password)
    {
        if ($this->validatePassword($password) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("Password \"$password\" is not a valid HTTP password.");
        }

        $oldPassword     = $this->_password;
        $this->_password = $password;

        return $oldPassword;
    }

    /**
     * Returns the domain or host IP portion of the URL, or FALSE if none.
     *
     * @return string
     */
    public function getHost()
    {
        return strlen($this->_host) > 0 ? $this->_host : false;
    }

    /**
     * Returns true if and only if the host string passes validation. If no host is passed,
     * then the host contained in the instance variable is used.
     *
     * @param  string $host The HTTP host
     * @return boolean
     * @uses   Zend_Filter
     */
    public function validateHost($host = null)
    {
        if ($host === null) {
            $host = $this->_host;
        }

        // If the host is empty, then it is considered invalid
        if (strlen($host) === 0) {
            return false;
        }

        // Check the host against the allowed values; delegated to Zend_Filter.
        $validate = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_ALL);

        return $validate->isValid($host);
    }

    /**
     * Sets the host for the current URI, and returns the old host
     *
     * @param  string $host The HTTP host
     * @throws Zend_Uri_Exception When $host is nota valid HTTP host
     * @return string
     */
    public function setHost($host)
    {
        if ($this->validateHost($host) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("Host \"$host\" is not a valid HTTP host");
        }

        $oldHost     = $this->_host;
        $this->_host = $host;

        return $oldHost;
    }

    /**
     * Returns the TCP port, or FALSE if none.
     *
     * @return string
     */
    public function getPort()
    {
        return strlen($this->_port) > 0 ? $this->_port : false;
    }

    /**
     * Returns true if and only if the TCP port string passes validation. If no port is passed,
     * then the port contained in the instance variable is used.
     *
     * @param  string $port The HTTP port
     * @return boolean
     */
    public function validatePort($port = null)
    {
        if ($port === null) {
            $port = $this->_port;
        }

        // If the port is empty, then it is considered valid
        if (strlen($port) === 0) {
            return true;
        }

        // Check the port against the allowed values
        return ctype_digit((string) $port) and 1 <= $port and $port <= 65535;
    }

    /**
     * Sets the port for the current URI, and returns the old port
     *
     * @param  string $port The HTTP port
     * @throws Zend_Uri_Exception When $port is not a valid HTTP port
     * @return string
     */
    public function setPort($port)
    {
        if ($this->validatePort($port) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("Port \"$port\" is not a valid HTTP port.");
        }

        $oldPort     = $this->_port;
        $this->_port = $port;

        return $oldPort;
    }

    /**
     * Returns the path and filename portion of the URL, or FALSE if none.
     *
     * @return string
     */
    public function getPath()
    {
        return strlen($this->_path) > 0 ? $this->_path : '/';
    }

    /**
     * Returns true if and only if the path string passes validation. If no path is passed,
     * then the path contained in the instance variable is used.
     *
     * @param  string $path The HTTP path
     * @throws Zend_Uri_Exception When path validation fails
     * @return boolean
     */
    public function validatePath($path = null)
    {
        if ($path === null) {
            $path = $this->_path;
        }

        // If the path is empty, then it is considered valid
        if (strlen($path) === 0) {
            return true;
        }

        // Determine whether the path is well-formed
        $pattern = '/^' . $this->_regex['path'] . '$/';
        $status  = @preg_match($pattern, $path);
        if ($status === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Internal error: path validation failed');
        }

        return (boolean) $status;
    }

    /**
     * Sets the path for the current URI, and returns the old path
     *
     * @param  string $path The HTTP path
     * @throws Zend_Uri_Exception When $path is not a valid HTTP path
     * @return string
     */
    public function setPath($path)
    {
        if ($this->validatePath($path) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("Path \"$path\" is not a valid HTTP path");
        }

        $oldPath     = $this->_path;
        $this->_path = $path;

        return $oldPath;
    }

    /**
     * Returns the query portion of the URL (after ?), or FALSE if none.
     *
     * @return string
     */
    public function getQuery()
    {
        return strlen($this->_query) > 0 ? $this->_query : false;
    }

    /**
     * Returns true if and only if the query string passes validation. If no query is passed,
     * then the query string contained in the instance variable is used.
     *
     * @param  string $query The query to validate
     * @throws Zend_Uri_Exception When query validation fails
     * @return boolean
     * @link   http://www.faqs.org/rfcs/rfc2396.html
     */
    public function validateQuery($query = null)
    {
        if ($query === null) {
            $query = $this->_query;
        }

        // If query is empty, it is considered to be valid
        if (strlen($query) === 0) {
            return true;
        }

        // Determine whether the query is well-formed
        $pattern = '/^' . $this->_regex['uric'] . '*$/';
        $status  = @preg_match($pattern, $query);
        if ($status === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Internal error: query validation failed');
        }

        return $status == 1;
    }

    /**
     * Set the query string for the current URI, and return the old query
     * string This method accepts both strings and arrays.
     *
     * @param  string|array $query The query string or array
     * @throws Zend_Uri_Exception When $query is not a valid query string
     * @return string              Old query string
     */
    public function setQuery($query)
    {
        $oldQuery = $this->_query;

        // If query is empty, set an empty string
        if (empty($query) === true) {
            $this->_query = '';
            return $oldQuery;
        }

        // If query is an array, make a string out of it
        if (is_array($query) === true) {
            $query = http_build_query($query, '', '&');
        } else {
            // If it is a string, make sure it is valid. If not parse and encode it
            $query = (string) $query;
            if ($this->validateQuery($query) === false) {
                parse_str($query, $queryArray);
                $query = http_build_query($queryArray, '', '&');
            }
        }

        // Make sure the query is valid, and set it
        if ($this->validateQuery($query) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("'$query' is not a valid query string");
        }

        $this->_query = $query;

        return $oldQuery;
    }

    /**
     * Returns the fragment portion of the URL (after #), or FALSE if none.
     *
     * @return string|false
     */
    public function getFragment()
    {
        return strlen($this->_fragment) > 0 ? $this->_fragment : false;
    }

    /**
     * Returns true if and only if the fragment passes validation. If no fragment is passed,
     * then the fragment contained in the instance variable is used.
     *
     * @param  string $fragment Fragment of an URI
     * @throws Zend_Uri_Exception When fragment validation fails
     * @return boolean
     * @link   http://www.faqs.org/rfcs/rfc2396.html
     */
    public function validateFragment($fragment = null)
    {
        if ($fragment === null) {
            $fragment = $this->_fragment;
        }

        // If fragment is empty, it is considered to be valid
        if (strlen($fragment) === 0) {
            return true;
        }

        // Determine whether the fragment is well-formed
        $pattern = '/^' . $this->_regex['uric'] . '*$/';
        $status  = @preg_match($pattern, $fragment);
        if ($status === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Internal error: fragment validation failed');
        }

        return (boolean) $status;
    }

    /**
     * Sets the fragment for the current URI, and returns the old fragment
     *
     * @param  string $fragment Fragment of the current URI
     * @throws Zend_Uri_Exception When $fragment is not a valid HTTP fragment
     * @return string
     */
    public function setFragment($fragment)
    {
        if ($this->validateFragment($fragment) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("Fragment \"$fragment\" is not a valid HTTP fragment");
        }

        $oldFragment     = $this->_fragment;
        $this->_fragment = $fragment;

        return $oldFragment;
    }
}
Text/Table/Decorator/Ascii.php000066600000006262151256604610012222 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package   Zend_Text_Table
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 * @version   $Id: Ascii.php 12529 2008-11-10 21:05:43Z dasprid $
 */

/**
 * @see Zend_Text_Table_Decorator_Interface
 */
require_once 'Zend/Text/Table/Decorator/Interface.php';

/**
 * ASCII Decorator for Zend_Text_Table
 *
 * @category  Zend
 * @package   Zend_Text_Table
 * @uses      Zend_Text_Table_Decorator_Interface
 * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Text_Table_Decorator_Ascii implements Zend_Text_Table_Decorator_Interface
{
    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getTopLeft()
    {
        return '+';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getTopRight()
    {
        return '+';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getBottomLeft()
    {
        return '+';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getBottomRight()
    {
        return '+';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getVertical()
    {
        return '|';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getHorizontal()
    {
        return '-';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getCross()
    {
        return '+';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getVerticalRight()
    {
        return '+';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getVerticalLeft()
    {
        return '+';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getHorizontalDown()
    {
        return '+';
    }

    /**
     * Defined by Zend_Text_Table_Decorator_Interface
     *
     * @return string
     */
    public function getHorizontalUp()
    {
        return '+';
    }
}
Controller/Response/HttpTestCase.php000066600000006637151256604610013577 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

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

/**
 * Zend_Controller_Response_HttpTestCase
 *
 * @uses Zend_Controller_Response_Http
 * @package Zend_Controller
 * @subpackage Request
 */
class Zend_Controller_Response_HttpTestCase extends Zend_Controller_Response_Http
{
    /**
     * "send" headers by returning array of all headers that would be sent
     * 
     * @return array
     */
    public function sendHeaders()
    {
        $headers = array();
        foreach ($this->_headersRaw as $header) {
            $headers[] = $header;
        }
        foreach ($this->_headers as $header) {
            $name = $header['name'];
            $key  = strtolower($name);
            if (array_key_exists($name, $headers)) {
                if ($header['replace']) {
                    $headers[$key] = $header['name'] . ': ' . $header['value'];
                }
            } else {
                $headers[$key] = $header['name'] . ': ' . $header['value'];
            }
        }
        return $headers;
    }

    /**
     * Can we send headers?
     * 
     * @param  bool $throw 
     * @return void
     */
    public function canSendHeaders($throw = false)
    {
        return true;
    }

    /**
     * Return the concatenated body segments
     * 
     * @return string
     */
    public function outputBody()
    {
        $fullContent = '';
        foreach ($this->_body as $content) {
            $fullContent .= $content;
        }
        return $fullContent;
    }

    /**
     * Get body and/or body segments
     * 
     * @param  bool|string $spec 
     * @return string|array|null
     */
    public function getBody($spec = false)
    {
        if (false === $spec) {
            return $this->outputBody();
        } elseif (true === $spec) {
            return $this->_body;
        } elseif (is_string($spec) && isset($this->_body[$spec])) {
            return $this->_body[$spec];
        }

        return null;
    }

    /**
     * "send" Response
     *
     * Concats all response headers, and then final body (separated by two 
     * newlines)
     * 
     * @return string
     */
    public function sendResponse()
    {
        $headers = $this->sendHeaders();
        $content = implode("\n", $headers) . "\n\n";

        if ($this->isException() && $this->renderExceptions()) {
            $exceptions = '';
            foreach ($this->getException() as $e) {
                $exceptions .= $e->__toString() . "\n";
            }
            $content .= $exceptions;
        } else {
            $content .= $this->outputBody();
        }

        return $content;
    }
}
Controller/Response/Abstract.php000066600000047757151256604610012777 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Zend_Controller_Response_Abstract
 *
 * Base class for Zend_Controller responses
 *
 * @package Zend_Controller
 * @subpackage Response
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Controller_Response_Abstract
{
    /**
     * Body content
     * @var array
     */
    protected $_body = array();

    /**
     * Exception stack
     * @var Exception
     */
    protected $_exceptions = array();

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

    /**
     * Array of raw headers. Each header is a single string, the entire header to emit
     * @var array
     */
    protected $_headersRaw = array();

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

    /**
     * Flag; is this response a redirect?
     * @var boolean
     */
    protected $_isRedirect = false;

    /**
     * Whether or not to render exceptions; off by default
     * @var boolean
     */
    protected $_renderExceptions = false;

    /**
     * Flag; if true, when header operations are called after headers have been
     * sent, an exception will be raised; otherwise, processing will continue
     * as normal. Defaults to true.
     *
     * @see canSendHeaders()
     * @var boolean
     */
    public $headersSentThrowsException = true;

    /**
     * Normalize a header name
     *
     * 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;
    }

    /**
     * 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_Controller_Response_Abstract
     */
    public function setHeader($name, $value, $replace = false)
    {
        $this->canSendHeaders(true);
        $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;
    }

    /**
     * Set redirect URL
     *
     * Sets Location header and response code. Forces replacement of any prior
     * redirects.
     *
     * @param string $url
     * @param int $code
     * @return Zend_Controller_Response_Abstract
     */
    public function setRedirect($url, $code = 302)
    {
        $this->canSendHeaders(true);
        $this->setHeader('Location', $url, true)
             ->setHttpResponseCode($code);

        return $this;
    }

    /**
     * Is this a redirect?
     *
     * @return boolean
     */
    public function isRedirect()
    {
        return $this->_isRedirect;
    }

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

    /**
     * Clear headers
     *
     * @return Zend_Controller_Response_Abstract
     */
    public function clearHeaders()
    {
        $this->_headers = array();

        return $this;
    }

    /**
     * Set raw HTTP header
     *
     * Allows setting non key => value headers, such as status codes
     *
     * @param string $value
     * @return Zend_Controller_Response_Abstract
     */
    public function setRawHeader($value)
    {
        $this->canSendHeaders(true);
        if ('Location' == substr($value, 0, 8)) {
            $this->_isRedirect = true;
        }
        $this->_headersRaw[] = (string) $value;
        return $this;
    }

    /**
     * Retrieve all {@link setRawHeader() raw HTTP headers}
     *
     * @return array
     */
    public function getRawHeaders()
    {
        return $this->_headersRaw;
    }

    /**
     * Clear all {@link setRawHeader() raw HTTP headers}
     *
     * @return Zend_Controller_Response_Abstract
     */
    public function clearRawHeaders()
    {
        $this->_headersRaw = array();
        return $this;
    }

    /**
     * Clear all headers, normal and raw
     *
     * @return Zend_Controller_Response_Abstract
     */
    public function clearAllHeaders()
    {
        return $this->clearHeaders()
                    ->clearRawHeaders();
    }

    /**
     * Set HTTP response code to use with headers
     *
     * @param int $code
     * @return Zend_Controller_Response_Abstract
     */
    public function setHttpResponseCode($code)
    {
        if (!is_int($code) || (100 > $code) || (599 < $code)) {
            require_once 'Zend/Controller/Response/Exception.php';
            throw new Zend_Controller_Response_Exception('Invalid HTTP response code');
        }

        if ((300 <= $code) && (307 >= $code)) {
            $this->_isRedirect = true;
        } else {
            $this->_isRedirect = false;
        }

        $this->_httpResponseCode = $code;
        return $this;
    }

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

    /**
     * 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_Controller_Response_Exception
     */
    public function canSendHeaders($throw = false)
    {
        $ok = headers_sent($file, $line);
        if ($ok && $throw && $this->headersSentThrowsException) {
            require_once 'Zend/Controller/Response/Exception.php';
            throw new Zend_Controller_Response_Exception('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
        }

        return !$ok;
    }

    /**
     * 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 Zend_Controller_Response_Abstract
     */
    public function sendHeaders()
    {
        // Only check if we can send headers if we have headers to send
        if (count($this->_headersRaw) || count($this->_headers) || (200 != $this->_httpResponseCode)) {
            $this->canSendHeaders(true);
        } elseif (200 == $this->_httpResponseCode) {
            // Haven't changed the response code, and we have no headers
            return $this;
        }

        $httpCodeSent = false;

        foreach ($this->_headersRaw as $header) {
            if (!$httpCodeSent && $this->_httpResponseCode) {
                header($header, true, $this->_httpResponseCode);
                $httpCodeSent = true;
            } else {
                header($header);
            }
        }

        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;
        }

        return $this;
    }

    /**
     * Set body content
     *
     * If $name is not passed, or is not a string, resets the entire body and
     * sets the 'default' key to $content.
     *
     * If $name is a string, sets the named segment in the body array to
     * $content.
     *
     * @param string $content
     * @param null|string $name
     * @return Zend_Controller_Response_Abstract
     */
    public function setBody($content, $name = null)
    {
        if ((null === $name) || !is_string($name)) {
            $this->_body = array('default' => (string) $content);
        } else {
            $this->_body[$name] = (string) $content;
        }

        return $this;
    }

    /**
     * Append content to the body content
     *
     * @param string $content
     * @param null|string $name
     * @return Zend_Controller_Response_Abstract
     */
    public function appendBody($content, $name = null)
    {
        if ((null === $name) || !is_string($name)) {
            if (isset($this->_body['default'])) {
                $this->_body['default'] .= (string) $content;
            } else {
                return $this->append('default', $content);
            }
        } elseif (isset($this->_body[$name])) {
            $this->_body[$name] .= (string) $content;
        } else {
            return $this->append($name, $content);
        }

        return $this;
    }

    /**
     * Clear body array
     *
     * With no arguments, clears the entire body array. Given a $name, clears
     * just that named segment; if no segment matching $name exists, returns
     * false to indicate an error.
     *
     * @param  string $name Named segment to clear
     * @return boolean
     */
    public function clearBody($name = null)
    {
        if (null !== $name) {
            $name = (string) $name;
            if (isset($this->_body[$name])) {
                unset($this->_body[$name]);
                return true;
            }

            return false;
        }

        $this->_body = array();
        return true;
    }

    /**
     * Return the body content
     *
     * If $spec is false, returns the concatenated values of the body content
     * array. If $spec is boolean true, returns the body content array. If
     * $spec is a string and matches a named segment, returns the contents of
     * that segment; otherwise, returns null.
     *
     * @param boolean $spec
     * @return string|array|null
     */
    public function getBody($spec = false)
    {
        if (false === $spec) {
            ob_start();
            $this->outputBody();
            return ob_get_clean();
        } elseif (true === $spec) {
            return $this->_body;
        } elseif (is_string($spec) && isset($this->_body[$spec])) {
            return $this->_body[$spec];
        }

        return null;
    }

    /**
     * Append a named body segment to the body content array
     *
     * If segment already exists, replaces with $content and places at end of
     * array.
     *
     * @param string $name
     * @param string $content
     * @return Zend_Controller_Response_Abstract
     */
    public function append($name, $content)
    {
        if (!is_string($name)) {
            require_once 'Zend/Controller/Response/Exception.php';
            throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
        }

        if (isset($this->_body[$name])) {
            unset($this->_body[$name]);
        }
        $this->_body[$name] = (string) $content;
        return $this;
    }

    /**
     * Prepend a named body segment to the body content array
     *
     * If segment already exists, replaces with $content and places at top of
     * array.
     *
     * @param string $name
     * @param string $content
     * @return void
     */
    public function prepend($name, $content)
    {
        if (!is_string($name)) {
            require_once 'Zend/Controller/Response/Exception.php';
            throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
        }

        if (isset($this->_body[$name])) {
            unset($this->_body[$name]);
        }

        $new = array($name => (string) $content);
        $this->_body = $new + $this->_body;

        return $this;
    }

    /**
     * Insert a named segment into the body content array
     *
     * @param  string $name
     * @param  string $content
     * @param  string $parent
     * @param  boolean $before Whether to insert the new segment before or
     * after the parent. Defaults to false (after)
     * @return Zend_Controller_Response_Abstract
     */
    public function insert($name, $content, $parent = null, $before = false)
    {
        if (!is_string($name)) {
            require_once 'Zend/Controller/Response/Exception.php';
            throw new Zend_Controller_Response_Exception('Invalid body segment key ("' . gettype($name) . '")');
        }

        if ((null !== $parent) && !is_string($parent)) {
            require_once 'Zend/Controller/Response/Exception.php';
            throw new Zend_Controller_Response_Exception('Invalid body segment parent key ("' . gettype($parent) . '")');
        }

        if (isset($this->_body[$name])) {
            unset($this->_body[$name]);
        }

        if ((null === $parent) || !isset($this->_body[$parent])) {
            return $this->append($name, $content);
        }

        $ins  = array($name => (string) $content);
        $keys = array_keys($this->_body);
        $loc  = array_search($parent, $keys);
        if (!$before) {
            // Increment location if not inserting before
            ++$loc;
        }

        if (0 === $loc) {
            // If location of key is 0, we're prepending
            $this->_body = $ins + $this->_body;
        } elseif ($loc >= (count($this->_body))) {
            // If location of key is maximal, we're appending
            $this->_body = $this->_body + $ins;
        } else {
            // Otherwise, insert at location specified
            $pre  = array_slice($this->_body, 0, $loc);
            $post = array_slice($this->_body, $loc);
            $this->_body = $pre + $ins + $post;
        }

        return $this;
    }

    /**
     * Echo the body segments
     *
     * @return void
     */
    public function outputBody()
    {
        foreach ($this->_body as $content) {
            echo $content;
        }
    }

    /**
     * Register an exception with the response
     *
     * @param Exception $e
     * @return Zend_Controller_Response_Abstract
     */
    public function setException(Exception $e)
    {
        $this->_exceptions[] = $e;
        return $this;
    }

    /**
     * Retrieve the exception stack
     *
     * @return array
     */
    public function getException()
    {
        return $this->_exceptions;
    }

    /**
     * Has an exception been registered with the response?
     *
     * @return boolean
     */
    public function isException()
    {
        return !empty($this->_exceptions);
    }

    /**
     * Does the response object contain an exception of a given type?
     *
     * @param  string $type
     * @return boolean
     */
    public function hasExceptionOfType($type)
    {
        foreach ($this->_exceptions as $e) {
            if ($e instanceof $type) {
                return true;
            }
        }

        return false;
    }

    /**
     * Does the response object contain an exception with a given message?
     *
     * @param  string $message
     * @return boolean
     */
    public function hasExceptionOfMessage($message)
    {
        foreach ($this->_exceptions as $e) {
            if ($message == $e->getMessage()) {
                return true;
            }
        }

        return false;
    }

    /**
     * Does the response object contain an exception with a given code?
     *
     * @param  int $code
     * @return boolean
     */
    public function hasExceptionOfCode($code)
    {
        $code = (int) $code;
        foreach ($this->_exceptions as $e) {
            if ($code == $e->getCode()) {
                return true;
            }
        }

        return false;
    }

    /**
     * Retrieve all exceptions of a given type
     *
     * @param  string $type
     * @return false|array
     */
    public function getExceptionByType($type)
    {
        $exceptions = array();
        foreach ($this->_exceptions as $e) {
            if ($e instanceof $type) {
                $exceptions[] = $e;
            }
        }

        if (empty($exceptions)) {
            $exceptions = false;
        }

        return $exceptions;
    }

    /**
     * Retrieve all exceptions of a given message
     *
     * @param  string $message
     * @return false|array
     */
    public function getExceptionByMessage($message)
    {
        $exceptions = array();
        foreach ($this->_exceptions as $e) {
            if ($message == $e->getMessage()) {
                $exceptions[] = $e;
            }
        }

        if (empty($exceptions)) {
            $exceptions = false;
        }

        return $exceptions;
    }

    /**
     * Retrieve all exceptions of a given code
     *
     * @param mixed $code
     * @return void
     */
    public function getExceptionByCode($code)
    {
        $code       = (int) $code;
        $exceptions = array();
        foreach ($this->_exceptions as $e) {
            if ($code == $e->getCode()) {
                $exceptions[] = $e;
            }
        }

        if (empty($exceptions)) {
            $exceptions = false;
        }

        return $exceptions;
    }

    /**
     * Whether or not to render exceptions (off by default)
     *
     * If called with no arguments or a null argument, returns the value of the
     * flag; otherwise, sets it and returns the current value.
     *
     * @param boolean $flag Optional
     * @return boolean
     */
    public function renderExceptions($flag = null)
    {
        if (null !== $flag) {
            $this->_renderExceptions = $flag ? true : false;
        }

        return $this->_renderExceptions;
    }

    /**
     * Send the response, including all headers, rendering exceptions if so
     * requested.
     *
     * @return void
     */
    public function sendResponse()
    {
        $this->sendHeaders();

        if ($this->isException() && $this->renderExceptions()) {
            $exceptions = '';
            foreach ($this->getException() as $e) {
                $exceptions .= $e->__toString() . "\n";
            }
            echo $exceptions;
            return;
        }

        $this->outputBody();
    }

    /**
     * Magic __toString functionality
     *
     * Proxies to {@link sendResponse()} and returns response value as string
     * using output buffering.
     *
     * @return string
     */
    public function __toString()
    {
        ob_start();
        $this->sendResponse();
        return ob_get_clean();
    }
}
Controller/Action/HelperBroker/PriorityStack.php000066600000021400151256604610016017 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Action_HelperBroker_PriorityStack implements IteratorAggregate, ArrayAccess, Countable
{

    /** @protected */
    protected $_helpersByPriority = array();
    protected $_helpersByNameRef  = array();
    protected $_nextDefaultPriority = 1;
    
    /**
     * Magic property overloading for returning helper by name
     *
     * @param string $helperName    The helper name
     * @return Zend_Controller_Action_Helper_Abstract
     */
    public function __get($helperName)
    {
        if (!array_key_exists($helperName, $this->_helpersByNameRef)) {
            return false;
        }
        
        return $this->_helpersByNameRef[$helperName];
    }
    
    /**
     * Magic property overloading for returning if helper is set by name
     *
     * @param string $helperName    The helper name
     * @return Zend_Controller_Action_Helper_Abstract
     */
    public function __isset($helperName)
    {
        return array_key_exists($helperName, $this->_helpersByNameRef);
    }
    
    /**
     * Magic property overloading for unsetting if helper is exists by name
     *
     * @param string $helperName    The helper name
     * @return Zend_Controller_Action_Helper_Abstract
     */
    public function __unset($helperName)
    {
        return $this->offsetUnset($helperName);
    }
    
    /**
     * push helper onto the stack
     *
     * @param Zend_Controller_Action_Helper_Abstract $helper
     * @return Zend_Controller_Action_HelperBroker_PriorityStack
     */
    public function push(Zend_Controller_Action_Helper_Abstract $helper)
    {
        $this->offsetSet($this->getNextFreeHigherPriority(), $helper);
        return $this;
    }
    
    /**
     * Return something iterable
     *
     * @return array
     */
    public function getIterator()
    {
        return new ArrayObject($this->_helpersByPriority);
    }
    
    /**
     * offsetExists()
     *
     * @param int|string $priorityOrHelperName 
     * @return Zend_Controller_Action_HelperBroker_PriorityStack
     */
    public function offsetExists($priorityOrHelperName)
    {
        if (is_string($priorityOrHelperName)) {
            return array_key_exists($priorityOrHelperName, $this->_helpersByNameRef);
        } else {
            return array_key_exists($priorityOrHelperName, $this->_helpersByPriority);
        }
    }
    
    /**
     * offsetGet()
     *
     * @param int|string $priorityOrHelperName
     * @return Zend_Controller_Action_HelperBroker_PriorityStack
     */
    public function offsetGet($priorityOrHelperName)
    {
        if (!$this->offsetExists($priorityOrHelperName)) {
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception('A helper with priority ' . $priority . ' does not exist.');
        }
        
        if (is_string($priorityOrHelperName)) {
            return $this->_helpersByNameRef[$priorityOrHelperName];
        } else {
            return $this->_helpersByPriority[$priorityOrHelperName];
        }
    }
    
    /**
     * offsetSet()
     *
     * @param int $priority
     * @param Zend_Controller_Action_Helper_Abstract $helper
     * @return Zend_Controller_Action_HelperBroker_PriorityStack
     */
    public function offsetSet($priority, $helper)
    {
        $priority = (int) $priority;

        if (!$helper instanceof Zend_Controller_Action_Helper_Abstract) {
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception('$helper must extend Zend_Controller_Action_Helper_Abstract.');
        }
        
        if (array_key_exists($helper->getName(), $this->_helpersByNameRef)) {
            // remove any object with the same name to retain BC compailitbility
            // @todo At ZF 2.0 time throw an exception here.
            $this->offsetUnset($helper->getName());
        }
        
        if (array_key_exists($priority, $this->_helpersByPriority)) {
            $priority = $this->getNextFreeHigherPriority($priority);  // ensures LIFO
            trigger_error("A helper with the same priority already exists, reassigning to $priority", E_USER_WARNING);
        }
        
        $this->_helpersByPriority[$priority] = $helper;
        $this->_helpersByNameRef[$helper->getName()] = $helper;

        if ($priority == ($nextFreeDefault = $this->getNextFreeHigherPriority($this->_nextDefaultPriority))) {
            $this->_nextDefaultPriority = $nextFreeDefault;
        }
        
        krsort($this->_helpersByPriority);  // always make sure priority and LIFO are both enforced
        return $this;
    }
    
    /**
     * offsetUnset()
     *
     * @param int|string $priorityOrHelperName Priority integer or the helper name
     * @return Zend_Controller_Action_HelperBroker_PriorityStack
     */
    public function offsetUnset($priorityOrHelperName)
    {
        if (!$this->offsetExists($priorityOrHelperName)) {
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception('A helper with priority or name ' . $priorityOrHelperName . ' does not exist.');
        }
        
        if (is_string($priorityOrHelperName)) {
            $helperName = $priorityOrHelperName;
            $helper = $this->_helpersByNameRef[$helperName];
            $priority = array_search($helper, $this->_helpersByPriority, true);
        } else {
            $priority = $priorityOrHelperName;
            $helperName = $this->_helpersByPriority[$priorityOrHelperName]->getName();
        }
        
        unset($this->_helpersByNameRef[$helperName]);
        unset($this->_helpersByPriority[$priority]);
        return $this;
    }
    
    /**
     * return the count of helpers
     *
     * @return int
     */
    public function count()
    {
        return count($this->_helpersByPriority);
    }
    
    /**
     * Find the next free higher priority.  If an index is given, it will
     * find the next free highest priority after it.
     *
     * @param int $indexPriority OPTIONAL
     * @return int
     */
    public function getNextFreeHigherPriority($indexPriority = null)
    {
        if ($indexPriority == null) {
            $indexPriority = $this->_nextDefaultPriority;
        }
        
        $priorities = array_keys($this->_helpersByPriority);

        while (in_array($indexPriority, $priorities)) {
            $indexPriority++;
        }
        
        return $indexPriority;
    }
    
    /**
     * Find the next free lower priority.  If an index is given, it will
     * find the next free lower priority before it.
     *
     * @param int $indexPriority
     * @return int
     */
    public function getNextFreeLowerPriority($indexPriority = null)
    {
        if ($indexPriority == null) {
            $indexPriority = $this->_nextDefaultPriority;
        }
        
        $priorities = array_keys($this->_helpersByPriority);

        while (in_array($indexPriority, $priorities)) {
            $indexPriority--;
        }
        
        return $indexPriority;        
    }
    
    /**
     * return the highest priority
     *
     * @return int
     */
    public function getHighestPriority()
    {
        return max(array_keys($this->_helpersByPriority));
    }
    
    /**
     * return the lowest priority
     *
     * @return int
     */
    public function getLowestPriority()
    {
        return min(array_keys($this->_helpersByPriority));
    }
    
    /**
     * return the helpers referenced by name
     *
     * @return array
     */
    public function getHelpersByName()
    {
        return $this->_helpersByNameRef;
    }
    
}
Controller/Action/Helper/FlashMessenger.php000066600000015742151256604610014765 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Session
 */
require_once 'Zend/Session.php';

/**
 * @see Zend_Controller_Action_Helper_Abstract
 */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * Flash Messenger - implement session-based messages
 *
 * @uses       Zend_Controller_Action_Helper_Abstract
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */
class Zend_Controller_Action_Helper_FlashMessenger extends Zend_Controller_Action_Helper_Abstract implements IteratorAggregate, Countable
{
    /**
     * $_messages - Messages from previous request
     *
     * @var array
     */
    static protected $_messages = array();

    /**
     * $_session - Zend_Session storage object
     *
     * @var Zend_Session
     */
    static protected $_session = null;

    /**
     * $_messageAdded - Wether a message has been previously added
     *
     * @var boolean
     */
    static protected $_messageAdded = false;

    /**
     * $_namespace - Instance namespace, default is 'default'
     *
     * @var string
     */
    protected $_namespace = 'default';

    /**
     * __construct() - Instance constructor, needed to get iterators, etc
     *
     * @param  string $namespace
     * @return void
     */
    public function __construct()
    {
        if (!self::$_session instanceof Zend_Session_Namespace) {
            self::$_session = new Zend_Session_Namespace($this->getName());
            foreach (self::$_session as $namespace => $messages) {
                self::$_messages[$namespace] = $messages;
                unset(self::$_session->{$namespace});
            }
        }
    }

    /**
     * postDispatch() - runs after action is dispatched, in this
     * case, it is resetting the namespace in case we have forwarded to a different
     * action, Flashmessage will be 'clean' (default namespace)
     *
     * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface
     */
    public function postDispatch()
    {
        $this->resetNamespace();
        return $this;
    }

    /**
     * setNamespace() - change the namespace messages are added to, useful for
     * per action controller messaging between requests
     *
     * @param  string $namespace
     * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface
     */
    public function setNamespace($namespace = 'default')
    {
        $this->_namespace = $namespace;
        return $this;
    }

    /**
     * resetNamespace() - reset the namespace to the default
     *
     * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface
     */
    public function resetNamespace()
    {
        $this->setNamespace();
        return $this;
    }

    /**
     * addMessage() - Add a message to flash message
     *
     * @param  string $message
     * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface
     */
    public function addMessage($message)
    {
        if (self::$_messageAdded === false) {
            self::$_session->setExpirationHops(1, null, true);
        }

        if (!is_array(self::$_session->{$this->_namespace})) {
            self::$_session->{$this->_namespace} = array();
        }

        self::$_session->{$this->_namespace}[] = $message;

        return $this;
    }

    /**
     * hasMessages() - Wether a specific namespace has messages
     *
     * @return boolean
     */
    public function hasMessages()
    {
        return isset(self::$_messages[$this->_namespace]);
    }

    /**
     * getMessages() - Get messages from a specific namespace
     *
     * @return array
     */
    public function getMessages()
    {
        if ($this->hasMessages()) {
            return self::$_messages[$this->_namespace];
        }

        return array();
    }

    /**
     * Clear all messages from the previous request & current namespace
     *
     * @return boolean True if messages were cleared, false if none existed
     */
    public function clearMessages()
    {
        if ($this->hasMessages()) {
            unset(self::$_messages[$this->_namespace]);
            return true;
        }

        return false;
    }

    /**
     * hasCurrentMessages() - check to see if messages have been added to current
     * namespace within this request
     *
     * @return boolean
     */
    public function hasCurrentMessages()
    {
        return isset(self::$_session->{$this->_namespace});
    }

    /**
     * getCurrentMessages() - get messages that have been added to the current
     * namespace within this request
     *
     * @return array
     */
    public function getCurrentMessages()
    {
        if ($this->hasCurrentMessages()) {
            return self::$_session->{$this->_namespace};
        }

        return array();
    }

    /**
     * clear messages from the current request & current namespace
     *
     * @return boolean
     */
    public function clearCurrentMessages()
    {
        if ($this->hasCurrentMessages()) {
            unset(self::$_session->{$this->_namespace});
            return true;
        }
        
        return false;
    }
    
    /**
     * getIterator() - complete the IteratorAggregate interface, for iterating
     *
     * @return ArrayObject
     */
    public function getIterator()
    {
        if ($this->hasMessages()) {
            return new ArrayObject($this->getMessages());
        }

        return new ArrayObject();
    }

    /**
     * count() - Complete the countable interface
     *
     * @return int
     */
    public function count()
    {
        if ($this->hasMessages()) {
            return count($this->getMessages());
        }

        return 0;
    }

    /**
     * Strategy pattern: proxy to addMessage()
     * 
     * @param  string $message 
     * @return void
     */
    public function direct($message)
    {
        return $this->addMessage($message);
    }
}
Controller/Action/Helper/Url.php000066600000007623151256604610012620 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Url.php 12526 2008-11-10 20:25:20Z ralph $
 */

/**
 * @see Zend_Controller_Action_Helper_Abstract
 */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * Helper for creating URLs for redirects and other tasks
 *
 * @uses       Zend_Controller_Action_Helper_Abstract
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Action_Helper_Url extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * Create URL based on default route
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return string
     */
    public function simple($action, $controller = null, $module = null, array $params = null)
    {
        $request = $this->getRequest();

        if (null === $controller) {
            $controller = $request->getControllerName();
        }

        if (null === $module) {
            $module = $request->getModuleName();
        }

        $url = $controller . '/' . $action;
        if ($module != $this->getFrontController()->getDispatcher()->getDefaultModule()) {
            $url = $module . '/' . $url;
        }
        
        if ('' !== ($baseUrl = $this->getFrontController()->getBaseUrl())) {
        	$url = $baseUrl . '/' . $url;
        }

        if (null !== $params) {
            $paramPairs = array();
            foreach ($params as $key => $value) {
                $paramPairs[] = urlencode($key) . '/' . urlencode($value);
            }
            $paramString = implode('/', $paramPairs);
            $url .= '/' . $paramString;
        }

        $url = '/' . ltrim($url, '/');

        return $url;
    }

    /**
     * Assembles a URL based on a given route
     *
     * This method will typically be used for more complex operations, as it
     * ties into the route objects registered with the router.
     *
     * @param  array   $urlOptions Options passed to the assemble method of the Route object.
     * @param  mixed   $name       The name of a Route to use. If null it will use the current Route
     * @param  boolean $reset
     * @param  boolean $encode
     * @return string Url for the link href attribute.
     */
    public function url($urlOptions = array(), $name = null, $reset = false, $encode = true)
    {
        $router = $this->getFrontController()->getRouter();
        return $router->assemble($urlOptions, $name, $reset, $encode);
    }
    
    /**
     * Perform helper when called as $this->_helper->url() from an action controller
     *
     * Proxies to {@link simple()}
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return string
     */
    public function direct($action, $controller = null, $module = null, array $params = null)
    {
        return $this->simple($action, $controller, $module, $params);
    }
}
Controller/Action/Helper/Json.php000066600000007051151256604610012762 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Json.php 9098 2008-03-30 19:29:10Z thomas $
 */

/**
 * @see Zend_Controller_Action_Helper_Abstract
 */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * Simplify AJAX context switching based on requested format
 *
 * @uses       Zend_Controller_Action_Helper_Abstract
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Action_Helper_Json extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * Suppress exit when sendJson() called
     * @var boolean
     */
    public $suppressExit = false;

    /**
     * Create JSON response
     *
     * Encodes and returns data to JSON. Content-Type header set to 
     * 'application/json', and disables layouts and viewRenderer (if being 
     * used).
     *
     * @param  mixed   $data
     * @param  boolean $keepLayouts
     * @throws Zend_Controller_Action_Helper_Json
     * @return string
     */
    public function encodeJson($data, $keepLayouts = false)
    {
        /**
         * @see Zend_View_Helper_Json
         */
        require_once 'Zend/View/Helper/Json.php';
        $jsonHelper = new Zend_View_Helper_Json();
        $data = $jsonHelper->json($data, $keepLayouts);

        if (!$keepLayouts) {
            /**
             * @see Zend_Controller_Action_HelperBroker
             */
            require_once 'Zend/Controller/Action/HelperBroker.php';
            Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
        }

        return $data;
    }

    /**
     * Encode JSON response and immediately send
     * 
     * @param  mixed   $data 
     * @param  boolean $keepLayouts 
     * @return string|void
     */
    public function sendJson($data, $keepLayouts = false)
    {
        $data = $this->encodeJson($data, $keepLayouts);
        $response = $this->getResponse();
        $response->setBody($data);

        if (!$this->suppressExit) {
            $response->sendResponse();
            exit;
        }

        return $data;
    }

    /**
     * Strategy pattern: call helper as helper broker method
     *
     * Allows encoding JSON. If $sendNow is true, immediately sends JSON 
     * response. 
     * 
     * @param  mixed   $data 
     * @param  boolean $sendNow 
     * @param  boolean $keepLayouts 
     * @return string|void
     */
    public function direct($data, $sendNow = true, $keepLayouts = false)
    {
        if ($sendNow) {
            return $this->sendJson($data, $keepLayouts);
        }
        return $this->encodeJson($data, $keepLayouts);
    }
}
Controller/Action/Helper/ActionStack.php000066600000011303151256604610014247 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ActionStack.php 11493 2008-09-23 14:25:11Z doctorrock83 $
 */

/**
 * @see Zend_Controller_Action_Helper_Abstract
 */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * Add to action stack
 *
 * @uses       Zend_Controller_Action_Helper_Abstract
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Action_Helper_ActionStack extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Zend_Controller_Plugin_ActionStack
     */
    protected $_actionStack;

    /**
     * Constructor
     *
     * Register action stack plugin
     * 
     * @return void
     */
    public function __construct()
    {
        $front = Zend_Controller_Front::getInstance();
        if (!$front->hasPlugin('Zend_Controller_Plugin_ActionStack')) {
            /**
             * @see Zend_Controller_Plugin_ActionStack
             */
            require_once 'Zend/Controller/Plugin/ActionStack.php';
            $this->_actionStack = new Zend_Controller_Plugin_ActionStack();
            $front->registerPlugin($this->_actionStack, 97);
        } else {
            $this->_actionStack = $front->getPlugin('Zend_Controller_Plugin_ActionStack');
        }
    }

    /**
     * Push onto the stack 
     * 
     * @param  Zend_Controller_Request_Abstract $next 
     * @return Zend_Controller_Action_Helper_ActionStack Provides a fluent interface
     */
    public function pushStack(Zend_Controller_Request_Abstract $next)
    {
        $this->_actionStack->pushStack($next);
        return $this;
    }

    /**
     * Push a new action onto the stack
     * 
     * @param  string $action 
     * @param  string $controller 
     * @param  string $module 
     * @param  array  $params
     * @throws Zend_Controller_Action_Exception 
     * @return Zend_Controller_Action_Helper_ActionStack
     */
    public function actionToStack($action, $controller = null, $module = null, array $params = array())
    {
        if ($action instanceof Zend_Controller_Request_Abstract) {
            return $this->pushStack($action);
        } elseif (!is_string($action)) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception('ActionStack requires either a request object or minimally a string action');
        }

        $request = $this->getRequest();

        if ($request instanceof Zend_Controller_Request_Abstract === false){
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception('Request object not set yet');
        }
        
        $controller = (null === $controller) ? $request->getControllerName() : $controller;
        $module = (null === $module) ? $request->getModuleName() : $module;

        /**
         * @see Zend_Controller_Request_Simple
         */
        require_once 'Zend/Controller/Request/Simple.php';
        $newRequest = new Zend_Controller_Request_Simple($action, $controller, $module, $params);

        return $this->pushStack($newRequest);
    }

    /**
     * Perform helper when called as $this->_helper->actionStack() from an action controller
     *
     * Proxies to {@link simple()}
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array $params
     * @return boolean
     */
    public function direct($action, $controller = null, $module = null, array $params = array())
    {
        return $this->actionToStack($action, $controller, $module, $params);
    }
}
Controller/Action/Helper/Redirector.php000066600000036174151256604610014163 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** 
 * @see Zend_Controller_Action_Exception
 */
require_once 'Zend/Controller/Action/Exception.php';

/**
 * @see Zend_Controller_Action_Helper_Abstract
 */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Action_Helper_Redirector extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * HTTP status code for redirects
     * @var int
     */
    protected $_code = 302;

    /**
     * Whether or not calls to _redirect() should exit script execution
     * @var boolean
     */
    protected $_exit = true;

    /**
     * Whether or not _redirect() should attempt to prepend the base URL to the
     * passed URL (if it's a relative URL)
     * @var boolean
     */
    protected $_prependBase = true;

    /**
     * Url to which to redirect
     * @var string
     */
    protected $_redirectUrl = null;

    /**
     * Whether or not to use an absolute URI when redirecting
     * @var boolean
     */
    protected $_useAbsoluteUri = false;

    /**
     * Retrieve HTTP status code to emit on {@link _redirect()} call
     *
     * @return int
     */
    public function getCode()
    {
        return $this->_code;
    }

    /**
     * Validate HTTP status redirect code
     *
     * @param  int $code
     * @throws Zend_Controller_Action_Exception on invalid HTTP status code
     * @return true
     */
    protected function _checkCode($code)
    {
        $code = (int)$code;
        if ((300 > $code) || (307 < $code) || (304 == $code) || (306 == $code)) {
            /**
             * @see Zend_Controller_Exception
             */
            require_once 'Zend/Controller/Exception.php';
            throw new Zend_Controller_Action_Exception('Invalid redirect HTTP status code (' . $code  . ')');
        }

        return true;
    }

    /**
     * Retrieve HTTP status code for {@link _redirect()} behaviour
     *
     * @param  int $code
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setCode($code)
    {
        $this->_checkCode($code);
        $this->_code = $code;
        return $this;
    }

    /**
     * Retrieve flag for whether or not {@link _redirect()} will exit when finished.
     *
     * @return boolean
     */
    public function getExit()
    {
        return $this->_exit;
    }

    /**
     * Retrieve exit flag for {@link _redirect()} behaviour
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setExit($flag)
    {
        $this->_exit = ($flag) ? true : false;
        return $this;
    }

    /**
     * Retrieve flag for whether or not {@link _redirect()} will prepend the
     * base URL on relative URLs
     *
     * @return boolean
     */
    public function getPrependBase()
    {
        return $this->_prependBase;
    }

    /**
     * Retrieve 'prepend base' flag for {@link _redirect()} behaviour
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setPrependBase($flag)
    {
        $this->_prependBase = ($flag) ? true : false;
        return $this;
    }

    /**
     * Return use absolute URI flag
     *
     * @return boolean
     */
    public function getUseAbsoluteUri()
    {
        return $this->_useAbsoluteUri;
    }

    /**
     * Set use absolute URI flag
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_Redirector Provides a fluent interface
     */
    public function setUseAbsoluteUri($flag = true)
    {
        $this->_useAbsoluteUri = ($flag) ? true : false;
        return $this;
    }

    /**
     * Set redirect in response object
     *
     * @return void
     */
    protected function _redirect($url)
    {
        if ($this->getUseAbsoluteUri() && !preg_match('#^(https?|ftp)://#', $url)) {
            $host  = (isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'');
            $proto = (isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=="off") ? 'https' : 'http';
            $port  = (isset($_SERVER['SERVER_PORT'])?$_SERVER['SERVER_PORT']:80);
            $uri   = $proto . '://' . $host;
            if ((('http' == $proto) && (80 != $port)) || (('https' == $proto) && (443 != $port))) {
                $uri .= ':' . $port;
            }
            $url = $uri . '/' . ltrim($url, '/');
        }
        $this->_redirectUrl = $url;
        $this->getResponse()->setRedirect($url, $this->getCode());
    }

    /**
     * Retrieve currently set URL for redirect
     *
     * @return string
     */
    public function getRedirectUrl()
    {
        return $this->_redirectUrl;
    }

    /**
     * Determine if the baseUrl should be prepended, and prepend if necessary
     *
     * @param  string $url
     * @return string
     */
    protected function _prependBase($url)
    {
        if ($this->getPrependBase()) {
            $request = $this->getRequest();
            if ($request instanceof Zend_Controller_Request_Http) {
                $base = rtrim($request->getBaseUrl(), '/');
                if (!empty($base) && ('/' != $base)) {
                    $url = $base . '/' . ltrim($url, '/');
                } else {
                    $url = '/' . ltrim($url, '/');
                }
            }
        }

        return $url;
    }

    /**
     * Set a redirect URL of the form /module/controller/action/params
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return void
     */
    public function setGotoSimple($action, $controller = null, $module = null, array $params = array())
    {
        $dispatcher = $this->getFrontController()->getDispatcher();
        $request    = $this->getRequest();
        $curModule  = $request->getModuleName();
        $useDefaultController = false;

        if (null === $controller && null !== $module) {
            $useDefaultController = true;
        }

        if (null === $module) {
            $module = $curModule;
        } 
        
        if ($module == $dispatcher->getDefaultModule()) {
            $module = '';
        }

        if (null === $controller && !$useDefaultController) {
            $controller = $request->getControllerName();
            if (empty($controller)) {
                $controller = $dispatcher->getDefaultControllerName();
            }
        }

        $params['module']     = $module;
        $params['controller'] = $controller;
        $params['action']     = $action;

        $router = $this->getFrontController()->getRouter();
        $url    = $router->assemble($params, 'default', true);

        $this->_redirect($url);
    }

    /**
     * Build a URL based on a route
     *
     * @param  array   $urlOptions
     * @param  string  $name Route name
     * @param  boolean $reset
     * @param  boolean $encode
     * @return void
     */
    public function setGotoRoute(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
    {
        $router = $this->getFrontController()->getRouter();
        $url    = $router->assemble($urlOptions, $name, $reset, $encode);

        $this->_redirect($url);
    }

    /**
     * Set a redirect URL string
     *
     * By default, emits a 302 HTTP status header, prepends base URL as defined
     * in request object if url is relative, and halts script execution by
     * calling exit().
     *
     * $options is an optional associative array that can be used to control
     * redirect behaviour. The available option keys are:
     * - exit: boolean flag indicating whether or not to halt script execution when done
     * - prependBase: boolean flag indicating whether or not to prepend the base URL when a relative URL is provided
     * - code: integer HTTP status code to use with redirect. Should be between 300 and 307.
     *
     * _redirect() sets the Location header in the response object. If you set
     * the exit flag to false, you can override this header later in code
     * execution.
     *
     * If the exit flag is true (true by default), _redirect() will write and
     * close the current session, if any.
     *
     * @param  string $url
     * @param  array  $options
     * @return void
     */
    public function setGotoUrl($url, array $options = array())
    {
        // prevent header injections
        $url = str_replace(array("\n", "\r"), '', $url);

        $exit        = $this->getExit();
        $prependBase = $this->getPrependBase();
        $code        = $this->getCode();
        if (null !== $options) {
            if (isset($options['exit'])) {
                $this->setExit(($options['exit']) ? true : false);
            }
            if (isset($options['prependBase'])) {
                $this->setPrependBase(($options['prependBase']) ? true : false);
            }
            if (isset($options['code'])) {
                $this->setCode($options['code']);
            }
        }

        // If relative URL, decide if we should prepend base URL
        if (!preg_match('|^[a-z]+://|', $url)) {
            $url = $this->_prependBase($url);
        }

        $this->_redirect($url);
    }

    /**
     * Perform a redirect to an action/controller/module with params
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return void
     */
    public function gotoSimple($action, $controller = null, $module = null, array $params = array())
    {
        $this->setGotoSimple($action, $controller, $module, $params);

        if ($this->getExit()) {
            $this->redirectAndExit();
        }
    }

    /**
     * Perform a redirect to an action/controller/module with params, forcing an immdiate exit
     *
     * @param  mixed $action
     * @param  mixed $controller
     * @param  mixed $module
     * @param  array $params
     * @return void
     */
    public function gotoSimpleAndExit($action, $controller = null, $module = null, array $params = array())
    {
        $this->setGotoSimple($action, $controller, $module, $params);
        $this->redirectAndExit();
    }

    /**
     * Redirect to a route-based URL
     *
     * Uses route's assemble method tobuild the URL; route is specified by $name;
     * default route is used if none provided.
     *
     * @param  array   $urlOptions Array of key/value pairs used to assemble URL
     * @param  string  $name
     * @param  boolean $reset
     * @param  boolean $encode
     * @return void
     */
    public function gotoRoute(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
    {
        $this->setGotoRoute($urlOptions, $name, $reset, $encode);

        if ($this->getExit()) {
            $this->redirectAndExit();
        }
    }

    /**
     * Redirect to a route-based URL, and immediately exit
     *
     * Uses route's assemble method tobuild the URL; route is specified by $name;
     * default route is used if none provided.
     *
     * @param  array   $urlOptions Array of key/value pairs used to assemble URL
     * @param  string  $name
     * @param  boolean $reset
     * @return void
     */
    public function gotoRouteAndExit(array $urlOptions = array(), $name = null, $reset = false)
    {
        $this->setGotoRoute($urlOptions, $name, $reset);
        $this->redirectAndExit();
    }

    /**
     * Perform a redirect to a url
     *
     * @param  string $url
     * @param  array  $options
     * @return void
     */
    public function gotoUrl($url, array $options = array())
    {
        $this->setGotoUrl($url, $options);

        if ($this->getExit()) {
            $this->redirectAndExit();
        }
    }

    /**
     * Set a URL string for a redirect, perform redirect, and immediately exit
     *
     * @param  string $url
     * @param  array  $options
     * @return void
     */
    public function gotoUrlAndExit($url, array $options = array())
    {
        $this->gotoUrl($url, $options);
        $this->redirectAndExit();
    }

    /**
     * exit(): Perform exit for redirector
     *
     * @return void
     */
    public function redirectAndExit()
    {
        // Close session, if started
        if (class_exists('Zend_Session', false) && Zend_Session::isStarted()) {
            Zend_Session::writeClose();
        } elseif (isset($_SESSION)) {
            session_write_close();
        }

        $this->getResponse()->sendHeaders();
        exit();
    }

    /**
     * direct(): Perform helper when called as
     * $this->_helper->redirector($action, $controller, $module, $params)
     *
     * @param  string $action
     * @param  string $controller
     * @param  string $module
     * @param  array  $params
     * @return void
     */
    public function direct($action, $controller = null, $module = null, array $params = array())
    {
        $this->gotoSimple($action, $controller, $module, $params);
    }

    /**
     * Overloading
     *
     * Overloading for old 'goto', 'setGoto', and 'gotoAndExit' methods
     * 
     * @param  string $method 
     * @param  array $args 
     * @return mixed
     * @throws Zend_Controller_Action_Exception for invalid methods
     */
    public function __call($method, $args)
    {
        $method = strtolower($method);
        if ('goto' == $method) {
            return call_user_func_array(array($this, 'gotoSimple'), $args);
        }
        if ('setgoto' == $method) {
            return call_user_func_array(array($this, 'setGotoSimple'), $args);
        }
        if ('gotoandexit' == $method) {
            return call_user_func_array(array($this, 'gotoSimpleAndExit'), $args);
        }

        require_once 'Zend/Controller/Action/Exception.php';
        throw new Zend_Controller_Action_Exception(sprintf('Invalid method "%s" called on redirector', $method));
    }
}
Controller/Action/Helper/ViewRenderer.php000066600000072107151256604610014456 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Controller_Action_Helper_Abstract
 */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * @see Zend_View
 */
require_once 'Zend/View.php';

/**
 * View script integration
 *
 * Zend_Controller_Action_Helper_ViewRenderer provides transparent view
 * integration for action controllers. It allows you to create a view object
 * once, and populate it throughout all actions. Several global options may be
 * set:
 *
 * - noController: if set true, render() will not look for view scripts in
 *   subdirectories named after the controller
 * - viewSuffix: what view script filename suffix to use
 *
 * The helper autoinitializes the action controller view preDispatch(). It
 * determines the path to the class file, and then determines the view base
 * directory from there. It also uses the module name as a class prefix for
 * helpers and views such that if your module name is 'Search', it will set the
 * helper class prefix to 'Search_View_Helper' and the filter class prefix to ;
 * 'Search_View_Filter'.
 *
 * Usage:
 * <code>
 * // In your bootstrap:
 * Zend_Controller_Action_HelperBroker::addHelper(new Zend_Controller_Action_Helper_ViewRenderer());
 *
 * // In your action controller methods:
 * $viewHelper = $this->_helper->getHelper('view');
 *
 * // Don't use controller subdirectories
 * $viewHelper->setNoController(true);
 *
 * // Specify a different script to render:
 * $this->_helper->view('form');
 *
 * </code>
 *
 * @uses       Zend_Controller_Action_Helper_Abstract
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Action_Helper_ViewRenderer extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Zend_View_Interface
     */
    public $view;

    /**
     * Word delimiters
     * @var array
     */
    protected $_delimiters;

    /**
     * Front controller instance
     * @var Zend_Controller_Front
     */
    protected $_frontController;

    /**
     * @var Zend_Filter_Inflector
     */
    protected $_inflector;

    /**
     * Inflector target
     * @var string
     */
    protected $_inflectorTarget = '';

    /**
     * Current module directory
     * @var string
     */
    protected $_moduleDir = '';

    /**
     * Whether or not to autorender using controller name as subdirectory;
     * global setting (not reset at next invocation)
     * @var boolean
     */
    protected $_neverController = false;

    /**
     * Whether or not to autorender postDispatch; global setting (not reset at
     * next invocation)
     * @var boolean
     */
    protected $_neverRender     = false;

    /**
     * Whether or not to use a controller name as a subdirectory when rendering
     * @var boolean
     */
    protected $_noController    = false;

    /**
     * Whether or not to autorender postDispatch; per controller/action setting (reset
     * at next invocation)
     * @var boolean
     */
    protected $_noRender        = false;

    /**
     * Characters representing path delimiters in the controller
     * @var string|array
     */
    protected $_pathDelimiters;

    /**
     * Which named segment of the response to utilize
     * @var string
     */
    protected $_responseSegment = null;

    /**
     * Which action view script to render
     * @var string
     */
    protected $_scriptAction    = null;

    /**
     * View object basePath
     * @var string
     */
    protected $_viewBasePathSpec = ':moduleDir/views';

    /**
     * View script path specification string
     * @var string
     */
    protected $_viewScriptPathSpec = ':controller/:action.:suffix';

    /**
     * View script path specification string, minus controller segment
     * @var string
     */
    protected $_viewScriptPathNoControllerSpec = ':action.:suffix';

    /**
     * View script suffix
     * @var string
     */
    protected $_viewSuffix      = 'phtml';

    /**
     * Constructor
     *
     * Optionally set view object and options.
     *
     * @param  Zend_View_Interface $view
     * @param  array               $options
     * @return void
     */
    public function __construct(Zend_View_Interface $view = null, array $options = array())
    {
        if (null !== $view) {
            $this->setView($view);
        }

        if (!empty($options)) {
            $this->_setOptions($options);
        }
    }
    
    /**
     * Clone - also make sure the view is cloned.
     *
     * @return void
     */
    public function __clone()
    {
        if (isset($this->view) && $this->view instanceof Zend_View_Interface) {
            $this->view = clone $this->view;
            
        }
    }

    /**
     * Set the view object
     *
     * @param  Zend_View_Interface $view
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
        return $this;
    }

    /**
     * Get current module name
     * 
     * @return string
     */
    public function getModule()
    {
        $request = $this->getRequest();
        $module  = $request->getModuleName();
        if (null === $module) {
            $module = $this->getFrontController()->getDispatcher()->getDefaultModule();
        }

        return $module;
    }

    /**
     * Get module directory
     *
     * @throws Zend_Controller_Action_Exception
     * @return string
     */
    public function getModuleDirectory()
    {
        $module    = $this->getModule();
        $moduleDir = $this->getFrontController()->getControllerDirectory($module);
        if ((null === $moduleDir) || is_array($moduleDir)) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception('ViewRenderer cannot locate module directory');
        }
        $this->_moduleDir = dirname($moduleDir);
        return $this->_moduleDir;
    }

    /**
     * Get inflector
     * 
     * @return Zend_Filter_Inflector
     */
    public function getInflector()
    {
        if (null === $this->_inflector) {
            /**
             * @see Zend_Filter_Inflector
             */
            require_once 'Zend/Filter/Inflector.php';
            /**
             * @see Zend_Filter_PregReplace
             */
            require_once 'Zend/Filter/PregReplace.php';
            /**
             * @see Zend_Filter_Word_UnderscoreToSeparator
             */
            require_once 'Zend/Filter/Word/UnderscoreToSeparator.php';
            $this->_inflector = new Zend_Filter_Inflector();
            $this->_inflector->setStaticRuleReference('moduleDir', $this->_moduleDir) // moduleDir must be specified before the less specific 'module'
                 ->addRules(array(
                     ':module'     => array('Word_CamelCaseToDash', 'StringToLower'),
                     ':controller' => array('Word_CamelCaseToDash', new Zend_Filter_Word_UnderscoreToSeparator('/'), 'StringToLower', new Zend_Filter_PregReplace('/\./', '-')),
                     ':action'     => array('Word_CamelCaseToDash', new Zend_Filter_PregReplace('#[^a-z0-9' . preg_quote('/', '#') . ']+#i', '-'), 'StringToLower'),
                 ))
                 ->setStaticRuleReference('suffix', $this->_viewSuffix)
                 ->setTargetReference($this->_inflectorTarget);
        }

        // Ensure that module directory is current
        $this->getModuleDirectory();

        return $this->_inflector;
    }

    /**
     * Set inflector
     * 
     * @param  Zend_Filter_Inflector $inflector 
     * @param  boolean               $reference Whether the moduleDir, target, and suffix should be set as references to ViewRenderer properties
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setInflector(Zend_Filter_Inflector $inflector, $reference = false)
    {
        $this->_inflector = $inflector;
        if ($reference) {
            $this->_inflector->setStaticRuleReference('suffix', $this->_viewSuffix)
                 ->setStaticRuleReference('moduleDir', $this->_moduleDir)
                 ->setTargetReference($this->_inflectorTarget);
        }
        return $this;
    }

    /**
     * Set inflector target
     * 
     * @param  string $target 
     * @return void
     */
    protected function _setInflectorTarget($target)
    {
        $this->_inflectorTarget = (string) $target;
    }

    /**
     * Set internal module directory representation
     * 
     * @param  string $dir 
     * @return void
     */
    protected function _setModuleDir($dir)
    {
        $this->_moduleDir = (string) $dir;
    }

    /**
     * Get internal module directory representation
     * 
     * @return string
     */
    protected function _getModuleDir()
    {
        return $this->_moduleDir;
    }

    /**
     * Generate a class prefix for helper and filter classes
     *
     * @return string
     */
    protected function _generateDefaultPrefix()
    {
        $default = 'Zend_View';
        if (null === $this->_actionController) {
            return $default;
        }

        $class = get_class($this->_actionController);

        if (!strstr($class, '_')) {
            return $default;
        }

        $module = $this->getModule();
        if ('default' == $module) {
            return $default;
        }

        $prefix = substr($class, 0, strpos($class, '_')) . '_View';

        return $prefix;
    }

    /**
     * Retrieve base path based on location of current action controller
     *
     * @return string
     */
    protected function _getBasePath()
    {
        if (null === $this->_actionController) {
            return './views';
        }

        $inflector = $this->getInflector();
        $this->_setInflectorTarget($this->getViewBasePathSpec());
        
        $dispatcher = $this->_frontController->getDispatcher();
        $request = $this->getRequest();

        $parts = array(
            'module'     => (($moduleName = $request->getModuleName()) != '') ? $dispatcher->formatModuleName($moduleName) : $moduleName,
            'controller' => $request->getControllerName(),
            'action'     => $dispatcher->formatActionName($request->getActionName())
            );

        $path = $inflector->filter($parts);
        return $path;
    }

    /**
     * Set options
     *
     * @param  array $options
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    protected function _setOptions(array $options)
    {
        foreach ($options as $key => $value)
        {
            switch ($key) {
                case 'neverRender':
                case 'neverController':
                case 'noController':
                case 'noRender':
                    $property = '_' . $key;
                    $this->{$property} = ($value) ? true : false;
                    break;
                case 'responseSegment':
                case 'scriptAction':
                case 'viewBasePathSpec':
                case 'viewScriptPathSpec':
                case 'viewScriptPathNoControllerSpec':
                case 'viewSuffix':
                    $property = '_' . $key;
                    $this->{$property} = (string) $value;
                    break;
                default:
                    break;
            }
        }

        return $this;
    }

    /**
     * Initialize the view object
     *
     * $options may contain the following keys:
     * - neverRender - flag dis/enabling postDispatch() autorender (affects all subsequent calls)
     * - noController - flag indicating whether or not to look for view scripts in subdirectories named after the controller
     * - noRender - flag indicating whether or not to autorender postDispatch()
     * - responseSegment - which named response segment to render a view script to
     * - scriptAction - what action script to render
     * - viewBasePathSpec - specification to use for determining view base path
     * - viewScriptPathSpec - specification to use for determining view script paths
     * - viewScriptPathNoControllerSpec - specification to use for determining view script paths when noController flag is set
     * - viewSuffix - what view script filename suffix to use
     *
     * @param  string $path
     * @param  string $prefix
     * @param  array  $options
     * @throws Zend_Controller_Action_Exception
     * @return void
     */
    public function initView($path = null, $prefix = null, array $options = array())
    {
        if (null === $this->view) {
            $this->setView(new Zend_View());
        }

        // Reset some flags every time
        $options['noController'] = (isset($options['noController'])) ? $options['noController'] : false;
        $options['noRender']     = (isset($options['noRender'])) ? $options['noRender'] : false;
        $this->_scriptAction     = null;
        $this->_responseSegment  = null;

        // Set options first; may be used to determine other initializations
        $this->_setOptions($options);

        // Get base view path
        if (empty($path)) {
            $path = $this->_getBasePath();
            if (empty($path)) {
                /**
                 * @see Zend_Controller_Action_Exception
                 */
                require_once 'Zend/Controller/Action/Exception.php';
                throw new Zend_Controller_Action_Exception('ViewRenderer initialization failed: retrieved view base path is empty');
            }
        }

        if (null === $prefix) {
            $prefix = $this->_generateDefaultPrefix();
        }

        // Determine if this path has already been registered
        $currentPaths = $this->view->getScriptPaths();
        $path         = str_replace(array('/', '\\'), '/', $path);
        $pathExists   = false;
        foreach ($currentPaths as $tmpPath) {
            $tmpPath = str_replace(array('/', '\\'), '/', $tmpPath);
            if (strstr($tmpPath, $path)) {
                $pathExists = true;
                break;
            }
        }
        if (!$pathExists) {
            $this->view->addBasePath($path, $prefix);
        }

        // Register view with action controller (unless already registered)
        if ((null !== $this->_actionController) && (null === $this->_actionController->view)) {
            $this->_actionController->view       = $this->view;
            $this->_actionController->viewSuffix = $this->_viewSuffix;
        }
    }

    /**
     * init - initialize view
     *
     * @return void
     */
    public function init()
    {
        if ($this->getFrontController()->getParam('noViewRenderer')) {
            return;
        }

        $this->initView();
    }

    /**
     * Set view basePath specification
     *
     * Specification can contain one or more of the following:
     * - :moduleDir - current module directory
     * - :controller - name of current controller in the request
     * - :action - name of current action in the request
     * - :module - name of current module in the request
     *
     * @param  string $path
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setViewBasePathSpec($path)
    {
        $this->_viewBasePathSpec = (string) $path;
        return $this;
    }

    /**
     * Retrieve the current view basePath specification string
     *
     * @return string
     */
    public function getViewBasePathSpec()
    {
        return $this->_viewBasePathSpec;
    }

    /**
     * Set view script path specification
     *
     * Specification can contain one or more of the following:
     * - :moduleDir - current module directory
     * - :controller - name of current controller in the request
     * - :action - name of current action in the request
     * - :module - name of current module in the request
     *
     * @param  string $path
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setViewScriptPathSpec($path)
    {
        $this->_viewScriptPathSpec = (string) $path;
        return $this;
    }

    /**
     * Retrieve the current view script path specification string
     *
     * @return string
     */
    public function getViewScriptPathSpec()
    {
        return $this->_viewScriptPathSpec;
    }

    /**
     * Set view script path specification (no controller variant)
     *
     * Specification can contain one or more of the following:
     * - :moduleDir - current module directory
     * - :controller - name of current controller in the request
     * - :action - name of current action in the request
     * - :module - name of current module in the request
     *
     * :controller will likely be ignored in this variant.
     *
     * @param  string $path
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setViewScriptPathNoControllerSpec($path)
    {
        $this->_viewScriptPathNoControllerSpec = (string) $path;
        return $this;
    }

    /**
     * Retrieve the current view script path specification string (no controller variant)
     *
     * @return string
     */
    public function getViewScriptPathNoControllerSpec()
    {
        return $this->_viewScriptPathNoControllerSpec;
    }

    /**
     * Get a view script based on an action and/or other variables
     *
     * Uses values found in current request if no values passed in $vars.
     *
     * If {@link $_noController} is set, uses {@link $_viewScriptPathNoControllerSpec};
     * otherwise, uses {@link $_viewScriptPathSpec}.
     *
     * @param  string $action
     * @param  array  $vars
     * @return string
     */
    public function getViewScript($action = null, array $vars = array())
    {
        $request = $this->getRequest();
        if ((null === $action) && (!isset($vars['action']))) {
            $action = $this->getScriptAction();
            if (null === $action) {
                $action = $request->getActionName();
            }
            $vars['action'] = $action;
        } elseif (null !== $action) {
            $vars['action'] = $action;
        }

        $inflector = $this->getInflector();
        if ($this->getNoController() || $this->getNeverController()) {
            $this->_setInflectorTarget($this->getViewScriptPathNoControllerSpec());
        } else {
            $this->_setInflectorTarget($this->getViewScriptPathSpec());
        }
        return $this->_translateSpec($vars);
    }

    /**
     * Set the neverRender flag (i.e., globally dis/enable autorendering)
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setNeverRender($flag = true)
    {
        $this->_neverRender = ($flag) ? true : false;
        return $this;
    }

    /**
     * Retrieve neverRender flag value
     *
     * @return boolean
     */
    public function getNeverRender()
    {
        return $this->_neverRender;
    }

    /**
     * Set the noRender flag (i.e., whether or not to autorender)
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setNoRender($flag = true)
    {
        $this->_noRender = ($flag) ? true : false;
        return $this;
    }

    /**
     * Retrieve noRender flag value
     *
     * @return boolean
     */
    public function getNoRender()
    {
        return $this->_noRender;
    }

    /**
     * Set the view script to use
     *
     * @param  string $name
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setScriptAction($name)
    {
        $this->_scriptAction = (string) $name;
        return $this;
    }

    /**
     * Retrieve view script name
     *
     * @return string
     */
    public function getScriptAction()
    {
        return $this->_scriptAction;
    }

    /**
     * Set the response segment name
     *
     * @param  string $name
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setResponseSegment($name)
    {
        if (null === $name) {
            $this->_responseSegment = null;
        } else {
            $this->_responseSegment = (string) $name;
        }

        return $this;
    }

    /**
     * Retrieve named response segment name
     *
     * @return string
     */
    public function getResponseSegment()
    {
        return $this->_responseSegment;
    }

    /**
     * Set the noController flag (i.e., whether or not to render into controller subdirectories)
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setNoController($flag = true)
    {
        $this->_noController = ($flag) ? true : false;
        return $this;
    }

    /**
     * Retrieve noController flag value
     *
     * @return boolean
     */
    public function getNoController()
    {
        return $this->_noController;
    }

    /**
     * Set the neverController flag (i.e., whether or not to render into controller subdirectories)
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setNeverController($flag = true)
    {
        $this->_neverController = ($flag) ? true : false;
        return $this;
    }

    /**
     * Retrieve neverController flag value
     *
     * @return boolean
     */
    public function getNeverController()
    {
        return $this->_neverController;
    }

    /**
     * Set view script suffix
     *
     * @param  string $suffix
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setViewSuffix($suffix)
    {
        $this->_viewSuffix = (string) $suffix;
        return $this;
    }

    /**
     * Get view script suffix
     *
     * @return string
     */
    public function getViewSuffix()
    {
        return $this->_viewSuffix;
    }

    /**
     * Set options for rendering a view script
     *
     * @param  string  $action       View script to render
     * @param  string  $name         Response named segment to render to
     * @param  boolean $noController Whether or not to render within a subdirectory named after the controller
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    public function setRender($action = null, $name = null, $noController = null)
    {
        if (null !== $action) {
            $this->setScriptAction($action);
        }

        if (null !== $name) {
            $this->setResponseSegment($name);
        }

        if (null !== $noController) {
            $this->setNoController($noController);
        }

        return $this;
    }

    /**
     * Inflect based on provided vars
     *
     * Allowed variables are:
     * - :moduleDir - current module directory
     * - :module - current module name
     * - :controller - current controller name
     * - :action - current action name
     * - :suffix - view script file suffix
     *
     * @param  array $vars
     * @return string
     */
    protected function _translateSpec(array $vars = array())
    {
        $inflector  = $this->getInflector();
        $request    = $this->getRequest();
        $dispatcher = $this->_frontController->getDispatcher();
        $module     = $dispatcher->formatModuleName($request->getModuleName());
        $controller = $request->getControllerName();
        $action     = $dispatcher->formatActionName($request->getActionName());

        $params     = compact('module', 'controller', 'action');
        foreach ($vars as $key => $value) {
            switch ($key) {
                case 'module':
                case 'controller':
                case 'action':
                case 'moduleDir':
                case 'suffix':
                    $params[$key] = (string) $value;
                    break;
                default:
                    break;
            }
        }

        if (isset($params['suffix'])) {
            $origSuffix = $this->getViewSuffix();
            $this->setViewSuffix($params['suffix']);
        }
        if (isset($params['moduleDir'])) {
            $origModuleDir = $this->_getModuleDir();
            $this->_setModuleDir($params['moduleDir']);
        }

        $filtered = $inflector->filter($params);

        if (isset($params['suffix'])) {
            $this->setViewSuffix($origSuffix);
        }
        if (isset($params['moduleDir'])) {
            $this->_setModuleDir($origModuleDir);
        }

        return $filtered;
    }

    /**
     * Render a view script (optionally to a named response segment)
     *
     * Sets the noRender flag to true when called.
     *
     * @param  string $script
     * @param  string $name
     * @return void
     */
    public function renderScript($script, $name = null)
    {
        if (null === $name) {
            $name = $this->getResponseSegment();
        }

        $this->getResponse()->appendBody(
            $this->view->render($script),
            $name
        );

        $this->setNoRender();
    }

    /**
     * Render a view based on path specifications
     *
     * Renders a view based on the view script path specifications.
     *
     * @param  string  $action
     * @param  string  $name
     * @param  boolean $noController
     * @return void
     */
    public function render($action = null, $name = null, $noController = null)
    {
        $this->setRender($action, $name, $noController);
        $path = $this->getViewScript();
        $this->renderScript($path, $name);
    }

    /**
     * Render a script based on specification variables
     *
     * Pass an action, and one or more specification variables (view script suffix)
     * to determine the view script path, and render that script.
     *
     * @param  string $action
     * @param  array  $vars
     * @param  string $name
     * @return void
     */
    public function renderBySpec($action = null, array $vars = array(), $name = null)
    {
        if (null !== $name) {
            $this->setResponseSegment($name);
        }

        $path = $this->getViewScript($action, $vars);

        $this->renderScript($path);
    }

    /**
     * postDispatch - auto render a view
     *
     * Only autorenders if:
     * - _noRender is false
     * - action controller is present
     * - request has not been re-dispatched (i.e., _forward() has not been called)
     * - response is not a redirect
     *
     * @return void
     */
    public function postDispatch()
    {
        if ($this->_shouldRender()) {
            $this->render();
        }
    }

    /**
     * Should the ViewRenderer render a view script?
     * 
     * @return boolean
     */
    protected function _shouldRender()
    {
        return (!$this->getFrontController()->getParam('noViewRenderer')
            && !$this->_neverRender
            && !$this->_noRender
            && (null !== $this->_actionController)
            && $this->getRequest()->isDispatched()
            && !$this->getResponse()->isRedirect()
        );
    }

    /**
     * Use this helper as a method; proxies to setRender()
     *
     * @param  string  $action
     * @param  string  $name
     * @param  boolean $noController
     * @return void
     */
    public function direct($action = null, $name = null, $noController = null)
    {
        $this->setRender($action, $name, $noController);
    }
}
Controller/Action/Helper/ContextSwitch.php000066600000123333151256604610014661 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ContextSwitch.php 12812 2008-11-24 20:46:45Z matthew $
 */

/**
 * @see Zend_Controller_Action_Helper_Abstract
 */
require_once 'Zend/Controller/Action/Helper/Abstract.php';

/**
 * Simplify context switching based on requested format
 *
 * @uses       Zend_Controller_Action_Helper_Abstract
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Action_Helper_ContextSwitch extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * Trigger type constants
     */
    const TRIGGER_INIT = 'TRIGGER_INIT';
    const TRIGGER_POST = 'TRIGGER_POST';

    /**
     * Supported contexts
     * @var array
     */
    protected $_contexts = array();

    /**
     * JSON auto-serialization flag
     * @var boolean
     */
    protected $_autoJsonSerialization = true;

    /**
     * Controller property key to utilize for context switching
     * @var string
     */
    protected $_contextKey = 'contexts';

    /**
     * Request parameter containing requested context
     * @var string
     */
    protected $_contextParam = 'format';

    /**
     * Current context
     * @var string
     */
    protected $_currentContext;

    /**
     * Default context (xml)
     * @var string
     */
    protected $_defaultContext = 'xml';

    /**
     * Whether or not to disable layouts when switching contexts
     * @var boolean
     */
    protected $_disableLayout = true;

    /**
     * Methods that require special configuration
     * @var array
     */
    protected $_specialConfig = array(
        'setSuffix',
        'setHeaders',
        'setCallbacks',
    );

    /**
     * Methods that are not configurable via setOptions and setConfig
     * @var array
     */
    protected $_unconfigurable = array(
        'setOptions',
        'setConfig',
        'setHeader',
        'setCallback',
        'setContext',
        'setActionContext',
        'setActionContexts',
    );

    /**
     * @var Zend_Controller_Action_Helper_ViewRenderer
     */
    protected $_viewRenderer;

    /**
     * Original view suffix prior to detecting context switch
     * @var string
     */
    protected $_viewSuffixOrig;

    /**
     * Constructor
     *
     * @param  array|Zend_Config $options
     * @return void
     */
    public function __construct($options = null)
    {
        if ($options instanceof Zend_Config) {
            $this->setConfig($options);
        } elseif (is_array($options)) {
            $this->setOptions($options);
        }

        if (empty($this->_contexts)) {
            $this->addContexts(array(
                'json' => array(
                    'suffix'    => 'json',
                    'headers'   => array('Content-Type' => 'application/json'),
                    'callbacks' => array(
                        'init' => 'initJsonContext',
                        'post' => 'postJsonContext'
                    )
                ),
                'xml'  => array(
                    'suffix'    => 'xml',
                    'headers'   => array('Content-Type' => 'application/xml'),
                )
            ));
        }

        $this->init();
    }

    /**
     * Initialize at start of action controller
     *
     * Reset the view script suffix to the original state, or store the 
     * original state.
     * 
     * @return void
     */
    public function init()
    {
        if (null === $this->_viewSuffixOrig) {
            $this->_viewSuffixOrig = $this->_getViewRenderer()->getViewSuffix();
        } else {
            $this->_getViewRenderer()->setViewSuffix($this->_viewSuffixOrig);
        }
    }

    /**
     * Configure object from array of options
     *
     * @param  array $options
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setOptions(array $options)
    {
        if (isset($options['contexts'])) {
            $this->setContexts($options['contexts']);
            unset($options['contexts']);
        }

        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $this->_unconfigurable)) {
                continue;
            }

            if (in_array($method, $this->_specialConfig)) {
                $method = '_' . $method;
            }

            if (method_exists($this, $method)) {
                $this->$method($value);
            }
        }
        return $this;
    }

    /**
     * Set object state from config object
     *
     * @param  Zend_Config $config
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setConfig(Zend_Config $config)
    {
        return $this->setOptions($config->toArray());
    }

    /**
     * Strategy pattern: return object
     *
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function direct()
    {
        return $this;
    }

    /**
     * Initialize context detection and switching
     *
     * @param  mixed $format
     * @throws Zend_Controller_Action_Exception
     * @return void
     */
    public function initContext($format = null)
    {
        $this->_currentContext = null;

        $controller = $this->getActionController();
        $request    = $this->getRequest();
        $action     = $request->getActionName();

        // Return if no context switching enabled, or no context switching
        // enabled for this action
        $contexts = $this->getActionContexts($action);
        if (empty($contexts)) {
            return;
        }

        // Return if no context parameter provided
        if (!$context = $request->getParam($this->getContextParam())) {
            if ($format === null) {
                return;
            }
            $context = $format;
            $format  = null;
        }

        // Check if context allowed by action controller
        if (!$this->hasActionContext($action, $context)) {
            return;
        }

        // Return if invalid context parameter provided and no format or invalid
        // format provided
        if (!$this->hasContext($context)) {
            if (empty($format) || !$this->hasContext($format)) {

                return;
            }
        }

        // Use provided format if passed
        if (!empty($format) && $this->hasContext($format)) {
            $context = $format;
        }

        $suffix = $this->getSuffix($context);

        $this->_getViewRenderer()->setViewSuffix($suffix);

        $headers = $this->getHeaders($context);
        if (!empty($headers)) {
            $response = $this->getResponse();
            foreach ($headers as $header => $content) {
                $response->setHeader($header, $content);
            }
        }

        if ($this->getAutoDisableLayout()) {
            /**
             * @see Zend_Layout
             */
            require_once 'Zend/Layout.php';
            $layout = Zend_Layout::getMvcInstance();
            if (null !== $layout) {
                $layout->disableLayout();
            }
        }

        if (null !== ($callback = $this->getCallback($context, self::TRIGGER_INIT))) {
            if (is_string($callback) && method_exists($this, $callback)) {
                $this->$callback();
            } elseif (is_string($callback) && function_exists($callback)) {
                $callback();
            } elseif (is_array($callback)) {
                call_user_func($callback);
            } else {
                /**
                 * @see Zend_Controller_Action_Exception
                 */
                require_once 'Zend/Controller/Action/Exception.php';
                throw new Zend_Controller_Action_Exception(sprintf('Invalid context callback registered for context "%s"', $context));
            }
        }

        $this->_currentContext = $context;
    }

    /**
     * JSON context extra initialization
     *
     * Turns off viewRenderer auto-rendering
     *
     * @return void
     */
    public function initJsonContext()
    {
        if (!$this->getAutoJsonSerialization()) {
            return;
        }

        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        $view = $viewRenderer->view;
        if ($view instanceof Zend_View_Interface) {
            $viewRenderer->setNoRender(true);
        }
    }

    /**
     * Should JSON contexts auto-serialize?
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setAutoJsonSerialization($flag)
    {
        $this->_autoJsonSerialization = (bool) $flag;
        return $this;
    }

    /**
     * Get JSON context auto-serialization flag
     *
     * @return boolean
     */
    public function getAutoJsonSerialization()
    {
        return $this->_autoJsonSerialization;
    }

    /**
     * Set suffix from array
     *
     * @param  array $spec
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    protected function _setSuffix(array $spec)
    {
        foreach ($spec as $context => $suffixInfo) {
            if (!is_string($context)) {
                $context = null;
            }

            if (is_string($suffixInfo)) {
                $this->setSuffix($context, $suffixInfo);
                continue;
            } elseif (is_array($suffixInfo)) {
                if (isset($suffixInfo['suffix'])) {
                    $suffix                    = $suffixInfo['suffix'];
                    $prependViewRendererSuffix = true;

                    if ((null === $context) && isset($suffixInfo['context'])) {
                        $context = $suffixInfo['context'];
                    }

                    if (isset($suffixInfo['prependViewRendererSuffix'])) {
                        $prependViewRendererSuffix = $suffixInfo['prependViewRendererSuffix'];
                    }

                    $this->setSuffix($context, $suffix, $prependViewRendererSuffix);
                    continue;
                }

                $count = count($suffixInfo);
                switch (true) {
                    case (($count < 2) && (null === $context)):
                        /**
                         * @see Zend_Controller_Action_Exception
                         */
                        require_once 'Zend/Controller/Action/Exception.php';
                        throw new Zend_Controller_Action_Exception('Invalid suffix information provided in config');
                    case ($count < 2):
                        $suffix = array_shift($suffixInfo);
                        $this->setSuffix($context, $suffix);
                        break;
                    case (($count < 3) && (null === $context)):
                        $context = array_shift($suffixInfo);
                        $suffix  = array_shift($suffixInfo);
                        $this->setSuffix($context, $suffix);
                        break;
                    case (($count == 3) && (null === $context)):
                        $context = array_shift($suffixInfo);
                        $suffix  = array_shift($suffixInfo);
                        $prependViewRendererSuffix = array_shift($suffixInfo);
                        $this->setSuffix($context, $suffix, $prependViewRendererSuffix);
                        break;
                    case ($count >= 2):
                        $suffix  = array_shift($suffixInfo);
                        $prependViewRendererSuffix = array_shift($suffixInfo);
                        $this->setSuffix($context, $suffix, $prependViewRendererSuffix);
                        break;
                }
            }
        }
        return $this;
    }

    /**
     * Customize view script suffix to use when switching context.
     *
     * Passing an empty suffix value to the setters disables the view script
     * suffix change.
     *
     * @param  string  $context                   Context type for which to set suffix
     * @param  string  $suffix                    Suffix to use
     * @param  boolean $prependViewRendererSuffix Whether or not to prepend the new suffix to the viewrenderer suffix
     * @throws Zend_Controller_Action_Exception
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setSuffix($context, $suffix, $prependViewRendererSuffix = true)
    {
        if (!isset($this->_contexts[$context])) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception(sprintf('Cannot set suffix; invalid context type "%s"', $context));
        }

        if (empty($suffix)) {
            $suffix = '';
        }

        if (is_array($suffix)) {
            if (isset($suffix['prependViewRendererSuffix'])) {
                $prependViewRendererSuffix = $suffix['prependViewRendererSuffix'];
            }
            if (isset($suffix['suffix'])) {
                $suffix = $suffix['suffix'];
            } else {
                $suffix = '';
            }
        }

        $suffix = (string) $suffix;

        if ($prependViewRendererSuffix) {
            if (empty($suffix)) {
                $suffix = $this->_getViewRenderer()->getViewSuffix();
            } else {
                $suffix .= '.' . $this->_getViewRenderer()->getViewSuffix();
            }
        }

        $this->_contexts[$context]['suffix'] = $suffix;
        return $this;
    }

    /**
     * Retrieve suffix for given context type
     *
     * @param  string $type Context type
     * @throws Zend_Controller_Action_Exception
     * @return string
     */
    public function getSuffix($type)
    {
        if (!isset($this->_contexts[$type])) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception(sprintf('Cannot retrieve suffix; invalid context type "%s"', $type));
        }

        return $this->_contexts[$type]['suffix'];
    }

    /**
     * Does the given context exist?
     *
     * @param  string  $context
     * @param  boolean $throwException
     * @throws Zend_Controller_Action_Exception if context does not exist and throwException is true
     * @return bool
     */
    public function hasContext($context, $throwException = false)
    {
        if (is_string($context)) {
            if (isset($this->_contexts[$context])) {
                return true;
            }
        } elseif (is_array($context)) {
            $error = false;
            foreach ($context as $test) {
                if (!isset($this->_contexts[$test])) {
                    $error = (string) $test;
                    break;
                }
            }
            if (false === $error) {
                return true;
            }
            $context = $error;
        } elseif (true === $context) {
            return true;
        }

        if ($throwException) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception(sprintf('Context "%s" does not exist', $context));
        }

        return false;
    }

    /**
     * Add header to context
     *
     * @param  string $context
     * @param  string $header
     * @param  string $content
     * @throws Zend_Controller_Action_Exception
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function addHeader($context, $header, $content)
    {
        $context = (string) $context;
        $this->hasContext($context, true);

        $header  = (string) $header;
        $content = (string) $content;

        if (isset($this->_contexts[$context]['headers'][$header])) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception(sprintf('Cannot add "%s" header to context "%s": already exists', $header, $context));
        }

        $this->_contexts[$context]['headers'][$header] = $content;
        return $this;
    }

    /**
     * Customize response header to use when switching context
     *
     * Passing an empty header value to the setters disables the response
     * header.
     *
     * @param  string $type   Context type for which to set suffix
     * @param  string $header Header to set
     * @param  string $content Header content
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setHeader($context, $header, $content)
    {
        $this->hasContext($context, true);
        $context = (string) $context;
        $header  = (string) $header;
        $content = (string) $content;

        $this->_contexts[$context]['headers'][$header] = $content;
        return $this;
    }

    /**
     * Add multiple headers at once for a given context
     *
     * @param  string $context
     * @param  array  $headers
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function addHeaders($context, array $headers)
    {
        foreach ($headers as $header => $content) {
            $this->addHeader($context, $header, $content);
        }

        return $this;
    }

    /**
     * Set headers from context => headers pairs
     *
     * @param  array $options
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    protected function _setHeaders(array $options)
    {
        foreach ($options as $context => $headers) {
            if (!is_array($headers)) {
                continue;
            }
            $this->setHeaders($context, $headers);
        }

        return $this;
    }

    /**
     * Set multiple headers at once for a given context
     *
     * @param  string $context
     * @param  array  $headers
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setHeaders($context, array $headers)
    {
        $this->clearHeaders($context);
        foreach ($headers as $header => $content) {
            $this->setHeader($context, $header, $content);
        }

        return $this;
    }

    /**
     * Retrieve context header
     *
     * Returns the value of a given header for a given context type
     *
     * @param  string $context
     * @param  string $header
     * @return string|null
     */
    public function getHeader($context, $header)
    {
        $this->hasContext($context, true);
        $context = (string) $context;
        $header  = (string) $header;
        if (isset($this->_contexts[$context]['headers'][$header])) {
            return $this->_contexts[$context]['headers'][$header];
        }

        return null;
    }

    /**
     * Retrieve context headers
     *
     * Returns all headers for a context as key/value pairs
     *
     * @param  string $context
     * @return array
     */
    public function getHeaders($context)
    {
        $this->hasContext($context, true);
        $context = (string) $context;
        return $this->_contexts[$context]['headers'];
    }

    /**
     * Remove a single header from a context
     *
     * @param  string $context
     * @param  string $header
     * @return boolean
     */
    public function removeHeader($context, $header)
    {
        $this->hasContext($context, true);
        $context = (string) $context;
        $header  = (string) $header;
        if (isset($this->_contexts[$context]['headers'][$header])) {
            unset($this->_contexts[$context]['headers'][$header]);
            return true;
        }

        return false;
    }

    /**
     * Clear all headers for a given context
     *
     * @param  string $context
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function clearHeaders($context)
    {
        $this->hasContext($context, true);
        $context = (string) $context;
        $this->_contexts[$context]['headers'] = array();
        return $this;
    }

    /**
     * Validate trigger and return in normalized form
     *
     * @param  string $trigger
     * @throws Zend_Controller_Action_Exception
     * @return string
     */
    protected function _validateTrigger($trigger)
    {
        $trigger = strtoupper($trigger);
        if ('TRIGGER_' !== substr($trigger, 0, 8)) {
            $trigger = 'TRIGGER_' . $trigger;
        }

        if (!in_array($trigger, array(self::TRIGGER_INIT, self::TRIGGER_POST))) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception(sprintf('Invalid trigger "%s"', $trigger));
        }

        return $trigger;
    }

    /**
     * Set a callback for a given context and trigger
     *
     * @param  string       $context
     * @param  string       $trigger
     * @param  string|array $callback
     * @throws Zend_Controller_Action_Exception
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setCallback($context, $trigger, $callback)
    {
        $this->hasContext($context, true);
        $trigger = $this->_validateTrigger($trigger);

        if (!is_string($callback)) {
            if (!is_array($callback) || (2 != count($callback))) {
                /**
                 * @see Zend_Controller_Action_Exception
                 */
                require_once 'Zend/Controller/Action/Exception.php';
                throw new Zend_Controller_Action_Exception('Invalid callback specified');
            }
        }

        $this->_contexts[$context]['callbacks'][$trigger] = $callback;
        return $this;
    }

    /**
     * Set callbacks from array of context => callbacks pairs
     *
     * @param  array $options
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    protected function _setCallbacks(array $options)
    {
        foreach ($options as $context => $callbacks) {
            if (!is_array($callbacks)) {
                continue;
            }

            $this->setCallbacks($context, $callbacks);
        }
        return $this;
    }

    /**
     * Set callbacks for a given context
     *
     * Callbacks should be in trigger/callback pairs.
     *
     * @param  string $context
     * @param  array  $callbacks
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setCallbacks($context, array $callbacks)
    {
        $this->hasContext($context, true);
        $context = (string) $context;
        if (!isset($this->_contexts[$context]['callbacks'])) {
            $this->_contexts[$context]['callbacks'] = array();
        }

        foreach ($callbacks as $trigger => $callback) {
            $this->setCallback($context, $trigger, $callback);
        }
        return $this;
    }

    /**
     * Get a single callback for a given context and trigger
     *
     * @param  string $context
     * @param  string $trigger
     * @return string|array|null
     */
    public function getCallback($context, $trigger)
    {
        $this->hasContext($context, true);
        $trigger = $this->_validateTrigger($trigger);
        if (isset($this->_contexts[$context]['callbacks'][$trigger])) {
            return $this->_contexts[$context]['callbacks'][$trigger];
        }

        return null;
    }

    /**
     * Get all callbacks for a given context
     *
     * @param  string $context
     * @return array
     */
    public function getCallbacks($context)
    {
        $this->hasContext($context, true);
        return $this->_contexts[$context]['callbacks'];
    }

    /**
     * Clear a callback for a given context and trigger
     *
     * @param  string $context
     * @param  string $trigger
     * @return boolean
     */
    public function removeCallback($context, $trigger)
    {
        $this->hasContext($context, true);
        $trigger = $this->_validateTrigger($trigger);
        if (isset($this->_contexts[$context]['callbacks'][$trigger])) {
            unset($this->_contexts[$context]['callbacks'][$trigger]);
            return true;
        }

        return false;
    }

    /**
     * Clear all callbacks for a given context
     *
     * @param  string $context
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function clearCallbacks($context)
    {
        $this->hasContext($context, true);
        $this->_contexts[$context]['callbacks'] = array();
        return $this;
    }

    /**
     * Set name of parameter to use when determining context format
     *
     * @param  string $name
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setContextParam($name)
    {
        $this->_contextParam = (string) $name;
        return $this;
    }

    /**
     * Return context format request parameter name
     *
     * @return string
     */
    public function getContextParam()
    {
        return $this->_contextParam;
    }

    /**
     * Indicate default context to use when no context format provided
     *
     * @param  string $type
     * @throws Zend_Controller_Action_Exception
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setDefaultContext($type)
    {
        if (!isset($this->_contexts[$type])) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception(sprintf('Cannot set default context; invalid context type "%s"', $type));
        }

        $this->_defaultContext = $type;
        return $this;
    }

    /**
     * Return default context
     *
     * @return string
     */
    public function getDefaultContext()
    {
        return $this->_defaultContext;
    }

    /**
     * Set flag indicating if layout should be disabled
     *
     * @param  boolean $flag
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setAutoDisableLayout($flag)
    {
        $this->_disableLayout = ($flag) ? true : false;
        return $this;
    }

    /**
     * Retrieve auto layout disable flag
     *
     * @return boolean
     */
    public function getAutoDisableLayout()
    {
        return $this->_disableLayout;
    }

    /**
     * Add new context
     *
     * @param  string $context Context type
     * @param  array  $spec    Context specification
     * @throws Zend_Controller_Action_Exception
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function addContext($context, array $spec)
    {
        if ($this->hasContext($context)) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception(sprintf('Cannot add context "%s"; already exists', $context));
        }
        $context = (string) $context;

        $this->_contexts[$context] = array();

        $this->setSuffix($context,    (isset($spec['suffix'])    ? $spec['suffix']    : ''))
             ->setHeaders($context,   (isset($spec['headers'])   ? $spec['headers']   : array()))
             ->setCallbacks($context, (isset($spec['callbacks']) ? $spec['callbacks'] : array()));
        return $this;
    }

    /**
     * Overwrite existing context
     *
     * @param  string $context Context type
     * @param  array  $spec    Context specification
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setContext($context, array $spec)
    {
        $this->removeContext($context);
        return $this->addContext($context, $spec);
    }

    /**
     * Add multiple contexts
     *
     * @param  array $contexts
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function addContexts(array $contexts)
    {
        foreach ($contexts as $context => $spec) {
            $this->addContext($context, $spec);
        }
        return $this;
    }

    /**
     * Set multiple contexts, after first removing all
     *
     * @param  array $contexts
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setContexts(array $contexts)
    {
        $this->clearContexts();
        foreach ($contexts as $context => $spec) {
            $this->addContext($context, $spec);
        }
        return $this;
    }

    /**
     * Retrieve context specification
     *
     * @param  string $context
     * @return array|null
     */
    public function getContext($context)
    {
        if ($this->hasContext($context)) {
            return $this->_contexts[(string) $context];
        }
        return null;
    }

    /**
     * Retrieve context definitions
     *
     * @return array
     */
    public function getContexts()
    {
        return $this->_contexts;
    }

    /**
     * Remove a context
     *
     * @param  string $context
     * @return boolean
     */
    public function removeContext($context)
    {
        if ($this->hasContext($context)) {
            unset($this->_contexts[(string) $context]);
            return true;
        }
        return false;
    }

    /**
     * Remove all contexts
     *
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function clearContexts()
    {
        $this->_contexts = array();
        return $this;
    }

    /**
     * Return current context, if any
     *
     * @return null|string
     */
    public function getCurrentContext()
    {
        return $this->_currentContext;
    }

    /**
     * Post dispatch processing
     *
     * Execute postDispatch callback for current context, if available
     *
     * @throws Zend_Controller_Action_Exception
     * @return void
     */
    public function postDispatch()
    {
        $context = $this->getCurrentContext();
        if (null !== $context) {
            if (null !== ($callback = $this->getCallback($context, self::TRIGGER_POST))) {
                if (is_string($callback) && method_exists($this, $callback)) {
                    $this->$callback();
                } elseif (is_string($callback) && function_exists($callback)) {
                    $callback();
                } elseif (is_array($callback)) {
                    call_user_func($callback);
                } else {
                    /**
                     * @see Zend_Controller_Action_Exception
                     */
                    require_once 'Zend/Controller/Action/Exception.php';
                    throw new Zend_Controller_Action_Exception(sprintf('Invalid postDispatch context callback registered for context "%s"', $context));
                }
            }
        }
    }

    /**
     * JSON post processing
     *
     * JSON serialize view variables to response body
     *
     * @return void
     */
    public function postJsonContext()
    {
        if (!$this->getAutoJsonSerialization()) {
            return;
        }

        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        $view = $viewRenderer->view;
        if ($view instanceof Zend_View_Interface) {
            /**
             * @see Zend_Json
             */
            if(method_exists($view, 'getVars')) {
                require_once 'Zend/Json.php';
                $vars = Zend_Json::encode($view->getVars());
                $this->getResponse()->setBody($vars);
            } else {
                require_once 'Zend/Controller/Action/Exception.php';
                throw new Zend_Controller_Action_Exception('View does not implement the getVars() method needed to encode the view into JSON');
            }
        }
    }

    /**
     * Add one or more contexts to an action
     *
     * @param  string       $action
     * @param  string|array $context
     * @return Zend_Controller_Action_Helper_ContextSwitch|void Provides a fluent interface
     */
    public function addActionContext($action, $context)
    {
        $this->hasContext($context, true);
        $controller = $this->getActionController();
        if (null === $controller) {
            return;
        }
        $action     = (string) $action;
        $contextKey = $this->_contextKey;

        if (!isset($controller->$contextKey)) {
            $controller->$contextKey = array();
        }

        if (true === $context) {
            $contexts = $this->getContexts();
            $controller->{$contextKey}[$action] = array_keys($contexts);
            return $this;
        }

        $context = (array) $context;
        if (!isset($controller->{$contextKey}[$action])) {
            $controller->{$contextKey}[$action] = $context;
        } else {
            $controller->{$contextKey}[$action] = array_merge(
                $controller->{$contextKey}[$action],
                $context
            );
        }

        return $this;
    }

    /**
     * Set a context as available for a given controller action
     *
     * @param  string       $action
     * @param  string|array $context
     * @return Zend_Controller_Action_Helper_ContextSwitch|void Provides a fluent interface
     */
    public function setActionContext($action, $context)
    {
        $this->hasContext($context, true);
        $controller = $this->getActionController();
        if (null === $controller) {
            return;
        }
        $action     = (string) $action;
        $contextKey = $this->_contextKey;

        if (!isset($controller->$contextKey)) {
            $controller->$contextKey = array();
        }

        if (true === $context) {
            $contexts = $this->getContexts();
            $controller->{$contextKey}[$action] = array_keys($contexts);
        } else {
            $controller->{$contextKey}[$action] = (array) $context;
        }

        return $this;
    }

    /**
     * Add multiple action/context pairs at once
     *
     * @param  array $contexts
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function addActionContexts(array $contexts)
    {
        foreach ($contexts as $action => $context) {
            $this->addActionContext($action, $context);
        }
        return $this;
    }

    /**
     * Overwrite and set multiple action contexts at once
     *
     * @param  array $contexts
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function setActionContexts(array $contexts)
    {
        foreach ($contexts as $action => $context) {
            $this->setActionContext($action, $context);
        }
        return $this;
    }

    /**
     * Does a particular controller action have the given context(s)?
     *
     * @param  string       $action
     * @param  string|array $context
     * @throws Zend_Controller_Action_Exception
     * @return boolean
     */
    public function hasActionContext($action, $context)
    {
        $this->hasContext($context, true);
        $controller = $this->getActionController();
        if (null === $controller) {
            return false;
        }
        $action     = (string) $action;
        $contextKey = $this->_contextKey;

        if (!isset($controller->{$contextKey})) {
            return false;
        }

        $allContexts = $controller->{$contextKey};

        if (!is_array($allContexts)) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception("Invalid contexts found for controller");
        }

        if (!isset($allContexts[$action])) {
            return false;
        }

        if (true === $allContexts[$action]) {
            return true;
        }

        $contexts = $allContexts[$action];

        if (!is_array($contexts)) {
            /**
             * @see Zend_Controller_Action_Exception
             */
            require_once 'Zend/Controller/Action/Exception.php';
            throw new Zend_Controller_Action_Exception(sprintf("Invalid contexts found for action '%s'", $action));
        }

        if (is_string($context) && in_array($context, $contexts)) {
            return true;
        } elseif (is_array($context)) {
            $found = true;
            foreach ($context as $test) {
                if (!in_array($test, $contexts)) {
                    $found = false;
                    break;
                }
            }
            return $found;
        }

        return false;
    }

    /**
     * Get contexts for a given action or all actions in the controller
     *
     * @param  string $action
     * @return array
     */
    public function getActionContexts($action = null)
    {
        $controller = $this->getActionController();
        if (null === $controller) {
            return array();
        }
        $action     = (string) $action;
        $contextKey = $this->_contextKey;

        if (!isset($controller->$contextKey)) {
            return array();
        }

        if (null !== $action) {
            if (isset($controller->{$contextKey}[$action])) {
                return $controller->{$contextKey}[$action];
            } else {
                return array();
            }
        }

        return $controller->$contextKey;
    }

    /**
     * Remove one or more contexts for a given controller action
     *
     * @param  string       $action
     * @param  string|array $context
     * @return boolean
     */
    public function removeActionContext($action, $context)
    {
        if ($this->hasActionContext($action, $context)) {
            $controller     = $this->getActionController();
            $contextKey     = $this->_contextKey;
            $action         = (string) $action;
            $contexts       = $controller->$contextKey;
            $actionContexts = $contexts[$action];
            $contexts       = (array) $context;
            foreach ($contexts as $context) {
                $index = array_search($context, $actionContexts);
                if (false !== $index) {
                    unset($controller->{$contextKey}[$action][$index]);
                }
            }
            return true;
        }
        return false;
    }

    /**
     * Clear all contexts for a given controller action or all actions
     *
     * @param  string $action
     * @return Zend_Controller_Action_Helper_ContextSwitch Provides a fluent interface
     */
    public function clearActionContexts($action = null)
    {
        $controller = $this->getActionController();
        $contextKey = $this->_contextKey;

        if (!isset($controller->$contextKey) || empty($controller->$contextKey)) {
            return $this;
        }

        if (null === $action) {
            $controller->$contextKey = array();
            return $this;
        }

        $action = (string) $action;
        if (isset($controller->{$contextKey}[$action])) {
            unset($controller->{$contextKey}[$action]);
        }

        return $this;
    }

    /**
     * Retrieve ViewRenderer
     *
     * @return Zend_Controller_Action_Helper_ViewRenderer Provides a fluent interface
     */
    protected function _getViewRenderer()
    {
        if (null === $this->_viewRenderer) {
            $this->_viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        }

        return $this->_viewRenderer;
    }
}

Controller/Router/Route/Regex.php000066600000017777151256604610013065 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Regex.php 12525 2008-11-10 20:18:32Z ralph $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Controller_Router_Route_Abstract */
require_once 'Zend/Controller/Router/Route/Abstract.php';

/**
 * Regex Route
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Router_Route_Regex extends Zend_Controller_Router_Route_Abstract
{
    protected $_regex = null;
    protected $_defaults = array();
    protected $_reverse = null;
    protected $_map = array();
    protected $_values = array();

    /**
     * Instantiates route based on passed Zend_Config structure
     *
     * @param Zend_Config $config Configuration object
     */
    public static function getInstance(Zend_Config $config)
    {
        $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
        $map = ($config->map instanceof Zend_Config) ? $config->map->toArray() : array();
        $reverse = (isset($config->reverse)) ? $config->reverse : null;
        return new self($config->route, $defs, $map, $reverse);
    }

    public function __construct($route, $defaults = array(), $map = array(), $reverse = null)
    {
        $this->_regex = '#^' . $route . '$#i';
        $this->_defaults = (array) $defaults;
        $this->_map = (array) $map;
        $this->_reverse = $reverse;
    }

    public function getVersion() {
        return 1;
    }
    
    /**
     * Matches a user submitted path with a previously defined route.
     * Assigns and returns an array of defaults on a successful match.
     *
     * @param string $path Path used to match against this routing map
     * @return array|false An array of assigned values or a false on a mismatch
     */
    public function match($path)
    {
        $path = trim(urldecode($path), '/');
        $res = preg_match($this->_regex, $path, $values);

        if ($res === 0) return false;

        // array_filter_key()? Why isn't this in a standard PHP function set yet? :)
        foreach ($values as $i => $value) {
            if (!is_int($i) || $i === 0) {
                unset($values[$i]);
            }
        }

        $this->_values = $values;

        $values = $this->_getMappedValues($values);
        $defaults = $this->_getMappedValues($this->_defaults, false, true);

        $return = $values + $defaults;

        return $return;
    }

    /**
     * Maps numerically indexed array values to it's associative mapped counterpart.
     * Or vice versa. Uses user provided map array which consists of index => name
     * parameter mapping. If map is not found, it returns original array.
     *
     * Method strips destination type of keys form source array. Ie. if source array is
     * indexed numerically then every associative key will be stripped. Vice versa if reversed
     * is set to true.
     *
     * @param array $values Indexed or associative array of values to map
     * @param boolean $reversed False means translation of index to association. True means reverse.
     * @param boolean $preserve Should wrong type of keys be preserved or stripped.
     * @return array An array of mapped values
     */
    protected function _getMappedValues($values, $reversed = false, $preserve = false)
    {
        if (count($this->_map) == 0) {
            return $values;
        }

        $return = array();

        foreach ($values as $key => $value) {
            if (is_int($key) && !$reversed) {
                if (array_key_exists($key, $this->_map)) {
                    $index = $this->_map[$key];
                } elseif (false === ($index = array_search($key, $this->_map))) {
                    $index = $key;
                }
                $return[$index] = $values[$key];
            } elseif ($reversed) {
                $index = (!is_int($key)) ? array_search($key, $this->_map, true) : $key;
                if (false !== $index) {
                    $return[$index] = $values[$key];
                }
            } elseif ($preserve) {
                $return[$key] = $value;
            }
        }

        return $return;
    }

    /**
     * Assembles a URL path defined by this route
     *
     * @param array $data An array of name (or index) and value pairs used as parameters
     * @return string Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = false)
    {
        if ($this->_reverse === null) {
            require_once 'Zend/Controller/Router/Exception.php';
            throw new Zend_Controller_Router_Exception('Cannot assemble. Reversed route is not specified.');
        }

        $defaultValuesMapped  = $this->_getMappedValues($this->_defaults, true, false);
        $matchedValuesMapped  = $this->_getMappedValues($this->_values, true, false);
        $dataValuesMapped     = $this->_getMappedValues($data, true, false);

        // handle resets, if so requested (By null value) to do so
        if (($resetKeys = array_search(null, $dataValuesMapped, true)) !== false) {
            foreach ((array) $resetKeys as $resetKey) {
                if (isset($matchedValuesMapped[$resetKey])) {
                    unset($matchedValuesMapped[$resetKey]);
                    unset($dataValuesMapped[$resetKey]);
                }
            }
        }

        // merge all the data together, first defaults, then values matched, then supplied
        $mergedData = $defaultValuesMapped;
        $mergedData = $this->_arrayMergeNumericKeys($mergedData, $matchedValuesMapped);
        $mergedData = $this->_arrayMergeNumericKeys($mergedData, $dataValuesMapped);

        if ($encode) {
            foreach ($mergedData as $key => &$value) {
                $value = urlencode($value);
            }
        }	

        ksort($mergedData);

        $return = @vsprintf($this->_reverse, $mergedData);

        if ($return === false) {
            require_once 'Zend/Controller/Router/Exception.php';
            throw new Zend_Controller_Router_Exception('Cannot assemble. Too few arguments?');
        }

        return $return;

    }

    /**
     * Return a single parameter of route's defaults
     *
     * @param string $name Array key of the parameter
     * @return string Previously set default
     */
    public function getDefault($name) {
        if (isset($this->_defaults[$name])) {
            return $this->_defaults[$name];
        }
    }

    /**
     * Return an array of defaults
     *
     * @return array Route defaults
     */
    public function getDefaults() {
        return $this->_defaults;
    }

    /**
     * _arrayMergeNumericKeys() - allows for a strict key (numeric's included) array_merge.
     * php's array_merge() lacks the ability to merge with numeric keys.
     *
     * @param array $array1
     * @param array $array2
     * @return array
     */
    protected function _arrayMergeNumericKeys(Array $array1, Array $array2)
    {
        $returnArray = $array1;
        foreach ($array2 as $array2Index => $array2Value) {
            $returnArray[$array2Index] = $array2Value;
        }
        return $returnArray;
    }


}
Controller/Router/Route/Interface.php000066600000002423151256604610013671 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Interface.php 10607 2008-08-02 12:53:16Z martel $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Config */
require_once 'Zend/Config.php';

/**
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_Controller_Router_Route_Interface {
    public function match($path);
    public function assemble($data = array(), $reset = false, $encode = false);
    public static function getInstance(Zend_Config $config);
}

Controller/Router/Route/Chain.php000066600000010111151256604610013004 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Route.php 1847 2006-11-23 11:36:41Z martel $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Controller_Router_Route_Abstract */
require_once 'Zend/Controller/Router/Route/Abstract.php';

/**
 * Chain route is used for managing route chaining.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Router_Route_Chain extends Zend_Controller_Router_Route_Abstract
{

    protected $_routes = array();
    protected $_separators = array();

    /**
     * Instantiates route based on passed Zend_Config structure
     *
     * @param Zend_Config $config Configuration object
     */
    public static function getInstance(Zend_Config $config)
    { }

    public function chain(Zend_Controller_Router_Route_Interface $route, $separator = '/') {

        $this->_routes[] = $route;
        $this->_separators[] = $separator;

        return $this;

    }

    /**
     * Matches a user submitted path with a previously defined route.
     * Assigns and returns an array of defaults on a successful match.
     *
     * @param Zend_Controller_Request_Http $request Request to get the path info from
     * @return array|false An array of assigned values or a false on a mismatch
     */
    public function match($request, $partial = null)
    {

        $path = $request->getPathInfo();
        
        $values = array();

        foreach ($this->_routes as $key => $route) {
            
            // TODO: Should be an interface method. Hack for 1.0 BC  
            if (!method_exists($route, 'getVersion') || $route->getVersion() == 1) {
                $match = $request->getPathInfo();
            } else {
                $match = $request;
            }
            
            $res = $route->match($match);
            if ($res === false) return false;

            $values = $res + $values;

        }

        return $values;
    }

    /**
     * Assembles a URL path defined by this route
     *
     * @param array $data An array of variable and value pairs used as parameters
     * @return string Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = false)
    {
        $value = '';

        foreach ($this->_routes as $key => $route) {
            if ($key > 0) {
                $value .= $this->_separators[$key];
            }
            
            $value .= $route->assemble($data, $reset, $encode);
            
            if (method_exists($route, 'getVariables')) {
                $variables = $route->getVariables();
                
                foreach ($variables as $variable) {
                    $data[$variable] = null;
                }
            }
        }

        return $value;
    }

    /**
     * Set the request object for this and the child routes
     * 
     * @param  Zend_Controller_Request_Abstract|null $request
     * @return void
     */
    public function setRequest(Zend_Controller_Request_Abstract $request = null)
    {
        $this->_request = $request;

        foreach ($this->_routes as $route) {
            if (method_exists($route, 'setRequest')) {
                $route->setRequest($request);
            }
        }
    }

}
Controller/Router/Route/Static.php000066600000007053151256604610013224 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Route.php 1847 2006-11-23 11:36:41Z martel $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Controller_Router_Route_Abstract */
require_once 'Zend/Controller/Router/Route/Abstract.php';

/**
 * StaticRoute is used for managing static URIs.
 *
 * It's a lot faster compared to the standard Route implementation.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Router_Route_Static extends Zend_Controller_Router_Route_Abstract
{

    protected $_route = null;
    protected $_defaults = array();

    public function getVersion() {
        return 1;
    }
    
    /**
     * Instantiates route based on passed Zend_Config structure
     *
     * @param Zend_Config $config Configuration object
     */
    public static function getInstance(Zend_Config $config)
    {
        $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
        return new self($config->route, $defs);
    }

    /**
     * Prepares the route for mapping.
     *
     * @param string $route Map used to match with later submitted URL path
     * @param array $defaults Defaults for map variables with keys as variable names
     */
    public function __construct($route, $defaults = array())
    {
        $this->_route = trim($route, '/');
        $this->_defaults = (array) $defaults;
    }

    /**
     * Matches a user submitted path with a previously defined route.
     * Assigns and returns an array of defaults on a successful match.
     *
     * @param string $path Path used to match against this routing map
     * @return array|false An array of assigned values or a false on a mismatch
     */
    public function match($path)
    {
        if (trim($path, '/') == $this->_route) {
            return $this->_defaults;
        }
        return false;
    }

    /**
     * Assembles a URL path defined by this route
     *
     * @param array $data An array of variable and value pairs used as parameters
     * @return string Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = false)
    {
        return $this->_route;
    }

    /**
     * Return a single parameter of route's defaults
     *
     * @param string $name Array key of the parameter
     * @return string Previously set default
     */
    public function getDefault($name) {
        if (isset($this->_defaults[$name])) {
            return $this->_defaults[$name];
        }
        return null;
    }

    /**
     * Return an array of defaults
     *
     * @return array Route defaults
     */
    public function getDefaults() {
        return $this->_defaults;
    }

}
Controller/Router/Route/Module.php000066600000021132151256604610013214 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Module.php 12310 2008-11-05 20:49:16Z dasprid $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Controller_Router_Route_Abstract */
require_once 'Zend/Controller/Router/Route/Abstract.php';

/**
 * Module Route
 *
 * Default route for module functionality
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @see        http://manuals.rubyonrails.com/read/chapter/65
 */
class Zend_Controller_Router_Route_Module extends Zend_Controller_Router_Route_Abstract
{
    /**
     * URI delimiter
     */
    const URI_DELIMITER = '/';

    /**
     * Default values for the route (ie. module, controller, action, params)
     * @var array
     */
    protected $_defaults;

    protected $_values      = array();
    protected $_moduleValid = false;
    protected $_keysSet     = false;

    /**#@+
     * Array keys to use for module, controller, and action. Should be taken out of request.
     * @var string
     */
    protected $_moduleKey     = 'module';
    protected $_controllerKey = 'controller';
    protected $_actionKey     = 'action';
    /**#@-*/

    /**
     * @var Zend_Controller_Dispatcher_Interface
     */
    protected $_dispatcher;

    /**
     * @var Zend_Controller_Request_Abstract
     */
    protected $_request;

    public function getVersion() {
        return 1;
    }

    /**
     * Instantiates route based on passed Zend_Config structure
     */
    public static function getInstance(Zend_Config $config)
    {
        $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
        return new self($defs);
    }

    /**
     * Constructor
     *
     * @param array $defaults Defaults for map variables with keys as variable names
     * @param Zend_Controller_Dispatcher_Interface $dispatcher Dispatcher object
     * @param Zend_Controller_Request_Abstract $request Request object
     */
    public function __construct(array $defaults = array(),
                Zend_Controller_Dispatcher_Interface $dispatcher = null,
                Zend_Controller_Request_Abstract $request = null)
    {
        $this->_defaults = $defaults;

        if (isset($request)) {
            $this->_request = $request;
        }

        if (isset($dispatcher)) {
            $this->_dispatcher = $dispatcher;
        }
    }

    /**
     * Set request keys based on values in request object
     *
     * @return void
     */
    protected function _setRequestKeys()
    {
        if (null !== $this->_request) {
            $this->_moduleKey     = $this->_request->getModuleKey();
            $this->_controllerKey = $this->_request->getControllerKey();
            $this->_actionKey     = $this->_request->getActionKey();
        }

        if (null !== $this->_dispatcher) {
            $this->_defaults += array(
                $this->_controllerKey => $this->_dispatcher->getDefaultControllerName(),
                $this->_actionKey     => $this->_dispatcher->getDefaultAction(),
                $this->_moduleKey     => $this->_dispatcher->getDefaultModule()
            );
        }

        $this->_keysSet = true;
    }

    /**
     * Matches a user submitted path. Assigns and returns an array of variables
     * on a successful match.
     *
     * If a request object is registered, it uses its setModuleName(),
     * setControllerName(), and setActionName() accessors to set those values.
     * Always returns the values as an array.
     *
     * @param string $path Path used to match against this routing map
     * @return array An array of assigned values or a false on a mismatch
     */
    public function match($path)
    {
        $this->_setRequestKeys();

        $values = array();
        $params = array();
        $path   = trim($path, self::URI_DELIMITER);

        if ($path != '') {

            $path = explode(self::URI_DELIMITER, $path);

            if ($this->_dispatcher && $this->_dispatcher->isValidModule($path[0])) {
                $values[$this->_moduleKey] = array_shift($path);
                $this->_moduleValid = true;
            }

            if (count($path) && !empty($path[0])) {
                $values[$this->_controllerKey] = array_shift($path);
            }

            if (count($path) && !empty($path[0])) {
                $values[$this->_actionKey] = array_shift($path);
            }

            if ($numSegs = count($path)) {
                for ($i = 0; $i < $numSegs; $i = $i + 2) {
                    $key = urldecode($path[$i]);
                    $val = isset($path[$i + 1]) ? urldecode($path[$i + 1]) : null;
                    $params[$key] = (isset($params[$key]) ? (array_merge((array) $params[$key], array($val))): $val);
                }
            }
        }

        $this->_values = $values + $params;

        return $this->_values + $this->_defaults;
    }

    /**
     * Assembles user submitted parameters forming a URL path defined by this route
     *
     * @param array $data An array of variable and value pairs used as parameters
     * @param bool $reset Weither to reset the current params
     * @return string Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = true)
    {
        if (!$this->_keysSet) {
            $this->_setRequestKeys();
        }

        $params = (!$reset) ? $this->_values : array();

        foreach ($data as $key => $value) {
            if ($value !== null) {
                $params[$key] = $value;
            } elseif (isset($params[$key])) {
                unset($params[$key]);
            }
        }

        $params += $this->_defaults;

        $url = '';

        if ($this->_moduleValid || array_key_exists($this->_moduleKey, $data)) {
            if ($params[$this->_moduleKey] != $this->_defaults[$this->_moduleKey]) {
                $module = $params[$this->_moduleKey];
            }
        }
        unset($params[$this->_moduleKey]);

        $controller = $params[$this->_controllerKey];
        unset($params[$this->_controllerKey]);

        $action = $params[$this->_actionKey];
        unset($params[$this->_actionKey]);

        foreach ($params as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $arrayValue) {
                    if ($encode) $arrayValue = urlencode($arrayValue);
                    $url .= '/' . $key;
                    $url .= '/' . $arrayValue;
                }
            } else {
                if ($encode) $value = urlencode($value);
                $url .= '/' . $key;
                $url .= '/' . $value;
            }
        }

        if (!empty($url) || $action !== $this->_defaults[$this->_actionKey]) {
            if ($encode) $action = urlencode($action);
            $url = '/' . $action . $url;
        }

        if (!empty($url) || $controller !== $this->_defaults[$this->_controllerKey]) {
            if ($encode) $controller = urlencode($controller);
            $url = '/' . $controller . $url;
        }

        if (isset($module)) {
            if ($encode) $module = urlencode($module);
            $url = '/' . $module . $url;
        }

        return ltrim($url, self::URI_DELIMITER);
    }

    /**
     * Return a single parameter of route's defaults
     *
     * @param string $name Array key of the parameter
     * @return string Previously set default
     */
    public function getDefault($name) {
        if (isset($this->_defaults[$name])) {
            return $this->_defaults[$name];
        }
    }

    /**
     * Return an array of defaults
     *
     * @return array Route defaults
     */
    public function getDefaults() {
        return $this->_defaults;
    }

}
Controller/Router/Route/Hostname.php000066600000025707151256604610013561 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Route.php 9581 2008-06-01 14:08:03Z martel $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Controller_Router_Route_Abstract */
require_once 'Zend/Controller/Router/Route/Abstract.php';

/**
 * Hostname Route
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @see        http://manuals.rubyonrails.com/read/chapter/65
 */
class Zend_Controller_Router_Route_Hostname extends Zend_Controller_Router_Route_Abstract
{

    protected $_hostVariable   = ':';
    protected $_regexDelimiter = '#';
    protected $_defaultRegex   = null;

    /**
     * Holds names of all route's pattern variable names. Array index holds a position in host.
     * @var array
     */
    protected $_variables = array();

    /**
     * Holds Route patterns for all host parts. In case of a variable it stores it's regex
     * requirement or null. In case of a static part, it holds only it's direct value.
     * @var array
     */
    protected $_parts = array();

    /**
     * Holds user submitted default values for route's variables. Name and value pairs.
     * @var array
     */
    protected $_defaults = array();

    /**
     * Holds user submitted regular expression patterns for route's variables' values.
     * Name and value pairs.
     * @var array
     */
    protected $_requirements = array();

    /**
     * Default scheme
     * @var string
     */
    protected $_scheme = null;

    /**
     * Associative array filled on match() that holds matched path values
     * for given variable names.
     * @var array
     */
    protected $_values = array();

    /**
     * Current request object
     *
     * @var Zend_Controller_Request_Abstract
     */
    protected $_request;

    /**
     * Helper var that holds a count of route pattern's static parts
     * for validation
     * @var int
     */
    private $_staticCount = 0;

    /**
     * Set the request object
     *
     * @param  Zend_Controller_Request_Abstract|null $request
     * @return void
     */
    public function setRequest(Zend_Controller_Request_Abstract $request = null)
    {
        $this->_request = $request;
    }

    /**
     * Get the request object
     *
     * @return Zend_Controller_Request_Abstract $request
     */
    public function getRequest()
    {
        if ($this->_request === null) {
            require_once 'Zend/Controller/Front.php';
            $this->_request = Zend_Controller_Front::getInstance()->getRequest();
        }

        return $this->_request;
    }

    /**
     * Instantiates route based on passed Zend_Config structure
     *
     * @param Zend_Config $config Configuration object
     */
    public static function getInstance(Zend_Config $config)
    {
        $reqs   = ($config->reqs instanceof Zend_Config) ? $config->reqs->toArray() : array();
        $defs   = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
        $scheme = (isset($config->scheme)) ? $config->scheme : null;
        return new self($config->route, $defs, $reqs, $scheme);
    }

    /**
     * Prepares the route for mapping by splitting (exploding) it
     * to a corresponding atomic parts. These parts are assigned
     * a position which is later used for matching and preparing values.
     *
     * @param string $route Map used to match with later submitted hostname
     * @param array  $defaults Defaults for map variables with keys as variable names
     * @param array  $reqs Regular expression requirements for variables (keys as variable names)
     * @param string $scheme
     */
    public function __construct($route, $defaults = array(), $reqs = array(), $scheme = null)
    {
        $route               = trim($route, '.');
        $this->_defaults     = (array) $defaults;
        $this->_requirements = (array) $reqs;
        $this->_scheme       = $scheme;

        if ($route != '') {
            foreach (explode('.', $route) as $pos => $part) {
                if (substr($part, 0, 1) == $this->_hostVariable) {
                    $name = substr($part, 1);
                    $this->_parts[$pos] = (isset($reqs[$name]) ? $reqs[$name] : $this->_defaultRegex);
                    $this->_variables[$pos] = $name;
                } else {
                    $this->_parts[$pos] = $part;
                    $this->_staticCount++;
                }
            }
        }
    }

    /**
     * Matches a user submitted path with parts defined by a map. Assigns and
     * returns an array of variables on a successful match.
     *
     * @param Zend_Controller_Request_Http $request Request to get the host from
     * @return array|false An array of assigned values or a false on a mismatch
     */
    public function match($request)
    {
        // Check the scheme if required
        if ($this->_scheme !== null) {
            $scheme = $request->getScheme();

            if ($scheme !== $this->_scheme) {
                return false;
            }
        }

        // Get the host and remove unnecessary port information
        $host = $request->getHttpHost();
        if (preg_match('#:\d+$#', $host, $result) === 1) {
            $host = substr($host, 0, -strlen($result[0]));
        }

        $hostStaticCount = 0;
        $values = array();

        $host = trim($host, '.');

        if ($host != '') {
            $host = explode('.', $host);

            foreach ($host as $pos => $hostPart) {
                // Host is longer than a route, it's not a match
                if (!array_key_exists($pos, $this->_parts)) {
                    return false;
                }

                $name = isset($this->_variables[$pos]) ? $this->_variables[$pos] : null;
                $hostPart = urldecode($hostPart);

                // If it's a static part, match directly
                if ($name === null && $this->_parts[$pos] != $hostPart) {
                    return false;
                }

                // If it's a variable with requirement, match a regex. If not - everything matches
                if ($this->_parts[$pos] !== null && !preg_match($this->_regexDelimiter . '^' . $this->_parts[$pos] . '$' . $this->_regexDelimiter . 'iu', $hostPart)) {
                    return false;
                }

                // If it's a variable store it's value for later
                if ($name !== null) {
                    $values[$name] = $hostPart;
                } else {
                    $hostStaticCount++;
                }
            }
        }

        // Check if all static mappings have been matched
        if ($this->_staticCount != $hostStaticCount) {
            return false;
        }

        $return = $values + $this->_defaults;

        // Check if all map variables have been initialized
        foreach ($this->_variables as $var) {
            if (!array_key_exists($var, $return)) {
                return false;
            }
        }

        $this->_values = $values;

        return $return;

    }

    /**
     * Assembles user submitted parameters forming a hostname defined by this route
     *
     * @param  array $data An array of variable and value pairs used as parameters
     * @param  boolean $reset Whether or not to set route defaults with those provided in $data
     * @return string Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = false)
    {
        $host = array();
        $flag = false;

        foreach ($this->_parts as $key => $part) {
            $name = isset($this->_variables[$key]) ? $this->_variables[$key] : null;

            $useDefault = false;
            if (isset($name) && array_key_exists($name, $data) && $data[$name] === null) {
                $useDefault = true;
            }

            if (isset($name)) {
                if (isset($data[$name]) && !$useDefault) {
                    $host[$key] = $data[$name];
                    unset($data[$name]);
                } elseif (!$reset && !$useDefault && isset($this->_values[$name])) {
                    $host[$key] = $this->_values[$name];
                } elseif (isset($this->_defaults[$name])) {
                    $host[$key] = $this->_defaults[$name];
                } else {
                    require_once 'Zend/Controller/Router/Exception.php';
                    throw new Zend_Controller_Router_Exception($name . ' is not specified');
                }
            } else {
                $host[$key] = $part;
            }
        }

        $return = '';

        foreach (array_reverse($host, true) as $key => $value) {
            if ($flag || !isset($this->_variables[$key]) || $value !== $this->getDefault($this->_variables[$key])) {
                if ($encode) $value = urlencode($value);
                $return = '.' . $value . $return;
                $flag = true;
            }
        }

        $url = trim($return, '.');

        if ($this->_scheme !== null) {
            $scheme = $this->_scheme;
        } else {
            $request = $this->getRequest();
            if ($request instanceof Zend_Controller_Request_Http) {
                $scheme = $request->getScheme();
            } else {
                $scheme = 'http';
            }
        }

        $hostname = implode('.', $host);
        $url      = $scheme . '://' . $url;

        return $url;
    }

    /**
     * Return a single parameter of route's defaults
     *
     * @param string $name Array key of the parameter
     * @return string Previously set default
     */
    public function getDefault($name) {
        if (isset($this->_defaults[$name])) {
            return $this->_defaults[$name];
        }
        return null;
    }

    /**
     * Return an array of defaults
     *
     * @return array Route defaults
     */
    public function getDefaults() {
        return $this->_defaults;
    }

    /**
     * Get all variables which are used by the route
     *
     * @return array
     */
    public function getVariables()
    {
        return $this->_variables;
    }
}
Controller/Router/Route/Abstract.php000066600000003240151256604610013532 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Route.php 1847 2006-11-23 11:36:41Z martel $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Controller_Router_Route_Interface */
require_once 'Zend/Controller/Router/Route/Interface.php';

/**
 * Abstract Route
 *
 * Implements interface and provides convenience methods
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Controller_Router_Route_Abstract implements Zend_Controller_Router_Route_Interface
{

    public function getVersion() {
        return 2;
    }
    
    public function chain(Zend_Controller_Router_Route_Interface $route, $separator = '/')
    {
        require_once 'Zend/Controller/Router/Route/Chain.php';

        $chain = new Zend_Controller_Router_Route_Chain();
        $chain->chain($this)->chain($route, $separator);

        return $chain;
    }

}
Controller/Dispatcher/Abstract.php000066600000027776151256604610013266 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Dispatcher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Controller_Dispatcher_Interface */
require_once 'Zend/Controller/Dispatcher/Interface.php';

/**
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Dispatcher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Controller_Dispatcher_Abstract implements Zend_Controller_Dispatcher_Interface
{
    /**
     * Default action
     * @var string
     */
    protected $_defaultAction = 'index';

    /**
     * Default controller
     * @var string
     */
    protected $_defaultController = 'index';

    /**
     * Default module
     * @var string
     */
    protected $_defaultModule = 'default';

    /**
     * Front Controller instance
     * @var Zend_Controller_Front
     */
    protected $_frontController;

    /**
     * Array of invocation parameters to use when instantiating action
     * controllers
     * @var array
     */
    protected $_invokeParams = array();

    /**
     * Path delimiter character
     * @var string
     */
    protected $_pathDelimiter = '_';

    /**
     * Response object to pass to action controllers, if any
     * @var Zend_Controller_Response_Abstract|null
     */
    protected $_response = null;

    /**
     * Word delimiter characters
     * @var array
     */
    protected $_wordDelimiter = array('-', '.');

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct(array $params = array())
    {
        $this->setParams($params);
    }

    /**
     * Formats a string into a controller name.  This is used to take a raw
     * controller name, such as one stored inside a Zend_Controller_Request_Abstract
     * object, and reformat it to a proper class name that a class extending
     * Zend_Controller_Action would use.
     *
     * @param string $unformatted
     * @return string
     */
    public function formatControllerName($unformatted)
    {
        return ucfirst($this->_formatName($unformatted)) . 'Controller';
    }

    /**
     * Formats a string into an action name.  This is used to take a raw
     * action name, such as one that would be stored inside a Zend_Controller_Request_Abstract
     * object, and reformat into a proper method name that would be found
     * inside a class extending Zend_Controller_Action.
     *
     * @param string $unformatted
     * @return string
     */
    public function formatActionName($unformatted)
    {
        $formatted = $this->_formatName($unformatted, true);
        return strtolower(substr($formatted, 0, 1)) . substr($formatted, 1) . 'Action';
    }

    /**
     * Verify delimiter
     *
     * Verify a delimiter to use in controllers or actions. May be a single
     * string or an array of strings.
     *
     * @param string|array $spec
     * @return array
     * @throws Zend_Controller_Dispatcher_Exception with invalid delimiters
     */
    public function _verifyDelimiter($spec)
    {
        if (is_string($spec)) {
            return (array) $spec;
        } elseif (is_array($spec)) {
            $allStrings = true;
            foreach ($spec as $delim) {
                if (!is_string($delim)) {
                    $allStrings = false;
                    break;
                }
            }

            if (!$allStrings) {
                require_once 'Zend/Controller/Dispatcher/Exception.php';
                throw new Zend_Controller_Dispatcher_Exception('Word delimiter array must contain only strings');
            }

            return $spec;
        }

        require_once 'Zend/Controller/Dispatcher/Exception.php';
        throw new Zend_Controller_Dispatcher_Exception('Invalid word delimiter');
    }

    /**
     * Retrieve the word delimiter character(s) used in
     * controller or action names
     *
     * @return array
     */
    public function getWordDelimiter()
    {
        return $this->_wordDelimiter;
    }

    /**
     * Set word delimiter
     *
     * Set the word delimiter to use in controllers and actions. May be a
     * single string or an array of strings.
     *
     * @param string|array $spec
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setWordDelimiter($spec)
    {
        $spec = $this->_verifyDelimiter($spec);
        $this->_wordDelimiter = $spec;

        return $this;
    }

    /**
     * Retrieve the path delimiter character(s) used in
     * controller names
     *
     * @return array
     */
    public function getPathDelimiter()
    {
        return $this->_pathDelimiter;
    }

    /**
     * Set path delimiter
     *
     * Set the path delimiter to use in controllers. May be a single string or
     * an array of strings.
     *
     * @param string $spec
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setPathDelimiter($spec)
    {
        if (!is_string($spec)) {
            require_once 'Zend/Controller/Dispatcher/Exception.php';
            throw new Zend_Controller_Dispatcher_Exception('Invalid path delimiter');
        }
        $this->_pathDelimiter = $spec;

        return $this;
    }

    /**
     * Formats a string from a URI into a PHP-friendly name.
     *
     * By default, replaces words separated by the word separator character(s)
     * with camelCaps. If $isAction is false, it also preserves replaces words
     * separated by the path separation character with an underscore, making
     * the following word Title cased. All non-alphanumeric characters are
     * removed.
     *
     * @param string $unformatted
     * @param boolean $isAction Defaults to false
     * @return string
     */
    protected function _formatName($unformatted, $isAction = false)
    {
        // preserve directories
        if (!$isAction) {
            $segments = explode($this->getPathDelimiter(), $unformatted);
        } else {
            $segments = (array) $unformatted;
        }

        foreach ($segments as $key => $segment) {
            $segment        = str_replace($this->getWordDelimiter(), ' ', strtolower($segment));
            $segment        = preg_replace('/[^a-z0-9 ]/', '', $segment);
            $segments[$key] = str_replace(' ', '', ucwords($segment));
        }

        return implode('_', $segments);
    }

    /**
     * Retrieve front controller instance
     *
     * @return Zend_Controller_Front
     */
    public function getFrontController()
    {
        if (null === $this->_frontController) {
            require_once 'Zend/Controller/Front.php';
            $this->_frontController = Zend_Controller_Front::getInstance();
        }

        return $this->_frontController;
    }

    /**
     * Set front controller instance
     *
     * @param Zend_Controller_Front $controller
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setFrontController(Zend_Controller_Front $controller)
    {
        $this->_frontController = $controller;
        return $this;
    }

    /**
     * Add or modify a parameter to use when instantiating an action controller
     *
     * @param string $name
     * @param mixed $value
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setParam($name, $value)
    {
        $name = (string) $name;
        $this->_invokeParams[$name] = $value;
        return $this;
    }

    /**
     * Set parameters to pass to action controller constructors
     *
     * @param array $params
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setParams(array $params)
    {
        $this->_invokeParams = array_merge($this->_invokeParams, $params);
        return $this;
    }

    /**
     * Retrieve a single parameter from the controller parameter stack
     *
     * @param string $name
     * @return mixed
     */
    public function getParam($name)
    {
        if(isset($this->_invokeParams[$name])) {
            return $this->_invokeParams[$name];
        }

        return null;
    }

    /**
     * Retrieve action controller instantiation parameters
     *
     * @return array
     */
    public function getParams()
    {
        return $this->_invokeParams;
    }

    /**
     * Clear the controller parameter stack
     *
     * By default, clears all parameters. If a parameter name is given, clears
     * only that parameter; if an array of parameter names is provided, clears
     * each.
     *
     * @param null|string|array single key or array of keys for params to clear
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function clearParams($name = null)
    {
        if (null === $name) {
            $this->_invokeParams = array();
        } elseif (is_string($name) && isset($this->_invokeParams[$name])) {
            unset($this->_invokeParams[$name]);
        } elseif (is_array($name)) {
            foreach ($name as $key) {
                if (is_string($key) && isset($this->_invokeParams[$key])) {
                    unset($this->_invokeParams[$key]);
                }
            }
        }

        return $this;
    }

    /**
     * Set response object to pass to action controllers
     *
     * @param Zend_Controller_Response_Abstract|null $response
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setResponse(Zend_Controller_Response_Abstract $response = null)
    {
        $this->_response = $response;
        return $this;
    }

    /**
     * Return the registered response object
     *
     * @return Zend_Controller_Response_Abstract|null
     */
    public function getResponse()
    {
        return $this->_response;
    }

    /**
     * Set the default controller (minus any formatting)
     *
     * @param string $controller
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setDefaultControllerName($controller)
    {
        $this->_defaultController = (string) $controller;
        return $this;
    }

    /**
     * Retrieve the default controller name (minus formatting)
     *
     * @return string
     */
    public function getDefaultControllerName()
    {
        return $this->_defaultController;
    }

    /**
     * Set the default action (minus any formatting)
     *
     * @param string $action
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setDefaultAction($action)
    {
        $this->_defaultAction = (string) $action;
        return $this;
    }

    /**
     * Retrieve the default action name (minus formatting)
     *
     * @return string
     */
    public function getDefaultAction()
    {
        return $this->_defaultAction;
    }

    /**
     * Set the default module
     *
     * @param string $module
     * @return Zend_Controller_Dispatcher_Abstract
     */
    public function setDefaultModule($module)
    {
        $this->_defaultModule = (string) $module;
        return $this;
    }

    /**
     * Retrieve the default module
     *
     * @return string
     */
    public function getDefaultModule()
    {
        return $this->_defaultModule;
    }
}
Dom/Query.php000066600000013422151256604610007115 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Dom
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @see Zend_Dom_Query_Css2Xpath
 */
require_once 'Zend/Dom/Query/Css2Xpath.php';

/**
 * @see Zend_Dom_Query_Result
 */
require_once 'Zend/Dom/Query/Result.php';

/**
 * Query DOM structures based on CSS selectors and/or XPath
 * 
 * @package    Zend_Dom
 * @subpackage Query
 * @copyright  Copyright (C) 2008 - Present, Zend Technologies, Inc.
 * @license    New BSD {@link http://framework.zend.com/license/new-bsd}
 */
class Zend_Dom_Query
{
    /**#@+
     * @const string Document types
     */
    const DOC_XML   = 'docXml';
    const DOC_HTML  = 'docHtml';
    const DOC_XHTML = 'docXhtml';
    /**#@-*/

    /**
     * @var string
     */
    protected $_document;

    /**
     * Document type
     * @var string
     */
    protected $_docType;

    /**
     * Constructor
     * 
     * @param  null|string $document 
     * @return void
     */
    public function __construct($document = null)
    {
        if (null !== $document) {
            $this->setDocument($document);
        }
    }

    /**
     * Set document to query
     * 
     * @param  string $document 
     * @return Zend_Dom_Query
     */
    public function setDocument($document)
    {
        if ('<?xml' == substr(trim($document), 0, 5)) {
            return $this->setDocumentXml($document);
        }
        if (strstr($document, 'DTD XHTML')) {
            return $this->setDocumentXhtml($document);
        }
        return $this->setDocumentHtml($document);
    }

    /**
     * Register HTML document 
     * 
     * @param  string $document 
     * @return Zend_Dom_Query
     */
    public function setDocumentHtml($document)
    {
        $this->_document = (string) $document;
        $this->_docType  = self::DOC_HTML;
        return $this;
    }

    /**
     * Register XHTML document
     * 
     * @param  string $document 
     * @return Zend_Dom_Query
     */
    public function setDocumentXhtml($document)
    {
        $this->_document = (string) $document;
        $this->_docType  = self::DOC_XHTML;
        return $this;
    }

    /**
     * Register XML document
     * 
     * @param  string $document 
     * @return Zend_Dom_Query
     */
    public function setDocumentXml($document)
    {
        $this->_document = (string) $document;
        $this->_docType  = self::DOC_XML;
        return $this;
    }

    /**
     * Retrieve current document
     * 
     * @return string
     */
    public function getDocument()
    {
        return $this->_document;
    }

    /**
     * Get document type
     * 
     * @return string
     */
    public function getDocumentType()
    {
        return $this->_docType;
    }

    /**
     * Perform a CSS selector query
     * 
     * @param  string $query 
     * @return Zend_Dom_Query_Result
     */
    public function query($query)
    {
        $xpathQuery = Zend_Dom_Query_Css2Xpath::transform($query);
        return $this->queryXpath($xpathQuery, $query);
    }

    /**
     * Perform an XPath query
     * 
     * @param  string $xpathQuery
     * @param  string $query CSS selector query
     * @return Zend_Dom_Query_Result
     */
    public function queryXpath($xpathQuery, $query = null)
    {
        if (null === ($document = $this->getDocument())) {
            require_once 'Zend/Dom/Exception.php';
            throw new Zend_Dom_Exception('Cannot query; no document registered');
        }

        $domDoc = new DOMDocument;
        $type   = $this->getDocumentType();
        switch ($type) {
            case self::DOC_XML:
                $success = @$domDoc->loadXML($document);
                break;
            case self::DOC_HTML:
            case self::DOC_XHTML:
            default:
                $success = @$domDoc->loadHTML($document);
                break;
        }

        if (!$success) {
            require_once 'Zend/Dom/Exception.php';
            throw new Zend_Dom_Exception(sprintf('Error parsing document (type == %s)', $type));
        }

        $nodeList   = $this->_getNodeList($domDoc, $xpathQuery);
        return new Zend_Dom_Query_Result($query, $xpathQuery, $domDoc, $nodeList);
    }

    /**
     * Prepare node list
     * 
     * @param  DOMDocument $document
     * @param  string|array $xpathQuery
     * @return array
     */
    protected function _getNodeList($document, $xpathQuery)
    {
        $xpath      = new DOMXPath($document);
        $xpathQuery = (string) $xpathQuery;
        if (preg_match_all('|\[contains\((@[a-z0-9_-]+),\s?\' |i', $xpathQuery, $matches)) {
            foreach ($matches[1] as $attribute) {
                $queryString = '//*[' . $attribute . ']';
                $attributeName = substr($attribute, 1);
                $nodes = $xpath->query($queryString);
                foreach ($nodes as $node) {
                    $attr = $node->attributes->getNamedItem($attributeName);
                    $attr->value = ' ' . $attr->value . ' ';
                }
            }
        }
        return $xpath->query($xpathQuery);
    }
}
Server/Cache.php000066600000010357151256604610007546 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Server
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Cache.php 12195 2008-10-30 13:34:35Z matthew $
 */

/**
 * Zend_Server_Cache: cache server definitions
 *
 * @category   Zend
 * @package    Zend_Server
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Server_Cache
{
    /**
     * @var array Methods to skip when caching server
     */
    protected static $_skipMethods = array();

    /**
     * Cache a file containing the dispatch list.
     *
     * Serializes the server definition stores the information
     * in $filename.
     *
     * Returns false on any error (typically, inability to write to file), true
     * on success.
     *
     * @param  string $filename
     * @param  Zend_Server_Interface $server
     * @return bool
     */
    public static function save($filename, Zend_Server_Interface $server)
    {
        if (!is_string($filename)
            || (!file_exists($filename) && !is_writable(dirname($filename))))
        {
            return false;
        }

        $methods = $server->getFunctions();

        if ($methods instanceof Zend_Server_Definition) {
            $definition = new Zend_Server_Definition();
            foreach ($methods as $method) {
                if (in_array($method->getName(), self::$_skipMethods)) {
                    continue;
                }
                $definition->addMethod($method);
            }
            $methods = $definition;
        }

        if (0 === @file_put_contents($filename, serialize($methods))) {
            return false;
        }

        return true;
    }

    /**
     * Load server definition from a file
     *
     * Unserializes a stored server definition from $filename. Returns false if 
     * it fails in any way, true on success.
     *
     * Useful to prevent needing to build the server definition on each 
     * request. Sample usage:
     *
     * <code>
     * if (!Zend_Server_Cache::get($filename, $server)) {
     *     require_once 'Some/Service/Class.php';
     *     require_once 'Another/Service/Class.php';
     *
     *     // Attach Some_Service_Class with namespace 'some'
     *     $server->attach('Some_Service_Class', 'some');
     *
     *     // Attach Another_Service_Class with namespace 'another'
     *     $server->attach('Another_Service_Class', 'another');
     *
     *     Zend_Server_Cache::save($filename, $server);
     * }
     *
     * $response = $server->handle();
     * echo $response;
     * </code>
     *
     * @param  string $filename
     * @param  Zend_Server_Interface $server
     * @return bool
     */
    public static function get($filename, Zend_Server_Interface $server)
    {
        if (!is_string($filename)
            || !file_exists($filename)
            || !is_readable($filename))
        {
            return false;
        }


        if (false === ($dispatch = @file_get_contents($filename))) {
            return false;
        }

        if (false === ($dispatchArray = @unserialize($dispatch))) {
            return false;
        }

        $server->loadFunctions($dispatchArray);

        return true;
    }

    /**
     * Remove a cache file
     *
     * @param  string $filename
     * @return boolean
     */
    public static function delete($filename)
    {
        if (is_string($filename) && file_exists($filename)) {
            unlink($filename);
            return true;
        }

        return false;
    }
}
Server/Definition.php000066600000015120151256604610010624 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Server
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/**
 * Server methods metadata
 *
 * @todo       Implement iterator
 * @category   Zend
 * @package    Zend_Server
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Server_Definition implements Countable, Iterator
{
    /**
     * @var array Array of Zend_Server_Method_Definition objects
     */
    protected $_methods = array();

    /**
     * @var bool Whether or not overwriting existing methods is allowed
     */
    protected $_overwriteExistingMethods = false;

    /**
     * Constructor
     * 
     * @param  null|array $methods 
     * @return void
     */
    public function __construct($methods = null)
    {
        if (is_array($methods)) {
            $this->setMethods($methods);
        }
    }

    /**
     * Set flag indicating whether or not overwriting existing methods is allowed
     * 
     * @param mixed $flag 
     * @return void
     */
    public function setOverwriteExistingMethods($flag)
    {
        $this->_overwriteExistingMethods = (bool) $flag;
        return $this;
    }

    /**
     * Add method to definition
     * 
     * @param  array|Zend_Server_Method_Definition $method 
     * @param  null|string $name 
     * @return Zend_Server_Definition
     * @throws Zend_Server_Exception if duplicate or invalid method provided
     */
    public function addMethod($method, $name = null)
    {
        if (is_array($method)) {
            require_once 'Zend/Server/Method/Definition.php';
            $method = new Zend_Server_Method_Definition($method);
        } elseif (!$method instanceof Zend_Server_Method_Definition) {
            require_once 'Zend/Server/Exception.php';
            throw new Zend_Server_Exception('Invalid method provided');
        }

        if (is_numeric($name)) {
            $name = null;
        }
        if (null !== $name) {
            $method->setName($name);
        } else {
            $name = $method->getName();
        }
        if (null === $name) {
            require_once 'Zend/Server/Exception.php';
            throw new Zend_Server_Exception('No method name provided');
        }

        if (!$this->_overwriteExistingMethods && array_key_exists($name, $this->_methods)) {
            require_once 'Zend/Server/Exception.php';
            throw new Zend_Server_Exception(sprintf('Method by name of "%s" already exists', $name));
        }
        $this->_methods[$name] = $method;
        return $this;
    }

    /**
     * Add multiple methods
     * 
     * @param  array $methods Array of Zend_Server_Method_Definition objects or arrays
     * @return Zend_Server_Definition
     */
    public function addMethods(array $methods)
    {
        foreach ($methods as $key => $method) {
            $this->addMethod($method, $key);
        }
        return $this;
    }

    /**
     * Set all methods at once (overwrite)
     * 
     * @param  array $methods Array of Zend_Server_Method_Definition objects or arrays
     * @return Zend_Server_Definition
     */
    public function setMethods(array $methods)
    {
        $this->clearMethods();
        $this->addMethods($methods);
        return $this;
    }

    /**
     * Does the definition have the given method?
     * 
     * @param  string $method 
     * @return bool
     */
    public function hasMethod($method)
    {
        return array_key_exists($method, $this->_methods);
    }

    /**
     * Get a given method definition
     * 
     * @param  string $method 
     * @return null|Zend_Server_Method_Definition
     */
    public function getMethod($method)
    {
        if ($this->hasMethod($method)) {
            return $this->_methods[$method];
        }
        return false;
    }

    /**
     * Get all method definitions
     * 
     * @return array Array of Zend_Server_Method_Definition objects
     */
    public function getMethods()
    {
        return $this->_methods;
    }

    /**
     * Remove a method definition
     * 
     * @param  string $method 
     * @return Zend_Server_Definition
     */
    public function removeMethod($method)
    {
        if ($this->hasMethod($method)) {
            unset($this->_methods[$method]);
        }
        return $this;
    }

    /**
     * Clear all method definitions
     * 
     * @return Zend_Server_Definition
     */
    public function clearMethods()
    {
        $this->_methods = array();
        return $this;
    }

    /**
     * Cast definition to an array
     * 
     * @return array
     */
    public function toArray()
    {
        $methods = array();
        foreach ($this->getMethods() as $key => $method) {
            $methods[$key] = $method->toArray();
        }
        return $methods;
    }

    /**
     * Countable: count of methods
     * 
     * @return int
     */
    public function count()
    {
        return count($this->_methods);
    }

    /**
     * Iterator: current item
     * 
     * @return mixed
     */
    public function current()
    {
        return current($this->_methods);
    }

    /**
     * Iterator: current item key
     * 
     * @return int|string
     */
    public function key()
    {
        return key($this->_methods);
    }

    /**
     * Iterator: advance to next method
     * 
     * @return void
     */
    public function next()
    {
        return next($this->_methods);
    }

    /**
     * Iterator: return to first method
     * 
     * @return void
     */
    public function rewind()
    {
        return reset($this->_methods);
    }

    /**
     * Iterator: is the current index valid?
     * 
     * @return bool
     */
    public function valid()
    {
        return (bool) $this->current();
    }
}
Server/Reflection/Parameter.php000066600000007523151256604610012556 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Server
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Zend_Server_Reflection_Exception
 */
require_once 'Zend/Server/Reflection/Exception.php';

/**
 * Parameter Reflection
 *
 * Decorates a ReflectionParameter to allow setting the parameter type
 *
 * @category   Zend
 * @package    Zend_Server
 * @subpackage Reflection
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version $Id: Parameter.php 12619 2008-11-13 15:24:29Z alexander $
 */
class Zend_Server_Reflection_Parameter
{
    /**
     * @var ReflectionParameter
     */
    protected $_reflection;

    /**
     * Parameter position
     * @var int
     */
    protected $_position;

    /**
     * Parameter type
     * @var string
     */
    protected $_type;

    /**
     * Parameter description
     * @var string
     */
    protected $_description;

    /**
     * Constructor
     *
     * @param ReflectionParameter $r
     * @param string $type Parameter type
     * @param string $description Parameter description
     */
    public function __construct(ReflectionParameter $r, $type = 'mixed', $description = '')
    {
        $this->_reflection = $r;
        $this->setType($type);
        $this->setDescription($description);
    }

    /**
     * Proxy reflection calls
     *
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        if (method_exists($this->_reflection, $method)) {
            return call_user_func_array(array($this->_reflection, $method), $args);
        }

        throw new Zend_Server_Reflection_Exception('Invalid reflection method');
    }

    /**
     * Retrieve parameter type
     *
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * Set parameter type
     *
     * @param string|null $type
     * @return void
     */
    public function setType($type)
    {
        if (!is_string($type) && (null !== $type)) {
            throw new Zend_Server_Reflection_Exception('Invalid parameter type');
        }

        $this->_type = $type;
    }

    /**
     * Retrieve parameter description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->_description;
    }

    /**
     * Set parameter description
     *
     * @param string|null $description
     * @return void
     */
    public function setDescription($description)
    {
        if (!is_string($description) && (null !== $description)) {
            throw new Zend_Server_Reflection_Exception('Invalid parameter description');
        }

        $this->_description = $description;
    }

    /**
     * Set parameter position
     *
     * @param int $index
     * @return void
     */
    public function setPosition($index)
    {
        $this->_position = (int) $index;
    }

    /**
     * Return parameter position
     *
     * @return int
     */
    public function getPosition()
    {
        return $this->_position;
    }
}
Server/Reflection/Function/Abstract.php000066600000036647151256604610014177 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Server
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Zend_Server_Reflection_Exception
 */
require_once 'Zend/Server/Reflection/Exception.php';

/**
 * Zend_Server_Reflection_Node
 */
require_once 'Zend/Server/Reflection/Node.php';

/**
 * Zend_Server_Reflection_Parameter
 */
require_once 'Zend/Server/Reflection/Parameter.php';

/**
 * Zend_Server_Reflection_Prototype
 */
require_once 'Zend/Server/Reflection/Prototype.php';

/**
 * Function/Method Reflection
 *
 * Decorates a ReflectionFunction. Allows setting and retrieving an alternate
 * 'service' name (i.e., the name to be used when calling via a service),
 * setting and retrieving the description (originally set using the docblock
 * contents), retrieving the callback and callback type, retrieving additional
 * method invocation arguments, and retrieving the
 * method {@link Zend_Server_Reflection_Prototype prototypes}.
 *
 * @category   Zend
 * @package    Zend_Server
 * @subpackage Reflection
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version $Id: Abstract.php 12619 2008-11-13 15:24:29Z alexander $
 */
abstract class Zend_Server_Reflection_Function_Abstract
{
    /**
     * @var ReflectionFunction
     */
    protected $_reflection;

    /**
     * Additional arguments to pass to method on invocation
     * @var array
     */
    protected $_argv = array();

    /**
     * Used to store extra configuration for the method (typically done by the
     * server class, e.g., to indicate whether or not to instantiate a class).
     * Associative array; access is as properties via {@link __get()} and
     * {@link __set()}
     * @var array
     */
    protected $_config = array();

    /**
     * Declaring class (needed for when serialization occurs)
     * @var string
     */
    protected $_class;

    /**
     * Function/method description
     * @var string
     */
    protected $_description = '';

    /**
     * Namespace with which to prefix function/method name
     * @var string
     */
    protected $_namespace;

    /**
     * Prototypes
     * @var array
     */
    protected $_prototypes = array();

    private $_return;
    private $_returnDesc;
    private $_paramDesc;
    private $_sigParams;
    private $_sigParamsDepth;

    /**
     * Constructor
     *
     * @param ReflectionFunction $r
     */
    public function __construct(Reflector $r, $namespace = null, $argv = array())
    {
        // In PHP 5.1.x, ReflectionMethod extends ReflectionFunction. In 5.2.x,
        // both extend ReflectionFunctionAbstract. So, we can't do normal type
        // hinting in the prototype, but instead need to do some explicit
        // testing here.
        if ((!$r instanceof ReflectionFunction)
            && (!$r instanceof ReflectionMethod)) {
            throw new Zend_Server_Reflection_Exception('Invalid reflection class');
        }
        $this->_reflection = $r;

        // Determine namespace
        if (null !== $namespace){
            $this->setNamespace($namespace);
        }

        // Determine arguments
        if (is_array($argv)) {
            $this->_argv = $argv;
        }

        // If method call, need to store some info on the class
        if ($r instanceof ReflectionMethod) {
            $this->_class = $r->getDeclaringClass()->getName();
        }

        // Perform some introspection
        $this->_reflect();
    }

    /**
     * Create signature node tree
     *
     * Recursive method to build the signature node tree. Increments through
     * each array in {@link $_sigParams}, adding every value of the next level
     * to the current value (unless the current value is null).
     *
     * @param Zend_Server_Reflection_Node $parent
     * @param int $level
     * @return void
     */
    protected function _addTree(Zend_Server_Reflection_Node $parent, $level = 0)
    {
        if ($level >= $this->_sigParamsDepth) {
            return;
        }

        foreach ($this->_sigParams[$level] as $value) {
            $node = new Zend_Server_Reflection_Node($value, $parent);
            if ((null !== $value) && ($this->_sigParamsDepth > $level + 1)) {
                $this->_addTree($node, $level + 1);
            }
        }
    }

    /**
     * Build the signature tree
     *
     * Builds a signature tree starting at the return values and descending
     * through each method argument. Returns an array of
     * {@link Zend_Server_Reflection_Node}s.
     *
     * @return array
     */
    protected function _buildTree()
    {
        $returnTree = array();
        foreach ((array) $this->_return as $value) {
            $node = new Zend_Server_Reflection_Node($value);
            $this->_addTree($node);
            $returnTree[] = $node;
        }

        return $returnTree;
    }

    /**
     * Build method signatures
     *
     * Builds method signatures using the array of return types and the array of
     * parameters types
     *
     * @param array $return Array of return types
     * @param string $returnDesc Return value description
     * @param array $params Array of arguments (each an array of types)
     * @param array $paramDesc Array of parameter descriptions
     * @return array
     */
    protected function _buildSignatures($return, $returnDesc, $paramTypes, $paramDesc)
    {
        $this->_return         = $return;
        $this->_returnDesc     = $returnDesc;
        $this->_paramDesc      = $paramDesc;
        $this->_sigParams      = $paramTypes;
        $this->_sigParamsDepth = count($paramTypes);
        $signatureTrees        = $this->_buildTree();
        $signatures            = array();

        $endPoints = array();
        foreach ($signatureTrees as $root) {
            $tmp = $root->getEndPoints();
            if (empty($tmp)) {
                $endPoints = array_merge($endPoints, array($root));
            } else {
                $endPoints = array_merge($endPoints, $tmp);
            }
        }

        foreach ($endPoints as $node) {
            if (!$node instanceof Zend_Server_Reflection_Node) {
                continue;
            }

            $signature = array();
            do {
                array_unshift($signature, $node->getValue());
                $node = $node->getParent();
            } while ($node instanceof Zend_Server_Reflection_Node);

            $signatures[] = $signature;
        }

        // Build prototypes
        $params = $this->_reflection->getParameters();
        foreach ($signatures as $signature) {
            $return = new Zend_Server_Reflection_ReturnValue(array_shift($signature), $this->_returnDesc);
            $tmp    = array();
            foreach ($signature as $key => $type) {
                $param = new Zend_Server_Reflection_Parameter($params[$key], $type, $this->_paramDesc[$key]);
                $param->setPosition($key);
                $tmp[] = $param;
            }

            $this->_prototypes[] = new Zend_Server_Reflection_Prototype($return, $tmp);
        }
    }

    /**
     * Use code reflection to create method signatures
     *
     * Determines the method help/description text from the function DocBlock
     * comment. Determines method signatures using a combination of
     * ReflectionFunction and parsing of DocBlock @param and @return values.
     *
     * @param ReflectionFunction $function
     * @return array
     */
    protected function _reflect()
    {
        $function           = $this->_reflection;
        $helpText           = '';
        $signatures         = array();
        $returnDesc         = '';
        $paramCount         = $function->getNumberOfParameters();
        $paramCountRequired = $function->getNumberOfRequiredParameters();
        $parameters         = $function->getParameters();
        $docBlock           = $function->getDocComment();

        if (!empty($docBlock)) {
            // Get help text
            if (preg_match(':/\*\*\s*\r?\n\s*\*\s(.*?)\r?\n\s*\*(\s@|/):s', $docBlock, $matches))
            {
                $helpText = $matches[1];
                $helpText = preg_replace('/(^\s*\*\s)/m', '', $helpText);
                $helpText = preg_replace('/\r?\n\s*\*\s*(\r?\n)*/s', "\n", $helpText);
                $helpText = trim($helpText);
            }

            // Get return type(s) and description
            $return     = 'void';
            if (preg_match('/@return\s+(\S+)/', $docBlock, $matches)) {
                $return = explode('|', $matches[1]);
                if (preg_match('/@return\s+\S+\s+(.*?)(@|\*\/)/s', $docBlock, $matches))
                {
                    $value = $matches[1];
                    $value = preg_replace('/\s?\*\s/m', '', $value);
                    $value = preg_replace('/\s{2,}/', ' ', $value);
                    $returnDesc = trim($value);
                }
            }

            // Get param types and description
            if (preg_match_all('/@param\s+([^\s]+)/m', $docBlock, $matches)) {
                $paramTypesTmp = $matches[1];
                if (preg_match_all('/@param\s+\S+\s+(\$^\S+)\s+(.*?)(@|\*\/)/s', $docBlock, $matches))
                {
                    $paramDesc = $matches[2];
                    foreach ($paramDesc as $key => $value) {
                        $value = preg_replace('/\s?\*\s/m', '', $value);
                        $value = preg_replace('/\s{2,}/', ' ', $value);
                        $paramDesc[$key] = trim($value);
                    }
                }
            }
        } else {
            $helpText = $function->getName();
            $return   = 'void';
        }

        // Set method description
        $this->setDescription($helpText);

        // Get all param types as arrays
        if (!isset($paramTypesTmp) && (0 < $paramCount)) {
            $paramTypesTmp = array_fill(0, $paramCount, 'mixed');
        } elseif (!isset($paramTypesTmp)) {
            $paramTypesTmp = array();
        } elseif (count($paramTypesTmp) < $paramCount) {
            $start = $paramCount - count($paramTypesTmp);
            for ($i = $start; $i < $paramCount; ++$i) {
                $paramTypesTmp[$i] = 'mixed';
            }
        }

        // Get all param descriptions as arrays
        if (!isset($paramDesc) && (0 < $paramCount)) {
            $paramDesc = array_fill(0, $paramCount, '');
        } elseif (!isset($paramDesc)) {
            $paramDesc = array();
        } elseif (count($paramDesc) < $paramCount) {
            $start = $paramCount - count($paramDesc);
            for ($i = $start; $i < $paramCount; ++$i) {
                $paramDesc[$i] = '';
            }
        }

        if (count($paramTypesTmp) != $paramCount) {
            throw new Zend_Server_Reflection_Exception(
               'Variable number of arguments is not supported for services (except optional parameters). '
             . 'Number of function arguments must currespond to actual number of arguments described in a docblock.');
        }

        $paramTypes = array();
        foreach ($paramTypesTmp as $i => $param) {
            $tmp = explode('|', $param);
            if ($parameters[$i]->isOptional()) {
                array_unshift($tmp, null);
            }
            $paramTypes[] = $tmp;
        }

        $this->_buildSignatures($return, $returnDesc, $paramTypes, $paramDesc);
    }


    /**
     * Proxy reflection calls
     *
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        if (method_exists($this->_reflection, $method)) {
            return call_user_func_array(array($this->_reflection, $method), $args);
        }

        throw new Zend_Server_Reflection_Exception('Invalid reflection method ("' .$method. '")');
    }

    /**
     * Retrieve configuration parameters
     *
     * Values are retrieved by key from {@link $_config}. Returns null if no
     * value found.
     *
     * @param string $key
     * @return mixed
     */
    public function __get($key)
    {
        if (isset($this->_config[$key])) {
            return $this->_config[$key];
        }

        return null;
    }

    /**
     * Set configuration parameters
     *
     * Values are stored by $key in {@link $_config}.
     *
     * @param string $key
     * @param mixed $value
     * @return void
     */
    public function __set($key, $value)
    {
        $this->_config[$key] = $value;
    }

    /**
     * Set method's namespace
     *
     * @param string $namespace
     * @return void
     */
    public function setNamespace($namespace)
    {
        if (empty($namespace)) {
            $this->_namespace = '';
            return;
        }

        if (!is_string($namespace) || !preg_match('/[a-z0-9_\.]+/i', $namespace)) {
            throw new Zend_Server_Reflection_Exception('Invalid namespace');
        }

        $this->_namespace = $namespace;
    }

    /**
     * Return method's namespace
     *
     * @return string
     */
    public function getNamespace()
    {
        return $this->_namespace;
    }

    /**
     * Set the description
     *
     * @param string $string
     * @return void
     */
    public function setDescription($string)
    {
        if (!is_string($string)) {
            throw new Zend_Server_Reflection_Exception('Invalid description');
        }

        $this->_description = $string;
    }

    /**
     * Retrieve the description
     *
     * @return void
     */
    public function getDescription()
    {
        return $this->_description;
    }

    /**
     * Retrieve all prototypes as array of
     * {@link Zend_Server_Reflection_Prototype Zend_Server_Reflection_Prototypes}
     *
     * @return array
     */
    public function getPrototypes()
    {
        return $this->_prototypes;
    }

    /**
     * Retrieve additional invocation arguments
     *
     * @return array
     */
    public function getInvokeArguments()
    {
        return $this->_argv;
    }

    /**
     * Wakeup from serialization
     *
     * Reflection needs explicit instantiation to work correctly. Re-instantiate
     * reflection object on wakeup.
     *
     * @return void
     */
    public function __wakeup()
    {
        if ($this->_reflection instanceof ReflectionMethod) {
            $class = new ReflectionClass($this->_class);
            $this->_reflection = new ReflectionMethod($class->newInstance(), $this->getName());
        } else {
            $this->_reflection = new ReflectionFunction($this->getName());
        }
    }
}
Server/Reflection/ReturnValue.php000066600000005430151256604610013105 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Server
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * Zend_Server_Reflection_Exception
 */
require_once 'Zend/Server/Reflection/Exception.php';

/**
 * Return value reflection
 *
 * Stores the return value type and description
 *
 * @category   Zend
 * @package    Zend_Server
 * @subpackage Reflection
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version $Id: ReturnValue.php 12619 2008-11-13 15:24:29Z alexander $
 */
class Zend_Server_Reflection_ReturnValue
{
    /**
     * Return value type
     * @var string
     */
    protected $_type;

    /**
     * Return value description
     * @var string
     */
    protected $_description;

    /**
     * Constructor
     *
     * @param string $type Return value type
     * @param string $description Return value type
     */
    public function __construct($type = 'mixed', $description = '')
    {
        $this->setType($type);
        $this->setDescription($description);
    }

    /**
     * Retrieve parameter type
     *
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * Set parameter type
     *
     * @param string|null $type
     * @return void
     */
    public function setType($type)
    {
        if (!is_string($type) && (null !== $type)) {
            throw new Zend_Server_Reflection_Exception('Invalid parameter type');
        }

        $this->_type = $type;
    }

    /**
     * Retrieve parameter description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->_description;
    }

    /**
     * Set parameter description
     *
     * @param string|null $description
     * @return void
     */
    public function setDescription($description)
    {
        if (!is_string($description) && (null !== $description)) {
            throw new Zend_Server_Reflection_Exception('Invalid parameter description');
        }

        $this->_description = $description;
    }
}
Filter/StripTags.php000066600000023503151256604610010437 0ustar00<?php

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


/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';


/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_StripTags implements Zend_Filter_Interface
{
    /**
     * Unique ID prefix used for allowing comments
     */
    const UNIQUE_ID_PREFIX = '__Zend_Filter_StripTags__';

    /**
     * Whether comments are allowed
     *
     * If false (the default), then comments are removed from the input string.
     *
     * @var boolean
     */
    public $commentsAllowed;

    /**
     * Array of allowed tags and allowed attributes for each allowed tag
     *
     * Tags are stored in the array keys, and the array values are themselves
     * arrays of the attributes allowed for the corresponding tag.
     *
     * @var array
     */
    protected $_tagsAllowed = array();

    /**
     * Array of allowed attributes for all allowed tags
     *
     * Attributes stored here are allowed for all of the allowed tags.
     *
     * @var array
     */
    protected $_attributesAllowed = array();

    /**
     * Sets the filter options
     *
     * @param  array|string $tagsAllowed
     * @param  array|string $attributesAllowed
     * @param  boolean      $allowComments
     * @return void
     */
    public function __construct($tagsAllowed = null, $attributesAllowed = null, $commentsAllowed = false)
    {
        $this->setTagsAllowed($tagsAllowed);
        $this->setAttributesAllowed($attributesAllowed);
        $this->commentsAllowed = (boolean) $commentsAllowed;
    }

    /**
     * Returns the tagsAllowed option
     *
     * @return array
     */
    public function getTagsAllowed()
    {
        return $this->_tagsAllowed;
    }

    /**
     * Sets the tagsAllowed option
     *
     * @param  array|string $tagsAllowed
     * @return Zend_Filter_StripTags Provides a fluent interface
     */
    public function setTagsAllowed($tagsAllowed)
    {
        if (!is_array($tagsAllowed)) {
            $tagsAllowed = array($tagsAllowed);
        }

        foreach ($tagsAllowed as $index => $element) {
            // If the tag was provided without attributes
            if (is_int($index) && is_string($element)) {
                // Canonicalize the tag name
                $tagName = strtolower($element);
                // Store the tag as allowed with no attributes
                $this->_tagsAllowed[$tagName] = array();
            }
            // Otherwise, if a tag was provided with attributes
            else if (is_string($index) && (is_array($element) || is_string($element))) {
                // Canonicalize the tag name
                $tagName = strtolower($index);
                // Canonicalize the attributes
                if (is_string($element)) {
                    $element = array($element);
                }
                // Store the tag as allowed with the provided attributes
                $this->_tagsAllowed[$tagName] = array();
                foreach ($element as $attribute) {
                    if (is_string($attribute)) {
                        // Canonicalize the attribute name
                        $attributeName = strtolower($attribute);
                        $this->_tagsAllowed[$tagName][$attributeName] = null;
                    }
                }
            }
        }

        return $this;
    }

    /**
     * Returns the attributesAllowed option
     *
     * @return array
     */
    public function getAttributesAllowed()
    {
        return $this->_attributesAllowed;
    }

    /**
     * Sets the attributesAllowed option
     *
     * @param  array|string $attributesAllowed
     * @return Zend_Filter_StripTags Provides a fluent interface
     */
    public function setAttributesAllowed($attributesAllowed)
    {
        if (!is_array($attributesAllowed)) {
            $attributesAllowed = array($attributesAllowed);
        }

        // Store each attribute as allowed
        foreach ($attributesAllowed as $attribute) {
            if (is_string($attribute)) {
                // Canonicalize the attribute name
                $attributeName = strtolower($attribute);
                $this->_attributesAllowed[$attributeName] = null;
            }
        }

        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * @todo improve docblock descriptions
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        $valueCopy = (string) $value;

        // If comments are allowed, then replace them with unique identifiers
        if ($this->commentsAllowed) {
            preg_match_all('/<\!--.*?--\s*>/s' , (string) $valueCopy, $matches);
            $comments = array_unique($matches[0]);
            foreach ($comments as $k => $v) {
                $valueCopy = str_replace($v, self::UNIQUE_ID_PREFIX . $k, $valueCopy);
            }
        }

        // Initialize accumulator for filtered data
        $dataFiltered = '';
        // Parse the input data iteratively as regular pre-tag text followed by a
        // tag; either may be empty strings
        preg_match_all('/([^<]*)(<?[^>]*>?)/', (string) $valueCopy, $matches);
        // Iterate over each set of matches
        foreach ($matches[1] as $index => $preTag) {
            // If the pre-tag text is non-empty, strip any ">" characters from it
            if (strlen($preTag)) {
                $preTag = str_replace('>', '', $preTag);
            }
            // If a tag exists in this match, then filter the tag
            $tag = $matches[2][$index];
            if (strlen($tag)) {
                $tagFiltered = $this->_filterTag($tag);
            } else {
                $tagFiltered = '';
            }
            // Add the filtered pre-tag text and filtered tag to the data buffer
            $dataFiltered .= $preTag . $tagFiltered;
        }

        // If comments are allowed, then replace the unique identifiers with the corresponding comments
        if ($this->commentsAllowed) {
            foreach ($comments as $k => $v) {
                $dataFiltered = str_replace(self::UNIQUE_ID_PREFIX . $k, $v, $dataFiltered);
            }
        }

        // Return the filtered data
        return $dataFiltered;
    }

    /**
     * Filters a single tag against the current option settings
     *
     * @param  string $tag
     * @return string
     */
    protected function _filterTag($tag)
    {
        // Parse the tag into:
        // 1. a starting delimiter (mandatory)
        // 2. a tag name (if available)
        // 3. a string of attributes (if available)
        // 4. an ending delimiter (if available)
        $isMatch = preg_match('~(</?)(\w*)((/(?!>)|[^/>])*)(/?>)~', $tag, $matches);

        // If the tag does not match, then strip the tag entirely
        if (!$isMatch) {
            return '';
        }

        // Save the matches to more meaningfully named variables
        $tagStart      = $matches[1];
        $tagName       = strtolower($matches[2]);
        $tagAttributes = $matches[3];
        $tagEnd        = $matches[5];

        // If the tag is not an allowed tag, then remove the tag entirely
        if (!isset($this->_tagsAllowed[$tagName])) {
            return '';
        }

        // Trim the attribute string of whitespace at the ends
        $tagAttributes = trim($tagAttributes);

        // If there are non-whitespace characters in the attribute string
        if (strlen($tagAttributes)) {
            // Parse iteratively for well-formed attributes
            preg_match_all('/(\w+)\s*=\s*(?:(")(.*?)"|(\')(.*?)\')/s', $tagAttributes, $matches);

            // Initialize valid attribute accumulator
            $tagAttributes = '';

            // Iterate over each matched attribute
            foreach ($matches[1] as $index => $attributeName) {
                $attributeName      = strtolower($attributeName);
                $attributeDelimiter = $matches[2][$index];
                $attributeValue     = $matches[3][$index];

                // If the attribute is not allowed, then remove it entirely
                if (!array_key_exists($attributeName, $this->_tagsAllowed[$tagName])
                    && !array_key_exists($attributeName, $this->_attributesAllowed)) {
                    continue;
                }
                // Add the attribute to the accumulator
                $tagAttributes .= " $attributeName=" . $attributeDelimiter
                                . $attributeValue . $attributeDelimiter;
            }
        }

        // Reconstruct tags ending with "/>" as backwards-compatible XHTML tag
        if (strpos($tagEnd, '/') !== false) {
            $tagEnd = " $tagEnd";
        }

        // Return the filtered tag
        return $tagStart . $tagName . $tagAttributes . $tagEnd;
    }
}
Filter/Int.php000066600000002561151256604610007252 0ustar00<?php

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


/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';


/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Int implements Zend_Filter_Interface
{
    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns (int) $value
     *
     * @param  string $value
     * @return integer
     */
    public function filter($value)
    {
        return (int) ((string) $value);
    }
}
Filter/StringToLower.php000066600000004164151256604610011303 0ustar00<?php

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


/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';


/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_StringToLower implements Zend_Filter_Interface
{
    /**
     * Encoding for the input string
     *
     * @var string
     */
    protected $_encoding = null;

    /**
     * Set the input encoding for the given string
     *
     * @param  string $encoding
     * @throws Zend_Filter_Exception
     */
    public function setEncoding($encoding = null)
    {
        if (!function_exists('mb_strtolower')) {
            require_once 'Zend/Filter/Exception.php';
            throw new Zend_Filter_Exception('mbstring is required for this feature');
        }
        $this->_encoding = $encoding;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns the string $value, converting characters to lowercase as necessary
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        if ($this->_encoding) {
            return mb_strtolower((string) $value, $this->_encoding);
        }

        return strtolower((string) $value);
    }
}
Filter/Dir.php000066600000002564151256604610007241 0ustar00<?php

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


/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';


/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Dir implements Zend_Filter_Interface
{
    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns dirname($value)
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        return dirname((string) $value);
    }
}
Filter/HtmlEntities.php000066600000005762151256604610011137 0ustar00<?php

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


/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';


/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_HtmlEntities implements Zend_Filter_Interface
{
    /**
     * Corresponds to second htmlentities() argument
     *
     * @var integer
     */
    protected $_quoteStyle;

    /**
     * Corresponds to third htmlentities() argument
     *
     * @var string
     */
    protected $_charSet;

    /**
     * Sets filter options
     *
     * @param  integer $quoteStyle
     * @param  string  $charSet
     * @return void
     */
    public function __construct($quoteStyle = ENT_COMPAT, $charSet = 'ISO-8859-1')
    {
        $this->_quoteStyle = $quoteStyle;
        $this->_charSet    = $charSet;
    }

    /**
     * Returns the quoteStyle option
     *
     * @return integer
     */
    public function getQuoteStyle()
    {
        return $this->_quoteStyle;
    }

    /**
     * Sets the quoteStyle option
     *
     * @param  integer $quoteStyle
     * @return Zend_Filter_HtmlEntities Provides a fluent interface
     */
    public function setQuoteStyle($quoteStyle)
    {
        $this->_quoteStyle = $quoteStyle;
        return $this;
    }

    /**
     * Returns the charSet option
     *
     * @return string
     */
    public function getCharSet()
    {
        return $this->_charSet;
    }

    /**
     * Sets the charSet option
     *
     * @param  string $charSet
     * @return Zend_Filter_HtmlEntities Provides a fluent interface
     */
    public function setCharSet($charSet)
    {
        $this->_charSet = $charSet;
        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns the string $value, converting characters to their corresponding HTML entity
     * equivalents where they exist
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        return htmlentities((string) $value, $this->_quoteStyle, $this->_charSet);
    }
}
Filter/BaseName.php000066600000002600151256604610010165 0ustar00<?php

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


/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';


/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_BaseName implements Zend_Filter_Interface
{
    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns basename($value)
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        return basename((string) $value);
    }
}
Filter/StringTrim.php000066600000005012151256604610010614 0ustar00<?php

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


/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';


/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_StringTrim implements Zend_Filter_Interface
{
    /**
     * List of characters provided to the trim() function
     *
     * If this is null, then trim() is called with no specific character list,
     * and its default behavior will be invoked, trimming whitespace.
     *
     * @var string|null
     */
    protected $_charList;

    /**
     * Sets filter options
     *
     * @param  string $charList
     * @return void
     */
    public function __construct($charList = null)
    {
        $this->_charList = $charList;
    }

    /**
     * Returns the charList option
     *
     * @return string|null
     */
    public function getCharList()
    {
        return $this->_charList;
    }

    /**
     * Sets the charList option
     *
     * @param  string|null $charList
     * @return Zend_Filter_StringTrim Provides a fluent interface
     */
    public function setCharList($charList)
    {
        $this->_charList = $charList;
        return $this;
    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns the string $value with characters stripped from the beginning and end
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        if (null === $this->_charList) {
            return trim((string) $value);
        } else {
            return trim((string) $value, $this->_charList);
        }
    }
}
Filter/Exception.php000066600000002152151256604610010452 0ustar00<?php

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


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


/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Exception extends Zend_Exception
{}
Filter/Alnum.php000066600000006531151256604610007575 0ustar00<?php

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Alnum.php 12751 2008-11-21 18:30:48Z yoshida@zend.co.jp $
 */


/**
 * @see Zend_Filter_Interface
 */
require_once 'Zend/Filter/Interface.php';
/**
 * @see Zend_Locale
 */
require_once 'Zend/Locale.php';

/**
 * @category   Zend
 * @package    Zend_Filter
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Filter_Alnum implements Zend_Filter_Interface
{
    /**
     * Whether to allow white space characters; off by default
     *
     * @var boolean
     */
    public $allowWhiteSpace;

    /**
     * Is PCRE is compiled with UTF-8 and Unicode support
     *
     * @var mixed
     **/
    protected static $_unicodeEnabled;

    /**
     * Locale in browser.
     *
     * @var Zend_Locale object
     */
    protected $_locale;

    /**
     * The Alphabet means english alphabet.
     *
     * @var boolean
     */
    protected static $_meansEnglishAlphabet;

    /**
     * Sets default option values for this instance
     *
     * @param  boolean $allowWhiteSpace
     * @return void
     */
    public function __construct($allowWhiteSpace = false)
    {
        $this->allowWhiteSpace = (boolean) $allowWhiteSpace;
        if (null === self::$_unicodeEnabled) {
            self::$_unicodeEnabled = (@preg_match('/\pL/u', 'a')) ? true : false;
        }

        if (null === self::$_meansEnglishAlphabet) {
            $this->_locale = new Zend_Locale('auto');
            self::$_meansEnglishAlphabet = in_array($this->_locale->getLanguage(),
                                                    array('ja', 'ko', 'zh')
                                                    );
        }

    }

    /**
     * Defined by Zend_Filter_Interface
     *
     * Returns the string $value, removing all but alphabetic and digit characters
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        $whiteSpace = $this->allowWhiteSpace ? '\s' : '';
        if (!self::$_unicodeEnabled) {
            // POSIX named classes are not supported, use alternative a-zA-Z0-9 match
            $pattern = '/[^a-zA-Z0-9' . $whiteSpace . ']/';
        } else if (self::$_meansEnglishAlphabet) {
            //The Alphabet means english alphabet.
            $pattern = '/[^a-zA-Z0-9'  . $whiteSpace . ']/u';
        } else {
            //The Alphabet means each language's alphabet.
            $pattern = '/[^\p{L}\p{N}' . $whiteSpace . ']/u';
        }

        return preg_replace($pattern, '', (string) $value);
    }
}
InfoCard/Xml/Assertion/Interface.php000066600000004400151256604610013361 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * The Interface required by any InfoCard Assertion Object implemented within the component
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_InfoCard_Xml_Assertion_Interface
{
    /**
     * Get the Assertion ID of the assertion
     *
     * @return string The Assertion ID
     */
    public function getAssertionID();

    /**
     * Return an array of attributes (claims) contained within the assertion
     *
     * @return array An array of attributes / claims within the assertion
     */
    public function getAttributes();

    /**
     * Get the Assertion URI for this type of Assertion
     *
     * @return string the Assertion URI
     */
    public function getAssertionURI();

    /**
     * Return an array of conditions which the assertions are predicated on
     *
     * @return array an array of conditions
     */
    public function getConditions();

    /**
     * Validate the conditions array returned from the getConditions() call
     *
     * @param array $conditions An array of condtions for the assertion taken from getConditions()
     * @return mixed Boolean true on success, an array of condition, error message on failure
     */
    public function validateConditions(Array $conditions);
}
InfoCard/Xml/Assertion/Saml.php000066600000021447151256604610012367 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Saml.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Xml_Element
 */
require_once 'Zend/InfoCard/Xml/Element.php';

/**
 * Zend_InfoCard_Xml_Assertion_Interface
 */
require_once 'Zend/InfoCard/Xml/Assertion/Interface.php';

/**
 * A Xml Assertion Document in SAML Token format
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Xml_Assertion_Saml
    extends Zend_InfoCard_Xml_Element
    implements Zend_InfoCard_Xml_Assertion_Interface
{

    /**
     * Audience Restriction Condition
     */
    const CONDITION_AUDIENCE = 'AudienceRestrictionCondition';

    /**
     * The URI for a 'bearer' confirmation
     */
    const CONFIRMATION_BEARER = 'urn:oasis:names:tc:SAML:1.0:cm:bearer';

    /**
     * The amount of time in seconds to buffer when checking conditions to ensure
     * that differences between client/server clocks don't interfer too much
     */
    const CONDITION_TIME_ADJ = 3600; // +- 5 minutes

    protected function _getServerName() {
        return $_SERVER['SERVER_NAME'];
    }

    protected function _getServerPort() {
        return $_SERVER['SERVER_PORT'];
    }

    /**
     * Validate the conditions array returned from the getConditions() call
     *
     * @param array $conditions An array of condtions for the assertion taken from getConditions()
     * @return mixed Boolean true on success, an array of condition, error message on failure
     */
    public function validateConditions(Array $conditions)
    {

        $currentTime = time();

        if(!empty($conditions)) {

            foreach($conditions as $condition => $conditionValue) {
                switch(strtolower($condition)) {
                    case 'audiencerestrictioncondition':

                        $serverName = $this->_getServerName();
                        $serverPort = $this->_getServerPort();

                        $self_aliases[] = $serverName;
                        $self_aliases[] = "{{$serverName}:{$serverPort}";

                        $found = false;
                        if(is_array($conditionValue)) {
                            foreach($conditionValue as $audience) {

                                list(,,$audience) = explode('/', $audience);
                                if(in_array($audience, $self_aliases)) {
                                    $found = true;
                                    break;
                                }
                            }
                        }

                        if(!$found) {
                            return array($condition, 'Could not find self in allowed audience list');
                        }

                        break;
                    case 'notbefore':
                        $notbeforetime = strtotime($conditionValue);

                        if($currentTime < $notbeforetime) {
                            if($currentTime + self::CONDITION_TIME_ADJ < $notbeforetime) {
                                return array($condition, 'Current time is before specified window');
                            }
                        }

                        break;
                    case 'notonorafter':
                        $notonoraftertime = strtotime($conditionValue);

                        if($currentTime >= $notonoraftertime) {
                            if($currentTime - self::CONDITION_TIME_ADJ >= $notonoraftertime) {
                                return array($condition, 'Current time is after specified window');
                            }
                        }

                        break;

                }
            }
        }
        return true;
    }

    /**
     * Get the Assertion URI for this type of Assertion
     *
     * @return string the Assertion URI
     */
    public function getAssertionURI()
    {
        return Zend_InfoCard_Xml_Assertion::TYPE_SAML;
    }

    /**
     * Get the Major Version of the SAML Assertion
     *
     * @return integer The major version number
     */
    public function getMajorVersion()
    {
        return (int)(string)$this['MajorVersion'];
    }

    /**
     * The Minor Version of the SAML Assertion
     *
     * @return integer The minor version number
     */
    public function getMinorVersion()
    {
        return (int)(string)$this['MinorVersion'];
    }

    /**
     * Get the Assertion ID of the assertion
     *
     * @return string The Assertion ID
     */
    public function getAssertionID()
    {
        return (string)$this['AssertionID'];
    }

    /**
     * Get the Issuer URI of the assertion
     *
     * @return string the URI of the assertion Issuer
     */
    public function getIssuer()
    {
        return (string)$this['Issuer'];
    }

    /**
     * Get the Timestamp of when the assertion was issued
     *
     * @return integer a UNIX timestamp representing when the assertion was issued
     */
    public function getIssuedTimestamp()
    {
        return strtotime((string)$this['IssueInstant']);
    }

    /**
     * Return an array of conditions which the assertions are predicated on
     *
     * @throws Zend_InfoCard_Xml_Exception
     * @return array an array of conditions
     */
    public function getConditions()
    {

        list($conditions) = $this->xpath("//saml:Conditions");

        if(!($conditions instanceof Zend_InfoCard_Xml_Element)) {
            throw new Zend_InfoCard_Xml_Exception("Unable to find the saml:Conditions block");
        }

        $retval = array();

        foreach($conditions->children('urn:oasis:names:tc:SAML:1.0:assertion') as $key => $value) {
            switch($key) {
                case self::CONDITION_AUDIENCE:
                    foreach($value->children('urn:oasis:names:tc:SAML:1.0:assertion') as $audience_key => $audience_value) {
                        if($audience_key == 'Audience') {
                            $retval[$key][] = (string)$audience_value;
                        }
                    }
                    break;
            }
        }

        $retval['NotBefore'] = (string)$conditions['NotBefore'];
        $retval['NotOnOrAfter'] = (string)$conditions['NotOnOrAfter'];

        return $retval;
    }

    /**
     * Get they KeyInfo element for the Subject KeyInfo block
     *
     * @todo Not Yet Implemented
     * @ignore
     */
    public function getSubjectKeyInfo()
    {
        /**
         * @todo Not sure if this is part of the scope for now..
         */

        if($this->getConfirmationMethod() == self::CONFIRMATION_BEARER) {
            throw new Zend_InfoCard_Xml_Exception("Cannot get Subject Key Info when Confirmation Method was Bearer");
        }
    }

    /**
     * Return the Confirmation Method URI used in the Assertion
     *
     * @return string The confirmation method URI
     */
    public function getConfirmationMethod()
    {
        list($confirmation) = $this->xPath("//saml:ConfirmationMethod");
        return (string)$confirmation;
    }

    /**
     * Return an array of attributes (claims) contained within the assertion
     *
     * @return array An array of attributes / claims within the assertion
     */
    public function getAttributes()
    {
        $attributes = $this->xPath('//saml:Attribute');

        $retval = array();
        foreach($attributes as $key => $value) {

            $retkey = (string)$value['AttributeNamespace'].'/'.(string)$value['AttributeName'];

            $retval[$retkey]['name'] = (string)$value['AttributeName'];
            $retval[$retkey]['namespace'] = (string)$value['AttributeNamespace'];

            list($aValue) = $value->children('urn:oasis:names:tc:SAML:1.0:assertion');
            $retval[$retkey]['value'] = (string)$aValue;
        }

        return $retval;
    }
}
InfoCard/Xml/EncryptedData/XmlEnc.php000066600000004276151256604610013442 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: XmlEnc.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Xml_EncryptedData/Abstract.php
 */
require_once 'Zend/InfoCard/Xml/EncryptedData/Abstract.php';

/**
 * An XmlEnc formatted EncryptedData XML block
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Xml_EncryptedData_XmlEnc extends Zend_InfoCard_Xml_EncryptedData_Abstract
{

    /**
     * Returns the Encrypted CipherValue block from the EncryptedData XML document
     *
     * @throws Zend_InfoCard_Xml_Exception
     * @return string The value of the CipherValue block base64 encoded
     */
    public function getCipherValue()
    {
        $this->registerXPathNamespace('enc', 'http://www.w3.org/2001/04/xmlenc#');

        list(,$cipherdata) = $this->xpath("//enc:CipherData");

        if(!($cipherdata instanceof Zend_InfoCard_Xml_Element)) {
            throw new Zend_InfoCard_Xml_Exception("Unable to find the enc:CipherData block");
        }

        list(,$ciphervalue) = $cipherdata->xpath("//enc:CipherValue");

        if(!($ciphervalue instanceof Zend_InfoCard_Xml_Element)) {
            throw new Zend_InfoCard_Xml_Exception("Unable to fidn the enc:CipherValue block");
        }

        return (string)$ciphervalue;
    }
}
InfoCard/Xml/EncryptedData/Abstract.php000066600000006057151256604610014016 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Abstract.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Xml_Element
 */
require_once 'Zend/InfoCard/Xml/Element.php';

/**
 * Zend_InfoCard_Xml_KeyInfo
 */
require_once 'Zend/InfoCard/Xml/KeyInfo.php';

/**
 * An abstract class representing a generic EncryptedData XML block. This class is extended
 * into a specific type of EncryptedData XML block (i.e. XmlEnc) as necessary
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_InfoCard_Xml_EncryptedData_Abstract extends Zend_InfoCard_Xml_Element
{

    /**
     * Returns the KeyInfo Block
     *
     * @return Zend_InfoCard_Xml_KeyInfo_Abstract
     */
    public function getKeyInfo()
    {
        return Zend_InfoCard_Xml_KeyInfo::getInstance($this->KeyInfo[0]);
    }

    /**
     * Return the Encryption method used to encrypt the assertion document
     * (the symmetric cipher)
     *
     * @throws Zend_InfoCard_Xml_Exception
     * @return string The URI of the Symmetric Encryption Method used
     */
    public function getEncryptionMethod()
    {

        /**
         * @todo This is pretty hacky unless we can always be confident that the first
         * EncryptionMethod block is the correct one (the AES or compariable symetric algorithm)..
         * the second is the PK method if provided.
         */
        list($encryption_method) = $this->xpath("//enc:EncryptionMethod");

        if(!($encryption_method instanceof Zend_InfoCard_Xml_Element)) {
            throw new Zend_InfoCard_Xml_Exception("Unable to find the enc:EncryptionMethod symmetric encryption block");
        }

        $dom = self::convertToDOM($encryption_method);

        if(!$dom->hasAttribute('Algorithm')) {
            throw new Zend_InfoCard_Xml_Exception("Unable to determine the encryption algorithm in the Symmetric enc:EncryptionMethod XML block");
        }

        return $dom->getAttribute('Algorithm');
    }

    /**
     * Returns the value of the encrypted block
     *
     * @return string the value of the encrypted CipherValue block
     */
    abstract function getCipherValue();
}
InfoCard/Xml/Security/Transform.php000066600000007500151256604610013300 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Transform.php 9094 2008-03-30 18:36:55Z thomas $
 */

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

/**
 * A class to create a transform rule set based on XML URIs and then apply those rules
 * in the correct order to a given XML input
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Xml_Security_Transform
{
    /**
     * A list of transforms to apply
     *
     * @var array
     */
    protected $_transformList = array();

    /**
     * Returns the name of the transform class based on a given URI
     *
     * @throws Zend_InfoCard_Xml_Security_Exception
     * @param string $uri The transform URI
     * @return string The transform implementation class name
     */
    protected function _findClassbyURI($uri)
    {
        switch($uri) {
            case 'http://www.w3.org/2000/09/xmldsig#enveloped-signature':
                return 'Zend_InfoCard_Xml_Security_Transform_EnvelopedSignature';
            case 'http://www.w3.org/2001/10/xml-exc-c14n#':
                return 'Zend_InfoCard_Xml_Security_Transform_XmlExcC14N';
            default:
                throw new Zend_InfoCard_Xml_Security_Exception("Unknown or Unsupported Transformation Requested");
        }
    }

    /**
     * Add a Transform URI to the list of transforms to perform
     *
     * @param string $uri The Transform URI
     * @return Zend_InfoCard_Xml_Security_Transform
     */
    public function addTransform($uri)
    {
        $class = $this->_findClassbyURI($uri);

        $this->_transformList[] = array('uri' => $uri,
                                        'class' => $class);
        return $this;
    }

    /**
     * Return the list of transforms to perform
     *
     * @return array The list of transforms
     */
    public function getTransformList()
    {
        return $this->_transformList;
    }

    /**
     * Apply the transforms in the transform list to the input XML document
     *
     * @param string $strXmlDocument The input XML
     * @return string The XML after the transformations have been applied
     */
    public function applyTransforms($strXmlDocument)
    {
        foreach($this->_transformList as $transform) {
            Zend_Loader::loadClass($transform['class']);

            $transformer = new $transform['class'];

            // We can't really test this check because it would require logic changes in the component itself
            // @codeCoverageIgnoreStart
            if(!($transformer instanceof Zend_InfoCard_Xml_Security_Transform_Interface)) {
                throw new Zend_InfoCard_Xml_Security_Exception("Transforms must implement the Transform Interface");
            }
            // @codeCoverageIgnoreEnd

            $strXmlDocument = $transformer->transform($strXmlDocument);
        }

        return $strXmlDocument;
    }
}
InfoCard/Xml/Security/Transform/XmlExcC14N.php000066600000004175151256604610015073 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: XmlExcC14N.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Xml_Security_Transform_Interface
 */
require_once 'Zend/InfoCard/Xml/Security/Transform/Interface.php';

/**
 * Zend_InfoCard_Xml_Security_Transform_Exception
 */
require_once 'Zend/InfoCard/Xml/Security/Transform/Exception.php';

/**
 * A Transform to perform C14n XML Exclusive Canonicalization
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Xml_Security_Transform_XmlExcC14N
    implements Zend_InfoCard_Xml_Security_Transform_Interface
{
    /**
     * Transform the input XML based on C14n XML Exclusive Canonicalization rules
     *
     * @throws Zend_InfoCard_Xml_Security_Transform_Exception
     * @param string $strXMLData The input XML
     * @return string The output XML
     */
    public function transform($strXMLData)
    {
        $dom = new DOMDocument();
        $dom->loadXML($strXMLData);

        if(method_exists($dom, 'C14N')) {
            return $dom->C14N(true, false);
        }

        throw new Zend_InfoCard_Xml_Security_Transform_Exception("This transform requires the C14N() method to exist in the DOM extension");
    }
}
InfoCard/Xml/Security/Transform/EnvelopedSignature.php000066600000004217151256604610017105 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: EnvelopedSignature.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Xml_Security_Transform_Interface
 */
require_once 'Zend/InfoCard/Xml/Security/Transform/Interface.php';

/**
 * Zend_InfoCard_Xml_Security_Transform_Exception
 */
require_once 'Zend/InfoCard/Xml/Security/Transform/Exception.php';

/**
 * A object implementing the EnvelopedSignature XML Transform
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Xml_Security_Transform_EnvelopedSignature
    implements Zend_InfoCard_Xml_Security_Transform_Interface
{
    /**
     * Transforms the XML Document according to the EnvelopedSignature Transform
     *
     * @throws Zend_InfoCard_Xml_Security_Transform_Exception
     * @param string $strXMLData The input XML data
     * @return string the transformed XML data
     */
    public function transform($strXMLData)
    {
        $sxe = simplexml_load_string($strXMLData);

        if(!$sxe->Signature) {
            throw new Zend_InfoCard_Xml_Security_Transform_Exception("Unable to locate Signature Block for EnvelopedSignature Transform");
        }

        unset($sxe->Signature);

        return $sxe->asXML();
    }
}
InfoCard/Xml/Security/Transform/Interface.php000066600000003007151256604610015176 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Interface for XML Security Transforms
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_InfoCard_Xml_Security_Transform_Interface
{
    /**
     * Transform the given XML string according to the transform rules
     * implemented by the object using this interface
     *
     * @throws Zend_InfoCard_Xml_Security_Transform_Exception
     * @param string $strXmlData the input XML
     * @return string the output XML
     */
    public function transform($strXmlData);
}
InfoCard/Xml/Security/Transform/Exception.php000066600000002427151256604610015241 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Xml_Security_Exception
 */
require_once 'Zend/InfoCard/Xml/Security/Exception.php';

/**
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Xml_Security
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Xml_Security_Transform_Exception extends Zend_InfoCard_Xml_Security_Exception 
{
}
InfoCard/Cipher/Pki/Adapter/Abstract.php000066600000005064151256604610014041 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Abstract.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Cipher_Pki_Interface
 */
require_once 'Zend/InfoCard/Cipher/Pki/Interface.php';

/**
 * Zend_InfoCard_Cipher_Exception
 */
require_once 'Zend/InfoCard/Cipher/Exception.php';

/**
 * An abstract class for public-key ciphers
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_InfoCard_Cipher_Pki_Adapter_Abstract implements Zend_InfoCard_Cipher_Pki_Interface
{
    /**
     * OAEP Padding public key encryption
     */
    const OAEP_PADDING = 1;

    /**
     * No padding public key encryption
     */
    const NO_PADDING = 2;

    /**
     * The type of padding to use
     *
     * @var integer one of the padding constants in this class
     */
    protected $_padding;

    /**
     * Set the padding of the public key encryption
     *
     * @throws Zend_InfoCard_Cipher_Exception
     * @param integer $padding One of the constnats in this class
     * @return Zend_InfoCard_Pki_Adapter_Abstract
     */
    public function setPadding($padding)
    {
        switch($padding) {
            case self::OAEP_PADDING:
            case self::NO_PADDING:
                $this->_padding = $padding;
                break;
            default:
                throw new Zend_InfoCard_Cipher_Exception("Invalid Padding Type Provided");
        }

        return $this;
    }

    /**
     * Retruns the public-key padding used
     *
     * @return integer One of the padding constants in this class
     */
    public function getPadding()
    {
        return $this->_padding;
    }
}
InfoCard/Cipher/Pki/Adapter/Rsa.php000066600000007730151256604610013025 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Rsa.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Cipher_Pki_Adapter_Abstract
 */
require_once 'Zend/InfoCard/Cipher/Pki/Adapter/Abstract.php';

/**
 * Zend_InfoCard_Cipher_Pki_Rsa_Interface
 */
require_once 'Zend/InfoCard/Cipher/Pki/Rsa/Interface.php';

/**
 * RSA Public Key Encryption Cipher Object for the InfoCard component. Relies on OpenSSL
 * to implement the RSA algorithm
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Cipher_Pki_Adapter_Rsa
    extends Zend_InfoCard_Cipher_Pki_Adapter_Abstract
    implements Zend_InfoCard_Cipher_Pki_Rsa_Interface
{

    /**
     * Object Constructor
     *
     * @param integer $padding The type of Padding to use
     */
    public function __construct($padding = Zend_InfoCard_Cipher_Pki_Adapter_Abstract::NO_PADDING)
    {
        // Can't test this..
        // @codeCoverageIgnoreStart
        if(!extension_loaded('openssl')) {
            throw new Zend_InfoCard_Cipher_Exception("Use of this PKI RSA Adapter requires the openssl extension loaded");
        }
        // @codeCoverageIgnoreEnd

        $this->setPadding($padding);
    }

    /**
     * Decrypts RSA encrypted data using the given private key
     *
     * @throws Zend_InfoCard_Cipher_Exception
     * @param string $encryptedData The encrypted data in binary format
     * @param string $privateKey The private key in binary format
     * @param string $password The private key passphrase
     * @param integer $padding The padding to use during decryption (of not provided object value will be used)
     * @return string The decrypted data
     */
    public function decrypt($encryptedData, $privateKey, $password = null, $padding = null)
    {
        $private_key = openssl_pkey_get_private(array($privateKey, $password));

        if(!$private_key) {
            throw new Zend_InfoCard_Cipher_Exception("Failed to load private key");
        }

        if(!is_null($padding)) {
            try {
                $this->setPadding($padding);
            } catch(Exception $e) {
                openssl_free_key($private_key);
                throw $e;
            }
        }

        switch($this->getPadding()) {
            case self::NO_PADDING:
                $openssl_padding = OPENSSL_NO_PADDING;
                break;
            case self::OAEP_PADDING:
                $openssl_padding = OPENSSL_PKCS1_OAEP_PADDING;
                break;
        }

        $result = openssl_private_decrypt($encryptedData, $decryptedData, $private_key, $openssl_padding);

        openssl_free_key($private_key);

        if(!$result) {
            throw new Zend_InfoCard_Cipher_Exception("Unable to Decrypt Value using provided private key");
        }

        if($this->getPadding() == self::NO_PADDING) {
            $decryptedData = substr($decryptedData, 2);
            $start = strpos($decryptedData, 0) + 1;
            $decryptedData = substr($decryptedData, $start);
        }

        return $decryptedData;
    }
}
InfoCard/Cipher/Pki/Rsa/Interface.php000066600000003646151256604610013347 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Cipher_PKI_Adapter_Abstract
 */
require_once 'Zend/InfoCard/Cipher/Pki/Adapter/Abstract.php';

/**
 * The interface which defines the RSA Public-key encryption object
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_InfoCard_Cipher_Pki_Rsa_Interface
{
    /**
     * Decrypts RSA encrypted data using the given private key
     *
     * @throws Zend_InfoCard_Cipher_Exception
     * @param string $encryptedData The encrypted data in binary format
     * @param string $privateKey The private key in binary format
     * @param string $password The private key passphrase
     * @param integer $padding The padding to use during decryption (of not provided object value will be used)
     * @return string The decrypted data
     */
    public function decrypt($encryptedData, $privateKey, $password = null, $padding = Zend_InfoCard_Cipher_Pki_Adapter_Abstract::NO_PADDING);
}
InfoCard/Cipher/Symmetric/Aes128cbc/Interface.php000066600000002503151256604610015455 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Cipher_Symmetric_Aes256cbc_Interface
 */
require_once 'Zend/InfoCard/Cipher/Symmetric/Aes256cbc/Interface.php';

/**
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_InfoCard_Cipher_Symmetric_Aes128cbc_Interface 
    extends Zend_InfoCard_Cipher_Symmetric_Aes256cbc_Interface 
{
}
InfoCard/Cipher/Symmetric/Aes256cbc/Interface.php000066600000002307151256604610015461 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Interface.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_InfoCard_Cipher_Symmetric_Aes256cbc_Interface
{
    public function decrypt($encryptedData, $decryptionKey, $iv_length = null);
}
InfoCard/Cipher/Symmetric/Adapter/Abstract.php000066600000002451151256604610015267 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Abstract.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Cipher_Symmetric_Interface
 */
require_once 'Zend/InfoCard/Cipher/Symmetric/Interface.php';

/**
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_InfoCard_Cipher_Symmetric_Adapter_Abstract 
    implements Zend_InfoCard_Cipher_Symmetric_Interface 
{
}
InfoCard/Cipher/Symmetric/Adapter/Aes128cbc.php000066600000002615151256604610015141 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Aes128cbc.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Cipher_Symmetric_Adapter_Aes256cbc
 */
require_once 'Zend/InfoCard/Cipher/Symmetric/Adapter/Aes256cbc.php';

/**
 * Implements AES128 with CBC encryption implemented using the mCrypt extension
 * 
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Cipher_Symmetric_Adapter_Aes128cbc 
    extends Zend_InfoCard_Cipher_Symmetric_Adapter_Aes256cbc 
{
}
InfoCard/Cipher/Symmetric/Adapter/Aes256cbc.php000066600000007310151256604610015140 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Aes256cbc.php 9094 2008-03-30 18:36:55Z thomas $
 */

/**
 * Zend_InfoCard_Cipher_Symmetric_Adapter_Abstract
 */
require_once 'Zend/InfoCard/Cipher/Symmetric/Adapter/Abstract.php';

/**
 * Zend_InfoCard_Cipher_Symmetric_Aes256cbc_Interface
 */
require_once 'Zend/InfoCard/Cipher/Symmetric/Aes256cbc/Interface.php';

/**
 * Zend_InfoCard_Cipher_Exception
 */
require_once 'Zend/InfoCard/Cipher/Exception.php';

/**
 * Implements AES256 with CBC encryption implemented using the mCrypt extension
 *
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage Zend_InfoCard_Cipher
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_InfoCard_Cipher_Symmetric_Adapter_Aes256cbc
    extends Zend_InfoCard_Cipher_Symmetric_Adapter_Abstract
    implements Zend_InfoCard_Cipher_Symmetric_Aes256cbc_Interface
{
    /**
     * The MCRYPT Cipher constant for this encryption
     */
    const MCRYPT_CIPHER = MCRYPT_RIJNDAEL_128;

    /**
     * The MCRYPT Mode constant for this encryption
     */
    const MCRYPT_MODE   = MCRYPT_MODE_CBC;

    /**
     * The default length of the IV to use
     */
    const IV_LENGTH     = 16;

    /**
     * The object constructor
     *
     * @throws Zend_InfoCard_Cipher_Exception
     */
    public function __construct()
    {
        // Can't test for this
        // @codeCoverageIgnoreStart
        if(!extension_loaded('mcrypt')) {
            throw new Zend_InfoCard_Cipher_Exception("Use of the AES256CBC Cipher requires the mcrypt extension");
        }
        // @codeCoveregIgnoreEnd
    }

    /**
     * Decrypts data using the AES Algorithm using the mCrypt extension
     *
     * @throws Zend_InfoCard_Cipher_Exception
     * @param string $encryptedData The encrypted data in binary format
     * @param string $decryptionKey The decryption key
     * @param integer $iv_length The IV length to use
     * @return string the decrypted data with any terminating nulls removed
     */
    public function decrypt($encryptedData, $decryptionKey, $iv_length = null)
    {

        $iv_length = is_null($iv_length) ? self::IV_LENGTH : $iv_length;

        $mcrypt_iv = null;

        if($iv_length > 0) {
             $mcrypt_iv = substr($encryptedData, 0, $iv_length);
            $encryptedData = substr($encryptedData, $iv_length);
        }

        $decrypted = mcrypt_decrypt(self::MCRYPT_CIPHER, $decryptionKey, $encryptedData, self::MCRYPT_MODE, $mcrypt_iv);

        if(!$decrypted) {
            throw new Zend_InfoCard_Cipher_Exception("Failed to decrypt data using AES256CBC Algorithm");
        }

        $decryptedLength = strlen($decrypted);
        $paddingLength = substr($decrypted, $decryptedLength -1, 1);
        $decrypted = substr($decrypted, 0, $decryptedLength - ord($paddingLength));

        return rtrim($decrypted, "\0");
    }
}
Service/ReCaptcha/MailHide/Exception.php000066600000002247151256604610014140 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

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

/**
 * Zend_Service_ReCaptcha_MailHide_Exception
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage ReCaptcha
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Service_ReCaptcha_MailHide_Exception extends Zend_Exception
{}Service/Nirvanix/Namespace/Imfs.php000066600000007570151256604610013270 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

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

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

        return $resp->getBody();
    }

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

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

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

}Service/Nirvanix/Namespace/Base.php000066600000013030151256604610013230 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Nirvanix
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
 
/**
 * @see Zend_Http_Client
 */
require_once 'Zend/Http/Client.php';

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * Make a complete URI from an RPC method name.  All Nirvanix REST
     * service URIs use the same format.
     * 
     * @param  string  $methodName  RPC method name
     * @return string    
     */
    protected function _makeUri($methodName)
    {
        $methodName = ucfirst($methodName);
        return "{$this->_host}/ws/{$this->_namespace}/{$methodName}.ashx";
    }
    
    /**
     * All Nirvanix REST service calls return an XML payload.  This method
     * makes a Zend_Service_Nirvanix_Response from that XML payload.  
     *
     * @param  Zend_Http_Response  $httpResponse  Raw response from Nirvanix
     * @return Zend_Service_Nirvanix_Response     Wrapped response
     */
    protected function _wrapResponse($httpResponse)
    {
        return new Zend_Service_Nirvanix_Response($httpResponse->getBody());
    }
}Service/Technorati/TagsResult.php000066600000004771151256604610013075 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: TagsResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_Result 
 */
require_once 'Zend/Service/Technorati/Result.php';


/**
 * Represents a single Technorati TopTags or BlogPostTags query result object. 
 * It is never returned as a standalone object, 
 * but it always belongs to a valid Zend_Service_Technorati_TagsResultSet object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_TagsResult extends Zend_Service_Technorati_Result
{
    /**
     * Name of the tag.
     * 
     * @var     string
     * @access  protected
     */
    protected $_tag;
    
    /**
     * Number of posts containing this tag.
     * 
     * @var     int
     * @access  protected
     */
    protected $_posts;
    

    /**
     * Constructs a new object object from DOM Document.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $this->_fields = array( '_tag'   => 'tag',
                                '_posts' => 'posts');
        parent::__construct($dom);
        
        // filter fields
        $this->_tag   = (string) $this->_tag;
        $this->_posts = (int) $this->_posts;
    }

    /**
     * Returns the tag name.
     * 
     * @return  string
     */
    public function getTag() {
        return $this->_tag;
    }
    
    /**
     * Returns the number of posts.
     * 
     * @return  int
     */
    public function getPosts() {
        return $this->_posts;
    }
}
Service/Technorati/Exception.php000066600000002306151256604610012726 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 */


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


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

Service/Technorati/GetInfoResult.php000066600000005520151256604610013523 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: GetInfoResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Represents a single Technorati GetInfo query result object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_GetInfoResult
{
    /**
     * Technorati author
     *
     * @var     Zend_Service_Technorati_Author
     * @access  protected
     */
    protected $_author;

    /**
     * A list of weblogs claimed by this author
     *
     * @var     array
     * @access  protected
     */
    protected $_weblogs = array();


    /**
     * Constructs a new object object from DOM Document.
     *
     * @param   DomDocument $dom the ReST fragment for this object
     */
    public function __construct(DomDocument $dom)
    {
        $xpath = new DOMXPath($dom);

        /**
         * @see Zend_Service_Technorati_Author
         */
        require_once 'Zend/Service/Technorati/Author.php';

        $result = $xpath->query('//result');
        if ($result->length == 1) {
            $this->_author = new Zend_Service_Technorati_Author($result->item(0));
        }

        /**
         * @see Zend_Service_Technorati_Weblog
         */
        require_once 'Zend/Service/Technorati/Weblog.php';

        $result = $xpath->query('//item/weblog');
        if ($result->length >= 1) {
            foreach ($result as $weblog) {
                $this->_weblogs[] = new Zend_Service_Technorati_Weblog($weblog);
            }
        }
    }


    /**
     * Returns the author associated with queried username.
     * 
     * @return  Zend_Service_Technorati_Author
     */
    public function getAuthor() {
        return $this->_author;
    }

    /**
     * Returns the collection of weblogs authored by queried username.
     * 
     * @return  array of Zend_Service_Technorati_Weblog
     */
    public function getWeblogs() {
        return $this->_weblogs;
    }

}
Service/Technorati/KeyInfoResult.php000066600000006376151256604610013546 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: KeyInfoResult.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Represents a single Technorati KeyInfo query result object.
 * It provides information about your Technorati API Key daily usage.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_KeyInfoResult
{
    /**
     * Technorati API key
     *
     * @var     string
     * @access  protected
     */
    protected $_apiKey;

    /**
     * Number of queries used today
     *
     * @var     int
     * @access  protected
     */
    protected $_apiQueries;

    /**
     * Total number of available queries per day
     *
     * @var     int
     * @access  protected
     */
    protected $_maxQueries;
    

    /**
     * Constructs a new object from DOM Element.
     * Parses given Key element from $dom and sets API key string.
     *
     * @param   DomElement $dom the ReST fragment for this object
     * @param   string $apiKey  the API Key string
     */
    public function __construct(DomDocument $dom, $apiKey = null)
    {
        // $this->_dom   = $dom;
        // $this->_xpath = new DOMXPath($dom);
        $xpath = new DOMXPath($dom);

        $this->_apiQueries   = (int) $xpath->query('/tapi/document/result/apiqueries/text()')->item(0)->data;
        $this->_maxQueries   = (int) $xpath->query('/tapi/document/result/maxqueries/text()')->item(0)->data;
        $this->setApiKey($apiKey);
    }
    
    
    /**
     * Returns API Key string.
     * 
     * @return  string  API Key string
     */
    public function getApiKey() {
        return $this->_apiKey;
    }
    
    /**
     * Returns the number of queries sent today.
     * 
     * @return  int     number of queries sent today
     */
    public function getApiQueries() {
        return $this->_apiQueries;
    }
    
    /**
     * Returns Key's daily query limit.
     * 
     * @return  int     maximum number of available queries per day
     */
    public function getMaxQueries() {
        return $this->_maxQueries;
    }
    
    
    /**
     * Sets API Key string.
     * 
     * @param   string $apiKey  the API Key
     * @return  Zend_Service_Technorati_KeyInfoResult $this instance
     */
    public function setApiKey($apiKey) {
        $this->_apiKey = $apiKey;
        return $this;
    }
}
Service/Technorati/Result.php000066600000007074151256604610012255 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Result.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Represents a single Technorati Search query result object. 
 * It is never returned as a standalone object, 
 * but it always belongs to a valid Zend_Service_Technorati_SearchResultSet object.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @abstract 
 */
abstract class Zend_Service_Technorati_Result
{
    /**
     * An associative array of 'fieldName' => 'xmlfieldtag'
     *
     * @var     array
     * @access  protected
     */
    protected $_fields;

    /**
     * The ReST fragment for this result object
     *
     * @var     DomElement
     * @access  protected
     */
    protected $_dom;

    /**
     * Object for $this->_dom
     *
     * @var     DOMXpath
     * @access  protected
     */
    protected $_xpath;


    /**
     * Constructs a new object from DOM Element.
     * Properties are automatically fetched from XML
     * according to array of $_fields to be read.
     *
     * @param   DomElement $result  the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $this->_xpath = new DOMXPath($dom->ownerDocument);
        $this->_dom = $dom;
        
        // default fields for all search results
        $fields = array();

        // merge with child's object fields
        $this->_fields = array_merge($this->_fields, $fields);

        // add results to appropriate fields
        foreach($this->_fields as $phpName => $xmlName) {
            $query = "./$xmlName/text()";
            $node = $this->_xpath->query($query, $this->_dom);
            if ($node->length == 1) {
                $this->{$phpName} = (string) $node->item(0)->data;
            }
        }
    }
    
    /**
     * Parses weblog node and sets weblog object.
     * 
     * @return  void
     */
    protected function _parseWeblog()
    {
        // weblog object field
        $result = $this->_xpath->query('./weblog', $this->_dom);
        if ($result->length == 1) {
            /**
             * @see Zend_Service_Technorati_Weblog
             */
            require_once 'Zend/Service/Technorati/Weblog.php';
            $this->_weblog = new Zend_Service_Technorati_Weblog($result->item(0));
        } else {
            $this->_weblog = null;
        }
    }

    /**
     * Returns the document fragment for this object as XML string.
     *
     * @return string   the document fragment for this object
     *                  converted into XML format
     */
    public function getXml()
    {
        return $this->_dom->ownerDocument->saveXML($this->_dom);
    }
}
Service/Technorati/TagsResultSet.php000066600000004315151256604610013543 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: TagsResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/** 
 * @see Zend_Service_Technorati_ResultSet 
 */
require_once 'Zend/Service/Technorati/ResultSet.php';


/**
 * Represents a Technorati TopTags or BlogPostTags queries result set.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_TagsResultSet extends Zend_Service_Technorati_ResultSet
{
    /**
     * Constructs a new object object from DOM Document.
     *
     * @param   DomDocument $dom the ReST fragment for this object
     */
    public function __construct(DomDocument $dom, $options = array())
    {
        parent::__construct($dom, $options);

        $this->_totalResultsReturned  = (int) $this->_xpath->evaluate("count(/tapi/document/item)");
        $this->_totalResultsAvailable = (int) $this->_totalResultsReturned;
    }

    /**
     * Implements Zend_Service_Technorati_ResultSet::current().
     *
     * @return Zend_Service_Technorati_TagsResult current result
     */
    public function current()
    {
        /**
         * @see Zend_Service_Technorati_TagsResult
         */
        require_once 'Zend/Service/Technorati/TagsResult.php';
        return new Zend_Service_Technorati_TagsResult($this->_results->item($this->_currentIndex));
    }
}
Service/Technorati/Utils.php000066600000010456151256604610012075 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Utils.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * Collection of utilities for various Zend_Service_Technorati classes.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_Utils
{
    /**
     * Parses, validates and returns a valid Zend_Uri object
     * from given $input.
     *
     * @param   string|Zend_Uri_Http $input
     * @return  null|Zend_Uri_Http
     * @throws  Zend_Service_Technorati_Exception
     * @static
     */
    public static function normalizeUriHttp($input)
    {
        // allow null as value
        if ($input === null) {
            return null;
        }

        /**
         * @see Zend_Uri
         */
        require_once 'Zend/Uri.php';
        if ($input instanceof Zend_Uri_Http) {
            $uri = $input;
        } else {
            try {
                $uri = Zend_Uri::factory((string) $input);
            }
            // wrap exception under Zend_Service_Technorati_Exception object
            catch (Exception $e) {
                /**
                 * @see Zend_Service_Technorati_Exception
                 */
                require_once 'Zend/Service/Technorati/Exception.php';
                throw new Zend_Service_Technorati_Exception($e->getMessage());
            }
        }

        // allow inly Zend_Uri_Http objects or child classes
        if (!($uri instanceof Zend_Uri_Http)) {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php'; 
            throw new Zend_Service_Technorati_Exception(
                "Invalid URL $uri, only HTTP(S) protocols can be used");
        }
        
        return $uri;
    }
    /**
     * Parses, validates and returns a valid Zend_Date object
     * from given $input.
     * 
     * $input can be either a string, an integer or a Zend_Date object.
     * If $input is string or int, it will be provided to Zend_Date as it is.
     * If $input is a Zend_Date object, the object instance will be returned. 
     *
     * @param   mixed|Zend_Date $input
     * @return  null|Zend_Date
     * @throws  Zend_Service_Technorati_Exception
     * @static
     */
    public static function normalizeDate($input)
    {
        /**
         * @see Zend_Date
         */
        require_once 'Zend/Date.php';
        /**
         * @see Zend_Locale
         */
        require_once 'Zend/Locale.php';
        
        // allow null as value and return valid Zend_Date objects
        if (($input === null) || ($input instanceof Zend_Date)) {
            return $input;
        }
        
        // due to a BC break as of ZF 1.5 it's not safe to use Zend_Date::isDate() here
        // see ZF-2524, ZF-2334
        if (@strtotime($input) !== FALSE) {
            return new Zend_Date($input);
        } else {
            /**
             * @see Zend_Service_Technorati_Exception
             */
            require_once 'Zend/Service/Technorati/Exception.php';
            throw new Zend_Service_Technorati_Exception("'$input' is not a valid Date/Time");
        }
    }
    
    /**
     * @todo public static function xpathQueryAndSet() {}
     */

    /**
     * @todo public static function xpathQueryAndSetIf() {}
     */

    /**
     * @todo public static function xpathQueryAndSetUnless() {}
     */
}
Service/Technorati/ResultSet.php000066600000017237151256604610012733 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: ResultSet.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Technorati_Result
 */
require_once 'Zend/Service/Technorati/Result.php';


/**
 * This is the most essential result set.
 * The scope of this class is to be extended by a query-specific child result set class,
 * and it should never be used to initialize a standalone object.
 *
 * Each of the specific result sets represents a collection of query-specific
 * Zend_Service_Technorati_Result objects.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @abstract
 */
abstract class Zend_Service_Technorati_ResultSet implements SeekableIterator
{
    /**
     * The total number of results available
     *
     * @var     int
     * @access  protected
     */
    protected $_totalResultsAvailable;

    /**
     * The number of results in this result set
     *
     * @var     int
     * @access  protected
     */
    protected $_totalResultsReturned;

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


    /**
     * A DomNodeList of results
     *
     * @var     DomNodeList
     * @access  protected
     */
    protected $_results;

    /**
     * Technorati API response document
     *
     * @var     DomDocument
     * @access  protected
     */
    protected $_dom;

    /**
     * Object for $this->_dom
     *
     * @var     DOMXpath
     * @access  protected
     */
    protected $_xpath;

    /**
     * XML string representation for $this->_dom
     *
     * @var     string
     * @access  protected
     */
    protected $_xml;

    /**
     * Current Item
     *
     * @var     int
     * @access  protected
     */
    protected $_currentIndex = 0;


    /**
     * Parses the search response and retrieves the results for iteration.
     *
     * @param   DomDocument $dom    the ReST fragment for this object
     * @param   array $options      query options as associative array
     */
    public function __construct(DomDocument $dom, $options = array())
    {
        $this->_init($dom, $options);

        // Technorati loves to make developer's life really hard
        // I must read query options in order to normalize a single way
        // to display start and limit.
        // The value is printed out in XML using many different tag names,
        // too hard to get it from XML

        // Additionally, the following tags should be always available
        // according to API documentation but... this is not the truth!
        // - querytime
        // - limit
        // - start (sometimes rankingstart)

        // query tag is only available for some requests, the same for url.
        // For now ignore them.

        //$start = isset($options['start']) ? $options['start'] : 1;
        //$limit = isset($options['limit']) ? $options['limit'] : 20;
        //$this->_firstResultPosition = $start;
    }

    /**
     * Initializes this object from a DomDocument response.
     *
     * Because __construct and __wakeup shares some common executions,
     * it's useful to group them in a single initialization method.
     * This method is called once each time a new instance is created
     * or a serialized object is unserialized.
     *
     * @param   DomDocument $dom    the ReST fragment for this object
     * @param   array $options      query options as associative array
     *      * @return  void
     */
    protected function _init(DomDocument $dom, $options = array())
    {
        $this->_dom     = $dom;
        $this->_xpath   = new DOMXPath($dom);

        $this->_results = $this->_xpath->query("//item");
    }

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


    /**
     * Number of available results.
     *
     * @return  int     total number of available results
     */
    public function totalResultsAvailable()
    {
        return (int) $this->_totalResultsAvailable;
    }

    /**
     * Implements SeekableIterator::current().
     *
     * @return  void
     * @throws  Zend_Service_Exception
     * @abstract
     */
    // abstract public function current();

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

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

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

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

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

    /**
     * Returns the response document as XML string.
     *
     * @return string   the response document converted into XML format
     */
    public function getXml()
    {
        return $this->_dom->saveXML();
    }

    /**
     * Overwrites standard __sleep method to make this object serializable.
     *
     * DomDocument and DOMXpath objects cannot be serialized.
     * This method converts them back to an XML string.
     *
     * @return void
     */
    public function __sleep() {
        $this->_xml     = $this->getXml();
        $vars = array_keys(get_object_vars($this));
        return array_diff($vars, array('_dom', '_xpath'));
    }

    /**
     * Overwrites standard __wakeup method to make this object unserializable.
     *
     * Restores object status before serialization.
     * Converts XML string into a DomDocument object and creates a valid
     * DOMXpath instance for given DocDocument.
     *
     * @return void
     */
    public function __wakeup() {
        $dom = new DOMDocument();
        $dom->loadXml($this->_xml);
        $this->_init($dom);
        $this->_xml = null; // reset XML content
    }
}
Service/Technorati/Author.php000066600000014761151256604610012242 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Author.php 8064 2008-02-16 10:58:39Z thomas $
 */


/**
 * @see Zend_Service_Technorati_Utils
 */
require_once 'Zend/Service/Technorati/Utils.php';


/**
 * Represents a weblog Author object. It usually belongs to a Technorati account.
 * 
 * @category   Zend
 * @package    Zend_Service
 * @subpackage Technorati
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_Technorati_Author
{
    /**
     * Author first name
     *
     * @var     string
     * @access  protected
     */
    protected $_firstName;

    /**
     * Author last name
     *
     * @var     string
     * @access  protected
     */
    protected $_lastName;
    
    /**
     * Technorati account username
     *
     * @var     string
     * @access  protected
     */
    protected $_username;
    
    /**
     * Technorati account description
     *
     * @var     string
     * @access  protected
     */
    protected $_description;

    /**
     * Technorati account biography
     *
     * @var     string
     * @access  protected
     */
    protected $_bio;

    /**
     * Technorati account thumbnail picture URL, if any
     *
     * @var     null|Zend_Uri_Http
     * @access  protected
     */
    protected $_thumbnailPicture;


    /**
     * Constructs a new object from DOM Element.
     *
     * @param   DomElement $dom the ReST fragment for this object
     */
    public function __construct(DomElement $dom)
    {
        $xpath = new DOMXPath($dom->ownerDocument);

        $result = $xpath->query('./firstname/text()', $dom);
        if ($result->length == 1) $this->setFirstName($result->item(0)->data);
        
        $result = $xpath->query('./lastname/text()', $dom);
        if ($result->length == 1) $this->setLastName($result->item(0)->data);
        
        $result = $xpath->query('./username/text()', $dom);
        if ($result->length == 1) $this->setUsername($result->item(0)->data);
        
        $result = $xpath->query('./description/text()', $dom);
        if ($result->length == 1) $this->setDescription($result->item(0)->data);
        
        $result = $xpath->query('./bio/text()', $dom);
        if ($result->length == 1) $this->setBio($result->item(0)->data);

        $result = $xpath->query('./thumbnailpicture/text()', $dom);
        if ($result->length == 1) $this->setThumbnailPicture($result->item(0)->data);
    }
    

    /**
     * Returns Author first name.
     * 
     * @return  string  Author first name
     */
    public function getFirstName() {
        return $this->_firstName;
    }

    /**
     * Returns Author last name.
     * 
     * @return  string  Author last name
     */
    public function getLastName() {
        return $this->_lastName;
    }

    /**
     * Returns Technorati account username.
     * 
     * @return  string  Technorati account username
     */
    public function getUsername() {
        return $this->_username;
    }

    /**
     * Returns Technorati account description.
     * 
     * @return  string  Technorati account description
     */
    public function getDescription() {
        return $this->_description;
    }

    /**
     * Returns Technorati account biography.
     * 
     * @return  string  Technorati account biography
     */
    public function getBio() {
        return $this->_bio;
    }

    /**
     * Returns Technorati account thumbnail picture.
     * 
     * @return  null|Zend_Uri_Http  Technorati account thumbnail picture
     */
    public function getThumbnailPicture() {
        return $this->_thumbnailPicture;
    }


    /**
     * Sets author first name.
     * 
     * @param   string $input   first Name input value 
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setFirstName($input) {
        $this->_firstName = (string) $input;
        return $this;
    }

    /**
     * Sets author last name.
     * 
     * @param   string $input   last Name input value 
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setLastName($input) {
        $this->_lastName = (string) $input;
        return $this;
    }

    /**
     * Sets Technorati account username.
     * 
     * @param   string $input   username input value 
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setUsername($input) {
        $this->_username = (string) $input;
        return $this;
    }

    /**
     * Sets Technorati account biography.
     * 
     * @param   string $input   biography input value
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setBio($input) {
        $this->_bio = (string) $input;
        return $this;
    }

    /**
     * Sets Technorati account description.
     * 
     * @param   string $input   description input value
     * @return  Zend_Service_Technorati_Author  $this instance
     */
    public function setDescription($input) {
        $this->_description = (string) $input;
        return $this;
    }

    /**
     * Sets Technorati account thumbnail picture.
     * 
     * @param   string|Zend_Uri_Http $input thumbnail picture URI
     * @return  Zend_Service_Technorati_Author  $this instance
     * @throws  Zend_Service_Technorati_Exception if $input is an invalid URI
     *          (via Zend_Service_Technorati_Utils::normalizeUriHttp)
     */
    public function setThumbnailPicture($input) {
        $this->_thumbnailPicture = Zend_Service_Technorati_Utils::normalizeUriHttp($input);
        return $this;
    }

}
Locale/Exception.php000066600000002145151256604610010426 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Locale
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Exception.php 8064 2008-02-16 10:58:39Z thomas $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


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


/**
 * @category   Zend
 * @package    Zend_Locale
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Locale_Exception extends Zend_Exception
{
}
Locale/Data/ru.xml000066600000503160151256604610010003 0ustar00<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "http://www.unicode.org/cldr/dtd/1.6/ldml.dtd">
<ldml>
	<identity>
		<version number="$Revision: 1.126 $"/>
		<generation date="$Date: 2008/06/26 03:47:58 $"/>
		<language type="ru"/>
	</identity>
	<localeDisplayNames>
		<localeDisplayPattern>
			<localePattern>{0} ({1})</localePattern>
			<localeSeparator>, </localeSeparator>
		</localeDisplayPattern>
		<languages>
			<language type="aa">афар</language>
			<language type="ab">абхазский</language>
			<language type="ace">ачехский</language>
			<language type="ach">ачоли</language>
			<language type="ada">адангме</language>
			<language type="ady">адыгейский</language>
			<language type="ae">авестийский</language>
			<language type="af">африкаанс</language>
			<language type="afa">афразийский язык</language>
			<language type="afh">африхили</language>
			<language type="ain">айну</language>
			<language type="ak">акан</language>
			<language type="akk">аккадский</language>
			<language type="ale">алеутский</language>
			<language type="alg">алгонкинские языки</language>
			<language type="alt">южноалтайский</language>
			<language type="am">амхарский</language>
			<language type="an">арагонский</language>
			<language type="ang">староанглийский</language>
			<language type="anp">ангика</language>
			<language type="apa">апачские языки</language>
			<language type="ar">арабский</language>
			<language type="arc">арамейский</language>
			<language type="arn">арауканский</language>
			<language type="arp">арапахо</language>
			<language type="art">искусственный язык</language>
			<language type="arw">аравакский</language>
			<language type="as">ассамский</language>
			<language type="ast">астурийский</language>
			<language type="ath">атапачские языки</language>
			<language type="aus">австралийский язык</language>
			<language type="av">аварский</language>
			<language type="awa">авадхи</language>
			<language type="ay">аймара</language>
			<language type="az">азербайджанский</language>
			<language type="ba">башкирский</language>
			<language type="bad">банда</language>
			<language type="bai">бамилеке языки</language>
			<language type="bal">белуджский</language>
			<language type="ban">балийский</language>
			<language type="bas">баса</language>
			<language type="bat">балтийский язык</language>
			<language type="be">белорусский</language>
			<language type="bej">беджа</language>
			<language type="bem">бемба</language>
			<language type="ber">берберский</language>
			<language type="bg">болгарский</language>
			<language type="bh">бихари</language>
			<language type="bho">бходжпури</language>
			<language type="bi">бислама</language>
			<language type="bik">бикольский</language>
			<language type="bin">бини</language>
			<language type="bla">сиксика</language>
			<language type="bm">бамбарийский</language>
			<language type="bn">бенгальский</language>
			<language type="bnt">банту</language>
			<language type="bo">тибетский</language>
			<language type="br">бретонский</language>
			<language type="bra">брауи</language>
			<language type="bs">боснийский</language>
			<language type="btk">батакский</language>
			<language type="bua">бурятский</language>
			<language type="bug">бугийский</language>
			<language type="byn">билин (блин)</language>
			<language type="ca">каталанский</language>
			<language type="cad">каддо</language>
			<language type="cai">язык индейцев Центральной Америки</language>
			<language type="car">кариб</language>
			<language type="cau">кавказский язык</language>
			<language type="cch">атсам</language>
			<language type="ce">чеченский</language>
			<language type="ceb">кебуано</language>
			<language type="cel">кельтские другие</language>
			<language type="ch">чаморро</language>
			<language type="chb">чибча</language>
			<language type="chg">чагатайский</language>
			<language type="chk">чукотский</language>
			<language type="chm">марийский (черемисский)</language>
			<language type="chn">чинук жаргон</language>
			<language type="cho">чоктав</language>
			<language type="chp">чипевайян</language>
			<language type="chr">чероки</language>
			<language type="chy">чейенн</language>
			<language type="cmc">чамский язык</language>
			<language type="co">корсиканский</language>
			<language type="cop">коптский</language>
			<language type="cpe">англо-креольские и пиджин</language>
			<language type="cpf">франко-креольские и пиджины</language>
			<language type="cpp">португало-креольские и пиджины</language>
			<language type="cr">криийский</language>
			<language type="crh">крымско-татарский</language>
			<language type="crp">креольские и пиджины</language>
			<language type="cs">чешский</language>
			<language type="csb">кашубианский</language>
			<language type="cu">церковнославянский</language>
			<language type="cus">кушитский язык</language>
			<language type="cv">чувашский</language>
			<language type="cy">валлийский</language>
			<language type="da">датский</language>
			<language type="dak">дакота</language>
			<language type="dar">даргва</language>
			<language type="day">даяк</language>
			<language type="de">немецкий</language>
			<language type="de_AT">австрийский немецкий</language>
			<language type="de_CH">Швейцарский верхненемецкий</language>
			<language type="del">делаварский</language>
			<language type="den">славянский</language>
			<language type="dgr">догриб</language>
			<language type="din">динка</language>
			<language type="doi">догри</language>
			<language type="dra">дравидийский язык</language>
			<language type="dsb">нижнелужицкий</language>
			<language type="dua">дуала</language>
			<language type="dum">средненидерландский</language>
			<language type="dv">мальдивский</language>
			<language type="dyu">диула (дьюла)</language>
			<language type="dz">дзонг-кэ</language>
			<language type="ee">эве</language>
			<language type="efi">эфик</language>
			<language type="egy">древнеегипетский</language>
			<language type="eka">экаджук</language>
			<language type="el">греческий</language>
			<language type="elx">эламский</language>
			<language type="en">английский</language>
			<language type="en_AU">австралийский английский</language>
			<language type="en_CA">Канадский английский</language>
			<language type="en_GB">британский английский</language>
			<language type="en_US">американский английский</language>
			<language type="enm">среднеанглийский</language>
			<language type="eo">эсперанто</language>
			<language type="es">испанский</language>
			<language type="es_419">Латино-американский испанский</language>
			<language type="es_ES">Испанский иберийский</language>
			<language type="et">эстонский</language>
			<language type="eu">баскский</language>
			<language type="ewo">эвондо</language>
			<language type="fa">персидский</language>
			<language type="fan">фанг</language>
			<language type="fat">фанти</language>
			<language type="ff">фулах</language>
			<language type="fi">финский</language>
			<language type="fil">филиппинский</language>
			<language type="fiu">финно-угорский язык</language>
			<language type="fj">фиджи</language>
			<language type="fo">фарерский</language>
			<language type="fon">фон</language>
			<language type="fr">французский</language>
			<language type="fr_CA">Канадский французский</language>
			<language type="fr_CH">Швейцарский французский</language>
			<language type="frm">среднефранцузский</language>
			<language type="fro">старофранцузский</language>
			<language type="frr">фризский северный</language>
			<language type="frs">восточный фризский</language>
			<language type="fur">фриульский</language>
			<language type="fy">фризский</language>
			<language type="ga">ирландский</language>
			<language type="gaa">га</language>
			<language type="gay">гайо</language>
			<language type="gba">гбая</language>
			<language type="gd">гэльский</language>
			<language type="gem">германский язык</language>
			<language type="gez">геэз</language>
			<language type="gil">гильбертский</language>
			<language type="gl">галисийский</language>
			<language type="gmh">средневерхненемецкий</language>
			<language type="gn">гуарани</language>
			<language type="goh">древневерхненемецкий</language>
			<language type="gon">гонди</language>
			<language type="gor">горонтало</language>
			<language type="got">готский</language>
			<language type="grb">гребо</language>
			<language type="grc">древнегреческий</language>
			<language type="gsw">Швейцарский немецкий</language>
			<language type="gu">гуджарати</language>
			<language type="gv">мэнский</language>
			<language type="gwi">гвичин</language>
			<language type="ha">хауса</language>
			<language type="hai">хайда</language>
			<language type="haw">гавайский</language>
			<language type="he">иврит</language>
			<language type="hi">хинди</language>
			<language type="hil">хилигайнон</language>
			<language type="him">химачали</language>
			<language type="hit">хеттский</language>
			<language type="hmn">хмонг</language>
			<language type="ho">хиримоту</language>
			<language type="hr">хорватский</language>
			<language type="hsb">верхнелужицкий</language>
			<language type="ht">гаитянский</language>
			<language type="hu">венгерский</language>
			<language type="hup">хупа</language>
			<language type="hy">армянский</language>
			<language type="hz">гереро</language>
			<language type="ia">интерлингва</language>
			<language type="iba">ибанский</language>
			<language type="id">индонезийский</language>
			<language type="ie">интерлингве</language>
			<language type="ig">игбо</language>
			<language type="ii">сычуань</language>
			<language type="ijo">иджо</language>
			<language type="ik">инупиак</language>
			<language type="ilo">илоко</language>
			<language type="inc">индийский язык</language>
			<language type="ine">индоевропейский язык</language>
			<language type="inh">ингушский</language>
			<language type="io">идо</language>
			<language type="ira">иранский язык</language>
			<language type="iro">ирокезские языки</language>
			<language type="is">исландский</language>
			<language type="it">итальянский</language>
			<language type="iu">инуктитут</language>
			<language type="ja">японский</language>
			<language type="jbo">ложбан</language>
			<language type="jpr">еврейско-персидский</language>
			<language type="jrb">еврейско-арабский</language>
			<language type="jv">яванский</language>
			<language type="ka">грузинский</language>
			<language type="kaa">каракалпакский</language>
			<language type="kab">кабильский</language>
			<language type="kac">качинский</language>
			<language type="kaj">каджи</language>
			<language type="kam">камба</language>
			<language type="kar">каренский</language>
			<language type="kaw">кави</language>
			<language type="kbd">кабардинский</language>
			<language type="kcg">тьяп</language>
			<language type="kfo">коро</language>
			<language type="kg">конго</language>
			<language type="kha">кхаси</language>
			<language type="khi">койсанский язык</language>
			<language type="kho">хотанский</language>
			<language type="ki">кикуйю</language>
			<language type="kj">кунама</language>
			<language type="kk">казахский</language>
			<language type="kl">эскимосский (гренландский)</language>
			<language type="km">кхмерский</language>
			<language type="kmb">кимбундийский</language>
			<language type="kn">каннада</language>
			<language type="ko">корейский</language>
			<language type="kok">конкани</language>
			<language type="kos">косраенский</language>
			<language type="kpe">кпелле</language>
			<language type="kr">канури</language>
			<language type="krc">карачаево-балкарский</language>
			<language type="krl">карельский</language>
			<language type="kro">кру</language>
			<language type="kru">курух</language>
			<language type="ks">кашмири</language>
			<language type="ku">курдский</language>
			<language type="kum">кумыкский</language>
			<language type="kut">кутенаи</language>
			<language type="kv">коми</language>
			<language type="kw">корнийский</language>
			<language type="ky">киргизский</language>
			<language type="la">латинский</language>
			<language type="lad">ладино</language>
			<language type="lah">лахнда</language>
			<language type="lam">ламба</language>
			<language type="lb">люксембургский</language>
			<language type="lez">лезгинский</language>
			<language type="lg">ганда</language>
			<language type="li">лимбургский</language>
			<language type="ln">лингала</language>
			<language type="lo">лаосский</language>
			<language type="lol">монго</language>
			<language type="loz">лози</language>
			<language type="lt">литовский</language>
			<language type="lu">луба-катанга</language>
			<language type="lua">луба-лулуа</language>
			<language type="lui">луисеньо</language>
			<language type="lun">лунда</language>
			<language type="luo">луо (Кения и Танзания)</language>
			<language type="lus">лушай</language>
			<language type="lv">латышский</language>
			<language type="mad">мадурский</language>
			<language type="mag">магахи</language>
			<language type="mai">майтхили</language>
			<language type="mak">макассарский</language>
			<language type="man">мандинго</language>
			<language type="map">австронезийский</language>
			<language type="mas">масаи</language>
			<language type="mdf">мокшанский</language>
			<language type="mdr">мандарский</language>
			<language type="men">менде</language>
			<language type="mg">малагасийский</language>
			<language type="mga">среднеирландский</language>
			<language type="mh">маршалльский</language>
			<language type="mi">маори</language>
			<language type="mic">микмак</language>
			<language type="min">минангкабау</language>
			<language type="mis">смешанные языки</language>
			<language type="mk">македонский</language>
			<language type="mkh">монкхмерский язык</language>
			<language type="ml">малаялам</language>
			<language type="mn">монгольский</language>
			<language type="mnc">маньчжурский</language>
			<language type="mni">манипурский</language>
			<language type="mno">манобо языки</language>
			<language type="mo">молдавский</language>
			<language type="moh">мохаук</language>
			<language type="mos">моси</language>
			<language type="mr">маратхи</language>
			<language type="ms">малайский</language>
			<language type="mt">мальтийский</language>
			<language type="mul">несколько языков</language>
			<language type="mun">мунда языки</language>
			<language type="mus">крик</language>
			<language type="mwl">мирандийский</language>
			<language type="mwr">марвари</language>
			<language type="my">бирманский</language>
			<language type="myn">майя языки</language>
			<language type="myv">эрзя</language>
			<language type="na">науру</language>
			<language type="nah">ацтекский</language>
			<language type="nai">язык индейцев Северной Америки</language>
			<language type="nap">неаполитанский</language>
			<language type="nb">норвежский букмол</language>
			<language type="nd">ндебели (северный)</language>
			<language type="nds">нижнегерманский</language>
			<language type="ne">непальский</language>
			<language type="new">неварский</language>
			<language type="ng">ндонга</language>
			<language type="nia">ниас</language>
			<language type="nic">нигер-кордофанский язык</language>
			<language type="niu">ниуэ</language>
			<language type="nl">голландский</language>
			<language type="nl_BE">Бельгийский фламандский</language>
			<language type="nn">норвежский нюнорск</language>
			<language type="no">норвежский</language>
			<language type="nog">ногайский</language>
			<language type="non">старонорвежский</language>
			<language type="nqo">нко</language>
			<language type="nr">ндебели южный</language>
			<language type="nso">сото северный</language>
			<language type="nub">нубийские языки</language>
			<language type="nv">навахо</language>
			<language type="nwc">невари (классический)</language>
			<language type="ny">ньянджа</language>
			<language type="nym">ньямвези</language>
			<language type="nyn">ньянколе</language>
			<language type="nyo">ньоро</language>
			<language type="nzi">нзима</language>
			<language type="oc">окситанский</language>
			<language type="oj">оджибва</language>
			<language type="om">оромо</language>
			<language type="or">ория</language>
			<language type="os">осетинский</language>
			<language type="osa">оседжи</language>
			<language type="ota">старотурецкий</language>
			<language type="oto">отомангские языки</language>
			<language type="pa">панджаби (пенджаби)</language>
			<language type="paa">папуасский язык</language>
			<language type="pag">пангасинан</language>
			<language type="pal">пехлевийский</language>
			<language type="pam">пампанга</language>
			<language type="pap">папьяменто</language>
			<language type="pau">палау</language>
			<language type="peo">староперсидский</language>
			<language type="phi">филиппинский язык</language>
			<language type="phn">финикийский</language>
			<language type="pi">пали</language>
			<language type="pl">польский</language>
			<language type="pon">понапе</language>
			<language type="pra">пракриты языки</language>
			<language type="pro">старопровансальский</language>
			<language type="ps">пашто (пушту)</language>
			<language type="pt">португальский</language>
			<language type="pt_BR">бразильский португальский</language>
			<language type="pt_PT">Португальский иберийский</language>
			<language type="qu">кечуа</language>
			<language type="raj">раджастхани</language>
			<language type="rap">рапануи</language>
			<language type="rar">раротонганский</language>
			<language type="rm">ретороманский</language>
			<language type="rn">рунди</language>
			<language type="ro">румынский</language>
			<language type="roa">романский язык</language>
			<language type="rom">цыганский</language>
			<language type="root">корневой язык</language>
			<language type="ru">русский</language>
			<language type="rup">арумынский</language>
			<language type="rw">киньяруанда</language>
			<language type="sa">санскрит</language>
			<language type="sad">сандаве</language>
			<language type="sah">якутский</language>
			<language type="sai">язык индейцев Южной Америки</language>
			<language type="sal">салишские языки</language>
			<language type="sam">самаритянский арамейский</language>
			<language type="sas">сасаки</language>
			<language type="sat">сантали</language>
			<language type="sc">сардинский</language>
			<language type="scn">сицилийский</language>
			<language type="sco">шотландский</language>
			<language type="sd">синдхи</language>
			<language type="se">саамский (северный)</language>
			<language type="sel">селькупский</language>
			<language type="sem">семитский язык</language>
			<language type="sg">санго</language>
			<language type="sga">староирландский</language>
			<language type="sgn">язык глухонемых</language>
			<language type="sh">сербскохорватский</language>
			<language type="shn">шанский</language>
			<language type="si">сингальский</language>
			<language type="sid">сидама</language>
			<language type="sio">сиу языки</language>
			<language type="sit">синотибетский язык</language>
			<language type="sk">словацкий</language>
			<language type="sl">словенский</language>
			<language type="sla">славянский язык</language>
			<language type="sm">самоанский</language>
			<language type="sma">саамский (южный)</language>
			<language type="smi">саамские языки</language>
			<language type="smj">луле-саамский</language>
			<language type="smn">инари-саамский</language>
			<language type="sms">скольт-саамский</language>
			<language type="sn">шона</language>
			<language type="snk">сонинке</language>
			<language type="so">сомали</language>
			<language type="sog">согдийский</language>
			<language type="son">cонгаи</language>
			<language type="sq">албанский</language>
			<language type="sr">сербский</language>
			<language type="srn">сранан тонго</language>
			<language type="srr">серер</language>
			<language type="ss">свази</language>
			<language type="ssa">нило-сахарский язык</language>
			<language type="st">сото южный</language>
			<language type="su">сунданский</language>
			<language type="suk">сукума</language>
			<language type="sus">сусу</language>
			<language type="sux">шумерский</language>
			<language type="sv">шведский</language>
			<language type="sw">суахили</language>
			<language type="syc">классический сирийский</language>
			<language type="syr">сирийский</language>
			<language type="ta">тамильский</language>
			<language type="tai">тайский язык</language>
			<language type="te">телугу</language>
			<language type="tem">темне</language>
			<language type="ter">терено</language>
			<language type="tet">тетум</language>
			<language type="tg">таджикский</language>
			<language type="th">тайский</language>
			<language type="ti">тигринья</language>
			<language type="tig">тигре</language>
			<language type="tiv">тиви</language>
			<language type="tk">туркменский</language>
			<language type="tkl">токелайский</language>
			<language type="tl">тагалог</language>
			<language type="tlh">клингонский</language>
			<language type="tli">тлингит</language>
			<language type="tmh">тамашек</language>
			<language type="tn">тсвана</language>
			<language type="to">тонга</language>
			<language type="tog">ньяса (тонга)</language>
			<language type="tpi">ток-писин</language>
			<language type="tr">турецкий</language>
			<language type="ts">тсонга</language>
			<language type="tsi">цимшиан</language>
			<language type="tt">татарский</language>
			<language type="tum">тумбука</language>
			<language type="tup">тупи</language>
			<language type="tut">алтайский язык</language>
			<language type="tvl">тувалу</language>
			<language type="tw">тви</language>
			<language type="ty">таитянский</language>
			<language type="tyv">тувинский</language>
			<language type="udm">удмуртский</language>
			<language type="ug">уйгурский</language>
			<language type="uga">угаритский</language>
			<language type="uk">украинский</language>
			<language type="umb">умбунду</language>
			<language type="und">неизвестный или недействительный язык</language>
			<language type="ur">урду</language>
			<language type="uz">узбекский</language>
			<language type="vai">ваи</language>
			<language type="ve">венда</language>
			<language type="vi">вьетнамский</language>
			<language type="vo">волапюк</language>
			<language type="vot">водский</language>
			<language type="wa">валлонский</language>
			<language type="wak">вакашские языки</language>
			<language type="wal">воламо</language>
			<language type="war">варай</language>
			<language type="was">вашо</language>
			<language type="wen">лужицкие языки</language>
			<language type="wo">волоф</language>
			<language type="xal">калмыцкий</language>
			<language type="xh">ксоза</language>
			<language type="yao">яо</language>
			<language type="yap">яп</language>
			<language type="yi">идиш</language>
			<language type="yo">йоруба</language>
			<language type="ypk">юпикский язык</language>
			<language type="za">чжуань</language>
			<language type="zap">сапотекский</language>
			<language type="zbl">блиссимволика</language>
			<language type="zen">зенагский</language>
			<language type="zh">китайский</language>
			<language type="zh_Hans">упрощенный китайский</language>
			<language type="zh_Hant">Традиционный китайский</language>
			<language type="znd">занде</language>
			<language type="zu">зулу</language>
			<language type="zun">зуньи</language>
			<language type="zxx">без языкового содержания</language>
			<language type="zza">заза</language>
		</languages>
		<scripts>
			<script type="Arab">Арабская</script>
			<script type="Armi">Арамейская</script>
			<script type="Armn">Армянская</script>
			<script type="Avst">Авестийская</script>
			<script type="Bali">Балийская</script>
			<script type="Batk">Батакская</script>
			<script type="Beng">Бенгальская</script>
			<script type="Blis">Блиссимволика</script>
			<script type="Bopo">Бопомофо</script>
			<script type="Brah">Брахми</script>
			<script type="Brai">Брайля</script>
			<script type="Bugi">Бугинизийская</script>
			<script type="Buhd">Бухид</script>
			<script type="Cakm">Чакмийская</script>
			<script type="Cans">Унифицированные Символы Канадских Аборигенов</script>
			<script type="Cari">Карийская</script>
			<script type="Cham">Чамская</script>
			<script type="Cher">Чероки</script>
			<script type="Cirt">Кирт</script>
			<script type="Copt">Коптская</script>
			<script type="Cprt">Кипрская</script>
			<script type="Cyrl">Кириллица</script>
			<script type="Cyrs">Старославянская</script>
			<script type="Deva">Деванагари</script>
			<script type="Dsrt">Дезерет</script>
			<script type="Egyd">Египетская демотическая</script>
			<script type="Egyh">Египетская иератическая</script>
			<script type="Egyp">Египетская иероглифическая</script>
			<script type="Ethi">Эфиопская</script>
			<script type="Geok">Грузинская хуцури</script>
			<script type="Geor">Грузинская</script>
			<script type="Glag">Глаголица</script>
			<script type="Goth">Готская</script>
			<script type="Grek">Греческая</script>
			<script type="Gujr">Гуджарати</script>
			<script type="Guru">Гурмукхи</script>
			<script type="Hang">Хангул</script>
			<script type="Hani">Китайская</script>
			<script type="Hano">Хануну</script>
			<script type="Hans">Упрощенная китайская</script>
			<script type="Hant">Традиционная китайская</script>
			<script type="Hebr">Иврит</script>
			<script type="Hira">Хирагана</script>
			<script type="Hmng">Пахау хмонг</script>
			<script type="Hrkt">Катакана или хирагана</script>
			<script type="Hung">Старовенгерская</script>
			<script type="Inds">Хараппская (письменность долины Инда)</script>
			<script type="Ital">Староитальянская</script>
			<script type="Java">Яванская</script>
			<script type="Jpan">Японская</script>
			<script type="Kali">Кайа</script>
			<script type="Kana">Катакана</script>
			<script type="Khar">Кхароштхи</script>
			<script type="Khmr">Кхмерская</script>
			<script type="Knda">Каннада</script>
			<script type="Kore">Корейская</script>
			<script type="Kthi">Кайтхи</script>
			<script type="Lana">Ланна</script>
			<script type="Laoo">Лаосская</script>
			<script type="Latf">Латинская фрактура</script>
			<script type="Latg">Гэльская латинская</script>
			<script type="Latn">Латиница</script>
			<script type="Lepc">Лепха</script>
			<script type="Limb">Лимбу</script>
			<script type="Lina">Линейное письмо А</script>
			<script type="Linb">Линейное письмо Б</script>
			<script type="Lyci">Лициан</script>
			<script type="Lydi">Лидийская</script>
			<script type="Mand">Мандейская</script>
			<script type="Mani">Манихейская</script>
			<script type="Maya">Майя</script>
			<script type="Mero">Мероитская</script>
			<script type="Mlym">Малаяльская</script>
			<script type="Mong">Монгольская</script>
			<script type="Moon">Азбука Муна</script>
			<script type="Mtei">Манипури</script>
			<script type="Mymr">Майанмарская</script>
			<script type="Nkoo">Нко</script>
			<script type="Ogam">Огамическая</script>
			<script type="Olck">Ол Чики</script>
			<script type="Orkh">Орхоно-енисейская</script>
			<script type="Orya">Ория</script>
			<script type="Osma">Османская</script>
			<script type="Perm">Древнепермская</script>
			<script type="Phag">Пагспа</script>
			<script type="Phlv">Пахлави книжная</script>
			<script type="Phnx">Финикийская</script>
			<script type="Plrd">Поллардовская фонетика</script>
			<script type="Qaai">Унаследованная</script>
			<script type="Rjng">Реджангская</script>
			<script type="Roro">Ронго-ронго</script>
			<script type="Runr">Руническая</script>
			<script type="Samr">Самаритянская</script>
			<script type="Sara">Сарати</script>
			<script type="Saur">Саураштра</script>
			<script type="Sgnw">Язык знаков</script>
			<script type="Shaw">Алфавит Шоу</script>
			<script type="Sinh">Сингальская</script>
			<script type="Sund">Сунданская</script>
			<script type="Sylo">Силоти Нагри</script>
			<script type="Syrc">Сирийская</script>
			<script type="Syre">Сирийская эстрангело</script>
			<script type="Syrj">Западносирийская</script>
			<script type="Syrn">Восточно-сирийская</script>
			<script type="Tagb">Тагбанва</script>
			<script type="Tale">Тайский Ле</script>
			<script type="Talu">Новый Тайский Ле</script>
			<script type="Taml">Тамильская</script>
			<script type="Telu">Телугу</script>
			<script type="Teng">Тенгварская</script>
			<script type="Tfng">Древнеливийская</script>
			<script type="Tglg">Тагалог</script>
			<script type="Thaa">Таана</script>
			<script type="Thai">Тайская</script>
			<script type="Tibt">Тибетская</script>
			<script type="Ugar">Угаритская</script>
			<script type="Vaii">Вайская</script>
			<script type="Visp">Видимая речь</script>
			<script type="Xpeo">Староперсидская</script>
			<script type="Xsux">Шумеро-аккадская клинопись</script>
			<script type="Yiii">Йи (ицзу)</script>
			<script type="Zxxx">Ненаписанная</script>
			<script type="Zyyy">Общепринятая</script>
			<script type="Zzzz">Неизвестная или недействительная письменность</script>
		</scripts>
		<territories>
			<territory type="001">Мир</territory>
			<territory type="002">Африка</territory>
			<territory type="003">Северная Америка</territory>
			<territory type="005">Южная Америка</territory>
			<territory type="009">Океания</territory>
			<territory type="011">Западная Африка</territory>
			<territory type="013">Центральная Америка</territory>
			<territory type="014">Восточная Африка</territory>
			<territory type="015">Северная Африка</territory>
			<territory type="017">Центральная Африка</territory>
			<territory type="018">Южная Африка [018]</territory>
			<territory type="019">Центральная и Южная Америка</territory>
			<territory type="021">Северная Америка (021)</territory>
			<territory type="029">Карибы</territory>
			<territory type="030">Восточная Азия</territory>
			<territory type="034">Южная Азия</territory>
			<territory type="035">Юго-Восточная Азия</territory>
			<territory type="039">Южная Европа</territory>
			<territory type="053">Австралия и Новая Зеландия</territory>
			<territory type="054">Меланезия</territory>
			<territory type="057">Микронезия</territory>
			<territory type="061">Полинезия</territory>
			<territory type="062">Юг Средней Азии</territory>
			<territory type="142">Азия</territory>
			<territory type="143">Средняя Азия</territory>
			<territory type="145">Ближний и Средний Восток</territory>
			<territory type="150">Европа</territory>
			<territory type="151">Восточная Европа</territory>
			<territory type="154">Северная Европа</territory>
			<territory type="155">Западная Европа</territory>
			<territory type="172">СНГ</territory>
			<territory type="419">Латинская Америка и Карибские о-ва</territory>
			<territory type="830">Нормандские острова</territory>
			<territory type="AD">Андорра</territory>
			<territory type="AE">Объединенные Арабские Эмираты</territory>
			<territory type="AF">Афганистан</territory>
			<territory type="AG">Антигуа и Барбуда</territory>
			<territory type="AI">Ангуилла</territory>
			<territory type="AL">Албания</territory>
			<territory type="AM">Армения</territory>
			<territory type="AN">Нидерландские Антильские острова</territory>
			<territory type="AO">Ангола</territory>
			<territory type="AQ">Антарктика</territory>
			<territory type="AR">Аргентина</territory>
			<territory type="AS">Американское Самоа</territory>
			<territory type="AT">Австрия</territory>
			<territory type="AU">Австралия</territory>
			<territory type="AW">Аруба</territory>
			<territory type="AX">Аландские острова</territory>
			<territory type="AZ">Азербайджан</territory>
			<territory type="BA">Босния и Герцеговина</territory>
			<territory type="BB">Барбадос</territory>
			<territory type="BD">Бангладеш</territory>
			<territory type="BE">Бельгия</territory>
			<territory type="BF">Буркина Фасо</territory>
			<territory type="BG">Болгария</territory>
			<territory type="BH">Бахрейн</territory>
			<territory type="BI">Бурунди</territory>
			<territory type="BJ">Бенин</territory>
			<territory type="BL">Остров Святого Бартоломея</territory>
			<territory type="BM">Бермудские Острова</territory>
			<territory type="BN">Бруней Даруссалам</territory>
			<territory type="BO">Боливия</territory>
			<territory type="BR">Бразилия</territory>
			<territory type="BS">Багамские острова</territory>
			<territory type="BT">Бутан</territory>
			<territory type="BV">Остров Буве</territory>
			<territory type="BW">Ботсвана</territory>
			<territory type="BY">Беларусь</territory>
			<territory type="BZ">Белиз</territory>
			<territory type="CA">Канада</territory>
			<territory type="CC">Кокосовые острова</territory>
			<territory type="CD">Демократическая Республика Конго</territory>
			<territory type="CF">Центрально-Африканская Республика</territory>
			<territory type="CG">Конго</territory>
			<territory type="CH">Швейцария</territory>
			<territory type="CI">Кот д’Ивуар</territory>
			<territory type="CK">Острова Кука</territory>
			<territory type="CL">Чили</territory>
			<territory type="CM">Камерун</territory>
			<territory type="CN">Китай</territory>
			<territory type="CO">Колумбия</territory>
			<territory type="CR">Коста-Рика</territory>
			<territory type="CS">Сербия и Черногория</territory>
			<territory type="CU">Куба</territory>
			<territory type="CV">Острова Зеленого Мыса</territory>
			<territory type="CX">Остров Рождества</territory>
			<territory type="CY">Кипр</territory>
			<territory type="CZ">Чешская республика</territory>
			<territory type="DE">Германия</territory>
			<territory type="DJ">Джибути</territory>
			<territory type="DK">Дания</territory>
			<territory type="DM">Остров Доминика</territory>
			<territory type="DO">Доминиканская Республика</territory>
			<territory type="DZ">Алжир</territory>
			<territory type="EC">Эквадор</territory>
			<territory type="EE">Эстония</territory>
			<territory type="EG">Египет</territory>
			<territory type="EH">Западная Сахара</territory>
			<territory type="ER">Эритрея</territory>
			<territory type="ES">Испания</territory>
			<territory type="ET">Эфиопия</territory>
			<territory type="FI">Финляндия</territory>
			<territory type="FJ">Фиджи</territory>
			<territory type="FK">Фолклендские острова</territory>
			<territory type="FM">Федеративные Штаты Микронезии</territory>
			<territory type="FO">Фарерские острова</territory>
			<territory type="FR">Франция</territory>
			<territory type="GA">Габон</territory>
			<territory type="GB">Великобритания</territory>
			<territory type="GD">Гренада</territory>
			<territory type="GE">Грузия</territory>
			<territory type="GF">Французская Гвиана</territory>
			<territory type="GG">Гернси</territory>
			<territory type="GH">Гана</territory>
			<territory type="GI">Гибралтар</territory>
			<territory type="GL">Гренландия</territory>
			<territory type="GM">Гамбия</territory>
			<territory type="GN">Гвинея</territory>
			<territory type="GP">Гваделупа</territory>
			<territory type="GQ">Экваториальная Гвинея</territory>
			<territory type="GR">Греция</territory>
			<territory type="GS">Южная Джорджия и Южные Сандвичевы Острова</territory>
			<territory type="GT">Гватемала</territory>
			<territory type="GU">Гуам</territory>
			<territory type="GW">Гвинея-Биссау</territory>
			<territory type="GY">Гайана</territory>
			<territory type="HK">Гонконг</territory>
			<territory type="HM">Острова Херд и Макдональд</territory>
			<territory type="HN">Гондурас</territory>
			<territory type="HR">Хорватия</territory>
			<territory type="HT">Гаити</territory>
			<territory type="HU">Венгрия</territory>
			<territory type="ID">Индонезия</territory>
			<territory type="IE">Ирландия</territory>
			<territory type="IL">Израиль</territory>
			<territory type="IM">Остров Мэн</territory>
			<territory type="IN">Индия</territory>
			<territory type="IO">Британская территория в Индийском океане</territory>
			<territory type="IQ">Ирак</territory>
			<territory type="IR">Иран</territory>
			<territory type="IS">Исландия</territory>
			<territory type="IT">Италия</territory>
			<territory type="JE">Джерси</territory>
			<territory type="JM">Ямайка</territory>
			<territory type="JO">Иордания</territory>
			<territory type="JP">Япония</territory>
			<territory type="KE">Кения</territory>
			<territory type="KG">Кыргызстан</territory>
			<territory type="KH">Камбоджа</territory>
			<territory type="KI">Кирибати</territory>
			<territory type="KM">Коморские Острова</territory>
			<territory type="KN">Сент-Киттс и Невис</territory>
			<territory type="KP">Корейская Народно-Демократическая Республика</territory>
			<territory type="KR">Республика Корея</territory>
			<territory type="KW">Кувейт</territory>
			<territory type="KY">Каймановы острова</territory>
			<territory type="KZ">Казахстан</territory>
			<territory type="LA">Лаос</territory>
			<territory type="LB">Ливан</territory>
			<territory type="LC">Сент-Люсия</territory>
			<territory type="LI">Лихтенштейн</territory>
			<territory type="LK">Шри-Ланка</territory>
			<territory type="LR">Либерия</territory>
			<territory type="LS">Лесото</territory>
			<territory type="LT">Литва</territory>
			<territory type="LU">Люксембург</territory>
			<territory type="LV">Латвия</territory>
			<territory type="LY">Ливия</territory>
			<territory type="MA">Марокко</territory>
			<territory type="MC">Монако</territory>
			<territory type="MD">Молдова</territory>
			<territory type="ME">Черногория</territory>
			<territory type="MF">Остров Святого Мартина</territory>
			<territory type="MG">Мадагаскар</territory>
			<territory type="MH">Маршалловы Острова</territory>
			<territory type="MK">Македония</territory>
			<territory type="ML">Мали</territory>
			<territory type="MM">Мьянма</territory>
			<territory type="MN">Монголия</territory>
			<territory type="MO">Макао</territory>
			<territory type="MP">Северные Марианские Острова</territory>
			<territory type="MQ">Мартиник</territory>
			<territory type="MR">Мавритания</territory>
			<territory type="MS">Монсеррат</territory>
			<territory type="MT">Мальта</territory>
			<territory type="MU">Маврикий</territory>
			<territory type="MV">Мальдивы</territory>
			<territory type="MW">Малави</territory>
			<territory type="MX">Мексика</territory>
			<territory type="MY">Малайзия</territory>
			<territory type="MZ">Мозамбик</territory>
			<territory type="NA">Намибия</territory>
			<territory type="NC">Новая Каледония</territory>
			<territory type="NE">Нигер</territory>
			<territory type="NF">Остров Норфолк</territory>
			<territory type="NG">Нигерия</territory>
			<territory type="NI">Никарагуа</territory>
			<territory type="NL">Нидерланды</territory>
			<territory type="NO">Норвегия</territory>
			<territory type="NP">Непал</territory>
			<territory type="NR">Науру</territory>
			<territory type="NU">Ниуе</territory>
			<territory type="NZ">Новая Зеландия</territory>
			<territory type="OM">Оман</territory>
			<territory type="PA">Панама</territory>
			<territory type="PE">Перу</territory>
			<territory type="PF">Французская Полинезия</territory>
			<territory type="PG">Папуа-Новая Гвинея</territory>
			<territory type="PH">Филиппины</territory>
			<territory type="PK">Пакистан</territory>
			<territory type="PL">Польша</territory>
			<territory type="PM">Сен-Пьер и Микелон</territory>
			<territory type="PN">Питкерн</territory>
			<territory type="PR">Пуэрто-Рико</territory>
			<territory type="PS">Палестинская автономия</territory>
			<territory type="PT">Португалия</territory>
			<territory type="PW">Палау</territory>
			<territory type="PY">Парагвай</territory>
			<territory type="QA">Катар</territory>
			<territory type="QO">Внешняя Океания</territory>
			<territory type="QU">Европейский союз</territory>
			<territory type="RE">Реюньон</territory>
			<territory type="RO">Румыния</territory>
			<territory type="RS">Сербия</territory>
			<territory type="RU">Россия</territory>
			<territory type="RW">Руанда</territory>
			<territory type="SA">Саудовская Аравия</territory>
			<territory type="SB">Соломоновы Острова</territory>
			<territory type="SC">Сейшельские Острова</territory>
			<territory type="SD">Судан</territory>
			<territory type="SE">Швеция</territory>
			<territory type="SG">Сингапур</territory>
			<territory type="SH">Остров Святой Елены</territory>
			<territory type="SI">Словения</territory>
			<territory type="SJ">Свальбард и Ян-Майен</territory>
			<territory type="SK">Словакия</territory>
			<territory type="SL">Сьерра-Леоне</territory>
			<territory type="SM">Сан-Марино</territory>
			<territory type="SN">Сенегал</territory>
			<territory type="SO">Сомали</territory>
			<territory type="SR">Суринам</territory>
			<territory type="ST">Сан-Томе и Принсипи</territory>
			<territory type="SV">Сальвадор</territory>
			<territory type="SY">Сирийская Арабская Республика</territory>
			<territory type="SZ">Свазиленд</territory>
			<territory type="TC">Острова Тёркс и Кайкос</territory>
			<territory type="TD">Чад</territory>
			<territory type="TF">Французские Южные Территории</territory>
			<territory type="TG">Того</territory>
			<territory type="TH">Таиланд</territory>
			<territory type="TJ">Таджикистан</territory>
			<territory type="TK">Токелау</territory>
			<territory type="TL">Восточный Тимор</territory>
			<territory type="TM">Туркменистан</territory>
			<territory type="TN">Тунис</territory>
			<territory type="TO">Тонга</territory>
			<territory type="TR">Турция</territory>
			<territory type="TT">Тринидад и Тобаго</territory>
			<territory type="TV">Тувалу</territory>
			<territory type="TW">Тайвань</territory>
			<territory type="TZ">Танзания</territory>
			<territory type="UA">Украина</territory>
			<territory type="UG">Уганда</territory>
			<territory type="UM">Внешние малые острова (США)</territory>
			<territory type="US">США</territory>
			<territory type="UY">Уругвай</territory>
			<territory type="UZ">Узбекистан</territory>
			<territory type="VA">Ватикан</territory>
			<territory type="VC">Сент-Винсент и Гренадины</territory>
			<territory type="VE">Венесуэла</territory>
			<territory type="VG">Британские Виргинские Острова</territory>
			<territory type="VI">Американские Виргинские Острова</territory>
			<territory type="VN">Вьетнам</territory>
			<territory type="VU">Вануату</territory>
			<territory type="WF">Уоллис и Футуна</territory>
			<territory type="WS">Самоа</territory>
			<territory type="YE">Йемен</territory>
			<territory type="YT">Майотта</territory>
			<territory type="ZA">Южная Африка</territory>
			<territory type="ZM">Замбия</territory>
			<territory type="ZW">Зимбабве</territory>
			<territory type="ZZ">Неизвестный или недействительный регион</territory>
		</territories>
		<variants>
			<variant type="1901">Традиционная немецкая орфография</variant>
			<variant type="1994">Стандартизированная резьянская орфография</variant>
			<variant type="1996">Правила немецкой орфографии установленные с 1996 года</variant>
			<variant type="1606NICT">Поздне-средневековый французский до 1606 г.</variant>
			<variant type="AREVELA">Восточно-армянский</variant>
			<variant type="AREVMDA">Западно-армянский</variant>
			<variant type="BAKU1926">Унифицированный тюрско-латинский алфавит</variant>
			<variant type="FONIPA">Международный фонетический алфавит</variant>
			<variant type="MONOTON">Монотонный</variant>
			<variant type="POLYTON">Многотональный</variant>
			<variant type="POSIX">Компьютерный</variant>
			<variant type="ROZAJ">Резьянский</variant>
			<variant type="SAAHO">Сахо</variant>
			<variant type="SCOTLAND">Англо-шотландский</variant>
			<variant type="TARASK">Тарашкевица</variant>
			<variant type="VALENCIA">Валенсийский</variant>
		</variants>
		<keys>
			<key type="calendar">Календарь</key>
			<key type="collation">Сопоставление</key>
			<key type="currency">Валюта</key>
		</keys>
		<types>
			<type type="big5han" key="collation">традиционный китайский - Big5</type>
			<type type="buddhist" key="calendar">Буддийский календарь</type>
			<type type="chinese" key="calendar">Китайский календарь</type>
			<type type="direct" key="collation">прямой порядок</type>
			<type type="gb2312han" key="collation">упрощенный китайский - GB2312</type>
			<type type="gregorian" key="calendar">Григорианский календарь</type>
			<type type="hebrew" key="calendar">Еврейский календарь</type>
			<type type="indian" key="calendar">Национальный календарь Индии</type>
			<type type="islamic" key="calendar">Исламский календарь</type>
			<type type="islamic-civil" key="calendar">Исламский гражданский календарь</type>
			<type type="japanese" key="calendar">Японский календарь</type>
			<type type="phonebook" key="collation">порядок телефонной книги</type>
			<type type="pinyin" key="collation">пиньинь</type>
			<type type="roc" key="calendar">Китайский календарь</type>
			<type type="stroke" key="collation">по чертам</type>
			<type type="traditional" key="collation">традиционный порядок</type>
		</types>
		<measurementSystemNames>
			<measurementSystemName type="US">Англо-американская</measurementSystemName>
			<measurementSystemName type="metric">Метрическая</measurementSystemName>
		</measurementSystemNames>
		<codePatterns>
			<codePattern type="language">Язык: {0}</codePattern>
			<codePattern type="script">Написание: {0}</codePattern>
			<codePattern type="territory">Регион: {0}</codePattern>
		</codePatterns>
	</localeDisplayNames>
	<layout>
		<inList>titlecase-firstword</inList>
	</layout>
	<characters>
		<exemplarCharacters>[а-е ё ж-я]</exemplarCharacters>
		<exemplarCharacters type="auxiliary">[a-e g i m n p r t-x]</exemplarCharacters>
		<exemplarCharacters type="currencySymbol">[a-z]</exemplarCharacters>
	</characters>
	<delimiters>
		<quotationStart>«</quotationStart>
		<quotationEnd>»</quotationEnd>
		<alternateQuotationStart>„</alternateQuotationStart>
		<alternateQuotationEnd>“</alternateQuotationEnd>
	</delimiters>
	<dates>
		<localizedPatternChars>GanjkHmsSEDFwWxhKzAeugXZvcL</localizedPatternChars>
		<calendars>
			<calendar type="gregorian">
				<months>
					<monthContext type="format">
						<monthWidth type="abbreviated">
							<month type="1">янв.</month>
							<month type="2">февр.</month>
							<month type="3">марта</month>
							<month type="4">апр.</month>
							<month type="5">мая</month>
							<month type="6">июня</month>
							<month type="7">июля</month>
							<month type="8">авг.</month>
							<month type="9">сент.</month>
							<month type="10">окт.</month>
							<month type="11">нояб.</month>
							<month type="12">дек.</month>
						</monthWidth>
						<monthWidth type="wide">
							<month type="1">января</month>
							<month type="2">февраля</month>
							<month type="3">марта</month>
							<month type="4">апреля</month>
							<month type="5">мая</month>
							<month type="6">июня</month>
							<month type="7">июля</month>
							<month type="8">августа</month>
							<month type="9">сентября</month>
							<month type="10">октября</month>
							<month type="11">ноября</month>
							<month type="12">декабря</month>
						</monthWidth>
					</monthContext>
					<monthContext type="stand-alone">
						<monthWidth type="abbreviated">
							<month type="1">янв.</month>
							<month type="2">февр.</month>
							<month type="3">март</month>
							<month type="4">апр.</month>
							<month type="5">май</month>
							<month type="6">июнь</month>
							<month type="7">июль</month>
							<month type="8">авг.</month>
							<month type="9">сент.</month>
							<month type="10">окт.</month>
							<month type="11">нояб.</month>
							<month type="12">дек.</month>
						</monthWidth>
						<monthWidth type="narrow">
							<month type="1">Я</month>
							<month type="2">Ф</month>
							<month type="3">М</month>
							<month type="4">А</month>
							<month type="5">М</month>
							<month type="6">И</month>
							<month type="7">И</month>
							<month type="8">А</month>
							<month type="9">С</month>
							<month type="10">О</month>
							<month type="11">Н</month>
							<month type="12">Д</month>
						</monthWidth>
						<monthWidth type="wide">
							<month type="1">Январь</month>
							<month type="2">Февраль</month>
							<month type="3">Март</month>
							<month type="4">Апрель</month>
							<month type="5">Май</month>
							<month type="6">Июнь</month>
							<month type="7">Июль</month>
							<month type="8">Август</month>
							<month type="9">Сентябрь</month>
							<month type="10">Октябрь</month>
							<month type="11">Ноябрь</month>
							<month type="12">Декабрь</month>
						</monthWidth>
					</monthContext>
				</months>
				<days>
					<dayContext type="format">
						<dayWidth type="abbreviated">
							<day type="sun">Вс</day>
							<day type="mon">Пн</day>
							<day type="tue">Вт</day>
							<day type="wed">Ср</day>
							<day type="thu">Чт</day>
							<day type="fri">Пт</day>
							<day type="sat">Сб</day>
						</dayWidth>
						<dayWidth type="wide">
							<day type="sun">воскресенье</day>
							<day type="mon">понедельник</day>
							<day type="tue">вторник</day>
							<day type="wed">среда</day>
							<day type="thu">четверг</day>
							<day type="fri">пятница</day>
							<day type="sat">суббота</day>
						</dayWidth>
					</dayContext>
					<dayContext type="stand-alone">
						<dayWidth type="narrow">
							<day type="sun">В</day>
							<day type="mon">П</day>
							<day type="tue">В</day>
							<day type="wed">С</day>
							<day type="thu">Ч</day>
							<day type="fri">П</day>
							<day type="sat">С</day>
						</dayWidth>
						<dayWidth type="wide">
							<day type="sun">Воскресенье</day>
							<day type="mon">Понедельник</day>
							<day type="tue">Вторник</day>
							<day type="wed">Среда</day>
							<day type="thu">Четверг</day>
							<day type="fri">Пятница</day>
							<day type="sat">Суббота</day>
						</dayWidth>
					</dayContext>
				</days>
				<quarters>
					<quarterContext type="format">
						<quarterWidth type="abbreviated">
							<quarter type="1">1-й кв.</quarter>
							<quarter type="2">2-й кв.</quarter>
							<quarter type="3">3-й кв.</quarter>
							<quarter type="4">4-й кв.</quarter>
						</quarterWidth>
						<quarterWidth type="wide">
							<quarter type="1">1-й квартал</quarter>
							<quarter type="2">2-й квартал</quarter>
							<quarter type="3">3-й квартал</quarter>
							<quarter type="4">4-й квартал</quarter>
						</quarterWidth>
					</quarterContext>
					<quarterContext type="stand-alone">
						<quarterWidth type="narrow">
							<quarter type="1">1</quarter>
							<quarter type="2">2</quarter>
							<quarter type="3">3</quarter>
							<quarter type="4">4</quarter>
						</quarterWidth>
					</quarterContext>
				</quarters>
				<am>AM</am>
				<pm>PM</pm>
				<eras>
					<eraNames>
						<era type="0">до н.э.</era>
						<era type="1">н.э.</era>
					</eraNames>
					<eraAbbr>
						<era type="0">до н.э.</era>
						<era type="1">н.э.</era>
					</eraAbbr>
				</eras>
				<dateFormats>
					<dateFormatLength type="full">
						<dateFormat>
							<pattern>EEEE, d MMMM yyyy 'г'.</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="long">
						<dateFormat>
							<pattern>d MMMM yyyy 'г'.</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="medium">
						<dateFormat>
							<pattern>dd.MM.yyyy</pattern>
						</dateFormat>
					</dateFormatLength>
					<dateFormatLength type="short">
						<dateFormat>
							<pattern>dd.MM.yy</pattern>
						</dateFormat>
					</dateFormatLength>
				</dateFormats>
				<timeFormats>
					<timeFormatLength type="full">
						<timeFormat>
							<pattern>H:mm:ss v</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="long">
						<timeFormat>
							<pattern>H:mm:ss z</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="medium">
						<timeFormat>
							<pattern>H:mm:ss</pattern>
						</timeFormat>
					</timeFormatLength>
					<timeFormatLength type="short">
						<timeFormat>
							<pattern>H:mm</pattern>
						</timeFormat>
					</timeFormatLength>
				</timeFormats>
				<dateTimeFormats>
					<dateTimeFormatLength>
						<dateTimeFormat>
							<pattern>{1} {0}</pattern>
						</dateTimeFormat>
					</dateTimeFormatLength>
					<availableFormats>
						<dateFormatItem id="Ed">E d</dateFormatItem>
						<dateFormatItem id="H">H</dateFormatItem>
						<dateFormatItem id="HHmm">HH:mm</dateFormatItem>
						<dateFormatItem id="HHmmss">HH:mm:ss</dateFormatItem>
						<dateFormatItem id="Hm">H:mm</dateFormatItem>
						<dateFormatItem id="M">L</dateFormatItem>
						<dateFormatItem id="MEd">E, M-d</dateFormatItem>
						<dateFormatItem id="MMM">LLL</dateFormatItem>
						<dateFormatItem id="MMMEd">E MMM d</dateFormatItem>
						<dateFormatItem id="MMMMEd">E MMMM d</dateFormatItem>
						<dateFormatItem id="MMMMd">d MMMM</dateFormatItem>
						<dateFormatItem id="MMMd">d MMM</dateFormatItem>
						<dateFormatItem id="MMdd">dd.MM</dateFormatItem>
						<dateFormatItem id="Md">d.M</dateFormatItem>
						<dateFormatItem id="d">d</dateFormatItem>
						<dateFormatItem id="mmss">mm:ss</dateFormatItem>
						<dateFormatItem id="ms">mm:ss</dateFormatItem>
						<dateFormatItem id="y">yyyy</dateFormatItem>
						<dateFormatItem id="yM">yyyy-M</dateFormatItem>
						<dateFormatItem id="yMEd">EEE, yyyy-M-d</dateFormatItem>
						<dateFormatItem id="yMMM">MMM. y</dateFormatItem>
						<dateFormatItem id="yMMMEd">E, d MMM. y</dateFormatItem>
						<dateFormatItem id="yMMMM">MMMM y</dateFormatItem>
						<dateFormatItem id="yQ">Q y</dateFormatItem>
						<dateFormatItem id="yQQQ">yyyy QQQ</dateFormatItem>
						<dateFormatItem id="yyMM">MM.yy</dateFormatItem>
						<dateFormatItem id="yyMMM">MMM yy</dateFormatItem>
						<dateFormatItem id="yyMMMEEEd">EEE, d MMM yy</dateFormatItem>
						<dateFormatItem id="yyQ">Q yy</dateFormatItem>
						<dateFormatItem id="yyyy">yyyy</dateFormatItem>
						<dateFormatItem id="yyyyLLLL">LLLL yyyy</dateFormatItem>
						<dateFormatItem id="yyyyMM">MM.yyyy</dateFormatItem>
						<dateFormatItem id="yyyyMMMM">MMMM yyyy</dateFormatItem>
						<dateFormatItem id="yyyyQQQQ">QQQQ yyyy 'г'.</dateFormatItem>
					</availableFormats>
					<intervalFormats>
						<intervalFormatFallback>{0} - {1}</intervalFormatFallback>
						<intervalFormatItem id="M">
							<greatestDifference id="M">M-M</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MEd">
							<greatestDifference id="M">E, MM-dd – E, MM-dd</greatestDifference>
							<greatestDifference id="d">E, MM-dd – E, MM-dd</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MMM">
							<greatestDifference id="M">MMM-MMM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MMMEd">
							<greatestDifference id="M">d MMM - d MMM</greatestDifference>
							<greatestDifference id="d">d-d MMM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MMMM">
							<greatestDifference id="M">LLLL-LLLL</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="MMMd">
							<greatestDifference id="M">d MMM - d MMM</greatestDifference>
							<greatestDifference id="d">d-d MMM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="Md">
							<greatestDifference id="M">dd.MM - dd.MM</greatestDifference>
							<greatestDifference id="d">dd.MM - dd.MM</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="d">
							<greatestDifference id="d">d-d</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="h">
							<greatestDifference id="a">HH-HH</greatestDifference>
							<greatestDifference id="h">HH-HH</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="hm">
							<greatestDifference id="a">HH:mm-HH:mm</greatestDifference>
							<greatestDifference id="h">HH:mm-HH:mm</greatestDifference>
							<greatestDifference id="m">HH:mm-HH:mm</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="hmv">
							<greatestDifference id="a">HH:mm-HH:mm v</greatestDifference>
							<greatestDifference id="h">HH:mm-HH:mm v</greatestDifference>
							<greatestDifference id="m">HH:mm-HH:mm v</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="hv">
							<greatestDifference id="a">HH-HH v</greatestDifference>
							<greatestDifference id="h">HH-HH v</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="y">
							<greatestDifference id="y">y-y</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yM">
							<greatestDifference id="M">MM.yy - MM.yy</greatestDifference>
							<greatestDifference id="y">MM.yy - MM.yy</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMEd">
							<greatestDifference id="M">dd.MM.yy - dd.MM.yy</greatestDifference>
							<greatestDifference id="d">dd.MM.yy - dd.MM.yy</greatestDifference>
							<greatestDifference id="y">dd.MM.yy - dd.MM.yy</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMMM">
							<greatestDifference id="M">MMM-MMM yyyy 'г'.</greatestDifference>
							<greatestDifference id="y">MMM yyyy - MMM yyyy 'г'.</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMMMEd">
							<greatestDifference id="M">d MMM - d MMM yyyy 'г'.</greatestDifference>
							<greatestDifference id="d">d-d MMM yyyy 'г'.</greatestDifference>
							<greatestDifference id="y">d MMM yyyy - d MMM yyyy 'г'.</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMMMM">
							<greatestDifference id="M">LLLL-LLLL yyyy 'г'.</greatestDifference>
							<greatestDifference id="y">LLLL yyyy - LLLL yyyy 'г'.</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMMMd">
							<greatestDifference id="M">d MMM - d MMM yyyy 'г'.</greatestDifference>
							<greatestDifference id="d">d-d MMM yyyy 'г'.</greatestDifference>
							<greatestDifference id="y">d MMM yyyy - d MMM yyyy 'г'.</greatestDifference>
						</intervalFormatItem>
						<intervalFormatItem id="yMd">
							<greatestDifference id="M">dd.MM.yy - dd.MM.yy</greatestDifference>
							<greatestDifference id="d">dd.MM.yy - dd.MM.yy</greatestDifference>
							<greatestDifference id="y">dd.MM.yy - dd.MM.yy</greatestDifference>
						</intervalFormatItem>
					</intervalFormats>
				</dateTimeFormats>
				<fields>
					<field type="era">
						<displayName>Эра</displayName>
					</field>
					<field type="year">
						<displayName>Год</displayName>
					</field>
					<field type="month">
						<displayName>Месяц</displayName>
					</field>
					<field type="week">
						<displayName>Неделя</displayName>
					</field>
					<field type="day">
						<displayName>День</displayName>
						<relative type="0">Сегодня</relative>
						<relative type="1">Завтра</relative>
						<relative type="2">Послезавтра</relative>
						<relative type="-1">Вчера</relative>
						<relative type="-2">Позавчера</relative>
					</field>
					<field type="weekday">
						<displayName>День недели</displayName>
					</field>
					<field type="dayperiod">
						<displayName>AM/PM</displayName>
					</field>
					<field type="hour">
						<displayName>Час</displayName>
					</field>
					<field type="minute">
						<displayName>Минута</displayName>
					</field>
					<field type="second">
						<displayName>Секунда</displayName>
					</field>
					<field type="zone">
						<displayName>Часовой пояс</displayName>
					</field>
				</fields>
			</calendar>
			<calendar type="hebrew">
				<months>
					<monthContext type="format">
						<monthWidth type="abbreviated">
							<month type="1">Тишрей</month>
							<month type="2">Хешван</month>
							<month type="3">Кислев</month>
							<month type="4">Тевет</month>
							<month type="5">Шеват</month>
							<month type="7">Адар</month>
							<month type="8">Нисан</month>
							<month type="9">Ияр</month>
							<month type="10">Сиван</month>
							<month type="11">Таммуз</month>
							<month type="12">Ав</month>
							<month type="13">Элул</month>
						</monthWidth>
						<monthWidth type="wide">
							<month type="1">Тишрей</month>
							<month type="2">Хешван</month>
							<month type="3">Кислев</month>
							<month type="4">Тевет</month>
							<month type="5">Шеват</month>
							<month type="7">Адар</month>
							<month type="8">Нисан</month>
							<month type="9">Ияр</month>
							<month type="10">Сиван</month>
							<month type="11">Таммуз</month>
							<month type="12">Ав</month>
							<month type="13">Элул</month>
						</monthWidth>
					</monthContext>
				</months>
			</calendar>
			<calendar type="islamic">
				<months>
					<monthContext type="format">
						<monthWidth type="abbreviated">
							<month type="1">Мухаррам</month>
							<month type="2">Сафар</month>
							<month type="3">Раби-уль-авваль</month>
							<month type="4">Раби-уль-ахир</month>
							<month type="5">Джумад-уль-авваль</month>
							<month type="6">Джумад-уль-ахир</month>
							<month type="7">Раджаб</month>
							<month type="8">Шаабан</month>
							<month type="9">Рамадан</month>
							<month type="10">Шавваль</month>
							<month type="11">Зуль-Каада</month>
							<month type="12">Зуль-Хиджжа</month>
						</monthWidth>
						<monthWidth type="wide">
							<month type="1">Мухаррам</month>
							<month type="2">Сафар</month>
							<month type="3">Раби-уль-авваль</month>
							<month type="4">Раби-уль-ахир</month>
							<month type="5">Джумад-уль-авваль</month>
							<month type="6">Джумад-уль-ахир</month>
							<month type="7">Раджаб</month>
							<month type="8">Шаабан</month>
							<month type="9">Рамадан</month>
							<month type="10">Шавваль</month>
							<month type="11">Зуль-Каада</month>
							<month type="12">Зуль-Хиджжа</month>
						</monthWidth>
					</monthContext>
				</months>
			</calendar>
			<calendar type="persian">
				<months>
					<monthContext type="format">
						<monthWidth type="abbreviated">
							<month type="1">Фарвардин</month>
							<month type="2">Ордибехешт</month>
							<month type="3">Хордад</month>
							<month type="4">Тир</month>
							<month type="5">Мордад</month>
							<month type="6">Шахривер</month>
							<month type="7">Мехр</month>
							<month type="8">Абан</month>
							<month type="9">Азер</month>
							<month type="10">Дей</month>
							<month type="11">Бахман</month>
						</monthWidth>
						<monthWidth type="wide">
							<month type="1">Фарвардин</month>
							<month type="2">Ордибехешт</month>
							<month type="3">Хордад</month>
							<month type="4">Тир</month>
							<month type="5">Мордад</month>
							<month type="6">Шахривер</month>
							<month type="7">Мехр</month>
							<month type="8">Абан</month>
							<month type="9">Азер</month>
							<month type="10">Дей</month>
							<month type="11">Бахман</month>
							<month type="12">Эсфанд</month>
						</monthWidth>
					</monthContext>
				</months>
			</calendar>
		</calendars>
		<timeZoneNames>
			<hourFormat>+HH:mm;-HH:mm</hourFormat>
			<gmtFormat>GMT{0}</gmtFormat>
			<regionFormat>{0}</regionFormat>
			<fallbackFormat>{1} ({0})</fallbackFormat>
			<zone type="Etc/Unknown">
				<exemplarCity>Неизвестный</exemplarCity>
			</zone>
			<zone type="Europe/Andorra">
				<exemplarCity>Андорра</exemplarCity>
			</zone>
			<zone type="Asia/Dubai">
				<exemplarCity>Дубай</exemplarCity>
			</zone>
			<zone type="Asia/Kabul">
				<exemplarCity>Кабул</exemplarCity>
			</zone>
			<zone type="America/Antigua">
				<exemplarCity>Антигуа</exemplarCity>
			</zone>
			<zone type="America/Anguilla">
				<exemplarCity>Ангилья</exemplarCity>
			</zone>
			<zone type="Europe/Tirane">
				<exemplarCity>Тирана</exemplarCity>
			</zone>
			<zone type="Asia/Yerevan">
				<exemplarCity>Ереван</exemplarCity>
			</zone>
			<zone type="America/Curacao">
				<exemplarCity>Кюрасао</exemplarCity>
			</zone>
			<zone type="Africa/Luanda">
				<exemplarCity>Луанда</exemplarCity>
			</zone>
			<zone type="Antarctica/Rothera">
				<exemplarCity>Ротера</exemplarCity>
			</zone>
			<zone type="Antarctica/Palmer">
				<exemplarCity>Палмер</exemplarCity>
			</zone>
			<zone type="Antarctica/South_Pole">
				<exemplarCity>Южный полюс</exemplarCity>
			</zone>
			<zone type="Antarctica/Syowa">
				<exemplarCity>Сева</exemplarCity>
			</zone>
			<zone type="Antarctica/Mawson">
				<exemplarCity>Моусон</exemplarCity>
			</zone>
			<zone type="Antarctica/Davis">
				<exemplarCity>Дейвис</exemplarCity>
			</zone>
			<zone type="Antarctica/Vostok">
				<exemplarCity>Восток</exemplarCity>
			</zone>
			<zone type="Antarctica/Casey">
				<exemplarCity>Кейси</exemplarCity>
			</zone>
			<zone type="Antarctica/DumontDUrville">
				<exemplarCity>Дюмон-д'Юрвиль</exemplarCity>
			</zone>
			<zone type="Antarctica/McMurdo">
				<exemplarCity>Мак-Мердо</exemplarCity>
			</zone>
			<zone type="America/Argentina/Rio_Gallegos">
				<exemplarCity>Рио-Гальегос</exemplarCity>
			</zone>
			<zone type="America/Mendoza">
				<exemplarCity>Мендоса</exemplarCity>
			</zone>
			<zone type="America/Argentina/San_Juan">
				<exemplarCity>Сан-Хуан</exemplarCity>
			</zone>
			<zone type="America/Argentina/Ushuaia">
				<exemplarCity>Ушуая</exemplarCity>
			</zone>
			<zone type="America/Argentina/La_Rioja">
				<exemplarCity>Ла-Риоха</exemplarCity>
			</zone>
			<zone type="America/Argentina/San_Luis">
				<exemplarCity>Сан-Луис</exemplarCity>
			</zone>
			<zone type="America/Catamarca">
				<exemplarCity>Катамарка</exemplarCity>
			</zone>
			<zone type="America/Jujuy">
				<exemplarCity>Жужуй</exemplarCity>
			</zone>
			<zone type="America/Argentina/Tucuman">
				<exemplarCity>Тукуман</exemplarCity>
			</zone>
			<zone type="America/Cordoba">
				<exemplarCity>Кордова</exemplarCity>
			</zone>
			<zone type="America/Buenos_Aires">
				<exemplarCity>Буэнос-Айрес</exemplarCity>
			</zone>
			<zone type="Pacific/Pago_Pago">
				<exemplarCity>Паго-Паго</exemplarCity>
			</zone>
			<zone type="Europe/Vienna">
				<exemplarCity>Вена</exemplarCity>
			</zone>
			<zone type="Australia/Perth">
				<exemplarCity>Перт</exemplarCity>
			</zone>
			<zone type="Australia/Eucla">
				<exemplarCity>Юкла</exemplarCity>
			</zone>
			<zone type="Australia/Darwin">
				<exemplarCity>Дарвин</exemplarCity>
			</zone>
			<zone type="Australia/Adelaide">
				<exemplarCity>Аделаида</exemplarCity>
			</zone>
			<zone type="Australia/Broken_Hill">
				<exemplarCity>Брокен-Хилл</exemplarCity>
			</zone>
			<zone type="Australia/Currie">
				<exemplarCity>Керри</exemplarCity>
			</zone>
			<zone type="Australia/Melbourne">
				<exemplarCity>Мельбурн</exemplarCity>
			</zone>
			<zone type="Australia/Hobart">
				<exemplarCity>Хобарт</exemplarCity>
			</zone>
			<zone type="Australia/Lindeman">
				<exemplarCity>Линдеман</exemplarCity>
			</zone>
			<zone type="Australia/Sydney">
				<exemplarCity>Сидней</exemplarCity>
			</zone>
			<zone type="Australia/Brisbane">
				<exemplarCity>Брисбен</exemplarCity>
			</zone>
			<zone type="Australia/Lord_Howe">
				<exemplarCity>Лорд-Хау, о-в</exemplarCity>
			</zone>
			<zone type="America/Aruba">
				<exemplarCity>Аруба</exemplarCity>
			</zone>
			<zone type="Europe/Mariehamn">
				<exemplarCity>Мариехамн</exemplarCity>
			</zone>
			<zone type="Asia/Baku">
				<exemplarCity>Баку</exemplarCity>
			</zone>
			<zone type="Europe/Sarajevo">
				<exemplarCity>Сараево</exemplarCity>
			</zone>
			<zone type="America/Barbados">
				<exemplarCity>Барбадос</exemplarCity>
			</zone>
			<zone type="Asia/Dhaka">
				<exemplarCity>Дакка</exemplarCity>
			</zone>
			<zone type="Europe/Brussels">
				<exemplarCity>Брюссель</exemplarCity>
			</zone>
			<zone type="Africa/Ouagadougou">
				<exemplarCity>Уагадугу</exemplarCity>
			</zone>
			<zone type="Europe/Sofia">
				<exemplarCity>София</exemplarCity>
			</zone>
			<zone type="Asia/Bahrain">
				<exemplarCity>Бахрейн</exemplarCity>
			</zone>
			<zone type="Africa/Bujumbura">
				<exemplarCity>Бужумбура</exemplarCity>
			</zone>
			<zone type="Africa/Porto-Novo">
				<exemplarCity>Порто-Ново</exemplarCity>
			</zone>
			<zone type="Atlantic/Bermuda">
				<exemplarCity>Бермуды</exemplarCity>
			</zone>
			<zone type="Asia/Brunei">
				<exemplarCity>Бруней</exemplarCity>
			</zone>
			<zone type="America/La_Paz">
				<exemplarCity>Ла-Пас</exemplarCity>
			</zone>
			<zone type="America/Eirunepe">
				<exemplarCity>Эйрунепе</exemplarCity>
			</zone>
			<zone type="America/Rio_Branco">
				<exemplarCity>Риу-Бранку</exemplarCity>
			</zone>
			<zone type="America/Porto_Velho">
				<exemplarCity>Порту-Велью</exemplarCity>
			</zone>
			<zone type="America/Boa_Vista">
				<exemplarCity>Боа-Виста</exemplarCity>
			</zone>
			<zone type="America/Manaus">
				<exemplarCity>Манаус</exemplarCity>
			</zone>
			<zone type="America/Cuiaba">
				<exemplarCity>Куяба</exemplarCity>
			</zone>
			<zone type="America/Campo_Grande">
				<exemplarCity>Кампу-Гранди</exemplarCity>
			</zone>
			<zone type="America/Belem">
				<exemplarCity>Белен</exemplarCity>
			</zone>
			<zone type="America/Araguaina">
				<exemplarCity>Арагуаина</exemplarCity>
			</zone>
			<zone type="America/Sao_Paulo">
				<exemplarCity>Сан-Паулу</exemplarCity>
			</zone>
			<zone type="America/Bahia">
				<exemplarCity>Баия</exemplarCity>
			</zone>
			<zone type="America/Fortaleza">
				<exemplarCity>Форталеза</exemplarCity>
			</zone>
			<zone type="America/Maceio">
				<exemplarCity>Масейо</exemplarCity>
			</zone>
			<zone type="America/Recife">
				<exemplarCity>Ресифи</exemplarCity>
			</zone>
			<zone type="America/Noronha">
				<exemplarCity>Норонха</exemplarCity>
			</zone>
			<zone type="America/Nassau">
				<exemplarCity>Нассау</exemplarCity>
			</zone>
			<zone type="Asia/Thimphu">
				<exemplarCity>Тимпу</exemplarCity>
			</zone>
			<zone type="Africa/Gaborone">
				<exemplarCity>Габороне</exemplarCity>
			</zone>
			<zone type="Europe/Minsk">
				<exemplarCity>Минск</exemplarCity>
			</zone>
			<zone type="America/Belize">
				<exemplarCity>Белиз</exemplarCity>
			</zone>
			<zone type="America/Dawson">
				<exemplarCity>Доусон</exemplarCity>
			</zone>
			<zone type="America/Whitehorse">
				<exemplarCity>Уайтхорс</exemplarCity>
			</zone>
			<zone type="America/Inuvik">
				<exemplarCity>Инувик</exemplarCity>
			</zone>
			<zone type="America/Vancouver">
				<exemplarCity>Ванкувер</exemplarCity>
			</zone>
			<zone type="America/Dawson_Creek">
				<exemplarCity>Досон-Крик</exemplarCity>
			</zone>
			<zone type="America/Yellowknife">
				<exemplarCity>Йеллоунайф</exemplarCity>
			</zone>
			<zone type="America/Edmonton">
				<exemplarCity>Эдмонтон</exemplarCity>
			</zone>
			<zone type="America/Swift_Current">
				<exemplarCity>Свифт-Карент</exemplarCity>
			</zone>
			<zone type="America/Cambridge_Bay">
				<exemplarCity>Кеймбридж-Бей</exemplarCity>
			</zone>
			<zone type="America/Regina">
				<exemplarCity>Реджайна</exemplarCity>
			</zone>
			<zone type="America/Winnipeg">
				<exemplarCity>Виннипег</exemplarCity>
			</zone>
			<zone type="America/Resolute">
				<exemplarCity>Резолют</exemplarCity>
			</zone>
			<zone type="America/Rainy_River">
				<exemplarCity>Рейни-Ривер</exemplarCity>
			</zone>
			<zone type="America/Rankin_Inlet">
				<exemplarCity>Ранкин-Инлет</exemplarCity>
			</zone>
			<zone type="America/Coral_Harbour">
				<exemplarCity>Корал-Харбор</exemplarCity>
			</zone>
			<zone type="America/Thunder_Bay">
				<exemplarCity>Тандер-Бей</exemplarCity>
			</zone>
			<zone type="America/Nipigon">
				<exemplarCity>Нипигон</exemplarCity>
			</zone>
			<zone type="America/Toronto">
				<exemplarCity>Торонто</exemplarCity>
			</zone>
			<zone type="America/Montreal">
				<exemplarCity>Монреаль</exemplarCity>
			</zone>
			<zone type="America/Iqaluit">
				<exemplarCity>Икалуит</exemplarCity>
			</zone>
			<zone type="America/Pangnirtung">
				<exemplarCity>Пангниртанг</exemplarCity>
			</zone>
			<zone type="America/Moncton">
				<exemplarCity>Монктон</exemplarCity>
			</zone>
			<zone type="America/Halifax">
				<exemplarCity>Галифакс</exemplarCity>
			</zone>
			<zone type="America/Goose_Bay">
				<exemplarCity>Гус-Бей</exemplarCity>
			</zone>
			<zone type="America/Glace_Bay">
				<exemplarCity>Глейс-Бей</exemplarCity>
			</zone>
			<zone type="America/Blanc-Sablon">
				<exemplarCity>Бланк-Саблон</exemplarCity>
			</zone>
			<zone type="America/St_Johns">
				<exemplarCity>Сент-Джонс</exemplarCity>
			</zone>
			<zone type="Indian/Cocos">
				<exemplarCity>Кокосовые острова</exemplarCity>
			</zone>
			<zone type="Africa/Kinshasa">
				<exemplarCity>Киншаса</exemplarCity>
			</zone>
			<zone type="Africa/Lubumbashi">
				<exemplarCity>Лубумбаши</exemplarCity>
			</zone>
			<zone type="Africa/Bangui">
				<exemplarCity>Банги</exemplarCity>
			</zone>
			<zone type="Africa/Brazzaville">
				<exemplarCity>Браззавиль</exemplarCity>
			</zone>
			<zone type="Europe/Zurich">
				<exemplarCity>Цюрих</exemplarCity>
			</zone>
			<zone type="Africa/Abidjan">
				<exemplarCity>Абиджан</exemplarCity>
			</zone>
			<zone type="Pacific/Rarotonga">
				<exemplarCity>Раротонга</exemplarCity>
			</zone>
			<zone type="Pacific/Easter">
				<exemplarCity>Пасхи, о-в</exemplarCity>
			</zone>
			<zone type="America/Santiago">
				<exemplarCity>Сантьяго</exemplarCity>
			</zone>
			<zone type="Africa/Douala">
				<exemplarCity>Дуала</exemplarCity>
			</zone>
			<zone type="Asia/Kashgar">
				<exemplarCity>Кашгар</exemplarCity>
			</zone>
			<zone type="Asia/Urumqi">
				<exemplarCity>Урумчи</exemplarCity>
			</zone>
			<zone type="Asia/Chongqing">
				<exemplarCity>Чунцин</exemplarCity>
			</zone>
			<zone type="Asia/Shanghai">
				<exemplarCity>Шанхай</exemplarCity>
			</zone>
			<zone type="Asia/Harbin">
				<exemplarCity>Харбин</exemplarCity>
			</zone>
			<zone type="America/Bogota">
				<exemplarCity>Богота</exemplarCity>
			</zone>
			<zone type="America/Costa_Rica">
				<exemplarCity>Коста-Рика</exemplarCity>
			</zone>
			<zone type="America/Havana">
				<exemplarCity>Гавана</exemplarCity>
			</zone>
			<zone type="Atlantic/Cape_Verde">
				<exemplarCity>Острова Зеленого Мыса</exemplarCity>
			</zone>
			<zone type="Indian/Christmas">
				<exemplarCity>Рождества, о-в</exemplarCity>
			</zone>
			<zone type="Asia/Nicosia">
				<exemplarCity>Никосия</exemplarCity>
			</zone>
			<zone type="Europe/Prague">
				<exemplarCity>Прага</exemplarCity>
			</zone>
			<zone type="Europe/Berlin">
				<exemplarCity>Берлин</exemplarCity>
			</zone>
			<zone type="Africa/Djibouti">
				<exemplarCity>Джибути</exemplarCity>
			</zone>
			<zone type="Europe/Copenhagen">
				<exemplarCity>Копенгаген</exemplarCity>
			</zone>
			<zone type="America/Dominica">
				<exemplarCity>Доминика</exemplarCity>
			</zone>
			<zone type="America/Santo_Domingo">
				<exemplarCity>Санто-Доминго</exemplarCity>
			</zone>
			<zone type="Africa/Algiers">
				<exemplarCity>Алжир</exemplarCity>
			</zone>
			<zone type="Pacific/Galapagos">
				<exemplarCity>Галапагос, о-ва</exemplarCity>
			</zone>
			<zone type="America/Guayaquil">
				<exemplarCity>Гуаякиль</exemplarCity>
			</zone>
			<zone type="Europe/Tallinn">
				<exemplarCity>Таллин</exemplarCity>
			</zone>
			<zone type="Africa/Cairo">
				<exemplarCity>Каир</exemplarCity>
			</zone>
			<zone type="Africa/El_Aaiun">
				<exemplarCity>Эль-Аюн</exemplarCity>
			</zone>
			<zone type="Africa/Asmera">
				<exemplarCity>Асмера</exemplarCity>
			</zone>
			<zone type="Atlantic/Canary">
				<exemplarCity>Канарские о-ва</exemplarCity>
			</zone>
			<zone type="Africa/Ceuta">
				<exemplarCity>Сеута</exemplarCity>
			</zone>
			<zone type="Europe/Madrid">
				<exemplarCity>Мадрид</exemplarCity>
			</zone>
			<zone type="Africa/Addis_Ababa">
				<exemplarCity>Аддис-Абеба</exemplarCity>
			</zone>
			<zone type="Europe/Helsinki">
				<exemplarCity>Хельсинки</exemplarCity>
			</zone>
			<zone type="Pacific/Fiji">
				<exemplarCity>Фиджи</exemplarCity>
			</zone>
			<zone type="Atlantic/Stanley">
				<exemplarCity>Стэнли</exemplarCity>
			</zone>
			<zone type="Pacific/Truk">
				<exemplarCity>Трук, о-ва</exemplarCity>
			</zone>
			<zone type="Pacific/Ponape">
				<exemplarCity>Понапе, о-в</exemplarCity>
			</zone>
			<zone type="Pacific/Kosrae">
				<exemplarCity>Косрае</exemplarCity>
			</zone>
			<zone type="Atlantic/Faeroe">
				<exemplarCity>Фарерские острова</exemplarCity>
			</zone>
			<zone type="Europe/Paris">
				<exemplarCity>Париж</exemplarCity>
			</zone>
			<zone type="Africa/Libreville">
				<exemplarCity>Либревиль</exemplarCity>
			</zone>
			<zone type="Europe/London">
				<exemplarCity>Лондон</exemplarCity>
			</zone>
			<zone type="America/Grenada">
				<exemplarCity>Гренада</exemplarCity>
			</zone>
			<zone type="Asia/Tbilisi">
				<exemplarCity>Тбилиси</exemplarCity>
			</zone>
			<zone type="America/Cayenne">
				<exemplarCity>Кайенна</exemplarCity>
			</zone>
			<zone type="Europe/Guernsey">
				<exemplarCity>Гернси</exemplarCity>
			</zone>
			<zone type="Africa/Accra">
				<exemplarCity>Аккра</exemplarCity>
			</zone>
			<zone type="Europe/Gibraltar">
				<exemplarCity>Гибралтар</exemplarCity>
			</zone>
			<zone type="America/Thule">
				<exemplarCity>Туле</exemplarCity>
			</zone>
			<zone type="America/Godthab">
				<exemplarCity>Готхоб</exemplarCity>
			</zone>
			<zone type="America/Scoresbysund">
				<exemplarCity>Скорсбисунн</exemplarCity>
			</zone>
			<zone type="America/Danmarkshavn">
				<exemplarCity>Денмарксхавн</exemplarCity>
			</zone>
			<zone type="Africa/Banjul">
				<exemplarCity>Банжул</exemplarCity>
			</zone>
			<zone type="Africa/Conakry">
				<exemplarCity>Конакри</exemplarCity>
			</zone>
			<zone type="America/Guadeloupe">
				<exemplarCity>Гваделупа</exemplarCity>
			</zone>
			<zone type="Africa/Malabo">
				<exemplarCity>Малабо</exemplarCity>
			</zone>
			<zone type="Europe/Athens">
				<exemplarCity>Афины</exemplarCity>
			</zone>
			<zone type="Atlantic/South_Georgia">
				<exemplarCity>Ю.Джорджия и Ю.Сэндвинчевы о-ва</exemplarCity>
			</zone>
			<zone type="America/Guatemala">
				<exemplarCity>Гватемала</exemplarCity>
			</zone>
			<zone type="Pacific/Guam">
				<exemplarCity>Гуам</exemplarCity>
			</zone>
			<zone type="Africa/Bissau">
				<exemplarCity>Бисау</exemplarCity>
			</zone>
			<zone type="America/Guyana">
				<exemplarCity>Гайана</exemplarCity>
			</zone>
			<zone type="Asia/Hong_Kong">
				<exemplarCity>Гонконг</exemplarCity>
			</zone>
			<zone type="America/Tegucigalpa">
				<exemplarCity>Тегусигальпа</exemplarCity>
			</zone>
			<zone type="Europe/Zagreb">
				<exemplarCity>Загреб</exemplarCity>
			</zone>
			<zone type="America/Port-au-Prince">
				<exemplarCity>Порт-о-Пренс</exemplarCity>
			</zone>
			<zone type="Europe/Budapest">
				<exemplarCity>Будапешт</exemplarCity>
			</zone>
			<zone type="Asia/Jakarta">
				<exemplarCity>Джакарта</exemplarCity>
			</zone>
			<zone type="Asia/Pontianak">
				<exemplarCity>Понтианак</exemplarCity>
			</zone>
			<zone type="Asia/Makassar">
				<exemplarCity>Макасар</exemplarCity>
			</zone>
			<zone type="Asia/Jayapura">
				<exemplarCity>Джайпур</exemplarCity>
			</zone>
			<zone type="Europe/Dublin">
				<exemplarCity>Дублин</exemplarCity>
			</zone>
			<zone type="Asia/Jerusalem">
				<exemplarCity>Иерусалим</exemplarCity>
			</zone>
			<zone type="Europe/Isle_of_Man">
				<exemplarCity>Мэн, о-в</exemplarCity>
			</zone>
			<zone type="Asia/Calcutta">
				<exemplarCity>Калькутта</exemplarCity>
			</zone>
			<zone type="Indian/Chagos">
				<exemplarCity>Чагос</exemplarCity>
			</zone>
			<zone type="Asia/Baghdad">
				<exemplarCity>Багдад</exemplarCity>
			</zone>
			<zone type="Asia/Tehran">
				<exemplarCity>Тегеран</exemplarCity>
			</zone>
			<zone type="Atlantic/Reykjavik">
				<exemplarCity>Рейкьявик</exemplarCity>
			</zone>
			<zone type="Europe/Rome">
				<exemplarCity>Рим</exemplarCity>
			</zone>
			<zone type="Europe/Jersey">
				<exemplarCity>Джерси</exemplarCity>
			</zone>
			<zone type="America/Jamaica">
				<exemplarCity>Ямайка</exemplarCity>
			</zone>
			<zone type="Asia/Amman">
				<exemplarCity>Амман</exemplarCity>
			</zone>
			<zone type="Asia/Tokyo">
				<exemplarCity>Токио</exemplarCity>
			</zone>
			<zone type="Africa/Nairobi">
				<exemplarCity>Найроби</exemplarCity>
			</zone>
			<zone type="Asia/Bishkek">
				<exemplarCity>Бишкек</exemplarCity>
			</zone>
			<zone type="Asia/Phnom_Penh">
				<exemplarCity>Пномпень</exemplarCity>
			</zone>
			<zone type="Pacific/Enderbury">
				<exemplarCity>Эндербери, о-в</exemplarCity>
			</zone>
			<zone type="Pacific/Kiritimati">
				<exemplarCity>Киритимати</exemplarCity>
			</zone>
			<zone type="Pacific/Tarawa">
				<exemplarCity>Тарава</exemplarCity>
			</zone>
			<zone type="Indian/Comoro">
				<exemplarCity>Коморские острова</exemplarCity>
			</zone>
			<zone type="America/St_Kitts">
				<exemplarCity>Сент-Китс</exemplarCity>
			</zone>
			<zone type="Asia/Pyongyang">
				<exemplarCity>Пхеньян</exemplarCity>
			</zone>
			<zone type="Asia/Seoul">
				<exemplarCity>Сеул</exemplarCity>
			</zone>
			<zone type="Asia/Kuwait">
				<exemplarCity>Кувейт</exemplarCity>
			</zone>
			<zone type="America/Cayman">
				<exemplarCity>Каймановы острова</exemplarCity>
			</zone>
			<zone type="Asia/Aqtau">
				<exemplarCity>Актау</exemplarCity>
			</zone>
			<zone type="Asia/Oral">
				<exemplarCity>Орал (Уральск)</exemplarCity>
			</zone>
			<zone type="Asia/Aqtobe">
				<exemplarCity>Актобе (Актюбинск)</exemplarCity>
			</zone>
			<zone type="Asia/Qyzylorda">
				<exemplarCity>Кызылорда</exemplarCity>
			</zone>
			<zone type="Asia/Almaty">
				<exemplarCity>Алматы</exemplarCity>
			</zone>
			<zone type="Asia/Vientiane">
				<exemplarCity>Вьентьян</exemplarCity>
			</zone>
			<zone type="Asia/Beirut">
				<exemplarCity>Бейрут</exemplarCity>
			</zone>
			<zone type="America/St_Lucia">
				<exemplarCity>Сент-Люсия</exemplarCity>
			</zone>
			<zone type="Europe/Vaduz">
				<exemplarCity>Вадуц</exemplarCity>
			</zone>
			<zone type="Asia/Colombo">
				<exemplarCity>Коломбо</exemplarCity>
			</zone>
			<zone type="Africa/Monrovia">
				<exemplarCity>Монровия</exemplarCity>
			</zone>
			<zone type="Africa/Maseru">
				<exemplarCity>Масеру</exemplarCity>
			</zone>
			<zone type="Europe/Vilnius">
				<exemplarCity>Вильнюс</exemplarCity>
			</zone>
			<zone type="Europe/Luxembourg">
				<exemplarCity>Люксембург</exemplarCity>
			</zone>
			<zone type="Europe/Riga">
				<exemplarCity>Рига</exemplarCity>
			</zone>
			<zone type="Africa/Tripoli">
				<exemplarCity>Триполи</exemplarCity>
			</zone>
			<zone type="Africa/Casablanca">
				<exemplarCity>Касабланка</exemplarCity>
			</zone>
			<zone type="Europe/Monaco">
				<exemplarCity>Монако</exemplarCity>
			</zone>
			<zone type="Europe/Chisinau">
				<exemplarCity>Кишинев</exemplarCity>
			</zone>
			<zone type="Europe/Podgorica">
				<exemplarCity>Подгорица</exemplarCity>
			</zone>
			<zone type="Indian/Antananarivo">
				<exemplarCity>Антананариву</exemplarCity>
			</zone>
			<zone type="Pacific/Kwajalein">
				<exemplarCity>Кваджалейн</exemplarCity>
			</zone>
			<zone type="Pacific/Majuro">
				<exemplarCity>Маджуро</exemplarCity>
			</zone>
			<zone type="Europe/Skopje">
				<exemplarCity>Скопье</exemplarCity>
			</zone>
			<zone type="Africa/Bamako">
				<exemplarCity>Бамако</exemplarCity>
			</zone>
			<zone type="Asia/Rangoon">
				<exemplarCity>Рангун</exemplarCity>
			</zone>
			<zone type="Asia/Hovd">
				<exemplarCity>Ховд</exemplarCity>
			</zone>
			<zone type="Asia/Ulaanbaatar">
				<exemplarCity>Улан-Батор</exemplarCity>
			</zone>
			<zone type="Asia/Choibalsan">
				<exemplarCity>Чойбалсан</exemplarCity>
			</zone>
			<zone type="Asia/Macau">
				<exemplarCity>Макао</exemplarCity>
			</zone>
			<zone type="Pacific/Saipan">
				<exemplarCity>Сайпан</exemplarCity>
			</zone>
			<zone type="America/Martinique">
				<exemplarCity>Мартиника</exemplarCity>
			</zone>
			<zone type="Africa/Nouakchott">
				<exemplarCity>Нуакшот</exemplarCity>
			</zone>
			<zone type="America/Montserrat">
				<exemplarCity>Монсеррат</exemplarCity>
			</zone>
			<zone type="Europe/Malta">
				<exemplarCity>Мальта</exemplarCity>
			</zone>
			<zone type="Indian/Mauritius">
				<exemplarCity>Маврикий</exemplarCity>
			</zone>
			<zone type="Indian/Maldives">
				<exemplarCity>Мальдивы</exemplarCity>
			</zone>
			<zone type="Africa/Blantyre">
				<exemplarCity>Блантайр</exemplarCity>
			</zone>
			<zone type="America/Tijuana">
				<exemplarCity>Тихуана</exemplarCity>
			</zone>
			<zone type="America/Hermosillo">
				<exemplarCity>Эрмосильо</exemplarCity>
			</zone>
			<zone type="America/Mazatlan">
				<exemplarCity>Масатлан</exemplarCity>
			</zone>
			<zone type="America/Chihuahua">
				<exemplarCity>Чиуауа</exemplarCity>
			</zone>
			<zone type="America/Monterrey">
				<exemplarCity>Монтеррей</exemplarCity>
			</zone>
			<zone type="America/Mexico_City">
				<exemplarCity>Мехико</exemplarCity>
			</zone>
			<zone type="America/Merida">
				<exemplarCity>Мерида</exemplarCity>
			</zone>
			<zone type="America/Cancun">
				<exemplarCity>Канкун</exemplarCity>
			</zone>
			<zone type="Asia/Kuala_Lumpur">
				<exemplarCity>Куала-Лумпур</exemplarCity>
			</zone>
			<zone type="Asia/Kuching">
				<exemplarCity>Кучинг</exemplarCity>
			</zone>
			<zone type="Africa/Maputo">
				<exemplarCity>Мапуту</exemplarCity>
			</zone>
			<zone type="Africa/Windhoek">
				<exemplarCity>Виндхук</exemplarCity>
			</zone>
			<zone type="Pacific/Noumea">
				<exemplarCity>Нумеа</exemplarCity>
			</zone>
			<zone type="Africa/Niamey">
				<exemplarCity>Ниамей</exemplarCity>
			</zone>
			<zone type="Pacific/Norfolk">
				<exemplarCity>Норфолк</exemplarCity>
			</zone>
			<zone type="Africa/Lagos">
				<exemplarCity>Лагос</exemplarCity>
			</zone>
			<zone type="America/Managua">
				<exemplarCity>Манагуа</exemplarCity>
			</zone>
			<zone type="Europe/Amsterdam">
				<exemplarCity>Амстердам</exemplarCity>
			</zone>
			<zone type="Europe/Oslo">
				<exemplarCity>Осло</exemplarCity>
			</zone>
			<zone type="Asia/Katmandu">
				<exemplarCity>Катманду</exemplarCity>
			</zone>
			<zone type="Pacific/Nauru">
				<exemplarCity>Науру</exemplarCity>
			</zone>
			<zone type="Pacific/Niue">
				<exemplarCity>Ниуэ</exemplarCity>
			</zone>
			<zone type="Pacific/Chatham">
				<exemplarCity>Чатем, о-в</exemplarCity>
			</zone>
			<zone type="Pacific/Auckland">
				<exemplarCity>Окленд</exemplarCity>
			</zone>
			<zone type="Asia/Muscat">
				<exemplarCity>Маскат</exemplarCity>
			</zone>
			<zone type="America/Panama">
				<exemplarCity>Панама</exemplarCity>
			</zone>
			<zone type="America/Lima">
				<exemplarCity>Лима</exemplarCity>
			</zone>
			<zone type="Pacific/Tahiti">
				<exemplarCity>Таити, о-в</exemplarCity>
			</zone>
			<zone type="Pacific/Marquesas">
				<exemplarCity>Маркизские о-ва</exemplarCity>
			</zone>
			<zone type="Pacific/Gambier">
				<exemplarCity>Гамбье, о-ва</exemplarCity>
			</zone>
			<zone type="Pacific/Port_Moresby">
				<exemplarCity>Порт-Морсби</exemplarCity>
			</zone>
			<zone type="Asia/Manila">
				<exemplarCity>Манила</exemplarCity>
			</zone>
			<zone type="Asia/Karachi">
				<exemplarCity>Карачи</exemplarCity>
			</zone>
			<zone type="Europe/Warsaw">
				<exemplarCity>Варшава</exemplarCity>
			</zone>
			<zone type="America/Miquelon">
				<exemplarCity>Микелон</exemplarCity>
			</zone>
			<zone type="Pacific/Pitcairn">
				<exemplarCity>Питкерн</exemplarCity>
			</zone>
			<zone type="America/Puerto_Rico">
				<exemplarCity>Пуэрто-Рико</exemplarCity>
			</zone>
			<zone type="Asia/Gaza">
				<exemplarCity>Газа</exemplarCity>
			</zone>
			<zone type="Atlantic/Azores">
				<exemplarCity>Азорские о-ва</exemplarCity>
			</zone>
			<zone type="Atlantic/Madeira">
				<exemplarCity>Мадейра, о-в</exemplarCity>
			</zone>
			<zone type="Europe/Lisbon">
				<exemplarCity>Лиссабон</exemplarCity>
			</zone>
			<zone type="Pacific/Palau">
				<exemplarCity>Палау</exemplarCity>
			</zone>
			<zone type="America/Asuncion">
				<exemplarCity>Асунсьон</exemplarCity>
			</zone>
			<zone type="Asia/Qatar">
				<exemplarCity>Катар</exemplarCity>
			</zone>
			<zone type="Indian/Reunion">
				<exemplarCity>Реюньон</exemplarCity>
			</zone>
			<zone type="Europe/Bucharest">
				<exemplarCity>Бухарест</exemplarCity>
			</zone>
			<zone type="Europe/Belgrade">
				<exemplarCity>Белград</exemplarCity>
			</zone>
			<zone type="Europe/Kaliningrad">
				<exemplarCity>Калининград</exemplarCity>
			</zone>
			<zone type="Europe/Moscow">
				<exemplarCity>Москва</exemplarCity>
			</zone>
			<zone type="Europe/Volgograd">
				<exemplarCity>Волгоград</exemplarCity>
			</zone>
			<zone type="Europe/Samara">
				<exemplarCity>Самара</exemplarCity>
			</zone>
			<zone type="Asia/Yekaterinburg">
				<exemplarCity>Екатеринбург</exemplarCity>
			</zone>
			<zone type="Asia/Omsk">
				<exemplarCity>Омск</exemplarCity>
			</zone>
			<zone type="Asia/Novosibirsk">
				<exemplarCity>Новосибирск</exemplarCity>
			</zone>
			<zone type="Asia/Krasnoyarsk">
				<exemplarCity>Красноярск</exemplarCity>
			</zone>
			<zone type="Asia/Irkutsk">
				<exemplarCity>Иркутск</exemplarCity>
			</zone>
			<zone type="Asia/Yakutsk">
				<exemplarCity>Якутск</exemplarCity>
			</zone>
			<zone type="Asia/Vladivostok">
				<exemplarCity>Владивосток</exemplarCity>
			</zone>
			<zone type="Asia/Sakhalin">
				<exemplarCity>Сахалин, о-в</exemplarCity>
			</zone>
			<zone type="Asia/Magadan">
				<exemplarCity>Магадан</exemplarCity>
			</zone>
			<zone type="Asia/Kamchatka">
				<exemplarCity>Петропавловск-Камчатский</exemplarCity>
			</zone>
			<zone type="Asia/Anadyr">
				<exemplarCity>Анадырь</exemplarCity>
			</zone>
			<zone type="Africa/Kigali">
				<exemplarCity>Кигали</exemplarCity>
			</zone>
			<zone type="Asia/Riyadh">
				<exemplarCity>Эр-Рияд</exemplarCity>
			</zone>
			<zone type="Pacific/Guadalcanal">
				<exemplarCity>Гвадалканал</exemplarCity>
			</zone>
			<zone type="Indian/Mahe">
				<exemplarCity>Маэ</exemplarCity>
			</zone>
			<zone type="Africa/Khartoum">
				<exemplarCity>Хартум</exemplarCity>
			</zone>
			<zone type="Europe/Stockholm">
				<exemplarCity>Стокгольм</exemplarCity>
			</zone>
			<zone type="Asia/Singapore">
				<exemplarCity>Сингапур</exemplarCity>
			</zone>
			<zone type="Atlantic/St_Helena">
				<exemplarCity>Св. Елены, о-в</exemplarCity>
			</zone>
			<zone type="Europe/Ljubljana">
				<exemplarCity>Любляна</exemplarCity>
			</zone>
			<zone type="Arctic/Longyearbyen">
				<exemplarCity>Лонгйир</exemplarCity>
			</zone>
			<zone type="Europe/Bratislava">
				<exemplarCity>Братислава</exemplarCity>
			</zone>
			<zone type="Africa/Freetown">
				<exemplarCity>Фритаун</exemplarCity>
			</zone>
			<zone type="Europe/San_Marino">
				<exemplarCity>Сан-Марино</exemplarCity>
			</zone>
			<zone type="Africa/Dakar">
				<exemplarCity>Дакар</exemplarCity>
			</zone>
			<zone type="Africa/Mogadishu">
				<exemplarCity>Могадишо</exemplarCity>
			</zone>
			<zone type="America/Paramaribo">
				<exemplarCity>Парамарибо</exemplarCity>
			</zone>
			<zone type="Africa/Sao_Tome">
				<exemplarCity>Сан-Томе</exemplarCity>
			</zone>
			<zone type="America/El_Salvador">
				<exemplarCity>Сальвадор</exemplarCity>
			</zone>
			<zone type="Asia/Damascus">
				<exemplarCity>Дамаск</exemplarCity>
			</zone>
			<zone type="Africa/Mbabane">
				<exemplarCity>Мбабане</exemplarCity>
			</zone>
			<zone type="America/Grand_Turk">
				<exemplarCity>Гранд Турк</exemplarCity>
			</zone>
			<zone type="Africa/Ndjamena">
				<exemplarCity>Нджамена</exemplarCity>
			</zone>
			<zone type="Indian/Kerguelen">
				<exemplarCity>Кергелен</exemplarCity>
			</zone>
			<zone type="Africa/Lome">
				<exemplarCity>Ломе</exemplarCity>
			</zone>
			<zone type="Asia/Bangkok">
				<exemplarCity>Бангкок</exemplarCity>
			</zone>
			<zone type="Asia/Dushanbe">
				<exemplarCity>Душанбе</exemplarCity>
			</zone>
			<zone type="Pacific/Fakaofo">
				<exemplarCity>Факаофо</exemplarCity>
			</zone>
			<zone type="Asia/Dili">
				<exemplarCity>Дили</exemplarCity>
			</zone>
			<zone type="Asia/Ashgabat">
				<exemplarCity>Ашгабат</exemplarCity>
			</zone>
			<zone type="Africa/Tunis">
				<exemplarCity>Тунис</exemplarCity>
			</zone>
			<zone type="Pacific/Tongatapu">
				<exemplarCity>Тонгатапу</exemplarCity>
			</zone>
			<zone type="Europe/Istanbul">
				<exemplarCity>Стамбул</exemplarCity>
			</zone>
			<zone type="America/Port_of_Spain">
				<exemplarCity>Порт-оф-Спейн</exemplarCity>
			</zone>
			<zone type="Pacific/Funafuti">
				<exemplarCity>Фунафути</exemplarCity>
			</zone>
			<zone type="Asia/Taipei">
				<exemplarCity>Тайбэй</exemplarCity>
			</zone>
			<zone type="Africa/Dar_es_Salaam">
				<exemplarCity>Дар-эс-Салам</exemplarCity>
			</zone>
			<zone type="Europe/Uzhgorod">
				<exemplarCity>Ужгород</exemplarCity>
			</zone>
			<zone type="Europe/Kiev">
				<exemplarCity>Киев</exemplarCity>
			</zone>
			<zone type="Europe/Simferopol">
				<exemplarCity>Симферополь</exemplarCity>
			</zone>
			<zone type="Europe/Zaporozhye">
				<exemplarCity>Запорожье</exemplarCity>
			</zone>
			<zone type="Africa/Kampala">
				<exemplarCity>Кампала</exemplarCity>
			</zone>
			<zone type="Pacific/Midway">
				<exemplarCity>Мидуэй, о-ва</exemplarCity>
			</zone>
			<zone type="Pacific/Johnston">
				<exemplarCity>Джонстон, ат.</exemplarCity>
			</zone>
			<zone type="Pacific/Wake">
				<exemplarCity>Уэйк, о-в</exemplarCity>
			</zone>
			<zone type="America/Adak">
				<exemplarCity>Адак, о-в</exemplarCity>
			</zone>
			<zone type="America/Nome">
				<exemplarCity>Ном</exemplarCity>
			</zone>
			<zone type="Pacific/Honolulu">
				<exemplarCity>Гонолулу</exemplarCity>
			</zone>
			<zone type="America/Anchorage">
				<exemplarCity>Анкоридж</exemplarCity>
			</zone>
			<zone type="America/Yakutat">
				<exemplarCity>Якутат</exemplarCity>
			</zone>
			<zone type="America/Juneau">
				<exemplarCity>Джуно</exemplarCity>
			</zone>
			<zone type="America/Los_Angeles">
				<exemplarCity>Лос-Анджелес</exemplarCity>
			</zone>
			<zone type="America/Boise">
				<exemplarCity>Бойсе</exemplarCity>
			</zone>
			<zone type="America/Phoenix">
				<exemplarCity>Финикс</exemplarCity>
			</zone>
			<zone type="America/Shiprock">
				<exemplarCity>Шипрок</exemplarCity>
			</zone>
			<zone type="America/Denver">
				<exemplarCity>Денвер</exemplarCity>
			</zone>
			<zone type="America/North_Dakota/New_Salem">
				<exemplarCity>Нью-Салем</exemplarCity>
			</zone>
			<zone type="America/North_Dakota/Center">
				<exemplarCity>Северная Дакота - Центр</exemplarCity>
			</zone>
			<zone type="America/Chicago">
				<exemplarCity>Чикаго</exemplarCity>
			</zone>
			<zone type="America/Menominee">
				<exemplarCity>Меномини</exemplarCity>
			</zone>
			<zone type="America/Indiana/Vincennes">
				<exemplarCity>Винсенс</exemplarCity>
			</zone>
			<zone type="America/Indiana/Petersburg">
				<exemplarCity>Петерсбург</exemplarCity>
			</zone>
			<zone type="America/Indiana/Tell_City">
				<exemplarCity>Телл-Сити</exemplarCity>
			</zone>
			<zone type="America/Indiana/Knox">
				<exemplarCity>Нокс</exemplarCity>
			</zone>
			<zone type="America/Indiana/Winamac">
				<exemplarCity>Винамак</exemplarCity>
			</zone>
			<zone type="America/Indiana/Marengo">
				<exemplarCity>Маренго</exemplarCity>
			</zone>
			<zone type="America/Indianapolis">
				<exemplarCity>Индианаполис</exemplarCity>
			</zone>
			<zone type="America/Louisville">
				<exemplarCity>Луисвилл</exemplarCity>
			</zone>
			<zone type="America/Indiana/Vevay">
				<exemplarCity>Вивэй</exemplarCity>
			</zone>
			<zone type="America/Kentucky/Monticello">
				<exemplarCity>Монтиселло</exemplarCity>
			</zone>
			<zone type="America/Detroit">
				<exemplarCity>Детройт</exemplarCity>
			</zone>
			<zone type="America/New_York">
				<exemplarCity>Нью-Йорк</exemplarCity>
			</zone>
			<zone type="America/Montevideo">
				<exemplarCity>Монтевидео</exemplarCity>
			</zone>
			<zone type="Asia/Samarkand">
				<exemplarCity>Самарканд</exemplarCity>
			</zone>
			<zone type="Asia/Tashkent">
				<exemplarCity>Ташкент</exemplarCity>
			</zone>
			<zone type="Europe/Vatican">
				<exemplarCity>Ватикан</exemplarCity>
			</zone>
			<zone type="America/St_Vincent">
				<exemplarCity>Сент-Винсент</exemplarCity>
			</zone>
			<zone type="America/Caracas">
				<exemplarCity>Каракас</exemplarCity>
			</zone>
			<zone type="America/Tortola">
				<exemplarCity>Тортола</exemplarCity>
			</zone>
			<zone type="America/St_Thomas">
				<exemplarCity>Сент-Томас</exemplarCity>
			</zone>
			<zone type="Asia/Saigon">
				<exemplarCity>Сайгон</exemplarCity>
			</zone>
			<zone type="Pacific/Efate">
				<exemplarCity>Эфате</exemplarCity>
			</zone>
			<zone type="Pacific/Wallis">
				<exemplarCity>Уоллис</exemplarCity>
			</zone>
			<zone type="Pacific/Apia">
				<exemplarCity>Апия</exemplarCity>
			</zone>
			<zone type="Asia/Aden">
				<exemplarCity>Аден</exemplarCity>
			</zone>
			<zone type="Indian/Mayotte">
				<exemplarCity>Майорка</exemplarCity>
			</zone>
			<zone type="Africa/Johannesburg">
				<exemplarCity>Йоханнесбург</exemplarCity>
			</zone>
			<zone type="Africa/Lusaka">
				<exemplarCity>Лусака</exemplarCity>
			</zone>
			<zone type="Africa/Harare">
				<exemplarCity>Хараре</exemplarCity>
			</zone>
			<metazone type="Acre">
				<long>
					<generic>Акри время</generic>
					<standard>Акри стандартное время</standard>
					<daylight>Акри летнее время</daylight>
				</long>
				<short>
					<generic>Акри время</generic>
					<standard>Акри стандартное время</standard>
					<daylight>Акри летнее время</daylight>
				</short>
			</metazone>
			<metazone type="Afghanistan">
				<long>
					<standard>Афганистан время</standard>
				</long>
				<short>
					<standard>Афганистан время</standard>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Africa_Central">
				<long>
					<standard>Центральноафриканское время</standard>
				</long>
			</metazone>
			<metazone type="Africa_Eastern">
				<long>
					<standard>Восточноафриканское время</standard>
				</long>
			</metazone>
			<metazone type="Africa_Southern">
				<long>
					<standard>Южноафриканское время</standard>
				</long>
			</metazone>
			<metazone type="Africa_Western">
				<long>
					<standard>Западноафриканское время</standard>
					<daylight>Западноафриканское летнее время</daylight>
				</long>
			</metazone>
			<metazone type="Aktyubinsk">
				<long>
					<standard>Актюбинск стандартное время</standard>
					<daylight>Актюбинск летнее время</daylight>
				</long>
				<short>
					<standard>Актюбинск стандартное время</standard>
					<daylight>Актюбинск летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Alaska">
				<long>
					<generic>Аляска время</generic>
					<standard>Аляска стандартное время</standard>
					<daylight>Аляска летнее время</daylight>
				</long>
				<short>
					<generic>Аляска время</generic>
					<standard>Аляска стандартное время</standard>
					<daylight>Аляска летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Alaska_Hawaii">
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Almaty">
				<long>
					<standard>Алма-Ата стандартное время</standard>
					<daylight>Алма-Ата летнее время</daylight>
				</long>
				<short>
					<standard>Алма-Ата стандартное время</standard>
					<daylight>Алма-Ата летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="America_Central">
				<long>
					<generic>Средне-американское время</generic>
					<standard>Средне-американское стандартное время</standard>
					<daylight>Средне-американское летнее время</daylight>
				</long>
				<short>
					<generic>Средне-американское время</generic>
					<standard>Средне-американское стандартное время</standard>
					<daylight>Средне-американское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="America_Eastern">
				<long>
					<generic>Восточно-американское время</generic>
					<standard>Восточно-американское стандартное время</standard>
					<daylight>Восточно-американское летнее время</daylight>
				</long>
				<short>
					<generic>Восточно-американское время</generic>
					<standard>Восточно-американское стандартное время</standard>
					<daylight>Восточно-американское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="America_Mountain">
				<long>
					<generic>Горное время (США)</generic>
					<standard>Горное стандартное время (США)</standard>
					<daylight>Горное летнее время (США)</daylight>
				</long>
				<short>
					<generic>Горное время (США)</generic>
					<standard>Горное стандартное время (США)</standard>
					<daylight>Горное летнее время (США)</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="America_Pacific">
				<long>
					<generic>Тихоокеанское время</generic>
					<standard>Тихоокеанское стандартное время</standard>
					<daylight>Тихоокеанское летнее время</daylight>
				</long>
				<short>
					<generic>Тихоокеанское время</generic>
					<standard>Тихоокеанское стандартное время</standard>
					<daylight>Тихоокеанское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Anadyr">
				<long>
					<standard>Анадырь стандартное время</standard>
					<daylight>Анадырь летнее время</daylight>
				</long>
				<short>
					<standard>Анадырь стандартное время</standard>
					<daylight>Анадырь летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Aqtau">
				<long>
					<standard>Актау стандартное время</standard>
					<daylight>Актау летнее время</daylight>
				</long>
				<short>
					<standard>Актау стандартное время</standard>
					<daylight>Актау летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Aqtobe">
				<long>
					<standard>Актобе стандартное время</standard>
					<daylight>Актобе летнее время</daylight>
				</long>
				<short>
					<standard>Актобе стандартное время</standard>
					<daylight>Актобе летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Arabian">
				<long>
					<generic>Саудовская Аравия время</generic>
					<standard>Саудовская Аравия стандартное время</standard>
					<daylight>Саудовская Аравия летнее время</daylight>
				</long>
				<short>
					<generic>Саудовская Аравия время</generic>
					<standard>Саудовская Аравия стандартное время</standard>
					<daylight>Саудовская Аравия летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Argentina">
				<long>
					<standard>Аргентина стандартное время</standard>
					<daylight>Аргентина летнее время</daylight>
				</long>
				<short>
					<standard>Аргентина стандартное время</standard>
					<daylight>Аргентина летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Argentina_Western">
				<long>
					<standard>Аргентина (запад) стандартное время</standard>
				</long>
				<short>
					<standard>Аргентина (запад) стандартное время</standard>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Armenia">
				<long>
					<generic>Армения время</generic>
					<standard>Армения стандартное время</standard>
					<daylight>Армения летнее время</daylight>
				</long>
				<short>
					<generic>Армения время</generic>
					<standard>Армения стандартное время</standard>
					<daylight>Армения летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Atlantic">
				<long>
					<generic>Атлантическое время</generic>
					<standard>Атлантическое стандартное время</standard>
					<daylight>Атлантическое летнее время</daylight>
				</long>
				<short>
					<generic>Атлантическое время</generic>
					<standard>Атлантическое стандартное время</standard>
					<daylight>Атлантическое летнее время</daylight>
				</short>
			</metazone>
			<metazone type="Brasilia">
				<long>
					<standard>Бразилия стандартное время</standard>
					<daylight>Бразилия дневное время</daylight>
				</long>
				<short>
					<standard>Бразилия стандартное время</standard>
					<daylight>Бразилия дневное время</daylight>
				</short>
			</metazone>
			<metazone type="China">
				<long>
					<standard>Китайское стандартное время</standard>
				</long>
				<short>
					<standard>Китайское стандартное время</standard>
				</short>
			</metazone>
			<metazone type="Europe_Central">
				<long>
					<standard>Центральноевропейское время</standard>
					<daylight>Центральноевропейское летнее время</daylight>
				</long>
				<short>
					<standard>Центральноевропейское время</standard>
					<daylight>Центральноевропейское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Europe_Eastern">
				<long>
					<standard>Восточноевропейское время</standard>
					<daylight>Восточноевропейское летнее время</daylight>
				</long>
				<short>
					<standard>Восточноевропейское время</standard>
					<daylight>Восточноевропейское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Hong_Kong">
				<long>
					<standard>Гонконгское стандартное время</standard>
					<daylight>Гонконгское летнее время</daylight>
				</long>
				<short>
					<standard>Гонконгское стандартное время</standard>
					<daylight>Гонконгское летнее время</daylight>
				</short>
			</metazone>
			<metazone type="India">
				<long>
					<standard>Индийское стандартное время</standard>
				</long>
				<short>
					<standard>Индийское стандартное время</standard>
				</short>
			</metazone>
			<metazone type="Indochina">
				<long>
					<standard>Индокитайское стандартное время</standard>
				</long>
				<short>
					<standard>Индокитайское стандартное время</standard>
				</short>
			</metazone>
			<metazone type="Indonesia_Central">
				<long>
					<standard>Центральная Индонезия стандартное время</standard>
				</long>
				<short>
					<standard>Центральная Индонезия стандартное время</standard>
				</short>
			</metazone>
			<metazone type="Indonesia_Eastern">
				<long>
					<standard>Восточная Индонезия стандартное время</standard>
				</long>
				<short>
					<standard>Восточная Индонезия стандартное время</standard>
				</short>
			</metazone>
			<metazone type="Indonesia_Western">
				<long>
					<standard>Западная Индонезия стандартное время</standard>
				</long>
				<short>
					<standard>Западная Индонезия стандартное время</standard>
				</short>
			</metazone>
			<metazone type="Israel">
				<long>
					<standard>Израиль стандартное время</standard>
					<daylight>Израиль летнее время</daylight>
				</long>
				<short>
					<standard>Израиль стандартное время</standard>
					<daylight>Израиль летнее время</daylight>
				</short>
			</metazone>
			<metazone type="Japan">
				<long>
					<standard>Японское стандартное время</standard>
				</long>
				<short>
					<standard>Японское стандартное время</standard>
				</short>
			</metazone>
			<metazone type="Korea">
				<long>
					<standard>Корейское стандартное время</standard>
				</long>
				<short>
					<standard>Корейское стандартное время</standard>
				</short>
			</metazone>
			<metazone type="Kuybyshev">
				<long>
					<standard>Куйбышевское время</standard>
					<daylight>Куйбышевское летнее время</daylight>
				</long>
				<short>
					<standard>Куйбышевское время</standard>
					<daylight>Куйбышевское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Moscow">
				<long>
					<generic>Московское время</generic>
					<standard>Московское стандартное время</standard>
					<daylight>Московское летнее время</daylight>
				</long>
				<short>
					<generic>Московское время</generic>
					<standard>Московское стандартное время</standard>
					<daylight>Московское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Samara">
				<long>
					<standard>Самарское стандартное время</standard>
					<daylight>Самарское летнее время</daylight>
				</long>
				<short>
					<standard>Самарское стандартное время</standard>
					<daylight>Самарское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Turkey">
				<long>
					<generic>Турецкое время</generic>
					<standard>Турецкое стандартное время</standard>
					<daylight>Турецкое летнее время</daylight>
				</long>
				<short>
					<generic>Турецкое время</generic>
					<standard>Турецкое стандартное время</standard>
					<daylight>Турецкое летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
			<metazone type="Volgograd">
				<long>
					<standard>Волгоградское время</standard>
					<daylight>Волгоградское летнее время</daylight>
				</long>
				<short>
					<standard>Волгоградское время</standard>
					<daylight>Волгоградское летнее время</daylight>
				</short>
				<commonlyUsed>true</commonlyUsed>
			</metazone>
		</timeZoneNames>
	</dates>
	<numbers>
		<symbols>
			<decimal>,</decimal>
			<group> </group>
			<list>;</list>
			<percentSign>%</percentSign>
			<nativeZeroDigit>0</nativeZeroDigit>
			<patternDigit>#</patternDigit>
			<plusSign>+</plusSign>
			<minusSign>-</minusSign>
			<exponential>E</exponential>
			<perMille>‰</perMille>
			<infinity>∞</infinity>
		</symbols>
		<decimalFormats>
			<decimalFormatLength>
				<decimalFormat>
					<pattern>#,##0.###</pattern>
				</decimalFormat>
			</decimalFormatLength>
		</decimalFormats>
		<scientificFormats>
			<scientificFormatLength>
				<scientificFormat>
					<pattern>#E0</pattern>
				</scientificFormat>
			</scientificFormatLength>
		</scientificFormats>
		<percentFormats>
			<percentFormatLength>
				<percentFormat>
					<pattern>#,##0 %</pattern>
				</percentFormat>
			</percentFormatLength>
		</percentFormats>
		<currencyFormats>
			<currencyFormatLength>
				<currencyFormat>
					<pattern>#,##0.00 ¤</pattern>
				</currencyFormat>
			</currencyFormatLength>
		</currencyFormats>
		<currencies>
			<currency type="ADP">
				<displayName>Андоррская песета</displayName>
				<displayName count="few">андоррские песеты</displayName>
				<displayName count="other">андоррских песет</displayName>
				<symbol>андоррских песет</symbol>
			</currency>
			<currency type="AED">
				<displayName>Дирхам (ОАЭ)</displayName>
			</currency>
			<currency type="AFA">
				<displayName>Афгани (1927-2002)</displayName>
			</currency>
			<currency type="AFN">
				<displayName>Афгани</displayName>
			</currency>
			<currency type="ALL">
				<displayName>Албанский лек</displayName>
				<displayName count="few">албанских лека</displayName>
				<displayName count="other">албанских леков</displayName>
				<symbol>lek</symbol>
			</currency>
			<currency type="AMD">
				<displayName>Армянский драм</displayName>
				<displayName count="few">армянских драма</displayName>
				<displayName count="other">армянских драмов</displayName>
				<symbol>dram</symbol>
			</currency>
			<currency type="ANG">
				<displayName>Нидерландский антильский гульден</displayName>
				<symbol>NA f.</symbol>
			</currency>
			<currency type="AOA">
				<displayName>Ангольская кванза</displayName>
			</currency>
			<currency type="AOK">
				<displayName>Ангольская кванза (1977-1990)</displayName>
				<displayName count="few">ангольские кванзы</displayName>
				<displayName count="other">ангольских кванз</displayName>
			</currency>
			<currency type="AON">
				<displayName>Ангольская новая кванза (1990-2000)</displayName>
			</currency>
			<currency type="AOR">
				<displayName>Ангольская кванза реюстадо (1995-1999)</displayName>
				<displayName count="few">ангольские кванзы реюстадо (1995-1999)</displayName>
				<displayName count="other">ангольских кванз реюстадо (1995-1999)</displayName>
			</currency>
			<currency type="ARA">
				<displayName>Аргентинский аустрал</displayName>
			</currency>
			<currency type="ARP">
				<displayName>Аргентинское песо (1983-1985)</displayName>
			</currency>
			<currency type="ARS">
				<displayName>Аргентинское песо</displayName>
				<symbol>Arg$</symbol>
			</currency>
			<currency type="ATS">
				<displayName>Австрийский шиллинг</displayName>
			</currency>
			<currency type="AUD">
				<displayName>Австралийский доллар</displayName>
				<symbol>$A</symbol>
			</currency>
			<currency type="AWG">
				<displayName>Арубанский гульден</displayName>
			</currency>
			<currency type="AZM">
				<displayName>Старый азербайджанский манат</displayName>
			</currency>
			<currency type="AZN">
				<displayName>Азербайджанский манат</displayName>
			</currency>
			<currency type="BAD">
				<displayName>Динар Боснии и Герцеговины</displayName>
			</currency>
			<currency type="BAM">
				<displayName>Конвертируемая марка Боснии и Герцеговины</displayName>
			</currency>
			<currency type="BBD">
				<displayName>Барбадосский доллар</displayName>
				<symbol>BDS$</symbol>
			</currency>
			<currency type="BDT">
				<displayName>Бангладешская така</displayName>
				<symbol>Tk</symbol>
			</currency>
			<currency type="BEC">
				<displayName>Бельгийский франк (конвертируемый)</displayName>
			</currency>
			<currency type="BEF">
				<displayName>Бельгийский франк</displayName>
				<symbol>BF</symbol>
			</currency>
			<currency type="BEL">
				<displayName>Бельгийский франк (финансовый)</displayName>
			</currency>
			<currency type="BGL">
				<displayName>Лев</displayName>
				<symbol>lev</symbol>
			</currency>
			<currency type="BGN">
				<displayName>Болгарский лев</displayName>
			</currency>
			<currency type="BHD">
				<displayName>Бахрейнский динар</displayName>
				<symbol>BD</symbol>
			</currency>
			<currency type="BIF">
				<displayName>Бурундийский франк</displayName>
				<symbol>Fbu</symbol>
			</currency>
			<currency type="BMD">
				<displayName>Бермудский доллар</displayName>
				<symbol>Ber$</symbol>
			</currency>
			<currency type="BND">
				<displayName>Брунейский доллар</displayName>
			</currency>
			<currency type="BOB">
				<displayName>Боливиано</displayName>
				<symbol>Bs</symbol>
			</currency>
			<currency type="BOP">
				<displayName>Боливийское песо</displayName>
			</currency>
			<currency type="BOV">
				<displayName>Боливийский мвдол</displayName>
			</currency>
			<currency type="BRB">
				<displayName>Бразильский новый крузейро (1967-1986)</displayName>
			</currency>
			<currency type="BRC">
				<displayName>Бразильское крузадо</displayName>
			</currency>
			<currency type="BRE">
				<displayName>Бразильский крузейро (1990-1993)</displayName>
			</currency>
			<currency type="BRL">
				<displayName>Бразильский реал</displayName>
			</currency>
			<currency type="BRN">
				<displayName>Бразильское новое крузадо</displayName>
			</currency>
			<currency type="BRR">
				<displayName>Бразильский крузейро</displayName>
			</currency>
			<currency type="BSD">
				<displayName>Багамский доллар</displayName>
			</currency>
			<currency type="BTN">
				<displayName>Нгултрум</displayName>
				<symbol>Nu</symbol>
			</currency>
			<currency type="BUK">
				<displayName>Джа</displayName>
			</currency>
			<currency type="BWP">
				<displayName>Ботсванская пула</displayName>
			</currency>
			<currency type="BYB">
				<displayName>Белорусский рубль (1994-1999)</displayName>
			</currency>
			<currency type="BYR">
				<displayName>Белорусский рубль</displayName>
				<symbol>Rbl</symbol>
			</currency>
			<currency type="BZD">
				<displayName>Белизский доллар</displayName>
				<symbol>BZ$</symbol>
			</currency>
			<currency type="CAD">
				<displayName>Канадский доллар</displayName>
				<symbol>Can$</symbol>
			</currency>
			<currency type="CDF">
				<displayName>Конголезский франк</displayName>
			</currency>
			<currency type="CHE">
				<displayName>WIR евро</displayName>
			</currency>
			<currency type="CHF">
				<displayName>Швейцарский франк</displayName>
				<symbol>SwF</symbol>
			</currency>
			<currency type="CHW">
				<displayName>WIR франк</displayName>
			</currency>
			<currency type="CLF">
				<displayName>Условная расчетная единица Чили</displayName>
			</currency>
			<currency type="CLP">
				<displayName>Чилийское песо</displayName>
				<symbol>Ch$</symbol>
			</currency>
			<currency type="CNY">
				<displayName>Юань Ренминби</displayName>
				<symbol>Y</symbol>
			</currency>
			<currency type="COP">
				<displayName>Колумбийское песо</displayName>
				<symbol>Col$</symbol>
			</currency>
			<currency type="COU">
				<displayName>Единица реальной стоимости Колумбии</displayName>
			</currency>
			<currency type="CRC">
				<displayName>Костариканский колон</displayName>
				<symbol>C</symbol>
			</currency>
			<currency type="CSD">
				<displayName>Старый Сербский динар</displayName>
			</currency>
			<currency type="CSK">
				<displayName>Чехословацкая твердая крона</displayName>
			</currency>
			<currency type="CUP">
				<displayName>Кубинское песо</displayName>
			</currency>
			<currency type="CVE">
				<displayName>Эскудо Кабо-Верде</displayName>
				<symbol>CVEsc</symbol>
			</currency>
			<currency type="CYP">
				<displayName>Кипрский фунт</displayName>
				<symbol>£C</symbol>
			</currency>
			<currency type="CZK">
				<displayName>Чешская крона</displayName>
			</currency>
			<currency type="DDM">
				<displayName>Восточногерманская марка</displayName>
			</currency>
			<currency type="DEM">
				<displayName>Немецкая марка</displayName>
			</currency>
			<currency type="DJF">
				<displayName>Франк Джибути</displayName>
				<symbol>DF</symbol>
			</currency>
			<currency type="DKK">
				<displayName>Датская крона</displayName>
				<symbol>DKr</symbol>
			</currency>
			<currency type="DOP">
				<displayName>Доминиканское песо</displayName>
				<symbol>RD$</symbol>
			</currency>
			<currency type="DZD">
				<displayName>Алжирский динар</displayName>
				<symbol>DA</symbol>
			</currency>
			<currency type="ECS">
				<displayName>Эквадорский сукре</displayName>
			</currency>
			<currency type="ECV">
				<displayName>Постоянная единица стоимости Эквадора</displayName>
			</currency>
			<currency type="EEK">
				<displayName>Эстонская крона</displayName>
			</currency>
			<currency type="EGP">
				<displayName>Египетский фунт</displayName>
			</currency>
			<currency type="EQE">
				<displayName>Эквеле</displayName>
			</currency>
			<currency type="ERN">
				<displayName>Накфа</displayName>
			</currency>
			<currency type="ESA">
				<displayName>Испанская песета (А)</displayName>
			</currency>
			<currency type="ESB">
				<displayName>Испанская песета (конвертируемая)</displayName>
			</currency>
			<currency type="ESP">
				<displayName>Испанская песета</displayName>
			</currency>
			<currency type="ETB">
				<displayName>Эфиопский быр</displayName>
				<symbol>Br</symbol>
			</currency>
			<currency type="EUR">
				<displayName>Евро</displayName>
			</currency>
			<currency type="FIM">
				<displayName>Финская марка</displayName>
			</currency>
			<currency type="FJD">
				<displayName>Доллар Фиджи</displayName>
				<symbol>F$</symbol>
			</currency>
			<currency type="FKP">
				<displayName>Фунт Фолклендских островов</displayName>
			</currency>
			<currency type="FRF">
				<displayName>Французский франк</displayName>
			</currency>
			<currency type="GBP">
				<displayName>Английский фунт стерлингов</displayName>
				<symbol>£</symbol>
			</currency>
			<currency type="GEK">
				<displayName>Грузинский купон</displayName>
			</currency>
			<currency type="GEL">
				<displayName>Грузинский лари</displayName>
				<symbol>lari</symbol>
			</currency>
			<currency type="GHC">
				<displayName>Ганский седи</displayName>
			</currency>
			<currency type="GHS">
				<displayName>Седи Ганы</displayName>
			</currency>
			<currency type="GIP">
				<displayName>Гибралтарский фунт</displayName>
			</currency>
			<currency type="GMD">
				<displayName>Гамбийский даласи</displayName>
			</currency>
			<currency type="GNF">
				<displayName>Гвинейский франк</displayName>
				<symbol>GF</symbol>
			</currency>
			<currency type="GNS">
				<displayName>Гвинейская сили</displayName>
			</currency>
			<currency type="GQE">
				<displayName>Эквеле экваториальной Гвинеи</displayName>
			</currency>
			<currency type="GRD">
				<displayName>Греческая драхма</displayName>
			</currency>
			<currency type="GTQ">
				<displayName>Гватемальский кетсаль</displayName>
				<symbol>Q</symbol>
			</currency>
			<currency type="GWE">
				<displayName>Эскудо Португальской Гвинеи</displayName>
			</currency>
			<currency type="GWP">
				<displayName>Песо Гвинеи-Бисау</displayName>
			</currency>
			<currency type="GYD">
				<displayName>Гайанский доллар</displayName>
				<symbol>G$</symbol>
			</currency>
			<currency type="HKD">
				<displayName>Гонконгский доллар</displayName>
				<symbol>HK$</symbol>
			</currency>
			<currency type="HNL">
				<displayName>Гондурасская лемпира</displayName>
				<symbol>L</symbol>
			</currency>
			<currency type="HRD">
				<displayName>Хорватский динар</displayName>
			</currency>
			<currency type="HRK">
				<displayName>Хорватская куна</displayName>
			</currency>
			<currency type="HTG">
				<displayName>Гаитянский гурд</displayName>
			</currency>
			<currency type="HUF">
				<displayName>Венгерский форинт</displayName>
				<symbol>Ft</symbol>
			</currency>
			<currency type="IDR">
				<displayName>Индонезийская рупия</displayName>
				<symbol>Rp</symbol>
			</currency>
			<currency type="IEP">
				<displayName>Ирландский фунт</displayName>
				<symbol>IR£</symbol>
			</currency>
			<currency type="ILP">
				<displayName>Израильский фунт</displayName>
			</currency>
			<currency type="ILS">
				<displayName>Новый израильский шекель</displayName>
			</currency>
			<currency type="INR">
				<displayName>Индийская рупия</displayName>
				<symbol>INR</symbol>
			</currency>
			<currency type="IQD">
				<displayName>Иракский динар</displayName>
				<symbol>ID</symbol>
			</currency>
			<currency type="IRR">
				<displayName>Иранский риал</displayName>
				<symbol>RI</symbol>
			</currency>
			<currency type="ISK">
				<displayName>Исландская крона</displayName>
			</currency>
			<currency type="ITL">
				<displayName>Итальянская лира</displayName>
			</currency>
			<currency type="JMD">
				<displayName>Ямайский доллар</displayName>
				<symbol>J$</symbol>
			</currency>
			<currency type="JOD">
				<displayName>Иорданский динар</displayName>
				<symbol>JD</symbol>
			</currency>
			<currency type="JPY">
				<displayName>Японская иена</displayName>
				<symbol>¥</symbol>
			</currency>
			<currency type="KES">
				<displayName>Кенийский шиллинг</displayName>
				<symbol>K Sh</symbol>
			</currency>
			<currency type="KGS">
				<displayName>Киргизский сом</displayName>
				<symbol>som</symbol>
			</currency>
			<currency type="KHR">
				<displayName>Камбоджийский риель</displayName>
				<symbol>CR</symbol>
			</currency>
			<currency type="KMF">
				<displayName>Франк Коморских островов</displayName>
				<symbol>CF</symbol>
			</currency>
			<currency type="KPW">
				<displayName>Северо-корейская вона</displayName>
			</currency>
			<currency type="KRW">
				<displayName>Вона Республики Кореи</displayName>
			</currency>
			<currency type="KWD">
				<displayName>Кувейтский динар</displayName>
				<symbol>KD</symbol>
			</currency>
			<currency type="KYD">
				<displayName>Доллар Каймановых островов</displayName>
			</currency>
			<currency type="KZT">
				<displayName>Казахский тенге</displayName>
				<symbol>T</symbol>
			</currency>
			<currency type="LAK">
				<displayName>Кип ЛНДР</displayName>
			</currency>
			<currency type="LBP">
				<displayName>Ливанский фунт</displayName>
				<symbol>LL</symbol>
			</currency>
			<currency type="LKR">
				<displayName>Шри-Ланкийская рупия</displayName>
				<symbol>SL Re</symbol>
			</currency>
			<currency type="LRD">
				<displayName>Либерийский доллар</displayName>
			</currency>
			<currency type="LSL">
				<displayName>Лоти</displayName>
				<symbol>M</symbol>
			</currency>
			<currency type="LSM">
				<displayName>Малоти</displayName>
			</currency>
			<currency type="LTL">
				<displayName>Литовский лит</displayName>
			</currency>
			<currency type="LTT">
				<displayName>Литовский талон</displayName>
			</currency>
			<currency type="LUC">
				<displayName>Конвертируемый франк Люксембурга</displayName>
			</currency>
			<currency type="LUF">
				<displayName>Люксембургский франк</displayName>
			</currency>
			<currency type="LUL">
				<displayName>Финансовый франк Люксембурга</displayName>
			</currency>
			<currency type="LVL">
				<displayName>Латвийский лат</displayName>
			</currency>
			<currency type="LVR">
				<displayName>Латвийский рубль</displayName>
			</currency>
			<currency type="LYD">
				<displayName>Ливийский динар</displayName>
				<symbol>LD</symbol>
			</currency>
			<currency type="MAD">
				<displayName>Марокканский дирхам</displayName>
			</currency>
			<currency type="MAF">
				<displayName>Марокканский франк</displayName>
			</currency>
			<currency type="MDL">
				<displayName>Молдавский лей</displayName>
			</currency>
			<currency type="MGA">
				<displayName>Ариари</displayName>
			</currency>
			<currency type="MGF">
				<displayName>Малагасийский франк</displayName>
			</currency>
			<currency type="MKD">
				<displayName>Македонский динар</displayName>
				<symbol>MDen</symbol>
			</currency>
			<currency type="MLF">
				<displayName>Малийский франк</displayName>
			</currency>
			<currency type="MMK">
				<displayName>Кьят</displayName>
			</currency>
			<currency type="MNT">
				<displayName>Монгольский тугрик</displayName>
				<symbol>Tug</symbol>
			</currency>
			<currency type="MOP">
				<displayName>Патака</displayName>
			</currency>
			<currency type="MRO">
				<displayName>Мавританская угия</displayName>
				<symbol>UM</symbol>
			</currency>
			<currency type="MTL">
				<displayName>Мальтийская лира</displayName>
				<symbol>Lm</symbol>
			</currency>
			<currency type="MTP">
				<displayName>Мальтийский фунт</displayName>
			</currency>
			<currency type="MUR">
				<displayName>Маврикийская рупия</displayName>
			</currency>
			<currency type="MVR">
				<displayName>Мальдивская руфия</displayName>
			</currency>
			<currency type="MWK">
				<displayName>Малавийская квача</displayName>
				<symbol>MK</symbol>
			</currency>
			<currency type="MXN">
				<displayName>Мексиканское новое песо</displayName>
				<symbol>MEX$</symbol>
			</currency>
			<currency type="MXP">
				<displayName>Мексиканское серебряное песо (1861-1992)</displayName>
			</currency>
			<currency type="MXV">
				<displayName>Мексиканская пересчетная единица (UDI)</displayName>
			</currency>
			<currency type="MYR">
				<displayName>Малайзийский ринггит</displayName>
				<symbol>RM</symbol>
			</currency>
			<currency type="MZE">
				<displayName>Мозамбикское эскудо</displayName>
			</currency>
			<currency type="MZM">
				<displayName>Старый мозамбикский метикал</displayName>
				<symbol>Mt</symbol>
			</currency>
			<currency type="MZN">
				<displayName>Метикал</displayName>
			</currency>
			<currency type="NAD">
				<displayName>Доллар Намибии</displayName>
				<symbol>N$</symbol>
			</currency>
			<currency type="NGN">
				<displayName>Нигерийская найра</displayName>
			</currency>
			<currency type="NIC">
				<displayName>Никарагуанская кордоба</displayName>
			</currency>
			<currency type="NIO">
				<displayName>Золотая кордоба</displayName>
			</currency>
			<currency type="NLG">
				<displayName>Нидерландский гульден</displayName>
			</currency>
			<currency type="NOK">
				<displayName>Норвежская крона</displayName>
				<symbol>NKr</symbol>
			</currency>
			<currency type="NPR">
				<displayName>Непальская рупия</displayName>
				<symbol>Nrs</symbol>
			</currency>
			<currency type="NZD">
				<displayName>Новозеландский доллар</displayName>
				<symbol>$NZ</symbol>
			</currency>
			<currency type="OMR">
				<displayName>Оманский риал</displayName>
				<symbol>RO</symbol>
			</currency>
			<currency type="PAB">
				<displayName>Панамское бальбоа</displayName>
			</currency>
			<currency type="PEI">
				<displayName>Перуанское инти</displayName>
			</currency>
			<currency type="PEN">
				<displayName>Перуанский новый соль</displayName>
			</currency>
			<currency type="PES">
				<displayName>Перуанский соль</displayName>
			</currency>
			<currency type="PGK">
				<displayName>Кина</displayName>
			</currency>
			<currency type="PHP">
				<displayName>Филиппинское песо</displayName>
			</currency>
			<currency type="PKR">
				<displayName>Пакистанская рупия</displayName>
				<symbol>Pra</symbol>
			</currency>
			<currency type="PLN">
				<displayName>Польский злотый</displayName>
				<symbol>Zl</symbol>
			</currency>
			<currency type="PLZ">
				<displayName>Злотый</displayName>
			</currency>
			<currency type="PTE">
				<displayName>Португальское эскудо</displayName>
			</currency>
			<currency type="PYG">
				<displayName>Парагвайский гуарани</displayName>
			</currency>
			<currency type="QAR">
				<displayName>Катарский риал</displayName>
				<symbol>QR</symbol>
			</currency>
			<currency type="RHD">
				<displayName>Родезийский доллар</displayName>
			</currency>
			<currency type="ROL">
				<displayName>Старый Румынский лей</displayName>
				<symbol>leu</symbol>
			</currency>
			<currency type="RON">
				<displayName>Румынский лей</displayName>
			</currency>
			<currency type="RSD">
				<displayName>Сербский динар</displayName>
			</currency>
			<currency type="RUB">
				<displayName>Российский рубль</displayName>
				<displayName count="few">Российских рубля</displayName>
				<displayName count="many">Российских рублей</displayName>
				<displayName count="one">Российский рубль</displayName>
				<displayName count="other">Российского рубля</displayName>
				<symbol>руб.</symbol>
			</currency>
			<currency type="RUR">
				<displayName>Российский рубль (1991-1998)</displayName>
				<symbol>р.</symbol>
			</currency>
			<currency type="RWF">
				<displayName>Франк Руанды</displayName>
			</currency>
			<currency type="SAR">
				<displayName>Саудовский риал</displayName>
				<symbol>SRl</symbol>
			</currency>
			<currency type="SBD">
				<displayName>Доллар Соломоновых островов</displayName>
				<symbol>SI$</symbol>
			</currency>
			<currency type="SCR">
				<displayName>Сейшельская рупия</displayName>
				<symbol>SR</symbol>
			</currency>
			<currency type="SDD">
				<displayName>Суданский динар</displayName>
			</currency>
			<currency type="SDP">
				<displayName>Суданский фунт</displayName>
			</currency>
			<currency type="SEK">
				<displayName>Шведская крона</displayName>
				<symbol>SKr</symbol>
			</currency>
			<currency type="SGD">
				<displayName>Сингапурский доллар</displayName>
				<symbol>S$</symbol>
			</currency>
			<currency type="SHP">
				<displayName>Фунт острова Святой Елены</displayName>
			</currency>
			<currency type="SIT">
				<displayName>Словенский толар</displayName>
			</currency>
			<currency type="SKK">
				<displayName>Словацкая крона</displayName>
				<symbol>Sk</symbol>
			</currency>
			<currency type="SLL">
				<displayName>Леоне</displayName>
			</currency>
			<currency type="SOS">
				<displayName>Сомалийский шиллинг</displayName>
				<symbol>Sh.</symbol>
			</currency>
			<currency type="SRD">
				<displayName>Суринамский доллар</displayName>
			</currency>
			<currency type="SRG">
				<displayName>Суринамский гульден</displayName>
				<symbol>Sf</symbol>
			</currency>
			<currency type="STD">
				<displayName>Добра</displayName>
				<symbol>Db</symbol>
			</currency>
			<currency type="SUR">
				<displayName>Рубль СССР</displayName>
			</currency>
			<currency type="SVC">
				<displayName>Сальвадорский колон</displayName>
			</currency>
			<currency type="SYP">
				<displayName>Сирийский фунт</displayName>
				<symbol>LS</symbol>
			</currency>
			<currency type="SZL">
				<displayName>Свазилендский лилангени</displayName>
				<symbol>E</symbol>
			</currency>
			<currency type="THB">
				<displayName>Таиландский бат</displayName>
			</currency>
			<currency type="TJR">
				<displayName>Таджикский рубль</displayName>
			</currency>
			<currency type="TJS">
				<displayName>Таджикский сомони</displayName>
			</currency>
			<currency type="TMM">
				<displayName>Туркменский манат</displayName>
			</currency>
			<currency type="TND">
				<displayName>Тунисский динар</displayName>
			</currency>
			<currency type="TOP">
				<displayName>Паанга</displayName>
				<symbol>T$</symbol>
			</currency>
			<currency type="TPE">
				<displayName>Тиморское эскудо</displayName>
			</currency>
			<currency type="TRL">
				<displayName>Турецкая лира</displayName>
				<displayName count="few">турецкие лиры</displayName>
				<displayName count="many">турецких лир</displayName>
				<displayName count="one">туркцкая лира</displayName>
				<displayName count="other">турецких лир</displayName>
				<symbol>TL</symbol>
			</currency>
			<currency type="TRY">
				<displayName>Новая турецкая лира</displayName>
				<displayName count="few">новые турецкие лиры</displayName>
				<displayName count="many">Новых турецких лир</displayName>
				<displayName count="one">Новая турецкая лира</displayName>
				<displayName count="other">новых турецких лир</displayName>
			</currency>
			<currency type="TTD">
				<displayName>Доллар Тринидада и Тобаго</displayName>
				<symbol>TT$</symbol>
			</currency>
			<currency type="TWD">
				<displayName>Новый тайваньский доллар</displayName>
				<symbol>NT$</symbol>
			</currency>
			<currency type="TZS">
				<displayName>Танзанийский шиллинг</displayName>
				<symbol>T Sh</symbol>
			</currency>
			<currency type="UAH">
				<displayName>Украинская гривна</displayName>
				<symbol>грн.</symbol>
			</currency>
			<currency type="UAK">
				<displayName>Карбованец (украинский)</displayName>
			</currency>
			<currency type="UGS">
				<displayName>Старый угандийский шиллинг</displayName>
			</currency>
			<currency type="UGX">
				<displayName>У£гандийский шиллинг</displayName>
			</currency>
			<currency type="USD">
				<displayName>Доллар США</displayName>
				<symbol>$</symbol>
			</currency>
			<currency type="USN">
				<displayName>Доллар США следующего дня</displayName>
			</currency>
			<currency type="USS">
				<displayName>Доллар США текущего дня</displayName>
			</currency>
			<currency type="UYP">
				<displayName>Уругвайское старое песо (1975-1993)</displayName>
			</currency>
			<currency type="UYU">
				<displayName>Уругвайское песо</displayName>
			</currency>
			<currency type="UZS">
				<displayName>Узбекский сум</displayName>
			</currency>
			<currency type="VEB">
				<displayName>Венесуэльский боливар</displayName>
				<symbol>Be</symbol>
			</currency>
			<currency type="VND">
				<displayName>Вьетнамский донг</displayName>
				<symbol>Донг</symbol>
			</currency>
			<currency type="VUV">
				<displayName>Вату</displayName>
				<symbol>VT</symbol>
			</currency>
			<currency type="WST">
				<displayName>Тала</displayName>
			</currency>
			<currency type="XAF">
				<displayName>Франк КФА ВЕАС</displayName>
			</currency>
			<currency type="XAG">
				<displayName>Серебро</displayName>
			</currency>
			<currency type="XAU">
				<displayName>Золото</displayName>
			</currency>
			<currency type="XBA">
				<displayName>Европейская составная единица</displayName>
			</currency>
			<currency type="XBB">
				<displayName>Европейская денежная единица</displayName>
			</currency>
			<currency type="XBC">
				<displayName>расчетная единица европейского валютного соглашения (XBC)</displayName>
			</currency>
			<currency type="XBD">
				<displayName>расчетная единица европейского валютного соглашения (XBD)</displayName>
			</currency>
			<currency type="XCD">
				<displayName>Восточно-карибский доллар</displayName>
				<symbol>EC$</symbol>
			</currency>
			<currency type="XDR">
				<displayName>СДР (специальные права заимствования)</displayName>
			</currency>
			<currency type="XEU">
				<displayName>ЭКЮ (единица европейской валюты)</displayName>
			</currency>
			<currency type="XFO">
				<displayName>Французский золотой франк</displayName>
			</currency>
			<currency type="XFU">
				<displayName>Французский UIC-франк</displayName>
			</currency>
			<currency type="XOF">
				<displayName>Франк КФА ВСЕАО</displayName>
			</currency>
			<currency type="XPD">
				<displayName>Палладий</displayName>
			</currency>
			<currency type="XPF">
				<displayName>Франк КФП</displayName>
				<symbol>CFPF</symbol>
			</currency>
			<currency type="XPT">
				<displayName>Платина</displayName>
			</currency>
			<currency type="XRE">
				<displayName>единица RINET-фондов</displayName>
			</currency>
			<currency type="XTS">
				<displayName>тестовый валютный код</displayName>
			</currency>
			<currency type="XXX">
				<displayName>Неизвестная или недействительная валюта</displayName>
			</currency>
			<currency type="YDD">
				<displayName>Йеменский динар</displayName>
			</currency>
			<currency type="YER">
				<displayName>Йеменский риал</displayName>
				<symbol>YRl</symbol>
			</currency>
			<currency type="YUD">
				<displayName>Югославский твердый динар</displayName>
			</currency>
			<currency type="YUM">
				<displayName>Югославский новый динар</displayName>
			</currency>
			<currency type="YUN">
				<displayName>Югославский динар</displayName>
			</currency>
			<currency type="ZAL">
				<displayName>Южноафриканский рэнд (финансовый)</displayName>
			</currency>
			<currency type="ZAR">
				<displayName>Южноафриканский рэнд</displayName>
				<symbol>R</symbol>
			</currency>
			<currency type="ZMK">
				<displayName>Квача (замбийская)</displayName>
			</currency>
			<currency type="ZRN">
				<displayName>Новый заир</displayName>
			</currency>
			<currency type="ZRZ">
				<displayName>Заир</displayName>
			</currency>
			<currency type="ZWD">
				<displayName>Доллар Зимбабве</displayName>
				<symbol>Z$</symbol>
			</currency>
		</currencies>
	</numbers>
	<posix>
		<messages>
			<yesstr>да:д</yesstr>
			<nostr>нет:н</nostr>
		</messages>
	</posix>
</ldml>
Locale/Data.php000066600000163526151256604610007354 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Locale
 * @subpackage Data
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Data.php 12057 2008-10-21 17:19:43Z thomas $
 */

/**
 * include needed classes
 */
require_once 'Zend/Locale.php';

/**
 * Locale data reader, handles the CLDR
 *
 * @category   Zend
 * @package    Zend_Locale
 * @subpackage Data
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Locale_Data
{
    /**
     * Locale files
     *
     * @var ressource
     * @access private
     */
    private static $_ldml = array();

    /**
     * List of values which are collected
     *
     * @var array
     * @access private
     */
    private static $_list = array();

    /**
     * Internal cache for ldml values
     * 
     * @var Zend_Cache_Core
     * @access private
     */
    private static $_cache = null;

    /**
     * Read the content from locale
     *
     * Can be called like:
     * <ldml>
     *     <delimiter>test</delimiter>
     *     <second type='myone'>content</second>
     *     <second type='mysecond'>content2</second>
     *     <third type='mythird' />
     * </ldml>
     *
     * Case 1: _readFile('ar','/ldml/delimiter')             -> returns [] = test
     * Case 1: _readFile('ar','/ldml/second[@type=myone]')   -> returns [] = content
     * Case 2: _readFile('ar','/ldml/second','type')         -> returns [myone] = content; [mysecond] = content2
     * Case 3: _readFile('ar','/ldml/delimiter',,'right')    -> returns [right] = test
     * Case 4: _readFile('ar','/ldml/third','type','myone')  -> returns [myone] = mythird
     *
     * @param  string $locale
     * @param  string $path
     * @param  string $attribute
     * @param  string $value
     * @access private
     * @return array
     */
    private static function _readFile($locale, $path, $attribute, $value, $temp)
    {
        // without attribute - read all values
        // with attribute    - read only this value
        if (!empty(self::$_ldml[(string) $locale])) {

            $result = self::$_ldml[(string) $locale]->xpath($path);
            if (!empty($result)) {
                foreach ($result as &$found) {

                    if (empty($value)) {

                        if (empty($attribute)) {
                            // Case 1
                            $temp[] = (string) $found;
                        } else if (empty($temp[(string) $found[$attribute]])){
                            // Case 2
                            $temp[(string) $found[$attribute]] = (string) $found;
                        }

                    } else if (empty ($temp[$value])) {

                        if (empty($attribute)) {
                            // Case 3
                            $temp[$value] = (string) $found;
                        } else {
                            // Case 4
                            $temp[$value] = (string) $found[$attribute];
                        }

                    }
                }
            }
        }
        return $temp;
    }

    /**
     * Find possible routing to other path or locale
     *
     * @param  string $locale
     * @param  string $path
     * @param  string $attribute
     * @param  string $value
     * @param  array  $temp
     * @throws Zend_Locale_Exception
     * @access private
     */
    private static function _findRoute($locale, $path, $attribute, $value, &$temp)
    {
        // load locale file if not already in cache
        // needed for alias tag when referring to other locale
        if (empty(self::$_ldml[(string) $locale])) {
            $filename = dirname(__FILE__) . '/Data/' . $locale . '.xml';
            if (!file_exists($filename)) {
                require_once 'Zend/Locale/Exception.php';
                throw new Zend_Locale_Exception("Missing locale file '$filename' for '$locale' locale.");
            }

            self::$_ldml[(string) $locale] = simplexml_load_file($filename);
        }

        // search for 'alias' tag in the search path for redirection
        $search = '';
        $tok = strtok($path, '/');

        // parse the complete path
        if (!empty(self::$_ldml[(string) $locale])) {
            while ($tok !== false) {
                $search .=  '/' . $tok;
                if (strpos($search, '[@') !== false) {
                    while (strrpos($search, '[@') > strrpos($search, ']')) {
                        $tok = strtok('/');
                        if (empty($tok)) {
                            $search .= '/';
                        }
                        $search = $search . '/' . $tok;
                    }
                }
                $result = self::$_ldml[(string) $locale]->xpath($search . '/alias');

                // alias found
                if (!empty($result)) {

                    $source = $result[0]['source'];
                    $newpath = $result[0]['path'];

                    // new path - path //ldml is to ignore
                    if ($newpath != '//ldml') {
                        // other path - parse to make real path

                        while (substr($newpath,0,3) == '../') {
                            $newpath = substr($newpath, 3);
                            $search = substr($search, 0, strrpos($search, '/'));
                        }

                        // truncate ../ to realpath otherwise problems with alias
                        $path = $search . '/' . $newpath;
                        while (($tok = strtok('/'))!== false) {
                            $path = $path . '/' . $tok;
                        }
                    }

                    // reroute to other locale
                    if ($source != 'locale') {
                        $locale = $source;
                    }

                    $temp = self::_getFile($locale, $path, $attribute, $value, $temp);
                    return false;
                }

                $tok = strtok('/');
            }
        }
        return true;
    }


    /**
     * Read the right LDML file
     *
     * @param  string $locale
     * @param  string $path
     * @param  string $attribute
     * @param  string $value
     * @access private
     */
    private static function _getFile($locale, $path, $attribute = false, $value = false, $temp = array())
    {
        $result = self::_findRoute($locale, $path, $attribute, $value, $temp);
        if ($result) {
            $temp = self::_readFile($locale, $path, $attribute, $value, $temp);
        }

        // parse required locales reversive
        // example: when given zh_Hans_CN
        // 1. -> zh_Hans_CN
        // 2. -> zh_Hans
        // 3. -> zh
        // 4. -> root
        if (($locale != 'root') && ($result)) {
            $locale = substr($locale, 0, -strlen(strrchr($locale, '_')));
            if (!empty($locale)) {
                $temp = self::_getFile($locale, $path, $attribute, $value, $temp);
            } else {
                $temp = self::_getFile('root', $path, $attribute, $value, $temp);
            }
        }
        return $temp;
    }


    /**
     * Find the details for supplemental calendar datas
     *
     * @param  string $locale Locale for Detaildata
     * @param  array  $list   List to search
     * @return string         Key for Detaildata
     */
    private static function _calendarDetail($locale, $list)
    {
        $ret = "001";
        foreach ($list as $key => $value) {
            if (strpos($locale, '_') !== false) {
                $locale = substr($locale, strpos($locale, '_') + 1);
            }
            if (strpos($key, $locale) !== false) {
                $ret = $key;
                break;
            }
        }
        return $ret;
    }

    /**
     * Internal function for checking the locale
     *
     * @param string|Zend_Locale $locale Locale to check
     * @return string
     */
    private static function _checkLocale($locale)
    {
        if (empty($locale)) {
            $locale = new Zend_Locale();
        }

        if (!(Zend_Locale::isLocale((string) $locale, null, false))) {
            require_once 'Zend/Locale/Exception.php';
            throw new Zend_Locale_Exception("Locale (" . (string) $locale . ") is a unknown locale");
        }

        return (string) $locale;
    }

    /**
     * Read the LDML file, get a array of multipath defined value
     *
     * @param  string $locale
     * @param  string $path
     * @param  string $value
     * @return array
     * @access public
     */
    public static function getList($locale, $path, $value = false)
    {
        $locale = self::_checkLocale($locale);
        if (isset(self::$_cache)) {
            $val = $value;
            if (is_array($value)) {
                $val = implode('_' , $value);
            }

            $val = urlencode($val);
            $id = strtr('Zend_LocaleL_' . $locale . '_' . $path . '_' . $val, array('-' => '_', '%' => '_', '+' => '_'));
            if ($result = self::$_cache->load($id)) {
                return unserialize($result);
            }
        }

        $temp = array();
        switch(strtolower($path)) {
            case 'language':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/languages/language', 'type');
                break;

            case 'script':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/scripts/script', 'type');
                break;

            case 'territory':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/territories/territory', 'type');
                if ($value === 1) {
                    foreach($temp as $key => $value) {
                        if ((is_numeric($key) === false) and ($key != 'QO') and ($key != 'QU')) {
                            unset($temp[$key]);
                        }
                    }
                } else if ($value === 2) {
                    foreach($temp as $key => $value) {
                        if (is_numeric($key) or ($key == 'QO') or ($key == 'QU')) {
                            unset($temp[$key]);
                        }
                    }
                }
                break;

            case 'variant':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/variants/variant', 'type');
                break;

            case 'key':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/keys/key', 'type');
                break;

            case 'type':
                if (empty($type)) {
                    $temp = self::_getFile($locale, '/ldml/localeDisplayNames/types/type', 'type');
                } else {
                    if (($value == 'calendar') or
                        ($value == 'collation') or
                        ($value == 'currency')) {
                        $temp = self::_getFile($locale, '/ldml/localeDisplayNames/types/type[@key=\'' . $value . '\']', 'type');
                    } else {
                        $temp = self::_getFile($locale, '/ldml/localeDisplayNames/types/type[@type=\'' . $value . '\']', 'type');
                    }
                }
                break;

            case 'layout':
                $temp  = self::_getFile($locale, '/ldml/layout/orientation',                 'lines',      'lines');
                $temp += self::_getFile($locale, '/ldml/layout/orientation',                 'characters', 'characters');
                $temp += self::_getFile($locale, '/ldml/layout/inList',                      '',           'inList');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'currency\']',  '',           'currency');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'dayWidth\']',  '',           'dayWidth');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'fields\']',    '',           'fields');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'keys\']',      '',           'keys');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'languages\']', '',           'languages');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'long\']',      '',           'long');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'measurementSystemNames\']', '', 'measurementSystemNames');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'monthWidth\']',   '',        'monthWidth');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'quarterWidth\']', '',        'quarterWidth');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'scripts\']',   '',           'scripts');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'territories\']',  '',        'territories');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'types\']',     '',           'types');
                $temp += self::_getFile($locale, '/ldml/layout/inText[@type=\'variants\']',  '',           'variants');
                break;

            case 'characters':
                $temp  = self::_getFile($locale, '/ldml/characters/exemplarCharacters',                           '', 'characters');
                $temp += self::_getFile($locale, '/ldml/characters/exemplarCharacters[@type=\'auxiliary\']',      '', 'auxiliary');
                $temp += self::_getFile($locale, '/ldml/characters/exemplarCharacters[@type=\'currencySymbol\']', '', 'currencySymbol');
                break;

            case 'delimiters':
                $temp  = self::_getFile($locale, '/ldml/delimiters/quotationStart',          '', 'quoteStart');
                $temp += self::_getFile($locale, '/ldml/delimiters/quotationEnd',            '', 'quoteEnd');
                $temp += self::_getFile($locale, '/ldml/delimiters/alternateQuotationStart', '', 'quoteStartAlt');
                $temp += self::_getFile($locale, '/ldml/delimiters/alternateQuotationEnd',   '', 'quoteEndAlt');
                break;

            case 'measurement':
                $temp  = self::_getFile('supplementalData', '/supplementalData/measurementData/measurementSystem[@type=\'metric\']', 'territories', 'metric');
                $temp += self::_getFile('supplementalData', '/supplementalData/measurementData/measurementSystem[@type=\'US\']',     'territories', 'US');
                $temp += self::_getFile('supplementalData', '/supplementalData/measurementData/paperSize[@type=\'A4\']',             'territories', 'A4');
                $temp += self::_getFile('supplementalData', '/supplementalData/measurementData/paperSize[@type=\'US-Letter\']',      'territories', 'US-Letter');
                break;

            case 'months':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp  = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/default', 'choice', 'context');
                $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/monthContext[@type=\'format\']/default', 'choice', 'default');
                $temp['format']['abbreviated'] = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/monthContext[@type=\'format\']/monthWidth[@type=\'abbreviated\']/month', 'type');
                $temp['format']['narrow']      = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/monthContext[@type=\'format\']/monthWidth[@type=\'narrow\']/month', 'type');
                $temp['format']['wide']        = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/monthContext[@type=\'format\']/monthWidth[@type=\'wide\']/month', 'type');
                $temp['stand-alone']['abbreviated']  = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/monthContext[@type=\'stand-alone\']/monthWidth[@type=\'abbreviated\']/month', 'type');
                $temp['stand-alone']['narrow']       = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/monthContext[@type=\'stand-alone\']/monthWidth[@type=\'narrow\']/month', 'type');
                $temp['stand-alone']['wide']         = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/monthContext[@type=\'stand-alone\']/monthWidth[@type=\'wide\']/month', 'type');
                break;

            case 'month':
                if (empty($value)) {
                    $value = array("gregorian", "format", "wide");
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/months/monthContext[@type=\'' . $value[1] . '\']/monthWidth[@type=\'' . $value[2] . '\']/month', 'type');
                break;

            case 'days':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp  = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/default', 'choice', 'context');
                $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/dayContext[@type=\'format\']/default', 'choice', 'default');
                $temp['format']['abbreviated'] = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/dayContext[@type=\'format\']/dayWidth[@type=\'abbreviated\']/day', 'type');
                $temp['format']['narrow']      = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/dayContext[@type=\'format\']/dayWidth[@type=\'narrow\']/day', 'type');
                $temp['format']['wide']        = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/dayContext[@type=\'format\']/dayWidth[@type=\'wide\']/day', 'type');
                $temp['stand-alone']['abbreviated']  = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/dayContext[@type=\'stand-alone\']/dayWidth[@type=\'abbreviated\']/day', 'type');
                $temp['stand-alone']['narrow']       = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/dayContext[@type=\'stand-alone\']/dayWidth[@type=\'narrow\']/day', 'type');
                $temp['stand-alone']['wide']         = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/dayContext[@type=\'stand-alone\']/dayWidth[@type=\'wide\']/day', 'type');
                break;

            case 'day':
                if (empty($value)) {
                    $value = array("gregorian", "format", "wide");
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/days/dayContext[@type=\'' . $value[1] . '\']/dayWidth[@type=\'' . $value[2] . '\']/day', 'type');
                break;

            case 'week':
                $minDays   = self::_calendarDetail($locale, self::_getFile('supplementalData', '/supplementalData/weekData/minDays', 'territories'));
                $firstDay  = self::_calendarDetail($locale, self::_getFile('supplementalData', '/supplementalData/weekData/firstDay', 'territories'));
                $weekStart = self::_calendarDetail($locale, self::_getFile('supplementalData', '/supplementalData/weekData/weekendStart', 'territories'));
                $weekEnd   = self::_calendarDetail($locale, self::_getFile('supplementalData', '/supplementalData/weekData/weekendEnd', 'territories'));

                $temp  = self::_getFile('supplementalData', "/supplementalData/weekData/minDays[@territories='" . $minDays . "']", 'count', 'minDays');
                $temp += self::_getFile('supplementalData', "/supplementalData/weekData/firstDay[@territories='" . $firstDay . "']", 'day', 'firstDay');
                $temp += self::_getFile('supplementalData', "/supplementalData/weekData/weekendStart[@territories='" . $weekStart . "']", 'day', 'weekendStart');
                $temp += self::_getFile('supplementalData', "/supplementalData/weekData/weekendEnd[@territories='" . $weekEnd . "']", 'day', 'weekendEnd');
                break;

            case 'quarters':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp['format']['abbreviated'] = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/quarters/quarterContext[@type=\'format\']/quarterWidth[@type=\'abbreviated\']/quarter', 'type');
                $temp['format']['narrow']      = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/quarters/quarterContext[@type=\'format\']/quarterWidth[@type=\'narrow\']/quarter', 'type');
                $temp['format']['wide']        = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/quarters/quarterContext[@type=\'format\']/quarterWidth[@type=\'wide\']/quarter', 'type');
                $temp['stand-alone']['abbreviated']  = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/quarters/quarterContext[@type=\'stand-alone\']/quarterWidth[@type=\'abbreviated\']/quarter', 'type');
                $temp['stand-alone']['narrow']       = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/quarters/quarterContext[@type=\'stand-alone\']/quarterWidth[@type=\'narrow\']/quarter', 'type');
                $temp['stand-alone']['wide']         = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/quarters/quarterContext[@type=\'stand-alone\']/quarterWidth[@type=\'wide\']/quarter', 'type');
                break;

            case 'quarter':
                if (empty($value)) {
                    $value = array("gregorian", "format", "wide");
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/quarters/quarterContext[@type=\'' . $value[1] . '\']/quarterWidth[@type=\'' . $value[2] . '\']/quarter', 'type');
                break;

            case 'eras':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp['names']       = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/eras/eraNames/era', 'type');
                $temp['abbreviated'] = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/eras/eraAbbr/era', 'type');
                $temp['narrow']      = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/eras/eraNarrow/era', 'type');
                break;

            case 'era':
                if (empty($value)) {
                    $value = array("gregorian", "Abbr");
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/eras/era' . $value[1] . '/era', 'type');
                break;

            case 'date':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp  = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateFormats/dateFormatLength[@type=\'full\']/dateFormat/pattern', '', 'full');
                $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateFormats/dateFormatLength[@type=\'long\']/dateFormat/pattern', '', 'long');
                $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateFormats/dateFormatLength[@type=\'medium\']/dateFormat/pattern', '', 'medium');
                $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateFormats/dateFormatLength[@type=\'short\']/dateFormat/pattern', '', 'short');
                break;

            case 'time':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp  = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/timeFormats/timeFormatLength[@type=\'full\']/timeFormat/pattern', '', 'full');
                $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/timeFormats/timeFormatLength[@type=\'long\']/timeFormat/pattern', '', 'long');
                $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/timeFormats/timeFormatLength[@type=\'medium\']/timeFormat/pattern', '', 'medium');
                $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/timeFormats/timeFormatLength[@type=\'short\']/timeFormat/pattern', '', 'short');
                break;

            case 'datetime':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateTimeFormats/availableFormats/dateFormatItem', 'id');
                break;
                
            case 'field':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp2 = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/fields/field', 'type');
                foreach ($temp2 as $key => $keyvalue) {
                    $temp += self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/fields/field[@type=\'' . $key . '\']/displayName', '', $key);
                }
                break;

            case 'relative':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/fields/field/relative', 'type');
                break;

            case 'symbols':
                $temp  = self::_getFile($locale, '/ldml/numbers/symbols/decimal',         '', 'decimal');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/group',           '', 'group');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/list',            '', 'list');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/percentSign',     '', 'percent');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/nativeZeroDigit', '', 'zero');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/patternDigit',    '', 'pattern');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/plusSign',        '', 'plus');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/minusSign',       '', 'minus');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/exponential',     '', 'exponent');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/perMille',        '', 'mille');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/infinity',        '', 'infinity');
                $temp += self::_getFile($locale, '/ldml/numbers/symbols/nan',             '', 'nan');
                break;

            case 'nametocurrency':
                $_temp = self::_getFile($locale, '/ldml/numbers/currencies/currency', 'type');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $key . '\']/displayName', '', $key);
                }
                break;

            case 'currencytoname':
                $_temp = self::_getFile($locale, '/ldml/numbers/currencies/currency', 'type');
                foreach ($_temp as $key => $keyvalue) {
                    $val = self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $key . '\']/displayName', '', $key);
                    if (!isset($val[$key])) {
                        continue;
                    }
                    if (!isset($temp[$val[$key]])) {
                        $temp[$val[$key]] = $key;
                    } else {
                        $temp[$val[$key]] .= " " . $key;
                    }
                }
                break;

            case 'currencysymbol':
                $_temp = self::_getFile($locale, '/ldml/numbers/currencies/currency', 'type');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $key . '\']/symbol', '', $key);
                }
                break;

            case 'question':
                $temp  = self::_getFile($locale, '/ldml/posix/messages/yesstr',  '', 'yes');
                $temp += self::_getFile($locale, '/ldml/posix/messages/nostr',   '', 'no');
                break;

            case 'currencyfraction':
                $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info', 'iso4217');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info[@iso4217=\'' . $key . '\']', 'digits', $key);
                }
                break;

            case 'currencyrounding':
                $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info', 'iso4217');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info[@iso4217=\'' . $key . '\']', 'rounding', $key);
                }
                break;

            case 'currencytoregion':
                $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/region', 'iso3166');
                foreach ($_temp as $key => $keyvalue) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/currencyData/region[@iso3166=\'' . $key . '\']/currency', 'iso4217', $key);
                }
                break;

            case 'regiontocurrency':
                $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/region', 'iso3166');
                foreach ($_temp as $key => $keyvalue) {
                    $val = self::_getFile('supplementalData', '/supplementalData/currencyData/region[@iso3166=\'' . $key . '\']/currency', 'iso4217', $key);
                    if (!isset($val[$key])) {
                        continue;
                    }
                    if (!isset($temp[$val[$key]])) {
                        $temp[$val[$key]] = $key;
                    } else {
                        $temp[$val[$key]] .= " " . $key;
                    }
                }
                break;

            case 'regiontoterritory':
                $_temp = self::_getFile('supplementalData', '/supplementalData/territoryContainment/group', 'type');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/territoryContainment/group[@type=\'' . $key . '\']', 'contains', $key);
                }
                break;

            case 'territorytoregion':
                $_temp2 = self::_getFile('supplementalData', '/supplementalData/territoryContainment/group', 'type');
                $_temp = array();
                foreach ($_temp2 as $key => $found) {
                    $_temp += self::_getFile('supplementalData', '/supplementalData/territoryContainment/group[@type=\'' . $key . '\']', 'contains', $key);
                }
                foreach($_temp as $key => $found) {
                    $_temp3 = explode(" ", $found);
                    foreach($_temp3 as $found3) {
                        if (!isset($temp[$found3])) {
                            $temp[$found3] = (string) $key;
                        } else {
                            $temp[$found3] .= " " . $key;
                        }
                    }
                }
                break;

            case 'scripttolanguage':
                $_temp = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'scripts', $key);
                    if (empty($temp[$key])) {
                        unset($temp[$key]);
                    }
                }
                break;

            case 'languagetoscript':
                $_temp2 = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type');
                $_temp = array();
                foreach ($_temp2 as $key => $found) {
                    $_temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'scripts', $key);
                }
                foreach($_temp as $key => $found) {
                    $_temp3 = explode(" ", $found);
                    foreach($_temp3 as $found3) {
                        if (empty($found3)) {
                            continue;
                        }
                        if (!isset($temp[$found3])) {
                            $temp[$found3] = (string) $key;
                        } else {
                            $temp[$found3] .= " " . $key;
                        }
                    }
                }
                break;

            case 'territorytolanguage':
                $_temp = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'territories', $key);
                    if (empty($temp[$key])) {
                        unset($temp[$key]);
                    }
                }
                break;

            case 'languagetoterritory':
                $_temp2 = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type');
                $_temp = array();
                foreach ($_temp2 as $key => $found) {
                    $_temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'territories', $key);
                }
                foreach($_temp as $key => $found) {
                    $_temp3 = explode(" ", $found);
                    foreach($_temp3 as $found3) {
                        if (empty($found3)) {
                            continue;
                        }
                        if (!isset($temp[$found3])) {
                            $temp[$found3] = (string) $key;
                        } else {
                            $temp[$found3] .= " " . $key;
                        }
                    }
                }
                break;

            case 'timezonetowindows':
                $_temp = self::_getFile('supplementalData', '/supplementalData/timezoneData/mapTimezones[@type=\'windows\']/mapZone', 'other');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/timezoneData/mapTimezones[@type=\'windows\']/mapZone[@other=\'' . $key . '\']', 'type', $key);
                }
                break;

            case 'windowstotimezone':
                $_temp = self::_getFile('supplementalData', '/supplementalData/timezoneData/mapTimezones[@type=\'windows\']/mapZone', 'type');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/timezoneData/mapTimezones[@type=\'windows\']/mapZone[@type=\'' .$key . '\']', 'other', $key);
                }
                break;

            case 'territorytotimezone':
                $_temp = self::_getFile('supplementalData', '/supplementalData/timezoneData/zoneFormatting/zoneItem', 'type');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/timezoneData/zoneFormatting/zoneItem[@type=\'' . $key . '\']', 'territory', $key);
                }
                break;

            case 'timezonetoterritory':
                $_temp = self::_getFile('supplementalData', '/supplementalData/timezoneData/zoneFormatting/zoneItem', 'territory');
                foreach ($_temp as $key => $found) {
                    $temp += self::_getFile('supplementalData', '/supplementalData/timezoneData/zoneFormatting/zoneItem[@territory=\'' . $key . '\']', 'type', $key);
                }
                break;

            case 'citytotimezone':
                $_temp = self::_getFile($locale, '/ldml/dates/timeZoneNames/zone', 'type');
                foreach($_temp as $key => $found) {
                    $temp += self::_getFile($locale, '/ldml/dates/timeZoneNames/zone[@type=\'' . $key . '\']/exemplarCity', '', $key);
                }
                break;

            case 'timezonetocity':
                $_temp  = self::_getFile($locale, '/ldml/dates/timeZoneNames/zone', 'type');
                $temp = array();
                foreach($_temp as $key => $found) {
                    $temp += self::_getFile($locale, '/ldml/dates/timeZoneNames/zone[@type=\'' . $key . '\']/exemplarCity', '', $key);
                    if (!empty($temp[$key])) {
                        $temp[$temp[$key]] = $key;
                    }
                    unset($temp[$key]);
                }
                break;

            default :
                require_once 'Zend/Locale/Exception.php';
                throw new Zend_Locale_Exception("Unknown list ($path) for parsing locale data.");
                break;
        }

        if (isset(self::$_cache)) {
            self::$_cache->save( serialize($temp), $id);
        }

        return $temp;
    }

    /**
     * Read the LDML file, get a single path defined value
     *
     * @param  string $locale
     * @param  string $path
     * @param  string $value
     * @return string
     * @access public
     */
    public static function getContent($locale, $path, $value = false)
    {
        $locale = self::_checkLocale($locale);

        if (isset(self::$_cache)) {
            $val = $value;
            if (is_array($value)) {
                $val = implode('_' , $value);
            }
            $val = urlencode($val);
            $id = strtr('Zend_LocaleC_' . $locale . '_' . $path . '_' . $val, array('-' => '_', '%' => '_', '+' => '_'));
            if ($result = self::$_cache->load($id)) {
                return unserialize($result);
            }
        }

        switch(strtolower($path)) {
            case 'language':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/languages/language[@type=\'' . $value . '\']', 'type');
                break;

            case 'script':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/scripts/script[@type=\'' . $value . '\']', 'type');
                break;

            case 'country':
            case 'territory':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/territories/territory[@type=\'' . $value . '\']', 'type');
                break;

            case 'variant':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/variants/variant[@type=\'' . $value . '\']', 'type');
                break;

            case 'key':
                $temp = self::_getFile($locale, '/ldml/localeDisplayNames/keys/key[@type=\'' . $value . '\']', 'type');
                break;

            case 'datechars':
                $temp = self::_getFile($locale, '/ldml/dates/localizedPatternChars', '', 'chars');
                break;

            case 'defaultcalendar':
                $temp = self::_getFile($locale, '/ldml/dates/calendars/default', 'choice', 'default');
                break;

            case 'monthcontext':
                if (empty ($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/default', 'choice', 'context');
                break;

            case 'defaultmonth':
                if (empty ($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/months/monthContext[@type=\'format\']/default', 'choice', 'default');
                break;

            case 'month':
                if (!is_array($value)) {
                    $temp = $value;
                    $value = array("gregorian", "format", "wide", $temp);
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/months/monthContext[@type=\'' . $value[1] . '\']/monthWidth[@type=\'' . $value[2] . '\']/month[@type=\'' . $value[3] . '\']', 'type');
                break;

            case 'daycontext':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/default', 'choice', 'context');
                break;

            case 'defaultday':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/days/dayContext[@type=\'format\']/default', 'choice', 'default');
                break;

            case 'day':
                if (!is_array($value)) {
                    $temp = $value;
                    $value = array("gregorian", "format", "wide", $temp);
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/days/dayContext[@type=\'' . $value[1] . '\']/dayWidth[@type=\'' . $value[2] . '\']/day[@type=\'' . $value[3] . '\']', 'type');
                break;

            case 'quarter':
                if (!is_array($value)) {
                    $temp = $value;
                    $value = array("gregorian", "format", "wide", $temp);
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/quarters/quarterContext[@type=\'' . $value[1] . '\']/quarterWidth[@type=\'' . $value[2] . '\']/quarter[@type=\'' . $value[3] . '\']', 'type');
                break;

            case 'am':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/am', '', 'am');
                break;

            case 'pm':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/pm', '', 'pm');
                break;

            case 'era':
                if (!is_array($value)) {
                    $temp = $value;
                    $value = array("gregorian", "Abbr", $temp);
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/eras/era' . $value[1] . '/era[@type=\'' . $value[2] . '\']', 'type');
                break;

            case 'defaultdate':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateFormats/default', 'choice', 'default');
                break;

            case 'date':
                if (empty($value)) {
                    $value = array("gregorian", "medium");
                }
                if (!is_array($value)) {
                    $temp = $value;
                    $value = array("gregorian", $temp);
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/dateFormats/dateFormatLength[@type=\'' . $value[1] . '\']/dateFormat/pattern', '', 'pattern');
                break;

            case 'defaulttime':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/timeFormats/default', 'choice', 'default');
                break;

            case 'time':
                if (empty($value)) {
                    $value = array("gregorian", "medium");
                }
                if (!is_array($value)) {
                    $temp = $value;
                    $value = array("gregorian", $temp);
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/timeFormats/timeFormatLength[@type=\'' . $value[1] . '\']/timeFormat/pattern', '', 'pattern');
                break;

            case 'datetime':
                if (empty($value)) {
                    $value = "gregorian";
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value . '\']/dateTimeFormats/dateTimeFormatLength/dateTimeFormat/pattern', '', 'pattern');
                break;
                
            case 'field':
                if (!is_array($value)) {
                    $temp = $value;
                    $value = array("gregorian", $temp);
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/fields/field[@type=\'' . $value[1] . '\']/displayName', '', $value[1]);
                break;

            case 'relative':
                if (!is_array($value)) {
                    $temp = $value;
                    $value = array("gregorian", $temp);
                }
                $temp = self::_getFile($locale, '/ldml/dates/calendars/calendar[@type=\'' . $value[0] . '\']/fields/field/relative[@type=\'' . $value[1] . '\']', '', $value[1]);
                break;

            case 'decimalnumber':
                $temp = self::_getFile($locale, '/ldml/numbers/decimalFormats/decimalFormatLength/decimalFormat/pattern', '', 'default');
                break;

            case 'scientificnumber':
                $temp = self::_getFile($locale, '/ldml/numbers/scientificFormats/scientificFormatLength/scientificFormat/pattern', '', 'default');
                break;

            case 'percentnumber':
                $temp = self::_getFile($locale, '/ldml/numbers/percentFormats/percentFormatLength/percentFormat/pattern', '', 'default');
                break;

            case 'currencynumber':
                $temp = self::_getFile($locale, '/ldml/numbers/currencyFormats/currencyFormatLength/currencyFormat/pattern', '', 'default');
                break;

            case 'nametocurrency':
                $temp = self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $value . '\']/displayName', '', $value);
                break;

            case 'currencytoname':
                $temp = self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $value . '\']/displayName', '', $value);
                $_temp = self::_getFile($locale, '/ldml/numbers/currencies/currency', 'type');
                $temp = array();
                foreach ($_temp as $key => $keyvalue) {
                    $val = self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $key . '\']/displayName', '', $key);
                    if (!isset($val[$key]) or ($val[$key] != $value)) {
                        continue;
                    }
                    if (!isset($temp[$val[$key]])) {
                        $temp[$val[$key]] = $key;
                    } else {
                        $temp[$val[$key]] .= " " . $key;
                    }
                }
                break;

            case 'currencysymbol':
                $temp = self::_getFile($locale, '/ldml/numbers/currencies/currency[@type=\'' . $value . '\']/symbol', '', $value);
                break;

            case 'question':
                $temp = self::_getFile($locale, '/ldml/posix/messages/' . $value . 'str',  '', $value);
                break;

            case 'currencyfraction':
                if (empty($value)) {
                    $value = "DEFAULT";
                }
                $temp = self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info[@iso4217=\'' . $value . '\']', 'digits', 'digits');
                break;

            case 'currencyrounding':
                if (empty($value)) {
                    $value = "DEFAULT";
                }
                $temp = self::_getFile('supplementalData', '/supplementalData/currencyData/fractions/info[@iso4217=\'' . $value . '\']', 'rounding', 'rounding');
                break;

            case 'currencytoregion':
                $temp = self::_getFile('supplementalData', '/supplementalData/currencyData/region[@iso3166=\'' . $value . '\']/currency', 'iso4217', $value);
                break;

            case 'regiontocurrency':
                $_temp = self::_getFile('supplementalData', '/supplementalData/currencyData/region', 'iso3166');
                $temp = array();
                foreach ($_temp as $key => $keyvalue) {
                    $val = self::_getFile('supplementalData', '/supplementalData/currencyData/region[@iso3166=\'' . $key . '\']/currency', 'iso4217', $key);
                    if (!isset($val[$key]) or ($val[$key] != $value)) {
                        continue;
                    }
                    if (!isset($temp[$val[$key]])) {
                        $temp[$val[$key]] = $key;
                    } else {
                        $temp[$val[$key]] .= " " . $key;
                    }
                }
                break;

            case 'regiontoterritory':
                $temp = self::_getFile('supplementalData', '/supplementalData/territoryContainment/group[@type=\'' . $value . '\']', 'contains', $value);
                break;

            case 'territorytoregion':
                $_temp2 = self::_getFile('supplementalData', '/supplementalData/territoryContainment/group', 'type');
                $_temp = array();
                foreach ($_temp2 as $key => $found) {
                    $_temp += self::_getFile('supplementalData', '/supplementalData/territoryContainment/group[@type=\'' . $key . '\']', 'contains', $key);
                }
                $temp = array();
                foreach($_temp as $key => $found) {
                    $_temp3 = explode(" ", $found);
                    foreach($_temp3 as $found3) {
                        if ($found3 !== $value) {
                            continue;
                        }
                        if (!isset($temp[$found3])) {
                            $temp[$found3] = (string) $key;
                        } else {
                            $temp[$found3] .= " " . $key;
                        }
                    }
                }
                break;

            case 'scripttolanguage':
                $temp = self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $value . '\']', 'scripts', $value);
                break;

            case 'languagetoscript':
                $_temp2 = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type');
                $_temp = array();
                foreach ($_temp2 as $key => $found) {
                    $_temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'scripts', $key);
                }
                $temp = array();
                foreach($_temp as $key => $found) {
                    $_temp3 = explode(" ", $found);
                    foreach($_temp3 as $found3) {
                        if ($found3 !== $value) {
                            continue;
                        }
                        if (!isset($temp[$found3])) {
                            $temp[$found3] = (string) $key;
                        } else {
                            $temp[$found3] .= " " . $key;
                        }
                    }
                }
                break;

            case 'territorytolanguage':
                $temp = self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $value . '\']', 'territories', $value);
                break;

            case 'languagetoterritory':
                $_temp2 = self::_getFile('supplementalData', '/supplementalData/languageData/language', 'type');
                $_temp = array();
                foreach ($_temp2 as $key => $found) {
                    $_temp += self::_getFile('supplementalData', '/supplementalData/languageData/language[@type=\'' . $key . '\']', 'territories', $key);
                }
                $temp = array();
                foreach($_temp as $key => $found) {
                    $_temp3 = explode(" ", $found);
                    foreach($_temp3 as $found3) {
                        if ($found3 !== $value) {
                            continue;
                        }
                        if (!isset($temp[$found3])) {
                            $temp[$found3] = (string) $key;
                        } else {
                            $temp[$found3] .= " " . $key;
                        }
                    }
                }
                break;

            case 'timezonetowindows':
                $temp = self::_getFile('supplementalData', '/supplementalData/timezoneData/mapTimezones[@type=\'windows\']/mapZone[@other=\''.$value.'\']', 'type', $value);
                break;

            case 'windowstotimezone':
                $temp = self::_getFile('supplementalData', '/supplementalData/timezoneData/mapTimezones[@type=\'windows\']/mapZone[@type=\''.$value.'\']', 'other', $value);
                break;

            case 'territorytotimezone':
                $temp = self::_getFile('supplementalData', '/supplementalData/timezoneData/zoneFormatting/zoneItem[@type=\'' . $value . '\']', 'territory', $value);
                break;

            case 'timezonetoterritory':
                $temp = self::_getFile('supplementalData', '/supplementalData/timezoneData/zoneFormatting/zoneItem[@territory=\'' . $value . '\']', 'type', $value);
                break;

            case 'citytotimezone':
                $temp = self::_getFile($locale, '/ldml/dates/timeZoneNames/zone[@type=\'' . $value . '\']/exemplarCity', '', $value);
                break;

            case 'timezonetocity':
                $_temp  = self::_getFile($locale, '/ldml/dates/timeZoneNames/zone', 'type');
                $temp = array();
                foreach($_temp as $key => $found) {
                    $temp += self::_getFile($locale, '/ldml/dates/timeZoneNames/zone[@type=\'' . $key . '\']/exemplarCity', '', $key);
                    if (!empty($temp[$key])) {
                        if ($temp[$key] == $value) {
                            $temp[$temp[$key]] = $key;
                        }
                    }
                    unset($temp[$key]);
                }
                break;

            default :
                require_once 'Zend/Locale/Exception.php';
                throw new Zend_Locale_Exception("Unknown detail ($path) for parsing locale data.");
                break;
        }

        if (is_array($temp)) {
            $temp = current($temp);
        }
        if (isset(self::$_cache)) {
            self::$_cache->save( serialize($temp), $id);
        }

        return $temp;
    }

    /**
     * Returns the set cache
     * 
     * @return Zend_Cache_Core The set cache
     */
    public static function getCache()
    {
        return self::$_cache;
    }

    /**
     * Set a cache for Zend_Locale_Data
     * 
     * @param Zend_Cache_Core $cache A cache frontend
     */
    public static function setCache(Zend_Cache_Core $cache)
    {
        self::$_cache = $cache;
    }

    /**
     * Returns true when a cache is set
     *
     * @return boolean
     */
    public static function hasCache()
    {
        if (self::$_cache !== null) {
            return true;
        }

        return false;
    }

    /**
     * Removes any set cache
     *
     * @return void
     */
    public static function removeCache()
    {
        self::$_cache = null;
    }

    /**
     * Clears all set cache data
     *
     * @return void
     */
    public static function clearCache()
    {
        self::$_cache->clean();
    }
}
Dojo/Form/Decorator/AccordionContainer.php000066600000002664151256604610014563 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Dojo_Form_Decorator_DijitContainer */
require_once 'Zend/Dojo/Form/Decorator/DijitContainer.php';

/**
 * AccordionContainer
 *
 * Render a dijit AccordionContainer
 *
 * @uses       Zend_Dojo_Form_Decorator_DijitContainer
 * @package    Zend_Dojo
 * @subpackage Form_Decorator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: AccordionContainer.php 10009 2008-07-09 16:52:18Z matthew $
 */
class Zend_Dojo_Form_Decorator_AccordionContainer extends Zend_Dojo_Form_Decorator_DijitContainer
{
    /**
     * View helper
     * @var string
     */
    protected $_helper = 'AccordionContainer';
}
Dojo/Form/Decorator/SplitContainer.php000066600000002640151256604610013747 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Dojo_Form_Decorator_DijitContainer */
require_once 'Zend/Dojo/Form/Decorator/DijitContainer.php';

/**
 * SplitContainer
 *
 * Render a dijit SplitContainer
 *
 * @uses       Zend_Dojo_Form_Decorator_DijitContainer
 * @package    Zend_Dojo
 * @subpackage Form_Decorator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: SplitContainer.php 10009 2008-07-09 16:52:18Z matthew $
 */
class Zend_Dojo_Form_Decorator_SplitContainer extends Zend_Dojo_Form_Decorator_DijitContainer
{
    /**
     * View helper
     * @var string
     */
    protected $_helper = 'SplitContainer';
}
Dojo/Form/Decorator/StackContainer.php000066600000002642151256604610013723 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Dojo_Form_Decorator_DijitContainer */
require_once 'Zend/Dojo/Form/Decorator/DijitContainer.php';

/**
 * StackContainer
 *
 * Render a dijit StackContainer
 *
 * @uses       Zend_Dojo_Form_Decorator_DijitContainer
 * @package    Zend_Dojo
 * @subpackage Form_Decorator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: StackContainer.php 10009 2008-07-09 16:52:18Z matthew $
 */
class Zend_Dojo_Form_Decorator_StackContainer extends Zend_Dojo_Form_Decorator_DijitContainer
{
    /**
     * View helper
     * @var string
     */
    protected $_helper = 'StackContainer';
}

Dojo/Form/Decorator/BorderContainer.php000066600000002645151256604610014076 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Dojo_Form_Decorator_DijitContainer */
require_once 'Zend/Dojo/Form/Decorator/DijitContainer.php';

/**
 * BorderContainer
 *
 * Render a dijit BorderContainer
 *
 * @uses       Zend_Dojo_Form_Decorator_DijitContainer
 * @package    Zend_Dojo
 * @subpackage Form_Decorator
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: BorderContainer.php 10009 2008-07-09 16:52:18Z matthew $
 */
class Zend_Dojo_Form_Decorator_BorderContainer extends Zend_Dojo_Form_Decorator_DijitContainer
{
    /**
     * View helper
     * @var string
     */
    protected $_helper = 'BorderContainer';
}
Dojo/Form.php000066600000005620151256604610007070 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Dojo
 * @subpackage Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Form */
require_once 'Zend/Form.php';

/**
 * Dijit-enabled Form
 * 
 * @uses       Zend_Form
 * @package    Zend_Dojo
 * @subpackage Form
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Form.php 12373 2008-11-07 16:52:44Z matthew $
 */
class Zend_Dojo_Form extends Zend_Form
{
    /**
     * Constructor
     * 
     * @param  array|Zend_Config|null $options 
     * @return void
     */
    public function __construct($options = null)
    {
        $this->addPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator')
             ->addPrefixPath('Zend_Dojo_Form_Element', 'Zend/Dojo/Form/Element', 'element')
             ->addElementPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator', 'decorator')
             ->addDisplayGroupPrefixPath('Zend_Dojo_Form_Decorator', 'Zend/Dojo/Form/Decorator')
             ->setDefaultDisplayGroupClass('Zend_Dojo_Form_DisplayGroup');
        parent::__construct($options);
    }

    /**
     * Load the default decorators
     * 
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }

        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('FormElements')
                 ->addDecorator('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form_dojo'))
                 ->addDecorator('DijitForm');
        }
    }

    /**
     * Set the view object
     *
     * Ensures that the view object has the dojo view helper path set.
     * 
     * @param  Zend_View_Interface $view 
     * @return Zend_Dojo_Form_Element_Dijit
     */
    public function setView(Zend_View_Interface $view = null)
    {
        if (null !== $view) {
            if (false === $view->getPluginLoader('helper')->getPaths('Zend_Dojo_View_Helper')) {
                $view->addHelperPath('Zend/Dojo/View/Helper', 'Zend_Dojo_View_Helper');
            }
        }
        return parent::setView($view);
    }
}
Dojo/View/Helper/Dojo/Container.php000066600000064021151256604610013133 0ustar00<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Dojo
 * @subpackage View
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: Container.php 14166 2009-02-25 17:58:58Z matthew $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Dojo */
require_once 'Zend/Dojo.php';

/**
 * Container for  Dojo View Helper
 *
 * 
 * @package    Zend_Dojo
 * @subpackage View
 * @copyright  Copyright (C) 2008 - Present, Zend Technologies, Inc.
 * @license    New BSD {@link http://framework.zend.com/license/new-bsd}
 */
class Zend_Dojo_View_Helper_Dojo_Container
{ 
    /**
     * @var Zend_View_Interface
     */
    public $view; 

    /**
     * addOnLoad capture lock
     * @var bool
     */
    protected $_captureLock = false;

    /**
     * addOnLoad object on which to apply lambda
     * @var string
     */
    protected $_captureObj;

    /**
     * Base CDN url to utilize
     * @var string
     */
    protected $_cdnBase = Zend_Dojo::CDN_BASE_GOOGLE;

    /**
     * Path segment following version string of CDN path
     * @var string
     */
    protected $_cdnDojoPath = Zend_Dojo::CDN_DOJO_PATH_GOOGLE;

    /**
     * Dojo version to use from CDN
     * @var string
     */
    protected $_cdnVersion = '1.2.0';

    /**
     * Has the dijit loader been registered?
     * @var bool
     */
    protected $_dijitLoaderRegistered = false;

    /**
     * Registered programmatic dijits
     * @var array
     */
    protected $_dijits = array();

    /**
     * Dojo configuration
     * @var array
     */
    protected $_djConfig = array();

    /**
     * Whether or not dojo is enabled
     * @var bool
     */
    protected $_enabled = false;

    /**
     * Are we rendering as XHTML?
     * @var bool
     */
    protected $_isXhtml = false;

    /**
     * Arbitrary javascript to include in dojo script
     * @var array
     */
    protected $_javascriptStatements = array();

    /**
     * Dojo layers (custom builds) to use
     * @var array
     */
    protected $_layers = array();

    /**
     * Relative path to dojo
     * @var string
     */
    protected $_localPath = null;

    /**
     * Root of dojo where all dojo files are installed
     * @var string
     */
    protected $_localRelativePath = null;

    /**
     * Modules to require
     * @var array
     */
    protected $_modules = array();

    /**
     * Registered module paths
     * @var array
     */
    protected $_modulePaths = array();

    /**
     * Actions to perform on window load
     * @var array
     */
    protected $_onLoadActions = array();

    /**
     * Register the Dojo stylesheet?
     * @var bool
     */
    protected $_registerDojoStylesheet = false;

    /**
     * Style sheet modules to load
     * @var array
     */
    protected $_stylesheetModules = array();

    /**
     * Local stylesheets
     * @var array
     */
    protected $_stylesheets = array();

    /**
     * Set view object
     * 
     * @param  Zend_Dojo_View_Interface $view 
     * @return void
     */
    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }

    /**
     * Enable dojo
     * 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function enable()
    {
        $this->_enabled = true;
        return $this;
    }

    /**
     * Disable dojo
     * 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function disable()
    {
        $this->_enabled = false;
        return $this;
    }

    /**
     * Is dojo enabled?
     * 
     * @return bool
     */
    public function isEnabled()
    {
        return $this->_enabled;
    }
 
    /**
     * Specify a module to require
     * 
     * @param  string $module 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function requireModule($module)
    {
        if (!is_string($module) && !is_array($module)) {
            require_once 'Zend/Dojo/View/Exception.php';
            throw new Zend_Dojo_View_Exception('Invalid module name specified; must be a string or an array of strings');
        }

        $module = (array) $module;

        foreach ($module as $mod) {
            if (!preg_match('/^[a-z][a-z0-9._-]+$/i', $mod)) {
                require_once 'Zend/Dojo/View/Exception.php';
                throw new Zend_Dojo_View_Exception(sprintf('Module name specified, "%s", contains invalid characters', (string) $mod));
            }

            if (!in_array($mod, $this->_modules)) {
                $this->_modules[] = $mod;
            }
        }

        return $this;
    }

    /**
     * Retrieve list of modules to require
     * 
     * @return array
     */
    public function getModules()
    {
        return $this->_modules;
    }
 
    /**
     * Register a module path
     * 
     * @param  string $path 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function registerModulePath($module, $path)
    {
        $path = (string) $path;
        if (!in_array($module, $this->_modulePaths)) {
            $this->_modulePaths[$module] = $path;
        }

        return $this;
    }

    /**
     * List registered module paths
     * 
     * @return array
     */
    public function getModulePaths()
    {
        return $this->_modulePaths;
    }

    /**
     * Add layer (custom build) path
     * 
     * @param  string $path 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function addLayer($path)
    {
        $path = (string) $path;
        if (!in_array($path, $this->_layers)) {
            $this->_layers[] = $path;
        }
        return $this;
    }

    /**
     * Get registered layers
     * 
     * @return array
     */
    public function getLayers()
    {
        return $this->_layers;
    }

    /**
     * Remove a registered layer
     * 
     * @param  string $path 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function removeLayer($path)
    {
        $path = (string) $path;
        $layers = array_flip($this->_layers);
        if (array_key_exists($path, $layers)) {
            unset($layers[$path]);
            $this->_layers = array_keys($layers);
        }
        return $this;
    }

    /**
     * Clear all registered layers
     * 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function clearLayers()
    {
        $this->_layers = array();
        return $this;
    }

    /**
     * Set CDN base path
     * 
     * @param  string $url 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function setCdnBase($url)
    {
        $this->_cdnBase = (string) $url;
        return $this;
    }

    /**
     * Return CDN base URL
     * 
     * @return string
     */
    public function getCdnBase()
    {
        return $this->_cdnBase;
    }
 
    /**
     * Use CDN, using version specified
     * 
     * @param  string $version 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function setCdnVersion($version = null)
    {
        $this->enable();
        if (preg_match('/^[1-9]\.[0-9](\.[0-9])?$/', $version)) {
            $this->_cdnVersion = $version;
        }
        return $this;
    }
 
    /**
     * Get CDN version
     * 
     * @return string
     */
    public function getCdnVersion()
    {
        return $this->_cdnVersion;
    }

    /**
     * Set CDN path to dojo (relative to CDN base + version)
     * 
     * @param  string $path 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function setCdnDojoPath($path)
    {
        $this->_cdnDojoPath = (string) $path;
        return $this;
    }

    /**
     * Get CDN path to dojo (relative to CDN base + version)
     * 
     * @return string
     */
    public function getCdnDojoPath()
    {
        return $this->_cdnDojoPath;
    }

    /**
     * Are we using the CDN?
     * 
     * @return bool
     */
    public function useCdn()
    {
        return !$this->useLocalPath();
    }
 
    /**
     * Set path to local dojo
     * 
     * @param  string $path 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function setLocalPath($path)
    {
        $this->enable();
        $this->_localPath = (string) $path;
        return $this;
    }

    /**
     * Get local path to dojo
     * 
     * @return string
     */
    public function getLocalPath()
    {
        return $this->_localPath;
    }

    /**
     * Are we using a local path?
     * 
     * @return bool
     */
    public function useLocalPath()
    {
        return (null === $this->_localPath) ? false : true;
    }
 
    /**
     * Set Dojo configuration
     * 
     * @param  string $option 
     * @param  mixed $value 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function setDjConfig(array $config)
    {
        $this->_djConfig = $config;
        return $this;
    }

    /**
     * Set Dojo configuration option
     * 
     * @param  string $option 
     * @param  mixed $value 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function setDjConfigOption($option, $value)
    {
        $option = (string) $option;
        $this->_djConfig[$option] = $value;
        return $this;
    }

    /**
     * Retrieve dojo configuration values
     * 
     * @return array
     */
    public function getDjConfig()
    {
        return $this->_djConfig;
    }

    /**
     * Get dojo configuration value
     * 
     * @param  string $option 
     * @param  mixed $default 
     * @return mixed
     */
    public function getDjConfigOption($option, $default = null)
    {
        $option = (string) $option;
        if (array_key_exists($option, $this->_djConfig)) {
            return $this->_djConfig[$option];
        }
        return $default;
    }
 
    /**
     * Add a stylesheet by module name
     * 
     * @param  string $module 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function addStylesheetModule($module)
    {
        if (!preg_match('/^[a-z0-9]+\.[a-z0-9_-]+(\.[a-z0-9_-]+)*$/i', $module)) {
            require_once 'Zend/Dojo/View/Exception.php';
            throw new Zend_Dojo_View_Exception('Invalid stylesheet module specified');
        }
        if (in_array($module, $this->_stylesheetModules)) {
            return $this;
        }
        $this->_stylesheetModules[] = $module;
        return $this;
    }

    /**
     * Get all stylesheet modules currently registered
     * 
     * @return array
     */
    public function getStylesheetModules()
    {
        return $this->_stylesheetModules;
    }
 
    /**
     * Add a stylesheet
     * 
     * @param  string $path 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function addStylesheet($path)
    {
        $path = (string) $path;
        if (!in_array($path, $this->_stylesheets)) {
            $this->_stylesheets[] = (string) $path;
        }
        return $this;
    }

    /**
     * Register the dojo.css stylesheet?
     *
     * With no arguments, returns the status of the flag; with arguments, sets 
     * the flag and returns the object.
     * 
     * @param  null|bool $flag
     * @return Zend_Dojo_View_Helper_Dojo_Container|bool
     */
    public function registerDojoStylesheet($flag = null)
    {
        if (null === $flag) {
             return $this->_registerDojoStylesheet;
        }

        $this->_registerDojoStylesheet = (bool) $flag;
        return $this;
    }

    /**
     * Retrieve registered stylesheets
     * 
     * @return array
     */
    public function getStylesheets()
    {
        return $this->_stylesheets;
    }

    /**
     * Add a script to execute onLoad
     *
     * dojo.addOnLoad accepts:
     * - function name
     * - lambda
     * 
     * @param  string $callback Lambda
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function addOnLoad($callback)
    {
        if (!in_array($callback, $this->_onLoadActions, true)) {
            $this->_onLoadActions[] = $callback;
        }
        return $this;
    }

    /**
     * Prepend an onLoad event to the list of onLoad actions
     * 
     * @param  string $callback Lambda
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function prependOnLoad($callback)
    {
        if (!in_array($callback, $this->_onLoadActions, true)) {
            array_unshift($this->_onLoadActions, $callback);
        }
        return $this;
    }

    /**
     * Retrieve all registered onLoad actions
     * 
     * @return array
     */
    public function getOnLoadActions()
    {
        return $this->_onLoadActions;
    }

    /**
     * Start capturing routines to run onLoad
     * 
     * @return bool
     */
    public function onLoadCaptureStart()
    {
        if ($this->_captureLock) {
            require_once 'Zend/Dojo/View/Exception.php';
            throw new Zend_Dojo_View_Exception('Cannot nest onLoad captures');
        }

        $this->_captureLock = true;
        ob_start();
        return;
    }

    /**
     * Stop capturing routines to run onLoad
     * 
     * @return bool
     */
    public function onLoadCaptureEnd()
    {
        $data               = ob_get_clean();
        $this->_captureLock = false;

        $this->addOnLoad($data);
        return true;
    }

    /**
     * Add a programmatic dijit
     * 
     * @param  string $id 
     * @param  array $params 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function addDijit($id, array $params)
    {
        if (array_key_exists($id, $this->_dijits)) {
            require_once 'Zend/Dojo/View/Exception.php';
            throw new Zend_Dojo_View_Exception(sprintf('Duplicate dijit with id "%s" already registered', $id));
        }

        $this->_dijits[$id] = array(
            'id'     => $id,
            'params' => $params,
        );

        return $this;
    }

    /**
     * Set a programmatic dijit (overwrites)
     * 
     * @param  string $id 
     * @param  array $params 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function setDijit($id, array $params)
    {
        $this->removeDijit($id);
        return $this->addDijit($id, $params);
    }

    /**
     * Add multiple dijits at once
     *
     * Expects an array of id => array $params pairs
     * 
     * @param  array $dijits 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function addDijits(array $dijits)
    {
        foreach ($dijits as $id => $params) {
            $this->addDijit($id, $params);
        }
        return $this;
    }

    /**
     * Set multiple dijits at once (overwrites)
     *
     * Expects an array of id => array $params pairs
     * 
     * @param  array $dijits 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function setDijits(array $dijits)
    {
        $this->clearDijits();
        return $this->addDijits($dijits);
    }

    /**
     * Is the given programmatic dijit already registered?
     * 
     * @param  string $id 
     * @return bool
     */
    public function hasDijit($id)
    {
        return array_key_exists($id, $this->_dijits);
    }

    /**
     * Retrieve a dijit by id
     * 
     * @param  string $id 
     * @return array|null
     */
    public function getDijit($id)
    {
        if ($this->hasDijit($id)) {
            return $this->_dijits[$id]['params'];
        }
        return null;
    }

    /**
     * Retrieve all dijits
     *
     * Returns dijits as an array of assoc arrays
     * 
     * @return array
     */
    public function getDijits()
    {
        return array_values($this->_dijits);
    }

    /**
     * Remove a programmatic dijit if it exists
     * 
     * @param  string $id 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function removeDijit($id)
    {
        if (array_key_exists($id, $this->_dijits)) {
            unset($this->_dijits[$id]);
        }

        return $this;
    }

    /**
     * Clear all dijits
     * 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function clearDijits()
    {
        $this->_dijits = array();
        return $this;
    }

    /**
     * Render dijits as JSON structure
     * 
     * @return string
     */
    public function dijitsToJson()
    {
        require_once 'Zend/Json.php';
        return Zend_Json::encode($this->getDijits());
    }

    /**
     * Create dijit loader functionality
     * 
     * @return void
     */
    public function registerDijitLoader()
    {
        if (!$this->_dijitLoaderRegistered) {
            $js =<<<EOJ
function() {
    dojo.forEach(zendDijits, function(info) {
        var n = dojo.byId(info.id);
        if (null != n) {
            dojo.attr(n, dojo.mixin({ id: info.id }, info.params));
        }
    });
    dojo.parser.parse();
}
EOJ;
            $this->requireModule('dojo.parser');
            $this->prependOnLoad($js);
            $this->addJavascript('var zendDijits = ' . $this->dijitsToJson() . ';');
            $this->_dijitLoaderRegistered = true;
        }
    }

    /**
     * Add arbitrary javascript to execute in dojo JS container
     * 
     * @param  string $js 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function addJavascript($js)
    {
        $js = preg_replace('/^\s*(.*?)\s*$/s', '$1', $js);
        if (!in_array(substr($js, -1), array(';', '}'))) {
            $js .= ';';
        }

        if (in_array($js, $this->_javascriptStatements)) {
            return $this;
        }

        $this->_javascriptStatements[] = $js;
        return $this;
    }

    /**
     * Return all registered javascript statements
     * 
     * @return array
     */
    public function getJavascript()
    {
        return $this->_javascriptStatements;
    }

    /**
     * Clear arbitrary javascript stack
     * 
     * @return Zend_Dojo_View_Helper_Dojo_Container
     */
    public function clearJavascript()
    {
        $this->_javascriptStatements = array();
        return $this;
    }

    /**
     * Capture arbitrary javascript to include in dojo script
     * 
     * @return void
     */
    public function javascriptCaptureStart()
    {
        if ($this->_captureLock) {
            require_once 'Zend/Dojo/View/Exception.php';
            throw new Zend_Dojo_View_Exception('Cannot nest captures');
        }

        $this->_captureLock = true;
        ob_start();
        return;
    }

    /**
     * Finish capturing arbitrary javascript to include in dojo script
     * 
     * @return true
     */
    public function javascriptCaptureEnd()
    {
        $data               = ob_get_clean();
        $this->_captureLock = false;

        $this->addJavascript($data);
        return true;
    }

    /**
     * String representation of dojo environment
     * 
     * @return string
     */
    public function __toString()
    {
        if (!$this->isEnabled()) {
            return '';
        }

        $this->_isXhtml = $this->view->doctype()->isXhtml();

        if (Zend_Dojo_View_Helper_Dojo::useDeclarative()) {
            if (null === $this->getDjConfigOption('parseOnLoad')) {
                $this->setDjConfigOption('parseOnLoad', true);
            }
        }

        if (!empty($this->_dijits)) {
            $this->registerDijitLoader();
        }

        $html  = $this->_renderStylesheets() . PHP_EOL
               . $this->_renderDjConfig() . PHP_EOL
               . $this->_renderDojoScriptTag() . PHP_EOL
               . $this->_renderLayers() . PHP_EOL
               . $this->_renderExtras();
        return $html;
    }

    /**
     * Retrieve local path to dojo resources for building relative paths
     * 
     * @return string
     */
    protected function _getLocalRelativePath()
    {
        if (null === $this->_localRelativePath) {
            $localPath = $this->getLocalPath();
            $localPath = preg_replace('|[/\\\\]dojo[/\\\\]dojo.js[^/\\\\]*$|i', '', $localPath);
            $this->_localRelativePath = $localPath;
        }
        return $this->_localRelativePath;
    }

    /**
     * Render dojo stylesheets
     * 
     * @return string
     */
    protected function _renderStylesheets()
    {
        if ($this->useCdn()) {
            $base = $this->getCdnBase()
                  . $this->getCdnVersion();
        } else {
            $base = $this->_getLocalRelativePath();
        }

        $registeredStylesheets = $this->getStylesheetModules();
        foreach ($registeredStylesheets as $stylesheet) {
            $themeName     = substr($stylesheet, strrpos($stylesheet, '.') + 1);
            $stylesheet    = str_replace('.', '/', $stylesheet);
            $stylesheets[] = $base . '/' . $stylesheet . '/' . $themeName . '.css';
        }

        foreach ($this->getStylesheets() as $stylesheet) {
            $stylesheets[] = $stylesheet;
        }

        if ($this->_registerDojoStylesheet) {
            $stylesheets[] = $base . '/dojo/resources/dojo.css';
        }

        if (empty($stylesheets)) {
            return '';
        }

        array_reverse($stylesheets);
        $style = '<style type="text/css">' . PHP_EOL
               . (($this->_isXhtml) ? '<!--' : '<!--') . PHP_EOL;
        foreach ($stylesheets as $stylesheet) {
            $style .= '    @import "' . $stylesheet . '";' . PHP_EOL;
        }
        $style .= (($this->_isXhtml) ? '-->' : '-->') . PHP_EOL
                . '</style>';

        return $style;
    }

    /**
     * Render DjConfig values
     * 
     * @return string
     */
    protected function _renderDjConfig()
    {
        $djConfigValues = $this->getDjConfig();
        if (empty($djConfigValues)) {
            return '';
        }

        require_once 'Zend/Json.php';
        $scriptTag = '<script type="text/javascript">' . PHP_EOL
                   . (($this->_isXhtml) ? '//<![CDATA[' : '//<!--') . PHP_EOL
                   . '    var djConfig = ' . Zend_Json::encode($djConfigValues) . ';' . PHP_EOL
                   . (($this->_isXhtml) ? '//]]>' : '//-->') . PHP_EOL
                   . '</script>';

        return $scriptTag;
    }

    /**
     * Render dojo script tag
     *
     * Renders Dojo script tag by utilizing either local path provided or the 
     * CDN. If any djConfig values were set, they will be serialized and passed 
     * with that attribute.
     * 
     * @return string
     */
    protected function _renderDojoScriptTag()
    {
        if ($this->useCdn()) {
            $source = $this->getCdnBase()
                    . $this->getCdnVersion()
                    . $this->getCdnDojoPath();
        } else {
            $source = $this->getLocalPath();
        }

        $scriptTag = '<script type="text/javascript" src="' . $source . '"></script>';
        return $scriptTag;
    }

    /**
     * Render layers (custom builds) as script tags
     * 
     * @return string
     */
    protected function _renderLayers()
    {
        $layers = $this->getLayers();
        if (empty($layers)) {
            return '';
        }

        $html = array();
        foreach ($layers as $path) {
            $html[] = sprintf(
                '<script type="text/javascript" src="%s"></script>',
                htmlentities($path, ENT_QUOTES)
            );
        }

        return implode("\n", $html);
    }

    /**
     * Render dojo module paths and requires
     * 
     * @return string
     */
    protected function _renderExtras()
    {
        $js = array();
        $modulePaths = $this->getModulePaths();
        if (!empty($modulePaths)) {
            foreach ($modulePaths as $module => $path) {
                $js[] =  'dojo.registerModulePath("' . $this->view->escape($module) . '", "' . $this->view->escape($path) . '");';
            }
        }

        $modules = $this->getModules();
        if (!empty($modules)) {
            foreach ($modules as $module) {
                $js[] = 'dojo.require("' . $this->view->escape($module) . '");';
            }
        }

        $onLoadActions = array();
        foreach ($this->getOnLoadActions() as $callback) {
            $onLoadActions[] = 'dojo.addOnLoad(' . $callback . ');';
        }

        $javascript = implode("\n    ", $this->getJavascript());

        $content = '';
        if (!empty($js)) {
            $content .= implode("\n    ", $js) . "\n";
        }

        if (!empty($onLoadActions)) {
            $content .= implode("\n    ", $onLoadActions) . "\n";
        }

        if (!empty($javascript)) {
            $content .= $javascript . "\n";
        }

        if (preg_match('/^\s*$/s', $content)) {
            return '';
        }

        $html = '<script type="text/javascript">' . PHP_EOL
              . (($this->_isXhtml) ? '//<![CDATA[' : '//<!--') . PHP_EOL
              . $content
              . (($this->_isXhtml) ? '//]]>' : '//-->') . PHP_EOL
              . PHP_EOL . '</script>';
        return $html;
    }
}