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_Markup
 * @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: Markup.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * @see Zend_Loader_PluginLoader
 */
require_once 'Zend/Loader/PluginLoader.php';

/**
 * @category   Zend
 * @package    Zend_Markup
 * @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_Markup
{
    const CALLBACK = 'callback';
    const REPLACE  = 'replace';

    /**
     * The parser loader
     *
     * @var Zend_Loader_PluginLoader
     */
    protected static $_parserLoader;

    /**
     * The renderer loader
     *
     * @var Zend_Loader_PluginLoader
     */
    protected static $_rendererLoader;

    /**
     * Disable instantiation of Zend_Markup
     */
    private function __construct() { }

    /**
     * Get the parser loader
     *
     * @return Zend_Loader_PluginLoader
     */
    public static function getParserLoader()
    {
        if (!(self::$_parserLoader instanceof Zend_Loader_PluginLoader)) {
            self::$_parserLoader = new Zend_Loader_PluginLoader(array(
                'Zend_Markup_Parser' => 'Zend/Markup/Parser/',
            ));
        }

        return self::$_parserLoader;
    }

    /**
     * Get the renderer loader
     *
     * @return Zend_Loader_PluginLoader
     */
    public static function getRendererLoader()
    {
        if (!(self::$_rendererLoader instanceof Zend_Loader_PluginLoader)) {
            self::$_rendererLoader = new Zend_Loader_PluginLoader(array(
                'Zend_Markup_Renderer' => 'Zend/Markup/Renderer/',
            ));
        }

        return self::$_rendererLoader;
    }

    /**
     * Add a parser path
     *
     * @param  string $prefix
     * @param  string $path
     * @return Zend_Loader_PluginLoader
     */
    public static function addParserPath($prefix, $path)
    {
        return self::getParserLoader()->addPrefixPath($prefix, $path);
    }

    /**
     * Add a renderer path
     *
     * @param  string $prefix
     * @param  string $path
     * @return Zend_Loader_PluginLoader
     */
    public static function addRendererPath($prefix, $path)
    {
        return self::getRendererLoader()->addPrefixPath($prefix, $path);
    }

    /**
     * Factory pattern
     *
     * @param  string $parser
     * @param  string $renderer
     * @param  array $options
     * @return Zend_Markup_Renderer_RendererAbstract
     */
    public static function factory($parser, $renderer = 'Html', array $options = array())
    {
        $parserClass   = self::getParserLoader()->load($parser);
        $rendererClass = self::getRendererLoader()->load($renderer);

        $parser            = new $parserClass();
        $options['parser'] = $parser;
        $renderer          = new $rendererClass($options);

        return $renderer;
    }
}

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_InfoCard
 * @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: InfoCard.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * Zend_InfoCard_Xml_EncryptedData
 */
require_once 'Zend/InfoCard/Xml/EncryptedData.php';

/**
 * Zend_InfoCard_Xml_Assertion
 */
require_once 'Zend/InfoCard/Xml/Assertion.php';

/**
 * Zend_InfoCard_Cipher
 */
require_once 'Zend/InfoCard/Cipher.php';

/**
 * Zend_InfoCard_Xml_Security
 */
require_once 'Zend/InfoCard/Xml/Security.php';

/**
 * Zend_InfoCard_Adapter_Interface
 */
require_once 'Zend/InfoCard/Adapter/Interface.php';

/**
 * Zend_InfoCard_Claims
 */
require_once 'Zend/InfoCard/Claims.php';

