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

/**
 * Zend_Console_Getopt is a class to parse options for command-line
 * applications.
 *
 * Terminology:
 * Argument: an element of the argv array.  This may be part of an option,
 *   or it may be a non-option command-line argument.
 * Flag: the letter or word set off by a '-' or '--'.  Example: in '--output filename',
 *   '--output' is the flag.
 * Parameter: the additional argument that is associated with the option.
 *   Example: in '--output filename', the 'filename' is the parameter.
 * Option: the combination of a flag and its parameter, if any.
 *   Example: in '--output filename', the whole thing is the option.
 *
 * The following features are supported:
 *
 * - Short flags like '-a'.  Short flags are preceded by a single
 *   dash.  Short flags may be clustered e.g. '-abc', which is the
 *   same as '-a' '-b' '-c'.
 * - Long flags like '--verbose'.  Long flags are preceded by a
 *   double dash.  Long flags may not be clustered.
 * - Options may have a parameter, e.g. '--output filename'.
 * - Parameters for long flags may also be set off with an equals sign,
 *   e.g. '--output=filename'.
 * - Parameters for long flags may be checked as string, word, or integer.
 * - Automatic generation of a helpful usage message.
 * - Signal end of options with '--'; subsequent arguments are treated
 *   as non-option arguments, even if they begin with '-'.
 * - Raise exception Zend_Console_Getopt_Exception in several cases
 *   when invalid flags or parameters are given.  Usage message is
 *   returned in the exception object.
 *
 * The format for specifying options uses a PHP associative array.
 * The key is has the format of a list of pipe-separated flag names,
 * followed by an optional '=' to indicate a required parameter or
 * '-' to indicate an optional parameter.  Following that, the type
 * of parameter may be specified as 's' for string, 'w' for word,
 * or 'i' for integer.
 *
 * Examples:
 * - 'user|username|u=s'  this means '--user' or '--username' or '-u'
 *   are synonyms, and the option requires a string parameter.
 * - 'p=i'  this means '-p' requires an integer parameter.  No synonyms.
 * - 'verbose|v-i'  this means '--verbose' or '-v' are synonyms, and
 *   they take an optional integer parameter.
 * - 'help|h'  this means '--help' or '-h' are synonyms, and
 *   they take no parameter.
 *
 * The values in the associative array are strings that are used as
 * brief descriptions of the options when printing a usage message.
 *
 * The simpler format for specifying options used by PHP's getopt()
 * function is also supported.  This is similar to GNU getopt and shell
 * getopt format.
 *
 * Example:  'abc:' means options '-a', '-b', and '-c'
 * are legal, and the latter requires a string parameter.
 *
 * @category   Zend
 * @package    Zend_Console_Getopt
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    Release: @package_version@
 * @since      Class available since Release 0.6.0
 *
 * @todo  Handle params with multiple values, e.g. --colors=red,green,blue
 *        Set value of parameter to the array of values.  Allow user to specify
 *        the separator with Zend_Console_Getopt::CONFIG_PARAMETER_SEPARATOR.
 *        If this config value is null or empty string, do not split values
 *        into arrays.  Default separator is comma (',').
 *
 * @todo  Handle params with multiple values specified with separate options
 *        e.g. --colors red --colors green --colors blue should give one
 *        option with an array(red, green, blue).
 *        Enable with Zend_Console_Getopt::CONFIG_CUMULATIVE_PARAMETERS.
 *        Default is that subsequent options overwrite the parameter value.
 *
 * @todo  Handle flags occurring multiple times, e.g. -v -v -v
 *        Set value of the option's parameter to the integer count of instances
 *        instead of a boolean.
 *        Enable with Zend_Console_Getopt::CONFIG_CUMULATIVE_FLAGS.
 *        Default is that the value is simply boolean true regardless of
 *        how many instances of the flag appear.
 *
 * @todo  Handle flags that implicitly print usage message, e.g. --help
 *
 * @todo  Handle freeform options, e.g. --set-variable
 *        Enable with Zend_Console_Getopt::CONFIG_FREEFORM_FLAGS
 *        All flag-like syntax is recognized, no flag generates an exception.
 *
 * @todo  Handle numeric options, e.g. -1, -2, -3, -1000
 *        Enable with Zend_Console_Getopt::CONFIG_NUMERIC_FLAGS
 *        The rule must specify a named flag and the '#' symbol as the
 *        parameter type. e.g.,  'lines=#'
 *
 * @todo  Enable user to specify header and footer content in the help message.
 *
 * @todo  Feature request to handle option interdependencies.
 *        e.g. if -b is specified, -a must be specified or else the
 *        usage is invalid.
 *
 * @todo  Feature request to implement callbacks.
 *        e.g. if -a is specified, run function 'handleOptionA'().
 */
class Zend_Console_Getopt
{

    /**
     * The options for a given application can be in multiple formats.
     * modeGnu is for traditional 'ab:c:' style getopt format.
     * modeZend is for a more structured format.
     */
    const MODE_ZEND                         = 'zend';
    const MODE_GNU                          = 'gnu';

    /**
     * Constant tokens for various symbols used in the mode_zend
     * rule format.
     */
    const PARAM_REQUIRED                    = '=';
    const PARAM_OPTIONAL                    = '-';
    const TYPE_STRING                       = 's';
    const TYPE_WORD                         = 'w';
    const TYPE_INTEGER                      = 'i';

    /**
     * These are constants for optional behavior of this class.
     * ruleMode is either 'zend' or 'gnu' or a user-defined mode.
     * dashDash is true if '--' signifies the end of command-line options.
     * ignoreCase is true if '--opt' and '--OPT' are implicitly synonyms.
     * parseAll is true if all options on the command line should be parsed, regardless of
     * whether an argument appears before them.
     */
    const CONFIG_RULEMODE                   = 'ruleMode';
    const CONFIG_DASHDASH                   = 'dashDash';
    const CONFIG_IGNORECASE                 = 'ignoreCase';
    const CONFIG_PARSEALL                   = 'parseAll';

    /**
     * Defaults for getopt configuration are:
     * ruleMode is 'zend' format,
     * dashDash (--) token is enabled,
     * ignoreCase is not enabled,
     * parseAll is enabled.
     */
    protected $_getoptConfig = array(
        self::CONFIG_RULEMODE   => self::MODE_ZEND,
        self::CONFIG_DASHDASH   => true,
        self::CONFIG_IGNORECASE => false,
        self::CONFIG_PARSEALL   => true,
    );

    /**
     * Stores the command-line arguments for the calling applicaion.
     *
     * @var array
     */
    protected $_argv = array();

    /**
     * Stores the name of the calling applicaion.
     *
     * @var string
     */
    protected $_progname = '';

    /**
     * Stores the list of legal options for this application.
     *
     * @var array
     */
    protected $_rules = array();

    /**
     * Stores alternate spellings of legal options.
     *
     * @var array
     */
    protected $_ruleMap = array();

    /**
     * Stores options given by the user in the current invocation
     * of the application, as well as parameters given in options.
     *
     * @var array
     */
    protected $_options = array();

    /**
     * Stores the command-line arguments other than options.
     *
     * @var array
     */
    protected $_remainingArgs = array();

    /**
     * State of the options: parsed or not yet parsed?
     *
     * @var boolean
     */
    protected $_parsed = false;

    /**
     * The constructor takes one to three parameters.
     *
     * The first parameter is $rules, which may be a string for
     * gnu-style format, or a structured array for Zend-style format.
     *
     * The second parameter is $argv, and it is optional.  If not
     * specified, $argv is inferred from the global argv.
     *
     * The third parameter is an array of configuration parameters
     * to control the behavior of this instance of Getopt; it is optional.
     *
     * @param  array $rules
     * @param  array $argv
     * @param  array $getoptConfig
     * @return void
     */
    public function __construct($rules, $argv = null, $getoptConfig = array())
    {
        if (!isset($_SERVER['argv'])) {
            require_once 'Zend/Console/Getopt/Exception.php';
            if (ini_get('register_argc_argv') == false) {
                throw new Zend_Console_Getopt_Exception(
                    "argv is not available, because ini option 'register_argc_argv' is set Off"
                );
            } else {
                throw new Zend_Console_Getopt_Exception(
                    '$_SERVER["argv"] is not set, but Zend_Console_Getopt cannot work without this information.'
                );
            }
        }

        $this->_progname = $_SERVER['argv'][0];
        $this->setOptions($getoptConfig);
        $this->addRules($rules);
        if (!is_array($argv)) {
            $argv = array_slice($_SERVER['argv'], 1);
        }
        if (isset($argv)) {
            $this->addArguments((array)$argv);
        }
    }

    /**
     * Return the state of the option seen on the command line of the
     * current application invocation.  This function returns true, or the
     * parameter to the option, if any.  If the option was not given,
     * this function returns null.
     *
     * The magic __get method works in the context of naming the option
     * as a virtual member of this class.
     *
     * @param  string $key
     * @return string
     */
    public function __get($key)
    {
        return $this->getOption($key);
    }

    /**
     * Test whether a given option has been seen.
     *
     * @param  string $key
     * @return boolean
     */
    public function __isset($key)
    {
        $this->parse();
        if (isset($this->_ruleMap[$key])) {
            $key = $this->_ruleMap[$key];
            return isset($this->_options[$key]);
        }
        return false;
    }

    /**
     * Set the value for a given option.
     *
     * @param  string $key
     * @param  string $value
     * @return void
     */
    public function __set($key, $value)
    {
        $this->parse();
        if (isset($this->_ruleMap[$key])) {
            $key = $this->_ruleMap[$key];
            $this->_options[$key] = $value;
        }
    }

