Merge "Enable $wgVectorUseIconWatch by default."
[lhc/web/wiklou.git] / includes / Timestamp.php
1 <?php
2 /**
3 * Creation and parsing of MW-style timestamps.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @since 1.20
22 * @author Tyler Romeo, 2012
23 */
24
25 /**
26 * Library for creating and parsing MW-style timestamps. Based on the JS
27 * library that does the same thing.
28 *
29 * @since 1.20
30 */
31 class MWTimestamp {
32 /**
33 * Standard gmdate() formats for the different timestamp types.
34 */
35 private static $formats = array(
36 TS_UNIX => 'U',
37 TS_MW => 'YmdHis',
38 TS_DB => 'Y-m-d H:i:s',
39 TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
40 TS_ISO_8601_BASIC => 'Ymd\THis\Z',
41 TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
42 TS_RFC2822 => 'D, d M Y H:i:s',
43 TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
44 TS_POSTGRES => 'Y-m-d H:i:s',
45 );
46
47 /**
48 * Different units for human readable timestamps.
49 * @see MWTimestamp::getHumanTimestamp
50 */
51 private static $units = array(
52 "milliseconds" => 1,
53 "seconds" => 1000, // 1000 milliseconds per second
54 "minutes" => 60, // 60 seconds per minute
55 "hours" => 60, // 60 minutes per hour
56 "days" => 24, // 24 hours per day
57 "months" => 30, // approximately 30 days per month
58 "years" => 12, // 12 months per year
59 );
60
61 /**
62 * The actual timestamp being wrapped. Either a DateTime
63 * object or a string with a Unix timestamp depending on
64 * PHP.
65 * @var string|DateTime
66 */
67 private $timestamp;
68
69 /**
70 * Make a new timestamp and set it to the specified time,
71 * or the current time if unspecified.
72 *
73 * @since 1.20
74 *
75 * @param bool|string $timestamp Timestamp to set, or false for current time
76 */
77 public function __construct( $timestamp = false ) {
78 $this->setTimestamp( $timestamp );
79 }
80
81 /**
82 * Set the timestamp to the specified time, or the current time if unspecified.
83 *
84 * Parse the given timestamp into either a DateTime object or a Unix timestamp,
85 * and then store it.
86 *
87 * @since 1.20
88 *
89 * @param string|bool $ts Timestamp to store, or false for now
90 * @throws TimestampException
91 */
92 public function setTimestamp( $ts = false ) {
93 $da = array();
94 $strtime = '';
95
96 if ( !$ts || $ts === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) { // We want to catch 0, '', null... but not date strings starting with a letter.
97 $uts = time();
98 $strtime = "@$uts";
99 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
100 # TS_DB
101 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
102 # TS_EXIF
103 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
104 # TS_MW
105 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
106 # TS_UNIX
107 $strtime = "@$ts"; // http://php.net/manual/en/datetime.formats.compound.php
108 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
109 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
110 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
111 str_replace( '+00:00', 'UTC', $ts ) );
112 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
113 # TS_ISO_8601
114 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
115 #TS_ISO_8601_BASIC
116 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
117 # TS_POSTGRES
118 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
119 # TS_POSTGRES
120 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
121 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
122 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss
123 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
124 # The regex is a superset of rfc2822 for readability
125 $strtime = strtok( $ts, ';' );
126 } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
127 # TS_RFC850
128 $strtime = $ts;
129 } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
130 # asctime
131 $strtime = $ts;
132 } else {
133 throw new TimestampException( __METHOD__ . " : Invalid timestamp - $ts" );
134 }
135
136 if( !$strtime ) {
137 $da = array_map( 'intval', $da );
138 $da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
139 $strtime = call_user_func_array( "sprintf", $da );
140 }
141
142 try {
143 $final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
144 } catch( Exception $e ) {
145 throw new TimestampException( __METHOD__ . ' Invalid timestamp format.' );
146 }
147
148 if( $final === false ) {
149 throw new TimestampException( __METHOD__ . ' Invalid timestamp format.' );
150 }
151 $this->timestamp = $final;
152 }
153
154 /**
155 * Get the timestamp represented by this object in a certain form.
156 *
157 * Convert the internal timestamp to the specified format and then
158 * return it.
159 *
160 * @since 1.20
161 *
162 * @param int $style Constant Output format for timestamp
163 * @throws TimestampException
164 * @return string The formatted timestamp
165 */
166 public function getTimestamp( $style = TS_UNIX ) {
167 if( !isset( self::$formats[$style] ) ) {
168 throw new TimestampException( __METHOD__ . ' : Illegal timestamp output type.' );
169 }
170
171 if( is_object( $this->timestamp ) ) {
172 // DateTime object was used, call DateTime::format.
173 $output = $this->timestamp->format( self::$formats[$style] );
174 } elseif( TS_UNIX == $style ) {
175 // Unix timestamp was used and is wanted, just return it.
176 $output = $this->timestamp;
177 } else {
178 // Unix timestamp was used, use gmdate().
179 $output = gmdate( self::$formats[$style], $this->timestamp );
180 }
181
182 if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
183 $output .= ' GMT';
184 }
185
186 return $output;
187 }
188
189 /**
190 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
191 *
192 * Determine the difference between the timestamp and the current time, and
193 * generate a readable timestamp by returning "<N> <units> ago", where the
194 * largest possible unit is used.
195 *
196 * @since 1.20
197 *
198 * @return Message Formatted timestamp
199 */
200 public function getHumanTimestamp() {
201 $then = $this->getTimestamp( TS_UNIX );
202 $now = time();
203 $timeago = ($now - $then) * 1000;
204 $message = false;
205
206 foreach( self::$units as $unit => $factor ) {
207 $next = $timeago / $factor;
208 if( $next < 1 ) {
209 break;
210 } else {
211 $timeago = $next;
212 $message = array( $unit, floor( $timeago ) );
213 }
214 }
215
216 if( $message ) {
217 $initial = call_user_func_array( 'wfMessage', $message );
218 return wfMessage( 'ago', $initial->parse() );
219 } else {
220 return wfMessage( 'just-now' );
221 }
222 }
223
224 /**
225 * @since 1.20
226 *
227 * @return string
228 */
229 public function __toString() {
230 return $this->getTimestamp();
231 }
232 }
233
234 /**
235 * @since 1.20
236 */
237 class TimestampException extends MWException {}