Update OOjs UI to v0.1.0-pre (40de4dabe6)
[lhc/web/wiklou.git] / includes / MWTimestamp.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 * The actual timestamp being wrapped (DateTime object).
49 * @var DateTime
50 */
51 public $timestamp;
52
53 /**
54 * Make a new timestamp and set it to the specified time,
55 * or the current time if unspecified.
56 *
57 * @since 1.20
58 *
59 * @param bool|string $timestamp Timestamp to set, or false for current time
60 */
61 public function __construct( $timestamp = false ) {
62 $this->setTimestamp( $timestamp );
63 }
64
65 /**
66 * Set the timestamp to the specified time, or the current time if unspecified.
67 *
68 * Parse the given timestamp into either a DateTime object or a Unix timestamp,
69 * and then store it.
70 *
71 * @since 1.20
72 *
73 * @param string|bool $ts Timestamp to store, or false for now
74 * @throws TimestampException
75 */
76 public function setTimestamp( $ts = false ) {
77 $da = array();
78 $strtime = '';
79
80 // We want to catch 0, '', null... but not date strings starting with a letter.
81 if ( !$ts || $ts === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) {
82 $uts = time();
83 $strtime = "@$uts";
84 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
85 # TS_DB
86 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
87 # TS_EXIF
88 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
89 # TS_MW
90 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
91 # TS_UNIX
92 $strtime = "@$ts"; // http://php.net/manual/en/datetime.formats.compound.php
93 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
94 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
95 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
96 str_replace( '+00:00', 'UTC', $ts ) );
97 } elseif ( preg_match(
98 '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z?$/',
99 $ts,
100 $da
101 ) ) {
102 # TS_ISO_8601
103 } elseif ( preg_match(
104 '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z?$/',
105 $ts,
106 $da
107 ) ) {
108 #TS_ISO_8601_BASIC
109 } elseif ( preg_match(
110 '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',
111 $ts,
112 $da
113 ) ) {
114 # TS_POSTGRES
115 } elseif ( preg_match(
116 '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',
117 $ts,
118 $da
119 ) ) {
120 # TS_POSTGRES
121 } elseif ( preg_match(
122 # Day of week
123 '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' .
124 # dd Mon yyyy
125 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' .
126 # hh:mm:ss
127 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S',
128 $ts
129 ) ) {
130 # TS_RFC2822, accepting a trailing comment.
131 # See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
132 # The regex is a superset of rfc2822 for readability
133 $strtime = strtok( $ts, ';' );
134 } 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 ) ) {
135 # TS_RFC850
136 $strtime = $ts;
137 } 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 ) ) {
138 # asctime
139 $strtime = $ts;
140 } else {
141 throw new TimestampException( __METHOD__ . ": Invalid timestamp - $ts" );
142 }
143
144 if ( !$strtime ) {
145 $da = array_map( 'intval', $da );
146 $da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
147 $strtime = call_user_func_array( "sprintf", $da );
148 }
149
150 try {
151 $final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
152 } catch ( Exception $e ) {
153 throw new TimestampException( __METHOD__ . ': Invalid timestamp format.', $e->getCode(), $e );
154 }
155
156 if ( $final === false ) {
157 throw new TimestampException( __METHOD__ . ': Invalid timestamp format.' );
158 }
159 $this->timestamp = $final;
160 }
161
162 /**
163 * Get the timestamp represented by this object in a certain form.
164 *
165 * Convert the internal timestamp to the specified format and then
166 * return it.
167 *
168 * @since 1.20
169 *
170 * @param int $style Constant Output format for timestamp
171 * @throws TimestampException
172 * @return string The formatted timestamp
173 */
174 public function getTimestamp( $style = TS_UNIX ) {
175 if ( !isset( self::$formats[$style] ) ) {
176 throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
177 }
178
179 $output = $this->timestamp->format( self::$formats[$style] );
180
181 if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
182 $output .= ' GMT';
183 }
184
185 return $output;
186 }
187
188 /**
189 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
190 *
191 * Determine the difference between the timestamp and the current time, and
192 * generate a readable timestamp by returning "<N> <units> ago", where the
193 * largest possible unit is used.
194 *
195 * @since 1.20
196 * @since 1.22 Uses Language::getHumanTimestamp to produce the timestamp
197 *
198 * @param MWTimestamp|null $relativeTo The base timestamp to compare to
199 * (defaults to now).
200 * @param User|null $user User the timestamp is being generated for (or null
201 * to use main context's user).
202 * @param Language|null $lang Language to use to make the human timestamp
203 * (or null to use main context's language).
204 * @return string Formatted timestamp
205 */
206 public function getHumanTimestamp( MWTimestamp $relativeTo = null,
207 User $user = null, Language $lang = null
208 ) {
209 if ( $relativeTo === null ) {
210 $relativeTo = new self();
211 }
212 if ( $user === null ) {
213 $user = RequestContext::getMain()->getUser();
214 }
215 if ( $lang === null ) {
216 $lang = RequestContext::getMain()->getLanguage();
217 }
218
219 // Adjust for the user's timezone.
220 $offsetThis = $this->offsetForUser( $user );
221 $offsetRel = $relativeTo->offsetForUser( $user );
222
223 $ts = '';
224 if ( wfRunHooks( 'GetHumanTimestamp', array( &$ts, $this, $relativeTo, $user, $lang ) ) ) {
225 $ts = $lang->getHumanTimestamp( $this, $relativeTo, $user );
226 }
227
228 // Reset the timezone on the objects.
229 $this->timestamp->sub( $offsetThis );
230 $relativeTo->timestamp->sub( $offsetRel );
231
232 return $ts;
233 }
234
235 /**
236 * Adjust the timestamp depending on the given user's preferences.
237 *
238 * @since 1.22
239 *
240 * @param User $user User to take preferences from
241 * @return DateInterval Offset that was applied to the timestamp
242 */
243 public function offsetForUser( User $user ) {
244 global $wgLocalTZoffset;
245
246 $option = $user->getOption( 'timecorrection' );
247 $data = explode( '|', $option, 3 );
248
249 // First handle the case of an actual timezone being specified.
250 if ( $data[0] == 'ZoneInfo' ) {
251 try {
252 $tz = new DateTimeZone( $data[2] );
253 } catch ( Exception $e ) {
254 $tz = false;
255 }
256
257 if ( $tz ) {
258 $this->timestamp->setTimezone( $tz );
259 return new DateInterval( 'P0Y' );
260 } else {
261 $data[0] = 'Offset';
262 }
263 }
264
265 $diff = 0;
266 // If $option is in fact a pipe-separated value, check the
267 // first value.
268 if ( $data[0] == 'System' ) {
269 // First value is System, so use the system offset.
270 if ( $wgLocalTZoffset !== null ) {
271 $diff = $wgLocalTZoffset;
272 }
273 } elseif ( $data[0] == 'Offset' ) {
274 // First value is Offset, so use the specified offset
275 $diff = (int)$data[1];
276 } else {
277 // $option actually isn't a pipe separated value, but instead
278 // a comma separated value. Isn't MediaWiki fun?
279 $data = explode( ':', $option );
280 if ( count( $data ) >= 2 ) {
281 // Combination hours and minutes.
282 $diff = abs( (int)$data[0] ) * 60 + (int)$data[1];
283 if ( (int)$data[0] < 0 ) {
284 $diff *= -1;
285 }
286 } else {
287 // Just hours.
288 $diff = (int)$data[0] * 60;
289 }
290 }
291
292 $interval = new DateInterval( 'PT' . abs( $diff ) . 'M' );
293 if ( $diff < 1 ) {
294 $interval->invert = 1;
295 }
296
297 $this->timestamp->add( $interval );
298 return $interval;
299 }
300
301 /**
302 * Generate a purely relative timestamp, i.e., represent the time elapsed between
303 * the given base timestamp and this object.
304 *
305 * @param MWTimestamp $relativeTo Relative base timestamp (defaults to now)
306 * @param User $user Use to use offset for
307 * @param Language $lang Language to use
308 * @param array $chosenIntervals Intervals to use to represent it
309 * @return string Relative timestamp
310 */
311 public function getRelativeTimestamp(
312 MWTimestamp $relativeTo = null,
313 User $user = null,
314 Language $lang = null,
315 array $chosenIntervals = array()
316 ) {
317 if ( $relativeTo === null ) {
318 $relativeTo = new self;
319 }
320 if ( $user === null ) {
321 $user = RequestContext::getMain()->getUser();
322 }
323 if ( $lang === null ) {
324 $lang = RequestContext::getMain()->getLanguage();
325 }
326
327 $ts = '';
328 $diff = $this->diff( $relativeTo );
329 if ( wfRunHooks(
330 'GetRelativeTimestamp',
331 array( &$ts, &$diff, $this, $relativeTo, $user, $lang )
332 ) ) {
333 $seconds = ( ( ( $diff->days * 24 + $diff->h ) * 60 + $diff->i ) * 60 + $diff->s );
334 $ts = wfMessage( 'ago', $lang->formatDuration( $seconds, $chosenIntervals ) )
335 ->inLanguage( $lang )->text();
336 }
337
338 return $ts;
339 }
340
341 /**
342 * @since 1.20
343 *
344 * @return string
345 */
346 public function __toString() {
347 return $this->getTimestamp();
348 }
349
350 /**
351 * Calculate the difference between two MWTimestamp objects.
352 *
353 * @since 1.22
354 * @param MWTimestamp $relativeTo Base time to calculate difference from
355 * @return DateInterval|bool The DateInterval object representing the
356 * difference between the two dates or false on failure
357 */
358 public function diff( MWTimestamp $relativeTo ) {
359 return $this->timestamp->diff( $relativeTo->timestamp );
360 }
361
362 /**
363 * Set the timezone of this timestamp to the specified timezone.
364 *
365 * @since 1.22
366 * @param string $timezone Timezone to set
367 * @throws TimestampException
368 */
369 public function setTimezone( $timezone ) {
370 try {
371 $this->timestamp->setTimezone( new DateTimeZone( $timezone ) );
372 } catch ( Exception $e ) {
373 throw new TimestampException( __METHOD__ . ': Invalid timezone.', $e->getCode(), $e );
374 }
375 }
376
377 /**
378 * Get the timezone of this timestamp.
379 *
380 * @since 1.22
381 * @return DateTimeZone The timezone
382 */
383 public function getTimezone() {
384 return $this->timestamp->getTimezone();
385 }
386
387 /**
388 * Format the timestamp in a given format.
389 *
390 * @since 1.22
391 * @param string $format Pattern to format in
392 * @return string The formatted timestamp
393 */
394 public function format( $format ) {
395 return $this->timestamp->format( $format );
396 }
397
398 /**
399 * Get a timestamp instance in the server local timezone ($wgLocaltimezone)
400 *
401 * @since 1.22
402 * @param bool|string $ts Timestamp to set, or false for current time
403 * @return MWTimestamp The local instance
404 */
405 public static function getLocalInstance( $ts = false ) {
406 global $wgLocaltimezone;
407 $timestamp = new self( $ts );
408 $timestamp->setTimezone( $wgLocaltimezone );
409 return $timestamp;
410 }
411
412 /**
413 * Get a timestamp instance in GMT
414 *
415 * @since 1.22
416 * @param bool|string $ts Timestamp to set, or false for current time
417 * @return MWTimestamp The instance
418 */
419 public static function getInstance( $ts = false ) {
420 return new self( $ts );
421 }
422 }