    /**
     * Return the current set of options and parameters seen as a string.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->toString();
    }

    /**
     * Unset an option.
     *
     * @param  string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->parse();
        if (isset($this->_ruleMap[$key])) {
            $key = $this->_ruleMap[$key];
            unset($this->_options[$key]);
        }
    }

    /**
     * Define additional command-line arguments.
     * These are appended to those defined when the constructor was called.
     *
     * @param  array $argv
     * @throws Zend_Console_Getopt_Exception When not given an array as parameter
     * @return Zend_Console_Getopt Provides a fluent interface
     */
    public function addArguments($argv)
    {
        if(!is_array($argv)) {
            require_once 'Zend/Console/Getopt/Exception.php';
            throw new Zend_Console_Getopt_Exception(
                "Parameter #1 to addArguments should be an array");
        }
        $this->_argv = array_merge($this->_argv, $argv);
        $this->_parsed = false;
        return $this;
    }

    /**
     * Define full set of command-line arguments.
     * These replace any currently defined.
     *
     * @param  array $argv
     * @throws Zend_Console_Getopt_Exception When not given an array as parameter
     * @return Zend_Console_Getopt Provides a fluent interface
     */
    public function setArguments($argv)
    {
        if(!is_array($argv)) {
            require_once 'Zend/Console/Getopt/Exception.php';
            throw new Zend_Console_Getopt_Exception(
                "Parameter #1 to setArguments should be an array");
        }
        $this->_argv = $argv;
        $this->_parsed = false;
        return $this;
    }

    /**
     * Define multiple configuration options from an associative array.
     * These are not program options, but properties to configure
     * the behavior of Zend_Console_Getopt.
     *
     * @param  array $getoptConfig
     * @return Zend_Console_Getopt Provides a fluent interface
     */
    public function setOptions($getoptConfig)
    {
        if (isset($getoptConfig)) {
            foreach ($getoptConfig as $key => $value) {
                $this->setOption($key, $value);
            }
        }
        return $this;
    }

    /**
     * Define one configuration option as a key/value pair.
     * These are not program options, but properties to configure
     * the behavior of Zend_Console_Getopt.
     *
     * @param  string $configKey
     * @param  string $configValue
     * @return Zend_Console_Getopt Provides a fluent interface
     */
    public function setOption($configKey, $configValue)
    {
        if ($configKey !== null) {
            $this->_getoptConfig[$configKey] = $configValue;
        }
        return $this;
    }

    /**
     * Define additional option rules.
     * These are appended to the rules defined when the constructor was called.
     *
     * @param  array $rules
     * @return Zend_Console_Getopt Provides a fluent interface
     */
    public function addRules($rules)
    {
        $ruleMode = $this->_getoptConfig['ruleMode'];
        switch ($this->_getoptConfig['ruleMode']) {
            case self::MODE_ZEND:
                if (is_array($rules)) {
                    $this->_addRulesModeZend($rules);
                    break;
                }
                // intentional fallthrough
            case self::MODE_GNU:
                $this->_addRulesModeGnu($rules);
                break;
            default:
                /**
                 * Call addRulesModeFoo() for ruleMode 'foo'.
                 * The developer should subclass Getopt and
                 * provide this method.
                 */
                $method = '_addRulesMode' . ucfirst($ruleMode);
                $this->$method($rules);
        }
        $this->_parsed = false;
        return $this;
    }

    /**
     * Return the current set of options and parameters seen as a string.
     *
     * @return string
     */
    public function toString()
    {
        $this->parse();
        $s = array();
        foreach ($this->_options as $flag => $value) {
            $s[] = $flag . '=' . ($value === true ? 'true' : $value);
        }
        return implode(' ', $s);
    }

    /**
     * Return the current set of options and parameters seen
     * as an array of canonical options and parameters.
     *
     * Clusters have been expanded, and option aliases
     * have been mapped to their primary option names.
     *
     * @return array
     */
    public function toArray()
    {
        $this->parse();
        $s = array();
        foreach ($this->_options as $flag => $value) {
            $s[] = $flag;
            if ($value !== true) {
                $s[] = $value;
            }
        }
        return $s;
    }

    /**
     * Return the current set of options and parameters seen in Json format.
     *
     * @return string
     */
    public function toJson()
    {
        $this->parse();
        $j = array();
        foreach ($this->_options as $flag => $value) {
            $j['options'][] = array(
                'option' => array(
                    'flag' => $flag,
                    'parameter' => $value
                )
            );
        }

        /**
         * @see Zend_Json
         */
        require_once 'Zend/Json.php';
        $json = Zend_Json::encode($j);

        return $json;
    }

    /**
     * Return the current set of options and parameters seen in XML format.
     *
     * @return string
     */
    public function toXml()
    {
        $this->parse();
        $doc = new DomDocument('1.0', 'utf-8');
        $optionsNode = $doc->createElement('options');
        $doc->appendChild($optionsNode);
        foreach ($this->_options as $flag => $value) {
            $optionNode = $doc->createElement('option');
            $optionNode->setAttribute('flag', utf8_encode($flag));
            if ($value !== true) {
                $optionNode->setAttribute('parameter', utf8_encode($value));
            }
            $optionsNode->appendChild($optionNode);
        }
        $xml = $doc->saveXML();
        return $xml;
    }

    /**
     * Return a list of options that have been seen in the current argv.
     *
     * @return array
     */
    public function getOptions()
    {
        $this->parse();
        return array_keys($this->_options);
    }

