a4c79babb5cf0d2bee6032cedb5ea094fbefc3b2
[lhc/web/wiklou.git] / includes / libs / time / ConvertableTimestamp.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 ConvertableTimestamp {
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]}"; // 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
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 timestamp represented by this object in a certain form.
182 *
183 * Convert the internal timestamp to the specified format and then
184 * return it.
185 *
186 * @param int $style Constant Output format for timestamp
187 * @throws TimestampException
188 * @return string The formatted timestamp
189 */
190 public function getTimestamp( $style = TS_UNIX ) {
191 if ( !isset( self::$formats[$style] ) ) {
192 throw new TimestampException( __METHOD__ . ': Illegal timestamp output type.' );
193 }
194
195 $output = $this->timestamp->format( self::$formats[$style] );
196
197 if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
198 $output .= ' GMT';
199 }
200
201 if ( $style == TS_MW && strlen( $output ) !== 14 ) {
202 throw new TimestampException( __METHOD__ . ': The timestamp cannot be represented in ' .
203 'the specified format' );
204 }
205
206 return $output;
207 }
208
209 /**
210 * @return string
211 */
212 public function __toString() {
213 return $this->getTimestamp();
214 }
215
216 /**
217 * Calculate the difference between two ConvertableTimestamp objects.
218 *
219 * @param ConvertableTimestamp $relativeTo Base time to calculate difference from
220 * @return DateInterval|bool The DateInterval object representing the
221 * difference between the two dates or false on failure
222 */
223 public function diff( ConvertableTimestamp $relativeTo ) {
224 return $this->timestamp->diff( $relativeTo->timestamp );
225 }
226
227 /**
228 * Set the timezone of this timestamp to the specified timezone.
229 *
230 * @param string $timezone Timezone to set
231 * @throws TimestampException
232 */
233 public function setTimezone( $timezone ) {
234 try {
235 $this->timestamp->setTimezone( new DateTimeZone( $timezone ) );
236 } catch ( Exception $e ) {
237 throw new TimestampException( __METHOD__ . ': Invalid timezone.', $e->getCode(), $e );
238 }
239 }
240
241 /**
242 * Get the timezone of this timestamp.
243 *
244 * @return DateTimeZone The timezone
245 */
246 public function getTimezone() {
247 return $this->timestamp->getTimezone();
248 }
249
250 /**
251 * Format the timestamp in a given format.
252 *
253 * @param string $format Pattern to format in
254 * @return string The formatted timestamp
255 */
256 public function format( $format ) {
257 return $this->timestamp->format( $format );
258 }
259 }