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_Date
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @version    $Id: DateObject.php 23775 2011-03-01 17:25:24Z ralph $
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/**
 * @category   Zend
 * @package    Zend_Date
 * @subpackage Zend_Date_DateObject
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Date_DateObject {

    /**
     * UNIX Timestamp
     */
    private   $_unixTimestamp;
    protected static $_cache         = null;
    protected static $_cacheTags     = false;
    protected static $_defaultOffset = 0;

    /**
     * active timezone
     */
    private   $_timezone    = 'UTC';
    private   $_offset      = 0;
    private   $_syncronised = 0;

    // turn off DST correction if UTC or GMT
    protected $_dst         = true;

    /**
     * Table of Monthdays
     */
    private static $_monthTable = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    /**
     * Table of Years
     */
    private static $_yearTable = array(
        1970 => 0,            1960 => -315619200,   1950 => -631152000,
        1940 => -946771200,   1930 => -1262304000,  1920 => -1577923200,
        1910 => -1893456000,  1900 => -2208988800,  1890 => -2524521600,
        1880 => -2840140800,  1870 => -3155673600,  1860 => -3471292800,
        1850 => -3786825600,  1840 => -4102444800,  1830 => -4417977600,
        1820 => -4733596800,  1810 => -5049129600,  1800 => -5364662400,
        1790 => -5680195200,  1780 => -5995814400,  1770 => -6311347200,
        1760 => -6626966400,  1750 => -6942499200,  1740 => -7258118400,
        1730 => -7573651200,  1720 => -7889270400,  1710 => -8204803200,
        1700 => -8520336000,  1690 => -8835868800,  1680 => -9151488000,
        1670 => -9467020800,  1660 => -9782640000,  1650 => -10098172800,
        1640 => -10413792000, 1630 => -10729324800, 1620 => -11044944000,
        1610 => -11360476800, 1600 => -11676096000);

    /**
     * Set this object to have a new UNIX timestamp.
     *
     * @param  string|integer  $timestamp  OPTIONAL timestamp; defaults to local time using time()
     * @return string|integer  old timestamp
     * @throws Zend_Date_Exception
     */
    protected function setUnixTimestamp($timestamp = null)
    {
        $old = $this->_unixTimestamp;

        if (is_numeric($timestamp)) {
            $this->_unixTimestamp = $timestamp;
        } else if ($timestamp === null) {
            $this->_unixTimestamp = time();
        } else {
            require_once 'Zend/Date/Exception.php';
            throw new Zend_Date_Exception('\'' . $timestamp . '\' is not a valid UNIX timestamp', 0, null, $timestamp);
        }

        return $old;
    }

    /**
     * Returns this object's UNIX timestamp
     * A timestamp greater then the integer range will be returned as string
     * This function does not return the timestamp as object. Use copy() instead.
     *
     * @return  integer|string  timestamp
     */
    protected function getUnixTimestamp()
    {
        if ($this->_unixTimestamp === intval($this->_unixTimestamp)) {
            return (int) $this->_unixTimestamp;
        } else {
            return (string) $this->_unixTimestamp;
        }
    }

    /**
     * Internal function.
     * Returns time().  This method exists to allow unit tests to work-around methods that might otherwise
     * be hard-coded to use time().  For example, this makes it possible to test isYesterday() in Date.php.
     *
     * @param   integer  $sync      OPTIONAL time syncronisation value
     * @return  integer  timestamp
     */
    protected function _getTime($sync = null)
    {
        if ($sync !== null) {
            $this->_syncronised = round($sync);
        }
        return (time() + $this->_syncronised);
    }

    /**
     * Internal mktime function used by Zend_Date.
     * The timestamp returned by mktime() can exceed the precision of traditional UNIX timestamps,
     * by allowing PHP to auto-convert to using a float value.
     *
     * Returns a timestamp relative to 1970/01/01 00:00:00 GMT/UTC.
     * DST (Summer/Winter) is depriciated since php 5.1.0.
     * Year has to be 4 digits otherwise it would be recognised as
     * year 70 AD instead of 1970 AD as expected !!
     *
     * @param  integer  $hour
     * @param  integer  $minute
     * @param  integer  $second
     * @param  integer  $month
     * @param  integer  $day
     * @param  integer  $year
     * @param  boolean  $gmt     OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date
     * @return  integer|float  timestamp (number of seconds elapsed relative to 1970/01/01 00:00:00 GMT/UTC)
     */
    protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = false)
    {
        // complete date but in 32bit timestamp - use PHP internal
        if ((1901 < $year) and ($year < 2038)) {

            $oldzone = @date_default_timezone_get();
            // Timezone also includes DST settings, therefor substracting the GMT offset is not enough
            // We have to set the correct timezone to get the right value
            if (($this->_timezone != $oldzone) and ($gmt === false)) {
                date_default_timezone_set($this->_timezone);
            }
            $result = ($gmt) ? @gmmktime($hour, $minute, $second, $month, $day, $year)
                             :   @mktime($hour, $minute, $second, $month, $day, $year);
            date_default_timezone_set($oldzone);

            return $result;
        }

        if ($gmt !== true) {
            $second += $this->_offset;
        }

        if (isset(self::$_cache)) {
            $id = strtr('Zend_DateObject_mkTime_' . $this->_offset . '_' . $year.$month.$day.'_'.$hour.$minute.$second . '_'.(int)$gmt, '-','_');
            if ($result = self::$_cache->load($id)) {
                return unserialize($result);
            }
        }

        // date to integer
        $day   = intval($day);
        $month = intval($month);
        $year  = intval($year);

        // correct months > 12 and months < 1
        if ($month > 12) {
            $overlap = floor($month / 12);
            $year   += $overlap;
            $month  -= $overlap * 12;
        } else {
            $overlap = ceil((1 - $month) / 12);
            $year   -= $overlap;
            $month  += $overlap * 12;
        }

        $date = 0;
        if ($year >= 1970) {

            // Date is after UNIX epoch
            // go through leapyears
            // add months from latest given year
            for ($count = 1970; $count <= $year; $count++) {

                $leapyear = self::isYearLeapYear($count);
                if ($count < $year) {

                    $date += 365;
                    if ($leapyear === true) {
                        $date++;
                    }

                } else {

                    for ($mcount = 0; $mcount < ($month - 1); $mcount++) {
                        $date += self::$_monthTable[$mcount];
                        if (($leapyear === true) and ($mcount == 1)) {
                            $date++;
                        }

                    }
                }
            }

            $date += $day - 1;
            $date = (($date * 86400) + ($hour * 3600) + ($minute * 60) + $second);
        } else {

            // Date is before UNIX epoch
            // go through leapyears
            // add months from latest given year
            for ($count = 1969; $count >= $year; $count--) {

                $leapyear = self::isYearLeapYear($count);
                if ($count > $year)
                {
                    $date += 365;
                    if ($leapyear === true)
                        $date++;
                } else {

                    for ($mcount = 11; $mcount > ($month - 1); $mcount--) {
                        $date += self::$_monthTable[$mcount];
                        if (($leapyear === true) and ($mcount == 2)) {
                            $date++;
                        }

                    }
                }
            }

            $date += (self::$_monthTable[$month - 1] - $day);
            $date = -(($date * 86400) + (86400 - (($hour * 3600) + ($minute * 60) + $second)));

            // gregorian correction for 5.Oct.1582
            if ($date < -12220185600) {
                $date += 864000;
            } else if ($date < -12219321600) {
                $date  = -12219321600;
            }
        }

        if (isset(self::$_cache)) {
            if (self::$_cacheTags) {
                self::$_cache->save( serialize($date), $id, array('Zend_Date'));
            } else {
                self::$_cache->save( serialize($date), $id);
            }
        }

        return $date;
    }

    /**
     * Returns true, if given $year is a leap year.
     *
     * @param  integer  $year
     * @return boolean  true, if year is leap year
     */
    protected static function isYearLeapYear($year)
    {
        // all leapyears can be divided through 4
        if (($year % 4) != 0) {
            return false;
        }

        // all leapyears can be divided through 400
        if ($year % 400 == 0) {
            return true;
        } else if (($year > 1582) and ($year % 100 == 0)) {
            return false;
        }

        return true;
    }

    /**
     * Internal mktime function used by Zend_Date for handling 64bit timestamps.
     *
     * Returns a formatted date for a given timestamp.
     *
     * @param  string   $format     format for output
     * @param  mixed    $timestamp
     * @param  boolean  $gmt        OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date
     * @return string
     */
    protected function date($format, $timestamp = null, $gmt = false)
    {
        $oldzone = @date_default_timezone_get();
        if ($this->_timezone != $oldzone) {
            date_default_timezone_set($this->_timezone);
        }

        if ($timestamp === null) {
            $result = ($gmt) ? @gmdate($format) : @date($format);
            date_default_timezone_set($oldzone);
            return $result;
        }

        if (abs($timestamp) <= 0x7FFFFFFF) {
            $result = ($gmt) ? @gmdate($format, $timestamp) : @date($format, $timestamp);
            date_default_timezone_set($oldzone);
            return $result;
        }

        $jump      = false;
        $origstamp = $timestamp;
        if (isset(self::$_cache)) {
            $idstamp = strtr('Zend_DateObject_date_' . $this->_offset . '_'. $timestamp . '_'.(int)$gmt, '-','_');
            if ($result2 = self::$_cache->load($idstamp)) {
                $timestamp = unserialize($result2);
                $jump = true;
            }
        }

        // check on false or null alone fails
        if (empty($gmt) and empty($jump)) {
            $tempstamp = $timestamp;
            if ($tempstamp > 0) {
                while (abs($tempstamp) > 0x7FFFFFFF) {
                    $tempstamp -= (86400 * 23376);
                }

                $dst = date("I", $tempstamp);
                if ($dst === 1) {
                    $timestamp += 3600;
                }

                $temp       = date('Z', $tempstamp);
                $timestamp += $temp;
            }

            if (isset(self::$_cache)) {
                if (self::$_cacheTags) {
                    self::$_cache->save( serialize($timestamp), $idstamp, array('Zend_Date'));
                } else {
                    self::$_cache->save( serialize($timestamp), $idstamp);
                }
            }
        }

        if (($timestamp < 0) and ($gmt !== true)) {
            $timestamp -= $this->_offset;
        }

        date_default_timezone_set($oldzone);
        $date   = $this->getDateParts($timestamp, true);
        $length = strlen($format);
        $output = '';

        for ($i = 0; $i < $length; $i++) {
            switch($format[$i]) {
                // day formats
                case 'd':  // day of month, 2 digits, with leading zero, 01 - 31
                    $output .= (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']);
                    break;

                case 'D':  // day of week, 3 letters, Mon - Sun
                    $output .= date('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday'])));
                    break;

                case 'j':  // day of month, without leading zero, 1 - 31
                    $output .= $date['mday'];
                    break;

                case 'l':  // day of week, full string name, Sunday - Saturday
                    $output .= date('l', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday'])));
                    break;

                case 'N':  // ISO 8601 numeric day of week, 1 - 7
                    $day = self::dayOfWeek($date['year'], $date['mon'], $date['mday']);
                    if ($day == 0) {
                        $day = 7;
                    }
                    $output .= $day;
                    break;

                case 'S':  // english suffix for day of month, st nd rd th
                    if (($date['mday'] % 10) == 1) {
                        $output .= 'st';
                    } else if ((($date['mday'] % 10) == 2) and ($date['mday'] != 12)) {
                        $output .= 'nd';
                    } else if (($date['mday'] % 10) == 3) {
                        $output .= 'rd';
                    } else {
                        $output .= 'th';
                    }
                    break;

                case 'w':  // numeric day of week, 0 - 6
                    $output .= self::dayOfWeek($date['year'], $date['mon'], $date['mday']);
                    break;

                case 'z':  // day of year, 0 - 365
                    $output .= $date['yday'];
                    break;

                // week formats
                case 'W':  // ISO 8601, week number of year
                    $output .= $this->weekNumber($date['year'], $date['mon'], $date['mday']);
                    break;

                // month formats
                case 'F':  // string month name, january - december
                    $output .= date('F', mktime(0, 0, 0, $date['mon'], 2, 1971));
                    break;

                case 'm':  // number of month, with leading zeros, 01 - 12
                    $output .= (($date['mon'] < 10) ? '0' . $date['mon'] : $date['mon']);
                    break;

                case 'M':  // 3 letter month name, Jan - Dec
                    $output .= date('M',mktime(0, 0, 0, $date['mon'], 2, 1971));
                    break;

                case 'n':  // number of month, without leading zeros, 1 - 12
                    $output .= $date['mon'];
                    break;

                case 't':  // number of day in month
                    $output .= self::$_monthTable[$date['mon'] - 1];
                    break;

                // year formats
                case 'L':  // is leap year ?
                    $output .= (self::isYearLeapYear($date['year'])) ? '1' : '0';
                    break;

                case 'o':  // ISO 8601 year number
                    $week = $this->weekNumber($date['year'], $date['mon'], $date['mday']);
                    if (($week > 50) and ($date['mon'] == 1)) {
                        $output .= ($date['year'] - 1);
                    } else {
                        $output .= $date['year'];
                    }
                    break;

                case 'Y':  // year number, 4 digits
                    $output .= $date['year'];
                    break;

                case 'y':  // year number, 2 digits
                    $output .= substr($date['year'], strlen($date['year']) - 2, 2);
                    break;

                // time formats
                case 'a':  // lower case am/pm
                    $output .= (($date['hours'] >= 12) ? 'pm' : 'am');
                    break;

                case 'A':  // upper case am/pm
                    $output .= (($date['hours'] >= 12) ? 'PM' : 'AM');
                    break;

                case 'B':  // swatch internet time
                    $dayseconds = ($date['hours'] * 3600) + ($date['minutes'] * 60) + $date['seconds'];
                    if ($gmt === true) {
                        $dayseconds += 3600;
                    }
                    $output .= (int) (($dayseconds % 86400) / 86.4);
                    break;

                case 'g':  // hours without leading zeros, 12h format
                    if ($date['hours'] > 12) {
                        $hour = $date['hours'] - 12;
                    } else {
                        if ($date['hours'] == 0) {
                            $hour = '12';
                        } else {
                            $hour = $date['hours'];
                        }
                    }
                    $output .= $hour;
                    break;

                case 'G':  // hours without leading zeros, 24h format
                    $output .= $date['hours'];
                    break;

                case 'h':  // hours with leading zeros, 12h format
                    if ($date['hours'] > 12) {
                        $hour = $date['hours'] - 12;
                    } else {
                        if ($date['hours'] == 0) {
                            $hour = '12';
                        } else {
                            $hour = $date['hours'];
                        }
                    }
                    $output .= (($hour < 10) ? '0'.$hour : $hour);
                    break;

                case 'H':  // hours with leading zeros, 24h format
                    $output .= (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']);
                    break;

                case 'i':  // minutes with leading zeros
                    $output .= (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']);
                    break;

                case 's':  // seconds with leading zeros
                    $output .= (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']);
                    break;

                // timezone formats
                case 'e':  // timezone identifier
                    if ($gmt === true) {
                        $output .= gmdate('e', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    } else {
                        $output .=   date('e', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    }
                    break;

                case 'I':  // daylight saving time or not
                    if ($gmt === true) {
                        $output .= gmdate('I', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    } else {
                        $output .=   date('I', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    }
                    break;

                case 'O':  // difference to GMT in hours
                    $gmtstr = ($gmt === true) ? 0 : $this->getGmtOffset();
                    $output .= sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36);
                    break;

                case 'P':  // difference to GMT with colon
                    $gmtstr = ($gmt === true) ? 0 : $this->getGmtOffset();
                    $gmtstr = sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36);
                    $output = $output . substr($gmtstr, 0, 3) . ':' . substr($gmtstr, 3);
                    break;

                case 'T':  // timezone settings
                    if ($gmt === true) {
                        $output .= gmdate('T', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    } else {
                        $output .=   date('T', mktime($date['hours'], $date['minutes'], $date['seconds'],
                                                      $date['mon'], $date['mday'], 2000));
                    }
                    break;

                case 'Z':  // timezone offset in seconds
                    $output .= ($gmt === true) ? 0 : -$this->getGmtOffset();
                    break;

                // complete time formats
                case 'c':  // ISO 8601 date format
                    $difference = $this->getGmtOffset();
                    $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36);
                    $difference = substr($difference, 0, 3) . ':' . substr($difference, 3);
                    $output .= $date['year'] . '-'
                             . (($date['mon']     < 10) ? '0' . $date['mon']     : $date['mon'])     . '-'
                             . (($date['mday']    < 10) ? '0' . $date['mday']    : $date['mday'])    . 'T'
                             . (($date['hours']   < 10) ? '0' . $date['hours']   : $date['hours'])   . ':'
                             . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':'
                             . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds'])
                             . $difference;
                    break;

                case 'r':  // RFC 2822 date format
                    $difference = $this->getGmtOffset();
                    $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36);
                    $output .= gmdate('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday']))) . ', '
                             . (($date['mday']    < 10) ? '0' . $date['mday']    : $date['mday'])    . ' '
                             . date('M', mktime(0, 0, 0, $date['mon'], 2, 1971)) . ' '
                             . $date['year'] . ' '
                             . (($date['hours']   < 10) ? '0' . $date['hours']   : $date['hours'])   . ':'
                             . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':'
                             . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']) . ' '
                             . $difference;
                    break;

                case 'U':  // Unix timestamp
                    $output .= $origstamp;
                    break;

                // special formats
                case "\\":  // next letter to print with no format
                    $i++;
                    if ($i < $length) {
                        $output .= $format[$i];
                    }
                    break;

                default:  // letter is no format so add it direct
                    $output .= $format[$i];
                    break;
            }
        }

        return (string) $output;
    }

    /**
     * Returns the day of week for a Gregorian calendar date.
     * 0 = sunday, 6 = saturday
     *
     * @param  integer  $year
     * @param  integer  $month
     * @param  integer  $day
     * @return integer  dayOfWeek
     */
    protected static function dayOfWeek($year, $month, $day)
    {
        if ((1901 < $year) and ($year < 2038)) {
            return (int) date('w', mktime(0, 0, 0, $month, $day, $year));
        }

        // gregorian correction
        $correction = 0;
        if (($year < 1582) or (($year == 1582) and (($month < 10) or (($month == 10) && ($day < 15))))) {
            $correction = 3;
        }

        if ($month > 2) {
            $month -= 2;
        } else {
            $month += 10;
            $year--;
        }

        $day  = floor((13 * $month - 1) / 5) + $day + ($year % 100) + floor(($year % 100) / 4);
        $day += floor(($year / 100) / 4) - 2 * floor($year / 100) + 77 + $correction;

        return (int) ($day - 7 * floor($day / 7));
    }

    /**
     * Internal getDateParts function for handling 64bit timestamps, similar to:
     * http://www.php.net/getdate
     *
     * Returns an array of date parts for $timestamp, relative to 1970/01/01 00:00:00 GMT/UTC.
     *
     * $fast specifies ALL date parts should be returned (slower)
     * Default is false, and excludes $dayofweek, weekday, month and timestamp from parts returned.
     *
     * @param   mixed    $timestamp
     * @param   boolean  $fast   OPTIONAL defaults to fast (false), resulting in fewer date parts
     * @return  array
     */
    protected function getDateParts($timestamp = null, $fast = null)
    {

        // actual timestamp
        if (!is_numeric($timestamp)) {
            return getdate();
        }

        // 32bit timestamp
        if (abs($timestamp) <= 0x7FFFFFFF) {
            return @getdate((int) $timestamp);
        }

        if (isset(self::$_cache)) {
            $id = strtr('Zend_DateObject_getDateParts_' . $timestamp.'_'.(int)$fast, '-','_');
            if ($result = self::$_cache->load($id)) {
                return unserialize($result);
            }
        }

        $otimestamp = $timestamp;
        $numday = 0;
        $month = 0;
        // gregorian correction
        if ($timestamp < -12219321600) {
            $timestamp -= 864000;
        }

        // timestamp lower 0
        if ($timestamp < 0) {
            $sec = 0;
            $act = 1970;

            // iterate through 10 years table, increasing speed
            foreach(self::$_yearTable as $year => $seconds) {
                if ($timestamp >= $seconds) {
                    $i = $act;
                    break;
                }
                $sec = $seconds;
                $act = $year;
            }

            $timestamp -= $sec;
            if (!isset($i)) {
                $i = $act;
            }

            // iterate the max last 10 years
            do {
                --$i;
                $day = $timestamp;

                $timestamp += 31536000;
                $leapyear = self::isYearLeapYear($i);
                if ($leapyear === true) {
                    $timestamp += 86400;
                }

                if ($timestamp >= 0) {
                    $year = $i;
                    break;
                }
            } while ($timestamp < 0);

            $secondsPerYear = 86400 * ($leapyear ? 366 : 365) + $day;

            $timestamp = $day;
            // iterate through months
            for ($i = 12; --$i >= 0;) {
                $day = $timestamp;

                $timestamp += self::$_monthTable[$i] * 86400;
                if (($leapyear === true) and ($i == 1)) {
                    $timestamp += 86400;
                }

                if ($timestamp >= 0) {
                    $month  = $i;
                    $numday = self::$_monthTable[$i];
                    if (($leapyear === true) and ($i == 1)) {
                        ++$numday;
                    }
                    break;
                }
            }

            $timestamp  = $day;
            $numberdays = $numday + ceil(($timestamp + 1) / 86400);

            $timestamp += ($numday - $numberdays + 1) * 86400;
            $hours      = floor($timestamp / 3600);
        } else {

            // iterate through years
            for ($i = 1970;;$i++) {
                $day = $timestamp;

                $timestamp -= 31536000;
                $leapyear = self::isYearLeapYear($i);
                if ($leapyear === true) {
                    $timestamp -= 86400;
                }

                if ($timestamp < 0) {
                    $year = $i;
                    break;
                }
            }

            $secondsPerYear = $day;

            $timestamp = $day;
            // iterate through months
            for ($i = 0; $i <= 11; $i++) {
                $day = $timestamp;
                $timestamp -= self::$_monthTable[$i] * 86400;

                if (($leapyear === true) and ($i == 1)) {
                    $timestamp -= 86400;
                }

                if ($timestamp < 0) {
                    $month  = $i;
                    $numday = self::$_monthTable[$i];
                    if (($leapyear === true) and ($i == 1)) {
                        ++$numday;
                    }
                    break;
                }
            }

            $timestamp  = $day;
            $numberdays = ceil(($timestamp + 1) / 86400);
            $timestamp  = $timestamp - ($numberdays - 1) * 86400;
            $hours = floor($timestamp / 3600);
        }

        $timestamp -= $hours * 3600;

        $month  += 1;
        $minutes = floor($timestamp / 60);
        $seconds = $timestamp - $minutes * 60;

        if ($fast === true) {
            $array = array(
                'seconds' => $seconds,
                'minutes' => $minutes,
                'hours'   => $hours,
                'mday'    => $numberdays,
                'mon'     => $month,
                'year'    => $year,
                'yday'    => floor($secondsPerYear / 86400),
            );
        } else {

            $dayofweek = self::dayOfWeek($year, $month, $numberdays);
            $array = array(
                    'seconds' => $seconds,
                    'minutes' => $minutes,
                    'hours'   => $hours,
                    'mday'    => $numberdays,
                    'wday'    => $dayofweek,
                    'mon'     => $month,
                    'year'    => $year,
                    'yday'    => floor($secondsPerYear / 86400),
                    'weekday' => gmdate('l', 86400 * (3 + $dayofweek)),
                    'month'   => gmdate('F', mktime(0, 0, 0, $month, 1, 1971)),
                    0         => $otimestamp
            );
        }

        if (isset(self::$_cache)) {
            if (self::$_cacheTags) {
                self::$_cache->save( serialize($array), $id, array('Zend_Date'));
            } else {
                self::$_cache->save( serialize($array), $id);
            }
        }

        return $array;
    }

    /**
     * Internal getWeekNumber function for handling 64bit timestamps
     *
     * Returns the ISO 8601 week number of a given date
     *
     * @param  integer  $year
     * @param  integer  $month
     * @param  integer  $day
     * @return integer
     */
    protected function weekNumber($year, $month, $day)
    {
        if ((1901 < $year) and ($year < 2038)) {
            return (int) date('W', mktime(0, 0, 0, $month, $day, $year));
        }

        $dayofweek = self::dayOfWeek($year, $month, $day);
        $firstday  = self::dayOfWeek($year, 1, 1);
        if (($month == 1) and (($firstday < 1) or ($firstday > 4)) and ($day < 4)) {
            $firstday  = self::dayOfWeek($year - 1, 1, 1);
            $month     = 12;
            $day       = 31;

        } else if (($month == 12) and ((self::dayOfWeek($year + 1, 1, 1) < 5) and
                   (self::dayOfWeek($year + 1, 1, 1) > 0))) {
            return 1;
        }

        return intval (((self::dayOfWeek($year, 1, 1) < 5) and (self::dayOfWeek($year, 1, 1) > 0)) +
               4 * ($month - 1) + (2 * ($month - 1) + ($day - 1) + $firstday - $dayofweek + 6) * 36 / 256);
    }

    /**
     * Internal _range function
     * Sets the value $a to be in the range of [0, $b]
     *
     * @param float $a - value to correct
     * @param float $b - maximum range to set
     */
    private function _range($a, $b) {
        while ($a < 0) {
            $a += $b;
        }
        while ($a >= $b) {
            $a -= $b;
        }
        return $a;
    }

    /**
     * Calculates the sunrise or sunset based on a location
     *
     * @param  array  $location  Location for calculation MUST include 'latitude', 'longitude', 'horizon'
     * @param  bool   $horizon   true: sunrise; false: sunset
     * @return mixed  - false: midnight sun, integer:
     */
    protected function calcSun($location, $horizon, $rise = false)
    {
        // timestamp within 32bit
        if (abs($this->_unixTimestamp) <= 0x7FFFFFFF) {
            if ($rise === false) {
                return date_sunset($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'],
                                   $location['longitude'], 90 + $horizon, $this->getGmtOffset() / 3600);
            }
            return date_sunrise($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'],
                                $location['longitude'], 90 + $horizon, $this->getGmtOffset() / 3600);
        }

        // self calculation - timestamp bigger than 32bit
        // fix circle values
        $quarterCircle      = 0.5 * M_PI;
        $halfCircle         =       M_PI;
        $threeQuarterCircle = 1.5 * M_PI;
        $fullCircle         = 2   * M_PI;

        // radiant conversion for coordinates
        $radLatitude  = $location['latitude']   * $halfCircle / 180;
        $radLongitude = $location['longitude']  * $halfCircle / 180;

        // get solar coordinates
        $tmpRise       = $rise ? $quarterCircle : $threeQuarterCircle;
        $radDay        = $this->date('z',$this->_unixTimestamp) + ($tmpRise - $radLongitude) / $fullCircle;

        // solar anomoly and longitude
        $solAnomoly    = $radDay * 0.017202 - 0.0574039;
        $solLongitude  = $solAnomoly + 0.0334405 * sin($solAnomoly);
        $solLongitude += 4.93289 + 3.49066E-4 * sin(2 * $solAnomoly);

        // get quadrant
        $solLongitude = $this->_range($solLongitude, $fullCircle);

        if (($solLongitude / $quarterCircle) - intval($solLongitude / $quarterCircle) == 0) {
            $solLongitude += 4.84814E-6;
        }

        // solar ascension
        $solAscension = sin($solLongitude) / cos($solLongitude);
        $solAscension = atan2(0.91746 * $solAscension, 1);

        // adjust quadrant
        if ($solLongitude > $threeQuarterCircle) {
            $solAscension += $fullCircle;
        } else if ($solLongitude > $quarterCircle) {
            $solAscension += $halfCircle;
        }

        // solar declination
        $solDeclination  = 0.39782 * sin($solLongitude);
        $solDeclination /=  sqrt(-$solDeclination * $solDeclination + 1);
        $solDeclination  = atan2($solDeclination, 1);

        $solHorizon = $horizon - sin($solDeclination) * sin($radLatitude);
        $solHorizon /= cos($solDeclination) * cos($radLatitude);

        // midnight sun, always night
        if (abs($solHorizon) > 1) {
            return false;
        }

        $solHorizon /= sqrt(-$solHorizon * $solHorizon + 1);
        $solHorizon  = $quarterCircle - atan2($solHorizon, 1);

        if ($rise) {
            $solHorizon = $fullCircle - $solHorizon;
        }

        // time calculation
        $localTime     = $solHorizon + $solAscension - 0.0172028 * $radDay - 1.73364;
        $universalTime = $localTime - $radLongitude;

        // determinate quadrant
        $universalTime = $this->_range($universalTime, $fullCircle);

        // radiant to hours
        $universalTime *= 24 / $fullCircle;

        // convert to time
        $hour = intval($universalTime);
        $universalTime    = ($universalTime - $hour) * 60;
        $min  = intval($universalTime);
        $universalTime    = ($universalTime - $min) * 60;
        $sec  = intval($universalTime);

        return $this->mktime($hour, $min, $sec, $this->date('m', $this->_unixTimestamp),
                             $this->date('j', $this->_unixTimestamp), $this->date('Y', $this->_unixTimestamp),
                             -1, true);
    }

    /**
     * Sets a new timezone for calculation of $this object's gmt offset.
     * For a list of supported timezones look here: http://php.net/timezones
     * If no timezone can be detected or the given timezone is wrong UTC will be set.
     *
     * @param  string  $zone      OPTIONAL timezone for date calculation; defaults to date_default_timezone_get()
     * @return Zend_Date_DateObject Provides fluent interface
     * @throws Zend_Date_Exception
     */
    public function setTimezone($zone = null)
    {
        $oldzone = @date_default_timezone_get();
        if ($zone === null) {
            $zone = $oldzone;
        }

        // throw an error on false input, but only if the new date extension is available
        if (function_exists('timezone_open')) {
            if (!@timezone_open($zone)) {
                require_once 'Zend/Date/Exception.php';
                throw new Zend_Date_Exception("timezone ($zone) is not a known timezone", 0, null, $zone);
            }
        }
        // this can generate an error if the date extension is not available and a false timezone is given
        $result = @date_default_timezone_set($zone);
        if ($result === true) {
            $this->_offset   = mktime(0, 0, 0, 1, 2, 1970) - gmmktime(0, 0, 0, 1, 2, 1970);
            $this->_timezone = $zone;
        }
        date_default_timezone_set($oldzone);

        if (($zone == 'UTC') or ($zone == 'GMT')) {
            $this->_dst = false;
        } else {
            $this->_dst = true;
        }

        return $this;
    }

    /**
     * Return the timezone of $this object.
     * The timezone is initially set when the object is instantiated.
     *
     * @return  string  actual set timezone string
     */
    public function getTimezone()
    {
        return $this->_timezone;
    }

    /**
     * Return the offset to GMT of $this object's timezone.
     * The offset to GMT is initially set when the object is instantiated using the currently,
     * in effect, default timezone for PHP functions.
     *
     * @return  integer  seconds difference between GMT timezone and timezone when object was instantiated
     */
    public function getGmtOffset()
    {
        $date   = $this->getDateParts($this->getUnixTimestamp(), true);
        $zone   = @date_default_timezone_get();
        $result = @date_default_timezone_set($this->_timezone);
        if ($result === true) {
            $offset = $this->mktime($date['hours'], $date['minutes'], $date['seconds'],
                                    $date['mon'], $date['mday'], $date['year'], false)
                    - $this->mktime($date['hours'], $date['minutes'], $date['seconds'],
                                    $date['mon'], $date['mday'], $date['year'], true);
        }
        date_default_timezone_set($zone);

        return $offset;
    }

    /**
     * Internal method to check if the given cache supports tags
     *
     * @param Zend_Cache $cache
     */
    protected static function _getTagSupportForCache()
    {
        $backend = self::$_cache->getBackend();
        if ($backend instanceof Zend_Cache_Backend_ExtendedInterface) {
            $cacheOptions = $backend->getCapabilities();
            self::$_cacheTags = $cacheOptions['tags'];
        } else {
            self::$_cacheTags = false;
        }

        return self::$_cacheTags;
    }
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return $this;
    }

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * Set the object response encoding
     *
     * @param  mixed $int
     * @return Zend_Amf_Request
     */
    public function setObjectEncoding($int)
    {
        $this->_objectEncoding = $int;
        return $this;
    }
}

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_Amf
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $
 */

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