    /**
     * Return the state of the option seen on the command line of the
     * current application invocation.
     *
     * This function returns true, or the parameter value to the option, if any.
     * If the option was not given, this function returns false.
     *
     * @param  string $flag
     * @return mixed
     */
    public function getOption($flag)
    {
        $this->parse();
        if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
            $flag = strtolower($flag);
        }
        if (isset($this->_ruleMap[$flag])) {
            $flag = $this->_ruleMap[$flag];
            if (isset($this->_options[$flag])) {
                return $this->_options[$flag];
            }
        }
        return null;
    }

    /**
     * Return the arguments from the command-line following all options found.
     *
     * @return array
     */
    public function getRemainingArgs()
    {
        $this->parse();
        return $this->_remainingArgs;
    }

    /**
     * Return a useful option reference, formatted for display in an
     * error message.
     *
     * Note that this usage information is provided in most Exceptions
     * generated by this class.
     *
     * @return string
     */
    public function getUsageMessage()
    {
        $usage = "Usage: {$this->_progname} [ options ]\n";
        $maxLen = 20;
        $lines = array();
        foreach ($this->_rules as $rule) {
            $flags = array();
            if (is_array($rule['alias'])) {
                foreach ($rule['alias'] as $flag) {
                    $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag;
                }
            }
            $linepart['name'] = implode('|', $flags);
            if (isset($rule['param']) && $rule['param'] != 'none') {
                $linepart['name'] .= ' ';
                switch ($rule['param']) {
                    case 'optional':
                        $linepart['name'] .= "[ <{$rule['paramType']}> ]";
                        break;
                    case 'required':
                        $linepart['name'] .= "<{$rule['paramType']}>";
                        break;
                }
            }
            if (strlen($linepart['name']) > $maxLen) {
                $maxLen = strlen($linepart['name']);
            }
            $linepart['help'] = '';
            if (isset($rule['help'])) {
                $linepart['help'] .= $rule['help'];
            }
            $lines[] = $linepart;
        }
        foreach ($lines as $linepart) {
            $usage .= sprintf("%s %s\n",
            str_pad($linepart['name'], $maxLen),
            $linepart['help']);
        }
        return $usage;
    }

    /**
     * Define aliases for options.
     *
     * The parameter $aliasMap is an associative array
     * mapping option name (short or long) to an alias.
     *
     * @param  array $aliasMap
     * @throws Zend_Console_Getopt_Exception
     * @return Zend_Console_Getopt Provides a fluent interface
     */
    public function setAliases($aliasMap)
    {
        foreach ($aliasMap as $flag => $alias)
        {
            if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
                $flag = strtolower($flag);
                $alias = strtolower($alias);
            }
            if (!isset($this->_ruleMap[$flag])) {
                continue;
            }
            $flag = $this->_ruleMap[$flag];
            if (isset($this->_rules[$alias]) || isset($this->_ruleMap[$alias])) {
                $o = (strlen($alias) == 1 ? '-' : '--') . $alias;
                require_once 'Zend/Console/Getopt/Exception.php';
                throw new Zend_Console_Getopt_Exception(
                    "Option \"$o\" is being defined more than once.");
            }
            $this->_rules[$flag]['alias'][] = $alias;
            $this->_ruleMap[$alias] = $flag;
        }
        return $this;
    }

    /**
     * Define help messages for options.
     *
     * The parameter $help_map is an associative array
     * mapping option name (short or long) to the help string.
     *
     * @param  array $helpMap
     * @return Zend_Console_Getopt Provides a fluent interface
     */
    public function setHelp($helpMap)
    {
        foreach ($helpMap as $flag => $help)
        {
            if (!isset($this->_ruleMap[$flag])) {
                continue;
            }
            $flag = $this->_ruleMap[$flag];
            $this->_rules[$flag]['help'] = $help;
        }
        return $this;
    }

    /**
     * Parse command-line arguments and find both long and short
     * options.
     *
     * Also find option parameters, and remaining arguments after
     * all options have been parsed.
     *
     * @return Zend_Console_Getopt|null Provides a fluent interface
     */
    public function parse()
    {
        if ($this->_parsed === true) {
            return;
        }
        $argv = $this->_argv;
        $this->_options = array();
        $this->_remainingArgs = array();
        while (count($argv) > 0) {
            if ($argv[0] == '--') {
                array_shift($argv);
                if ($this->_getoptConfig[self::CONFIG_DASHDASH]) {
                    $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
                    break;
                }
            }
            if (substr($argv[0], 0, 2) == '--') {
                $this->_parseLongOption($argv);
            } else if (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1))  {
                $this->_parseShortOptionCluster($argv);
            } else if($this->_getoptConfig[self::CONFIG_PARSEALL]) {
                $this->_remainingArgs[] = array_shift($argv);
            } else {
                /*
                 * We should put all other arguments in _remainingArgs and stop parsing
                 * since CONFIG_PARSEALL is false.
                 */
                $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
                break;
            }
        }
        $this->_parsed = true;
        return $this;
    }

    /**
     * Parse command-line arguments for a single long option.
     * A long option is preceded by a double '--' character.
     * Long options may not be clustered.
     *
     * @param  mixed &$argv
     * @return void
     */
    protected function _parseLongOption(&$argv)
    {
        $optionWithParam = ltrim(array_shift($argv), '-');
        $l = explode('=', $optionWithParam, 2);
        $flag = array_shift($l);
        $param = array_shift($l);
        if (isset($param)) {
            array_unshift($argv, $param);
        }
        $this->_parseSingleOption($flag, $argv);
    }

    /**
     * Parse command-line arguments for short options.
     * Short options are those preceded by a single '-' character.
     * Short options may be clustered.
     *
     * @param  mixed &$argv
     * @return void
     */
    protected function _parseShortOptionCluster(&$argv)
    {
        $flagCluster = ltrim(array_shift($argv), '-');
        foreach (str_split($flagCluster) as $flag) {
            $this->_parseSingleOption($flag, $argv);
        }
    }

    /**
     * Parse command-line arguments for a single option.
     *
     * @param  string $flag
     * @param  mixed  $argv
     * @throws Zend_Console_Getopt_Exception
     * @return void
     */
    protected function _parseSingleOption($flag, &$argv)
    {
        if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
            $flag = strtolower($flag);
        }
        if (!isset($this->_ruleMap[$flag])) {
            require_once 'Zend/Console/Getopt/Exception.php';
            throw new Zend_Console_Getopt_Exception(
                "Option \"$flag\" is not recognized.",
                $this->getUsageMessage());
        }
        $realFlag = $this->_ruleMap[$flag];
        switch ($this->_rules[$realFlag]['param']) {
            case 'required':
                if (count($argv) > 0) {
                    $param = array_shift($argv);
                    $this->_checkParameterType($realFlag, $param);
                } else {
                    require_once 'Zend/Console/Getopt/Exception.php';
                    throw new Zend_Console_Getopt_Exception(
                        "Option \"$flag\" requires a parameter.",
                        $this->getUsageMessage());
                }
                break;
            case 'optional':
                if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
                    $param = array_shift($argv);
                    $this->_checkParameterType($realFlag, $param);
                } else {
                    $param = true;
                }
                break;
            default:
                $param = true;
        }
        $this->_options[$realFlag] = $param;
    }

    /**
     * Return true if the parameter is in a valid format for
     * the option $flag.
     * Throw an exception in most other cases.
     *
     * @param  string $flag
     * @param  string $param
     * @throws Zend_Console_Getopt_Exception
     * @return bool
     */
    protected function _checkParameterType($flag, $param)
    {
        $type = 'string';
        if (isset($this->_rules[$flag]['paramType'])) {
            $type = $this->_rules[$flag]['paramType'];
        }
        switch ($type) {
            case 'word':
                if (preg_match('/\W/', $param)) {
                    require_once 'Zend/Console/Getopt/Exception.php';
                    throw new Zend_Console_Getopt_Exception(
                        "Option \"$flag\" requires a single-word parameter, but was given \"$param\".",
                        $this->getUsageMessage());
                }
                break;
            case 'integer':
                if (preg_match('/\D/', $param)) {
                    require_once 'Zend/Console/Getopt/Exception.php';
                    throw new Zend_Console_Getopt_Exception(
                        "Option \"$flag\" requires an integer parameter, but was given \"$param\".",
                        $this->getUsageMessage());
                }
                break;
            case 'string':
            default:
                break;
        }
        return true;
    }

    /**
     * Define legal options using the gnu-style format.
     *
     * @param  string $rules
     * @return void
     */
    protected function _addRulesModeGnu($rules)
    {
        $ruleArray = array();

        /**
         * Options may be single alphanumeric characters.
         * Options may have a ':' which indicates a required string parameter.
         * No long options or option aliases are supported in GNU style.
         */
        preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
        foreach ($ruleArray[1] as $rule) {
            $r = array();
            $flag = substr($rule, 0, 1);
            if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
                $flag = strtolower($flag);
            }
            $r['alias'][] = $flag;
            if (substr($rule, 1, 1) == ':') {
                $r['param'] = 'required';
                $r['paramType'] = 'string';
            } else {
                $r['param'] = 'none';
            }
            $this->_rules[$flag] = $r;
            $this->_ruleMap[$flag] = $flag;
        }
    }

    /**
     * Define legal options using the Zend-style format.
     *
     * @param  array $rules
     * @throws Zend_Console_Getopt_Exception
     * @return void
     */
    protected function _addRulesModeZend($rules)
    {
        foreach ($rules as $ruleCode => $helpMessage)
        {
            // this may have to translate the long parm type if there
            // are any complaints that =string will not work (even though that use
            // case is not documented)
            if (in_array(substr($ruleCode, -2, 1), array('-', '='))) {
                $flagList  = substr($ruleCode, 0, -2);
                $delimiter = substr($ruleCode, -2, 1);
                $paramType = substr($ruleCode, -1);
            } else {
                $flagList = $ruleCode;
                $delimiter = $paramType = null;
            }
            if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
                $flagList = strtolower($flagList);
            }
            $flags = explode('|', $flagList);
            $rule = array();
            $mainFlag = $flags[0];
            foreach ($flags as $flag) {
                if (empty($flag)) {
                    require_once 'Zend/Console/Getopt/Exception.php';
                    throw new Zend_Console_Getopt_Exception(
                        "Blank flag not allowed in rule \"$ruleCode\".");
                }
                if (strlen($flag) == 1) {
                    if (isset($this->_ruleMap[$flag])) {
                        require_once 'Zend/Console/Getopt/Exception.php';
                        throw new Zend_Console_Getopt_Exception(
                            "Option \"-$flag\" is being defined more than once.");
                    }
                    $this->_ruleMap[$flag] = $mainFlag;
                    $rule['alias'][] = $flag;
                } else {
                    if (isset($this->_rules[$flag]) || isset($this->_ruleMap[$flag])) {
                        require_once 'Zend/Console/Getopt/Exception.php';
                        throw new Zend_Console_Getopt_Exception(
                            "Option \"--$flag\" is being defined more than once.");
                    }
                    $this->_ruleMap[$flag] = $mainFlag;
                    $rule['alias'][] = $flag;
                }
            }
            if (isset($delimiter)) {
                switch ($delimiter) {
                    case self::PARAM_REQUIRED:
                        $rule['param'] = 'required';
                        break;
                    case self::PARAM_OPTIONAL:
                    default:
                        $rule['param'] = 'optional';
                }
                switch (substr($paramType, 0, 1)) {
                    case self::TYPE_WORD:
                        $rule['paramType'] = 'word';
                        break;
                    case self::TYPE_INTEGER:
                        $rule['paramType'] = 'integer';
                        break;
                    case self::TYPE_STRING:
                    default:
                        $rule['paramType'] = 'string';
                }
            } else {
                $rule['param'] = 'none';
            }
            $rule['help'] = $helpMessage;
            $this->_rules[$mainFlag] = $rule;
        }
    }

}


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

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

/**
 * @category   Zend
 * @package    Zend_Console_Getopt
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Console_Getopt_Exception extends Zend_Exception
{
    /**
     * Usage
     *
     * @var string
     */
    protected $usage = '';

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

    /**
     * Returns the usage
     *
     * @return string
     */
    public function getUsageMessage()
    {
        return $this->usage;
    }
}

repo_name: michael-romer/zf-boilerplate

repo_language: PHP

mime_type: text/html


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

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

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


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

/** @see Zend_Serializer_Adapter_AdapterInterface */
require_once 'Zend/Serializer/Adapter/AdapterInterface.php';

/**
 * @category   Zend
 * @package    Zend_Serializer
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Serializer_Adapter_AdapterAbstract implements Zend_Serializer_Adapter_AdapterInterface
{
    /**
     * Serializer options
     *
     * @var array
     */
    protected $_options = array();

    /**
     * Constructor
     *
     * @param array|Zend_Config $opts Serializer options
     */
    public function __construct($opts = array())
    {
        $this->setOptions($opts);
    }

    /**
     * Set serializer options
     *
     * @param  array|Zend_Config $opts Serializer options
     * @return Zend_Serializer_Adapter_AdapterAbstract
     */
    public function setOptions($opts)
    {
        if ($opts instanceof Zend_Config) {
            $opts = $opts->toArray();
        } else {
            $opts = (array) $opts;
        }

        foreach ($opts as $k => $v) {
            $this->setOption($k, $v);
        }
        return $this;
    }

    /**
     * Set a serializer option
     *
     * @param  string $name Option name
     * @param  mixed $value Option value
     * @return Zend_Serializer_Adapter_AdapterAbstract
     */
    public function setOption($name, $value)
    {
        $this->_options[(string) $name] = $value;
        return $this;
    }

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

    /**
     * Get a serializer option
     *
     * @param  string $name
     * @return mixed
     * @throws Zend_Serializer_Exception
     */
    public function getOption($name)
    {
        $name = (string) $name;
        if (!array_key_exists($name, $this->_options)) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Unknown option name "'.$name.'"');
        }

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


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

