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