/**
 * @category   Zend
 * @package    Zend_InfoCard
 * @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_InfoCard
{
    /**
     * URI for XML Digital Signature SHA1 Digests
     */
    const DIGEST_SHA1        = 'http://www.w3.org/2000/09/xmldsig#sha1';

    /**
     * An array of certificate pair files and optional passwords for them to search
     * when trying to determine which certificate was used to encrypt the transient key
     *
     * @var Array
     */
    protected $_keyPairs;

    /**
     * The instance to use to decrypt public-key encrypted data
     *
     * @var Zend_InfoCard_Cipher_Pki_Interface
     */
    protected $_pkiCipherObj;

    /**
     * The instance to use to decrypt symmetric encrypted data
     *
     * @var Zend_InfoCard_Cipher_Symmetric_Interface
     */
    protected $_symCipherObj;

    /**
     * The InfoCard Adapter to use for callbacks into the application using the component
     * such as when storing assertions, etc.
     *
     * @var Zend_InfoCard_Adapter_Interface
     */
    protected $_adapter;

    /**
     * InfoCard Constructor
     *
     * @throws Zend_InfoCard_Exception
     */
    public function __construct()
    {
        $this->_keyPairs = array();

        if(!extension_loaded('mcrypt')) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Use of the Zend_InfoCard component requires the mcrypt extension to be enabled in PHP");
        }

        if(!extension_loaded('openssl')) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Use of the Zend_InfoCard component requires the openssl extension to be enabled in PHP");
        }
    }

    /**
     * Sets the adapter uesd for callbacks into the application using the component, used
     * when doing things such as storing / retrieving assertions, etc.
     *
     * @param Zend_InfoCard_Adapter_Interface $a The Adapter instance
     * @return Zend_InfoCard The instnace
     */
    public function setAdapter(Zend_InfoCard_Adapter_Interface $a)
    {
        $this->_adapter = $a;
        return $this;
    }

    /**
     * Retrieves the adapter used for callbacks into the application using the component.
     * If no adapter was set then an instance of Zend_InfoCard_Adapter_Default is used
     *
     * @return Zend_InfoCard_Adapter_Interface The Adapter instance
     */
    public function getAdapter()
    {
        if($this->_adapter === null) {
            require_once 'Zend/InfoCard/Adapter/Default.php';
            $this->setAdapter(new Zend_InfoCard_Adapter_Default());
        }

        return $this->_adapter;
    }

    /**
     * Gets the Public Key Cipher object used in this instance
     *
     * @return Zend_InfoCard_Cipher_Pki_Interface
     */
    public function getPkiCipherObject()
    {
        return $this->_pkiCipherObj;
    }

    /**
     * Sets the Public Key Cipher Object used in this instance
     *
     * @param Zend_InfoCard_Cipher_Pki_Interface $cipherObj
     * @return Zend_InfoCard
     */
    public function setPkiCipherObject(Zend_InfoCard_Cipher_Pki_Interface $cipherObj)
    {
        $this->_pkiCipherObj = $cipherObj;
        return $this;
    }

    /**
     * Get the Symmetric Cipher Object used in this instance
     *
     * @return Zend_InfoCard_Cipher_Symmetric_Interface
     */
    public function getSymCipherObject()
    {
        return $this->_symCipherObj;
    }

    /**
     * Sets the Symmetric Cipher Object used in this instance
     *
     * @param Zend_InfoCard_Cipher_Symmetric_Interface $cipherObj
     * @return Zend_InfoCard
     */
    public function setSymCipherObject($cipherObj)
    {
        $this->_symCipherObj = $cipherObj;
        return $this;
    }

    /**
     * Remove a Certificate Pair by Key ID from the search list
     *
     * @throws Zend_InfoCard_Exception
     * @param string $key_id The Certificate Key ID returned from adding the certificate pair
     * @return Zend_InfoCard
     */
    public function removeCertificatePair($key_id)
    {

        if(!key_exists($key_id, $this->_keyPairs)) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Attempted to remove unknown key id: $key_id");
        }

        unset($this->_keyPairs[$key_id]);
        return $this;
    }

    /**
     * Add a Certificate Pair to the list of certificates searched by the component
     *
     * @throws Zend_InfoCard_Exception
     * @param string $private_key_file The path to the private key file for the pair
     * @param string $public_key_file The path to the certificate / public key for the pair
     * @param string $type (optional) The URI for the type of key pair this is (default RSA with OAEP padding)
     * @param string $password (optional) The password for the private key file if necessary
     * @return string A key ID representing this key pair in the component
     */
    public function addCertificatePair($private_key_file, $public_key_file, $type = Zend_InfoCard_Cipher::ENC_RSA_OAEP_MGF1P, $password = null)
    {
        if(!file_exists($private_key_file) ||
           !file_exists($public_key_file)) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Could not locate the public and private certificate pair files: $private_key_file, $public_key_file");
        }

        if(!is_readable($private_key_file) ||
           !is_readable($public_key_file)) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Could not read the public and private certificate pair files (check permissions): $private_key_file, $public_key_file");
        }

        $key_id = md5($private_key_file.$public_key_file);

        if(key_exists($key_id, $this->_keyPairs)) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Attempted to add previously existing certificate pair: $private_key_file, $public_key_file");
        }

        switch($type) {
            case Zend_InfoCard_Cipher::ENC_RSA:
            case Zend_InfoCard_Cipher::ENC_RSA_OAEP_MGF1P:
                $this->_keyPairs[$key_id] = array('private' => $private_key_file,
                                'public'      => $public_key_file,
                                'type_uri'    => $type);

                if($password !== null) {
                    $this->_keyPairs[$key_id]['password'] = $password;
                } else {
                    $this->_keyPairs[$key_id]['password'] = null;
                }

                return $key_id;
                break;
            default:
                require_once 'Zend/InfoCard/Exception.php';
                throw new Zend_InfoCard_Exception("Invalid Certificate Pair Type specified: $type");
        }
    }

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

        require_once 'Zend/InfoCard/Exception.php';
        throw new Zend_InfoCard_Exception("Invalid Certificate Pair ID provided: $key_id");
    }

    /**
     * Retrieve the digest of a given public key / certificate using the provided digest
     * method
     *
     * @throws Zend_InfoCard_Exception
     * @param string $key_id The certificate key id in the component
     * @param string $digestMethod The URI of the digest method to use (default SHA1)
     * @return string The digest value in binary format
     */
    protected function _getPublicKeyDigest($key_id, $digestMethod = self::DIGEST_SHA1)
    {
        $certificatePair = $this->getCertificatePair($key_id);

        $temp = file($certificatePair['public']);
        unset($temp[count($temp)-1]);
        unset($temp[0]);
        $certificateData = base64_decode(implode("\n", $temp));

        switch($digestMethod) {
            case self::DIGEST_SHA1:
                $digest_retval = sha1($certificateData, true);
                break;
            default:
                require_once 'Zend/InfoCard/Exception.php';
                throw new Zend_InfoCard_Exception("Invalid Digest Type Provided: $digestMethod");
        }

        return $digest_retval;
    }

    /**
     * Find a certificate pair based on a digest of its public key / certificate file
     *
     * @param string $digest The digest value of the public key wanted in binary form
     * @param string $digestMethod The URI of the digest method used to calculate the digest
     * @return mixed The Key ID of the matching certificate pair or false if not found
     */
    protected function _findCertifiatePairByDigest($digest, $digestMethod = self::DIGEST_SHA1)
    {

        foreach($this->_keyPairs as $key_id => $certificate_data) {

            $cert_digest = $this->_getPublicKeyDigest($key_id, $digestMethod);

            if($cert_digest == $digest) {
                return $key_id;
            }
        }

        return false;
    }

    /**
     * Extracts the Signed Token from an EncryptedData block
     *
     * @throws Zend_InfoCard_Exception
     * @param string $strXmlToken The EncryptedData XML block
     * @return string The XML of the Signed Token inside of the EncryptedData block
     */
    protected function _extractSignedToken($strXmlToken)
    {
        $encryptedData = Zend_InfoCard_Xml_EncryptedData::getInstance($strXmlToken);

        // Determine the Encryption Method used to encrypt the token

        switch($encryptedData->getEncryptionMethod()) {
            case Zend_InfoCard_Cipher::ENC_AES128CBC:
            case Zend_InfoCard_Cipher::ENC_AES256CBC:
                break;
            default:
                require_once 'Zend/InfoCard/Exception.php';
                throw new Zend_InfoCard_Exception("Unknown Encryption Method used in the secure token");
        }

        // Figure out the Key we are using to decrypt the token

        $keyinfo = $encryptedData->getKeyInfo();

        if(!($keyinfo instanceof Zend_InfoCard_Xml_KeyInfo_XmlDSig)) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Expected a XML digital signature KeyInfo, but was not found");
        }

        $encryptedKey = $keyinfo->getEncryptedKey();

        switch($encryptedKey->getEncryptionMethod()) {
            case Zend_InfoCard_Cipher::ENC_RSA:
            case Zend_InfoCard_Cipher::ENC_RSA_OAEP_MGF1P:
                break;
            default:
                require_once 'Zend/InfoCard/Exception.php';
                throw new Zend_InfoCard_Exception("Unknown Key Encryption Method used in secure token");
        }

        $securityTokenRef = $encryptedKey->getKeyInfo()->getSecurityTokenReference();

        $key_id = $this->_findCertifiatePairByDigest($securityTokenRef->getKeyReference());

        if(!$key_id) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Unable to find key pair used to encrypt symmetric InfoCard Key");
        }

        $certificate_pair = $this->getCertificatePair($key_id);

        // Santity Check

        if($certificate_pair['type_uri'] != $encryptedKey->getEncryptionMethod()) {
            require_once 'Zend/InfoCard/Exception.php';
            throw new Zend_InfoCard_Exception("Certificate Pair which matches digest is not of same algorithm type as document, check addCertificate()");
        }

        $PKcipher = Zend_InfoCard_Cipher::getInstanceByURI($encryptedKey->getEncryptionMethod());

        $base64DecodeSupportsStrictParam = version_compare(PHP_VERSION, '5.2.0', '>=');

        if ($base64DecodeSupportsStrictParam) {
            $keyCipherValueBase64Decoded = base64_decode($encryptedKey->getCipherValue(), true);
        } else {
            $keyCipherValueBase64Decoded = base64_decode($encryptedKey->getCipherValue());
        }

        $symmetricKey = $PKcipher->decrypt(
            $keyCipherValueBase64Decoded,
            file_get_contents($certificate_pair['private']),
            $certificate_pair['password']
            );

        $symCipher = Zend_InfoCard_Cipher::getInstanceByURI($encryptedData->getEncryptionMethod());

        if ($base64DecodeSupportsStrictParam) {
            $dataCipherValueBase64Decoded = base64_decode($encryptedData->getCipherValue(), true);
        } else {
            $dataCipherValueBase64Decoded = base64_decode($encryptedData->getCipherValue());
        }

        $signedToken = $symCipher->decrypt($dataCipherValueBase64Decoded, $symmetricKey);

        return $signedToken;
    }

    /**
     * Process an input Infomation Card EncryptedData block sent from the client,
     * validate it, and return the claims contained within it on success or an error message on error
     *
     * @param string $strXmlToken The XML token sent to the server from the client
     * @return Zend_Infocard_Claims The Claims object containing the claims, or any errors which occurred
     */
    public function process($strXmlToken)
    {

        $retval = new Zend_InfoCard_Claims();

        require_once 'Zend/InfoCard/Exception.php';
        try {
            $signedAssertionsXml = $this->_extractSignedToken($strXmlToken);
        } catch(Zend_InfoCard_Exception $e) {
            $retval->setError('Failed to extract assertion document');
            $retval->setCode(Zend_InfoCard_Claims::RESULT_PROCESSING_FAILURE);
            return $retval;
        }

        try {
            $assertions = Zend_InfoCard_Xml_Assertion::getInstance($signedAssertionsXml);
        } catch(Zend_InfoCard_Exception $e) {
            $retval->setError('Failure processing assertion document');
            $retval->setCode(Zend_InfoCard_Claims::RESULT_PROCESSING_FAILURE);
            return $retval;
        }

        if(!($assertions instanceof Zend_InfoCard_Xml_Assertion_Interface)) {
            throw new Zend_InfoCard_Exception("Invalid Assertion Object returned");
        }

        if(!($reference_id = Zend_InfoCard_Xml_Security::validateXMLSignature($assertions->asXML()))) {
            $retval->setError("Failure Validating the Signature of the assertion document");
            $retval->setCode(Zend_InfoCard_Claims::RESULT_VALIDATION_FAILURE);
            return $retval;
        }

        // The reference id should be locally scoped as far as I know
        if($reference_id[0] == '#') {
            $reference_id = substr($reference_id, 1);
        } else {
            $retval->setError("Reference of document signature does not reference the local document");
            $retval->setCode(Zend_InfoCard_Claims::RESULT_VALIDATION_FAILURE);
            return $retval;
        }

        // Make sure the signature is in reference to the same document as the assertions
        if($reference_id != $assertions->getAssertionID()) {
            $retval->setError("Reference of document signature does not reference the local document");
            $retval->setCode(Zend_InfoCard_Claims::RESULT_VALIDATION_FAILURE);
        }

        // Validate we haven't seen this before and the conditions are acceptable
        $conditions = $this->getAdapter()->retrieveAssertion($assertions->getAssertionURI(), $assertions->getAssertionID());

        if($conditions === false) {
            $conditions = $assertions->getConditions();
        }

        if(is_array($condition_error = $assertions->validateConditions($conditions))) {
            $retval->setError("Conditions of assertion document are not met: {$condition_error[1]} ({$condition_error[0]})");
            $retval->setCode(Zend_InfoCard_Claims::RESULT_VALIDATION_FAILURE);
        }

        $attributes = $assertions->getAttributes();

        $retval->setClaims($attributes);

        if($retval->getCode() == 0) {
            $retval->setCode(Zend_InfoCard_Claims::RESULT_SUCCESS);
        }

        return $retval;
    }
}


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_Mime
 * @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: Mime.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * Support class for MultiPart Mime Messages
 *
 * @category   Zend
 * @package    Zend_Mime
 * @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_Mime
{
    const TYPE_OCTETSTREAM = 'application/octet-stream';
    const TYPE_TEXT = 'text/plain';
    const TYPE_HTML = 'text/html';
    const ENCODING_7BIT = '7bit';
    const ENCODING_8BIT = '8bit';
    const ENCODING_QUOTEDPRINTABLE = 'quoted-printable';
    const ENCODING_BASE64 = 'base64';
    const DISPOSITION_ATTACHMENT = 'attachment';
    const DISPOSITION_INLINE = 'inline';
    const LINELENGTH = 72;
    const LINEEND = "\n";
    const MULTIPART_ALTERNATIVE = 'multipart/alternative';
    const MULTIPART_MIXED = 'multipart/mixed';
    const MULTIPART_RELATED = 'multipart/related';

    protected $_boundary;
    protected static $makeUnique = 0;

    // lookup-Tables for QuotedPrintable
    public static $qpKeys = array(
        "\x00","\x01","\x02","\x03","\x04","\x05","\x06","\x07",
        "\x08","\x09","\x0A","\x0B","\x0C","\x0D","\x0E","\x0F",
        "\x10","\x11","\x12","\x13","\x14","\x15","\x16","\x17",
        "\x18","\x19","\x1A","\x1B","\x1C","\x1D","\x1E","\x1F",
        "\x7F","\x80","\x81","\x82","\x83","\x84","\x85","\x86",
        "\x87","\x88","\x89","\x8A","\x8B","\x8C","\x8D","\x8E",
        "\x8F","\x90","\x91","\x92","\x93","\x94","\x95","\x96",
        "\x97","\x98","\x99","\x9A","\x9B","\x9C","\x9D","\x9E",
        "\x9F","\xA0","\xA1","\xA2","\xA3","\xA4","\xA5","\xA6",
        "\xA7","\xA8","\xA9","\xAA","\xAB","\xAC","\xAD","\xAE",
        "\xAF","\xB0","\xB1","\xB2","\xB3","\xB4","\xB5","\xB6",
        "\xB7","\xB8","\xB9","\xBA","\xBB","\xBC","\xBD","\xBE",
        "\xBF","\xC0","\xC1","\xC2","\xC3","\xC4","\xC5","\xC6",
        "\xC7","\xC8","\xC9","\xCA","\xCB","\xCC","\xCD","\xCE",
        "\xCF","\xD0","\xD1","\xD2","\xD3","\xD4","\xD5","\xD6",
        "\xD7","\xD8","\xD9","\xDA","\xDB","\xDC","\xDD","\xDE",
        "\xDF","\xE0","\xE1","\xE2","\xE3","\xE4","\xE5","\xE6",
        "\xE7","\xE8","\xE9","\xEA","\xEB","\xEC","\xED","\xEE",
        "\xEF","\xF0","\xF1","\xF2","\xF3","\xF4","\xF5","\xF6",
        "\xF7","\xF8","\xF9","\xFA","\xFB","\xFC","\xFD","\xFE",
        "\xFF"
        );

    public static $qpReplaceValues = array(
        "=00","=01","=02","=03","=04","=05","=06","=07",
        "=08","=09","=0A","=0B","=0C","=0D","=0E","=0F",
        "=10","=11","=12","=13","=14","=15","=16","=17",
        "=18","=19","=1A","=1B","=1C","=1D","=1E","=1F",
        "=7F","=80","=81","=82","=83","=84","=85","=86",
        "=87","=88","=89","=8A","=8B","=8C","=8D","=8E",
        "=8F","=90","=91","=92","=93","=94","=95","=96",
        "=97","=98","=99","=9A","=9B","=9C","=9D","=9E",
        "=9F","=A0","=A1","=A2","=A3","=A4","=A5","=A6",
        "=A7","=A8","=A9","=AA","=AB","=AC","=AD","=AE",
        "=AF","=B0","=B1","=B2","=B3","=B4","=B5","=B6",
        "=B7","=B8","=B9","=BA","=BB","=BC","=BD","=BE",
        "=BF","=C0","=C1","=C2","=C3","=C4","=C5","=C6",
        "=C7","=C8","=C9","=CA","=CB","=CC","=CD","=CE",
        "=CF","=D0","=D1","=D2","=D3","=D4","=D5","=D6",
        "=D7","=D8","=D9","=DA","=DB","=DC","=DD","=DE",
        "=DF","=E0","=E1","=E2","=E3","=E4","=E5","=E6",
        "=E7","=E8","=E9","=EA","=EB","=EC","=ED","=EE",
        "=EF","=F0","=F1","=F2","=F3","=F4","=F5","=F6",
        "=F7","=F8","=F9","=FA","=FB","=FC","=FD","=FE",
        "=FF"
        );

    public static $qpKeysString =
         "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF";

    /**
     * Check if the given string is "printable"
     *
     * Checks that a string contains no unprintable characters. If this returns
     * false, encode the string for secure delivery.
     *
     * @param string $str
     * @return boolean
     */
    public static function isPrintable($str)
    {
        return (strcspn($str, self::$qpKeysString) == strlen($str));
    }

    /**
     * Encode a given string with the QUOTED_PRINTABLE mechanism and wrap the lines.
     *
     * @param string $str
     * @param int $lineLength Defaults to {@link LINELENGTH}
     * @param int $lineEnd Defaults to {@link LINEEND}
     * @return string
     */
    public static function encodeQuotedPrintable($str,
        $lineLength = self::LINELENGTH,
        $lineEnd = self::LINEEND)
    {
        $out = '';
        $str = self::_encodeQuotedPrintable($str);

        // Split encoded text into separate lines
        while ($str) {
            $ptr = strlen($str);
            if ($ptr > $lineLength) {
                $ptr = $lineLength;
            }

            // Ensure we are not splitting across an encoded character
            $pos = strrpos(substr($str, 0, $ptr), '=');
            if ($pos !== false && $pos >= $ptr - 2) {
                $ptr = $pos;
            }

            // Check if there is a space at the end of the line and rewind
            if ($ptr > 0 && $str[$ptr - 1] == ' ') {
                --$ptr;
            }

            // Add string and continue
            $out .= substr($str, 0, $ptr) . '=' . $lineEnd;
            $str = substr($str, $ptr);
        }

        $out = rtrim($out, $lineEnd);
        $out = rtrim($out, '=');
        return $out;
    }

    /**
     * Converts a string into quoted printable format.
     *
     * @param  string $str
     * @return string
     */
    private static function _encodeQuotedPrintable($str)
    {
        $str = str_replace('=', '=3D', $str);
        $str = str_replace(self::$qpKeys, self::$qpReplaceValues, $str);
        $str = rtrim($str);
        return $str;
    }

    /**
     * Encode a given string with the QUOTED_PRINTABLE mechanism for Mail Headers.
     *
     * Mail headers depend on an extended quoted printable algorithm otherwise
     * a range of bugs can occur.
     *
     * @param string $str
     * @param string $charset
     * @param int $lineLength Defaults to {@link LINELENGTH}
     * @param int $lineEnd Defaults to {@link LINEEND}
     * @return string
     */
    public static function encodeQuotedPrintableHeader($str, $charset,
        $lineLength = self::LINELENGTH,
        $lineEnd = self::LINEEND)
    {
        // Reduce line-length by the length of the required delimiter, charsets and encoding
        $prefix = sprintf('=?%s?Q?', $charset);
        $lineLength = $lineLength-strlen($prefix)-3;

        $str = self::_encodeQuotedPrintable($str);

        // Mail-Header required chars have to be encoded also:
        $str = str_replace(array('?', ' ', '_'), array('=3F', '=20', '=5F'), $str);

        // initialize first line, we need it anyways
        $lines = array(0 => "");

        // Split encoded text into separate lines
        $tmp = "";
        while(strlen($str) > 0) {
            $currentLine = max(count($lines)-1, 0);
            $token       = self::getNextQuotedPrintableToken($str);
            $str         = substr($str, strlen($token));

            $tmp .= $token;
            if($token == '=20') {
                // only if we have a single char token or space, we can append the
                // tempstring it to the current line or start a new line if necessary.
                if(strlen($lines[$currentLine].$tmp) > $lineLength) {
                    $lines[$currentLine+1] = $tmp;
                } else {
                    $lines[$currentLine] .= $tmp;
                }
                $tmp = "";
            }
            // don't forget to append the rest to the last line
            if(strlen($str) == 0) {
                $lines[$currentLine] .= $tmp;
            }
        }

        // assemble the lines together by pre- and appending delimiters, charset, encoding.
        for($i = 0; $i < count($lines); $i++) {
            $lines[$i] = " ".$prefix.$lines[$i]."?=";
        }
        $str = trim(implode($lineEnd, $lines));
        return $str;
    }

    /**
     * Retrieves the first token from a quoted printable string.
     *
     * @param  string $str
     * @return string
     */
    private static function getNextQuotedPrintableToken($str)
    {
        if(substr($str, 0, 1) == "=") {
            $token = substr($str, 0, 3);
        } else {
            $token = substr($str, 0, 1);
        }
        return $token;
    }

    /**
     * Encode a given string in mail header compatible base64 encoding.
     *
     * @param string $str
     * @param string $charset
     * @param int $lineLength Defaults to {@link LINELENGTH}
     * @param int $lineEnd Defaults to {@link LINEEND}
     * @return string
     */
    public static function encodeBase64Header($str,
        $charset,
        $lineLength = self::LINELENGTH,
        $lineEnd = self::LINEEND)
    {
        $prefix = '=?' . $charset . '?B?';
        $suffix = '?=';
        $remainingLength = $lineLength - strlen($prefix) - strlen($suffix);

        $encodedValue = self::encodeBase64($str, $remainingLength, $lineEnd);
        $encodedValue = str_replace($lineEnd, $suffix . $lineEnd . ' ' . $prefix, $encodedValue);
        $encodedValue = $prefix . $encodedValue . $suffix;
        return $encodedValue;
    }

    /**
     * Encode a given string in base64 encoding and break lines
     * according to the maximum linelength.
     *
     * @param string $str
     * @param int $lineLength Defaults to {@link LINELENGTH}
     * @param int $lineEnd Defaults to {@link LINEEND}
     * @return string
     */
    public static function encodeBase64($str,
        $lineLength = self::LINELENGTH,
        $lineEnd = self::LINEEND)
    {
        return rtrim(chunk_split(base64_encode($str), $lineLength, $lineEnd));
    }

    /**
     * Constructor
     *
     * @param null|string $boundary
     * @access public
     * @return void
     */
    public function __construct($boundary = null)
    {
        // This string needs to be somewhat unique
        if ($boundary === null) {
            $this->_boundary = '=_' . md5(microtime(1) . self::$makeUnique++);
        } else {
            $this->_boundary = $boundary;
        }
    }

    /**
     * Encode the given string with the given encoding.
     *
     * @param string $str
     * @param string $encoding
     * @param string $EOL EOL string; defaults to {@link Zend_Mime::LINEEND}
     * @return string
     */
    public static function encode($str, $encoding, $EOL = self::LINEEND)
    {
        switch ($encoding) {
            case self::ENCODING_BASE64:
                return self::encodeBase64($str, self::LINELENGTH, $EOL);

            case self::ENCODING_QUOTEDPRINTABLE:
                return self::encodeQuotedPrintable($str, self::LINELENGTH, $EOL);

            default:
                /**
                 * @todo 7Bit and 8Bit is currently handled the same way.
                 */
                return $str;
        }
    }

    /**
     * Return a MIME boundary
     *
     * @access public
     * @return string
     */
    public function boundary()
    {
        return $this->_boundary;
    }

    /**
     * Return a MIME boundary line
     *
     * @param mixed $EOL Defaults to {@link LINEEND}
     * @access public
     * @return string
     */
    public function boundaryLine($EOL = self::LINEEND)
    {
        return $EOL . '--' . $this->_boundary . $EOL;
    }

    /**
     * Return MIME ending
     *
     * @access public
     * @return string
     */
    public function mimeEnd($EOL = self::LINEEND)
    {
        return $EOL . '--' . $this->_boundary . '--' . $EOL;
    }
}


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_Session
 * @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: Session.php 24196 2011-07-05 15:58:11Z matthew $
 * @since      Preview Release 0.2
 */