/** @see Zend_Serializer_Adapter_AdapterAbstract */
require_once 'Zend/Serializer/Adapter/AdapterAbstract.php';

/**
 * @category   Zend
 * @package    Zend_Serializer
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Serializer_Adapter_Igbinary extends Zend_Serializer_Adapter_AdapterAbstract
{
    /**
     * @var string Serialized null value
     */
    private static $_serializedNull = null;

    /**
     * Constructor
     *
     * @param  array|Zend_Config $opts
     * @return void
     * @throws Zend_Serializer_Exception If igbinary extension is not present
     */
    public function __construct($opts = array())
    {
        if (!extension_loaded('igbinary')) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('PHP extension "igbinary" is required for this adapter');
        }

        parent::__construct($opts);

        if (self::$_serializedNull === null) {
            self::$_serializedNull = igbinary_serialize(null);
        }
    }

    /**
     * Serialize PHP value to igbinary
     *
     * @param  mixed $value
     * @param  array $opts
     * @return string
     * @throws Zend_Serializer_Exception on igbinary error
     */
    public function serialize($value, array $opts = array())
    {
        $ret = igbinary_serialize($value);
        if ($ret === false) {
            $lastErr = error_get_last();
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception($lastErr['message']);
        }
        return $ret;
    }

    /**
     * Deserialize igbinary string to PHP value
     *
     * @param  string|binary $serialized
     * @param  array $opts
     * @return mixed
     * @throws Zend_Serializer_Exception on igbinary error
     */
    public function unserialize($serialized, array $opts = array())
    {
        $ret = igbinary_unserialize($serialized);
        if ($ret === null && $serialized !== self::$_serializedNull) {
            $lastErr = error_get_last();
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception($lastErr['message']);
        }
        return $ret;
    }
}


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

/** @see Zend_Serializer_Adapter_AdapterAbstract */
require_once 'Zend/Serializer/Adapter/AdapterAbstract.php';

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

/**
 * @category   Zend
 * @package    Zend_Serializer
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Serializer_Adapter_Json extends Zend_Serializer_Adapter_AdapterAbstract
{
    /**
     * @var array Default options
     */
    protected $_options = array(
        'cycleCheck'           => false,
        'enableJsonExprFinder' => false,
        'objectDecodeType'     => Zend_Json::TYPE_ARRAY,
    );

    /**
     * Serialize PHP value to JSON
     *
     * @param  mixed $value
     * @param  array $opts
     * @return string
     * @throws Zend_Serializer_Exception on JSON encoding exception
     */
    public function serialize($value, array $opts = array())
    {
        $opts = $opts + $this->_options;

        try  {
            return Zend_Json::encode($value, $opts['cycleCheck'], $opts);
        } catch (Exception $e) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Serialization failed', 0, $e);
        }
    }

    /**
     * Deserialize JSON to PHP value
     *
     * @param  string $json
     * @param  array $opts
     * @return mixed
     */
    public function unserialize($json, array $opts = array())
    {
        $opts = $opts + $this->_options;

        try {
            $ret = Zend_Json::decode($json, $opts['objectDecodeType']);
        } catch (Exception $e) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Unserialization failed by previous error', 0, $e);
        }

        // json_decode returns null for invalid JSON
        if ($ret === null && $json !== 'null') {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Invalid json data');
        }

        return $ret;
    }
}


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

/** @see Zend_Serializer_Adapter_AdapterAbstract */
require_once 'Zend/Serializer/Adapter/AdapterAbstract.php';

/**
 * @category   Zend
 * @package    Zend_Serializer
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Serializer_Adapter_PhpCode extends Zend_Serializer_Adapter_AdapterAbstract
{
    /**
     * Serialize PHP using var_export
     *
     * @param  mixed $value
     * @param  array $opts
     * @return string
     */
    public function serialize($value, array $opts = array())
    {
        return var_export($value, true);
    }

    /**
     * Deserialize PHP string
     *
     * Warning: this uses eval(), and should likely be avoided.
     *
     * @param  string $code
     * @param  array $opts
     * @return mixed
     * @throws Zend_Serializer_Exception on eval error
     */
    public function unserialize($code, array $opts = array())
    {
        $eval = @eval('$ret=' . $code . ';');
        if ($eval === false) {
                $lastErr = error_get_last();
                require_once 'Zend/Serializer/Exception.php';
                throw new Zend_Serializer_Exception('eval failed: ' . $lastErr['message']);
        }
        return $ret;
    }
}


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

/** @see Zend_Serializer_Adapter_AdapterAbstract */
require_once 'Zend/Serializer/Adapter/AdapterAbstract.php';

