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