Localisation updates Cantonese, Chinese and Old/Late Time Chinese
[lhc/web/wiklou.git] / includes / MagicWord.php
1 <?php
2 /**
3 * File for magic words
4 * See docs/magicword.txt
5 *
6 * @file
7 * @ingroup Parser
8 */
9
10 /**
11 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
12 * Usage:
13 * if (MagicWord::get( 'redirect' )->match( $text ) )
14 *
15 * Possible future improvements:
16 * * Simultaneous searching for a number of magic words
17 * * MagicWord::$mObjects in shared memory
18 *
19 * Please avoid reading the data out of one of these objects and then writing
20 * special case code. If possible, add another match()-like function here.
21 *
22 * To add magic words in an extension, use the LanguageGetMagic hook. For
23 * magic words which are also Parser variables, add a MagicWordwgVariableIDs
24 * hook. Use string keys.
25 *
26 * @ingroup Parser
27 */
28 class MagicWord {
29 /**#@+
30 * @private
31 */
32 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
33 var $mRegexStart, $mBaseRegex, $mVariableRegex;
34 var $mModified, $mFound;
35
36 static public $mVariableIDsInitialised = false;
37 static public $mVariableIDs = array(
38 'currentmonth',
39 'currentmonthname',
40 'currentmonthnamegen',
41 'currentmonthabbrev',
42 'currentday',
43 'currentday2',
44 'currentdayname',
45 'currentyear',
46 'currenttime',
47 'currenthour',
48 'localmonth',
49 'localmonthname',
50 'localmonthnamegen',
51 'localmonthabbrev',
52 'localday',
53 'localday2',
54 'localdayname',
55 'localyear',
56 'localtime',
57 'localhour',
58 'numberofarticles',
59 'numberoffiles',
60 'numberofedits',
61 'sitename',
62 'server',
63 'servername',
64 'scriptpath',
65 'pagename',
66 'pagenamee',
67 'fullpagename',
68 'fullpagenamee',
69 'namespace',
70 'namespacee',
71 'currentweek',
72 'currentdow',
73 'localweek',
74 'localdow',
75 'revisionid',
76 'revisionday',
77 'revisionday2',
78 'revisionmonth',
79 'revisionyear',
80 'revisiontimestamp',
81 'subpagename',
82 'subpagenamee',
83 'displaytitle',
84 'talkspace',
85 'talkspacee',
86 'subjectspace',
87 'subjectspacee',
88 'talkpagename',
89 'talkpagenamee',
90 'subjectpagename',
91 'subjectpagenamee',
92 'numberofusers',
93 'newsectionlink',
94 'numberofpages',
95 'currentversion',
96 'basepagename',
97 'basepagenamee',
98 'urlencode',
99 'currenttimestamp',
100 'localtimestamp',
101 'directionmark',
102 'language',
103 'contentlanguage',
104 'pagesinnamespace',
105 'numberofadmins',
106 'defaultsort',
107 'pagesincategory',
108 );
109
110 /* Array of caching hints for ParserCache */
111 static public $mCacheTTLs = array (
112 'currentmonth' => 86400,
113 'currentmonthname' => 86400,
114 'currentmonthnamegen' => 86400,
115 'currentmonthabbrev' => 86400,
116 'currentday' => 3600,
117 'currentday2' => 3600,
118 'currentdayname' => 3600,
119 'currentyear' => 86400,
120 'currenttime' => 3600,
121 'currenthour' => 3600,
122 'localmonth' => 86400,
123 'localmonthname' => 86400,
124 'localmonthnamegen' => 86400,
125 'localmonthabbrev' => 86400,
126 'localday' => 3600,
127 'localday2' => 3600,
128 'localdayname' => 3600,
129 'localyear' => 86400,
130 'localtime' => 3600,
131 'localhour' => 3600,
132 'numberofarticles' => 3600,
133 'numberoffiles' => 3600,
134 'numberofedits' => 3600,
135 'currentweek' => 3600,
136 'currentdow' => 3600,
137 'localweek' => 3600,
138 'localdow' => 3600,
139 'numberofusers' => 3600,
140 'numberofpages' => 3600,
141 'currentversion' => 86400,
142 'currenttimestamp' => 3600,
143 'localtimestamp' => 3600,
144 'pagesinnamespace' => 3600,
145 'numberofadmins' => 3600,
146 );
147
148 static public $mDoubleUnderscoreIDs = array(
149 'notoc',
150 'nogallery',
151 'forcetoc',
152 'toc',
153 'noeditsection',
154 'newsectionlink',
155 'hiddencat',
156 );
157
158
159 static public $mObjects = array();
160 static public $mDoubleUnderscoreArray = null;
161
162 /**#@-*/
163
164 function __construct($id = 0, $syn = '', $cs = false) {
165 $this->mId = $id;
166 $this->mSynonyms = (array)$syn;
167 $this->mCaseSensitive = $cs;
168 $this->mRegex = '';
169 $this->mRegexStart = '';
170 $this->mVariableRegex = '';
171 $this->mVariableStartToEndRegex = '';
172 $this->mModified = false;
173 }
174
175 /**
176 * Factory: creates an object representing an ID
177 * @static
178 */
179 static function &get( $id ) {
180 wfProfileIn( __METHOD__ );
181 if (!array_key_exists( $id, self::$mObjects ) ) {
182 $mw = new MagicWord();
183 $mw->load( $id );
184 self::$mObjects[$id] = $mw;
185 }
186 wfProfileOut( __METHOD__ );
187 return self::$mObjects[$id];
188 }
189
190 /**
191 * Get an array of parser variable IDs
192 */
193 static function getVariableIDs() {
194 if ( !self::$mVariableIDsInitialised ) {
195 # Deprecated constant definition hook, available for extensions that need it
196 $magicWords = array();
197 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
198 foreach ( $magicWords as $word ) {
199 define( $word, $word );
200 }
201
202 # Get variable IDs
203 wfRunHooks( 'MagicWordwgVariableIDs', array( &self::$mVariableIDs ) );
204 self::$mVariableIDsInitialised = true;
205 }
206 return self::$mVariableIDs;
207 }
208
209 /* Allow external reads of TTL array */
210 static function getCacheTTL($id) {
211 if (array_key_exists($id,self::$mCacheTTLs)) {
212 return self::$mCacheTTLs[$id];
213 } else {
214 return -1;
215 }
216 }
217
218 /** Get a MagicWordArray of double-underscore entities */
219 static function getDoubleUnderscoreArray() {
220 if ( is_null( self::$mDoubleUnderscoreArray ) ) {
221 self::$mDoubleUnderscoreArray = new MagicWordArray( self::$mDoubleUnderscoreIDs );
222 }
223 return self::$mDoubleUnderscoreArray;
224 }
225
226 # Initialises this object with an ID
227 function load( $id ) {
228 global $wgContLang;
229 $this->mId = $id;
230 $wgContLang->getMagic( $this );
231 if ( !$this->mSynonyms ) {
232 $this->mSynonyms = array( 'dkjsagfjsgashfajsh' );
233 #throw new MWException( "Error: invalid magic word '$id'" );
234 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
235 }
236 }
237
238 /**
239 * Preliminary initialisation
240 * @private
241 */
242 function initRegex() {
243 #$variableClass = Title::legalChars();
244 # This was used for matching "$1" variables, but different uses of the feature will have
245 # different restrictions, which should be checked *after* the MagicWord has been matched,
246 # not here. - IMSoP
247
248 $escSyn = array();
249 foreach ( $this->mSynonyms as $synonym )
250 // In case a magic word contains /, like that's going to happen;)
251 $escSyn[] = preg_quote( $synonym, '/' );
252 $this->mBaseRegex = implode( '|', $escSyn );
253
254 $case = $this->mCaseSensitive ? '' : 'iu';
255 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
256 $this->mRegexStart = "/^(?:{$this->mBaseRegex})/{$case}";
257 $this->mVariableRegex = str_replace( "\\$1", "(.*?)", $this->mRegex );
258 $this->mVariableStartToEndRegex = str_replace( "\\$1", "(.*?)",
259 "/^(?:{$this->mBaseRegex})$/{$case}" );
260 }
261
262 /**
263 * Gets a regex representing matching the word
264 */
265 function getRegex() {
266 if ($this->mRegex == '' ) {
267 $this->initRegex();
268 }
269 return $this->mRegex;
270 }
271
272 /**
273 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
274 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
275 * the complete expression
276 */
277 function getRegexCase() {
278 if ( $this->mRegex === '' )
279 $this->initRegex();
280
281 return $this->mCaseSensitive ? '' : 'iu';
282 }
283
284 /**
285 * Gets a regex matching the word, if it is at the string start
286 */
287 function getRegexStart() {
288 if ($this->mRegex == '' ) {
289 $this->initRegex();
290 }
291 return $this->mRegexStart;
292 }
293
294 /**
295 * regex without the slashes and what not
296 */
297 function getBaseRegex() {
298 if ($this->mRegex == '') {
299 $this->initRegex();
300 }
301 return $this->mBaseRegex;
302 }
303
304 /**
305 * Returns true if the text contains the word
306 * @return bool
307 */
308 function match( $text ) {
309 return preg_match( $this->getRegex(), $text );
310 }
311
312 /**
313 * Returns true if the text starts with the word
314 * @return bool
315 */
316 function matchStart( $text ) {
317 return preg_match( $this->getRegexStart(), $text );
318 }
319
320 /**
321 * Returns NULL if there's no match, the value of $1 otherwise
322 * The return code is the matched string, if there's no variable
323 * part in the regex and the matched variable part ($1) if there
324 * is one.
325 */
326 function matchVariableStartToEnd( $text ) {
327 $matches = array();
328 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
329 if ( $matchcount == 0 ) {
330 return NULL;
331 } else {
332 # multiple matched parts (variable match); some will be empty because of
333 # synonyms. The variable will be the second non-empty one so remove any
334 # blank elements and re-sort the indices.
335 # See also bug 6526
336
337 $matches = array_values(array_filter($matches));
338
339 if ( count($matches) == 1 ) { return $matches[0]; }
340 else { return $matches[1]; }
341 }
342 }
343
344
345 /**
346 * Returns true if the text matches the word, and alters the
347 * input string, removing all instances of the word
348 */
349 function matchAndRemove( &$text ) {
350 $this->mFound = false;
351 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
352 return $this->mFound;
353 }
354
355 function matchStartAndRemove( &$text ) {
356 $this->mFound = false;
357 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
358 return $this->mFound;
359 }
360
361 /**
362 * Used in matchAndRemove()
363 * @private
364 **/
365 function pregRemoveAndRecord( ) {
366 $this->mFound = true;
367 return '';
368 }
369
370 /**
371 * Replaces the word with something else
372 */
373 function replace( $replacement, $subject, $limit=-1 ) {
374 $res = preg_replace( $this->getRegex(), StringUtils::escapeRegexReplacement( $replacement ), $subject, $limit );
375 $this->mModified = !($res === $subject);
376 return $res;
377 }
378
379 /**
380 * Variable handling: {{SUBST:xxx}} style words
381 * Calls back a function to determine what to replace xxx with
382 * Input word must contain $1
383 */
384 function substituteCallback( $text, $callback ) {
385 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
386 $this->mModified = !($res === $text);
387 return $res;
388 }
389
390 /**
391 * Matches the word, where $1 is a wildcard
392 */
393 function getVariableRegex() {
394 if ( $this->mVariableRegex == '' ) {
395 $this->initRegex();
396 }
397 return $this->mVariableRegex;
398 }
399
400 /**
401 * Matches the entire string, where $1 is a wildcard
402 */
403 function getVariableStartToEndRegex() {
404 if ( $this->mVariableStartToEndRegex == '' ) {
405 $this->initRegex();
406 }
407 return $this->mVariableStartToEndRegex;
408 }
409
410 /**
411 * Accesses the synonym list directly
412 */
413 function getSynonym( $i ) {
414 return $this->mSynonyms[$i];
415 }
416
417 function getSynonyms() {
418 return $this->mSynonyms;
419 }
420
421 /**
422 * Returns true if the last call to replace() or substituteCallback()
423 * returned a modified text, otherwise false.
424 */
425 function getWasModified(){
426 return $this->mModified;
427 }
428
429 /**
430 * $magicarr is an associative array of (magic word ID => replacement)
431 * This method uses the php feature to do several replacements at the same time,
432 * thereby gaining some efficiency. The result is placed in the out variable
433 * $result. The return value is true if something was replaced.
434 * @static
435 **/
436 function replaceMultiple( $magicarr, $subject, &$result ){
437 $search = array();
438 $replace = array();
439 foreach( $magicarr as $id => $replacement ){
440 $mw = MagicWord::get( $id );
441 $search[] = $mw->getRegex();
442 $replace[] = $replacement;
443 }
444
445 $result = preg_replace( $search, $replace, $subject );
446 return !($result === $subject);
447 }
448
449 /**
450 * Adds all the synonyms of this MagicWord to an array, to allow quick
451 * lookup in a list of magic words
452 */
453 function addToArray( &$array, $value ) {
454 global $wgContLang;
455 foreach ( $this->mSynonyms as $syn ) {
456 $array[$wgContLang->lc($syn)] = $value;
457 }
458 }
459
460 function isCaseSensitive() {
461 return $this->mCaseSensitive;
462 }
463
464 function getId() {
465 return $this->mId;
466 }
467 }
468
469 /**
470 * Class for handling an array of magic words
471 * @ingroup Parser
472 */
473 class MagicWordArray {
474 var $names = array();
475 var $hash;
476 var $baseRegex, $regex;
477 var $matches;
478
479 function __construct( $names = array() ) {
480 $this->names = $names;
481 }
482
483 /**
484 * Add a magic word by name
485 */
486 public function add( $name ) {
487 global $wgContLang;
488 $this->names[] = $name;
489 $this->hash = $this->baseRegex = $this->regex = null;
490 }
491
492 /**
493 * Add a number of magic words by name
494 */
495 public function addArray( $names ) {
496 $this->names = array_merge( $this->names, array_values( $names ) );
497 $this->hash = $this->baseRegex = $this->regex = null;
498 }
499
500 /**
501 * Get a 2-d hashtable for this array
502 */
503 function getHash() {
504 if ( is_null( $this->hash ) ) {
505 global $wgContLang;
506 $this->hash = array( 0 => array(), 1 => array() );
507 foreach ( $this->names as $name ) {
508 $magic = MagicWord::get( $name );
509 $case = intval( $magic->isCaseSensitive() );
510 foreach ( $magic->getSynonyms() as $syn ) {
511 if ( !$case ) {
512 $syn = $wgContLang->lc( $syn );
513 }
514 $this->hash[$case][$syn] = $name;
515 }
516 }
517 }
518 return $this->hash;
519 }
520
521 /**
522 * Get the base regex
523 */
524 function getBaseRegex() {
525 if ( is_null( $this->baseRegex ) ) {
526 $this->baseRegex = array( 0 => '', 1 => '' );
527 foreach ( $this->names as $name ) {
528 $magic = MagicWord::get( $name );
529 $case = intval( $magic->isCaseSensitive() );
530 foreach ( $magic->getSynonyms() as $i => $syn ) {
531 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
532 if ( $this->baseRegex[$case] === '' ) {
533 $this->baseRegex[$case] = $group;
534 } else {
535 $this->baseRegex[$case] .= '|' . $group;
536 }
537 }
538 }
539 }
540 return $this->baseRegex;
541 }
542
543 /**
544 * Get an unanchored regex
545 */
546 function getRegex() {
547 if ( is_null( $this->regex ) ) {
548 $base = $this->getBaseRegex();
549 $this->regex = array( '', '' );
550 if ( $this->baseRegex[0] !== '' ) {
551 $this->regex[0] = "/{$base[0]}/iuS";
552 }
553 if ( $this->baseRegex[1] !== '' ) {
554 $this->regex[1] = "/{$base[1]}/S";
555 }
556 }
557 return $this->regex;
558 }
559
560 /**
561 * Get a regex for matching variables
562 */
563 function getVariableRegex() {
564 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
565 }
566
567 /**
568 * Get an anchored regex for matching variables
569 */
570 function getVariableStartToEndRegex() {
571 $base = $this->getBaseRegex();
572 $newRegex = array( '', '' );
573 if ( $base[0] !== '' ) {
574 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
575 }
576 if ( $base[1] !== '' ) {
577 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
578 }
579 return $newRegex;
580 }
581
582 /**
583 * Parse a match array from preg_match
584 * Returns array(magic word ID, parameter value)
585 * If there is no parameter value, that element will be false.
586 */
587 function parseMatch( $m ) {
588 reset( $m );
589 while ( list( $key, $value ) = each( $m ) ) {
590 if ( $key === 0 || $value === '' ) {
591 continue;
592 }
593 $parts = explode( '_', $key, 2 );
594 if ( count( $parts ) != 2 ) {
595 // This shouldn't happen
596 // continue;
597 throw new MWException( __METHOD__ . ': bad parameter name' );
598 }
599 list( /* $synIndex */, $magicName ) = $parts;
600 $paramValue = next( $m );
601 return array( $magicName, $paramValue );
602 }
603 // This shouldn't happen either
604 throw new MWException( __METHOD__.': parameter not found' );
605 return array( false, false );
606 }
607
608 /**
609 * Match some text, with parameter capture
610 * Returns an array with the magic word name in the first element and the
611 * parameter in the second element.
612 * Both elements are false if there was no match.
613 */
614 public function matchVariableStartToEnd( $text ) {
615 global $wgContLang;
616 $regexes = $this->getVariableStartToEndRegex();
617 foreach ( $regexes as $regex ) {
618 if ( $regex !== '' ) {
619 $m = false;
620 if ( preg_match( $regex, $text, $m ) ) {
621 return $this->parseMatch( $m );
622 }
623 }
624 }
625 return array( false, false );
626 }
627
628 /**
629 * Match some text, without parameter capture
630 * Returns the magic word name, or false if there was no capture
631 */
632 public function matchStartToEnd( $text ) {
633 $hash = $this->getHash();
634 if ( isset( $hash[1][$text] ) ) {
635 return $hash[1][$text];
636 }
637 global $wgContLang;
638 $lc = $wgContLang->lc( $text );
639 if ( isset( $hash[0][$lc] ) ) {
640 return $hash[0][$lc];
641 }
642 return false;
643 }
644
645 /**
646 * Returns an associative array, ID => param value, for all items that match
647 * Removes the matched items from the input string (passed by reference)
648 */
649 public function matchAndRemove( &$text ) {
650 $found = array();
651 $regexes = $this->getRegex();
652 foreach ( $regexes as $regex ) {
653 if ( $regex === '' ) {
654 continue;
655 }
656 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER );
657 foreach ( $matches as $m ) {
658 list( $name, $param ) = $this->parseMatch( $m );
659 $found[$name] = $param;
660 }
661 $text = preg_replace( $regex, '', $text );
662 }
663 return $found;
664 }
665 }