/**
 * @link       http://www.python.org
 * @see        Phython3.1/Lib/pickle.py
 * @see        Phython3.1/Modules/_pickle.c
 * @link       http://pickle-js.googlecode.com
 * @category   Zend
 * @package    Zend_Serializer
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Serializer_Adapter_PythonPickle extends Zend_Serializer_Adapter_AdapterAbstract
{
    /* Pickle opcodes. See pickletools.py for extensive docs.  The listing
       here is in kind-of alphabetical order of 1-character pickle code.
       pickletools groups them by purpose. */
    const OP_MARK            = '(';     // push special markobject on stack
    const OP_STOP            = '.';     // every pickle ends with STOP
    const OP_POP             = '0';     // discard topmost stack item
    const OP_POP_MARK        = '1';     // discard stack top through topmost markobject
    const OP_DUP             = '2';     // duplicate top stack item
    const OP_FLOAT           = 'F';     // push float object; decimal string argument
    const OP_INT             = 'I';     // push integer or bool; decimal string argument
    const OP_BININT          = 'J';     // push four-byte signed int
    const OP_BININT1         = 'K';     // push 1-byte unsigned int
    const OP_LONG            = 'L';     // push long; decimal string argument
    const OP_BININT2         = 'M';     // push 2-byte unsigned int
    const OP_NONE            = 'N';     // push None
    const OP_PERSID          = 'P';     // push persistent object; id is taken from string arg
    const OP_BINPERSID       = 'Q';     //  "       "         "  ;  "  "   "     "  stack
    const OP_REDUCE          = 'R';     // apply callable to argtuple, both on stack
    const OP_STRING          = 'S';     // push string; NL-terminated string argument
    const OP_BINSTRING       = 'T';     // push string; counted binary string argument
    const OP_SHORT_BINSTRING = 'U';     //  "     "   ;    "      "       "      " < 256 bytes
    const OP_UNICODE         = 'V';     // push Unicode string; raw-unicode-escaped'd argument
    const OP_BINUNICODE      = 'X';     //   "     "       "  ; counted UTF-8 string argument
    const OP_APPEND          = 'a';     // append stack top to list below it
    const OP_BUILD           = 'b';     // call __setstate__ or __dict__.update()
    const OP_GLOBAL          = 'c';     // push self.find_class(modname, name); 2 string args
    const OP_DICT            = 'd';     // build a dict from stack items
    const OP_EMPTY_DICT      = '}';     // push empty dict
    const OP_APPENDS         = 'e';     // extend list on stack by topmost stack slice
    const OP_GET             = 'g';     // push item from memo on stack; index is string arg
    const OP_BINGET          = 'h';     //   "    "    "    "   "   "  ;   "    " 1-byte arg
    const OP_INST            = 'i';     // build & push class instance
    const OP_LONG_BINGET     = 'j';     // push item from memo on stack; index is 4-byte arg
    const OP_LIST            = 'l';     // build list from topmost stack items
    const OP_EMPTY_LIST      = ']';     // push empty list
    const OP_OBJ             = 'o';     // build & push class instance
    const OP_PUT             = 'p';     // store stack top in memo; index is string arg
    const OP_BINPUT          = 'q';     //   "     "    "   "   " ;   "    " 1-byte arg
    const OP_LONG_BINPUT     = 'r';     //   "     "    "   "   " ;   "    " 4-byte arg
    const OP_SETITEM         = 's';     // add key+value pair to dict
    const OP_TUPLE           = 't';     // build tuple from topmost stack items
    const OP_EMPTY_TUPLE     = ')';     // push empty tuple
    const OP_SETITEMS        = 'u';     // modify dict by adding topmost key+value pairs
    const OP_BINFLOAT        = 'G';     // push float; arg is 8-byte float encoding

    /* Protocol 2 */
    const OP_PROTO           = "\x80";  // identify pickle protocol
    const OP_NEWOBJ          = "\x81";  // build object by applying cls.__new__ to argtuple
    const OP_EXT1            = "\x82";  // push object from extension registry; 1-byte index
    const OP_EXT2            = "\x83";  // ditto, but 2-byte index
    const OP_EXT4            = "\x84";  // ditto, but 4-byte index
    const OP_TUPLE1          = "\x85";  // build 1-tuple from stack top
    const OP_TUPLE2          = "\x86";  // build 2-tuple from two topmost stack items
    const OP_TUPLE3          = "\x87";  // build 3-tuple from three topmost stack items
    const OP_NEWTRUE         = "\x88";  // push True
    const OP_NEWFALSE        = "\x89";  // push False
    const OP_LONG1           = "\x8a";  // push long from < 256 bytes
    const OP_LONG4           = "\x8b";  // push really big long

    /* Protocol 3 (Python 3.x) */
    const OP_BINBYTES        = 'B';     // push bytes; counted binary string argument
    const OP_SHORT_BINBYTES  = 'C';     //  "     "   ;    "      "       "      " < 256 bytes

    /**
     * @var bool Whether or not this is a PHP 6 binary
     */
    protected static $_isPhp6 = null;

    /**
     * @var bool Whether or not the system is little-endian
     */
    protected static $_isLittleEndian = null;

    /**
     * @var array Strings representing quotes
     */
    protected static $_quoteString = array(
        '\\' => '\\\\',
        "\x00" => '\\x00', "\x01" => '\\x01', "\x02" => '\\x02', "\x03" => '\\x03',
        "\x04" => '\\x04', "\x05" => '\\x05', "\x06" => '\\x06', "\x07" => '\\x07',
        "\x08" => '\\x08', "\x09" => '\\t',   "\x0a" => '\\n',   "\x0b" => '\\x0b',
        "\x0c" => '\\x0c', "\x0d" => '\\r',   "\x0e" => '\\x0e', "\x0f" => '\\x0f',
        "\x10" => '\\x10', "\x11" => '\\x11', "\x12" => '\\x12', "\x13" => '\\x13',
        "\x14" => '\\x14', "\x15" => '\\x15', "\x16" => '\\x16', "\x17" => '\\x17',
        "\x18" => '\\x18', "\x19" => '\\x19', "\x1a" => '\\x1a', "\x1b" => '\\x1b',
        "\x1c" => '\\x1c', "\x1d" => '\\x1d', "\x1e" => '\\x1e', "\x1f" => '\\x1f',
        "\xff" => '\\xff'
    );

    /**
     * @var array Default options
     */
    protected $_options = array(
        'protocol'           => 0,
    );

    // process vars
    protected $_protocol           = 0;
    protected $_binary             = false;
    protected $_memo               = array();
    protected $_pickle             = '';
    protected $_pickleLen          = 0;
    protected $_pos                = 0;
    protected $_stack              = array();
    protected $_marker             = null;

    /**
     * Constructor
     *
     * @link Zend_Serializer_Adapter_AdapterAbstract::__construct()
     */
    public function __construct($opts=array())
    {
        parent::__construct($opts);

        // init
        if (self::$_isLittleEndian === null) {
            self::$_isLittleEndian = (pack('l', 1) === "\x01\x00\x00\x00");
        }
        if (self::$_isPhp6 === null) {
            self::$_isPhp6 = !version_compare(PHP_VERSION, '6.0.0', '<');
        }

        $this->_marker = new stdClass();
    }

    /**
     * Set an option
     *
     * @link   Zend_Serializer_Adapter_AdapterAbstract::setOption()
     * @param  string $name
     * @param  mixed $value
     * @return Zend_Serializer_Adapter_PythonPickle
     */
    public function setOption($name, $value)
    {
        switch ($name) {
            case 'protocol':
                $value = $this->_checkProtocolNumber($value);
                break;
        }

        return parent::setOption($name, $value);
    }

    /**
     * Check and normalize pickle protocol number
     *
     * @param  int $number
     * @return int
     * @throws Zend_Serializer_Exception
     */
    protected function _checkProtocolNumber($number)
    {
        $int = (int) $number;
        if ($int < 0 || $int > 3) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Invalid or unknown protocol version "'.$number.'"');
        }
        return $int;
    }

    /* serialize */

    /**
     * Serialize PHP to PythonPickle format
     *
     * @param  mixed $value
     * @param  array $opts
     * @return string
     */
    public function serialize($value, array $opts = array())
    {
        $opts = $opts + $this->_options;

        $this->_protocol = $this->_checkProtocolNumber($opts['protocol']);
        $this->_binary   = $this->_protocol != 0;

        // clear process vars before serializing
        $this->_memo   = array();
        $this->_pickle = '';

        // write
        if ($this->_protocol >= 2) {
            $this->_writeProto($this->_protocol);
        }
        $this->_write($value);
        $this->_writeStop();

        // clear process vars after serializing
        $this->_memo = array();
        $pickle = $this->_pickle;
        $this->_pickle = '';

        return $pickle;
    }

    /**
     * Write a value
     *
     * @param  mixed $value
     * @return void
     * @throws Zend_Serializer_Exception on invalid or unrecognized value type
     */
    protected function _write($value)
    {
        if ($value === null) {
            $this->_writeNull();
        } elseif ($value === true) {
            $this->_writeTrue();
        } elseif ($value === false) {
            $this->_writeFalse();
        } elseif (is_int($value)) {
            $this->_writeInt($value);
        } elseif (is_float($value)) {
            $this->_writeFloat($value);
        } elseif (is_string($value)) {
            // TODO: write unicode / binary
            $this->_writeString($value);
        } elseif (is_array($value)) {
            if ($this->_isArrayAssoc($value)) {
                $this->_writeArrayDict($value);
            } else {
                $this->_writeArrayList($value);
            }
        } elseif (is_object($value)) {
            $this->_writeObject($value);
        } else {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception(
                'PHP-Type "'.gettype($value).'" isn\'t serializable with '.get_class($this)
            );
        }
    }

    /**
     * Write pickle protocol
     *
     * @param  int $protocol
     * @return void
     */
    protected function _writeProto($protocol)
    {
        $this->_pickle .= self::OP_PROTO . $protocol;
    }

    /**
     * Write a get
     *
     * @param  int $id Id of memo
     * @return void
     */
    protected function _writeGet($id)
    {
        if ($this->_binary) {
            if ($id <= 0xff) {
                // BINGET + chr(i)
                $this->_pickle .= self::OP_BINGET . chr($id);
            } else {
                // LONG_BINGET + pack("<i", i)
                $idBin = pack('l', $id);
                if (self::$_isLittleEndian === false) {
                    $idBin = strrev($bin);
                }
                $this->_pickle .= self::OP_LONG_BINGET . $idBin;
            }
        } else {
            $this->_pickle .= self::OP_GET . $id . "\r\n";
        }
    }

    /**
     * Write a put
     *
     * @param  int $id Id of memo
     * @return void
     */
    protected function _writePut($id)
    {
        if ($this->_binary) {
            if ($id <= 0xff) {
                // BINPUT + chr(i)
                $this->_pickle .= self::OP_BINPUT . chr($id);
            } else {
                // LONG_BINPUT + pack("<i", i)
                $idBin = pack('l', $id);
                if (self::$_isLittleEndian === false) {
                    $idBin = strrev($bin);
                }
                $this->_pickle .= self::OP_LONG_BINPUT . $idBin;
            }
        } else {
            $this->_pickle .= self::OP_PUT . $id . "\r\n";
        }
    }

    /**
     * Write a null as None
     *
     * @return void
     */
    protected function _writeNull()
    {
        $this->_pickle .= self::OP_NONE;
    }

    /**
     * Write a boolean true
     *
     * @return void
     */
    protected function _writeTrue()
    {
        if ($this->_protocol >= 2) {
            $this->_pickle .= self::OP_NEWTRUE;
        } else {
            $this->_pickle .= self::OP_INT . "01\r\n";
        }
    }

    /**
     * Write a boolean false
     *
     * @return void
     */
    protected function _writeFalse()
    {
        if ($this->_protocol >= 2) {
            $this->_pickle .= self::OP_NEWFALSE;
        } else {
            $this->_pickle .= self::OP_INT . "00\r\n";
        }
    }

    /**
     * Write an integer value
     *
     * @param  int $value
     * @return void
     */
    protected function _writeInt($value)
    {
        if ($this->_binary) {
            if ($value >= 0) {
                if ($value <= 0xff) {
                    // self.write(BININT1 + chr(obj))
                    $this->_pickle .= self::OP_BININT1 . chr($value);
                } elseif ($value <= 0xffff) {
                    // self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
                    $this->_pickle .= self::OP_BININT2 . pack('v', $value);
                }
                return;
            }

            // Next check for 4-byte signed ints:
            $highBits = $value >> 31;  // note that Python shift sign-extends
            if ($highBits == 0 || $highBits == -1) {
                // All high bits are copies of bit 2**31, so the value
                // fits in a 4-byte signed int.
                // self.write(BININT + pack("<i", obj))
                $bin = pack('l', $value);
                if (self::$_isLittleEndian === false) {
                    $bin = strrev($bin);
                }
                $this->_pickle .= self::OP_BININT . $bin;
                return;
            }
        }

        $this->_pickle .= self::OP_INT . $value . "\r\n";
    }

    /**
     * Write a float value
     *
     * @param  float $value
     * @return void
     */
    protected function _writeFloat($value)
    {
        if ($this->_binary) {
            // self.write(BINFLOAT + pack('>d', obj))
            $bin = pack('d', $value);
            if (self::$_isLittleEndian === true) {
                $bin = strrev($bin);
            }
            $this->_pickle .= self::OP_BINFLOAT . $bin;
        } else {
            $this->_pickle .= self::OP_FLOAT . $value . "\r\n";
        }
    }

    /**
     * Write a string value
     *
     * @param  string $value
     * @return void
     */
    protected function _writeString($value)
    {
        if ( ($id=$this->_searchMomo($value)) !== false ) {
            $this->_writeGet($id);
            return;
        }

        if ($this->_binary) {
            $n = strlen($value);
            if ($n <= 0xff) {
                // self.write(SHORT_BINSTRING + chr(n) + obj)
                $this->_pickle .= self::OP_SHORT_BINSTRING . chr($n) . $value;
            } else {
                // self.write(BINSTRING + pack("<i", n) + obj)
                $binLen = pack('l', $n);
                if (self::$_isLittleEndian === false) {
                    $binLen = strrev($binLen);
                }
                $this->_pickle .= self::OP_BINSTRING . $binLen . $value;
            }
        } else {
            $this->_pickle .= self::OP_STRING . $this->_quoteString($value) . "\r\n";
        }

        $this->_momorize($value);
    }

    /**
     * Write an associative array value as dictionary
     *
     * @param  array $value
     * @return void
     */
    protected function _writeArrayDict(array $value)
    {
        if (($id=$this->_searchMomo($value)) !== false) {
            $this->_writeGet($id);;
            return;
        }

        $this->_pickle .= self::OP_MARK . self::OP_DICT;
        $this->_momorize($value);

        foreach ($value as $k => $v) {
            $this->_pickle .= $this->_write($k)
                            . $this->_write($v)
                            . self::OP_SETITEM;
        }
    }

    /**
     * Write a simple array value as list
     *
     * @param  array $value
     * @return void
     */
    protected function _writeArrayList(array $value)
    {
        if (($id = $this->_searchMomo($value)) !== false) {
            $this->_writeGet($id);
            return;
        }

        $this->_pickle .= self::OP_MARK . self::OP_LIST;
        $this->_momorize($value);

        foreach ($value as $k => $v) {
            $this->_pickle .= $this->_write($v) . self::OP_APPEND;
        }
    }

    /**
     * Write an object as an dictionary
     *
     * @param  object $value
     * @return void
     */
    protected function _writeObject($value)
    {
        // can't serialize php objects to python objects yet
        $this->_writeArrayDict(get_object_vars($value));
    }

    /**
     * Write stop
     *
     * @return void
     */
    protected function _writeStop()
    {
        $this->_pickle .= self::OP_STOP;
    }

    /* serialize helper */

    /**
     * Add a value to the memo and write the id
     *
     * @param mixed $value
     * @return void
     */
    protected function _momorize($value)
    {
        $id = count($this->_memo);
        $this->_memo[$id] = $value;
        $this->_writePut($id);
    }

    /**
     * Search a value in the meno and return  the id
     *
     * @param  mixed $value
     * @return int|false The id or false
     */
    protected function _searchMomo($value)
    {
        return array_search($value, $this->_memo, true);
    }

    /**
     * Is an array associative?
     *
     * @param  array $value
     * @return boolean
     */
    protected function _isArrayAssoc(array $value)
    {
        return array_diff_key($value, array_keys(array_keys($value)));
    }

    /**
     * Quote/Escape a string
     *
     * @param  string $str
     * @return string quoted string
     */
    protected function _quoteString($str)
    {
        $quoteArr = self::$_quoteString;

        if (($cntSingleQuote = substr_count($str, "'"))
            && ($cntDoubleQuote = substr_count($str, '"'))
            && ($cntSingleQuote < $cntDoubleQuote)
        ) {
            $quoteArr['"'] = '\\"';
            $enclosure     = '"';
        } else {
            $quoteArr["'"] = "\\'";
            $enclosure     = "'";
        }

        return $enclosure . strtr($str, $quoteArr) . $enclosure;
    }

    /* unserialize */

    /**
     * Unserialize from Python Pickle format to PHP
     *
     * @param  string $pickle
     * @param  array $opts
     * @return mixed
     * @throws Zend_Serializer_Exception on invalid Pickle string
     */
    public function unserialize($pickle, array $opts = array())
    {
        // init process vars
        $this->_pos       = 0;
        $this->_pickle    = $pickle;
        $this->_pickleLen = strlen($this->_pickle);
        $this->_memo      = array();
        $this->_stack     = array();

        // read pickle string
        while (($op=$this->_read(1)) !== self::OP_STOP) {
            $this->_load($op);
        }

        if (!count($this->_stack)) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('No data found');
        }

        $ret = array_pop($this->_stack);

        // clear process vars
        $this->_pos       = 0;
        $this->_pickle    = '';
        $this->_pickleLen = 0;
        $this->_memo      = array();
        $this->_stack     = array();

        return $ret;
    }

    /**
     * Load a pickle opcode
     *
     * @param  string $op
     * @return void
     * @throws Zend_Serializer_Exception on invalid opcode
     */
    protected function _load($op)
    {
        switch ($op) {
            case self::OP_PUT:
                $this->_loadPut();
                break;
            case self::OP_BINPUT:
                $this->_loadBinPut();
                break;
            case self::OP_LONG_BINPUT:
                $this->_loadLongBinPut();
                break;
            case self::OP_GET:
                $this->_loadGet();
                break;
            case self::OP_BINGET:
                $this->_loadBinGet();
                break;
            case self::OP_LONG_BINGET:
                $this->_loadLongBinGet();
                break;
            case self::OP_NONE:
                $this->_loadNone();
                break;
            case self::OP_NEWTRUE:
                $this->_loadNewTrue();
                break;
            case self::OP_NEWFALSE:
                $this->_loadNewFalse();
                break;
            case self::OP_INT:
                $this->_loadInt();
                break;
            case self::OP_BININT:
                $this->_loadBinInt();
                break;
            case self::OP_BININT1:
                $this->_loadBinInt1();
                break;
            case self::OP_BININT2:
                $this->_loadBinInt2();
                break;
            case self::OP_LONG:
                $this->_loadLong();
                break;
            case self::OP_LONG1:
                $this->_loadLong1();
                break;
            case self::OP_LONG4:
                $this->_loadLong4();
                break;
            case self::OP_FLOAT:
                $this->_loadFloat();
                break;
            case self::OP_BINFLOAT:
                $this->_loadBinFloat();
                break;
            case self::OP_STRING:
                $this->_loadString();
                break;
            case self::OP_BINSTRING:
                $this->_loadBinString();
                break;
            case self::OP_SHORT_BINSTRING:
                $this->_loadShortBinString();
                break;
            case self::OP_BINBYTES:
                $this->_loadBinBytes();
                break;
            case self::OP_SHORT_BINBYTES:
                $this->_loadShortBinBytes();
                break;
            case self::OP_UNICODE:
                $this->_loadUnicode();
                break;
            case self::OP_BINUNICODE:
                $this->_loadBinUnicode();
                break;
            case self::OP_MARK:
                $this->_loadMark();
                break;
            case self::OP_LIST:
                $this->_loadList();
                break;
            case self::OP_EMPTY_LIST:
                $this->_loadEmptyList();
                break;
            case self::OP_APPEND:
                $this->_loadAppend();
                break;
            case self::OP_APPENDS:
                $this->_loadAppends();
                break;
            case self::OP_DICT:
                $this->_loadDict();
                break;
            case self::OP_EMPTY_DICT:
                $this->_loadEmptyDict();
                break;
            case self::OP_SETITEM:
                $this->_loadSetItem();
                break;
            case self::OP_SETITEMS:
                $this->_loadSetItems();
                break;
            case self::OP_TUPLE:
                $this->_loadTuple();
                break;
            case self::OP_TUPLE1:
                $this->_loadTuple1();
                break;
            case self::OP_TUPLE2:
                $this->_loadTuple2();
                break;
            case self::OP_TUPLE3:
                $this->_loadTuple3();
                break;
            case self::OP_PROTO:
                $this->_loadProto();
                break;
            default:
                require_once 'Zend/Serializer/Exception.php';
                throw new Zend_Serializer_Exception('Invalid or unknown opcode "'.$op.'"');
        }
    }

    /**
     * Load a PUT opcode
     *
     * @return void
     * @throws Zend_Serializer_Exception on missing stack
     */
    protected function _loadPut()
    {
        $id = (int)$this->_readline();

        $lastStack = count($this->_stack)-1;
        if (!isset($this->_stack[$lastStack])) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('No stack exist');
        }
        $this->_memo[$id] = & $this->_stack[$lastStack];
    }

    /**
     * Load a binary PUT
     *
     * @return void
     * @throws Zend_Serializer_Exception on missing stack
     */
    protected function _loadBinPut()
    {
        $id = ord($this->_read(1));

        $lastStack = count($this->_stack)-1;
        if (!isset($this->_stack[$lastStack])) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('No stack exist');
        }
        $this->_memo[$id] = & $this->_stack[$lastStack];
    }

    /**
     * Load a long binary PUT
     *
     * @return void
     * @throws Zend_Serializer_Exception on missing stack
     */
    protected function _loadLongBinPut()
    {
        $bin = $this->_read(4);
        if (self::$_isLittleEndian === false) {
            $bin = strrev($bin);
        }
        list(, $id) = unpack('l', $bin);

        $lastStack = count($this->_stack)-1;
        if (!isset($this->_stack[$lastStack])) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('No stack exist');
        }
        $this->_memo[$id] = & $this->_stack[$lastStack];
    }

    /**
     * Load a GET operation
     *
     * @return void
     * @throws Zend_Serializer_Exception on missing GET identifier
     */
    protected function _loadGet()
    {
        $id = (int)$this->_readline();

        if (!array_key_exists($id, $this->_memo)) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Get id "' . $id . '" not found in momo');
        }
        $this->_stack[] = & $this->_memo[$id];
    }

    /**
     * Load a binary GET operation
     *
     * @return void
     * @throws Zend_Serializer_Exception on missing GET identifier
     */
    protected function _loadBinGet()
    {
        $id = ord($this->_read(1));

        if (!array_key_exists($id, $this->_memo)) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Get id "' . $id . '" not found in momo');
        }
        $this->_stack[] = & $this->_memo[$id];
    }

    /**
     * Load a long binary GET operation
     *
     * @return void
     * @throws Zend_Serializer_Exception on missing GET identifier
     */
    protected function _loadLongBinGet()
    {
        $bin = $this->_read(4);
        if (self::$_isLittleEndian === false) {
            $bin = strrev($bin);
        }
        list(, $id) = unpack('l', $bin);

        if (!array_key_exists($id, $this->_memo)) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Get id "' . $id . '" not found in momo');
        }
        $this->_stack[] = & $this->_memo[$id];
    }

    /**
     * Load a NONE operator
     *
     * @return void
     */
    protected function _loadNone()
    {
        $this->_stack[] = null;
    }

    /**
     * Load a boolean TRUE operator
     *
     * @return void
     */
    protected function _loadNewTrue()
    {
        $this->_stack[] = true;
    }

    /**
     * Load a boolean FALSE operator
     *
     * @return void
     */
    protected function _loadNewFalse()
    {
        $this->_stack[] = false;
    }

    /**
     * Load an integer operator
     *
     * @return void
     */
    protected function _loadInt()
    {
        $line = $this->_readline();
        if ($line === '01') {
            $this->_stack[] = true;
        } elseif ($line === '00') {
            $this->_stack[] = false;
        } else {
            $this->_stack[] = (int)$line;
        }
    }

    /**
     * Load a binary integer operator
     *
     * @return void
     */
    protected function _loadBinInt()
    {
        $bin = $this->_read(4);
        if (self::$_isLittleEndian === false) {
            $bin = strrev($bin);
        }
        list(, $int)    = unpack('l', $bin);
        $this->_stack[] = $int;
    }

    /**
     * Load the first byte of a binary integer
     *
     * @return void
     */
    protected function _loadBinInt1()
    {
        $this->_stack[] = ord($this->_read(1));
    }

    /**
     * Load the second byte of a binary integer
     *
     * @return void
     */
    protected function _loadBinInt2()
    {
        $bin = $this->_read(2);
        list(, $int)    = unpack('v', $bin);
        $this->_stack[] = $int;
    }

    /**
     * Load a long (float) operator
     *
     * @return void
     */
    protected function _loadLong()
    {
        $data = rtrim($this->_readline(), 'L');
        if ($data === '') {
            $this->_stack[] = 0;
        } else {
            $this->_stack[] = $data;
        }
    }

    /**
     * Load a one byte long integer
     *
     * @return void
     */
    protected function _loadLong1()
    {
        $n    = ord($this->_read(1));
        $data = $this->_read($n);
        $this->_stack[] = $this->_decodeBinLong($data);
    }

    /**
     * Load a 4 byte long integer
     *
     * @return void
     */
    protected function _loadLong4()
    {
        $nBin = $this->_read(4);
        if (self::$_isLittleEndian === false) {
            $nBin = strrev($$nBin);
        }
        list(, $n) = unpack('l', $nBin);
        $data = $this->_read($n);

        $this->_stack[] = $this->_decodeBinLong($data);
    }

    /**
     * Load a float value
     *
     * @return void
     */
    protected function _loadFloat()
    {
        $float = (float)$this->_readline();
        $this->_stack[] = $float;
    }

    /**
     * Load a binary float value
     *
     * @return void
     */
    protected function _loadBinFloat()
    {
        $bin = $this->_read(8);
        if (self::$_isLittleEndian === true) {
            $bin = strrev($bin);
        }
        list(, $float)  = unpack('d', $bin);
        $this->_stack[] = $float;
    }

    /**
     * Load a string
     *
     * @return void
     */
    protected function _loadString()
    {
        $this->_stack[] = $this->_unquoteString((string)$this->_readline());
    }

    /**
     * Load a binary string
     *
     * @return void
     */
    protected function _loadBinString()
    {
        $bin = $this->_read(4);
        if (!self::$_isLittleEndian) {
            $bin = strrev($bin);
        }
        list(, $len)    = unpack('l', $bin);
        $this->_stack[] = (string)$this->_read($len);
    }

    /**
     * Load a short binary string
     *
     * @return void
     */
    protected function _loadShortBinString()
    {
        $len            = ord($this->_read(1));
        $this->_stack[] = (string)$this->_read($len);
    }

    /**
     * Load arbitrary binary bytes
     *
     * @return void
     */
    protected function _loadBinBytes()
    {
        // read byte length
        $nBin = $this->_read(4);
        if (self::$_isLittleEndian === false) {
            $nBin = strrev($$nBin);
        }
        list(, $n)      = unpack('l', $nBin);
        $this->_stack[] = $this->_read($n);
    }

    /**
     * Load a single binary byte
     *
     * @return void
     */
    protected function _loadShortBinBytes()
    {
        $n              = ord($this->_read(1));
        $this->_stack[] = $this->_read($n);
    }

    /**
     * Load a unicode string
     *
     * @return void
     */
    protected function _loadUnicode()
    {
        $data    = $this->_readline();
        $pattern = '/\\\\u([a-fA-F0-9]{4})/u'; // \uXXXX
        $data    = preg_replace_callback($pattern, array($this, '_convertMatchingUnicodeSequence2Utf8'), $data);

        if (self::$_isPhp6) {
            $data = unicode_decode($data, 'UTF-8');
        }

        $this->_stack[] = $data;
    }

    /**
     * Convert a unicode sequence to UTF-8
     *
     * @param  array $match
     * @return string
     */
    protected function _convertMatchingUnicodeSequence2Utf8(array $match)
    {
        return $this->_hex2Utf8($match[1]);
    }

    /**
     * Convert a hex string to a UTF-8 string
     *
     * @param  string $sequence
     * @return string
     * @throws Zend_Serializer_Exception on unmatched unicode sequence
     */
    protected function _hex2Utf8($hex)
    {
        $uniCode = hexdec($hex);

        if ($uniCode < 0x80) { // 1Byte
            $utf8Char = chr($uniCode);

        } elseif ($uniCode < 0x800) { // 2Byte
            $utf8Char = chr(0xC0 | $uniCode >> 6)
                      . chr(0x80 | $uniCode & 0x3F);

        } elseif ($uniCode < 0x10000) { // 3Byte
            $utf8Char = chr(0xE0 | $uniCode >> 12)
                      . chr(0x80 | $uniCode >> 6 & 0x3F)
                      . chr(0x80 | $uniCode & 0x3F);

        } elseif ($uniCode < 0x110000) { // 4Byte
            $utf8Char  = chr(0xF0 | $uniCode >> 18)
                       . chr(0x80 | $uniCode >> 12 & 0x3F)
                       . chr(0x80 | $uniCode >> 6 & 0x3F)
                       . chr(0x80 | $uniCode & 0x3F);
        } else {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Unsupported unicode character found "' . dechex($uniCode) . '"');
        }

        return $utf8Char;
    }

    /**
     * Load binary unicode sequence
     *
     * @return void
     */
    protected function _loadBinUnicode()
    {
        // read byte length
        $n = $this->_read(4);
        if (self::$_isLittleEndian === false) {
            $n = strrev($n);
        }
        list(, $n) = unpack('l', $n);
        $data      = $this->_read($n);

        if (self::$_isPhp6) {
            $data = unicode_decode($data, 'UTF-8');
        }

        $this->_stack[] = $data;
    }

    /**
     * Load a marker sequence
     *
     * @return void
     */
    protected function _loadMark()
    {
        $this->_stack[] = $this->_marker;
    }

    /**
     * Load an array (list)
     *
     * @return void
     */
    protected function _loadList()
    {
        $k = $this->_lastMarker();
        $this->_stack[$k] = array();

        // remove all elements after marker
        $max = count($this->_stack);
        for ($i = $k+1, $max; $i < $max; $i++) {
            unset($this->_stack[$i]);
        }
    }

    /**
     * Load an append (to list) sequence
     *
     * @return void
     */
    protected function _loadAppend()
    {
        $value  =  array_pop($this->_stack);
        $list   =& $this->_stack[count($this->_stack)-1];
        $list[] =  $value;
    }

    /**
     * Load an empty list sequence
     *
     * @return void
     */
    protected function _loadEmptyList()
    {
        $this->_stack[] = array();
    }

    /**
     * Load multiple append (to list) sequences at once
     *
     * @return void
     */
    protected function _loadAppends()
    {
        $k    =  $this->_lastMarker();
        $list =& $this->_stack[$k - 1];
        $max  =  count($this->_stack);
        for ($i = $k + 1; $i < $max; $i++) {
            $list[] = $this->_stack[$i];
            unset($this->_stack[$i]);
        }
        unset($this->_stack[$k]);
    }

    /**
     * Load an associative array (Python dictionary)
     *
     * @return void
     */
    protected function _loadDict()
    {
        $k = $this->_lastMarker();
        $this->_stack[$k] = array();

        // remove all elements after marker
        $max = count($this->_stack);
        for($i = $k + 1; $i < $max; $i++) {
            unset($this->_stack[$i]);
        }
    }

    /**
     * Load an item from a set
     *
     * @return void
     */
    protected function _loadSetItem()
    {
        $value =  array_pop($this->_stack);
        $key   =  array_pop($this->_stack);
        $dict  =& $this->_stack[count($this->_stack) - 1];
        $dict[$key] = $value;
    }

    /**
     * Load an empty dictionary
     *
     * @return void
     */
    protected function _loadEmptyDict()
    {
        $this->_stack[] = array();
    }

    /**
     * Load set items
     *
     * @return void
     */
    protected function _loadSetItems()
    {
        $k    =  $this->_lastMarker();
        $dict =& $this->_stack[$k - 1];
        $max  =  count($this->_stack);
        for ($i = $k + 1; $i < $max; $i += 2) {
            $key        = $this->_stack[$i];
            $value      = $this->_stack[$i + 1];
            $dict[$key] = $value;
            unset($this->_stack[$i], $this->_stack[$i+1]);
        }
        unset($this->_stack[$k]);
    }

    /**
     * Load a tuple
     *
     * @return void
     */
    protected function _loadTuple()
    {
        $k                =  $this->_lastMarker();
        $this->_stack[$k] =  array();
        $tuple            =& $this->_stack[$k];
        $max              =  count($this->_stack);
        for($i = $k + 1; $i < $max; $i++) {
            $tuple[] = $this->_stack[$i];
            unset($this->_stack[$i]);
        }
    }

    /**
     * Load single item tuple
     *
     * @return void
     */
    protected function _loadTuple1()
    {
        $value1 = array_pop($this->_stack);
        $this->_stack[] = array($value1);
    }

    /**
     * Load two item tuple
     *
     * @return void
     */
    protected function _loadTuple2()
    {
        $value2 = array_pop($this->_stack);
        $value1 = array_pop($this->_stack);
        $this->_stack[] = array($value1, $value2);
    }

    /**
     * Load three item tuple
     *
     * @return void
     */
    protected function _loadTuple3() {
        $value3 = array_pop($this->_stack);
        $value2 = array_pop($this->_stack);
        $value1 = array_pop($this->_stack);
        $this->_stack[] = array($value1, $value2, $value3);
    }

    /**
     * Load a proto value
     *
     * @return void
     * @throws Zend_Serializer_Exception if Pickle version does not support this feature
     */
    protected function _loadProto()
    {
        $proto = ord($this->_read(1));
        if ($proto < 2 || $proto > 3) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Invalid protocol version detected');
        }
        $this->_protocol = $proto;
    }

    /* unserialize helper */

    /**
     * Read a segment of the pickle
     *
     * @param  mixed $len
     * @return string
     * @throws Zend_Serializer_Exception if position matches end of data
     */
    protected function _read($len)
    {
        if (($this->_pos + $len) > $this->_pickleLen) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('End of data');
        }

        $this->_pos+= $len;
        return substr($this->_pickle, ($this->_pos - $len), $len);
    }

    /**
     * Read a line of the pickle at once
     *
     * @return string
     * @throws Zend_Serializer_Exception if no EOL character found
     */
    protected function _readline()
    {
        $eolLen = 2;
        $eolPos = strpos($this->_pickle, "\r\n", $this->_pos);
        if ($eolPos === false) {
            $eolPos = strpos($this->_pickle, "\n", $this->_pos);
            $eolLen = 1;
        }

        if ($eolPos === false) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('No new line found');
        }
        $ret        = substr($this->_pickle, $this->_pos, $eolPos-$this->_pos);
        $this->_pos = $eolPos + $eolLen;

        return $ret;
    }

    /**
     * Unquote/Unescape a quoted string
     *
     * @param  string $str quoted string
     * @return string unquoted string
     */
    protected function _unquoteString($str)
    {
        $quoteArr = array_flip(self::$_quoteString);

        if ($str[0] == '"') {
            $quoteArr['\\"'] = '"';
        } else {
            $quoteArr["\\'"] = "'";
        }

        return strtr(substr(trim($str), 1, -1), $quoteArr);
    }

    /**
     * Return last marker position in stack
     *
     * @return int
     */
    protected function _lastMarker()
    {
        for ($k = count($this->_stack)-1; $k >= 0; $k -= 1) {
            if ($this->_stack[$k] === $this->_marker) {
                break;
            }
        }
        return $k;
    }

    /**
     * Decode a binary long sequence
     *
     * @param  string $data
     * @return int|float|string
     */
    protected function _decodeBinLong($data)
    {
        $nbytes = strlen($data);

        if ($nbytes == 0) {
            return 0;
        }

        $long = 0;

        if ($nbytes > 7) {
            if (!extension_loaded('bcmath')) {
                return INF;
            }

            for ($i=0; $i<$nbytes; $i++) {
                $long = bcadd($long, bcmul(ord($data[$i]), bcpow(256, $i, 0)));
            }
            if (0x80 <= ord($data[$nbytes-1])) {
                $long = bcsub($long, bcpow(2, $nbytes * 8));
            }

        } else {
            for ($i=0; $i<$nbytes; $i++) {
                $long+= ord($data[$i]) * pow(256, $i);
            }
            if (0x80 <= ord($data[$nbytes-1])) {
                $long-= pow(2, $nbytes * 8);
                // $long-= 1 << ($nbytes * 8);
            }
        }

        return $long;
    }
}


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

