<?php
/**
 * Horde Date wrapper/logic class, including some calculation
 * functions.
 *
 * @category Horde
 * @package  Date
 *
 * @TODO in format():
 *   http://php.net/intldateformatter
 *
 * @TODO on timezones:
 *   http://trac.agavi.org/ticket/1008
 *   http://trac.agavi.org/changeset/3659
 *
 * @TODO on switching to PHP::DateTime:
 *   The only thing ever stored in the database *IS* Unix timestamps. Doing
 *   anything other than that is unmanageable, yet some frameworks use 'server
 *   based' times in their systems, simply because they do not bother with
 *   daylight saving and only 'serve' one timezone!
 *
 *   The second you have to manage 'real' time across timezones then daylight
 *   saving becomes essential, BUT only on the display side! Since the browser
 *   only provides a time offset, this is useless and to be honest should simply
 *   be ignored ( until it is upgraded to provide the correct information ;)
 *   ). So we need a 'display' function that takes a simple numeric epoch, and a
 *   separate timezone id into which the epoch is to be 'converted'. My W3C
 *   mapping works simply because ADOdb then converts that to it's own simple
 *   offset abbreviation - in my case GMT or BST. As long as DateTime passes the
 *   full 64 bit number the date range from 100AD is also preserved ( and
 *   further back if 2 digit years are disabled ). If I want to display the
 *   'real' timezone with this 'time' then I just add it in place of ADOdb's
 *   'timezone'. I am tempted to simply adjust the ADOdb class to take a
 *   timezone in place of the simple GMT switch it currently uses.
 *
 *   The return path is just the reverse and simply needs to take the client
 *   display offset off prior to storage of the UTC epoch. SO we use
 *   DateTimeZone to get an offset value for the clients timezone and simply add
 *   or subtract this from a timezone agnostic display on the client end when
 *   entering new times.
 *
 *
 *   It's not really feasible to store dates in specific timezone, as most
 *   national/local timezones support DST - and that is a pain to support, as
 *   eg.  sorting breaks when some timestamps get repeated. That's why it's
 *   usually better to store datetimes as either UTC datetime or plain unix
 *   timestamp. I usually go with the former - using database datetime type.
 */

/**
 * @category Horde
 * @package  Date
 */
class Horde_Date
{
    const DATE_SUNDAY = 0;
    const DATE_MONDAY = 1;
    const DATE_TUESDAY = 2;
    const DATE_WEDNESDAY = 3;
    const DATE_THURSDAY = 4;
    const DATE_FRIDAY = 5;
    const DATE_SATURDAY = 6;

    const MASK_SUNDAY = 1;
    const MASK_MONDAY = 2;
    const MASK_TUESDAY = 4;
    const MASK_WEDNESDAY = 8;
    const MASK_THURSDAY = 16;
    const MASK_FRIDAY = 32;
    const MASK_SATURDAY = 64;
    const MASK_WEEKDAYS = 62;
    const MASK_WEEKEND = 65;
    const MASK_ALLDAYS = 127;

    const MASK_SECOND = 1;
    const MASK_MINUTE = 2;
    const MASK_HOUR = 4;
    const MASK_DAY = 8;
    const MASK_MONTH = 16;
    const MASK_YEAR = 32;
    const MASK_ALLPARTS = 63;

    const DATE_DEFAULT = 'Y-m-d H:i:s';
    const DATE_JSON = 'Y-m-d\TH:i:s';

    /**
     * Year
     *
     * @var integer
     */
    protected $_year;

    /**
     * Month
     *
     * @var integer
     */
    protected $_month;

    /**
     * Day
     *
     * @var integer
     */
    protected $_mday;

    /**
     * Hour
     *
     * @var integer
     */
    protected $_hour = 0;

    /**
     * Minute
     *
     * @var integer
     */
    protected $_min = 0;

    /**
     * Second
     *
     * @var integer
     */
    protected $_sec = 0;

    /**
     * String representation of the date's timezone.
     *
     * @var string
     */
    protected $_timezone;