/**
 * @package    Zend_Amf
 * @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_Amf_Exception extends Zend_Exception
{
}


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Amf
 * @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: Constants.php 23775 2011-03-01 17:25:24Z ralph $
 */

/**
 * The following constants are used throughout serialization and
 * deserialization to detect the AMF marker and encoding types.
 *
 * @package    Zend_Amf
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
final class Zend_Amf_Constants
{
    const AMF0_NUMBER            = 0x00;
    const AMF0_BOOLEAN           = 0x01;
    const AMF0_STRING            = 0x02;
    const AMF0_OBJECT            = 0x03;
    const AMF0_MOVIECLIP         = 0x04;
    const AMF0_NULL              = 0x05;
    const AMF0_UNDEFINED         = 0x06;
    const AMF0_REFERENCE         = 0x07;
    const AMF0_MIXEDARRAY        = 0x08;
    const AMF0_OBJECTTERM        = 0x09;
    const AMF0_ARRAY             = 0x0a;
    const AMF0_DATE              = 0x0b;
    const AMF0_LONGSTRING        = 0x0c;
    const AMF0_UNSUPPORTED       = 0x0e;
    const AMF0_XML               = 0x0f;
    const AMF0_TYPEDOBJECT       = 0x10;
    const AMF0_AMF3              = 0x11;
    const AMF0_OBJECT_ENCODING   = 0x00;

    const AMF3_UNDEFINED         = 0x00;
    const AMF3_NULL              = 0x01;
    const AMF3_BOOLEAN_FALSE     = 0x02;
    const AMF3_BOOLEAN_TRUE      = 0x03;
    const AMF3_INTEGER           = 0x04;
    const AMF3_NUMBER            = 0x05;
    const AMF3_STRING            = 0x06;
    const AMF3_XML               = 0x07;
    const AMF3_DATE              = 0x08;
    const AMF3_ARRAY             = 0x09;
    const AMF3_OBJECT            = 0x0A;
    const AMF3_XMLSTRING         = 0x0B;
    const AMF3_BYTEARRAY         = 0x0C;
    const AMF3_OBJECT_ENCODING   = 0x03;

    // Object encodings for AMF3 object types
    const ET_PROPLIST            = 0x00;
    const ET_EXTERNAL            = 0x01;
    const ET_DYNAMIC             = 0x02;
    const ET_PROXY               = 0x03;

    const FMS_OBJECT_ENCODING    = 0x01;

    /**
     * Special content length value that indicates "unknown" content length
     * per AMF Specification
     */
    const UNKNOWN_CONTENT_LENGTH = -1;
    const URL_APPEND_HEADER      = 'AppendToGatewayUrl';
    const RESULT_METHOD          = '/onResult';
    const STATUS_METHOD          = '/onStatus';
    const CREDENTIALS_HEADER     = 'Credentials';
    const PERSISTENT_HEADER      = 'RequestPersistentHeader';
    const DESCRIBE_HEADER        = 'DescribeService';

    const GUEST_ROLE             = 'anonymous';
}


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_Amf
 * @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: Server.php 24206 2011-07-06 13:52:02Z matthew $
 */

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

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

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

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

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

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

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