/** @see Zend_Serializer_Adapter_AdapterAbstract */
require_once 'Zend/Serializer/Adapter/AdapterAbstract.php';

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

/** @see Zend_Amf_Parse_Amf3_Serializer */
require_once 'Zend/Amf/Parse/Amf3/Serializer.php';

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

/** @see Zend_Amf_Parse_Amf3_Deserializer */
require_once 'Zend/Amf/Parse/Amf3/Deserializer.php';

/**
 * @category   Zend
 * @package    Zend_Serializer
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Serializer_Adapter_Amf3 extends Zend_Serializer_Adapter_AdapterAbstract
{
    /**
     * Serialize a PHP value to AMF3 format
     *
     * @param  mixed $value
     * @param  array $opts
     * @return string
     * @throws Zend_Serializer_Exception
     */
    public function serialize($value, array $opts = array())
    {
        try  {
            $stream     = new Zend_Amf_Parse_OutputStream();
            $serializer = new Zend_Amf_Parse_Amf3_Serializer($stream);
            $serializer->writeTypeMarker($value);
            return $stream->getStream();
        } catch (Exception $e) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Serialization failed by previous error', 0, $e);
        }
    }

    /**
     * Deserialize an AMF3 value to PHP
     *
     * @param  mixed $value
     * @param  array $opts
     * @return string
     * @throws Zend_Serializer_Exception
     */
    public function unserialize($value, array $opts = array())
    {
        try {
            $stream       = new Zend_Amf_Parse_InputStream($value);
            $deserializer = new Zend_Amf_Parse_Amf3_Deserializer($stream);
            return $deserializer->readTypeMarker();
        } catch (Exception $e) {
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception('Unserialization failed by previous error', 0, $e);
        }
    }
}


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

