Test improperly quoted attribute values in HTML tags and table cells
[lhc/web/wiklou.git] / includes / Timestamp.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 TS_DB2 => 'Y-m-d H:i:s',
46 );
47
48 /**
49 * Different units for human readable timestamps.
50 * @see MWTimestamp::getHumanTimestamp
51 */
52 private static $units = array(
53 "milliseconds" => 1,
54 "seconds" => 1000, // 1000 milliseconds per second
55 "minutes" => 60, // 60 seconds per minute
56 "hours" => 60, // 60 minutes per hour
57 "days" => 24, // 24 hours per day
58 "months" => 30, // approximately 30 days per month
59 "years" => 12, // 12 months per year
60 );
61
62 /**
63 * The actual timestamp being wrapped. Either a DateTime
64 * object or a string with a Unix timestamp depending on
65 * PHP.
66 * @var string|DateTime
67 */
68 private $timestamp;
69
70 /**
71 * Make a new timestamp and set it to the specified time,
72 * or the current time if unspecified.
73 *
74 * @since 1.20
75 *
76 * @param $timestamp bool|string Timestamp to set, or false for current time
77 */
78 public function __construct( $timestamp = false ) {
79 $this->setTimestamp( $timestamp );
80 }
81
82 /**
83 * Set the timestamp to the specified time, or the current time if unspecified.
84 *
85 * Parse the given timestamp into either a DateTime object or a Unix timestamp,
86 * and then store it.
87 *
88 * @since 1.20
89 *
90 * @param $ts string|bool Timestamp to store, or false for now
91 * @throws TimestampException
92 */
93 public function setTimestamp( $ts = false ) {
94 $da = array();
95 $strtime = '';
96
97 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.
98 $uts = time();
99 $strtime = "@$uts";
100 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
101 # TS_DB
102 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
103 # TS_EXIF
104 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
105 # TS_MW
106 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
107 # TS_UNIX
108 $strtime = "@$ts"; // http://php.net/manual/en/datetime.formats.compound.php
109 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
110 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
111 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
112 str_replace( '+00:00', 'UTC', $ts ) );
113 } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
114 # TS_ISO_8601
115 } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
116 #TS_ISO_8601_BASIC
117 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
118 # TS_POSTGRES
119 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
120 # TS_POSTGRES
121 } elseif (preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/', $ts, $da ) ) {
122 # TS_DB2
123 } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
124 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
125 '[ \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
126 # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
127 # The regex is a superset of rfc2822 for readability
128 $strtime = strtok( $ts, ';' );
129 } 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 ) ) {
130 # TS_RFC850
131 $strtime = $ts;
132 } 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 ) ) {
133 # asctime
134 $strtime = $ts;
135 } else {
136 throw new TimestampException( __METHOD__ . " : Invalid timestamp - $ts" );
137 }
138
139 if( !$strtime ) {
140 $da = array_map( 'intval', $da );
141 $da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
142 $strtime = call_user_func_array( "sprintf", $da );
143 }
144
145 try {
146 $final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
147 } catch(Exception $e) {
148 throw new TimestampException( __METHOD__ . ' Invalid timestamp format.' );
149 }
150
151 if( $final === false ) {
152 throw new TimestampException( __METHOD__ . ' Invalid timestamp format.' );
153 }
154 $this->timestamp = $final;
155 }
156
157 /**
158 * Get the timestamp represented by this object in a certain form.
159 *
160 * Convert the internal timestamp to the specified format and then
161 * return it.
162 *
163 * @since 1.20
164 *
165 * @param $style int Constant Output format for timestamp
166 * @throws TimestampException
167 * @return string The formatted timestamp
168 */
169 public function getTimestamp( $style = TS_UNIX ) {
170 if( !isset( self::$formats[$style] ) ) {
171 throw new TimestampException( __METHOD__ . ' : Illegal timestamp output type.' );
172 }
173
174 if( is_object( $this->timestamp ) ) {
175 // DateTime object was used, call DateTime::format.
176 $output = $this->timestamp->format( self::$formats[$style] );
177 } elseif( TS_UNIX == $style ) {
178 // Unix timestamp was used and is wanted, just return it.
179 $output = $this->timestamp;
180 } else {
181 // Unix timestamp was used, use gmdate().
182 $output = gmdate( self::$formats[$style], $this->timestamp );
183 }
184
185 if ( ( $style == TS_RFC2822 ) || ( $style == TS_POSTGRES ) ) {
186 $output .= ' GMT';
187 }
188
189 return $output;
190 }
191
192 /**
193 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
194 *
195 * Determine the difference between the timestamp and the current time, and
196 * generate a readable timestamp by returning "<N> <units> ago", where the
197 * largest possible unit is used.
198 *
199 * @since 1.20
200 *
201 * @return Message Formatted timestamp
202 */
203 public function getHumanTimestamp() {
204 $then = $this->getTimestamp( TS_UNIX );
205 $now = time();
206 $timeago = ($now - $then) * 1000;
207 $message = false;
208
209 foreach( self::$units as $unit => $factor ) {
210 $next = $timeago / $factor;
211 if( $next < 1 ) {
212 break;
213 } else {
214 $timeago = $next;
215 $message = array( $unit, floor( $timeago ) );
216 }
217 }
218
219 if( $message ) {
220 $initial = call_user_func_array( 'wfMessage', $message );
221 return wfMessage( 'ago', $initial->parse() );
222 } else {
223 return wfMessage( 'just-now' );
224 }
225 }
226
227 /**
228 * @since 1.20
229 *
230 * @return string
231 */
232 public function __toString() {
233 return $this->getTimestamp();
234 }
235 }
236
237 /**
238 * @since 1.20
239 */
240 class TimestampException extends MWException {}