/** @see Zend_Amf_Parse_TypeLoader */
require_once 'Zend/Amf/Parse/TypeLoader.php';

/** @see Zend_Auth */
require_once 'Zend/Auth.php';
/**
 * An AMF gateway server implementation to allow the connection of the Adobe Flash Player to
 * Zend Framework
 *
 * @todo       Make the reflection methods cache and autoload.
 * @package    Zend_Amf
 * @subpackage Server
 * @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_Amf_Server implements Zend_Server_Interface
{
    /**
     * Array of dispatchables
     * @var array
     */
    protected $_methods = array();

    /**
     * Array of classes that can be called without being explicitly loaded
     *
     * Keys are class names.
     *
     * @var array
     */
    protected $_classAllowed = array();

    /**
     * Loader for classes in added directories
     * @var Zend_Loader_PluginLoader
     */
    protected $_loader;

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

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

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

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

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

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

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

    /**
     * Authentication handler object
     *
     * @var Zend_Amf_Auth_Abstract
     */
    protected $_auth;
    /**
     * ACL handler object
     *
     * @var Zend_Acl
     */
    protected $_acl;
    /**
     * The server constructor
     */
    public function __construct()
    {
        Zend_Amf_Parse_TypeLoader::setResourceLoader(new Zend_Loader_PluginLoader(array("Zend_Amf_Parse_Resource" => "Zend/Amf/Parse/Resource")));
    }

    /**
     * Set authentication adapter
     *
     * If the authentication adapter implements a "getAcl()" method, populate
     * the ACL of this instance with it (if none exists already).
     *
     * @param  Zend_Amf_Auth_Abstract $auth
     * @return Zend_Amf_Server
     */
    public function setAuth(Zend_Amf_Auth_Abstract $auth)
    {
        $this->_auth = $auth;
        if ((null === $this->getAcl()) && method_exists($auth, 'getAcl')) {
            $this->setAcl($auth->getAcl());
        }
        return $this;
    }
   /**
     * Get authentication adapter
     *
     * @return Zend_Amf_Auth_Abstract
     */
    public function getAuth()
    {
        return $this->_auth;
    }

    /**
     * Set ACL adapter
     *
     * @param  Zend_Acl $acl
     * @return Zend_Amf_Server
     */
    public function setAcl(Zend_Acl $acl)
    {
        $this->_acl = $acl;
        return $this;
    }
   /**
     * Get ACL adapter
     *
     * @return Zend_Acl
     */
    public function getAcl()
    {
        return $this->_acl;
    }

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

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

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

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

    /**
     * Check if the ACL allows accessing the function or method
     *
     * @param string|object $object Object or class being accessed
     * @param string $function Function or method being accessed
     * @return unknown_type
     */
    protected function _checkAcl($object, $function)
    {
        if(!$this->_acl) {
            return true;
        }
        if($object) {
            $class = is_object($object)?get_class($object):$object;
            if(!$this->_acl->has($class)) {
                require_once 'Zend/Acl/Resource.php';
                $this->_acl->add(new Zend_Acl_Resource($class));
            }
            $call = array($object, "initAcl");
            if(is_callable($call) && !call_user_func($call, $this->_acl)) {
                // if initAcl returns false, no ACL check
                return true;
            }
        } else {
            $class = null;
        }

        $auth = Zend_Auth::getInstance();
        if($auth->hasIdentity()) {
            $role = $auth->getIdentity()->role;
        } else {
            if($this->_acl->hasRole(Zend_Amf_Constants::GUEST_ROLE)) {
                $role = Zend_Amf_Constants::GUEST_ROLE;
            } else {
                require_once 'Zend/Amf/Server/Exception.php';
                throw new Zend_Amf_Server_Exception("Unauthenticated access not allowed");
            }
        }
        if($this->_acl->isAllowed($role, $class, $function)) {
            return true;
        } else {
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception("Access not allowed");
        }
    }

    /**
     * Get PluginLoader for the Server
     *
     * @return Zend_Loader_PluginLoader
     */
    protected function getLoader()
    {
        if(empty($this->_loader)) {
            require_once 'Zend/Loader/PluginLoader.php';
            $this->_loader = new Zend_Loader_PluginLoader();
        }
        return $this->_loader;
    }

    /**
     * Loads a remote class or method and executes the function and returns
     * the result
     *
     * @param  string $method Is the method to execute
     * @param  mixed $param values for the method
     * @return mixed $response the result of executing the method
     * @throws Zend_Amf_Server_Exception
     */
    protected function _dispatch($method, $params = null, $source = null)
    {
        if($source) {
            if(($mapped = Zend_Amf_Parse_TypeLoader::getMappedClassName($source)) !== false) {
                $source = $mapped;
            }
        }
        $qualifiedName = empty($source) ? $method : $source . '.' . $method;

        if (!isset($this->_table[$qualifiedName])) {
            // if source is null a method that was not defined was called.
            if ($source) {
                $className = str_replace('.', '_', $source);
                if(class_exists($className, false) && !isset($this->_classAllowed[$className])) {
                    require_once 'Zend/Amf/Server/Exception.php';
                    throw new Zend_Amf_Server_Exception('Can not call "' . $className . '" - use setClass()');
                }
                try {
                    $this->getLoader()->load($className);
                } catch (Exception $e) {
                    require_once 'Zend/Amf/Server/Exception.php';
                    throw new Zend_Amf_Server_Exception('Class "' . $className . '" does not exist: '.$e->getMessage(), 0, $e);
                }
                // Add the new loaded class to the server.
                $this->setClass($className, $source);
            }

            if (!isset($this->_table[$qualifiedName])) {
                // Source is null or doesn't contain specified method
                require_once 'Zend/Amf/Server/Exception.php';
                throw new Zend_Amf_Server_Exception('Method "' . $method . '" does not exist');
            }
        }

        $info = $this->_table[$qualifiedName];
        $argv = $info->getInvokeArguments();

        if (0 < count($argv)) {
            $params = array_merge($params, $argv);
        }

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

        return $return;
    }

    /**
     * Handles each of the 11 different command message types.
     *
     * A command message is a flex.messaging.messages.CommandMessage
     *
     * @see    Zend_Amf_Value_Messaging_CommandMessage
     * @param  Zend_Amf_Value_Messaging_CommandMessage $message
     * @return Zend_Amf_Value_Messaging_AcknowledgeMessage
     */
    protected function _loadCommandMessage(Zend_Amf_Value_Messaging_CommandMessage $message)
    {
        require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
        switch($message->operation) {
            case Zend_Amf_Value_Messaging_CommandMessage::DISCONNECT_OPERATION :
            case Zend_Amf_Value_Messaging_CommandMessage::CLIENT_PING_OPERATION :
                $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
                break;
            case Zend_Amf_Value_Messaging_CommandMessage::LOGIN_OPERATION :
                $data = explode(':', base64_decode($message->body));
                $userid = $data[0];
                $password = isset($data[1])?$data[1]:"";
                if(empty($userid)) {
                    require_once 'Zend/Amf/Server/Exception.php';
                    throw new Zend_Amf_Server_Exception('Login failed: username not supplied');
                }
                if(!$this->_handleAuth($userid, $password)) {
                    require_once 'Zend/Amf/Server/Exception.php';
                    throw new Zend_Amf_Server_Exception('Authentication failed');
                }
                $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
                break;
           case Zend_Amf_Value_Messaging_CommandMessage::LOGOUT_OPERATION :
                if($this->_auth) {
                    Zend_Auth::getInstance()->clearIdentity();
                }
                $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
                break;
            default :
                require_once 'Zend/Amf/Server/Exception.php';
                throw new Zend_Amf_Server_Exception('CommandMessage::' . $message->operation . ' not implemented');
                break;
        }
        return $return;
    }

    /**
     * Create appropriate error message
     *
     * @param int $objectEncoding Current AMF encoding
     * @param string $message Message that was being processed when error happened
     * @param string $description Error description
     * @param mixed $detail Detailed data about the error
     * @param int $code Error code
     * @param int $line Error line
     * @return Zend_Amf_Value_Messaging_ErrorMessage|array
     */
    protected function _errorMessage($objectEncoding, $message, $description, $detail, $code, $line)
    {
        $return = null;
        switch ($objectEncoding) {
            case Zend_Amf_Constants::AMF0_OBJECT_ENCODING :
                return array (
                        'description' => ($this->isProduction ()) ? '' : $description,
                        'detail' => ($this->isProduction ()) ? '' : $detail,
                        'line' => ($this->isProduction ()) ? 0 : $line,
                        'code' => $code
                );
            case Zend_Amf_Constants::AMF3_OBJECT_ENCODING :
                require_once 'Zend/Amf/Value/Messaging/ErrorMessage.php';
                $return = new Zend_Amf_Value_Messaging_ErrorMessage ( $message );
                $return->faultString = $this->isProduction () ? '' : $description;
                $return->faultCode = $code;
                $return->faultDetail = $this->isProduction () ? '' : $detail;
                break;
        }
        return $return;
    }

    /**
     * Handle AMF authentication
     *
     * @param string $userid
     * @param string $password
     * @return boolean
     */
    protected function _handleAuth( $userid,  $password)
    {
        if (!$this->_auth) {
            return true;
        }
        $this->_auth->setCredentials($userid, $password);
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($this->_auth);
        if ($result->isValid()) {
            if (!$this->isSession()) {
                $this->setSession();
            }
            return true;
        } else {
            // authentication failed, good bye
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception(
                "Authentication failed: " . join("\n",
                    $result->getMessages()), $result->getCode());
        }

    }

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

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

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

        // Authenticate, if we have credential headers
        $error   = false;
        $headers = $request->getAmfHeaders();
        if (isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER])
            && isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid)
            && isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password)
        ) {
            try {
                if ($this->_handleAuth(
                        $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid,
                        $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password
                )) {
                    // use RequestPersistentHeader to clear credentials
                    $response->addAmfHeader(
                        new Zend_Amf_Value_MessageHeader(
                            Zend_Amf_Constants::PERSISTENT_HEADER,
                            false,
                            new Zend_Amf_Value_MessageHeader(
                                Zend_Amf_Constants::CREDENTIALS_HEADER,
                                false, null
                            )
                        )
                    );
                }
            } catch (Exception $e) {
                // Error during authentication; report it
                $error = $this->_errorMessage(
                    $objectEncoding,
                    '',
                    $e->getMessage(),
                    $e->getTraceAsString(),
                    $e->getCode(),
                    $e->getLine()
                );
                $responseType = Zend_AMF_Constants::STATUS_METHOD;
            }
        }

        // Iterate through each of the service calls in the AMF request
        foreach($request->getAmfBodies() as $body)
        {
            if ($error) {
                // Error during authentication; just report it and be done
                $responseURI = $body->getResponseURI() . $responseType;
                $newBody     = new Zend_Amf_Value_MessageBody($responseURI, null, $error);
                $response->addAmfBody($newBody);
                continue;
            }
            try {
                switch ($objectEncoding) {
                    case Zend_Amf_Constants::AMF0_OBJECT_ENCODING:
                        // AMF0 Object Encoding
                        $targetURI = $body->getTargetURI();
                        $message = '';

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

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

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

                            if ($source) {
                                // Break off method name from namespace into source
                                $method = substr(strrchr($targetURI, '.'), 1);
                                $return = $this->_dispatch($method, $body->getData(), $source);
                            } else {
                                // Just have a method name.
                                $return = $this->_dispatch($targetURI, $body->getData());
                            }
                        }
                        break;
                }
                $responseType = Zend_AMF_Constants::RESULT_METHOD;
            } catch (Exception $e) {
                $return = $this->_errorMessage($objectEncoding, $message,
                    $e->getMessage(), $e->getTraceAsString(),$e->getCode(),  $e->getLine());
                $responseType = Zend_AMF_Constants::STATUS_METHOD;
            }

            $responseURI = $body->getResponseURI() . $responseType;
            $newBody     = new Zend_Amf_Value_MessageBody($responseURI, null, $return);
            $response->addAmfBody($newBody);
        }
        // Add a session header to the body if session is requested.
        if($this->isSession()) {
           $currentID = session_id();
           $joint = "?";
           if(isset($_SERVER['QUERY_STRING'])) {
               if(!strpos($_SERVER['QUERY_STRING'], $currentID) !== FALSE) {
                   if(strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) {
                       $joint = "&";
                   }
               }
           }

            // create a new AMF message header with the session id as a variable.
            $sessionValue = $joint . $this->_sessionName . "=" . $currentID;
            $sessionHeader = new Zend_Amf_Value_MessageHeader(Zend_Amf_Constants::URL_APPEND_HEADER, false, $sessionValue);
            $response->addAmfHeader($sessionHeader);
        }

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

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

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

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

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

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

        return $this->_request;
    }

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

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

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

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

        // Use the class name as the name space by default.

        if ($namespace == '') {
            $namespace = is_object($class) ? get_class($class) : $class;
        }

        $this->_classAllowed[is_object($class) ? get_class($class) : $class] = true;

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

        return $this;
    }

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

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

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

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

    /**
     * Creates an array of directories in which services can reside.
     * TODO: add support for prefixes?
     *
     * @param string $dir
     */
    public function addDirectory($dir)
    {
        $this->getLoader()->addPrefixPath("", $dir);
    }

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

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

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

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

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

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

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

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

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

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

    /**
     * List all available methods
     *
     * Returns an array of method names.
     *
     * @return array
     */
    public function listMethods()
    {
        return array_keys($this->_table);
    }
}


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

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

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

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

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

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

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

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

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

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

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

        // Loop through the AMF Headers that need to be returned.
        $headerCount = count($this->_headers);
        $stream->writeInt($headerCount);
        foreach ($this->getAmfHeaders() as $header) {
            $serializer = new Zend_Amf_Parse_Amf0_Serializer($stream);
            $stream->writeUTF($header->name);
            $stream->writeByte($header->mustRead);
            $stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH);
            if (is_object($header->data)) {
                // Workaround for PHP5 with E_STRICT enabled complaining about
                // "Only variables should be passed by reference"
                $placeholder = null;
                $serializer->writeTypeMarker($placeholder, null, $header->data);
            } else {
                $serializer->writeTypeMarker($header->data);
            }
        }

        // loop through the AMF bodies that need to be returned.
        $bodyCount = count($this->_bodies);
        $stream->writeInt($bodyCount);
        foreach ($this->_bodies as $body) {
            $serializer = new Zend_Amf_Parse_Amf0_Serializer($stream);
            $stream->writeUTF($body->getTargetURI());
            $stream->writeUTF($body->getResponseURI());
            $stream->writeLong(Zend_Amf_Constants::UNKNOWN_CONTENT_LENGTH);
            $bodyData = $body->getData();
            $markerType = ($this->_objectEncoding == Zend_Amf_Constants::AMF0_OBJECT_ENCODING) ? null : Zend_Amf_Constants::AMF0_AMF3;
            if (is_object($bodyData)) {
                // Workaround for PHP5 with E_STRICT enabled complaining about
                // "Only variables should be passed by reference"
                $placeholder = null;
                $serializer->writeTypeMarker($placeholder, $markerType, $bodyData);
            } else {
                $serializer->writeTypeMarker($bodyData, $markerType);
            }
        }

        return $this;
    }

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

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

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

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

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

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

    /**
     * Set the AMF encoding that will be used for serialization
     *
     * @param  int $encoding
     * @return Zend_Amf_Response
     */
    public function setObjectEncoding($encoding)
    {
        $this->_objectEncoding = $encoding;
        return $this;
    }
}


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