/**
 * @see Zend_Session_Abstract
 */
require_once 'Zend/Session/Abstract.php';

/**
 * @see Zend_Session_Namespace
 */
require_once 'Zend/Session/Namespace.php';

/**
 * @see Zend_Session_SaveHandler_Interface
 */
require_once 'Zend/Session/SaveHandler/Interface.php';

/**
 * Zend_Session
 *
 * @category   Zend
 * @package    Zend_Session
 * @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_Session extends Zend_Session_Abstract
{
    /**
     * Whether or not Zend_Session is being used with unit tests
     *
     * @internal
     * @var bool
     */
    public static $_unitTestEnabled = false;

    /**
     * $_throwStartupException
     *
     * @var bool|bitset This could also be a combiniation of error codes to catch
     */
    protected static $_throwStartupExceptions = true;

    /**
     * Check whether or not the session was started
     *
     * @var bool
     */
    private static $_sessionStarted = false;

    /**
     * Whether or not the session id has been regenerated this request.
     *
     * Id regeneration state
     * <0 - regenerate requested when session is started
     * 0  - do nothing
     * >0 - already called session_regenerate_id()
     *
     * @var int
     */
    private static $_regenerateIdState = 0;

    /**
     * Private list of php's ini values for ext/session
     * null values will default to the php.ini value, otherwise
     * the value below will overwrite the default ini value, unless
     * the user has set an option explicity with setOptions()
     *
     * @var array
     */
    private static $_defaultOptions = array(
        'save_path'                 => null,
        'name'                      => null, /* this should be set to a unique value for each application */
        'save_handler'              => null,
        //'auto_start'                => null, /* intentionally excluded (see manual) */
        'gc_probability'            => null,
        'gc_divisor'                => null,
        'gc_maxlifetime'            => null,
        'serialize_handler'         => null,
        'cookie_lifetime'           => null,
        'cookie_path'               => null,
        'cookie_domain'             => null,
        'cookie_secure'             => null,
        'cookie_httponly'           => null,
        'use_cookies'               => null,
        'use_only_cookies'          => 'on',
        'referer_check'             => null,
        'entropy_file'              => null,
        'entropy_length'            => null,
        'cache_limiter'             => null,
        'cache_expire'              => null,
        'use_trans_sid'             => null,
        'bug_compat_42'             => null,
        'bug_compat_warn'           => null,
        'hash_function'             => null,
        'hash_bits_per_character'   => null
    );

    /**
     * List of options pertaining to Zend_Session that can be set by developers
     * using Zend_Session::setOptions(). This list intentionally duplicates
     * the individual declaration of static "class" variables by the same names.
     *
     * @var array
     */
    private static $_localOptions = array(
        'strict'                => '_strict',
        'remember_me_seconds'   => '_rememberMeSeconds',
        'throw_startup_exceptions' => '_throwStartupExceptions'
    );

    /**
     * Whether or not write close has been performed.
     *
     * @var bool
     */
    private static $_writeClosed = false;

    /**
     * Whether or not session id cookie has been deleted
     *
     * @var bool
     */
    private static $_sessionCookieDeleted = false;

    /**
     * Whether or not session has been destroyed via session_destroy()
     *
     * @var bool
     */
    private static $_destroyed = false;

    /**
     * Whether or not session must be initiated before usage
     *
     * @var bool
     */
    private static $_strict = false;

    /**
     * Default number of seconds the session will be remembered for when asked to be remembered
     *
     * @var int
     */
    private static $_rememberMeSeconds = 1209600; // 2 weeks

    /**
     * Whether the default options listed in Zend_Session::$_localOptions have been set
     *
     * @var bool
     */
    private static $_defaultOptionsSet = false;

    /**
     * A reference to the set session save handler
     *
     * @var Zend_Session_SaveHandler_Interface
     */
    private static $_saveHandler = null;

    /**
     * Constructor overriding - make sure that a developer cannot instantiate
     */
    protected function __construct()
    {
    }

    /**
     * setOptions - set both the class specified
     *
     * @param  array $userOptions - pass-by-keyword style array of <option name, option value> pairs
     * @throws Zend_Session_Exception
     * @return void
     */
    public static function setOptions(array $userOptions = array())
    {
        // set default options on first run only (before applying user settings)
        if (!self::$_defaultOptionsSet) {
            foreach (self::$_defaultOptions as $defaultOptionName => $defaultOptionValue) {
                if (isset(self::$_defaultOptions[$defaultOptionName])) {
                    ini_set("session.$defaultOptionName", $defaultOptionValue);
                }
            }

            self::$_defaultOptionsSet = true;
        }

        // set the options the user has requested to set
        foreach ($userOptions as $userOptionName => $userOptionValue) {

            $userOptionName = strtolower($userOptionName);

            // set the ini based values
            if (array_key_exists($userOptionName, self::$_defaultOptions)) {
                ini_set("session.$userOptionName", $userOptionValue);
            }
            elseif (isset(self::$_localOptions[$userOptionName])) {
                self::${self::$_localOptions[$userOptionName]} = $userOptionValue;
            }
            else {
                /** @see Zend_Session_Exception */
                require_once 'Zend/Session/Exception.php';
                throw new Zend_Session_Exception("Unknown option: $userOptionName = $userOptionValue");
            }
        }
    }

    /**
     * getOptions()
     *
     * @param string $optionName OPTIONAL
     * @return array|string
     */
    public static function getOptions($optionName = null)
    {
        $options = array();
        foreach (ini_get_all('session') as $sysOptionName => $sysOptionValues) {
            $options[substr($sysOptionName, 8)] = $sysOptionValues['local_value'];
        }
        foreach (self::$_localOptions as $localOptionName => $localOptionMemberName) {
            $options[$localOptionName] = self::${$localOptionMemberName};
        }

        if ($optionName) {
            if (array_key_exists($optionName, $options)) {
                return $options[$optionName];
            }
            return null;
        }

        return $options;
    }

    /**
     * setSaveHandler() - Session Save Handler assignment
     *
     * @param Zend_Session_SaveHandler_Interface $interface
     * @return void
     */
    public static function setSaveHandler(Zend_Session_SaveHandler_Interface $saveHandler)
    {
        self::$_saveHandler = $saveHandler;

        if (self::$_unitTestEnabled) {
            return;
        }

        session_set_save_handler(
            array(&$saveHandler, 'open'),
            array(&$saveHandler, 'close'),
            array(&$saveHandler, 'read'),
            array(&$saveHandler, 'write'),
            array(&$saveHandler, 'destroy'),
            array(&$saveHandler, 'gc')
            );
    }

    /**
     * getSaveHandler() - Get the session Save Handler
     *
     * @return Zend_Session_SaveHandler_Interface
     */
    public static function getSaveHandler()
    {
        return self::$_saveHandler;
    }

    /**
     * regenerateId() - Regenerate the session id.  Best practice is to call this after
     * session is started.  If called prior to session starting, session id will be regenerated
     * at start time.
     *
     * @throws Zend_Session_Exception
     * @return void
     */
    public static function regenerateId()
    {
        if (!self::$_unitTestEnabled && headers_sent($filename, $linenum)) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception("You must call " . __CLASS__ . '::' . __FUNCTION__ .
                "() before any output has been sent to the browser; output started in {$filename}/{$linenum}");
        }

        if ( !self::$_sessionStarted ) {
            self::$_regenerateIdState = -1;
        } else {
            if (!self::$_unitTestEnabled) {
                session_regenerate_id(true);
            }
            self::$_regenerateIdState = 1;
        }
    }

    /**
     * rememberMe() - Write a persistent cookie that expires after a number of seconds in the future. If no number of
     * seconds is specified, then this defaults to self::$_rememberMeSeconds.  Due to clock errors on end users' systems,
     * large values are recommended to avoid undesirable expiration of session cookies.
     *
     * @param int $seconds OPTIONAL specifies TTL for cookie in seconds from present time
     * @return void
     */
    public static function rememberMe($seconds = null)
    {
        $seconds = (int) $seconds;
        $seconds = ($seconds > 0) ? $seconds : self::$_rememberMeSeconds;

        self::rememberUntil($seconds);
    }

    /**
     * forgetMe() - Write a volatile session cookie, removing any persistent cookie that may have existed. The session
     * would end upon, for example, termination of a web browser program.
     *
     * @return void
     */
    public static function forgetMe()
    {
        self::rememberUntil(0);
    }

    /**
     * rememberUntil() - This method does the work of changing the state of the session cookie and making
     * sure that it gets resent to the browser via regenerateId()
     *
     * @param int $seconds
     * @return void
     */
    public static function rememberUntil($seconds = 0)
    {
        if (self::$_unitTestEnabled) {
            self::regenerateId();
            return;
        }

        $cookieParams = session_get_cookie_params();

        session_set_cookie_params(
            $seconds,
            $cookieParams['path'],
            $cookieParams['domain'],
            $cookieParams['secure']
            );

        // normally "rememberMe()" represents a security context change, so should use new session id
        self::regenerateId();
    }

    /**
     * sessionExists() - whether or not a session exists for the current request
     *
     * @return bool
     */
    public static function sessionExists()
    {
        if (ini_get('session.use_cookies') == '1' && isset($_COOKIE[session_name()])) {
            return true;
        } elseif (!empty($_REQUEST[session_name()])) {
            return true;
        } elseif (self::$_unitTestEnabled) {
            return true;
        }

        return false;
    }

    /**
     * Whether or not session has been destroyed via session_destroy()
     *
     * @return bool
     */
    public static function isDestroyed()
    {
        return self::$_destroyed;
    }

    /**
     * start() - Start the session.
     *
     * @param bool|array $options  OPTIONAL Either user supplied options, or flag indicating if start initiated automatically
     * @throws Zend_Session_Exception
     * @return void
     */
    public static function start($options = false)
    {
        if (self::$_sessionStarted && self::$_destroyed) {
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('The session was explicitly destroyed during this request, attempting to re-start is not allowed.');
        }

        if (self::$_sessionStarted) {
            return; // already started
        }

        // make sure our default options (at the least) have been set
        if (!self::$_defaultOptionsSet) {
            self::setOptions(is_array($options) ? $options : array());
        }

        // In strict mode, do not allow auto-starting Zend_Session, such as via "new Zend_Session_Namespace()"
        if (self::$_strict && $options === true) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('You must explicitly start the session with Zend_Session::start() when session options are set to strict.');
        }

        $filename = $linenum = null;
        if (!self::$_unitTestEnabled && headers_sent($filename, $linenum)) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception("Session must be started before any output has been sent to the browser;"
               . " output started in {$filename}/{$linenum}");
        }

        // See http://www.php.net/manual/en/ref.session.php for explanation
        if (!self::$_unitTestEnabled && defined('SID')) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('session has already been started by session.auto-start or session_start()');
        }

        /**
         * Hack to throw exceptions on start instead of php errors
         * @see http://framework.zend.com/issues/browse/ZF-1325
         */

        $errorLevel = (is_int(self::$_throwStartupExceptions)) ? self::$_throwStartupExceptions : E_ALL;

        /** @see Zend_Session_Exception */
        if (!self::$_unitTestEnabled) {

            if (self::$_throwStartupExceptions) {
                require_once 'Zend/Session/Exception.php';
                set_error_handler(array('Zend_Session_Exception', 'handleSessionStartError'), $errorLevel);
            }

            $startedCleanly = session_start();

            if (self::$_throwStartupExceptions) {
                restore_error_handler();
            }

            if (!$startedCleanly || Zend_Session_Exception::$sessionStartError != null) {
                if (self::$_throwStartupExceptions) {
                    set_error_handler(array('Zend_Session_Exception', 'handleSilentWriteClose'), $errorLevel);
                }
                session_write_close();
                if (self::$_throwStartupExceptions) {
                    restore_error_handler();
                    throw new Zend_Session_Exception(__CLASS__ . '::' . __FUNCTION__ . '() - ' . Zend_Session_Exception::$sessionStartError);
                }
            }
        }

        parent::$_readable = true;
        parent::$_writable = true;
        self::$_sessionStarted = true;
        if (self::$_regenerateIdState === -1) {
            self::regenerateId();
        }

        // run validators if they exist
        if (isset($_SESSION['__ZF']['VALID'])) {
            self::_processValidators();
        }

        self::_processStartupMetadataGlobal();
    }

    /**
     * _processGlobalMetadata() - this method initizes the sessions GLOBAL
     * metadata, mostly global data expiration calculations.
     *
     * @return void
     */
    private static function _processStartupMetadataGlobal()
    {
        // process global metadata
        if (isset($_SESSION['__ZF'])) {

            // expire globally expired values
            foreach ($_SESSION['__ZF'] as $namespace => $namespace_metadata) {

                // Expire Namespace by Time (ENT)
                if (isset($namespace_metadata['ENT']) && ($namespace_metadata['ENT'] > 0) && (time() > $namespace_metadata['ENT']) ) {
                    unset($_SESSION[$namespace]);
                    unset($_SESSION['__ZF'][$namespace]);
                }

                // Expire Namespace by Global Hop (ENGH) if it wasnt expired above
                if (isset($_SESSION['__ZF'][$namespace]) && isset($namespace_metadata['ENGH']) && $namespace_metadata['ENGH'] >= 1) {

                    $_SESSION['__ZF'][$namespace]['ENGH']--;

                    if ($_SESSION['__ZF'][$namespace]['ENGH'] === 0) {
                        if (isset($_SESSION[$namespace])) {
                            parent::$_expiringData[$namespace] = $_SESSION[$namespace];
                            unset($_SESSION[$namespace]);
                        }
                        unset($_SESSION['__ZF'][$namespace]);
                    }
                }

                // Expire Namespace Variables by Time (ENVT)
                if (isset($namespace_metadata['ENVT'])) {
                    foreach ($namespace_metadata['ENVT'] as $variable => $time) {
                        if (time() > $time) {
                            unset($_SESSION[$namespace][$variable]);
                            unset($_SESSION['__ZF'][$namespace]['ENVT'][$variable]);
                        }
                    }
                    if (empty($_SESSION['__ZF'][$namespace]['ENVT'])) {
                        unset($_SESSION['__ZF'][$namespace]['ENVT']);
                    }
                }

                // Expire Namespace Variables by Global Hop (ENVGH)
                if (isset($namespace_metadata['ENVGH'])) {
                    foreach ($namespace_metadata['ENVGH'] as $variable => $hops) {
                        $_SESSION['__ZF'][$namespace]['ENVGH'][$variable]--;

                        if ($_SESSION['__ZF'][$namespace]['ENVGH'][$variable] === 0) {
                            if (isset($_SESSION[$namespace][$variable])) {
                                parent::$_expiringData[$namespace][$variable] = $_SESSION[$namespace][$variable];
                                unset($_SESSION[$namespace][$variable]);
                            }
                            unset($_SESSION['__ZF'][$namespace]['ENVGH'][$variable]);
                        }
                    }
                    if (empty($_SESSION['__ZF'][$namespace]['ENVGH'])) {
                        unset($_SESSION['__ZF'][$namespace]['ENVGH']);
                    }
                }

                if (isset($namespace) && empty($_SESSION['__ZF'][$namespace])) {
                    unset($_SESSION['__ZF'][$namespace]);
                }
            }
        }

        if (isset($_SESSION['__ZF']) && empty($_SESSION['__ZF'])) {
            unset($_SESSION['__ZF']);
        }
    }

    /**
     * isStarted() - convenience method to determine if the session is already started.
     *
     * @return bool
     */
    public static function isStarted()
    {
        return self::$_sessionStarted;
    }

    /**
     * isRegenerated() - convenience method to determine if session_regenerate_id()
     * has been called during this request by Zend_Session.
     *
     * @return bool
     */
    public static function isRegenerated()
    {
        return ( (self::$_regenerateIdState > 0) ? true : false );
    }

    /**
     * getId() - get the current session id
     *
     * @return string
     */
    public static function getId()
    {
        return session_id();
    }

    /**
     * setId() - set an id to a user specified id
     *
     * @throws Zend_Session_Exception
     * @param string $id
     * @return void
     */
    public static function setId($id)
    {
        if (!self::$_unitTestEnabled && defined('SID')) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('The session has already been started.  The session id must be set first.');
        }

        if (!self::$_unitTestEnabled && headers_sent($filename, $linenum)) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception("You must call ".__CLASS__.'::'.__FUNCTION__.
                "() before any output has been sent to the browser; output started in {$filename}/{$linenum}");
        }

        if (!is_string($id) || $id === '') {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception('You must provide a non-empty string as a session identifier.');
        }

        session_id($id);
    }

    /**
     * registerValidator() - register a validator that will attempt to validate this session for
     * every future request
     *
     * @param Zend_Session_Validator_Interface $validator
     * @return void
     */
    public static function registerValidator(Zend_Session_Validator_Interface $validator)
    {
        $validator->setup();
    }

    /**
     * stop() - Disable write access.  Optionally disable read (not implemented).
     *
     * @return void
     */
    public static function stop()
    {
        parent::$_writable = false;
    }

    /**
     * writeClose() - Shutdown the sesssion, close writing and detach $_SESSION from the back-end storage mechanism.
     * This will complete the internal data transformation on this request.
     *
     * @param bool $readonly - OPTIONAL remove write access (i.e. throw error if Zend_Session's attempt writes)
     * @return void
     */
    public static function writeClose($readonly = true)
    {
        if (self::$_unitTestEnabled) {
            return;
        }

        if (self::$_writeClosed) {
            return;
        }

        if ($readonly) {
            parent::$_writable = false;
        }

        session_write_close();
        self::$_writeClosed = true;
    }

    /**
     * destroy() - This is used to destroy session data, and optionally, the session cookie itself
     *
     * @param bool $remove_cookie - OPTIONAL remove session id cookie, defaults to true (remove cookie)
     * @param bool $readonly - OPTIONAL remove write access (i.e. throw error if Zend_Session's attempt writes)
     * @return void
     */
    public static function destroy($remove_cookie = true, $readonly = true)
    {
        if (self::$_unitTestEnabled) {
            return;
        }

        if (self::$_destroyed) {
            return;
        }

        if ($readonly) {
            parent::$_writable = false;
        }

        session_destroy();
        self::$_destroyed = true;

        if ($remove_cookie) {
            self::expireSessionCookie();
        }
    }

    /**
     * expireSessionCookie() - Sends an expired session id cookie, causing the client to delete the session cookie
     *
     * @return void
     */
    public static function expireSessionCookie()
    {
        if (self::$_unitTestEnabled) {
            return;
        }

        if (self::$_sessionCookieDeleted) {
            return;
        }

        self::$_sessionCookieDeleted = true;

        if (isset($_COOKIE[session_name()])) {
            $cookie_params = session_get_cookie_params();

            setcookie(
                session_name(),
                false,
                315554400, // strtotime('1980-01-01'),
                $cookie_params['path'],
                $cookie_params['domain'],
                $cookie_params['secure']
                );
        }
    }

    /**
     * _processValidator() - internal function that is called in the existence of VALID metadata
     *
     * @throws Zend_Session_Exception
     * @return void
     */
    private static function _processValidators()
    {
        foreach ($_SESSION['__ZF']['VALID'] as $validator_name => $valid_data) {
            if (!class_exists($validator_name)) {
                require_once 'Zend/Loader.php';
                Zend_Loader::loadClass($validator_name);
            }
            $validator = new $validator_name;
            if ($validator->validate() === false) {
                /** @see Zend_Session_Exception */
                require_once 'Zend/Session/Exception.php';
                throw new Zend_Session_Exception("This session is not valid according to {$validator_name}.");
            }
        }
    }

    /**
     * namespaceIsset() - check to see if a namespace is set
     *
     * @param string $namespace
     * @return bool
     */
    public static function namespaceIsset($namespace)
    {
        return parent::_namespaceIsset($namespace);
    }

    /**
     * namespaceUnset() - unset a namespace or a variable within a namespace
     *
     * @param string $namespace
     * @throws Zend_Session_Exception
     * @return void
     */
    public static function namespaceUnset($namespace)
    {
        parent::_namespaceUnset($namespace);
        Zend_Session_Namespace::resetSingleInstance($namespace);
    }

    /**
     * namespaceGet() - get all variables in a namespace
     * Deprecated: Use getIterator() in Zend_Session_Namespace.
     *
     * @param string $namespace
     * @return array
     */
    public static function namespaceGet($namespace)
    {
        return parent::_namespaceGetAll($namespace);
    }

    /**
     * getIterator() - return an iteratable object for use in foreach and the like,
     * this completes the IteratorAggregate interface
     *
     * @throws Zend_Session_Exception
     * @return ArrayObject
     */
    public static function getIterator()
    {
        if (parent::$_readable === false) {
            /** @see Zend_Session_Exception */
            require_once 'Zend/Session/Exception.php';
            throw new Zend_Session_Exception(parent::_THROW_NOT_READABLE_MSG);
        }

        $spaces  = array();
        if (isset($_SESSION)) {
            $spaces = array_keys($_SESSION);
            foreach($spaces as $key => $space) {
                if (!strncmp($space, '__', 2) || !is_array($_SESSION[$space])) {
                    unset($spaces[$key]);
                }
            }
        }

        return new ArrayObject(array_merge($spaces, array_keys(parent::$_expiringData)));
    }

    /**
     * isWritable() - returns a boolean indicating if namespaces can write (use setters)
     *
     * @return bool
     */
    public static function isWritable()
    {
        return parent::$_writable;
    }

    /**
     * isReadable() - returns a boolean indicating if namespaces can write (use setters)
     *
     * @return bool
     */
    public static function isReadable()
    {
        return parent::$_readable;
    }

}


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_Memory
 * @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: Memory.php 23775 2011-03-01 17:25:24Z ralph $
 */

