Handle missing namespace prefix in XML dumps more gracefully
[lhc/web/wiklou.git] / includes / libs / time / ConvertibleTimestamp.php
1 <?php
2 /**
3 * Creation, parsing, and conversion of 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, parsing, and converting timestamps. Based on the JS
27 * library that does the same thing.
28 *
29 * @since 1.28
30 */
31 class ConvertibleTimestamp {
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 * @param bool|string|int|float|DateTime $timestamp Timestamp to set, or false for current time
58 */
59 public function __construct( $timestamp = false ) {
60 if ( $timestamp instanceof DateTime ) {
61 $this->timestamp = $timestamp;
62 } else {
63 $this->setTimestamp( $timestamp );
64 }
65 }
66
67 /**
68 * Set the timestamp to the specified time, or the current time if unspecified.
69 *
70 * Parse the given timestamp into either a DateTime object or a Unix timestamp,
71 * and then store it.
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 = [];
78 $da = [];
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]}"; // 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,
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
161 $this->timestamp = $final;
162 }
163
164 /**
165 * Convert a timestamp string to a given format.
166 *
167 * @param int $style Constant Output format for timestamp
168 * @param string $ts Timestamp
169 * @return string|bool Formatted timestamp or false on failure
170 */
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;
177 }
178 }
179
180 /**
181 * Get the current time in the given format
182 *
183 * @param int $style Constant Output format for timestamp
184 * @return string
185 */
186 public static function now( $style = TS_MW ) {
187 return static::convert( $style, time() );
188 }
189
190 /**
191 * Get the timestamp represented by this object in a certain form.
192 *
193 * Convert the internal timestamp to the specified format and then
194 * return it.
195 *
196 * @param int $style Constant Output format for timestamp
197 * @throws TimestampException
198 * @return string The formatted timestamp
199 */
200 public function getTimestamp( $style = TS_UNIX ) {
201 if ( !isset( self::$formats[$style] ) ) {
202 throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
203 }
204
205 $output = $this->timestamp->format( self::$formats[$style] );
206
207 if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
208 $output .= ' GMT';
209 }
210
211 if ( $style == TS_MW && strlen( $output ) !== 14 ) {
212 throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
213 'the specified format' );
214 }
215
216 return $output;
217 }
218
219 /**
220 * @return string
221 */
222 public function __toString() {
223 return $this->getTimestamp();
224 }
225
226 /**
227 * Calculate the difference between two ConvertibleTimestamp objects.
228 *
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
232 */
233 public function diff( ConvertibleTimestamp $relativeTo ) {
234 return $this->timestamp->diff( $relativeTo->timestamp );
235 }
236
237 /**
238 * Set the timezone of this timestamp to the specified timezone.
239 *
240 * @param string $timezone Timezone to set
241 * @throws TimestampException
242 */
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 );
248 }
249 }
250
251 /**
252 * Get the timezone of this timestamp.
253 *
254 * @return DateTimeZone The timezone
255 */
256 public function getTimezone() {
257 return $this->timestamp->getTimezone();
258 }
259
260 /**
261 * Format the timestamp in a given format.
262 *
263 * @param string $format Pattern to format in
264 * @return string The formatted timestamp
265 */
266 public function format( $format ) {
267 return $this->timestamp->format( $format );
268 }
269 }