Changes default value so that it's not converted to array( 0 => '' ) by the (array...
[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 = array(), $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 * @return MagicWord
196 */
197 static function &get( $id ) {
198 wfProfileIn( __METHOD__ );
199 if ( !isset( self::$mObjects[$id] ) ) {
200 $mw = new MagicWord();
201 $mw->load( $id );
202 self::$mObjects[$id] = $mw;
203 }
204 wfProfileOut( __METHOD__ );
205 return self::$mObjects[$id];
206 }
207
208 /**
209 * Get an array of parser variable IDs
210 */
211 static function getVariableIDs() {
212 if ( !self::$mVariableIDsInitialised ) {
213 # Deprecated constant definition hook, available for extensions that need it
214 $magicWords = array();
215 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
216 foreach ( $magicWords as $word ) {
217 define( $word, $word );
218 }
219
220 # Get variable IDs
221 wfRunHooks( 'MagicWordwgVariableIDs', array( &self::$mVariableIDs ) );
222 self::$mVariableIDsInitialised = true;
223 }
224 return self::$mVariableIDs;
225 }
226
227 /**
228 * Get an array of parser substitution modifier IDs
229 */
230 static function getSubstIDs() {
231 return self::$mSubstIDs;
232 }
233
234 /* Allow external reads of TTL array */
235 static function getCacheTTL($id) {
236 if (array_key_exists($id,self::$mCacheTTLs)) {
237 return self::$mCacheTTLs[$id];
238 } else {
239 return -1;
240 }
241 }
242
243 /** Get a MagicWordArray of double-underscore entities */
244 static function getDoubleUnderscoreArray() {
245 if ( is_null( self::$mDoubleUnderscoreArray ) ) {
246 self::$mDoubleUnderscoreArray = new MagicWordArray( self::$mDoubleUnderscoreIDs );
247 }
248 return self::$mDoubleUnderscoreArray;
249 }
250
251 /**
252 * Clear the self::$mObjects variable
253 * For use in parser tests
254 */
255 public static function clearCache() {
256 self::$mObjects = array();
257 }
258
259 # Initialises this object with an ID
260 function load( $id ) {
261 global $wgContLang;
262 $this->mId = $id;
263 $wgContLang->getMagic( $this );
264 if ( !$this->mSynonyms ) {
265 $this->mSynonyms = array( 'dkjsagfjsgashfajsh' );
266 #throw new MWException( "Error: invalid magic word '$id'" );
267 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
268 }
269 }
270
271 /**
272 * Preliminary initialisation
273 * @private
274 */
275 function initRegex() {
276 // Sort the synonyms by length, descending, so that the longest synonym
277 // matches in precedence to the shortest
278 $synonyms = $this->mSynonyms;
279 usort( $synonyms, array( $this, 'compareStringLength' ) );
280
281 $escSyn = array();
282 foreach ( $synonyms as $synonym )
283 // In case a magic word contains /, like that's going to happen;)
284 $escSyn[] = preg_quote( $synonym, '/' );
285 $this->mBaseRegex = implode( '|', $escSyn );
286
287 $case = $this->mCaseSensitive ? '' : 'iu';
288 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
289 $this->mRegexStart = "/^(?:{$this->mBaseRegex})/{$case}";
290 $this->mVariableRegex = str_replace( "\\$1", "(.*?)", $this->mRegex );
291 $this->mVariableStartToEndRegex = str_replace( "\\$1", "(.*?)",
292 "/^(?:{$this->mBaseRegex})$/{$case}" );
293 }
294
295 /**
296 * A comparison function that returns -1, 0 or 1 depending on whether the
297 * first string is longer, the same length or shorter than the second
298 * string.
299 */
300 function compareStringLength( $s1, $s2 ) {
301 $l1 = strlen( $s1 );
302 $l2 = strlen( $s2 );
303 if ( $l1 < $l2 ) {
304 return 1;
305 } elseif ( $l1 > $l2 ) {
306 return -1;
307 } else {
308 return 0;
309 }
310 }
311
312 /**
313 * Gets a regex representing matching the word
314 */
315 function getRegex() {
316 if ($this->mRegex == '' ) {
317 $this->initRegex();
318 }
319 return $this->mRegex;
320 }
321
322 /**
323 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
324 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
325 * the complete expression
326 */
327 function getRegexCase() {
328 if ( $this->mRegex === '' )
329 $this->initRegex();
330
331 return $this->mCaseSensitive ? '' : 'iu';
332 }
333
334 /**
335 * Gets a regex matching the word, if it is at the string start
336 */
337 function getRegexStart() {
338 if ($this->mRegex == '' ) {
339 $this->initRegex();
340 }
341 return $this->mRegexStart;
342 }
343
344 /**
345 * regex without the slashes and what not
346 */
347 function getBaseRegex() {
348 if ($this->mRegex == '') {
349 $this->initRegex();
350 }
351 return $this->mBaseRegex;
352 }
353
354 /**
355 * Returns true if the text contains the word
356 * @return bool
357 */
358 function match( $text ) {
359 return (bool)preg_match( $this->getRegex(), $text );
360 }
361
362 /**
363 * Returns true if the text starts with the word
364 * @return bool
365 */
366 function matchStart( $text ) {
367 return (bool)preg_match( $this->getRegexStart(), $text );
368 }
369
370 /**
371 * Returns NULL if there's no match, the value of $1 otherwise
372 * The return code is the matched string, if there's no variable
373 * part in the regex and the matched variable part ($1) if there
374 * is one.
375 */
376 function matchVariableStartToEnd( $text ) {
377 $matches = array();
378 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
379 if ( $matchcount == 0 ) {
380 return null;
381 } else {
382 # multiple matched parts (variable match); some will be empty because of
383 # synonyms. The variable will be the second non-empty one so remove any
384 # blank elements and re-sort the indices.
385 # See also bug 6526
386
387 $matches = array_values(array_filter($matches));
388
389 if ( count($matches) == 1 ) { return $matches[0]; }
390 else { return $matches[1]; }
391 }
392 }
393
394
395 /**
396 * Returns true if the text matches the word, and alters the
397 * input string, removing all instances of the word
398 */
399 function matchAndRemove( &$text ) {
400 $this->mFound = false;
401 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
402 return $this->mFound;
403 }
404
405 function matchStartAndRemove( &$text ) {
406 $this->mFound = false;
407 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
408 return $this->mFound;
409 }
410
411 /**
412 * Used in matchAndRemove()
413 * @private
414 **/
415 function pregRemoveAndRecord( ) {
416 $this->mFound = true;
417 return '';
418 }
419
420 /**
421 * Replaces the word with something else
422 */
423 function replace( $replacement, $subject, $limit=-1 ) {
424 $res = preg_replace( $this->getRegex(), StringUtils::escapeRegexReplacement( $replacement ), $subject, $limit );
425 $this->mModified = !($res === $subject);
426 return $res;
427 }
428
429 /**
430 * Variable handling: {{SUBST:xxx}} style words
431 * Calls back a function to determine what to replace xxx with
432 * Input word must contain $1
433 */
434 function substituteCallback( $text, $callback ) {
435 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
436 $this->mModified = !($res === $text);
437 return $res;
438 }
439
440 /**
441 * Matches the word, where $1 is a wildcard
442 */
443 function getVariableRegex() {
444 if ( $this->mVariableRegex == '' ) {
445 $this->initRegex();
446 }
447 return $this->mVariableRegex;
448 }
449
450 /**
451 * Matches the entire string, where $1 is a wildcard
452 */
453 function getVariableStartToEndRegex() {
454 if ( $this->mVariableStartToEndRegex == '' ) {
455 $this->initRegex();
456 }
457 return $this->mVariableStartToEndRegex;
458 }
459
460 /**
461 * Accesses the synonym list directly
462 */
463 function getSynonym( $i ) {
464 return $this->mSynonyms[$i];
465 }
466
467 function getSynonyms() {
468 return $this->mSynonyms;
469 }
470
471 /**
472 * Returns true if the last call to replace() or substituteCallback()
473 * returned a modified text, otherwise false.
474 */
475 function getWasModified(){
476 return $this->mModified;
477 }
478
479 /**
480 * $magicarr is an associative array of (magic word ID => replacement)
481 * This method uses the php feature to do several replacements at the same time,
482 * thereby gaining some efficiency. The result is placed in the out variable
483 * $result. The return value is true if something was replaced.
484 * @static
485 **/
486 function replaceMultiple( $magicarr, $subject, &$result ){
487 $search = array();
488 $replace = array();
489 foreach( $magicarr as $id => $replacement ){
490 $mw = MagicWord::get( $id );
491 $search[] = $mw->getRegex();
492 $replace[] = $replacement;
493 }
494
495 $result = preg_replace( $search, $replace, $subject );
496 return !($result === $subject);
497 }
498
499 /**
500 * Adds all the synonyms of this MagicWord to an array, to allow quick
501 * lookup in a list of magic words
502 */
503 function addToArray( &$array, $value ) {
504 global $wgContLang;
505 foreach ( $this->mSynonyms as $syn ) {
506 $array[$wgContLang->lc($syn)] = $value;
507 }
508 }
509
510 function isCaseSensitive() {
511 return $this->mCaseSensitive;
512 }
513
514 function getId() {
515 return $this->mId;
516 }
517 }
518
519 /**
520 * Class for handling an array of magic words
521 * @ingroup Parser
522 */
523 class MagicWordArray {
524 var $names = array();
525 var $hash;
526 var $baseRegex, $regex;
527 var $matches;
528
529 function __construct( $names = array() ) {
530 $this->names = $names;
531 }
532
533 /**
534 * Add a magic word by name
535 */
536 public function add( $name ) {
537 $this->names[] = $name;
538 $this->hash = $this->baseRegex = $this->regex = null;
539 }
540
541 /**
542 * Add a number of magic words by name
543 */
544 public function addArray( $names ) {
545 $this->names = array_merge( $this->names, array_values( $names ) );
546 $this->hash = $this->baseRegex = $this->regex = null;
547 }
548
549 /**
550 * Get a 2-d hashtable for this array
551 */
552 function getHash() {
553 if ( is_null( $this->hash ) ) {
554 global $wgContLang;
555 $this->hash = array( 0 => array(), 1 => array() );
556 foreach ( $this->names as $name ) {
557 $magic = MagicWord::get( $name );
558 $case = intval( $magic->isCaseSensitive() );
559 foreach ( $magic->getSynonyms() as $syn ) {
560 if ( !$case ) {
561 $syn = $wgContLang->lc( $syn );
562 }
563 $this->hash[$case][$syn] = $name;
564 }
565 }
566 }
567 return $this->hash;
568 }
569
570 /**
571 * Get the base regex
572 */
573 function getBaseRegex() {
574 if ( is_null( $this->baseRegex ) ) {
575 $this->baseRegex = array( 0 => '', 1 => '' );
576 foreach ( $this->names as $name ) {
577 $magic = MagicWord::get( $name );
578 $case = intval( $magic->isCaseSensitive() );
579 foreach ( $magic->getSynonyms() as $i => $syn ) {
580 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
581 if ( $this->baseRegex[$case] === '' ) {
582 $this->baseRegex[$case] = $group;
583 } else {
584 $this->baseRegex[$case] .= '|' . $group;
585 }
586 }
587 }
588 }
589 return $this->baseRegex;
590 }
591
592 /**
593 * Get an unanchored regex that does not match parameters
594 */
595 function getRegex() {
596 if ( is_null( $this->regex ) ) {
597 $base = $this->getBaseRegex();
598 $this->regex = array( '', '' );
599 if ( $this->baseRegex[0] !== '' ) {
600 $this->regex[0] = "/{$base[0]}/iuS";
601 }
602 if ( $this->baseRegex[1] !== '' ) {
603 $this->regex[1] = "/{$base[1]}/S";
604 }
605 }
606 return $this->regex;
607 }
608
609 /**
610 * Get a regex for matching variables with parameters
611 */
612 function getVariableRegex() {
613 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
614 }
615
616 /**
617 * Get a regex anchored to the start of the string that does not match parameters
618 */
619 function getRegexStart() {
620 $base = $this->getBaseRegex();
621 $newRegex = array( '', '' );
622 if ( $base[0] !== '' ) {
623 $newRegex[0] = "/^(?:{$base[0]})/iuS";
624 }
625 if ( $base[1] !== '' ) {
626 $newRegex[1] = "/^(?:{$base[1]})/S";
627 }
628 return $newRegex;
629 }
630
631 /**
632 * Get an anchored regex for matching variables with parameters
633 */
634 function getVariableStartToEndRegex() {
635 $base = $this->getBaseRegex();
636 $newRegex = array( '', '' );
637 if ( $base[0] !== '' ) {
638 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
639 }
640 if ( $base[1] !== '' ) {
641 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
642 }
643 return $newRegex;
644 }
645
646 /**
647 * Parse a match array from preg_match
648 * Returns array(magic word ID, parameter value)
649 * If there is no parameter value, that element will be false.
650 */
651 function parseMatch( $m ) {
652 reset( $m );
653 while ( list( $key, $value ) = each( $m ) ) {
654 if ( $key === 0 || $value === '' ) {
655 continue;
656 }
657 $parts = explode( '_', $key, 2 );
658 if ( count( $parts ) != 2 ) {
659 // This shouldn't happen
660 // continue;
661 throw new MWException( __METHOD__ . ': bad parameter name' );
662 }
663 list( /* $synIndex */, $magicName ) = $parts;
664 $paramValue = next( $m );
665 return array( $magicName, $paramValue );
666 }
667 // This shouldn't happen either
668 throw new MWException( __METHOD__.': parameter not found' );
669 }
670
671 /**
672 * Match some text, with parameter capture
673 * Returns an array with the magic word name in the first element and the
674 * parameter in the second element.
675 * Both elements are false if there was no match.
676 */
677 public function matchVariableStartToEnd( $text ) {
678 $regexes = $this->getVariableStartToEndRegex();
679 foreach ( $regexes as $regex ) {
680 if ( $regex !== '' ) {
681 $m = false;
682 if ( preg_match( $regex, $text, $m ) ) {
683 return $this->parseMatch( $m );
684 }
685 }
686 }
687 return array( false, false );
688 }
689
690 /**
691 * Match some text, without parameter capture
692 * Returns the magic word name, or false if there was no capture
693 */
694 public function matchStartToEnd( $text ) {
695 $hash = $this->getHash();
696 if ( isset( $hash[1][$text] ) ) {
697 return $hash[1][$text];
698 }
699 global $wgContLang;
700 $lc = $wgContLang->lc( $text );
701 if ( isset( $hash[0][$lc] ) ) {
702 return $hash[0][$lc];
703 }
704 return false;
705 }
706
707 /**
708 * Returns an associative array, ID => param value, for all items that match
709 * Removes the matched items from the input string (passed by reference)
710 */
711 public function matchAndRemove( &$text ) {
712 $found = array();
713 $regexes = $this->getRegex();
714 foreach ( $regexes as $regex ) {
715 if ( $regex === '' ) {
716 continue;
717 }
718 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER );
719 foreach ( $matches as $m ) {
720 list( $name, $param ) = $this->parseMatch( $m );
721 $found[$name] = $param;
722 }
723 $text = preg_replace( $regex, '', $text );
724 }
725 return $found;
726 }
727
728 /**
729 * Return the ID of the magic word at the start of $text, and remove
730 * the prefix from $text.
731 * Return false if no match found and $text is not modified.
732 * Does not match parameters.
733 */
734 public function matchStartAndRemove( &$text ) {
735 $regexes = $this->getRegexStart();
736 foreach ( $regexes as $regex ) {
737 if ( $regex === '' ) {
738 continue;
739 }
740 if ( preg_match( $regex, $text, $m ) ) {
741 list( $id, ) = $this->parseMatch( $m );
742 if ( strlen( $m[0] ) >= strlen( $text ) ) {
743 $text = '';
744 } else {
745 $text = substr( $text, strlen( $m[0] ) );
746 }
747 return $id;
748 }
749 }
750 return false;
751 }
752 }