Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / libs / time / ConvertibleTimestamp.php
blobc830b4eb642c2ddf99c055d82fd6414b82b2bd93
1 <?php
2 /**
3 * Creation, parsing, and conversion of 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, parsing, and converting timestamps. Based on the JS
27 * library that does the same thing.
29 * @since 1.28
31 class ConvertibleTimestamp {
32 /**
33 * Standard gmdate() formats for the different timestamp types.
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',
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 * @param bool|string|int|float|DateTime $timestamp Timestamp to set, or false for current time
59 public function __construct( $timestamp = false ) {
60 if ( $timestamp instanceof DateTime ) {
61 $this->timestamp = $timestamp;
62 } else {
63 $this->setTimestamp( $timestamp );
67 /**
68 * Set the timestamp to the specified time, or the current time if unspecified.
70 * Parse the given timestamp into either a DateTime object or a Unix timestamp,
71 * and then store it.
73 * @param string|bool $ts Timestamp to store, or false for now
74 * @throws TimestampException
76 public function setTimestamp( $ts = false ) {
77 $m = [];
78 $da = [];
79 $strtime = '';
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]}"; // https://secure.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,
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,
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,
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,
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',
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" );
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 );
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 );
157 if ( $final === false ) {
158 throw new TimestampException( __METHOD__ . ': Invalid timestamp format.' );
161 $this->timestamp = $final;
165 * Convert a timestamp string to a given format.
167 * @param int $style Constant Output format for timestamp
168 * @param string $ts Timestamp
169 * @return string|bool Formatted timestamp or false on failure
171 public static function convert( $style = TS_UNIX, $ts ) {
172 try {
173 $ct = new static( $ts );
174 return $ct->getTimestamp( $style );
175 } catch ( TimestampException $e ) {
176 return false;
181 * Get the current time in the given format
183 * @param int $style Constant Output format for timestamp
184 * @return string
186 public static function now( $style = TS_MW ) {
187 return static::convert( $style, time() );
191 * Get the timestamp represented by this object in a certain form.
193 * Convert the internal timestamp to the specified format and then
194 * return it.
196 * @param int $style Constant Output format for timestamp
197 * @throws TimestampException
198 * @return string The formatted timestamp
200 public function getTimestamp( $style = TS_UNIX ) {
201 if ( !isset( self::$formats[$style] ) ) {
202 throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
205 $output = $this->timestamp->format( self::$formats[$style] );
207 if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
208 $output .= ' GMT';
211 if ( $style == TS_MW && strlen( $output ) !== 14 ) {
212 throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
213 'the specified format' );
216 return $output;
220 * @return string
222 public function __toString() {
223 return $this->getTimestamp();
227 * Calculate the difference between two ConvertibleTimestamp objects.
229 * @param ConvertibleTimestamp $relativeTo Base time to calculate difference from
230 * @return DateInterval|bool The DateInterval object representing the
231 * difference between the two dates or false on failure
233 public function diff( ConvertibleTimestamp $relativeTo ) {
234 return $this->timestamp->diff( $relativeTo->timestamp );
238 * Set the timezone of this timestamp to the specified timezone.
240 * @param string $timezone Timezone to set
241 * @throws TimestampException
243 public function setTimezone( $timezone ) {
244 try {
245 $this->timestamp->setTimezone( new DateTimeZone( $timezone ) );
246 } catch ( Exception $e ) {
247 throw new TimestampException( __METHOD__ . ': Invalid timezone.', $e->getCode(), $e );
252 * Get the timezone of this timestamp.
254 * @return DateTimeZone The timezone
256 public function getTimezone() {
257 return $this->timestamp->getTimezone();
261 * Format the timestamp in a given format.
263 * @param string $format Pattern to format in
264 * @return string The formatted timestamp
266 public function format( $format ) {
267 return $this->timestamp->format( $format );