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