/** @see Zend_Serializer_Adapter_AdapterAbstract */
require_once 'Zend/Serializer/Adapter/AdapterAbstract.php';

/**
 * @category   Zend
 * @package    Zend_Serializer
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Serializer_Adapter_PhpSerialize extends Zend_Serializer_Adapter_AdapterAbstract
{
    /**
     *  @var null|string Serialized boolean false value
     */
    private static $_serializedFalse = null;

    /**
     * Constructor
     *
     * @param  array|Zend_Config $opts
     * @return void
     */
    public function __construct($opts = array())
    {
        parent::__construct($opts);

        if (self::$_serializedFalse === null) {
            self::$_serializedFalse = serialize(false);
        }
    }

    /**
     * Serialize using serialize()
     *
     * @param  mixed $value
     * @param  array $opts
     * @return string
     * @throws Zend_Serializer_Exception On serialize error
     */
    public function serialize($value, array $opts = array())
    {
        $ret = serialize($value);
        if ($ret === false) {
            $lastErr = error_get_last();
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception($lastErr['message']);
        }
        return $ret;
    }

    /**
     * Unserialize
     *
     * @todo   Allow integration with unserialize_callback_func
     * @param  string $serialized
     * @param  array $opts
     * @return mixed
     * @throws Zend_Serializer_Exception on unserialize error
     */
    public function unserialize($serialized, array $opts = array())
    {
        // TODO: @see php.ini directive "unserialize_callback_func"
        $ret = @unserialize($serialized);
        if ($ret === false && $serialized !== self::$_serializedFalse) {
            $lastErr = error_get_last();
            require_once 'Zend/Serializer/Exception.php';
            throw new Zend_Serializer_Exception($lastErr['message']);
        }
        return $ret;
    }
}


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