    /**
     * These aliases map Windows, Lotus, and other Timezone IDs to those
     * understood by PHP.
     *
     * @todo This list better moves somewhere else
     * @var array
     */
    protected static $_timezoneAliases = array(
        'Dateline Standard Time' => 'Etc/GMT+12',
        'UTC-11' => 'Etc/GMT+11',
        'Hawaiian Standard Time' => 'Pacific/Honolulu',
        'Alaskan Standard Time' => 'America/Anchorage',
        'Pacific Standard Time (Mexico)' => 'America/Santa_Isabel',
        'Pacific Standard Time' => 'America/Los_Angeles',
        'US Mountain Standard Time' => 'America/Phoenix',
        'Mountain Standard Time (Mexico)' => 'America/Chihuahua',
        'Mountain Standard Time' => 'America/Denver',
        'Central America Standard Time' => 'America/Guatemala',
        'Central Standard Time' => 'America/Chicago',
        'Central Standard Time (Mexico)' => 'America/Mexico_City',
        'Canada Central Standard Time' => 'America/Regina',
        'SA Pacific Standard Time' => 'America/Bogota',
        'Eastern Standard Time' => 'America/New_York',
        'US Eastern Standard Time' => 'America/Indianapolis',
        'Venezuela Standard Time' => 'America/Caracas',
        'Paraguay Standard Time' => 'America/Asuncion',
        'Atlantic Standard Time' => 'America/Halifax',
        'Central Brazilian Standard Time' => 'America/Cuiaba',
        'SA Western Standard Time' => 'America/La_Paz',
        'Pacific SA Standard Time' => 'America/Santiago',
        'Newfoundland Standard Time' => 'America/St_Johns',
        'E. South America Standard Time' => 'America/Sao_Paulo',
        'Argentina Standard Time' => 'America/Buenos_Aires',
        'SA Eastern Standard Time' => 'America/Cayenne',
        'Greenland Standard Time' => 'America/Godthab',
        'Montevideo Standard Time' => 'America/Montevideo',
        'Bahia Standard Time' => 'America/Bahia',
        'UTC-02' => 'Etc/GMT+2',
        'Azores Standard Time' => 'Atlantic/Azores',
        'Cape Verde Standard Time' => 'Atlantic/Cape_Verde',
        'Morocco Standard Time' => 'Africa/Casablanca',
        'GMT Standard Time' => 'Europe/London',
        'Greenwich Standard Time' => 'Atlantic/Reykjavik',
        'W. Europe Standard Time' => 'Europe/Berlin',
        'Central Europe Standard Time' => 'Europe/Budapest',
        'Romance Standard Time' => 'Europe/Paris',
        'Central European Standard Time' => 'Europe/Warsaw',
        'W. Central Africa Standard Time' => 'Africa/Lagos',
        'Namibia Standard Time' => 'Africa/Windhoek',
        'Jordan Standard Time' => 'Asia/Amman',
        'GTB Standard Time' => 'Europe/Bucharest',
        'Middle East Standard Time' => 'Asia/Beirut',
        'Egypt Standard Time' => 'Africa/Cairo',
        'Syria Standard Time' => 'Asia/Damascus',
        'E. Europe Standard Time' => 'Asia/Nicosia',
        'South Africa Standard Time' => 'Africa/Johannesburg',
        'FLE Standard Time' => 'Europe/Kiev',
        'Turkey Standard Time' => 'Europe/Istanbul',
        'Israel Standard Time' => 'Asia/Jerusalem',
        'Arabic Standard Time' => 'Asia/Baghdad',
        'Kaliningrad Standard Time' => 'Europe/Kaliningrad',
        'Arab Standard Time' => 'Asia/Riyadh',
        'E. Africa Standard Time' => 'Africa/Nairobi',
        'Iran Standard Time' => 'Asia/Tehran',
        'Arabian Standard Time' => 'Asia/Dubai',
        'Azerbaijan Standard Time' => 'Asia/Baku',
        'Russian Standard Time' => 'Europe/Moscow',
        'Mauritius Standard Time' => 'Indian/Mauritius',
        'Georgian Standard Time' => 'Asia/Tbilisi',
        'Caucasus Standard Time' => 'Asia/Yerevan',
        'Afghanistan Standard Time' => 'Asia/Kabul',
        'Pakistan Standard Time' => 'Asia/Karachi',
        'West Asia Standard Time' => 'Asia/Tashkent',
        'India Standard Time' => 'Asia/Calcutta',
        'Sri Lanka Standard Time' => 'Asia/Colombo',
        'Nepal Standard Time' => 'Asia/Katmandu',
        'Central Asia Standard Time' => 'Asia/Almaty',
        'Bangladesh Standard Time' => 'Asia/Dhaka',
        'Ekaterinburg Standard Time' => 'Asia/Yekaterinburg',
        'Myanmar Standard Time' => 'Asia/Rangoon',
        'SE Asia Standard Time' => 'Asia/Bangkok',
        'N. Central Asia Standard Time' => 'Asia/Novosibirsk',
        'China Standard Time' => 'Asia/Shanghai',
        'North Asia Standard Time' => 'Asia/Krasnoyarsk',
        'Singapore Standard Time' => 'Asia/Singapore',
        'W. Australia Standard Time' => 'Australia/Perth',
        'Taipei Standard Time' => 'Asia/Taipei',
        'Ulaanbaatar Standard Time' => 'Asia/Ulaanbaatar',
        'North Asia East Standard Time' => 'Asia/Irkutsk',
        'Tokyo Standard Time' => 'Asia/Tokyo',
        'Korea Standard Time' => 'Asia/Seoul',
        'Cen. Australia Standard Time' => 'Australia/Adelaide',
        'AUS Central Standard Time' => 'Australia/Darwin',
        'E. Australia Standard Time' => 'Australia/Brisbane',
        'AUS Eastern Standard Time' => 'Australia/Sydney',
        'West Pacific Standard Time' => 'Pacific/Port_Moresby',
        'Tasmania Standard Time' => 'Australia/Hobart',
        'Yakutsk Standard Time' => 'Asia/Yakutsk',
        'Central Pacific Standard Time' => 'Pacific/Guadalcanal',
        'Vladivostok Standard Time' => 'Asia/Vladivostok',
        'New Zealand Standard Time' => 'Pacific/Auckland',
        'UTC+12' => 'Etc/GMT-12',
        'Fiji Standard Time' => 'Pacific/Fiji',
        'Magadan Standard Time' => 'Asia/Magadan',
        'Tonga Standard Time' => 'Pacific/Tongatapu',
        'Samoa Standard Time' => 'Pacific/Apia',
        // Found from Lotus Notes
        'W. Europe' => 'Europe/Berlin',
        'E. Europe' => 'Asia/Nicosia',
        // Old Olsen names, from the "backward" file.
        'Africa/Asmera' => 'Africa/Nairobi',
        'Africa/Timbuktu' => 'Africa/Abidjan',
        'America/Argentina/ComodRivadavia' => 'America/Argentina/Catamarca',
        'America/Atka' => 'America/Adak',
        'America/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
        'America/Catamarca' => 'America/Argentina/Catamarca',
        'America/Coral_Harbour' => 'America/Atikokan',
        'America/Cordoba' => 'America/Argentina/Cordoba',
        'America/Ensenada' => 'America/Tijuana',
        'America/Fort_Wayne' => 'America/Indiana/Indianapolis',
        'America/Indianapolis' => 'America/Indiana/Indianapolis',
        'America/Jujuy' => 'America/Argentina/Jujuy',
        'America/Knox_IN' => 'America/Indiana/Knox',
        'America/Louisville' => 'America/Kentucky/Louisville',
        'America/Mendoza' => 'America/Argentina/Mendoza',
        'America/Montreal' => 'America/Toronto',
        'America/Porto_Acre' => 'America/Rio_Branco',
        'America/Rosario' => 'America/Argentina/Cordoba',
        'America/Santa_Isabel' => 'America/Tijuana',
        'America/Shiprock' => 'America/Denver',
        'America/Virgin' => 'America/Port_of_Spain',
        'Antarctica/South_Pole' => 'Pacific/Auckland',
        'Asia/Ashkhabad' => 'Asia/Ashgabat',
        'Asia/Calcutta' => 'Asia/Kolkata',
        'Asia/Chongqing' => 'Asia/Shanghai',
        'Asia/Chungking' => 'Asia/Shanghai',
        'Asia/Dacca' => 'Asia/Dhaka',
        'Asia/Harbin' => 'Asia/Shanghai',
        'Asia/Kashgar' => 'Asia/Urumqi',
        'Asia/Katmandu' => 'Asia/Kathmandu',
        'Asia/Macao' => 'Asia/Macau',
        'Asia/Saigon' => 'Asia/Ho_Chi_Minh',
        'Asia/Tel_Aviv' => 'Asia/Jerusalem',
        'Asia/Thimbu' => 'Asia/Thimphu',
        'Asia/Ujung_Pandang' => 'Asia/Makassar',
        'Asia/Ulan_Bator' => 'Asia/Ulaanbaatar',
        'Atlantic/Faeroe' => 'Atlantic/Faroe',
        'Atlantic/Jan_Mayen' => 'Europe/Oslo',
        'Australia/ACT' => 'Australia/Sydney',
        'Australia/Canberra' => 'Australia/Sydney',
        'Australia/LHI' => 'Australia/Lord_Howe',
        'Australia/NSW' => 'Australia/Sydney',
        'Australia/North' => 'Australia/Darwin',
        'Australia/Queensland' => 'Australia/Brisbane',
        'Australia/South' => 'Australia/Adelaide',
        'Australia/Tasmania' => 'Australia/Hobart',
        'Australia/Victoria' => 'Australia/Melbourne',
        'Australia/West' => 'Australia/Perth',
        'Australia/Yancowinna' => 'Australia/Broken_Hill',
        'Brazil/Acre' => 'America/Rio_Branco',
        'Brazil/DeNoronha' => 'America/Noronha',
        'Brazil/East' => 'America/Sao_Paulo',
        'Brazil/West' => 'America/Manaus',
        'Canada/Atlantic' => 'America/Halifax',
        'Canada/Central' => 'America/Winnipeg',
        'Canada/East-Saskatchewan' => 'America/Regina',
        'Canada/Eastern' => 'America/Toronto',
        'Canada/Mountain' => 'America/Edmonton',
        'Canada/Newfoundland' => 'America/St_Johns',
        'Canada/Pacific' => 'America/Vancouver',
        'Canada/Saskatchewan' => 'America/Regina',
        'Canada/Yukon' => 'America/Whitehorse',
        'Chile/Continental' => 'America/Santiago',
        'Chile/EasterIsland' => 'Pacific/Easter',
        'Cuba' => 'America/Havana',
        'Egypt' => 'Africa/Cairo',
        'Eire' => 'Europe/Dublin',
        'Europe/Belfast' => 'Europe/London',
        'Europe/Tiraspol' => 'Europe/Chisinau',
        'GB' => 'Europe/London',
        'GB-Eire' => 'Europe/London',
        'GMT+0' => 'Etc/GMT',
        'GMT-0' => 'Etc/GMT',
        'GMT0' => 'Etc/GMT',
        'Greenwich' => 'Etc/GMT',
        'Hongkong' => 'Asia/Hong_Kong',
        'Iceland' => 'Atlantic/Reykjavik',
        'Iran' => 'Asia/Tehran',
        'Israel' => 'Asia/Jerusalem',
        'Jamaica' => 'America/Jamaica',
        'Japan' => 'Asia/Tokyo',
        'Kwajalein' => 'Pacific/Kwajalein',
        'Libya' => 'Africa/Tripoli',
        'Mexico/BajaNorte' => 'America/Tijuana',
        'Mexico/BajaSur' => 'America/Mazatlan',
        'Mexico/General' => 'America/Mexico_City',
        'NZ' => 'Pacific/Auckland',
        'NZ-CHAT' => 'Pacific/Chatham',
        'Navajo' => 'America/Denver',
        'PRC' => 'Asia/Shanghai',
        'Pacific/Ponape' => 'Pacific/Pohnpei',
        'Pacific/Samoa' => 'Pacific/Pago_Pago',
        'Pacific/Truk' => 'Pacific/Chuuk',
        'Pacific/Yap' => 'Pacific/Chuuk',
        'Poland' => 'Europe/Warsaw',
        'Portugal' => 'Europe/Lisbon',
        'ROC' => 'Asia/Taipei',
        'ROK' => 'Asia/Seoul',
        'Singapore' => 'Asia/Singapore',
        'Turkey' => 'Europe/Istanbul',
        'UCT' => 'Etc/UCT',
        'US/Alaska' => 'America/Anchorage',
        'US/Aleutian' => 'America/Adak',
        'US/Arizona' => 'America/Phoenix',
        'US/Central' => 'America/Chicago',
        'US/East-Indiana' => 'America/Indiana/Indianapolis',
        'US/Eastern' => 'America/New_York',
        'US/Hawaii' => 'Pacific/Honolulu',
        'US/Indiana-Starke' => 'America/Indiana/Knox',
        'US/Michigan' => 'America/Detroit',
        'US/Mountain' => 'America/Denver',
        'US/Pacific' => 'America/Los_Angeles',
        'US/Samoa' => 'Pacific/Pago_Pago',
        'UTC' => 'UTC',
        'Universal' => 'UTC',
        'W-SU' => 'Europe/Moscow',
        'Zulu' => 'UTC',
    );

