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

/** User land classes and interfaces turned on by Zend/Pdf.php file inclusion. */
/** @todo Section should be removed with ZF 2.0 release as obsolete            */

/** Zend_Pdf_Page */
require_once 'Zend/Pdf/Page.php';

/** Zend_Pdf_Style */
require_once 'Zend/Pdf/Style.php';

/** Zend_Pdf_Color_GrayScale */
require_once 'Zend/Pdf/Color/GrayScale.php';

/** Zend_Pdf_Color_Rgb */
require_once 'Zend/Pdf/Color/Rgb.php';

/** Zend_Pdf_Color_Cmyk */
require_once 'Zend/Pdf/Color/Cmyk.php';

/** Zend_Pdf_Color_Html */
require_once 'Zend/Pdf/Color/Html.php';

/** Zend_Pdf_Image */
require_once 'Zend/Pdf/Image.php';

/** Zend_Pdf_Font */
require_once 'Zend/Pdf/Font.php';

/** Zend_Pdf_Resource_Extractor */
require_once 'Zend/Pdf/Resource/Extractor.php';

/** Zend_Pdf_Canvas */
require_once 'Zend/Pdf/Canvas.php';

/** Internally used classes */
require_once 'Zend/Pdf/Element.php';
require_once 'Zend/Pdf/Element/Array.php';
require_once 'Zend/Pdf/Element/String/Binary.php';
require_once 'Zend/Pdf/Element/Boolean.php';
require_once 'Zend/Pdf/Element/Dictionary.php';
require_once 'Zend/Pdf/Element/Name.php';
require_once 'Zend/Pdf/Element/Null.php';
require_once 'Zend/Pdf/Element/Numeric.php';
require_once 'Zend/Pdf/Element/String.php';