/** Zend_Memory_Exception */
require_once 'Zend/Memory/Manager.php';

/** Zend_Memory_Value */
require_once 'Zend/Memory/Value.php';

/** Zend_Memory_Container */
require_once 'Zend/Memory/Container.php';

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

/**
 * @category   Zend
 * @package    Zend_Memory
 * @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_Memory
{
    /**
     * Factory
     *
     * @param string $backend backend name
     * @param array $backendOptions associative array of options for the corresponding backend constructor
     * @return Zend_Memory_Manager
     * @throws Zend_Memory_Exception
     */
    public static function factory($backend, $backendOptions = array())
    {
        if (strcasecmp($backend, 'none') == 0) {
            return new Zend_Memory_Manager();
        }

        // Look through available backendsand
        // (that allows to specify it in any case)
        $backendIsFound = false;
        foreach (Zend_Cache::$standardBackends as $zendCacheBackend) {
            if (strcasecmp($backend, $zendCacheBackend) == 0) {
                $backend = $zendCacheBackend;
                $backendIsFound = true;
                break;
            }
        }

        if (!$backendIsFound) {
            require_once 'Zend/Memory/Exception.php';
            throw new Zend_Memory_Exception("Incorrect backend ($backend)");
        }

        $backendClass = 'Zend_Cache_Backend_' . $backend;

        // For perfs reasons, we do not use the Zend_Loader::loadClass() method
        // (security controls are explicit)
        require_once str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php';

        $backendObject = new $backendClass($backendOptions);

        return new Zend_Memory_Manager($backendObject);
    }
}


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_Crypt
 * @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: Crypt.php 23953 2011-05-03 05:47:39Z ralph $
 */