    /**
     * These aliases map timezone abbreviations to those understood by PHP.
     *
     * @todo This list better moves somewhere else
     * @see getTimezoneAlias()
     * @var array
     */
    protected static $_timezoneAbbreviations = array();

    /**
     * A list of (Olson) timezone identifiers understood by PHP.
     *
     * @todo This list better moves somewhere else
     * @see getTimezoneAlias()
     * @var array
     */
    protected static $_timezoneIdentifiers = array();

    /**
     * Default format for __toString()
     *
     * @var string
     */
    protected $_defaultFormat = self::DATE_DEFAULT;

    /**
     * Default specs that are always supported.
     * @var string
     */
    protected static $_defaultSpecs = '-%CdDeHImMnRStTyY';

    /**
     * Internally supported strftime() specifiers.
     * @var string
     */
    protected static $_supportedSpecs = '';

    /**
     * Map of required correction masks.
     *
     * @see __set()
     *
     * @var array
     */
    protected static $_corrections = array(
        'year'  => self::MASK_YEAR,
        'month' => self::MASK_MONTH,
        'mday'  => self::MASK_DAY,
        'hour'  => self::MASK_HOUR,
        'min'   => self::MASK_MINUTE,
        'sec'   => self::MASK_SECOND,
    );

    protected $_formatCache = array();

