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