Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / MWTimestamp.php
blobea91470e852f083200b94df149e74d1d1faac5b3
1 <?php
2 /**
3 * Creation and parsing of MW-style timestamps.
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.
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.
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
20 * @file
21 * @since 1.20
22 * @author Tyler Romeo, 2012
25 /**
26 * Library for creating and parsing MW-style timestamps. Based on the JS
27 * library that does the same thing.
29 * @since 1.20
31 class MWTimestamp {
32 /**
33 * Standard gmdate() formats for the different timestamp types.
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',
47 /**
48 * The actual timestamp being wrapped (DateTime object).
49 * @var DateTime
51 public $timestamp;
53 /**
54 * Make a new timestamp and set it to the specified time,
55 * or the current time if unspecified.
57 * @since 1.20
59 * @param bool|string $timestamp Timestamp to set, or false for current time
61 public function __construct( $timestamp = false ) {
62 $this->setTimestamp( $timestamp );
65 /**
66 * Set the timestamp to the specified time, or the current time if unspecified.
68 * Parse the given timestamp into either a DateTime object or a Unix timestamp,
69 * and then store it.
71 * @since 1.20
73 * @param string|bool $ts Timestamp to store, or false for now
74 * @throws TimestampException
76 public function setTimestamp( $ts = false ) {
77 $da = array();
78 $strtime = '';
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,
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,
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,
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,
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',
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" );
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 );
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 );
156 if ( $final === false ) {
157 throw new TimestampException( __METHOD__ . ': Invalid timestamp format.' );
159 $this->timestamp = $final;
163 * Get the timestamp represented by this object in a certain form.
165 * Convert the internal timestamp to the specified format and then
166 * return it.
168 * @since 1.20
170 * @param int $style Constant Output format for timestamp
171 * @throws TimestampException
172 * @return string The formatted timestamp
174 public function getTimestamp( $style = TS_UNIX ) {
175 if ( !isset( self::$formats[$style] ) ) {
176 throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
179 $output = $this->timestamp->format( self::$formats[$style] );
181 if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
182 $output .= ' GMT';
185 if ( $style == TS_MW && strlen( $output ) !== 14 ) {
186 throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
187 'the specified format' );
190 return $output;
194 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
196 * Determine the difference between the timestamp and the current time, and
197 * generate a readable timestamp by returning "<N> <units> ago", where the
198 * largest possible unit is used.
200 * @since 1.20
201 * @since 1.22 Uses Language::getHumanTimestamp to produce the timestamp
203 * @param MWTimestamp|null $relativeTo The base timestamp to compare to
204 * (defaults to now).
205 * @param User|null $user User the timestamp is being generated for (or null
206 * to use main context's user).
207 * @param Language|null $lang Language to use to make the human timestamp
208 * (or null to use main context's language).
209 * @return string Formatted timestamp
211 public function getHumanTimestamp( MWTimestamp $relativeTo = null,
212 User $user = null, Language $lang = null
214 if ( $relativeTo === null ) {
215 $relativeTo = new self();
217 if ( $user === null ) {
218 $user = RequestContext::getMain()->getUser();
220 if ( $lang === null ) {
221 $lang = RequestContext::getMain()->getLanguage();
224 // Adjust for the user's timezone.
225 $offsetThis = $this->offsetForUser( $user );
226 $offsetRel = $relativeTo->offsetForUser( $user );
228 $ts = '';
229 if ( Hooks::run( 'GetHumanTimestamp', array( &$ts, $this, $relativeTo, $user, $lang ) ) ) {
230 $ts = $lang->getHumanTimestamp( $this, $relativeTo, $user );
233 // Reset the timezone on the objects.
234 $this->timestamp->sub( $offsetThis );
235 $relativeTo->timestamp->sub( $offsetRel );
237 return $ts;
241 * Adjust the timestamp depending on the given user's preferences.
243 * @since 1.22
245 * @param User $user User to take preferences from
246 * @return DateInterval Offset that was applied to the timestamp
248 public function offsetForUser( User $user ) {
249 global $wgLocalTZoffset;
251 $option = $user->getOption( 'timecorrection' );
252 $data = explode( '|', $option, 3 );
254 // First handle the case of an actual timezone being specified.
255 if ( $data[0] == 'ZoneInfo' ) {
256 try {
257 $tz = new DateTimeZone( $data[2] );
258 } catch ( Exception $e ) {
259 $tz = false;
262 if ( $tz ) {
263 $this->timestamp->setTimezone( $tz );
264 return new DateInterval( 'P0Y' );
265 } else {
266 $data[0] = 'Offset';
270 $diff = 0;
271 // If $option is in fact a pipe-separated value, check the
272 // first value.
273 if ( $data[0] == 'System' ) {
274 // First value is System, so use the system offset.
275 if ( $wgLocalTZoffset !== null ) {
276 $diff = $wgLocalTZoffset;
278 } elseif ( $data[0] == 'Offset' ) {
279 // First value is Offset, so use the specified offset
280 $diff = (int)$data[1];
281 } else {
282 // $option actually isn't a pipe separated value, but instead
283 // a comma separated value. Isn't MediaWiki fun?
284 $data = explode( ':', $option );
285 if ( count( $data ) >= 2 ) {
286 // Combination hours and minutes.
287 $diff = abs( (int)$data[0] ) * 60 + (int)$data[1];
288 if ( (int)$data[0] < 0 ) {
289 $diff *= -1;
291 } else {
292 // Just hours.
293 $diff = (int)$data[0] * 60;
297 $interval = new DateInterval( 'PT' . abs( $diff ) . 'M' );
298 if ( $diff < 1 ) {
299 $interval->invert = 1;
302 $this->timestamp->add( $interval );
303 return $interval;
307 * Generate a purely relative timestamp, i.e., represent the time elapsed between
308 * the given base timestamp and this object.
310 * @param MWTimestamp $relativeTo Relative base timestamp (defaults to now)
311 * @param User $user Use to use offset for
312 * @param Language $lang Language to use
313 * @param array $chosenIntervals Intervals to use to represent it
314 * @return string Relative timestamp
316 public function getRelativeTimestamp(
317 MWTimestamp $relativeTo = null,
318 User $user = null,
319 Language $lang = null,
320 array $chosenIntervals = array()
322 if ( $relativeTo === null ) {
323 $relativeTo = new self;
325 if ( $user === null ) {
326 $user = RequestContext::getMain()->getUser();
328 if ( $lang === null ) {
329 $lang = RequestContext::getMain()->getLanguage();
332 $ts = '';
333 $diff = $this->diff( $relativeTo );
334 if ( Hooks::run(
335 'GetRelativeTimestamp',
336 array( &$ts, &$diff, $this, $relativeTo, $user, $lang )
337 ) ) {
338 $seconds = ( ( ( $diff->days * 24 + $diff->h ) * 60 + $diff->i ) * 60 + $diff->s );
339 $ts = wfMessage( 'ago', $lang->formatDuration( $seconds, $chosenIntervals ) )
340 ->inLanguage( $lang )->text();
343 return $ts;
347 * @since 1.20
349 * @return string
351 public function __toString() {
352 return $this->getTimestamp();
356 * Calculate the difference between two MWTimestamp objects.
358 * @since 1.22
359 * @param MWTimestamp $relativeTo Base time to calculate difference from
360 * @return DateInterval|bool The DateInterval object representing the
361 * difference between the two dates or false on failure
363 public function diff( MWTimestamp $relativeTo ) {
364 return $this->timestamp->diff( $relativeTo->timestamp );
368 * Set the timezone of this timestamp to the specified timezone.
370 * @since 1.22
371 * @param string $timezone Timezone to set
372 * @throws TimestampException
374 public function setTimezone( $timezone ) {
375 try {
376 $this->timestamp->setTimezone( new DateTimeZone( $timezone ) );
377 } catch ( Exception $e ) {
378 throw new TimestampException( __METHOD__ . ': Invalid timezone.', $e->getCode(), $e );
383 * Get the timezone of this timestamp.
385 * @since 1.22
386 * @return DateTimeZone The timezone
388 public function getTimezone() {
389 return $this->timestamp->getTimezone();
393 * Format the timestamp in a given format.
395 * @since 1.22
396 * @param string $format Pattern to format in
397 * @return string The formatted timestamp
399 public function format( $format ) {
400 return $this->timestamp->format( $format );
404 * Get a timestamp instance in the server local timezone ($wgLocaltimezone)
406 * @since 1.22
407 * @param bool|string $ts Timestamp to set, or false for current time
408 * @return MWTimestamp The local instance
410 public static function getLocalInstance( $ts = false ) {
411 global $wgLocaltimezone;
412 $timestamp = new self( $ts );
413 $timestamp->setTimezone( $wgLocaltimezone );
414 return $timestamp;
418 * Get a timestamp instance in GMT
420 * @since 1.22
421 * @param bool|string $ts Timestamp to set, or false for current time
422 * @return MWTimestamp The instance
424 public static function getInstance( $ts = false ) {
425 return new self( $ts );