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