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