/**
 * General entity which describes PDF document.
 * It implements document abstraction with a document level operations.
 *
 * Class is used to create new PDF document or load existing document.
 * See details in a class constructor description
 *
 * Class agregates document level properties and entities (pages, bookmarks,
 * document level actions, attachments, form object, etc)
 *
 * @category   Zend
 * @package    Zend_Pdf
 * @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_Pdf
{
  /**** Class Constants ****/

    /**
     * Version number of generated PDF documents.
     */
    const PDF_VERSION = '1.4';

    /**
     * PDF file header.
     */
    const PDF_HEADER  = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";

    /**
     * Pages collection
     *
     * @todo implement it as a class, which supports ArrayAccess and Iterator interfaces,
     *       to provide incremental parsing and pages tree updating.
     *       That will give good performance and memory (PDF size) benefits.
     *
     * @var array   - array of Zend_Pdf_Page object
     */
    public $pages = array();

    /**
     * Document properties
     *
     * It's an associative array with PDF meta information, values may
     * be string, boolean or float.
     * Returned array could be used directly to access, add, modify or remove
     * document properties.
     *
     * Standard document properties: Title (must be set for PDF/X documents), Author,
     * Subject, Keywords (comma separated list), Creator (the name of the application,
     * that created document, if it was converted from other format), Trapped (must be
     * true, false or null, can not be null for PDF/X documents)
     *
     * @var array
     */
    public $properties = array();

    /**
     * Original properties set.
     *
     * Used for tracking properties changes
     *
     * @var array
     */
    protected $_originalProperties = array();

    /**
     * Document level javascript
     *
     * @var string
     */
    protected $_javaScript = null;

    /**
     * Document named destinations or "GoTo..." actions, used to refer
     * document parts from outside PDF
     *
     * @var array   - array of Zend_Pdf_Target objects
     */
    protected $_namedTargets = array();

    /**
     * Document outlines
     *
     * @var array - array of Zend_Pdf_Outline objects
     */
    public $outlines = array();

    /**
     * Original document outlines list
     * Used to track outlines update
     *
     * @var array - array of Zend_Pdf_Outline objects
     */
    protected $_originalOutlines = array();

    /**
     * Original document outlines open elements count
     * Used to track outlines update
     *
     * @var integer
     */
    protected $_originalOpenOutlinesCount = 0;

    /**
     * Pdf trailer (last or just created)
     *
     * @var Zend_Pdf_Trailer
     */
    protected $_trailer = null;

    /**
     * PDF objects factory.
     *
     * @var Zend_Pdf_ElementFactory_Interface
     */
    protected $_objFactory = null;

    /**
     * Memory manager for stream objects
     *
     * @var Zend_Memory_Manager|null
     */
    protected static $_memoryManager = null;

    /**
     * Pdf file parser.
     * It's not used, but has to be destroyed only with Zend_Pdf object
     *
     * @var Zend_Pdf_Parser
     */
    protected $_parser;

    /**
     * List of inheritable attributesfor pages tree
     *
     * @var array
     */
    protected static $_inheritableAttributes = array('Resources', 'MediaBox', 'CropBox', 'Rotate');

    /**
     * True if the object is a newly created PDF document (affects save() method behavior)
     * False otherwise
     *
     * @var boolean
     */
    protected $_isNewDocument = true;

    /**
     * Request used memory manager
     *
     * @return Zend_Memory_Manager
     */
    static public function getMemoryManager()
    {
        if (self::$_memoryManager === null) {
            require_once 'Zend/Memory.php';
            self::$_memoryManager = Zend_Memory::factory('none');
        }

        return self::$_memoryManager;
    }

    /**
     * Set user defined memory manager
     *
     * @param Zend_Memory_Manager $memoryManager
     */
    static public function setMemoryManager(Zend_Memory_Manager $memoryManager)
    {
        self::$_memoryManager = $memoryManager;
    }

    /**
     * Create new PDF document from a $source string
     *
     * @param string $source
     * @param integer $revision
     * @return Zend_Pdf
     */
    public static function parse(&$source = null, $revision = null)
    {
        return new Zend_Pdf($source, $revision);
    }

    /**
     * Load PDF document from a file
     *
     * @param string $source
     * @param integer $revision
     * @return Zend_Pdf
     */
    public static function load($source = null, $revision = null)
    {
        return new Zend_Pdf($source, $revision, true);
    }

    /**
     * Render PDF document and save it.
     *
     * If $updateOnly is true and it's not a new document, then it only
     * appends new section to the end of file.
     *
     * @param string $filename
     * @param boolean $updateOnly
     * @throws Zend_Pdf_Exception
     */
    public function save($filename, $updateOnly = false)
    {
        if (($file = @fopen($filename, $updateOnly ? 'ab':'wb')) === false ) {
            require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception( "Can not open '$filename' file for writing." );
        }

        $this->render($updateOnly, $file);

        fclose($file);
    }

    /**
     * Creates or loads PDF document.
     *
     * If $source is null, then it creates a new document.
     *
     * If $source is a string and $load is false, then it loads document
     * from a binary string.
     *
     * If $source is a string and $load is true, then it loads document
     * from a file.

     * $revision used to roll back document to specified version
     * (0 - current version, 1 - previous version, 2 - ...)
     *
     * @param string  $source - PDF file to load
     * @param integer $revision
     * @throws Zend_Pdf_Exception
     * @return Zend_Pdf
     */
    public function __construct($source = null, $revision = null, $load = false)
    {
        require_once 'Zend/Pdf/ElementFactory.php';
        $this->_objFactory = Zend_Pdf_ElementFactory::createFactory(1);

        if ($source !== null) {
            require_once 'Zend/Pdf/Parser.php';
            $this->_parser           = new Zend_Pdf_Parser($source, $this->_objFactory, $load);
            $this->_pdfHeaderVersion = $this->_parser->getPDFVersion();
            $this->_trailer          = $this->_parser->getTrailer();
            if ($this->_trailer->Encrypt !== null) {
                require_once 'Zend/Pdf/Exception.php';
                throw new Zend_Pdf_Exception('Encrypted document modification is not supported');
            }
            if ($revision !== null) {
                $this->rollback($revision);
            } else {
                $this->_loadPages($this->_trailer->Root->Pages);
            }

            $this->_loadNamedDestinations($this->_trailer->Root, $this->_parser->getPDFVersion());
            $this->_loadOutlines($this->_trailer->Root);

            if ($this->_trailer->Info !== null) {
                $this->properties = $this->_trailer->Info->toPhp();

                if (isset($this->properties['Trapped'])) {
                    switch ($this->properties['Trapped']) {
                        case 'True':
                            $this->properties['Trapped'] = true;
                            break;

                        case 'False':
                            $this->properties['Trapped'] = false;
                            break;

                        case 'Unknown':
                            $this->properties['Trapped'] = null;
                            break;

                        default:
                            // Wrong property value
                            // Do nothing
                            break;
                    }
                }

                $this->_originalProperties = $this->properties;
            }

            $this->_isNewDocument = false;
        } else {
            $this->_pdfHeaderVersion = Zend_Pdf::PDF_VERSION;

            $trailerDictionary = new Zend_Pdf_Element_Dictionary();

            /**
             * Document id
             */
            $docId = md5(uniqid(rand(), true));   // 32 byte (128 bit) identifier
            $docIdLow  = substr($docId,  0, 16);  // first 16 bytes
            $docIdHigh = substr($docId, 16, 16);  // second 16 bytes

            $trailerDictionary->ID = new Zend_Pdf_Element_Array();
            $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdLow);
            $trailerDictionary->ID->items[] = new Zend_Pdf_Element_String_Binary($docIdHigh);

            $trailerDictionary->Size = new Zend_Pdf_Element_Numeric(0);

            require_once 'Zend/Pdf/Trailer/Generator.php';
            $this->_trailer = new Zend_Pdf_Trailer_Generator($trailerDictionary);

            /**
             * Document catalog indirect object.
             */
            $docCatalog = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
            $docCatalog->Type    = new Zend_Pdf_Element_Name('Catalog');
            $docCatalog->Version = new Zend_Pdf_Element_Name(Zend_Pdf::PDF_VERSION);
            $this->_trailer->Root = $docCatalog;

            /**
             * Pages container
             */
            $docPages = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
            $docPages->Type  = new Zend_Pdf_Element_Name('Pages');
            $docPages->Kids  = new Zend_Pdf_Element_Array();
            $docPages->Count = new Zend_Pdf_Element_Numeric(0);
            $docCatalog->Pages = $docPages;
        }
    }

    /**
     * Retrive number of revisions.
     *
     * @return integer
     */
    public function revisions()
    {
        $revisions = 1;
        $currentTrailer = $this->_trailer;

        while ($currentTrailer->getPrev() !== null && $currentTrailer->getPrev()->Root !== null ) {
            $revisions++;
            $currentTrailer = $currentTrailer->getPrev();
        }

        return $revisions++;
    }

    /**
     * Rollback document $steps number of revisions.
     * This method must be invoked before any changes, applied to the document.
     * Otherwise behavior is undefined.
     *
     * @param integer $steps
     */
    public function rollback($steps)
    {
        for ($count = 0; $count < $steps; $count++) {
            if ($this->_trailer->getPrev() !== null && $this->_trailer->getPrev()->Root !== null) {
                $this->_trailer = $this->_trailer->getPrev();
            } else {
                break;
            }
        }
        $this->_objFactory->setObjectCount($this->_trailer->Size->value);

        // Mark content as modified to force new trailer generation at render time
        $this->_trailer->Root->touch();

        $this->pages = array();
        $this->_loadPages($this->_trailer->Root->Pages);
    }

    /**
     * Load pages recursively
     *
     * @param Zend_Pdf_Element_Reference $pages
     * @param array|null $attributes
     */
    protected function _loadPages(Zend_Pdf_Element_Reference $pages, $attributes = array())
    {
        if ($pages->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
            require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('Wrong argument');
        }

        foreach ($pages->getKeys() as $property) {
            if (in_array($property, self::$_inheritableAttributes)) {
                $attributes[$property] = $pages->$property;
                $pages->$property = null;
            }
        }

        foreach ($pages->Kids->items as $child) {
            if ($child->Type->value == 'Pages') {
                $this->_loadPages($child, $attributes);
            } else if ($child->Type->value == 'Page') {
                foreach (self::$_inheritableAttributes as $property) {
                    if ($child->$property === null && array_key_exists($property, $attributes)) {
                        /**
                         * Important note.
                         * If any attribute or dependant object is an indirect object, then it's still
                         * shared between pages.
                         */
                        if ($attributes[$property] instanceof Zend_Pdf_Element_Object  ||
                            $attributes[$property] instanceof Zend_Pdf_Element_Reference) {
                            $child->$property = $attributes[$property];
                        } else {
                            $child->$property = $this->_objFactory->newObject($attributes[$property]);
                        }
                    }
                }

                require_once 'Zend/Pdf/Page.php';
                $this->pages[] = new Zend_Pdf_Page($child, $this->_objFactory);
            }
        }
    }

    /**
     * Load named destinations recursively
     *
     * @param Zend_Pdf_Element_Reference $root Document catalog entry
     * @param string $pdfHeaderVersion
     * @throws Zend_Pdf_Exception
     */
    protected function _loadNamedDestinations(Zend_Pdf_Element_Reference $root, $pdfHeaderVersion)
    {
        if ($root->Version !== null  &&  version_compare($root->Version->value, $pdfHeaderVersion, '>')) {
            $versionIs_1_2_plus = version_compare($root->Version->value,    '1.1', '>');
        } else {
            $versionIs_1_2_plus = version_compare($pdfHeaderVersion, '1.1', '>');
        }

        if ($versionIs_1_2_plus) {
            // PDF version is 1.2+
            // Look for Destinations structure at Name dictionary
            if ($root->Names !== null  &&  $root->Names->Dests !== null) {
                require_once 'Zend/Pdf/NameTree.php';
                require_once 'Zend/Pdf/Target.php';
                foreach (new Zend_Pdf_NameTree($root->Names->Dests) as $name => $destination) {
                    $this->_namedTargets[$name] = Zend_Pdf_Target::load($destination);
                }
            }
        } else {
            // PDF version is 1.1 (or earlier)
            // Look for Destinations sructure at Dest entry of document catalog
            if ($root->Dests !== null) {
                if ($root->Dests->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
                    require_once 'Zend/Pdf/Exception.php';
                    throw new Zend_Pdf_Exception('Document catalog Dests entry must be a dictionary.');
                }

                require_once 'Zend/Pdf/Target.php';
                foreach ($root->Dests->getKeys() as $destKey) {
                    $this->_namedTargets[$destKey] = Zend_Pdf_Target::load($root->Dests->$destKey);
                }
            }
        }
    }

    /**
     * Load outlines recursively
     *
     * @param Zend_Pdf_Element_Reference $root Document catalog entry
     */
    protected function _loadOutlines(Zend_Pdf_Element_Reference $root)
    {
        if ($root->Outlines === null) {
            return;
        }

        if ($root->Outlines->getType() != Zend_Pdf_Element::TYPE_DICTIONARY) {
            require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('Document catalog Outlines entry must be a dictionary.');
        }

        if ($root->Outlines->Type !== null  &&  $root->Outlines->Type->value != 'Outlines') {
            require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('Outlines Type entry must be an \'Outlines\' string.');
        }

        if ($root->Outlines->First === null) {
            return;
        }

        $outlineDictionary = $root->Outlines->First;
        $processedDictionaries = new SplObjectStorage();
        while ($outlineDictionary !== null  &&  !$processedDictionaries->contains($outlineDictionary)) {
            $processedDictionaries->attach($outlineDictionary);

            require_once 'Zend/Pdf/Outline/Loaded.php';
            $this->outlines[] = new Zend_Pdf_Outline_Loaded($outlineDictionary);

            $outlineDictionary = $outlineDictionary->Next;
        }

        $this->_originalOutlines = $this->outlines;

        if ($root->Outlines->Count !== null) {
            $this->_originalOpenOutlinesCount = $root->Outlines->Count->value;
        }
    }

    /**
     * Orginize pages to tha pages tree structure.
     *
     * @todo atomatically attach page to the document, if it's not done yet.
     * @todo check, that page is attached to the current document
     *
     * @todo Dump pages as a balanced tree instead of a plain set.
     */
    protected function _dumpPages()
    {
        $root = $this->_trailer->Root;
        $pagesContainer = $root->Pages;

        $pagesContainer->touch();
        $pagesContainer->Kids->items = array();

        foreach ($this->pages as $page ) {
            $page->render($this->_objFactory);

            $pageDictionary = $page->getPageDictionary();
            $pageDictionary->touch();
            $pageDictionary->Parent = $pagesContainer;

            $pagesContainer->Kids->items[] = $pageDictionary;
        }

        $this->_refreshPagesHash();

        $pagesContainer->Count->touch();
        $pagesContainer->Count->value = count($this->pages);

        // Refresh named destinations list
        foreach ($this->_namedTargets as $name => $namedTarget) {
            if ($namedTarget instanceof Zend_Pdf_Destination_Explicit) {
                // Named target is an explicit destination
                if ($this->resolveDestination($namedTarget, false) === null) {
                    unset($this->_namedTargets[$name]);
                }
            } else if ($namedTarget instanceof Zend_Pdf_Action) {
                // Named target is an action
                if ($this->_cleanUpAction($namedTarget, false) === null) {
                    // Action is a GoTo action with an unresolved destination
                    unset($this->_namedTargets[$name]);
                }
            } else {
                require_once 'Zend/Pdf/Exception.php';
                throw new Zend_Pdf_Exception('Wrong type of named targed (\'' . get_class($namedTarget) . '\').');
            }
        }

        // Refresh outlines
        require_once 'Zend/Pdf/RecursivelyIteratableObjectsContainer.php';
        $iterator = new RecursiveIteratorIterator(new Zend_Pdf_RecursivelyIteratableObjectsContainer($this->outlines), RecursiveIteratorIterator::SELF_FIRST);
        foreach ($iterator as $outline) {
            $target = $outline->getTarget();

            if ($target !== null) {
                if ($target instanceof Zend_Pdf_Destination) {
                    // Outline target is a destination
                    if ($this->resolveDestination($target, false) === null) {
                        $outline->setTarget(null);
                    }
                } else if ($target instanceof Zend_Pdf_Action) {
                    // Outline target is an action
                    if ($this->_cleanUpAction($target, false) === null) {
                        // Action is a GoTo action with an unresolved destination
                        $outline->setTarget(null);
                    }
                } else {
                    require_once 'Zend/Pdf/Exception.php';
                    throw new Zend_Pdf_Exception('Wrong outline target.');
                }
            }
        }

        $openAction = $this->getOpenAction();
        if ($openAction !== null) {
            if ($openAction instanceof Zend_Pdf_Action) {
                // OpenAction is an action
                if ($this->_cleanUpAction($openAction, false) === null) {
                    // Action is a GoTo action with an unresolved destination
                    $this->setOpenAction(null);
                }
            } else if ($openAction instanceof Zend_Pdf_Destination) {
                // OpenAction target is a destination
                if ($this->resolveDestination($openAction, false) === null) {
                    $this->setOpenAction(null);
                }
            } else {
                require_once 'Zend/Pdf/Exception.php';
                throw new Zend_Pdf_Exception('OpenAction has to be either PDF Action or Destination.');
            }
        }
    }

    /**
     * Dump named destinations
     *
     * @todo Create a balanced tree instead of plain structure.
     */
    protected function _dumpNamedDestinations()
    {
        ksort($this->_namedTargets, SORT_STRING);

        $destArrayItems = array();
        foreach ($this->_namedTargets as $name => $destination) {
            $destArrayItems[] = new Zend_Pdf_Element_String($name);

            if ($destination instanceof Zend_Pdf_Target) {
                $destArrayItems[] = $destination->getResource();
            } else {
                require_once 'Zend/Pdf/Exception.php';
                throw new Zend_Pdf_Exception('PDF named destinations must be a Zend_Pdf_Target object.');
            }
        }
        $destArray = $this->_objFactory->newObject(new Zend_Pdf_Element_Array($destArrayItems));

        $DestTree = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
        $DestTree->Names = $destArray;

        $root = $this->_trailer->Root;

        if ($root->Names === null) {
            $root->touch();
            $root->Names = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
        } else {
            $root->Names->touch();
        }
        $root->Names->Dests = $DestTree;
    }

    /**
     * Dump outlines recursively
     */
    protected function _dumpOutlines()
    {
        $root = $this->_trailer->Root;

        if ($root->Outlines === null) {
            if (count($this->outlines) == 0) {
                return;
            } else {
                $root->Outlines = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());
                $root->Outlines->Type = new Zend_Pdf_Element_Name('Outlines');
                $updateOutlinesNavigation = true;
            }
        } else {
            $updateOutlinesNavigation = false;
            if (count($this->_originalOutlines) != count($this->outlines)) {
                // If original and current outlines arrays have different size then outlines list was updated
                $updateOutlinesNavigation = true;
            } else if ( !(array_keys($this->_originalOutlines) === array_keys($this->outlines)) ) {
                // If original and current outlines arrays have different keys (with a glance to an order) then outlines list was updated
                $updateOutlinesNavigation = true;
            } else {
                foreach ($this->outlines as $key => $outline) {
                    if ($this->_originalOutlines[$key] !== $outline) {
                        $updateOutlinesNavigation = true;
                    }
                }
            }
        }

        $lastOutline = null;
        $openOutlinesCount = 0;
        if ($updateOutlinesNavigation) {
            $root->Outlines->touch();
            $root->Outlines->First = null;

            foreach ($this->outlines as $outline) {
                if ($lastOutline === null) {
                    // First pass. Update Outlines dictionary First entry using corresponding value
                    $lastOutline = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines);
                    $root->Outlines->First = $lastOutline;
                } else {
                    // Update previous outline dictionary Next entry (Prev is updated within dumpOutline() method)
                    $currentOutlineDictionary = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines, $lastOutline);
                    $lastOutline->Next = $currentOutlineDictionary;
                    $lastOutline       = $currentOutlineDictionary;
                }
                $openOutlinesCount += $outline->openOutlinesCount();
            }

            $root->Outlines->Last  = $lastOutline;
        } else {
            foreach ($this->outlines as $outline) {
                $lastOutline = $outline->dumpOutline($this->_objFactory, $updateOutlinesNavigation, $root->Outlines, $lastOutline);
                $openOutlinesCount += $outline->openOutlinesCount();
            }
        }

        if ($openOutlinesCount != $this->_originalOpenOutlinesCount) {
            $root->Outlines->touch;
            $root->Outlines->Count = new Zend_Pdf_Element_Numeric($openOutlinesCount);
        }
    }

    /**
     * Create page object, attached to the PDF document.
     * Method signatures:
     *
     * 1. Create new page with a specified pagesize.
     *    If $factory is null then it will be created and page must be attached to the document to be
     *    included into output.
     * ---------------------------------------------------------
     * new Zend_Pdf_Page(string $pagesize);
     * ---------------------------------------------------------
     *
     * 2. Create new page with a specified pagesize (in default user space units).
     *    If $factory is null then it will be created and page must be attached to the document to be
     *    included into output.
     * ---------------------------------------------------------
     * new Zend_Pdf_Page(numeric $width, numeric $height);
     * ---------------------------------------------------------
     *
     * @param mixed $param1
     * @param mixed $param2
     * @return Zend_Pdf_Page
     */
    public function newPage($param1, $param2 = null)
    {
        require_once 'Zend/Pdf/Page.php';
        if ($param2 === null) {
            return new Zend_Pdf_Page($param1, $this->_objFactory);
        } else {
            return new Zend_Pdf_Page($param1, $param2, $this->_objFactory);
        }
    }

    /**
     * Return the document-level Metadata
     * or null Metadata stream is not presented
     *
     * @return string
     */
    public function getMetadata()
    {
        if ($this->_trailer->Root->Metadata !== null) {
            return $this->_trailer->Root->Metadata->value;
        } else {
            return null;
        }
    }

    /**
     * Sets the document-level Metadata (mast be valid XMP document)
     *
     * @param string $metadata
     */
    public function setMetadata($metadata)
    {
        $metadataObject = $this->_objFactory->newStreamObject($metadata);
        $metadataObject->dictionary->Type    = new Zend_Pdf_Element_Name('Metadata');
        $metadataObject->dictionary->Subtype = new Zend_Pdf_Element_Name('XML');

        $this->_trailer->Root->Metadata = $metadataObject;
        $this->_trailer->Root->touch();
    }

    /**
     * Return the document-level JavaScript
     * or null if there is no JavaScript for this document
     *
     * @return string
     */
    public function getJavaScript()
    {
        return $this->_javaScript;
    }

    /**
     * Get open Action
     * Returns Zend_Pdf_Target (Zend_Pdf_Destination or Zend_Pdf_Action object)
     *
     * @return Zend_Pdf_Target
     */
    public function getOpenAction()
    {
        if ($this->_trailer->Root->OpenAction !== null) {
            require_once 'Zend/Pdf/Target.php';
            return Zend_Pdf_Target::load($this->_trailer->Root->OpenAction);
        } else {
            return null;
        }
    }

    /**
     * Set open Action which is actually Zend_Pdf_Destination or Zend_Pdf_Action object
     *
     * @param Zend_Pdf_Target $openAction
     * @returns Zend_Pdf
     */
    public function setOpenAction(Zend_Pdf_Target $openAction = null)
    {
        $root = $this->_trailer->Root;
        $root->touch();

        if ($openAction === null) {
            $root->OpenAction = null;
        } else {
            $root->OpenAction = $openAction->getResource();

            if ($openAction instanceof Zend_Pdf_Action)  {
                $openAction->dumpAction($this->_objFactory);
            }
        }

        return $this;
    }

    /**
     * Return an associative array containing all the named destinations (or GoTo actions) in the PDF.
     * Named targets can be used to reference from outside
     * the PDF, ex: 'http://www.something.com/mydocument.pdf#MyAction'
     *
     * @return array
     */
    public function getNamedDestinations()
    {
        return $this->_namedTargets;
    }

    /**
     * Return specified named destination
     *
     * @param string $name
     * @return Zend_Pdf_Destination_Explicit|Zend_Pdf_Action_GoTo
     */
    public function getNamedDestination($name)
    {
        if (isset($this->_namedTargets[$name])) {
            return $this->_namedTargets[$name];
        } else {
            return null;
        }
    }

    /**
     * Set specified named destination
     *
     * @param string $name
     * @param Zend_Pdf_Destination_Explicit|Zend_Pdf_Action_GoTo $target
     */
    public function setNamedDestination($name, $destination = null)
    {
        if ($destination !== null  &&
            !$destination instanceof Zend_Pdf_Action_GoTo  &&
            !$destination instanceof Zend_Pdf_Destination_Explicit) {
            require_once 'Zend/Pdf/Exception.php';
            throw new Zend_Pdf_Exception('PDF named destination must refer an explicit destination or a GoTo PDF action.');
        }

        if ($destination !== null) {
           $this->_namedTargets[$name] = $destination;
        } else {
            unset($this->_namedTargets[$name]);
        }
    }

    /**
     * Pages collection hash:
     * <page dictionary object hash id> => Zend_Pdf_Page
     *
     * @var SplObjectStorage
     */
    protected $_pageReferences = null;

    /**
     * Pages collection hash:
     * <page number> => Zend_Pdf_Page
     *
     * @var array
     */
    protected $_pageNumbers = null;

    /**
     * Refresh page collection hashes
     *
     * @return Zend_Pdf
     */
    protected function _refreshPagesHash()
    {
        $this->_pageReferences = array();
        $this->_pageNumbers    = array();
        $count = 1;
        foreach ($this->pages as $page) {
            $pageDictionaryHashId = spl_object_hash($page->getPageDictionary()->getObject());
            $this->_pageReferences[$pageDictionaryHashId] = $page;
            $this->_pageNumbers[$count++]                 = $page;
        }

        return $this;
    }

    /**
     * Resolve destination.
     *
     * Returns Zend_Pdf_Page page object or null if destination is not found within PDF document.
     *
     * @param Zend_Pdf_Destination $destination  Destination to resolve
     * @param boolean $refreshPagesHash  Refresh page collection hashes before processing
     * @return Zend_Pdf_Page|null
     * @throws Zend_Pdf_Exception
     */
    public function resolveDestination(Zend_Pdf_Destination $destination, $refreshPageCollectionHashes = true)
    {
        if ($this->_pageReferences === null  ||  $refreshPageCollectionHashes) {
            $this->_refreshPagesHash();
        }

        if ($destination instanceof Zend_Pdf_Destination_Named) {
            if (!isset($this->_namedTargets[$destination->getName()])) {
                return null;
            }
            $destination = $this->getNamedDestination($destination->getName());

            if ($destination instanceof Zend_Pdf_Action) {
                if (!$destination instanceof Zend_Pdf_Action_GoTo) {
                    return null;
                }
                $destination = $destination->getDestination();
            }

            if (!$destination instanceof Zend_Pdf_Destination_Explicit) {
                require_once 'Zend/Pdf/Exception.php';
                throw new Zend_Pdf_Exception('Named destination target has to be an explicit destination.');
            }
        }

        // Named target is an explicit destination
        $pageElement = $destination->getResource()->items[0];

        if ($pageElement->getType() == Zend_Pdf_Element::TYPE_NUMERIC) {
            // Page reference is a PDF number
            if (!isset($this->_pageNumbers[$pageElement->value])) {
                return null;
            }

            return $this->_pageNumbers[$pageElement->value];
        }

        // Page reference is a PDF page dictionary reference
        $pageDictionaryHashId = spl_object_hash($pageElement->getObject());
        if (!isset($this->_pageReferences[$pageDictionaryHashId])) {
            return null;
        }
        return $this->_pageReferences[$pageDictionaryHashId];
    }

    /**
     * Walk through action and its chained actions tree and remove nodes
     * if they are GoTo actions with an unresolved target.
     *
     * Returns null if root node is deleted or updated action overwise.
     *
     * @todo Give appropriate name and make method public
     *
     * @param Zend_Pdf_Action $action
     * @param boolean $refreshPagesHash  Refresh page collection hashes before processing
     * @return Zend_Pdf_Action|null
     */
    protected function _cleanUpAction(Zend_Pdf_Action $action, $refreshPageCollectionHashes = true)
    {
        if ($this->_pageReferences === null  ||  $refreshPageCollectionHashes) {
            $this->_refreshPagesHash();
        }

        // Named target is an action
        if ($action instanceof Zend_Pdf_Action_GoTo  &&
            $this->resolveDestination($action->getDestination(), false) === null) {
            // Action itself is a GoTo action with an unresolved destination
            return null;
        }

        // Walk through child actions
        $iterator = new RecursiveIteratorIterator($action, RecursiveIteratorIterator::SELF_FIRST);

        $actionsToClean        = array();
        $deletionCandidateKeys = array();
        foreach ($iterator as $chainedAction) {
            if ($chainedAction instanceof Zend_Pdf_Action_GoTo  &&
                $this->resolveDestination($chainedAction->getDestination(), false) === null) {
                // Some child action is a GoTo action with an unresolved destination
                // Mark it as a candidate for deletion
                $actionsToClean[]        = $iterator->getSubIterator();
                $deletionCandidateKeys[] = $iterator->getSubIterator()->key();
            }
        }
        foreach ($actionsToClean as $id => $action) {
            unset($action->next[$deletionCandidateKeys[$id]]);
        }

        return $action;
    }

    /**
     * Extract fonts attached to the document
     *
     * returns array of Zend_Pdf_Resource_Font_Extracted objects
     *
     * @return array
     * @throws Zend_Pdf_Exception
     */
    public function extractFonts()
    {
        $fontResourcesUnique = array();
        foreach ($this->pages as $page) {
            $pageResources = $page->extractResources();

            if ($pageResources->Font === null) {
                // Page doesn't contain have any font reference
                continue;
            }

            $fontResources = $pageResources->Font;

            foreach ($fontResources->getKeys() as $fontResourceName) {
                $fontDictionary = $fontResources->$fontResourceName;

                if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference  ||
                       $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
                    require_once 'Zend/Pdf/Exception.php';
                    throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.');
                }

                $fontResourcesUnique[spl_object_hash($fontDictionary->getObject())] = $fontDictionary;
            }
        }

        $fonts = array();
        require_once 'Zend/Pdf/Exception.php';
        foreach ($fontResourcesUnique as $resourceId => $fontDictionary) {
            try {
                // Try to extract font
                require_once 'Zend/Pdf/Resource/Font/Extracted.php';
                $extractedFont = new Zend_Pdf_Resource_Font_Extracted($fontDictionary);

                $fonts[$resourceId] = $extractedFont;
            } catch (Zend_Pdf_Exception $e) {
                if ($e->getMessage() != 'Unsupported font type.') {
                    throw $e;
                }
            }
        }

        return $fonts;
    }

    /**
     * Extract font attached to the page by specific font name
     *
     * $fontName should be specified in UTF-8 encoding
     *
     * @return Zend_Pdf_Resource_Font_Extracted|null
     * @throws Zend_Pdf_Exception
     */
    public function extractFont($fontName)
    {
        $fontResourcesUnique = array();
        require_once 'Zend/Pdf/Exception.php';
        foreach ($this->pages as $page) {
            $pageResources = $page->extractResources();

            if ($pageResources->Font === null) {
                // Page doesn't contain have any font reference
                continue;
            }

            $fontResources = $pageResources->Font;

            foreach ($fontResources->getKeys() as $fontResourceName) {
                $fontDictionary = $fontResources->$fontResourceName;

                if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference  ||
                       $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
                    require_once 'Zend/Pdf/Exception.php';
                    throw new Zend_Pdf_Exception('Font dictionary has to be an indirect object or object reference.');
                }

                $resourceId = spl_object_hash($fontDictionary->getObject());
                if (isset($fontResourcesUnique[$resourceId])) {
                    continue;
                } else {
                    // Mark resource as processed
                    $fontResourcesUnique[$resourceId] = 1;
                }

                if ($fontDictionary->BaseFont->value != $fontName) {
                    continue;
                }

                try {
                    // Try to extract font
                    require_once 'Zend/Pdf/Resource/Font/Extracted.php';
                    return new Zend_Pdf_Resource_Font_Extracted($fontDictionary);
                } catch (Zend_Pdf_Exception $e) {
                    if ($e->getMessage() != 'Unsupported font type.') {
                        throw $e;
                    }
                    // Continue searhing
                }
            }
        }

        return null;
    }

    /**
     * Render the completed PDF to a string.
     * If $newSegmentOnly is true and it's not a new document,
     * then only appended part of PDF is returned.
     *
     * @param boolean $newSegmentOnly
     * @param resource $outputStream
     * @return string
     * @throws Zend_Pdf_Exception
     */
    public function render($newSegmentOnly = false, $outputStream = null)
    {
        if ($this->_isNewDocument) {
            // Drop full document first time even $newSegmentOnly is set to true
            $newSegmentOnly = false;
            $this->_isNewDocument = false;
        }

        // Save document properties if necessary
        if ($this->properties != $this->_originalProperties) {
            $docInfo = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());

            foreach ($this->properties as $key => $value) {
                switch ($key) {
                    case 'Trapped':
                        switch ($value) {
                            case true:
                                $docInfo->$key = new Zend_Pdf_Element_Name('True');
                                break;

                            case false:
                                $docInfo->$key = new Zend_Pdf_Element_Name('False');
                                break;

                            case null:
                                $docInfo->$key = new Zend_Pdf_Element_Name('Unknown');
                                break;

                            default:
                                require_once 'Zend/Pdf/Exception.php';
                                throw new Zend_Pdf_Exception('Wrong Trapped document property vale: \'' . $value . '\'. Only true, false and null values are allowed.');
                                break;
                        }

                    case 'CreationDate':
                        // break intentionally omitted
                    case 'ModDate':
                        $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
                        break;

                    case 'Title':
                        // break intentionally omitted
                    case 'Author':
                        // break intentionally omitted
                    case 'Subject':
                        // break intentionally omitted
                    case 'Keywords':
                        // break intentionally omitted
                    case 'Creator':
                        // break intentionally omitted
                    case 'Producer':
                        if (extension_loaded('mbstring') === true) {
                            $detected = mb_detect_encoding($value);
                            if ($detected !== 'ASCII') {
                                $value = "\xfe\xff" . mb_convert_encoding($value, 'UTF-16', $detected);
                            }
                        }
                        $docInfo->$key = new Zend_Pdf_Element_String((string)$value);
                        break;

                    default:
                        // Set property using PDF type based on PHP type
                        $docInfo->$key = Zend_Pdf_Element::phpToPdf($value);
                        break;
                }
            }

            $this->_trailer->Info = $docInfo;
        }

        $this->_dumpPages();
        $this->_dumpNamedDestinations();
        $this->_dumpOutlines();

        // Check, that PDF file was modified
        // File is always modified by _dumpPages() now, but future implementations may eliminate this.
        if (!$this->_objFactory->isModified()) {
            if ($newSegmentOnly) {
                // Do nothing, return
                return '';
            }

            if ($outputStream === null) {
                return $this->_trailer->getPDFString();
            } else {
                $pdfData = $this->_trailer->getPDFString();
                while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
                    $pdfData = substr($pdfData, $byteCount);
                }

                return '';
            }
        }

        // offset (from a start of PDF file) of new PDF file segment
        $offset = $this->_trailer->getPDFLength();
        // Last Object number in a list of free objects
        $lastFreeObject = $this->_trailer->getLastFreeObject();

        // Array of cross-reference table subsections
        $xrefTable = array();
        // Object numbers of first objects in each subsection
        $xrefSectionStartNums = array();

        // Last cross-reference table subsection
        $xrefSection = array();
        // Dummy initialization of the first element (specail case - header of linked list of free objects).
        $xrefSection[] = 0;
        $xrefSectionStartNums[] = 0;
        // Object number of last processed PDF object.
        // Used to manage cross-reference subsections.
        // Initialized by zero (specail case - header of linked list of free objects).
        $lastObjNum = 0;

        if ($outputStream !== null) {
            if (!$newSegmentOnly) {
                $pdfData = $this->_trailer->getPDFString();
                while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {
                    $pdfData = substr($pdfData, $byteCount);
                }
            }
        } else {
            $pdfSegmentBlocks = ($newSegmentOnly) ? array() : array($this->_trailer->getPDFString());
        }

        // Iterate objects to create new reference table
        foreach ($this->_objFactory->listModifiedObjects() as $updateInfo) {
            $objNum = $updateInfo->getObjNum();

            if ($objNum - $lastObjNum != 1) {
                // Save cross-reference table subsection and start new one
                $xrefTable[] = $xrefSection;
                $xrefSection = array();
                $xrefSectionStartNums[] = $objNum;
            }

            if ($updateInfo->isFree()) {
                // Free object cross-reference table entry
                $xrefSection[]  = sprintf("%010d %05d f \n", $lastFreeObject, $updateInfo->getGenNum());
                $lastFreeObject = $objNum;
            } else {
                // In-use object cross-reference table entry
                $xrefSection[]  = sprintf("%010d %05d n \n", $offset, $updateInfo->getGenNum());

                $pdfBlock = $updateInfo->getObjectDump();
                $offset += strlen($pdfBlock);

                if ($outputStream === null) {
                    $pdfSegmentBlocks[] = $pdfBlock;
                } else {
                    while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
                        $pdfBlock = substr($pdfBlock, $byteCount);
                    }
                }
            }
            $lastObjNum = $objNum;
        }
        // Save last cross-reference table subsection
        $xrefTable[] = $xrefSection;

        // Modify first entry (specail case - header of linked list of free objects).
        $xrefTable[0][0] = sprintf("%010d 65535 f \n", $lastFreeObject);

        $xrefTableStr = "xref\n";
        foreach ($xrefTable as $sectId => $xrefSection) {
            $xrefTableStr .= sprintf("%d %d \n", $xrefSectionStartNums[$sectId], count($xrefSection));
            foreach ($xrefSection as $xrefTableEntry) {
                $xrefTableStr .= $xrefTableEntry;
            }
        }

        $this->_trailer->Size->value = $this->_objFactory->getObjectCount();

        $pdfBlock = $xrefTableStr
                 .  $this->_trailer->toString()
                 . "startxref\n" . $offset . "\n"
                 . "%%EOF\n";

        $this->_objFactory->cleanEnumerationShiftCache();

        if ($outputStream === null) {
            $pdfSegmentBlocks[] = $pdfBlock;

            return implode('', $pdfSegmentBlocks);
        } else {
            while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {
                $pdfBlock = substr($pdfBlock, $byteCount);
            }

            return '';
        }
    }

    /**
     * Set the document-level JavaScript
     *
     * @param string $javascript
     */
    public function setJavaScript($javascript)
    {
        $this->_javaScript = $javascript;
    }

    /**
     * Convert date to PDF format (it's close to ASN.1 (Abstract Syntax Notation
     * One) defined in ISO/IEC 8824).
     *
     * @todo This really isn't the best location for this method. It should
     *   probably actually exist as Zend_Pdf_Element_Date or something like that.
     *
     * @todo Address the following E_STRICT issue:
     *   PHP Strict Standards:  date(): It is not safe to rely on the system's
     *   timezone settings. Please use the date.timezone setting, the TZ
     *   environment variable or the date_default_timezone_set() function. In
     *   case you used any of those methods and you are still getting this
     *   warning, you most likely misspelled the timezone identifier.
     *
     * @param integer $timestamp (optional) If omitted, uses the current time.
     * @return string
     */
    public static function pdfDate($timestamp = null)
    {
        if ($timestamp === null) {
            $date = date('\D\:YmdHisO');
        } else {
            $date = date('\D\:YmdHisO', $timestamp);
        }
        return substr_replace($date, '\'', -2, 0) . '\'';
    }

}


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

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

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