    /**
     * Builds a new date object. If $date contains date parts, use them to
     * initialize the object.
     *
     * Recognized formats:
     * - arrays with keys 'year', 'month', 'mday', 'day'
     *   'hour', 'min', 'minute', 'sec'
     * - objects with properties 'year', 'month', 'mday', 'hour', 'min', 'sec'
     * - yyyy-mm-dd hh:mm:ss
     * - yyyymmddhhmmss
     * - yyyymmddThhmmssZ
     * - yyyymmdd (might conflict with unix timestamps between 31 Oct 1966 and
     *   03 Mar 1973)
     * - unix timestamps
     * - anything parsed by strtotime()/DateTime.
     *
     * @throws Horde_Date_Exception
     */
    public function __construct($date = null, $timezone = null)
    {
        if (!self::$_supportedSpecs) {
            self::$_supportedSpecs = self::$_defaultSpecs;
            if (function_exists('nl_langinfo')) {
                self::$_supportedSpecs .= 'bBpxX';
            }
        }

        if (func_num_args() > 2) {
            // Handle args in order: year month day hour min sec tz
            $this->_initializeFromArgs(func_get_args());
            return;
        }

        $this->_initializeTimezone($timezone);

        if (is_null($date)) {
            return;
        }

        if (is_string($date)) {
            $date = trim($date, '"');
        }

        if (is_object($date)) {
            $this->_initializeFromObject($date);
        } elseif (is_array($date)) {
            $this->_initializeFromArray($date);
        } elseif (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})(?:\.\d+)?(Z?)$/', $date, $parts)) {
            $this->_year  = (int)$parts[1];
            $this->_month = (int)$parts[2];
            $this->_mday  = (int)$parts[3];
            $this->_hour  = (int)$parts[4];
            $this->_min   = (int)$parts[5];
            $this->_sec   = (int)$parts[6];
            if ($parts[7]) {
                $this->_initializeTimezone('UTC');
            }
        } elseif (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $date, $parts) &&
                  $parts[2] > 0 && $parts[2] <= 12 &&
                  $parts[3] > 0 && $parts[3] <= 31) {
            $this->_year  = (int)$parts[1];
            $this->_month = (int)$parts[2];
            $this->_mday  = (int)$parts[3];
            $this->_hour = $this->_min = $this->_sec = 0;
        } elseif ((string)(int)$date == $date) {
            // Try as a timestamp.
            if ($this->_timezone) {
                $oldtimezone = date_default_timezone_get();
                date_default_timezone_set($this->_timezone);
            }
            $parts = @getdate($date);
            if ($parts) {
                $this->_year  = $parts['year'];
                $this->_month = $parts['mon'];
                $this->_mday  = $parts['mday'];
                $this->_hour  = $parts['hours'];
                $this->_min   = $parts['minutes'];
                $this->_sec   = $parts['seconds'];
            }
            if ($this->_timezone) {
                date_default_timezone_set($oldtimezone);
            }
        } else {
            if (!empty($timezone)) {
                try {
                    $parsed = new DateTime($date, new DateTimeZone($timezone));
                } catch (Exception $e) {
                    throw new Horde_Date_Exception(sprintf(Horde_Date_Translation::t("Failed to parse time string (%s)"), $date));
                }
            } else {
                try {
                    $parsed = new DateTime($date);
                } catch (Exception $e) {
                    throw new Horde_Date_Exception(sprintf(Horde_Date_Translation::t("Failed to parse time string (%s)"), $date));
                }
                $parsed->setTimezone(new DateTimeZone(date_default_timezone_get()));
                $this->_initializeTimezone(date_default_timezone_get());
            }
            $this->_year  = (int)$parsed->format('Y');
            $this->_month = (int)$parsed->format('m');
            $this->_mday  = (int)$parsed->format('d');
            $this->_hour  = (int)$parsed->format('H');
            $this->_min   = (int)$parsed->format('i');
            $this->_sec   = (int)$parsed->format('s');
        }
    }

    /**
     * Returns a simple string representation of the date object
     *
     * @return string  This object converted to a string.
     */
    public function __toString()
    {
        try {
            return $this->format($this->_defaultFormat);
        } catch (Exception $e) {
            return '';
        }
    }

    /**
     * Returns a DateTime object representing this object.
     *
     * @return DateTime
     */
    public function toDateTime()
    {
        try {
            $date = new DateTime(null, new DateTimeZone($this->_timezone));
            $date->setDate($this->_year, $this->_month, $this->_mday);
            $date->setTime($this->_hour, $this->_min, $this->_sec);
        } catch (Exception $e) {
            throw new Horde_Date_Exception($e);
        }
        return $date;
    }

    /**
     * Converts a date in the proleptic Gregorian calendar to the no of days
     * since 24th November, 4714 B.C.
     *
     * Returns the no of days since Monday, 24th November, 4714 B.C. in the
     * proleptic Gregorian calendar (which is 24th November, -4713 using
     * 'Astronomical' year numbering, and 1st January, 4713 B.C. in the
     * proleptic Julian calendar).  This is also the first day of the 'Julian
     * Period' proposed by Joseph Scaliger in 1583, and the number of days
     * since this date is known as the 'Julian Day'.  (It is not directly
     * to do with the Julian calendar, although this is where the name
     * is derived from.)
     *
     * The algorithm is valid for all years (positive and negative), and
     * also for years preceding 4714 B.C.
     *
     * Algorithm is from PEAR::Date_Calc
     *
     * @author Monte Ohrt <monte@ispi.net>
     * @author Pierre-Alain Joye <pajoye@php.net>
     * @author Daniel Convissor <danielc@php.net>
     * @author C.A. Woodcock <c01234@netcomuk.co.uk>
     *
     * @return integer  The number of days since 24th November, 4714 B.C.
     */
    public function toDays()
    {
        if (function_exists('GregorianToJD')) {
            return gregoriantojd($this->_month, $this->_mday, $this->_year);
        }

        $day = $this->_mday;
        $month = $this->_month;
        $year = $this->_year;

        if ($month > 2) {
            // March = 0, April = 1, ..., December = 9,
            // January = 10, February = 11
            $month -= 3;
        } else {
            $month += 9;
            --$year;
        }

        $hb_negativeyear = $year < 0;
        $century         = intval($year / 100);
        $year            = $year % 100;

        if ($hb_negativeyear) {
            // Subtract 1 because year 0 is a leap year;
            // And N.B. that we must treat the leap years as occurring
            // one year earlier than they do, because for the purposes
            // of calculation, the year starts on 1st March:
            //
            return intval((14609700 * $century + ($year == 0 ? 1 : 0)) / 400) +
                   intval((1461 * $year + 1) / 4) +
                   intval((153 * $month + 2) / 5) +
                   $day + 1721118;
        } else {
            return intval(146097 * $century / 4) +
                   intval(1461 * $year / 4) +
                   intval((153 * $month + 2) / 5) +
                   $day + 1721119;
        }
    }

    /**
     * Converts number of days since 24th November, 4714 B.C. (in the proleptic
     * Gregorian calendar, which is year -4713 using 'Astronomical' year
     * numbering) to Gregorian calendar date.
     *
     * Returned date belongs to the proleptic Gregorian calendar, using
     * 'Astronomical' year numbering.
     *
     * The algorithm is valid for all years (positive and negative), and
     * also for years preceding 4714 B.C. (i.e. for negative 'Julian Days'),
     * and so the only limitation is platform-dependent (for 32-bit systems
     * the maximum year would be something like about 1,465,190 A.D.).
     *
     * N.B. Monday, 24th November, 4714 B.C. is Julian Day '0'.
     *
     * Algorithm is from PEAR::Date_Calc
     *
     * @author Monte Ohrt <monte@ispi.net>
     * @author Pierre-Alain Joye <pajoye@php.net>
     * @author Daniel Convissor <danielc@php.net>
     * @author C.A. Woodcock <c01234@netcomuk.co.uk>
     *
     * @param int    $days   the number of days since 24th November, 4714 B.C.
     * @param string $format the string indicating how to format the output
     *
     * @return  Horde_Date  A Horde_Date object representing the date.
     */
    public static function fromDays($days)
    {
        if (function_exists('jdtogregorian')) {
            list($month, $day, $year) = explode('/', jdtogregorian($days));
        } else {
            $days = intval($days);

            $days   -= 1721119;
            $century = floor((4 * $days - 1) / 146097);
            $days    = floor(4 * $days - 1 - 146097 * $century);
            $day     = floor($days / 4);

            $year = floor((4 * $day +  3) / 1461);
            $day  = floor(4 * $day +  3 - 1461 * $year);
            $day  = floor(($day +  4) / 4);

            $month = floor((5 * $day - 3) / 153);
            $day   = floor(5 * $day - 3 - 153 * $month);
            $day   = floor(($day +  5) /  5);

            $year = $century * 100 + $year;
            if ($month < 10) {
                $month +=3;
            } else {
                $month -=9;
                ++$year;
            }
        }

        return new Horde_Date($year, $month, $day);
    }

    /**
     * Getter for the date and time properties.
     *
     * @param string $name  One of 'year', 'month', 'mday', 'hour', 'min',
     *                      'sec' or 'timezone' (since Horde_Date 2.0.0).
     *
     * @return integer|string  The property value, or null if not set.
     */
    public function __get($name)
    {
        if ($name == 'day') {
            $name = 'mday';
        }
        if ($name[0] == '_') {
            return null;
        }
        return $this->{'_' . $name};
    }

    /**
     * Setter for the date and time properties.
     *
     * @param string $name           One of 'year', 'month', 'mday', 'hour',
     *                               'min', 'sec' or 'timezone' (since
     *                               Horde_Date 2.0.0).
     * @param integer|string $value  The property value.
     */
    public function __set($name, $value)
    {
        if ($name == 'timezone') {
            $this->_initializeTimezone($value);
            return;
        }

        if ($name == 'day') {
            $name = 'mday';
        }

        if ($name != 'year' && $name != 'month' && $name != 'mday' &&
            $name != 'hour' && $name != 'min' && $name != 'sec') {
            throw new InvalidArgumentException('Undefined property ' . $name);
        }

        $down = $value < $this->{'_' . $name};
        $this->{'_' . $name} = $value;
        $this->_correct(self::$_corrections[$name], $down);
        $this->_formatCache = array();
    }

    /**
     * Returns whether a date or time property exists.
     *
     * @param string $name  One of 'year', 'month', 'mday', 'hour', 'min' or
     *                      'sec'.
     *
     * @return boolen  True if the property exists and is set.
     */
    public function __isset($name)
    {
        if ($name == 'day') {
            $name = 'mday';
        }
        return ($name == 'year' || $name == 'month' || $name == 'mday' ||
                $name == 'hour' || $name == 'min' || $name == 'sec') &&
            isset($this->{'_' . $name});
    }

    /**
     * Adds a number of seconds or units to this date, returning a new Date
     * object.
     */
    public function add($factor)
    {
        $d = clone($this);
        if (is_array($factor) || is_object($factor)) {
            foreach ($factor as $property => $value) {
                $d->$property += $value;
            }
        } else {
            $d->sec += $factor;
        }

        return $d;
    }

    /**
     * Subtracts a number of seconds or units from this date, returning a new
     * Horde_Date object.
     */
    public function sub($factor)
    {
        if (is_array($factor)) {
            foreach ($factor as &$value) {
                $value *= -1;
            }
        } else {
            $factor *= -1;
        }

        return $this->add($factor);
    }

    /**
     * Returns the normalized (Olson) timezone name of a timezone alias.
     *
     * We currently support Windows and Lotus timezone names, and timezone
     * abbreviations.
     *
     * @since Horde_Date 2.3.0
     *
     * @param string $timezone  Some timezone alias.
     *
     * @return string  The Olson timezone name, or the original value, if no
     *                 alias found.
     */
    public static function getTimezoneAlias($timezone)
    {
        if (empty(self::$_timezoneIdentifiers)) {
            self::$_timezoneIdentifiers = array_flip(DateTimeZone::listIdentifiers());
        }
        if (isset(self::$_timezoneIdentifiers[$timezone])) {
            return $timezone;
        }
        /* Workaround for standard cases of bug #11688 */
        if (isset(self::$_timezoneAliases[$timezone])) {
            $timezone = self::$_timezoneAliases[$timezone];
        }
        if (empty(self::$_timezoneAbbreviations)) {
            self::$_timezoneAbbreviations = DateTimeZone::listAbbreviations();
        }
        $lower = Horde_String::lower($timezone);
        if (isset(self::$_timezoneAbbreviations[$lower])) {
            $timezone = reset(self::$_timezoneAbbreviations[$lower]);
            $timezone = $timezone['timezone_id'];
        }
        return $timezone;
    }

    /**
     * Converts this object to a different timezone.
     *
     * @param string $timezone  The new timezone.
     *
     * @return Horde_Date  This object.
     * @throws Horde_Date_Exception
     */
    public function setTimezone($timezone)
    {
        $date = $this->toDateTime();
        $timezone = self::getTimezoneAlias($timezone);
        try {
            $date->setTimezone(new DateTimeZone($timezone));
        } catch (Exception $e) {
            throw new Horde_Date_Exception($e->getMessage());
        }
        $this->_timezone = $timezone;
        $this->_year     = (int)$date->format('Y');
        $this->_month    = (int)$date->format('m');
        $this->_mday     = (int)$date->format('d');
        $this->_hour     = (int)$date->format('H');
        $this->_min      = (int)$date->format('i');
        $this->_sec      = (int)$date->format('s');
        $this->_formatCache = array();
        return $this;
    }

    /**
     * Sets the default date format used in __toString()
     *
     * @param string $format
     */
    public function setDefaultFormat($format)
    {
        $this->_defaultFormat = $format;
    }

    /**
     * Returns the day of the week (0 = Sunday, 6 = Saturday) of this date.
     *
     * @return integer  The day of the week.
     */
    public function dayOfWeek()
    {
        if ($this->_month > 2) {
            $month = $this->_month - 2;
            $year = $this->_year;
        } else {
            $month = $this->_month + 10;
            $year = $this->_year - 1;
        }

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

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

    /**
     * Returns the day number of the year (1 to 365/366).
     *
     * @return integer  The day of the year.
     */
    public function dayOfYear()
    {
        return $this->format('z') + 1;
    }

    /**
     * Returns the week of the month.
     *
     * @return integer  The week number.
     */
    public function weekOfMonth()
    {
        return ceil($this->_mday / 7);
    }

    /**
     * Returns the week of the year, first Monday is first day of first week.
     *
     * @return integer  The week number.
     */
    public function weekOfYear()
    {
        return $this->format('W');
    }

    /**
     * Returns the number of weeks in the given year (52 or 53).
     *
     * @param integer $year  The year to count the number of weeks in.
     *
     * @return integer $numWeeks   The number of weeks in $year.
     */
    public static function weeksInYear($year)
    {
        // Find the last Thursday of the year.
        $date = new Horde_Date($year . '-12-31');
        while ($date->dayOfWeek() != self::DATE_THURSDAY) {
            --$date->mday;
        }
        return $date->weekOfYear();
    }

    /**
     * Sets the date of this object to the $nth weekday of $weekday.
     *
     * @param integer $weekday  The day of the week (0 = Sunday, etc).
     * @param integer $nth      The $nth $weekday to set to (defaults to 1).
     *                          Negative values count from end of the month
     *                          (@since Horde_Date 2.1.0).
     */
    public function setNthWeekday($weekday, $nth = 1)
    {
        if ($weekday < self::DATE_SUNDAY || $weekday > self::DATE_SATURDAY) {
            return;
        }

        if ($nth >= 0) {
            $this->_mday = 1;
            $first = $this->dayOfWeek();
            $this->_mday = $weekday - $first + 1;
            if ($weekday < $first) {
                $this->_mday += 7;
            }
            $diff = 7 * $nth - 7;
            $this->_mday += $diff;
            $this->_correct(self::MASK_DAY, false);
        } else {
            $this->_mday = Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
            $last = $this->dayOfWeek();
            $this->_mday -= $last - $weekday;
            if ($last < $weekday) {
                $this->_mday -= 7;
            }
            $diff = -7 * $nth - 7;
            $this->_mday -= $diff;
            $this->_correct(self::MASK_DAY, true);
            $this->_formatCache = array();
        }
    }

    /**
     * Is the date currently represented by this object a valid date?
     *
     * @return boolean  Validity, counting leap years, etc.
     */
    public function isValid()
    {
        return ($this->_year >= 0 && $this->_year <= 9999);
    }

    /**
     * Compares this date to another date object to see which one is
     * greater (later). Assumes that the dates are in the same
     * timezone.
     *
     * @param mixed $other  The date to compare to.
     *
     * @return integer  ==  0 if they are on the same date
     *                  >=  1 if $this is greater (later)
     *                  <= -1 if $other is greater (later)
     */
    public function compareDate($other)
    {
        if (!($other instanceof Horde_Date)) {
            $other = new Horde_Date($other);
        }

        if ($this->_year != $other->year) {
            return $this->_year - $other->year;
        }
        if ($this->_month != $other->month) {
            return $this->_month - $other->month;
        }

        return $this->_mday - $other->mday;
    }

    /**
     * Returns whether this date is after the other.
     *
     * @param mixed $other  The date to compare to.
     *
     * @return boolean  True if this date is after the other.
     */
    public function after($other)
    {
        return $this->compareDate($other) > 0;
    }

    /**
     * Returns whether this date is before the other.
     *
     * @param mixed $other  The date to compare to.
     *
     * @return boolean  True if this date is before the other.
     */
    public function before($other)
    {
        return $this->compareDate($other) < 0;
    }

    /**
     * Returns whether this date is the same like the other.
     *
     * @param mixed $other  The date to compare to.
     *
     * @return boolean  True if this date is the same like the other.
     */
    public function equals($other)
    {
        return $this->compareDate($other) == 0;
    }

    /**
     * Compares this to another date object by time, to see which one
     * is greater (later). Assumes that the dates are in the same
     * timezone.
     *
     * @param mixed $other  The date to compare to.
     *
     * @return integer  ==  0 if they are at the same time
     *                  >=  1 if $this is greater (later)
     *                  <= -1 if $other is greater (later)
     */
    public function compareTime($other)
    {
        if (!($other instanceof Horde_Date)) {
            $other = new Horde_Date($other);
        }

        if ($this->_hour != $other->hour) {
            return $this->_hour - $other->hour;
        }
        if ($this->_min != $other->min) {
            return $this->_min - $other->min;
        }

        return $this->_sec - $other->sec;
    }

    /**
     * Compares this to another date object, including times, to see
     * which one is greater (later). Assumes that the dates are in the
     * same timezone.
     *
     * @param mixed $other  The date to compare to.
     *
     * @return integer  ==  0 if they are equal
     *                  >=  1 if $this is greater (later)
     *                  <= -1 if $other is greater (later)
     */
    public function compareDateTime($other)
    {
        if (!($other instanceof Horde_Date)) {
            $other = new Horde_Date($other);
        }

        if ($diff = $this->compareDate($other)) {
            return $diff;
        }

        return $this->compareTime($other);
    }

    /**
     * Returns number of days between this date and another.
     *
     * @param Horde_Date $other  The other day to diff with.
     *
     * @return integer  The absolute number of days between the two dates.
     */
    public function diff($other)
    {
        return abs($this->toDays() - $other->toDays());
    }

    /**
     * Returns the time offset for local time zone.
     *
     * @param boolean $colon  Place a colon between hours and minutes?
     *
     * @return string  Timezone offset as a string in the format +HH:MM.
     */
    public function tzOffset($colon = true)
    {
        return $colon ? $this->format('P') : $this->format('O');
    }

    /**
     * Returns the unix timestamp representation of this date.
     *
     * @return integer  A unix timestamp.
     */
    public function timestamp()
    {
        if ($this->_year >= 1970 && $this->_year < 2038) {
            return mktime($this->_hour, $this->_min, $this->_sec,
                          $this->_month, $this->_mday, $this->_year);
        }
        return $this->format('U');
    }

    /**
     * Returns the unix timestamp representation of this date, 12:00am.
     *
     * @return integer  A unix timestamp.
     */
    public function datestamp()
    {
        if ($this->_year >= 1970 && $this->_year < 2038) {
            return mktime(0, 0, 0, $this->_month, $this->_mday, $this->_year);
        }
        $date = new DateTime($this->format('Y-m-d'));
        return $date->format('U');
    }

    /**
     * Formats date and time to be passed around as a short url parameter.
     *
     * @return string  Date and time.
     */
    public function dateString()
    {
        return sprintf('%04d%02d%02d', $this->_year, $this->_month, $this->_mday);
    }

    /**
     * Formats date and time to the ISO format used by JSON.
     *
     * @return string  Date and time.
     */
    public function toJson()
    {
        return $this->format(self::DATE_JSON);
    }

    /**
     * Formats date and time to the RFC 2445 iCalendar DATE-TIME format.
     *
     * @param boolean $floating  Whether to return a floating date-time
     *                           (without time zone information).
     *
     * @return string  Date and time.
     */
    public function toiCalendar($floating = false)
    {
        if ($floating) {
            return $this->format('Ymd\THis');
        }
        $dateTime = $this->toDateTime();
        $dateTime->setTimezone(new DateTimeZone('UTC'));
        return $dateTime->format('Ymd\THis\Z');
    }

    /**
     * Formats time using the specifiers available in date() or in the DateTime
     * class' format() method.
     *
     * To format in languages other than English, use strftime() instead.
     *
     * @param string $format
     *
     * @return string  Formatted time.
     */
    public function format($format)
    {
        if (!isset($this->_formatCache[$format])) {
            $this->_formatCache[$format] = $this->toDateTime()->format($format);
        }
        return $this->_formatCache[$format];
    }

    /**
     * Formats date and time using strftime() format.
     *
     * @return string  strftime() formatted date and time.
     */
    public function strftime($format)
    {
        if (preg_match('/%[^' . self::$_supportedSpecs . ']/', $format)) {
            return strftime($format, $this->timestamp());
        } else {
            return $this->_strftime($format);
        }
    }

    /**
     * Callback used to replace a strtime pattern
     *
     * @param array $matches  preg_replace_callback() matches.
     *
     * @return string Replacement string.
     */
    protected function _regexCallback($reg)
    {
        switch ($reg[0]) {
            case '%b':  return $this->strftime(Horde_Nls::getLangInfo(constant('ABMON_' . (int)$this->_month)));
            case '%B':  return $this->strftime(Horde_Nls::getLangInfo(constant('MON_' . (int)$this->_month)));
            case '%C':  return (int)($this->_year / 100);
            case '%-d':
            case '%#d': return sprintf('%d',   $this->_mday);
            case '%d':  return sprintf('%02d', $this->_mday);
            case '%D':  return $this->strftime('%m/%d/%y');
            case '%e':  return sprintf('%2d', $this->_mday);
            case '%-H':
            case '%#H': return sprintf('%d',   $this->_hour);
            case '%H':  return sprintf('%02d', $this->_hour);
            case '%-I':
            case '%#I': return sprintf('%d',   $this->_hour == 0 ? 12 : ($this->_hour > 12 ? $this->_hour - 12 : $this->_hour));
            case '%I':  return sprintf('%02d', $this->_hour == 0 ? 12 : ($this->_hour > 12 ? $this->_hour - 12 : $this->_hour));
            case '%-m':
            case '%#m': return sprintf('%d', $this->_month);
            case '%m':  return sprintf('%02d', $this->_month);
            case '%-M':
            case '%#M': return sprintf('%d', $this->_min);
            case '%M':  return sprintf('%02d', $this->_min);
            case '%n':  return "\n";
            case '%p':  return $this->strftime(Horde_Nls::getLangInfo($this->_hour < 12 ? AM_STR : PM_STR));
            case '%R':  return $this->strftime('%H:%M');
            case '%-S':
            case '%#S': return sprintf('%d', $this->_sec);
            case '%S':  return sprintf('%02d', $this->_sec);
            case '%t':  return "\t";
            case '%T':  return $this->strftime('%H:%M:%S');
            case '%x':  return $this->strftime(Horde_Nls::getLangInfo(D_FMT));
            case '%X':  return $this->strftime(Horde_Nls::getLangInfo(T_FMT));
            case '%y':  return substr(sprintf('%04d', $this->_year), -2);
            case '%Y':  return (int)$this->_year;
            case '%%':  return '%';
        }
        return $reg[0];
    }

    /**
     * Formats date and time using a limited set of the strftime() format.
     *
     * @return string  strftime() formatted date and time.
     */
    protected function _strftime($format)
    {
        return preg_replace_callback('/(%([-#]?)[%bBCdDeHImMnpRStTxXyY])/', array($this, '_regexCallback'), $format);
    }

    /**
     * Corrects any over- or underflows in any of the date's members.
     *
     * @param integer $mask  We may not want to correct some overflows.
     * @param integer $down  Whether to correct the date up or down.
     */
    protected function _correct($mask = self::MASK_ALLPARTS, $down = false)
    {
        if ($mask & self::MASK_SECOND) {
            if ($this->_sec < 0 || $this->_sec > 59) {
                $mask |= self::MASK_MINUTE;

                $this->_min += (int)($this->_sec / 60);
                $this->_sec %= 60;
                if ($this->_sec < 0) {
                    $this->_min--;
                    $this->_sec += 60;
                }
            }
        }

        if ($mask & self::MASK_MINUTE) {
            if ($this->_min < 0 || $this->_min > 59) {
                $mask |= self::MASK_HOUR;

                $this->_hour += (int)($this->_min / 60);
                $this->_min %= 60;
                if ($this->_min < 0) {
                    $this->_hour--;
                    $this->_min += 60;
                }
            }
        }

        if ($mask & self::MASK_HOUR) {
            if ($this->_hour < 0 || $this->_hour > 23) {
                $mask |= self::MASK_DAY;

                $this->_mday += (int)($this->_hour / 24);
                $this->_hour %= 24;
                if ($this->_hour < 0) {
                    $this->_mday--;
                    $this->_hour += 24;
                }
            }
        }

        if ($mask & self::MASK_MONTH) {
            $this->_correctMonth();
            /* When correcting the month, always correct the day too. Months
             * have different numbers of days. */
            if (isset($this->_mday)) {
                $mask |= self::MASK_DAY;
            }
        }

        if ($mask & self::MASK_DAY) {
            while ($this->_mday > (366 + 31)) {
                if ((Horde_Date_Utils::isLeapYear($this->_year) &&
                     ($this->_month <= 2)) ||
                    (Horde_Date_Utils::isLeapYear($this->_year + 1) &&
                     ($this->_month > 2))) {
                    $this->_mday -= 366;
                } else {
                    $this->_mday -= 365;
                }
                $this->_year++;
            }
            while ($this->_mday > 28 &&
                   $this->_mday > Horde_Date_Utils::daysInMonth($this->_month, $this->_year)) {
                if ($down) {
                    $this->_mday -= Horde_Date_Utils::daysInMonth($this->_month + 1, $this->_year) - Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
                } else {
                    $this->_mday -= Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
                    $this->_month++;
                }
                $this->_correctMonth();
            }
            while ($this->_mday < 1) {
                --$this->_month;
                $this->_correctMonth();
                $this->_mday += Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
            }
        }
    }

    /**
     * Corrects the current month.
     *
     * This cannot be done in _correct() because that would also trigger a
     * correction of the day, which would result in an infinite loop.
     */
    protected function _correctMonth()
    {
        $this->_year += (int)($this->_month / 12);
        $this->_month %= 12;
        if ($this->_month < 1) {
            $this->_year--;
            $this->_month += 12;
        }
    }

    /**
     * Handles args in order: year month day hour min sec tz
     */
    protected function _initializeFromArgs($args)
    {
        $tz = (isset($args[6])) ? array_pop($args) : null;
        $this->_initializeTimezone($tz);

        $args = array_slice($args, 0, 6);
        $keys = array('year' => 1, 'month' => 1, 'mday' => 1, 'hour' => 0, 'min' => 0, 'sec' => 0);
        $date = array_combine(array_slice(array_keys($keys), 0, count($args)), $args);
        $date = array_merge($keys, $date);

        $this->_initializeFromArray($date);
    }

    protected function _initializeFromArray($date)
    {
        if (isset($date['year']) && is_string($date['year']) && strlen($date['year']) == 2) {
            if ($date['year'] > 70) {
                $date['year'] += 1900;
            } else {
                $date['year'] += 2000;
            }
        }

        foreach ($date as $key => $val) {
            if (in_array($key, array('year', 'month', 'mday', 'hour', 'min', 'sec'))) {
                $this->{'_'. $key} = (int)$val;
            }
        }

        // If $date['day'] is present and numeric we may have been passed
        // a Horde_Form_datetime array.
        if (isset($date['day']) &&
            (string)(int)$date['day'] == $date['day']) {
            $this->_mday = (int)$date['day'];
        }
        // 'minute' key also from Horde_Form_datetime
        if (isset($date['minute']) &&
            (string)(int)$date['minute'] == $date['minute']) {
            $this->_min = (int)$date['minute'];
        }

        $this->_correct();
    }

    protected function _initializeFromObject($date)
    {
        if ($date instanceof DateTime) {
            $this->_year  = (int)$date->format('Y');
            $this->_month = (int)$date->format('m');
            $this->_mday  = (int)$date->format('d');
            $this->_hour  = (int)$date->format('H');
            $this->_min   = (int)$date->format('i');
            $this->_sec   = (int)$date->format('s');
            $this->_initializeTimezone($date->getTimezone()->getName());
        } else {
            $is_horde_date = $date instanceof Horde_Date;
            foreach (array('year', 'month', 'mday', 'hour', 'min', 'sec') as $key) {
                if ($is_horde_date || isset($date->$key)) {
                    $this->{'_' . $key} = (int)$date->$key;
                }
            }
            if (!$is_horde_date) {
                $this->_correct();
            } else {
                $this->_initializeTimezone($date->timezone);
            }
        }
    }

    protected function _initializeTimezone($timezone)
    {
        if (empty($timezone)) {
            $timezone = date_default_timezone_get();
        } elseif (array_key_exists($timezone, self::$_timezoneAliases)) {
            /* Workaround for standard cases of bug #11688 */
            $timezone = self::$_timezoneAliases[$timezone];
        }

        $this->_timezone = $timezone;
    }
}
