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