PageRenderTime 65ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Date/DateObject.php

https://github.com/sashafr/open-context-code
PHP | 1060 lines | 670 code | 176 blank | 214 comment | 149 complexity | 8fbb4fd0fc52dcbb3bb2278897350187 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Date
  17. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @version $Id: DateObject.php 9066 2008-03-27 16:47:14Z thomas $
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. */
  21. /**
  22. * @category Zend
  23. * @package Zend_Date
  24. * @subpackage Zend_Date_DateObject
  25. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  26. * @license http://framework.zend.com/license/new-bsd New BSD License
  27. */
  28. abstract class Zend_Date_DateObject {
  29. /**
  30. * UNIX Timestamp
  31. */
  32. private $_unixTimestamp;
  33. protected static $_cache = null;
  34. protected static $_defaultOffset = 0;
  35. /**
  36. * active timezone
  37. */
  38. private $_timezone = 'UTC';
  39. private $_offset = 0;
  40. private $_syncronised = 0;
  41. // turn off DST correction if UTC or GMT
  42. protected $_dst = true;
  43. /**
  44. * Table of Monthdays
  45. */
  46. private static $_monthTable = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  47. /**
  48. * Table of Years
  49. */
  50. private static $_yearTable = array(
  51. 1970 => 0, 1960 => -315619200, 1950 => -631152000,
  52. 1940 => -946771200, 1930 => -1262304000, 1920 => -1577923200,
  53. 1910 => -1893456000, 1900 => -2208988800, 1890 => -2524521600,
  54. 1880 => -2840140800, 1870 => -3155673600, 1860 => -3471292800,
  55. 1850 => -3786825600, 1840 => -4102444800, 1830 => -4417977600,
  56. 1820 => -4733596800, 1810 => -5049129600, 1800 => -5364662400,
  57. 1790 => -5680195200, 1780 => -5995814400, 1770 => -6311347200,
  58. 1760 => -6626966400, 1750 => -6942499200, 1740 => -7258118400,
  59. 1730 => -7573651200, 1720 => -7889270400, 1710 => -8204803200,
  60. 1700 => -8520336000, 1690 => -8835868800, 1680 => -9151488000,
  61. 1670 => -9467020800, 1660 => -9782640000, 1650 => -10098172800,
  62. 1640 => -10413792000, 1630 => -10729324800, 1620 => -11044944000,
  63. 1610 => -11360476800, 1600 => -11676096000);
  64. /**
  65. * Set this object to have a new UNIX timestamp.
  66. *
  67. * @param string|integer $timestamp OPTIONAL timestamp; defaults to local time using time()
  68. * @return string|integer old timestamp
  69. * @throws Zend_Date_Exception
  70. */
  71. protected function setUnixTimestamp($timestamp = null)
  72. {
  73. $old = $this->_unixTimestamp;
  74. if (is_numeric($timestamp)) {
  75. $this->_unixTimestamp = $timestamp;
  76. } else if ($timestamp === null) {
  77. $this->_unixTimestamp = time();
  78. } else {
  79. require_once 'Zend/Date/Exception.php';
  80. throw new Zend_Date_Exception('\'' . $timestamp . '\' is not a valid UNIX timestamp', $timestamp);
  81. }
  82. return $old;
  83. }
  84. /**
  85. * Returns this object's UNIX timestamp
  86. * A timestamp greater then the integer range will be returned as string
  87. * This function does not return the timestamp as object. Use copy() instead.
  88. *
  89. * @return integer|string timestamp
  90. */
  91. protected function getUnixTimestamp()
  92. {
  93. if ($this->_unixTimestamp === intval($this->_unixTimestamp)) {
  94. return (int) $this->_unixTimestamp;
  95. } else {
  96. return (string) $this->_unixTimestamp;
  97. }
  98. }
  99. /**
  100. * Internal function.
  101. * Returns time(). This method exists to allow unit tests to work-around methods that might otherwise
  102. * be hard-coded to use time(). For example, this makes it possible to test isYesterday() in Date.php.
  103. *
  104. * @param integer $sync OPTIONAL time syncronisation value
  105. * @return integer timestamp
  106. */
  107. protected function _getTime($sync = null)
  108. {
  109. if ($sync !== null) {
  110. $this->_syncronised = round($sync);
  111. }
  112. return (time() + $this->_syncronised);
  113. }
  114. /**
  115. * Internal mktime function used by Zend_Date.
  116. * The timestamp returned by mktime() can exceed the precision of traditional UNIX timestamps,
  117. * by allowing PHP to auto-convert to using a float value.
  118. *
  119. * Returns a timestamp relative to 1970/01/01 00:00:00 GMT/UTC.
  120. * DST (Summer/Winter) is depriciated since php 5.1.0.
  121. * Year has to be 4 digits otherwise it would be recognised as
  122. * year 70 AD instead of 1970 AD as expected !!
  123. *
  124. * @param integer $hour
  125. * @param integer $minute
  126. * @param integer $second
  127. * @param integer $month
  128. * @param integer $day
  129. * @param integer $year
  130. * @param boolean $gmt OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date
  131. * @return integer|float timestamp (number of seconds elapsed relative to 1970/01/01 00:00:00 GMT/UTC)
  132. */
  133. protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = false)
  134. {
  135. // complete date but in 32bit timestamp - use PHP internal
  136. if ((1901 < $year) and ($year < 2038)) {
  137. $oldzone = @date_default_timezone_get();
  138. // Timezone also includes DST settings, therefor substracting the GMT offset is not enough
  139. // We have to set the correct timezone to get the right value
  140. if (($this->_timezone != $oldzone) and ($gmt === false)) {
  141. date_default_timezone_set($this->_timezone);
  142. }
  143. $result = ($gmt) ? @gmmktime($hour, $minute, $second, $month, $day, $year)
  144. : @mktime($hour, $minute, $second, $month, $day, $year);
  145. date_default_timezone_set($oldzone);
  146. return $result;
  147. }
  148. if ($gmt !== true) {
  149. $second += $this->_offset;
  150. }
  151. if (isset(self::$_cache)) {
  152. $id = strtr('Zend_DateObject_mkTime_' . $this->_offset . '_' . $year.$month.$day.'_'.$hour.$minute.$second . '_'.(int)$gmt, '-','_');
  153. if ($result = self::$_cache->load($id)) {
  154. return unserialize($result);
  155. }
  156. }
  157. // date to integer
  158. $day = intval($day);
  159. $month = intval($month);
  160. $year = intval($year);
  161. // correct months > 12 and months < 1
  162. if ($month > 12) {
  163. $overlap = floor($month / 12);
  164. $year += $overlap;
  165. $month -= $overlap * 12;
  166. } else {
  167. $overlap = ceil((1 - $month) / 12);
  168. $year -= $overlap;
  169. $month += $overlap * 12;
  170. }
  171. $date = 0;
  172. if ($year >= 1970) {
  173. // Date is after UNIX epoch
  174. // go through leapyears
  175. // add months from latest given year
  176. for ($count = 1970; $count <= $year; $count++) {
  177. $leapyear = self::isYearLeapYear($count);
  178. if ($count < $year) {
  179. $date += 365;
  180. if ($leapyear === true) {
  181. $date++;
  182. }
  183. } else {
  184. for ($mcount = 0; $mcount < ($month - 1); $mcount++) {
  185. $date += self::$_monthTable[$mcount];
  186. if (($leapyear === true) and ($mcount == 1)) {
  187. $date++;
  188. }
  189. }
  190. }
  191. }
  192. $date += $day - 1;
  193. $date = (($date * 86400) + ($hour * 3600) + ($minute * 60) + $second);
  194. } else {
  195. // Date is before UNIX epoch
  196. // go through leapyears
  197. // add months from latest given year
  198. for ($count = 1969; $count >= $year; $count--) {
  199. $leapyear = self::isYearLeapYear($count);
  200. if ($count > $year)
  201. {
  202. $date += 365;
  203. if ($leapyear === true)
  204. $date++;
  205. } else {
  206. for ($mcount = 11; $mcount > ($month - 1); $mcount--) {
  207. $date += self::$_monthTable[$mcount];
  208. if (($leapyear === true) and ($mcount == 1)) {
  209. $date++;
  210. }
  211. }
  212. }
  213. }
  214. $date += (self::$_monthTable[$month - 1] - $day);
  215. $date = -(($date * 86400) + (86400 - (($hour * 3600) + ($minute * 60) + $second)));
  216. // gregorian correction for 5.Oct.1582
  217. if ($date < -12220185600) {
  218. $date += 864000;
  219. } else if ($date < -12219321600) {
  220. $date = -12219321600;
  221. }
  222. }
  223. if (isset(self::$_cache)) {
  224. self::$_cache->save( serialize($date), $id);
  225. }
  226. return $date;
  227. }
  228. /**
  229. * Returns true, if given $year is a leap year.
  230. *
  231. * @param integer $year
  232. * @return boolean true, if year is leap year
  233. */
  234. protected static function isYearLeapYear($year)
  235. {
  236. // all leapyears can be divided through 4
  237. if (($year % 4) != 0) {
  238. return false;
  239. }
  240. // all leapyears can be divided through 400
  241. if ($year % 400 == 0) {
  242. return true;
  243. } else if (($year > 1582) and ($year % 100 == 0)) {
  244. return false;
  245. }
  246. return true;
  247. }
  248. /**
  249. * Internal mktime function used by Zend_Date for handling 64bit timestamps.
  250. *
  251. * Returns a formatted date for a given timestamp.
  252. *
  253. * @param string $format format for output
  254. * @param mixed $timestamp
  255. * @param boolean $gmt OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date
  256. * @return string
  257. */
  258. protected function date($format, $timestamp = null, $gmt = false)
  259. {
  260. $oldzone = @date_default_timezone_get();
  261. if ($this->_timezone != $oldzone) {
  262. date_default_timezone_set($this->_timezone);
  263. }
  264. if ($timestamp === null) {
  265. $result = ($gmt) ? @gmdate($format) : @date($format);
  266. date_default_timezone_set($oldzone);
  267. return $result;
  268. }
  269. if (abs($timestamp) <= 0x7FFFFFFF) {
  270. $result = ($gmt) ? @gmdate($format, $timestamp) : @date($format, $timestamp);
  271. date_default_timezone_set($oldzone);
  272. return $result;
  273. }
  274. $jump = false;
  275. if (isset(self::$_cache)) {
  276. $idstamp = strtr('Zend_DateObject_date_' . $this->_offset . '_'. $timestamp . '_'.(int)$gmt, '-','_');
  277. if ($result2 = self::$_cache->load($idstamp)) {
  278. $timestamp = unserialize($result2);
  279. $jump = true;
  280. }
  281. }
  282. // check on false or null alone failes
  283. if (empty($gmt) and empty($jump)) {
  284. $tempstamp = $timestamp;
  285. if ($tempstamp > 0) {
  286. while (abs($tempstamp) > 0x7FFFFFFF) {
  287. $tempstamp -= (86400 * 23376);
  288. }
  289. $dst = date("I", $tempstamp);
  290. if ($dst === 1) {
  291. $timestamp += 3600;
  292. }
  293. $temp = date('Z', $tempstamp);
  294. $timestamp += $temp;
  295. }
  296. if (isset(self::$_cache)) {
  297. self::$_cache->save( serialize($timestamp), $idstamp);
  298. }
  299. }
  300. if (($timestamp < 0) and ($gmt !== true)) {
  301. $timestamp -= $this->_offset;
  302. }
  303. date_default_timezone_set($oldzone);
  304. $date = $this->getDateParts($timestamp, true);
  305. $length = strlen($format);
  306. $output = '';
  307. for ($i = 0; $i < $length; $i++) {
  308. switch($format[$i]) {
  309. // day formats
  310. case 'd': // day of month, 2 digits, with leading zero, 01 - 31
  311. $output .= (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']);
  312. break;
  313. case 'D': // day of week, 3 letters, Mon - Sun
  314. $output .= date('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday'])));
  315. break;
  316. case 'j': // day of month, without leading zero, 1 - 31
  317. $output .= $date['mday'];
  318. break;
  319. case 'l': // day of week, full string name, Sunday - Saturday
  320. $output .= date('l', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday'])));
  321. break;
  322. case 'N': // ISO 8601 numeric day of week, 1 - 7
  323. $day = self::dayOfWeek($date['year'], $date['mon'], $date['mday']);
  324. if ($day == 0) {
  325. $day = 7;
  326. }
  327. $output .= $day;
  328. break;
  329. case 'S': // english suffix for day of month, st nd rd th
  330. if (($date['mday'] % 10) == 1) {
  331. $output .= 'st';
  332. } else if ((($date['mday'] % 10) == 2) and ($date['mday'] != 12)) {
  333. $output .= 'nd';
  334. } else if (($date['mday'] % 10) == 3) {
  335. $output .= 'rd';
  336. } else {
  337. $output .= 'th';
  338. }
  339. break;
  340. case 'w': // numeric day of week, 0 - 6
  341. $output .= self::dayOfWeek($date['year'], $date['mon'], $date['mday']);
  342. break;
  343. case 'z': // day of year, 0 - 365
  344. $output .= $date['yday'];
  345. break;
  346. // week formats
  347. case 'W': // ISO 8601, week number of year
  348. $output .= $this->weekNumber($date['year'], $date['mon'], $date['mday']);
  349. break;
  350. // month formats
  351. case 'F': // string month name, january - december
  352. $output .= date('F', mktime(0, 0, 0, $date['mon'], 2, 1971));
  353. break;
  354. case 'm': // number of month, with leading zeros, 01 - 12
  355. $output .= (($date['mon'] < 10) ? '0' . $date['mon'] : $date['mon']);
  356. break;
  357. case 'M': // 3 letter month name, Jan - Dec
  358. $output .= date('M',mktime(0, 0, 0, $date['mon'], 2, 1971));
  359. break;
  360. case 'n': // number of month, without leading zeros, 1 - 12
  361. $output .= $date['mon'];
  362. break;
  363. case 't': // number of day in month
  364. $output .= self::$_monthTable[$date['mon'] - 1];
  365. break;
  366. // year formats
  367. case 'L': // is leap year ?
  368. $output .= (self::isYearLeapYear($date['year'])) ? '1' : '0';
  369. break;
  370. case 'o': // ISO 8601 year number
  371. $week = $this->weekNumber($date['year'], $date['mon'], $date['mday']);
  372. if (($week > 50) and ($date['mon'] == 1)) {
  373. $output .= ($date['year'] - 1);
  374. } else {
  375. $output .= $date['year'];
  376. }
  377. break;
  378. case 'Y': // year number, 4 digits
  379. $output .= $date['year'];
  380. break;
  381. case 'y': // year number, 2 digits
  382. $output .= substr($date['year'], strlen($date['year']) - 2, 2);
  383. break;
  384. // time formats
  385. case 'a': // lower case am/pm
  386. $output .= (($date['hours'] >= 12) ? 'pm' : 'am');
  387. break;
  388. case 'A': // upper case am/pm
  389. $output .= (($date['hours'] >= 12) ? 'PM' : 'AM');
  390. break;
  391. case 'B': // swatch internet time
  392. $dayseconds = ($date['hours'] * 3600) + ($date['minutes'] * 60) + $date['seconds'];
  393. if ($gmt === true) {
  394. $dayseconds += 3600;
  395. }
  396. $output .= (int) (($dayseconds % 86400) / 86.4);
  397. break;
  398. case 'g': // hours without leading zeros, 12h format
  399. if ($date['hours'] > 12) {
  400. $hour = $date['hours'] - 12;
  401. } else {
  402. if ($date['hours'] == 0) {
  403. $hour = '12';
  404. } else {
  405. $hour = $date['hours'];
  406. }
  407. }
  408. $output .= $hour;
  409. break;
  410. case 'G': // hours without leading zeros, 24h format
  411. $output .= $date['hours'];
  412. break;
  413. case 'h': // hours with leading zeros, 12h format
  414. if ($date['hours'] > 12) {
  415. $hour = $date['hours'] - 12;
  416. } else {
  417. if ($date['hours'] == 0) {
  418. $hour = '12';
  419. } else {
  420. $hour = $date['hours'];
  421. }
  422. }
  423. $output .= (($hour < 10) ? '0'.$hour : $hour);
  424. break;
  425. case 'H': // hours with leading zeros, 24h format
  426. $output .= (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']);
  427. break;
  428. case 'i': // minutes with leading zeros
  429. $output .= (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']);
  430. break;
  431. case 's': // seconds with leading zeros
  432. $output .= (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']);
  433. break;
  434. // timezone formats
  435. case 'e': // timezone identifier
  436. if ($gmt === true) {
  437. $output .= gmdate('e', mktime($date['hours'], $date['minutes'], $date['seconds'],
  438. $date['mon'], $date['mday'], 2000));
  439. } else {
  440. $output .= date('e', mktime($date['hours'], $date['minutes'], $date['seconds'],
  441. $date['mon'], $date['mday'], 2000));
  442. }
  443. break;
  444. case 'I': // daylight saving time or not
  445. if ($gmt === true) {
  446. $output .= gmdate('I', mktime($date['hours'], $date['minutes'], $date['seconds'],
  447. $date['mon'], $date['mday'], 2000));
  448. } else {
  449. $output .= date('I', mktime($date['hours'], $date['minutes'], $date['seconds'],
  450. $date['mon'], $date['mday'], 2000));
  451. }
  452. break;
  453. case 'O': // difference to GMT in hours
  454. $gmtstr = ($gmt === true) ? 0 : $this->_offset;
  455. $output .= sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36);
  456. break;
  457. case 'P': // difference to GMT with colon
  458. $gmtstr = ($gmt === true) ? 0 : $this->_offset;
  459. $gmtstr = sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36);
  460. $output = $output . substr($gmtstr, 0, 3) . ':' . substr($gmtstr, 3);
  461. break;
  462. case 'T': // timezone settings
  463. if ($gmt === true) {
  464. $output .= gmdate('T', mktime($date['hours'], $date['minutes'], $date['seconds'],
  465. $date['mon'], $date['mday'], 2000));
  466. } else {
  467. $output .= date('T', mktime($date['hours'], $date['minutes'], $date['seconds'],
  468. $date['mon'], $date['mday'], 2000));
  469. }
  470. break;
  471. case 'Z': // timezone offset in seconds
  472. $output .= ($gmt === true) ? 0 : -$this->_offset;
  473. break;
  474. // complete time formats
  475. case 'c': // ISO 8601 date format
  476. $difference = $this->_offset;
  477. $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36);
  478. $output .= $date['year'] . '-'
  479. . (($date['mon'] < 10) ? '0' . $date['mon'] : $date['mon']) . '-'
  480. . (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']) . 'T'
  481. . (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']) . ':'
  482. . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':'
  483. . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds'])
  484. . $difference;
  485. break;
  486. case 'r': // RFC 2822 date format
  487. $difference = $this->_offset;
  488. $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36);
  489. $output .= gmdate('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday']))) . ', '
  490. . (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']) . ' '
  491. . date('M', mktime(0, 0, 0, $date['mon'], 2, 1971)) . ' '
  492. . $date['year'] . ' '
  493. . (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']) . ':'
  494. . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':'
  495. . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']) . ' '
  496. . $difference;
  497. break;
  498. case 'U': // Unix timestamp
  499. $output .= $timestamp;
  500. break;
  501. // special formats
  502. case "\\": // next letter to print with no format
  503. $i++;
  504. if ($i < $length) {
  505. $output .= $format[$i];
  506. }
  507. break;
  508. default: // letter is no format so add it direct
  509. $output .= $format[$i];
  510. break;
  511. }
  512. }
  513. return (string) $output;
  514. }
  515. /**
  516. * Returns the day of week for a Gregorian calendar date.
  517. * 0 = sunday, 6 = saturday
  518. *
  519. * @param integer $year
  520. * @param integer $month
  521. * @param integer $day
  522. * @return integer dayOfWeek
  523. */
  524. protected static function dayOfWeek($year, $month, $day)
  525. {
  526. if ((1901 < $year) and ($year < 2038)) {
  527. return (int) date('w', mktime(0, 0, 0, $month, $day, $year));
  528. }
  529. // gregorian correction
  530. $correction = 0;
  531. if (($year < 1582) or (($year == 1582) and (($month < 10) or (($month == 10) && ($day < 15))))) {
  532. $correction = 3;
  533. }
  534. if ($month > 2) {
  535. $month -= 2;
  536. } else {
  537. $month += 10;
  538. $year--;
  539. }
  540. $day = floor((13 * $month - 1) / 5) + $day + ($year % 100) + floor(($year % 100) / 4);
  541. $day += floor(($year / 100) / 4) - 2 * floor($year / 100) + 77 + $correction;
  542. return (int) ($day - 7 * floor($day / 7));
  543. }
  544. /**
  545. * Internal getDateParts function for handling 64bit timestamps, similar to:
  546. * http://www.php.net/getdate
  547. *
  548. * Returns an array of date parts for $timestamp, relative to 1970/01/01 00:00:00 GMT/UTC.
  549. *
  550. * $fast specifies ALL date parts should be returned (slower)
  551. * Default is false, and excludes $dayofweek, weekday, month and timestamp from parts returned.
  552. *
  553. * @param mixed $timestamp
  554. * @param boolean $fast OPTIONAL defaults to fast (false), resulting in fewer date parts
  555. * @return array
  556. */
  557. protected function getDateParts($timestamp = null, $fast = null)
  558. {
  559. // actual timestamp
  560. if ($timestamp === null) {
  561. return getdate();
  562. }
  563. // 32bit timestamp
  564. if (abs($timestamp) <= 0x7FFFFFFF) {
  565. return @getdate($timestamp);
  566. }
  567. if (isset(self::$_cache)) {
  568. $id = strtr('Zend_DateObject_getDateParts_' . $timestamp.'_'.(int)$fast, '-','_');
  569. if ($result = self::$_cache->load($id)) {
  570. return unserialize($result);
  571. }
  572. }
  573. $otimestamp = $timestamp;
  574. $numday = 0;
  575. $month = 0;
  576. // gregorian correction
  577. if ($timestamp < -12219321600) {
  578. $timestamp -= 864000;
  579. }
  580. // timestamp lower 0
  581. if ($timestamp < 0) {
  582. $sec = 0;
  583. $act = 1970;
  584. // iterate through 10 years table, increasing speed
  585. foreach(self::$_yearTable as $year => $seconds) {
  586. if ($timestamp >= $seconds) {
  587. $i = $act;
  588. break;
  589. }
  590. $sec = $seconds;
  591. $act = $year;
  592. }
  593. $timestamp -= $sec;
  594. if (!isset($i)) {
  595. $i = $act;
  596. }
  597. // iterate the max last 10 years
  598. do {
  599. --$i;
  600. $day = $timestamp;
  601. $timestamp += 31536000;
  602. $leapyear = self::isYearLeapYear($i);
  603. if ($leapyear === true) {
  604. $timestamp += 86400;
  605. }
  606. if ($timestamp >= 0) {
  607. $year = $i;
  608. break;
  609. }
  610. } while ($timestamp < 0);
  611. $secondsPerYear = 86400 * ($leapyear ? 366 : 365) + $day;
  612. $timestamp = $day;
  613. // iterate through months
  614. for ($i = 12; --$i >= 0;) {
  615. $day = $timestamp;
  616. $timestamp += self::$_monthTable[$i] * 86400;
  617. if (($leapyear === true) and ($i == 1)) {
  618. $timestamp += 86400;
  619. }
  620. if ($timestamp >= 0) {
  621. $month = $i;
  622. $numday = self::$_monthTable[$i];
  623. if (($leapyear === true) and ($i == 1)) {
  624. ++$numday;
  625. }
  626. break;
  627. }
  628. }
  629. $timestamp = $day;
  630. $numberdays = $numday + ceil(($timestamp + 1) / 86400);
  631. $timestamp += ($numday - $numberdays + 1) * 86400;
  632. $hours = floor($timestamp / 3600);
  633. } else {
  634. // iterate through years
  635. for ($i = 1970;;$i++) {
  636. $day = $timestamp;
  637. $timestamp -= 31536000;
  638. $leapyear = self::isYearLeapYear($i);
  639. if ($leapyear === true) {
  640. $timestamp -= 86400;
  641. }
  642. if ($timestamp < 0) {
  643. $year = $i;
  644. break;
  645. }
  646. }
  647. $secondsPerYear = $day;
  648. $timestamp = $day;
  649. // iterate through months
  650. for ($i = 0; $i <= 11; $i++) {
  651. $day = $timestamp;
  652. $timestamp -= self::$_monthTable[$i] * 86400;
  653. if (($leapyear === true) and ($i == 1)) {
  654. $timestamp -= 86400;
  655. }
  656. if ($timestamp < 0) {
  657. $month = $i;
  658. $numday = self::$_monthTable[$i];
  659. if (($leapyear === true) and ($i == 1)) {
  660. ++$numday;
  661. }
  662. break;
  663. }
  664. }
  665. $timestamp = $day;
  666. $numberdays = ceil(($timestamp + 1) / 86400);
  667. $timestamp = $timestamp - ($numberdays - 1) * 86400;
  668. $hours = floor($timestamp / 3600);
  669. }
  670. $timestamp -= $hours * 3600;
  671. $month += 1;
  672. $minutes = floor($timestamp / 60);
  673. $seconds = $timestamp - $minutes * 60;
  674. if ($fast === true) {
  675. $array = array(
  676. 'seconds' => $seconds,
  677. 'minutes' => $minutes,
  678. 'hours' => $hours,
  679. 'mday' => $numberdays,
  680. 'mon' => $month,
  681. 'year' => $year,
  682. 'yday' => floor($secondsPerYear / 86400),
  683. );
  684. } else {
  685. $dayofweek = self::dayOfWeek($year, $month, $numberdays);
  686. $array = array(
  687. 'seconds' => $seconds,
  688. 'minutes' => $minutes,
  689. 'hours' => $hours,
  690. 'mday' => $numberdays,
  691. 'wday' => $dayofweek,
  692. 'mon' => $month,
  693. 'year' => $year,
  694. 'yday' => floor($secondsPerYear / 86400),
  695. 'weekday' => gmdate('l', 86400 * (3 + $dayofweek)),
  696. 'month' => gmdate('F', mktime(0, 0, 0, $month, 1, 1971)),
  697. 0 => $otimestamp
  698. );
  699. }
  700. if (isset(self::$_cache)) {
  701. self::$_cache->save( serialize($array), $id);
  702. }
  703. return $array;
  704. }
  705. /**
  706. * Internal getWeekNumber function for handling 64bit timestamps
  707. *
  708. * Returns the ISO 8601 week number of a given date
  709. *
  710. * @param integer $year
  711. * @param integer $month
  712. * @param integer $day
  713. * @return integer
  714. */
  715. protected function weekNumber($year, $month, $day)
  716. {
  717. if ((1901 < $year) and ($year < 2038)) {
  718. return (int) date('W', mktime(0, 0, 0, $month, $day, $year));
  719. }
  720. $dayofweek = self::dayOfWeek($year, $month, $day);
  721. $firstday = self::dayOfWeek($year, 1, 1);
  722. if (($month == 1) and (($firstday < 1) or ($firstday > 4)) and ($day < 4)) {
  723. $firstday = self::dayOfWeek($year - 1, 1, 1);
  724. $month = 12;
  725. $day = 31;
  726. } else if (($month == 12) and ((self::dayOfWeek($year + 1, 1, 1) < 5) and
  727. (self::dayOfWeek($year + 1, 1, 1) > 0))) {
  728. return 1;
  729. }
  730. return intval (((self::dayOfWeek($year, 1, 1) < 5) and (self::dayOfWeek($year, 1, 1) > 0)) +
  731. 4 * ($month - 1) + (2 * ($month - 1) + ($day - 1) + $firstday - $dayofweek + 6) * 36 / 256);
  732. }
  733. /**
  734. * Internal _range function
  735. * Sets the value $a to be in the range of [0, $b]
  736. *
  737. * @param float $a - value to correct
  738. * @param float $b - maximum range to set
  739. */
  740. private function _range($a, $b) {
  741. while ($a < 0) {
  742. $a += $b;
  743. }
  744. while ($a >= $b) {
  745. $a -= $b;
  746. }
  747. return $a;
  748. }
  749. /**
  750. * Calculates the sunrise or sunset based on a location
  751. *
  752. * @param array $location Location for calculation MUST include 'latitude', 'longitude', 'horizon'
  753. * @param bool $horizon true: sunrise; false: sunset
  754. * @return mixed - false: midnight sun, integer:
  755. */
  756. protected function calcSun($location, $horizon, $rise = false)
  757. {
  758. // timestamp within 32bit
  759. if (abs($this->_unixTimestamp) <= 0x7FFFFFFF) {
  760. if ($rise === false) {
  761. return date_sunset($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'],
  762. $location['longitude'], 90 + $horizon, $this->_offset / 3600);
  763. }
  764. return date_sunrise($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'],
  765. $location['longitude'], 90 + $horizon, $this->_offset / 3600);
  766. }
  767. // self calculation - timestamp bigger than 32bit
  768. // fix circle values
  769. $quarterCircle = 0.5 * M_PI;
  770. $halfCircle = M_PI;
  771. $threeQuarterCircle = 1.5 * M_PI;
  772. $fullCircle = 2 * M_PI;
  773. // radiant conversion for coordinates
  774. $radLatitude = $location['latitude'] * $halfCircle / 180;
  775. $radLongitude = $location['longitude'] * $halfCircle / 180;
  776. // get solar coordinates
  777. $tmpRise = $rise ? $quarterCircle : $threeQuarterCircle;
  778. $radDay = $this->date('z',$this->_unixTimestamp) + ($tmpRise - $radLongitude) / $fullCircle;
  779. // solar anomoly and longitude
  780. $solAnomoly = $radDay * 0.017202 - 0.0574039;
  781. $solLongitude = $solAnomoly + 0.0334405 * sin($solAnomoly);
  782. $solLongitude += 4.93289 + 3.49066E-4 * sin(2 * $solAnomoly);
  783. // get quadrant
  784. $solLongitude = $this->_range($solLongitude, $fullCircle);
  785. if (($solLongitude / $quarterCircle) - intval($solLongitude / $quarterCircle) == 0) {
  786. $solLongitude += 4.84814E-6;
  787. }
  788. // solar ascension
  789. $solAscension = sin($solLongitude) / cos($solLongitude);
  790. $solAscension = atan2(0.91746 * $solAscension, 1);
  791. // adjust quadrant
  792. if ($solLongitude > $threeQuarterCircle) {
  793. $solAscension += $fullCircle;
  794. } else if ($solLongitude > $quarterCircle) {
  795. $solAscension += $halfCircle;
  796. }
  797. // solar declination
  798. $solDeclination = 0.39782 * sin($solLongitude);
  799. $solDeclination /= sqrt(-$solDeclination * $solDeclination + 1);
  800. $solDeclination = atan2($solDeclination, 1);
  801. $solHorizon = $horizon - sin($solDeclination) * sin($radLatitude);
  802. $solHorizon /= cos($solDeclination) * cos($radLatitude);
  803. // midnight sun, always night
  804. if (abs($solHorizon) > 1) {
  805. return false;
  806. }
  807. $solHorizon /= sqrt(-$solHorizon * $solHorizon + 1);
  808. $solHorizon = $quarterCircle - atan2($solHorizon, 1);
  809. if ($rise) {
  810. $solHorizon = $fullCircle - $solHorizon;
  811. }
  812. // time calculation
  813. $localTime = $solHorizon + $solAscension - 0.0172028 * $radDay - 1.73364;
  814. $universalTime = $localTime - $radLongitude;
  815. // determinate quadrant
  816. $universalTime = $this->_range($universalTime, $fullCircle);
  817. // radiant to hours
  818. $universalTime *= 24 / $fullCircle;
  819. // convert to time
  820. $hour = intval($universalTime);
  821. $universalTime = ($universalTime - $hour) * 60;
  822. $min = intval($universalTime);
  823. $universalTime = ($universalTime - $min) * 60;
  824. $sec = intval($universalTime);
  825. return $this->mktime($hour, $min, $sec, $this->date('m', $this->_unixTimestamp),
  826. $this->date('j', $this->_unixTimestamp), $this->date('Y', $this->_unixTimestamp),
  827. -1, true);
  828. }
  829. /**
  830. * Sets a new timezone for calculation of $this object's gmt offset.
  831. * For a list of supported timezones look here: http://php.net/timezones
  832. * If no timezone can be detected or the given timezone is wrong UTC will be set.
  833. *
  834. * @param string $zone OPTIONAL timezone for date calculation; defaults to date_default_timezone_get()
  835. * @return string actual set timezone string
  836. * @throws Zend_Date_Exception
  837. */
  838. public function setTimezone($zone = null)
  839. {
  840. $oldzone = @date_default_timezone_get();
  841. if ($zone === null) {
  842. $zone = $oldzone;
  843. }
  844. // throw an error on false input, but only if the new date extension is available
  845. if (function_exists('timezone_open')) {
  846. if (!@timezone_open($zone)) {
  847. require_once 'Zend/Date/Exception.php';
  848. throw new Zend_Date_Exception("timezone ($zone) is not a known timezone", $zone);
  849. }
  850. }
  851. // this can generate an error if the date extension is not available and a false timezone is given
  852. $result = @date_default_timezone_set($zone);
  853. if ($result === true) {
  854. $this->_offset = mktime(0, 0, 0, 1, 2, 1970) - gmmktime(0, 0, 0, 1, 2, 1970);
  855. $this->_timezone = $zone;
  856. }
  857. date_default_timezone_set($oldzone);
  858. if (($zone == 'UTC') or ($zone == 'GMT')) {
  859. $this->_dst = false;
  860. }
  861. return $result;
  862. }
  863. /**
  864. * Return the timezone of $this object.
  865. * The timezone is initially set when the object is instantiated.
  866. *
  867. * @return string actual set timezone string
  868. */
  869. public function getTimezone()
  870. {
  871. return $this->_timezone;
  872. }
  873. /**
  874. * Return the offset to GMT of $this object's timezone.
  875. * The offset to GMT is initially set when the object is instantiated using the currently,
  876. * in effect, default timezone for PHP functions.
  877. *
  878. * @return integer seconds difference between GMT timezone and timezone when object was instantiated
  879. */
  880. public function getGmtOffset()
  881. {
  882. return $this->_offset;
  883. }
  884. }