Fixup some more wrong static usages
[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 $this->names[] = $name;
518 $this->hash = $this->baseRegex = $this->regex = null;
519 }
520
521 /**
522 * Add a number of magic words by name
523 */
524 public function addArray( $names ) {
525 $this->names = array_merge( $this->names, array_values( $names ) );
526 $this->hash = $this->baseRegex = $this->regex = null;
527 }
528
529 /**
530 * Get a 2-d hashtable for this array
531 */
532 function getHash() {
533 if ( is_null( $this->hash ) ) {
534 global $wgContLang;
535 $this->hash = array( 0 => array(), 1 => array() );
536 foreach ( $this->names as $name ) {
537 $magic = MagicWord::get( $name );
538 $case = intval( $magic->isCaseSensitive() );
539 foreach ( $magic->getSynonyms() as $syn ) {
540 if ( !$case ) {
541 $syn = $wgContLang->lc( $syn );
542 }
543 $this->hash[$case][$syn] = $name;
544 }
545 }
546 }
547 return $this->hash;
548 }
549
550 /**
551 * Get the base regex
552 */
553 function getBaseRegex() {
554 if ( is_null( $this->baseRegex ) ) {
555 $this->baseRegex = array( 0 => '', 1 => '' );
556 foreach ( $this->names as $name ) {
557 $magic = MagicWord::get( $name );
558 $case = intval( $magic->isCaseSensitive() );
559 foreach ( $magic->getSynonyms() as $i => $syn ) {
560 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
561 if ( $this->baseRegex[$case] === '' ) {
562 $this->baseRegex[$case] = $group;
563 } else {
564 $this->baseRegex[$case] .= '|' . $group;
565 }
566 }
567 }
568 }
569 return $this->baseRegex;
570 }
571
572 /**
573 * Get an unanchored regex that does not match parameters
574 */
575 function getRegex() {
576 if ( is_null( $this->regex ) ) {
577 $base = $this->getBaseRegex();
578 $this->regex = array( '', '' );
579 if ( $this->baseRegex[0] !== '' ) {
580 $this->regex[0] = "/{$base[0]}/iuS";
581 }
582 if ( $this->baseRegex[1] !== '' ) {
583 $this->regex[1] = "/{$base[1]}/S";
584 }
585 }
586 return $this->regex;
587 }
588
589 /**
590 * Get a regex for matching variables with parameters
591 */
592 function getVariableRegex() {
593 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
594 }
595
596 /**
597 * Get a regex anchored to the start of the string that does not match parameters
598 */
599 function getRegexStart() {
600 $base = $this->getBaseRegex();
601 $newRegex = array( '', '' );
602 if ( $base[0] !== '' ) {
603 $newRegex[0] = "/^(?:{$base[0]})/iuS";
604 }
605 if ( $base[1] !== '' ) {
606 $newRegex[1] = "/^(?:{$base[1]})/S";
607 }
608 return $newRegex;
609 }
610
611 /**
612 * Get an anchored regex for matching variables with parameters
613 */
614 function getVariableStartToEndRegex() {
615 $base = $this->getBaseRegex();
616 $newRegex = array( '', '' );
617 if ( $base[0] !== '' ) {
618 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
619 }
620 if ( $base[1] !== '' ) {
621 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
622 }
623 return $newRegex;
624 }
625
626 /**
627 * Parse a match array from preg_match
628 * Returns array(magic word ID, parameter value)
629 * If there is no parameter value, that element will be false.
630 */
631 function parseMatch( $m ) {
632 reset( $m );
633 while ( list( $key, $value ) = each( $m ) ) {
634 if ( $key === 0 || $value === '' ) {
635 continue;
636 }
637 $parts = explode( '_', $key, 2 );
638 if ( count( $parts ) != 2 ) {
639 // This shouldn't happen
640 // continue;
641 throw new MWException( __METHOD__ . ': bad parameter name' );
642 }
643 list( /* $synIndex */, $magicName ) = $parts;
644 $paramValue = next( $m );
645 return array( $magicName, $paramValue );
646 }
647 // This shouldn't happen either
648 throw new MWException( __METHOD__.': parameter not found' );
649 return array( false, false );
650 }
651
652 /**
653 * Match some text, with parameter capture
654 * Returns an array with the magic word name in the first element and the
655 * parameter in the second element.
656 * Both elements are false if there was no match.
657 */
658 public function matchVariableStartToEnd( $text ) {
659 $regexes = $this->getVariableStartToEndRegex();
660 foreach ( $regexes as $regex ) {
661 if ( $regex !== '' ) {
662 $m = false;
663 if ( preg_match( $regex, $text, $m ) ) {
664 return $this->parseMatch( $m );
665 }
666 }
667 }
668 return array( false, false );
669 }
670
671 /**
672 * Match some text, without parameter capture
673 * Returns the magic word name, or false if there was no capture
674 */
675 public function matchStartToEnd( $text ) {
676 $hash = $this->getHash();
677 if ( isset( $hash[1][$text] ) ) {
678 return $hash[1][$text];
679 }
680 global $wgContLang;
681 $lc = $wgContLang->lc( $text );
682 if ( isset( $hash[0][$lc] ) ) {
683 return $hash[0][$lc];
684 }
685 return false;
686 }
687
688 /**
689 * Returns an associative array, ID => param value, for all items that match
690 * Removes the matched items from the input string (passed by reference)
691 */
692 public function matchAndRemove( &$text ) {
693 $found = array();
694 $regexes = $this->getRegex();
695 foreach ( $regexes as $regex ) {
696 if ( $regex === '' ) {
697 continue;
698 }
699 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER );
700 foreach ( $matches as $m ) {
701 list( $name, $param ) = $this->parseMatch( $m );
702 $found[$name] = $param;
703 }
704 $text = preg_replace( $regex, '', $text );
705 }
706 return $found;
707 }
708
709 /**
710 * Return the ID of the magic word at the start of $text, and remove
711 * the prefix from $text.
712 * Return false if no match found and $text is not modified.
713 * Does not match parameters.
714 */
715 public function matchStartAndRemove( &$text ) {
716 $regexes = $this->getRegexStart();
717 foreach ( $regexes as $regex ) {
718 if ( $regex === '' ) {
719 continue;
720 }
721 if ( preg_match( $regex, $text, $m ) ) {
722 list( $id, $param ) = $this->parseMatch( $m );
723 if ( strlen( $m[0] ) >= strlen( $text ) ) {
724 $text = '';
725 } else {
726 $text = substr( $text, strlen( $m[0] ) );
727 }
728 return $id;
729 }
730 }
731 return false;
732 }
733 }