/**
 * @category   Zend
 * @package    Zend_Paginator
 * @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_Paginator implements Countable, IteratorAggregate
{
    /**
     * Specifies that the factory should try to detect the proper adapter type first
     *
     * @var string
     */
    const INTERNAL_ADAPTER = 'Zend_Paginator_Adapter_Internal';

    /**
     * The cache tag prefix used to namespace Paginator results in the cache
     *
     */
    const CACHE_TAG_PREFIX = 'Zend_Paginator_';

    /**
     * Adapter plugin loader
     *
     * @var Zend_Loader_PluginLoader
     */
    protected static $_adapterLoader = null;

    /**
     * Configuration file
     *
     * @var Zend_Config
     */
    protected static $_config = null;

    /**
     * Default scrolling style
     *
     * @var string
     */
    protected static $_defaultScrollingStyle = 'Sliding';

    /**
     * Default item count per page
     *
     * @var int
     */
    protected static $_defaultItemCountPerPage = 10;

    /**
     * Default number of local pages (i.e., the number of discretes
     * page numbers that will be displayed, including the current
     * page number)
     *
     * @var int
     */
    protected static $_defaultPageRange = 10;

    /**
     * Scrolling style plugin loader
     *
     * @var Zend_Loader_PluginLoader
     */
    protected static $_scrollingStyleLoader = null;

    /**
     * Cache object
     *
     * @var Zend_Cache_Core
     */
    protected static $_cache;

    /**
     * Enable or disable the cache by Zend_Paginator instance
     *
     * @var bool
     */
    protected $_cacheEnabled = true;

    /**
     * Adapter
     *
     * @var Zend_Paginator_Adapter_Interface
     */
    protected $_adapter = null;

    /**
     * Number of items in the current page
     *
     * @var integer
     */
    protected $_currentItemCount = null;

    /**
     * Current page items
     *
     * @var Traversable
     */
    protected $_currentItems = null;

    /**
     * Current page number (starting from 1)
     *
     * @var integer
     */
    protected $_currentPageNumber = 1;

    /**
     * Result filter
     *
     * @var Zend_Filter_Interface
     */
    protected $_filter = null;

    /**
     * Number of items per page
     *
     * @var integer
     */
    protected $_itemCountPerPage = null;

    /**
     * Number of pages
     *
     * @var integer
     */
    protected $_pageCount = null;

    /**
     * Number of local pages (i.e., the number of discrete page numbers
     * that will be displayed, including the current page number)
     *
     * @var integer
     */
    protected $_pageRange = null;

    /**
     * Pages
     *
     * @var array
     */
    protected $_pages = null;

    /**
     * View instance used for self rendering
     *
     * @var Zend_View_Interface
     */
    protected $_view = null;

    /**
     * Adds an adapter prefix path to the plugin loader.
     *
     * @param string $prefix
     * @param string $path
     */
    public static function addAdapterPrefixPath($prefix, $path)
    {
        self::getAdapterLoader()->addPrefixPath($prefix, $path);
    }

    /**
     * Adds an array of adapter prefix paths to the plugin
     * loader.
     *
     *
     * $prefixPaths = array(
     *     'My_Paginator_Adapter'   => 'My/Paginator/Adapter/',
     *     'Your_Paginator_Adapter' => 'Your/Paginator/Adapter/'
     * );
     *
     *
     * @param array $prefixPaths
     */
    public static function addAdapterPrefixPaths(array $prefixPaths)
    {
        if (isset($prefixPaths['prefix']) && isset($prefixPaths['path'])) {
            self::addAdapterPrefixPath($prefixPaths['prefix'], $prefixPaths['path']);
        } else {
            foreach ($prefixPaths as $prefix => $path) {
                if (is_array($path) && isset($path['prefix']) && isset($path['path'])) {
                    $prefix = $path['prefix'];
                    $path   = $path['path'];
                }

                self::addAdapterPrefixPath($prefix, $path);
            }
        }
    }

    /**
     * Adds a scrolling style prefix path to the plugin loader.
     *
     * @param string $prefix
     * @param string $path
     */
    public static function addScrollingStylePrefixPath($prefix, $path)
    {
        self::getScrollingStyleLoader()->addPrefixPath($prefix, $path);
    }

    /**
     * Adds an array of scrolling style prefix paths to the plugin
     * loader.
     *
     *
     * $prefixPaths = array(
     *     'My_Paginator_ScrollingStyle'   => 'My/Paginator/ScrollingStyle/',
     *     'Your_Paginator_ScrollingStyle' => 'Your/Paginator/ScrollingStyle/'
     * );
     *
     *
     * @param array $prefixPaths
     */
    public static function addScrollingStylePrefixPaths(array $prefixPaths)
    {
        if (isset($prefixPaths['prefix']) && isset($prefixPaths['path'])) {
            self::addScrollingStylePrefixPath($prefixPaths['prefix'], $prefixPaths['path']);
        } else {
            foreach ($prefixPaths as $prefix => $path) {
                if (is_array($path) && isset($path['prefix']) && isset($path['path'])) {
                    $prefix = $path['prefix'];
                    $path   = $path['path'];
                }

                self::addScrollingStylePrefixPath($prefix, $path);
            }
        }
    }

    /**
     * Factory.
     *
     * @param  mixed $data
     * @param  string $adapter
     * @param  array $prefixPaths
     * @return Zend_Paginator
     */
    public static function factory($data, $adapter = self::INTERNAL_ADAPTER,
                                   array $prefixPaths = null)
    {
        if ($data instanceof Zend_Paginator_AdapterAggregate) {
            return new self($data->getPaginatorAdapter());
        } else {
            if ($adapter == self::INTERNAL_ADAPTER) {
                if (is_array($data)) {
                    $adapter = 'Array';
                } else if ($data instanceof Zend_Db_Table_Select) {
                    $adapter = 'DbTableSelect';
                } else if ($data instanceof Zend_Db_Select) {
                    $adapter = 'DbSelect';
                } else if ($data instanceof Iterator) {
                    $adapter = 'Iterator';
                } else if (is_integer($data)) {
                    $adapter = 'Null';
                } else {
                    $type = (is_object($data)) ? get_class($data) : gettype($data);

                    /**
                     * @see Zend_Paginator_Exception
                     */
                    require_once 'Zend/Paginator/Exception.php';

                    throw new Zend_Paginator_Exception('No adapter for type ' . $type);
                }
            }

            $pluginLoader = self::getAdapterLoader();

            if (null !== $prefixPaths) {
                foreach ($prefixPaths as $prefix => $path) {
                    $pluginLoader->addPrefixPath($prefix, $path);
                }
            }

            $adapterClassName = $pluginLoader->load($adapter);

            return new self(new $adapterClassName($data));
        }
    }

    /**
     * Returns the adapter loader.  If it doesn't exist it's created.
     *
     * @return Zend_Loader_PluginLoader
     */
    public static function getAdapterLoader()
    {
        if (self::$_adapterLoader === null) {
            self::$_adapterLoader = new Zend_Loader_PluginLoader(
                array('Zend_Paginator_Adapter' => 'Zend/Paginator/Adapter')
            );
        }

        return self::$_adapterLoader;
    }

    /**
     * Set a global config
     *
     * @param Zend_Config $config
     */
    public static function setConfig(Zend_Config $config)
    {
        self::$_config = $config;

        $adapterPaths = $config->get('adapterpaths');

        if ($adapterPaths != null) {
            self::addAdapterPrefixPaths($adapterPaths->adapterpath->toArray());
        }

        $prefixPaths = $config->get('prefixpaths');

        if ($prefixPaths != null) {
            self::addScrollingStylePrefixPaths($prefixPaths->prefixpath->toArray());
        }

        $scrollingStyle = $config->get('scrollingstyle');

        if ($scrollingStyle != null) {
            self::setDefaultScrollingStyle($scrollingStyle);
        }
    }

    /**
     * Returns the default scrolling style.
     *
     * @return  string
     */
    public static function getDefaultScrollingStyle()
    {
        return self::$_defaultScrollingStyle;
    }

    /**
     * Get the default item count per page
     *
     * @return int
     */
    public static function getDefaultItemCountPerPage()
    {
        return self::$_defaultItemCountPerPage;
    }

    /**
     * Set the default item count per page
     *
     * @param int $count
     */
    public static function setDefaultItemCountPerPage($count)
    {
        self::$_defaultItemCountPerPage = (int) $count;
    }

    /**
     * Get the default page range
     *
     * @return int
     */
    public static function getDefaultPageRange()
    {
        return self::$_defaultPageRange;
    }

    /**
     * Set the default page range
     *
     * @param int $count
     */
    public static function setDefaultPageRange($count)
    {
        self::$_defaultPageRange = (int) $count;
    }

    /**
     * Sets a cache object
     *
     * @param Zend_Cache_Core $cache
     */
    public static function setCache(Zend_Cache_Core $cache)
    {
        self::$_cache = $cache;
    }

    /**
     * Sets the default scrolling style.
     *
     * @param  string $scrollingStyle
     */
    public static function setDefaultScrollingStyle($scrollingStyle = 'Sliding')
    {
        self::$_defaultScrollingStyle = $scrollingStyle;
    }

    /**
     * Returns the scrolling style loader.  If it doesn't exist it's
     * created.
     *
     * @return Zend_Loader_PluginLoader
     */
    public static function getScrollingStyleLoader()
    {
        if (self::$_scrollingStyleLoader === null) {
            self::$_scrollingStyleLoader = new Zend_Loader_PluginLoader(
                array('Zend_Paginator_ScrollingStyle' => 'Zend/Paginator/ScrollingStyle')
            );
        }

        return self::$_scrollingStyleLoader;
    }

    /**
     * Constructor.
     *
     * @param Zend_Paginator_Adapter_Interface|Zend_Paginator_AdapterAggregate $adapter
     */
    public function __construct($adapter)
    {
        if ($adapter instanceof Zend_Paginator_Adapter_Interface) {
            $this->_adapter = $adapter;
        } else if ($adapter instanceof Zend_Paginator_AdapterAggregate) {
            $this->_adapter = $adapter->getPaginatorAdapter();
        } else {
            /**
             * @see Zend_Paginator_Exception
             */
            require_once 'Zend/Paginator/Exception.php';

            throw new Zend_Paginator_Exception(
                'Zend_Paginator only accepts instances of the type ' .
                'Zend_Paginator_Adapter_Interface or Zend_Paginator_AdapterAggregate.'
            );
        }

        $config = self::$_config;

        if ($config != null) {
            $setupMethods = array('ItemCountPerPage', 'PageRange');

            foreach ($setupMethods as $setupMethod) {
                $value = $config->get(strtolower($setupMethod));

                if ($value != null) {
                    $setupMethod = 'set' . $setupMethod;
                    $this->$setupMethod($value);
                }
            }
        }
    }

    /**
     * Serializes the object as a string.  Proxies to {@link render()}.
     *
     * @return string
     */
    public function __toString()
    {
        try {
            $return = $this->render();
            return $return;
        } catch (Exception $e) {
            trigger_error($e->getMessage(), E_USER_WARNING);
        }

        return '';
    }

    /**
     * Enables/Disables the cache for this instance
     *
     * @param bool $enable
     * @return Zend_Paginator
     */
    public function setCacheEnabled($enable)
    {
        $this->_cacheEnabled = (bool)$enable;
        return $this;
    }

    /**
     * Returns the number of pages.
     *
     * @return integer
     */
    public function count()
    {
        if (!$this->_pageCount) {
            $this->_pageCount = $this->_calculatePageCount();
        }

        return $this->_pageCount;
    }

    /**
     * Returns the total number of items available.
     *
     * @return integer
     */
    public function getTotalItemCount()
    {
        return count($this->getAdapter());
    }

    /**
     * Clear the page item cache.
     *
     * @param int $pageNumber
     * @return Zend_Paginator
     */
    public function clearPageItemCache($pageNumber = null)
    {
        if (!$this->_cacheEnabled()) {
            return $this;
        }

        if (null === $pageNumber) {
            foreach (self::$_cache->getIdsMatchingTags(array($this->_getCacheInternalId())) as $id) {
                if (preg_match('|'.self::CACHE_TAG_PREFIX."(\d+)_.*|", $id, $page)) {
                    self::$_cache->remove($this->_getCacheId($page[1]));
                }
            }
        } else {
            $cleanId = $this->_getCacheId($pageNumber);
            self::$_cache->remove($cleanId);
        }
        return $this;
    }

    /**
     * Returns the absolute item number for the specified item.
     *
     * @param  integer $relativeItemNumber Relative item number
     * @param  integer $pageNumber Page number
     * @return integer
     */
    public function getAbsoluteItemNumber($relativeItemNumber, $pageNumber = null)
    {
        $relativeItemNumber = $this->normalizeItemNumber($relativeItemNumber);

        if ($pageNumber == null) {
            $pageNumber = $this->getCurrentPageNumber();
        }

        $pageNumber = $this->normalizePageNumber($pageNumber);

        return (($pageNumber - 1) * $this->getItemCountPerPage()) + $relativeItemNumber;
    }

    /**
     * Returns the adapter.
     *
     * @return Zend_Paginator_Adapter_Interface
     */
    public function getAdapter()
    {
        return $this->_adapter;
    }

    /**
     * Returns the number of items for the current page.
     *
     * @return integer
     */
    public function getCurrentItemCount()
    {
        if ($this->_currentItemCount === null) {
            $this->_currentItemCount = $this->getItemCount($this->getCurrentItems());
        }

        return $this->_currentItemCount;
    }

    /**
     * Returns the items for the current page.
     *
     * @return Traversable
     */
    public function getCurrentItems()
    {
        if ($this->_currentItems === null) {
            $this->_currentItems = $this->getItemsByPage($this->getCurrentPageNumber());
        }

        return $this->_currentItems;
    }

    /**
     * Returns the current page number.
     *
     * @return integer
     */
    public function getCurrentPageNumber()
    {
        return $this->normalizePageNumber($this->_currentPageNumber);
    }

    /**
     * Sets the current page number.
     *
     * @param  integer $pageNumber Page number
     * @return Zend_Paginator $this
     */
    public function setCurrentPageNumber($pageNumber)
    {
        $this->_currentPageNumber = (integer) $pageNumber;
        $this->_currentItems      = null;
        $this->_currentItemCount  = null;

        return $this;
    }

    /**
     * Get the filter
     *
     * @return Zend_Filter_Interface
     */
    public function getFilter()
    {
        return $this->_filter;
    }

    /**
     * Set a filter chain
     *
     * @param Zend_Filter_Interface $filter
     * @return Zend_Paginator
     */
    public function setFilter(Zend_Filter_Interface $filter)
    {
        $this->_filter = $filter;

        return $this;
    }

    /**
     * Returns an item from a page.  The current page is used if there's no
     * page sepcified.
     *
     * @param  integer $itemNumber Item number (1 to itemCountPerPage)
     * @param  integer $pageNumber
     * @return mixed
     */
    public function getItem($itemNumber, $pageNumber = null)
    {
        if ($pageNumber == null) {
            $pageNumber = $this->getCurrentPageNumber();
        } else if ($pageNumber < 0) {
            $pageNumber = ($this->count() + 1) + $pageNumber;
        }

        $page = $this->getItemsByPage($pageNumber);
        $itemCount = $this->getItemCount($page);

        if ($itemCount == 0) {
            /**
             * @see Zend_Paginator_Exception
             */
            require_once 'Zend/Paginator/Exception.php';

            throw new Zend_Paginator_Exception('Page ' . $pageNumber . ' does not exist');
        }

        if ($itemNumber < 0) {
            $itemNumber = ($itemCount + 1) + $itemNumber;
        }

        $itemNumber = $this->normalizeItemNumber($itemNumber);

        if ($itemNumber > $itemCount) {
            /**
             * @see Zend_Paginator_Exception
             */
            require_once 'Zend/Paginator/Exception.php';

            throw new Zend_Paginator_Exception('Page ' . $pageNumber . ' does not'
                                             . ' contain item number ' . $itemNumber);
        }

        return $page[$itemNumber - 1];
    }

    /**
     * Returns the number of items per page.
     *
     * @return integer
     */
    public function getItemCountPerPage()
    {
        if (empty($this->_itemCountPerPage)) {
            $this->_itemCountPerPage = self::getDefaultItemCountPerPage();
        }

        return $this->_itemCountPerPage;
    }

    /**
     * Sets the number of items per page.
     *
     * @param  integer $itemCountPerPage
     * @return Zend_Paginator $this
     */
    public function setItemCountPerPage($itemCountPerPage = -1)
    {
        $this->_itemCountPerPage = (integer) $itemCountPerPage;
        if ($this->_itemCountPerPage < 1) {
            $this->_itemCountPerPage = $this->getTotalItemCount();
        }
        $this->_pageCount        = $this->_calculatePageCount();
        $this->_currentItems     = null;
        $this->_currentItemCount = null;

        return $this;
    }

    /**
     * Returns the number of items in a collection.
     *
     * @param  mixed $items Items
     * @return integer
     */
    public function getItemCount($items)
    {
        $itemCount = 0;

        if (is_array($items) || $items instanceof Countable) {
            $itemCount = count($items);
        } else { // $items is something like LimitIterator
            $itemCount = iterator_count($items);
        }

        return $itemCount;
    }

    /**
     * Returns the items for a given page.
     *
     * @return Traversable
     */
    public function getItemsByPage($pageNumber)
    {
        $pageNumber = $this->normalizePageNumber($pageNumber);

        if ($this->_cacheEnabled()) {
            $data = self::$_cache->load($this->_getCacheId($pageNumber));
            if ($data !== false) {
                return $data;
            }
        }

        $offset = ($pageNumber - 1) * $this->getItemCountPerPage();

        $items = $this->_adapter->getItems($offset, $this->getItemCountPerPage());

        $filter = $this->getFilter();

        if ($filter !== null) {
            $items = $filter->filter($items);
        }

        if (!$items instanceof Traversable) {
            $items = new ArrayIterator($items);
        }

        if ($this->_cacheEnabled()) {
            self::$_cache->save($items, $this->_getCacheId($pageNumber), array($this->_getCacheInternalId()));
        }

        return $items;
    }

    /**
     * Returns a foreach-compatible iterator.
     *
     * @return Traversable
     */
    public function getIterator()
    {
        return $this->getCurrentItems();
    }

    /**
     * Returns the page range (see property declaration above).
     *
     * @return integer
     */
    public function getPageRange()
    {
        if (null === $this->_pageRange) {
            $this->_pageRange = self::getDefaultPageRange();
        }

        return $this->_pageRange;
    }

    /**
     * Sets the page range (see property declaration above).
     *
     * @param  integer $pageRange
     * @return Zend_Paginator $this
     */
    public function setPageRange($pageRange)
    {
        $this->_pageRange = (integer) $pageRange;

        return $this;
    }

    /**
     * Returns the page collection.
     *
     * @param  string $scrollingStyle Scrolling style
     * @return array
     */
    public function getPages($scrollingStyle = null)
    {
        if ($this->_pages === null) {
            $this->_pages = $this->_createPages($scrollingStyle);
        }

        return $this->_pages;
    }

    /**
     * Returns a subset of pages within a given range.
     *
     * @param  integer $lowerBound Lower bound of the range
     * @param  integer $upperBound Upper bound of the range
     * @return array
     */
    public function getPagesInRange($lowerBound, $upperBound)
    {
        $lowerBound = $this->normalizePageNumber($lowerBound);
        $upperBound = $this->normalizePageNumber($upperBound);

        $pages = array();

        for ($pageNumber = $lowerBound; $pageNumber <= $upperBound; $pageNumber++) {
            $pages[$pageNumber] = $pageNumber;
        }

        return $pages;
    }

    /**
     * Returns the page item cache.
     *
     * @return array
     */
    public function getPageItemCache()
    {
        $data = array();
        if ($this->_cacheEnabled()) {
            foreach (self::$_cache->getIdsMatchingTags(array($this->_getCacheInternalId())) as $id) {
                    if (preg_match('|'.self::CACHE_TAG_PREFIX."(\d+)_.*|", $id, $page)) {
                        $data[$page[1]] = self::$_cache->load($this->_getCacheId($page[1]));
                    }
            }
        }
        return $data;
    }

    /**
     * Retrieves the view instance.  If none registered, attempts to pull f
     * rom ViewRenderer.
     *
     * @return Zend_View_Interface|null
     */
    public function getView()
    {
        if ($this->_view === null) {
            /**
             * @see Zend_Controller_Action_HelperBroker
             */
            require_once 'Zend/Controller/Action/HelperBroker.php';

            $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
            if ($viewRenderer->view === null) {
                $viewRenderer->initView();
            }
            $this->_view = $viewRenderer->view;
        }

        return $this->_view;
    }

    /**
     * Sets the view object.
     *
     * @param  Zend_View_Interface $view
     * @return Zend_Paginator
     */
    public function setView(Zend_View_Interface $view = null)
    {
        $this->_view = $view;

        return $this;
    }

    /**
     * Brings the item number in range of the page.
     *
     * @param  integer $itemNumber
     * @return integer
     */
    public function normalizeItemNumber($itemNumber)
    {
        $itemNumber = (integer) $itemNumber;

        if ($itemNumber < 1) {
            $itemNumber = 1;
        }

        if ($itemNumber > $this->getItemCountPerPage()) {
            $itemNumber = $this->getItemCountPerPage();
        }

        return $itemNumber;
    }

    /**
     * Brings the page number in range of the paginator.
     *
     * @param  integer $pageNumber
     * @return integer
     */
    public function normalizePageNumber($pageNumber)
    {
        $pageNumber = (integer) $pageNumber;

        if ($pageNumber < 1) {
            $pageNumber = 1;
        }

        $pageCount = $this->count();

        if ($pageCount > 0 && $pageNumber > $pageCount) {
            $pageNumber = $pageCount;
        }

        return $pageNumber;
    }

    /**
     * Renders the paginator.
     *
     * @param  Zend_View_Interface $view
     * @return string
     */
    public function render(Zend_View_Interface $view = null)
    {
        if (null !== $view) {
            $this->setView($view);
        }

        $view = $this->getView();

        return $view->paginationControl($this);
    }

    /**
     * Returns the items of the current page as JSON.
     *
     * @return string
     */
    public function toJson()
    {
        $currentItems = $this->getCurrentItems();

        if ($currentItems instanceof Zend_Db_Table_Rowset_Abstract) {
            return Zend_Json::encode($currentItems->toArray());
        } else {
            return Zend_Json::encode($currentItems);
        }
    }

    /**
     * Tells if there is an active cache object
     * and if the cache has not been desabled
     *
     * @return bool
     */
    protected function _cacheEnabled()
    {
        return ((self::$_cache !== null) && $this->_cacheEnabled);
    }

    /**
     * Makes an Id for the cache
     * Depends on the adapter object and the page number
     *
     * Used to store item in cache from that Paginator instance
     *  and that current page
     *
     * @param int $page
     * @return string
     */
    protected function _getCacheId($page = null)
    {
        if ($page === null) {
            $page = $this->getCurrentPageNumber();
        }
        return self::CACHE_TAG_PREFIX . $page . '_' . $this->_getCacheInternalId();
    }

    /**
     * Get the internal cache id
     * Depends on the adapter and the item count per page
     *
     * Used to tag that unique Paginator instance in cache
     *
     * @return string
     */
    protected function _getCacheInternalId()
    {
        return md5(serialize(array(
            $this->getAdapter(),
            $this->getItemCountPerPage()
        )));
    }

    /**
     * Calculates the page count.
     *
     * @return integer
     */
    protected function _calculatePageCount()
    {
        return (integer) ceil($this->getAdapter()->count() / $this->getItemCountPerPage());
    }

    /**
     * Creates the page collection.
     *
     * @param  string $scrollingStyle Scrolling style
     * @return stdClass
     */
    protected function _createPages($scrollingStyle = null)
    {
        $pageCount         = $this->count();
        $currentPageNumber = $this->getCurrentPageNumber();

        $pages = new stdClass();
        $pages->pageCount        = $pageCount;
        $pages->itemCountPerPage = $this->getItemCountPerPage();
        $pages->first            = 1;
        $pages->current          = $currentPageNumber;
        $pages->last             = $pageCount;

        // Previous and next
        if ($currentPageNumber - 1 > 0) {
            $pages->previous = $currentPageNumber - 1;
        }

        if ($currentPageNumber + 1 <= $pageCount) {
            $pages->next = $currentPageNumber + 1;
        }

        // Pages in range
        $scrollingStyle = $this->_loadScrollingStyle($scrollingStyle);
        $pages->pagesInRange     = $scrollingStyle->getPages($this);
        $pages->firstPageInRange = min($pages->pagesInRange);
        $pages->lastPageInRange  = max($pages->pagesInRange);

        // Item numbers
        if ($this->getCurrentItems() !== null) {
            $pages->currentItemCount = $this->getCurrentItemCount();
            $pages->itemCountPerPage = $this->getItemCountPerPage();
            $pages->totalItemCount   = $this->getTotalItemCount();
            $pages->firstItemNumber  = (($currentPageNumber - 1) * $this->getItemCountPerPage()) + 1;
            $pages->lastItemNumber   = $pages->firstItemNumber + $pages->currentItemCount - 1;
        }

        return $pages;
    }

    /**
     * Loads a scrolling style.
     *
     * @param string $scrollingStyle
     * @return Zend_Paginator_ScrollingStyle_Interface
     */
    protected function _loadScrollingStyle($scrollingStyle = null)
    {
        if ($scrollingStyle === null) {
            $scrollingStyle = self::$_defaultScrollingStyle;
        }

        switch (strtolower(gettype($scrollingStyle))) {
            case 'object':
                if (!$scrollingStyle instanceof Zend_Paginator_ScrollingStyle_Interface) {
                    /**
                     * @see Zend_View_Exception
                     */
                    require_once 'Zend/View/Exception.php';

                    throw new Zend_View_Exception('Scrolling style must implement ' .
                        'Zend_Paginator_ScrollingStyle_Interface');
                }

                return $scrollingStyle;

            case 'string':
                $className = self::getScrollingStyleLoader()->load($scrollingStyle);

                return new $className();

            case 'null':
                // Fall through to default case

            default:
                /**
                 * @see Zend_View_Exception
                 */
                require_once 'Zend/View/Exception.php';

                throw new Zend_View_Exception('Scrolling style must be a class ' .
                    'name or object implementing Zend_Paginator_ScrollingStyle_Interface');
        }
    }
}

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_Json
 * @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 24421 2011-08-28 15:41:18Z adamlundrigan $
 */