/**
 * Utility class to walk through a data stream byte by byte with conventional names
 *
 * @package    Zend_Amf
 * @subpackage Util
 * @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_Amf_Util_BinaryStream
{
    /**
     * @var string Byte stream
     */
    protected $_stream;

    /**
     * @var int Length of stream
     */
    protected $_streamLength;

    /**
     * @var bool BigEndian encoding?
     */
    protected $_bigEndian;

    /**
     * @var int Current position in stream
     */
    protected $_needle;

    /**
     * Constructor
     *
     * Create a reference to a byte stream that is going to be parsed or created
     * by the methods in the class. Detect if the class should use big or
     * little Endian encoding.
     *
     * @param  string $stream use '' if creating a new stream or pass a string if reading.
     * @return void
     */
    public function __construct($stream)
    {
        if (!is_string($stream)) {
            require_once 'Zend/Amf/Exception.php';
            throw new Zend_Amf_Exception('Inputdata is not of type String');
        }

        $this->_stream       = $stream;
        $this->_needle       = 0;
        $this->_streamLength = strlen($stream);
        $this->_bigEndian    = (pack('l', 1) === "\x00\x00\x00\x01");
    }

    /**
     * Returns the current stream
     *
     * @return string
     */
    public function getStream()
    {
        return $this->_stream;
    }

    /**
     * Read the number of bytes in a row for the length supplied.
     *
     * @todo   Should check that there are enough bytes left in the stream we are about to read.
     * @param  int $length
     * @return string
     * @throws Zend_Amf_Exception for buffer underrun
     */
    public function readBytes($length)
    {
        if (($length + $this->_needle) > $this->_streamLength) {
            require_once 'Zend/Amf/Exception.php';
            throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
        }
        $bytes = substr($this->_stream, $this->_needle, $length);
        $this->_needle+= $length;
        return $bytes;
    }

    /**
     * Write any length of bytes to the stream
     *
     * Usually a string.
     *
     * @param  string $bytes
     * @return Zend_Amf_Util_BinaryStream
     */
    public function writeBytes($bytes)
    {
        $this->_stream.= $bytes;
        return $this;
    }

    /**
     * Reads a signed byte
     *
     * @return int Value is in the range of -128 to 127.
     */
    public function readByte()
    {
        if (($this->_needle + 1) > $this->_streamLength) {
            require_once 'Zend/Amf/Exception.php';
            throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
        }

        return ord($this->_stream{$this->_needle++});
    }

    /**
     * Writes the passed string into a signed byte on the stream.
     *
     * @param  string $stream
     * @return Zend_Amf_Util_BinaryStream
     */
    public function writeByte($stream)
    {
        $this->_stream.= pack('c', $stream);
        return $this;
    }

    /**
     * Reads a signed 32-bit integer from the data stream.
     *
     * @return int Value is in the range of -2147483648 to 2147483647
     */
    public function readInt()
    {
        return ($this->readByte() << 8) + $this->readByte();
    }

    /**
     * Write an the integer to the output stream as a 32 bit signed integer
     *
     * @param  int $stream
     * @return Zend_Amf_Util_BinaryStream
     */
    public function writeInt($stream)
    {
        $this->_stream.= pack('n', $stream);
        return $this;
    }

    /**
     * Reads a UTF-8 string from the data stream
     *
     * @return string A UTF-8 string produced by the byte representation of characters
     */
    public function readUtf()
    {
        $length = $this->readInt();
        return $this->readBytes($length);
    }

    /**
     * Wite a UTF-8 string to the outputstream
     *
     * @param  string $stream
     * @return Zend_Amf_Util_BinaryStream
     */
    public function writeUtf($stream)
    {
        $this->writeInt(strlen($stream));
        $this->_stream.= $stream;
        return $this;
    }

    /**
     * Read a long UTF string
     *
     * @return string
     */
    public function readLongUtf()
    {
        $length = $this->readLong();
        return $this->readBytes($length);
    }

    /**
     * Write a long UTF string to the buffer
     *
     * @param  string $stream
     * @return Zend_Amf_Util_BinaryStream
     */
    public function writeLongUtf($stream)
    {
        $this->writeLong(strlen($stream));
        $this->_stream.= $stream;
    }

    /**
     * Read a long numeric value
     *
     * @return double
     */
    public function readLong()
    {
        return ($this->readByte() << 24) + ($this->readByte() << 16) + ($this->readByte() << 8) + $this->readByte();
    }

    /**
     * Write long numeric value to output stream
     *
     * @param  int|string $stream
     * @return Zend_Amf_Util_BinaryStream
     */
    public function writeLong($stream)
    {
        $this->_stream.= pack('N', $stream);
        return $this;
    }

    /**
     * Read a 16 bit unsigned short.
     *
     * @todo   This could use the unpack() w/ S,n, or v
     * @return double
     */
    public function readUnsignedShort()
    {
        $byte1 = $this->readByte();
        $byte2 = $this->readByte();
        return (($byte1 << 8) | $byte2);
    }

    /**
     * Reads an IEEE 754 double-precision floating point number from the data stream.
     *
     * @return double Floating point number
     */
    public function readDouble()
    {
        $bytes = substr($this->_stream, $this->_needle, 8);
        $this->_needle+= 8;

        if (!$this->_bigEndian) {
            $bytes = strrev($bytes);
        }

        $double = unpack('dflt', $bytes);
        return $double['flt'];
    }

    /**
     * Writes an IEEE 754 double-precision floating point number from the data stream.
     *
     * @param  string|double $stream
     * @return Zend_Amf_Util_BinaryStream
     */
    public function writeDouble($stream)
    {
        $stream = pack('d', $stream);
        if (!$this->_bigEndian) {
            $stream = strrev($stream);
        }
        $this->_stream.= $stream;
        return $this;
    }

}