/**
 * @category   Zend
 * @package    Zend_Serializer
 * @subpackage Adapter
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Zend_Serializer_Adapter_AdapterInterface
{
    /**
     * Constructor
     *
     * @param  array|Zend_Config $opts Serializer options
     * @return void
     */
    public function __construct($opts = array());

    /**
     * Set serializer options
     *
     * @param  array|Zend_Config $opts Serializer options
     * @return Zend_Serializer_Adapter_AdapterInterface
     */
    public function setOptions($opts);

    /**
     * Set a serializer option
     *
     * @param  string $name Option name
     * @param  mixed $value Option value
     * @return Zend_Serializer_Adapter_AdapterInterface
     */
    public function setOption($name, $value);

    /**
     * Get serializer options
     *
     * @return array
     */
    public function getOptions();

    /**
     * Get a serializer option
     *
     * @param  string $name
     * @return mixed
     * @throws Zend_Serializer_Exception
     */
    public function getOption($name);

    /**
     * Generates a storable representation of a value.
     *
     * @param  mixed $value Data to serialize
     * @param  array $options Serialize options
     * @return string
     * @throws Zend_Serializer_Exception
     */
    public function serialize($value, array $options = array());

    /**
     * Creates a PHP value from a stored representation.
     *
     * @param  string $serialized Serialized string
     * @param  array $options Unserialize options
     * @return mixed
     * @throws Zend_Serializer_Exception
     */
    public function unserialize($serialized, array $options = array());
}