/**
 * @category   Zend
 * @package    Zend_Crypt
 * @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_Crypt
{

    const TYPE_OPENSSL = 'openssl';
    const TYPE_HASH = 'hash';
    const TYPE_MHASH = 'mhash';

    protected static $_type = null;

    /**
     * @var array
     */
    protected static $_supportedAlgosOpenssl = array(
        'md2',
        'md4',
        'mdc2',
        'rmd160',
        'sha',
        'sha1',
        'sha224',
        'sha256',
        'sha384',
        'sha512'
    );

    /**
     * @var array
     */
    protected static $_supportedAlgosMhash = array(
        'adler32',
        'crc32',
        'crc32b',
        'gost',
        'haval128',
        'haval160',
        'haval192',
        'haval256',
        'md4',
        'md5',
        'ripemd160',
        'sha1',
        'sha256',
        'tiger',
        'tiger128',
        'tiger160'
    );

    /**
     * @param string $algorithm
     * @param string $data
     * @param bool $binaryOutput
     * @return unknown
     */
    public static function hash($algorithm, $data, $binaryOutput = false)
    {
        $algorithm = strtolower($algorithm);
        if (function_exists($algorithm)) {
            return $algorithm($data, $binaryOutput);
        }
        self::_detectHashSupport($algorithm);
        $supportedMethod = '_digest' . ucfirst(self::$_type);
        $result = self::$supportedMethod($algorithm, $data, $binaryOutput);
        return $result;
    }

    /**
     * @param string $algorithm
     * @throws Zend_Crypt_Exception
     */
    protected static function _detectHashSupport($algorithm)
    {
        if (function_exists('hash')) {
            self::$_type = self::TYPE_HASH;
            if (in_array($algorithm, hash_algos())) {
               return;
            }
        }
        if (function_exists('mhash')) {
            self::$_type = self::TYPE_MHASH;
            if (in_array($algorithm, self::$_supportedAlgosMhash)) {
               return;
            }
        }
        if (function_exists('openssl_digest')) {
            if ($algorithm == 'ripemd160') {
                $algorithm = 'rmd160';
            }
            self::$_type = self::TYPE_OPENSSL;
            if (in_array($algorithm, self::$_supportedAlgosOpenssl)) {
               return;
            }
        }
        /**
         * @see Zend_Crypt_Exception
         */
        require_once 'Zend/Crypt/Exception.php';
        throw new Zend_Crypt_Exception('\'' . $algorithm . '\' is not supported by any available extension or native function');
    }

    /**
     * @param string $algorithm
     * @param string $data
     * @param bool $binaryOutput
     * @return string
     */
    protected static function _digestHash($algorithm, $data, $binaryOutput)
    {
        return hash($algorithm, $data, $binaryOutput);
    }

    /**
     * @param string $algorithm
     * @param string $data
     * @param bool $binaryOutput
     * @return string
     */
    protected static function _digestMhash($algorithm, $data, $binaryOutput)
    {
        $constant = constant('MHASH_' . strtoupper($algorithm));
        $binary = mhash($constant, $data);
        if ($binaryOutput) {
            return $binary;
        }
        return bin2hex($binary);
    }

    /**
     * @param string $algorithm
     * @param string $data
     * @param bool $binaryOutput
     * @return string
     */
    protected static function _digestOpenssl($algorithm, $data, $binaryOutput)
    {
        if ($algorithm == 'ripemd160') {
            $algorithm = 'rmd160';
        }
        return openssl_digest($data, $algorithm, $binaryOutput);
    }

}


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_Uri
 * @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: Uri.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * Abstract class for all Zend_Uri handlers
 *
 * @category  Zend
 * @package   Zend_Uri
 * @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_Uri
{
    /**
     * Scheme of this URI (http, ftp, etc.)
     *
     * @var string
     */
    protected $_scheme = '';

    /**
     * Global configuration array
     *
     * @var array
     */
    static protected $_config = array(
        'allow_unwise' => false
    );

    /**
     * Return a string representation of this URI.
     *
     * @see    getUri()
     * @return string
     */
    public function __toString()
    {
        try {
            return $this->getUri();
        } catch (Exception $e) {
            trigger_error($e->getMessage(), E_USER_WARNING);
            return '';
        }
    }

    /**
     * Convenience function, checks that a $uri string is well-formed
     * by validating it but not returning an object.  Returns TRUE if
     * $uri is a well-formed URI, or FALSE otherwise.
     *
     * @param  string $uri The URI to check
     * @return boolean
     */
    public static function check($uri)
    {
        try {
            $uri = self::factory($uri);
        } catch (Exception $e) {
            return false;
        }

        return $uri->valid();
    }

    /**
     * Create a new Zend_Uri object for a URI.  If building a new URI, then $uri should contain
     * only the scheme (http, ftp, etc).  Otherwise, supply $uri with the complete URI.
     *
     * @param  string $uri       The URI form which a Zend_Uri instance is created
     * @param  string $className The name of the class to use in order to manipulate URI
     * @throws Zend_Uri_Exception When an empty string was supplied for the scheme
     * @throws Zend_Uri_Exception When an illegal scheme is supplied
     * @throws Zend_Uri_Exception When the scheme is not supported
     * @throws Zend_Uri_Exception When $className doesn't exist or doesn't implements Zend_Uri
     * @return Zend_Uri
     * @link   http://www.faqs.org/rfcs/rfc2396.html
     */
    public static function factory($uri = 'http', $className = null)
    {
        // Separate the scheme from the scheme-specific parts
        $uri            = explode(':', $uri, 2);
        $scheme         = strtolower($uri[0]);
        $schemeSpecific = isset($uri[1]) === true ? $uri[1] : '';

        if (strlen($scheme) === 0) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('An empty string was supplied for the scheme');
        }

        // Security check: $scheme is used to load a class file, so only alphanumerics are allowed.
        if (ctype_alnum($scheme) === false) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception('Illegal scheme supplied, only alphanumeric characters are permitted');
        }

        if ($className === null) {
            /**
             * Create a new Zend_Uri object for the $uri. If a subclass of Zend_Uri exists for the
             * scheme, return an instance of that class. Otherwise, a Zend_Uri_Exception is thrown.
             */
            switch ($scheme) {
                case 'http':
                    // Break intentionally omitted
                case 'https':
                    $className = 'Zend_Uri_Http';
                    break;

                case 'mailto':
                    // TODO
                default:
                    require_once 'Zend/Uri/Exception.php';
                    throw new Zend_Uri_Exception("Scheme \"$scheme\" is not supported");
                    break;
            }
        }

        require_once 'Zend/Loader.php';
        try {
            Zend_Loader::loadClass($className);
        } catch (Exception $e) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("\"$className\" not found");
        }

        $schemeHandler = new $className($scheme, $schemeSpecific);

        if (! $schemeHandler instanceof Zend_Uri) {
            require_once 'Zend/Uri/Exception.php';
            throw new Zend_Uri_Exception("\"$className\" is not an instance of Zend_Uri");
        }

        return $schemeHandler;
    }

    /**
     * Get the URI's scheme
     *
     * @return string|false Scheme or false if no scheme is set.
     */
    public function getScheme()
    {
        if (empty($this->_scheme) === false) {
            return $this->_scheme;
        } else {
            return false;
        }
    }

    /**
     * Set global configuration options
     *
     * @param Zend_Config|array $config
     */
    static public function setConfig($config)
    {
        if ($config instanceof Zend_Config) {
            $config = $config->toArray();
        } elseif (!is_array($config)) {
            throw new Zend_Uri_Exception("Config must be an array or an instance of Zend_Config.");
        }

        foreach ($config as $k => $v) {
            self::$_config[$k] = $v;
        }
    }

    /**
     * Zend_Uri and its subclasses cannot be instantiated directly.
     * Use Zend_Uri::factory() to return a new Zend_Uri object.
     *
     * @param string $scheme         The scheme of the URI
     * @param string $schemeSpecific The scheme-specific part of the URI
     */
    abstract protected function __construct($scheme, $schemeSpecific = '');

    /**
     * Return a string representation of this URI.
     *
     * @return string
     */
    abstract public function getUri();

    /**
     * Returns TRUE if this URI is valid, or FALSE otherwise.
     *
     * @return boolean
     */
    abstract public function valid();
}


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_Version
 * @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: Version.php 24483 2011-09-29 15:31:19Z matthew $
 */

