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