/**
 * Zend_Json_Expr.
 *
 * @see Zend_Json_Expr
 */
require_once 'Zend/Json/Expr.php';

/**
 * Class for encoding to and decoding from JSON.
 *
 * @category   Zend
 * @package    Zend_Json
 * @uses       Zend_Json_Expr
 * @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_Json
{
    /**
     * How objects should be encoded -- arrays or as StdClass. TYPE_ARRAY is 1
     * so that it is a boolean true value, allowing it to be used with
     * ext/json's functions.
     */
    const TYPE_ARRAY  = 1;
    const TYPE_OBJECT = 0;

     /**
      * To check the allowed nesting depth of the XML tree during xml2json conversion.
      *
      * @var int
      */
    public static $maxRecursionDepthAllowed=25;

    /**
     * @var bool
     */
    public static $useBuiltinEncoderDecoder = false;

    /**
     * Decodes the given $encodedValue string which is
     * encoded in the JSON format
     *
     * Uses ext/json's json_decode if available.
     *
     * @param string $encodedValue Encoded in JSON format
     * @param int $objectDecodeType Optional; flag indicating how to decode
     * objects. See {@link Zend_Json_Decoder::decode()} for details.
     * @return mixed
     */
    public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
    {
        $encodedValue = (string) $encodedValue;
        if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
            $decode = json_decode($encodedValue, $objectDecodeType);

            // php < 5.3
            if (!function_exists('json_last_error')) {
                if ($decode === $encodedValue) {
                    require_once 'Zend/Json/Exception.php';
                    throw new Zend_Json_Exception('Decoding failed');
                }
            // php >= 5.3
            } elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) {
                require_once 'Zend/Json/Exception.php';
                switch ($jsonLastErr) {
                    case JSON_ERROR_DEPTH:
                        throw new Zend_Json_Exception('Decoding failed: Maximum stack depth exceeded');
                    case JSON_ERROR_CTRL_CHAR:
                        throw new Zend_Json_Exception('Decoding failed: Unexpected control character found');
                    case JSON_ERROR_SYNTAX:
                        throw new Zend_Json_Exception('Decoding failed: Syntax error');
                    default:
                        throw new Zend_Json_Exception('Decoding failed');
                }
            }

            return $decode;
        }

        require_once 'Zend/Json/Decoder.php';
        return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType);
    }

    /**
     * Encode the mixed $valueToEncode into the JSON format
     *
     * Encodes using ext/json's json_encode() if available.
     *
     * NOTE: Object should not contain cycles; the JSON format
     * does not allow object reference.
     *
     * NOTE: Only public variables will be encoded
     *
     * NOTE: Encoding native javascript expressions are possible using Zend_Json_Expr.
     *       You can enable this by setting $options['enableJsonExprFinder'] = true
     *
     * @see Zend_Json_Expr
     *
     * @param  mixed $valueToEncode
     * @param  boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
     * @param  array $options Additional options used during encoding
     * @return string JSON encoded object
     */
    public static function encode($valueToEncode, $cycleCheck = false, $options = array())
    {
        if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
            return $valueToEncode->toJson();
        }

        // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
        $javascriptExpressions = array();
        if(isset($options['enableJsonExprFinder'])
           && ($options['enableJsonExprFinder'] == true)
        ) {
            /**
             * @see Zend_Json_Encoder
             */
            require_once "Zend/Json/Encoder.php";
            $valueToEncode = self::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
        }

        // Encoding
        if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
            $encodedResult = json_encode($valueToEncode);
        } else {
            require_once 'Zend/Json/Encoder.php';
            $encodedResult = Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);
        }

        //only do post-proccessing to revert back the Zend_Json_Expr if any.
        if (count($javascriptExpressions) > 0) {
            $count = count($javascriptExpressions);
            for($i = 0; $i < $count; $i++) {
                $magicKey = $javascriptExpressions[$i]['magicKey'];
                $value    = $javascriptExpressions[$i]['value'];

                $encodedResult = str_replace(
                    //instead of replacing "key:magicKey", we replace directly magicKey by value because "key" never changes.
                    '"' . $magicKey . '"',
                    $value,
                    $encodedResult
                );
            }
        }

         return $encodedResult;
    }

    /**
     * Check & Replace Zend_Json_Expr for tmp ids in the valueToEncode
     *
     * Check if the value is a Zend_Json_Expr, and if replace its value
     * with a magic key and save the javascript expression in an array.
     *
     * NOTE this method is recursive.
     *
     * NOTE: This method is used internally by the encode method.
     *
     * @see encode
     * @param array|object|Zend_Json_Expr $value a string - object property to be encoded
     * @param array $javascriptExpressions
     * @param null $currentKey
     *
     * @internal param mixed $valueToCheck
     * @return void
     */
    protected static function _recursiveJsonExprFinder(&$value, array &$javascriptExpressions, $currentKey = null)
    {
         if ($value instanceof Zend_Json_Expr) {
            // TODO: Optimize with ascii keys, if performance is bad
            $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
            $javascriptExpressions[] = array(

                //if currentKey is integer, encodeUnicodeString call is not required.
                "magicKey" => (is_int($currentKey)) ? $magicKey : Zend_Json_Encoder::encodeUnicodeString($magicKey),
                "value"    => $value->__toString(),
            );
            $value = $magicKey;
        } elseif (is_array($value)) {
            foreach ($value as $k => $v) {
                $value[$k] = self::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
            }
        } elseif (is_object($value)) {
            foreach ($value as $k => $v) {
                $value->$k = self::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
            }
        }
        return $value;
    }

    /**
     * Return the value of an XML attribute text or the text between
     * the XML tags
     *
     * In order to allow Zend_Json_Expr from xml, we check if the node
     * matchs the pattern that try to detect if it is a new Zend_Json_Expr
     * if it matches, we return a new Zend_Json_Expr instead of a text node
     *
     * @param SimpleXMLElement $simpleXmlElementObject
     * @return Zend_Json_Expr|string
     */
    protected static function _getXmlValue($simpleXmlElementObject) {
        $pattern = '/^[\s]*new Zend_Json_Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/';
        $matchings = array();
        $match = preg_match ($pattern, $simpleXmlElementObject, $matchings);
        if ($match) {
            return new Zend_Json_Expr($matchings[1]);
        } else {
            return (trim(strval($simpleXmlElementObject)));
        }
    }
    /**
     * _processXml - Contains the logic for xml2json
     *
     * The logic in this function is a recursive one.
     *
     * The main caller of this function (i.e. fromXml) needs to provide
     * only the first two parameters i.e. the SimpleXMLElement object and
     * the flag for ignoring or not ignoring XML attributes. The third parameter
     * will be used internally within this function during the recursive calls.
     *
     * This function converts the SimpleXMLElement object into a PHP array by
     * calling a recursive (protected static) function in this class. Once all
     * the XML elements are stored in the PHP array, it is returned to the caller.
     *
     * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit.
     *
     * @param SimpleXMLElement $simpleXmlElementObject
     * @param boolean $ignoreXmlAttributes
     * @param integer $recursionDepth
     * @return array
     */
    protected static function _processXml($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0)
    {
        // Keep an eye on how deeply we are involved in recursion.
        if ($recursionDepth > self::$maxRecursionDepthAllowed) {
            // XML tree is too deep. Exit now by throwing an exception.
            require_once 'Zend/Json/Exception.php';
            throw new Zend_Json_Exception(
                "Function _processXml exceeded the allowed recursion depth of " .
                self::$maxRecursionDepthAllowed);
        } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)

        $children = $simpleXmlElementObject->children();
        $name = $simpleXmlElementObject->getName();
        $value = self::_getXmlValue($simpleXmlElementObject);
        $attributes = (array) $simpleXmlElementObject->attributes();

        if (count($children) == 0) {
            if (!empty($attributes) && !$ignoreXmlAttributes) {
                foreach ($attributes['@attributes'] as $k => $v) {
                    $attributes['@attributes'][$k]= self::_getXmlValue($v);
                }
                if (!empty($value)) {
                    $attributes['@text'] = $value;
                }
                return array($name => $attributes);
            } else {
               return array($name => $value);
            }
        } else {
            $childArray= array();
            foreach ($children as $child) {
                $childname = $child->getName();
                $element = self::_processXml($child,$ignoreXmlAttributes,$recursionDepth+1);
                if (array_key_exists($childname, $childArray)) {
                    if (empty($subChild[$childname])) {
                        $childArray[$childname] = array($childArray[$childname]);
                        $subChild[$childname] = true;
                    }
                    $childArray[$childname][] = $element[$childname];
                } else {
                    $childArray[$childname] = $element[$childname];
                }
            }
            if (!empty($attributes) && !$ignoreXmlAttributes) {
                foreach ($attributes['@attributes'] as $k => $v) {
                    $attributes['@attributes'][$k] = self::_getXmlValue($v);
                }
                $childArray['@attributes'] = $attributes['@attributes'];
            }
            if (!empty($value)) {
                $childArray['@text'] = $value;
            }
            return array($name => $childArray);
        }
    }

    /**
     * fromXml - Converts XML to JSON
     *
     * Converts a XML formatted string into a JSON formatted string.
     * The value returned will be a string in JSON format.
     *
     * The caller of this function needs to provide only the first parameter,
     * which is an XML formatted String. The second parameter is optional, which
     * lets the user to select if the XML attributes in the input XML string
     * should be included or ignored in xml2json conversion.
     *
     * This function converts the XML formatted string into a PHP array by
     * calling a recursive (protected static) function in this class. Then, it
     * converts that PHP array into JSON by calling the "encode" static funcion.
     *
     * Throws a Zend_Json_Exception if the input not a XML formatted string.
     * NOTE: Encoding native javascript expressions via Zend_Json_Expr is not possible.
     *
     * @static
     * @access public
     * @param string $xmlStringContents XML String to be converted
     * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
     * the xml2json conversion process.
     * @return mixed - JSON formatted string on success
     * @throws Zend_Json_Exception
     */
    public static function fromXml($xmlStringContents, $ignoreXmlAttributes=true)
    {
        // Load the XML formatted string into a Simple XML Element object.
        $simpleXmlElementObject = simplexml_load_string($xmlStringContents);

        // If it is not a valid XML content, throw an exception.
        if ($simpleXmlElementObject == null) {
            require_once 'Zend/Json/Exception.php';
            throw new Zend_Json_Exception('Function fromXml was called with an invalid XML formatted string.');
        } // End of if ($simpleXmlElementObject == null)

        $resultArray = null;

        // Call the recursive function to convert the XML into a PHP array.
        $resultArray = self::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);

        // Convert the PHP array to JSON using Zend_Json encode method.
        // It is just that simple.
        $jsonStringOutput = self::encode($resultArray);
        return($jsonStringOutput);
    }

    /**
     * Pretty-print JSON string
     *
     * Use 'format' option to select output format - currently html and txt supported, txt is default
     * Use 'indent' option to override the indentation string set in the format - by default for the 'txt' format it's a tab
     *
     * @param string $json Original JSON string
     * @param array $options Encoding options
     * @return string
     */
    public static function prettyPrint($json, $options = array())
    {
        $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
        $result = '';
        $indent = 0;

        $format= 'txt';

        $ind = "\t";

        if (isset($options['format'])) {
            $format = $options['format'];
        }

        switch ($format) {
            case 'html':
                $lineBreak = '<br />';
                $ind = '    ';
                break;
            default:
            case 'txt':
                $lineBreak = "\n";
                $ind = "\t";
                break;
        }

        // override the defined indent setting with the supplied option
        if (isset($options['indent'])) {
            $ind = $options['indent'];
        }

        $inLiteral = false;
        foreach($tokens as $token) {
            if($token == '') {
                continue;
            }

            $prefix = str_repeat($ind, $indent);
            if (!$inLiteral && ($token == '{' || $token == '[')) {
                $indent++;
                if (($result != '') && ($result[(strlen($result)-1)] == $lineBreak)) {
                    $result .= $prefix;
                }
                $result .= $token . $lineBreak;
            } elseif (!$inLiteral && ($token == '}' || $token == ']')) {
                $indent--;
                $prefix = str_repeat($ind, $indent);
                $result .= $lineBreak . $prefix . $token;
            } elseif (!$inLiteral && $token == ',') {
                $result .= $token . $lineBreak;
            } else {
                $result .= ( $inLiteral ? '' : $prefix ) . $token;

                // Count # of unescaped double-quotes in token, subtract # of
                // escaped double-quotes and if the result is odd then we are
                // inside a string literal
                if ((substr_count($token, "\"")-substr_count($token, "\\\"")) % 2 != 0) {
                    $inLiteral = !$inLiteral;
                }
            }
        }
        return $result;
   }
}