/**
 * Class to store and retrieve the version of Zend Framework.
 *
 * @category   Zend
 * @package    Zend_Version
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
final class Zend_Version
{
    /**
     * Zend Framework version identification - see compareVersion()
     */
    const VERSION = '1.11.11';

    /**
     * The latest stable version Zend Framework available
     *
     * @var string
     */
    protected static $_latestVersion;

    /**
     * Compare the specified Zend Framework version string $version
     * with the current Zend_Version::VERSION of Zend Framework.
     *
     * @param  string  $version  A version string (e.g. "0.7.1").
     * @return int           -1 if the $version is older,
     *                           0 if they are the same,
     *                           and +1 if $version is newer.
     *
     */
    public static function compareVersion($version)
    {
        $version = strtolower($version);
        $version = preg_replace('/(\d)pr(\d?)/', '$1a$2', $version);
        return version_compare($version, strtolower(self::VERSION));
    }

    /**
     * Fetches the version of the latest stable release
     *
     * @link http://framework.zend.com/download/latest
     * @return string
     */
    public static function getLatest()
    {
        if (null === self::$_latestVersion) {
            self::$_latestVersion = 'not available';

            $handle = fopen('http://framework.zend.com/api/zf-version', 'r');
            if (false !== $handle) {
                self::$_latestVersion = stream_get_contents($handle);
                fclose($handle);
            }
        }

        return self::$_latestVersion;
    }
}