Merge "Remove button-math"
[lhc/web/wiklou.git] / includes / parser / DateFormatter.php
1 <?php
2 /**
3 * Date formatter
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 * @ingroup Parser
22 */
23
24 /**
25 * Date formatter, recognises dates in plain text and formats them according to user preferences.
26 * @todo preferences, OutputPage
27 * @ingroup Parser
28 */
29 class DateFormatter {
30 var $mSource, $mTarget;
31 var $monthNames = '', $rxDM, $rxMD, $rxDMY, $rxYDM, $rxMDY, $rxYMD;
32
33 var $regexes, $pDays, $pMonths, $pYears;
34 var $rules, $xMonths, $preferences;
35
36 protected $lang;
37
38 const ALL = -1;
39 const NONE = 0;
40 const MDY = 1;
41 const DMY = 2;
42 const YMD = 3;
43 const ISO1 = 4;
44 const LASTPREF = 4;
45 const ISO2 = 5;
46 const YDM = 6;
47 const DM = 7;
48 const MD = 8;
49 const LAST = 8;
50
51 /**
52 * @param $lang Language In which language to format the date
53 */
54 function __construct( Language $lang ) {
55 $this->lang = $lang;
56
57 $this->monthNames = $this->getMonthRegex();
58 for ( $i = 1; $i <= 12; $i++ ) {
59 $this->xMonths[$this->lang->lc( $this->lang->getMonthName( $i ) )] = $i;
60 $this->xMonths[$this->lang->lc( $this->lang->getMonthAbbreviation( $i ) )] = $i;
61 }
62
63 $this->regexTrail = '(?![a-z])/iu';
64
65 # Partial regular expressions
66 $this->prxDM = '\[\[(\d{1,2})[ _](' . $this->monthNames . ')\]\]';
67 $this->prxMD = '\[\[(' . $this->monthNames . ')[ _](\d{1,2})\]\]';
68 $this->prxY = '\[\[(\d{1,4}([ _]BC|))\]\]';
69 $this->prxISO1 = '\[\[(-?\d{4})]]-\[\[(\d{2})-(\d{2})\]\]';
70 $this->prxISO2 = '\[\[(-?\d{4})-(\d{2})-(\d{2})\]\]';
71
72 # Real regular expressions
73 $this->regexes[self::DMY] = "/{$this->prxDM}(?: *, *| +){$this->prxY}{$this->regexTrail}";
74 $this->regexes[self::YDM] = "/{$this->prxY}(?: *, *| +){$this->prxDM}{$this->regexTrail}";
75 $this->regexes[self::MDY] = "/{$this->prxMD}(?: *, *| +){$this->prxY}{$this->regexTrail}";
76 $this->regexes[self::YMD] = "/{$this->prxY}(?: *, *| +){$this->prxMD}{$this->regexTrail}";
77 $this->regexes[self::DM] = "/{$this->prxDM}{$this->regexTrail}";
78 $this->regexes[self::MD] = "/{$this->prxMD}{$this->regexTrail}";
79 $this->regexes[self::ISO1] = "/{$this->prxISO1}{$this->regexTrail}";
80 $this->regexes[self::ISO2] = "/{$this->prxISO2}{$this->regexTrail}";
81
82 # Extraction keys
83 # See the comments in replace() for the meaning of the letters
84 $this->keys[self::DMY] = 'jFY';
85 $this->keys[self::YDM] = 'Y jF';
86 $this->keys[self::MDY] = 'FjY';
87 $this->keys[self::YMD] = 'Y Fj';
88 $this->keys[self::DM] = 'jF';
89 $this->keys[self::MD] = 'Fj';
90 $this->keys[self::ISO1] = 'ymd'; # y means ISO year
91 $this->keys[self::ISO2] = 'ymd';
92
93 # Target date formats
94 $this->targets[self::DMY] = '[[F j|j F]] [[Y]]';
95 $this->targets[self::YDM] = '[[Y]], [[F j|j F]]';
96 $this->targets[self::MDY] = '[[F j]], [[Y]]';
97 $this->targets[self::YMD] = '[[Y]] [[F j]]';
98 $this->targets[self::DM] = '[[F j|j F]]';
99 $this->targets[self::MD] = '[[F j]]';
100 $this->targets[self::ISO1] = '[[Y|y]]-[[F j|m-d]]';
101 $this->targets[self::ISO2] = '[[y-m-d]]';
102
103 # Rules
104 # pref source target
105 $this->rules[self::DMY][self::MD] = self::DM;
106 $this->rules[self::ALL][self::MD] = self::MD;
107 $this->rules[self::MDY][self::DM] = self::MD;
108 $this->rules[self::ALL][self::DM] = self::DM;
109 $this->rules[self::NONE][self::ISO2] = self::ISO1;
110
111 $this->preferences = array(
112 'default' => self::NONE,
113 'dmy' => self::DMY,
114 'mdy' => self::MDY,
115 'ymd' => self::YMD,
116 'ISO 8601' => self::ISO1,
117 );
118 }
119
120 /**
121 * Get a DateFormatter object
122 *
123 * @param $lang Language|string|null In which language to format the date
124 * Defaults to the site content language
125 * @return DateFormatter object
126 */
127 public static function &getInstance( $lang = null ) {
128 global $wgMemc, $wgContLang;
129 static $dateFormatter = false;
130 $lang = $lang ? wfGetLangObj( $lang ) : $wgContLang;
131 $key = wfMemcKey( 'dateformatter', $lang->getCode() );
132 if ( !$dateFormatter ) {
133 $dateFormatter = $wgMemc->get( $key );
134 if ( !$dateFormatter ) {
135 $dateFormatter = new DateFormatter( $lang );
136 $wgMemc->set( $key, $dateFormatter, 3600 );
137 }
138 }
139 return $dateFormatter;
140 }
141
142 /**
143 * @param string $preference User preference
144 * @param string $text Text to reformat
145 * @param array $options can contain 'linked' and/or 'match-whole'
146 * @return mixed|String
147 */
148 function reformat( $preference, $text, $options = array( 'linked' ) ) {
149 $linked = in_array( 'linked', $options );
150 $match_whole = in_array( 'match-whole', $options );
151
152 if ( isset( $this->preferences[$preference] ) ) {
153 $preference = $this->preferences[$preference];
154 } else {
155 $preference = self::NONE;
156 }
157 for ( $i = 1; $i <= self::LAST; $i++ ) {
158 $this->mSource = $i;
159 if ( isset( $this->rules[$preference][$i] ) ) {
160 # Specific rules
161 $this->mTarget = $this->rules[$preference][$i];
162 } elseif ( isset( $this->rules[self::ALL][$i] ) ) {
163 # General rules
164 $this->mTarget = $this->rules[self::ALL][$i];
165 } elseif ( $preference ) {
166 # User preference
167 $this->mTarget = $preference;
168 } else {
169 # Default
170 $this->mTarget = $i;
171 }
172 $regex = $this->regexes[$i];
173
174 // Horrible hack
175 if ( !$linked ) {
176 $regex = str_replace( array( '\[\[', '\]\]' ), '', $regex );
177 }
178
179 if ( $match_whole ) {
180 // Let's hope this works
181 $regex = preg_replace( '!^/!', '/^', $regex );
182 $regex = str_replace( $this->regexTrail,
183 '$' . $this->regexTrail, $regex );
184 }
185
186 // Another horrible hack
187 $this->mLinked = $linked;
188 $text = preg_replace_callback( $regex, array( &$this, 'replace' ), $text );
189 unset( $this->mLinked );
190 }
191 return $text;
192 }
193
194 /**
195 * @param $matches
196 * @return string
197 */
198 function replace( $matches ) {
199 # Extract information from $matches
200 $linked = true;
201 if ( isset( $this->mLinked ) ) {
202 $linked = $this->mLinked;
203 }
204
205 $bits = array();
206 $key = $this->keys[$this->mSource];
207 for ( $p = 0; $p < strlen( $key ); $p++ ) {
208 if ( $key[$p] != ' ' ) {
209 $bits[$key[$p]] = $matches[$p + 1];
210 }
211 }
212
213 return $this->formatDate( $bits, $linked );
214 }
215
216 /**
217 * @param $bits array
218 * @param $link bool
219 * @return string
220 */
221 function formatDate( $bits, $link = true ) {
222 $format = $this->targets[$this->mTarget];
223
224 if ( !$link ) {
225 // strip piped links
226 $format = preg_replace( '/\[\[[^|]+\|([^\]]+)\]\]/', '$1', $format );
227 // strip remaining links
228 $format = str_replace( array( '[[', ']]' ), '', $format );
229 }
230
231 # Construct new date
232 $text = '';
233 $fail = false;
234
235 // Pre-generate y/Y stuff because we need the year for the <span> title.
236 if ( !isset( $bits['y'] ) && isset( $bits['Y'] ) ) {
237 $bits['y'] = $this->makeIsoYear( $bits['Y'] );
238 }
239 if ( !isset( $bits['Y'] ) && isset( $bits['y'] ) ) {
240 $bits['Y'] = $this->makeNormalYear( $bits['y'] );
241 }
242
243 if ( !isset( $bits['m'] ) ) {
244 $m = $this->makeIsoMonth( $bits['F'] );
245 if ( !$m || $m == '00' ) {
246 $fail = true;
247 } else {
248 $bits['m'] = $m;
249 }
250 }
251
252 if ( !isset( $bits['d'] ) ) {
253 $bits['d'] = sprintf( '%02d', $bits['j'] );
254 }
255
256 for ( $p = 0; $p < strlen( $format ); $p++ ) {
257 $char = $format[$p];
258 switch ( $char ) {
259 case 'd': # ISO day of month
260 $text .= $bits['d'];
261 break;
262 case 'm': # ISO month
263 $text .= $bits['m'];
264 break;
265 case 'y': # ISO year
266 $text .= $bits['y'];
267 break;
268 case 'j': # ordinary day of month
269 if ( !isset( $bits['j'] ) ) {
270 $text .= intval( $bits['d'] );
271 } else {
272 $text .= $bits['j'];
273 }
274 break;
275 case 'F': # long month
276 if ( !isset( $bits['F'] ) ) {
277 $m = intval( $bits['m'] );
278 if ( $m > 12 || $m < 1 ) {
279 $fail = true;
280 } else {
281 $text .= $this->lang->getMonthName( $m );
282 }
283 } else {
284 $text .= ucfirst( $bits['F'] );
285 }
286 break;
287 case 'Y': # ordinary (optional BC) year
288 $text .= $bits['Y'];
289 break;
290 default:
291 $text .= $char;
292 }
293 }
294 if ( $fail ) {
295 $text = $matches[0];
296 }
297
298 $isoBits = array();
299 if ( isset( $bits['y'] ) ) {
300 $isoBits[] = $bits['y'];
301 }
302 $isoBits[] = $bits['m'];
303 $isoBits[] = $bits['d'];
304 $isoDate = implode( '-', $isoBits );
305
306 // Output is not strictly HTML (it's wikitext), but <span> is whitelisted.
307 $text = Html::rawElement( 'span',
308 array( 'class' => 'mw-formatted-date', 'title' => $isoDate ), $text );
309
310 return $text;
311 }
312
313 /**
314 * @todo document
315 * @return string
316 */
317 function getMonthRegex() {
318 $names = array();
319 for ( $i = 1; $i <= 12; $i++ ) {
320 $names[] = $this->lang->getMonthName( $i );
321 $names[] = $this->lang->getMonthAbbreviation( $i );
322 }
323 return implode( '|', $names );
324 }
325
326 /**
327 * Makes an ISO month, e.g. 02, from a month name
328 * @param string $monthName month name
329 * @return string ISO month name
330 */
331 function makeIsoMonth( $monthName ) {
332 $n = $this->xMonths[$this->lang->lc( $monthName )];
333 return sprintf( '%02d', $n );
334 }
335
336 /**
337 * @todo document
338 * @param string $year Year name
339 * @return string ISO year name
340 */
341 function makeIsoYear( $year ) {
342 # Assumes the year is in a nice format, as enforced by the regex
343 if ( substr( $year, -2 ) == 'BC' ) {
344 $num = intval( substr( $year, 0, -3 ) ) - 1;
345 # PHP bug note: sprintf( "%04d", -1 ) fails poorly
346 $text = sprintf( '-%04d', $num );
347
348 } else {
349 $text = sprintf( '%04d', $year );
350 }
351 return $text;
352 }
353
354 /**
355 * @todo document
356 * @return int|string
357 */
358 function makeNormalYear( $iso ) {
359 if ( $iso[0] == '-' ) {
360 $text = ( intval( substr( $iso, 1 ) ) + 1 ) . ' BC';
361 } else {
362 $text = intval( $iso );
363 }
364 return $text;
365 }
366 }