4 * See docs/magicword.txt
11 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
13 * if (MagicWord::get( 'redirect' )->match( $text ) )
15 * Possible future improvements:
16 * * Simultaneous searching for a number of magic words
17 * * MagicWord::$mObjects in shared memory
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.
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.
32 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
33 var $mRegexStart, $mBaseRegex, $mVariableRegex;
34 var $mModified, $mFound;
36 static public $mVariableIDsInitialised = false;
37 static public $mVariableIDs = array(
41 'currentmonthnamegen',
98 'numberofactiveusers',
111 /* Array of caching hints for ParserCache */
112 static public $mCacheTTLs = array (
113 'currentmonth' => 86400,
114 'currentmonth1' => 86400,
115 'currentmonthname' => 86400,
116 'currentmonthnamegen' => 86400,
117 'currentmonthabbrev' => 86400,
118 'currentday' => 3600,
119 'currentday2' => 3600,
120 'currentdayname' => 3600,
121 'currentyear' => 86400,
122 'currenttime' => 3600,
123 'currenthour' => 3600,
124 'localmonth' => 86400,
125 'localmonth1' => 86400,
126 'localmonthname' => 86400,
127 'localmonthnamegen' => 86400,
128 'localmonthabbrev' => 86400,
131 'localdayname' => 3600,
132 'localyear' => 86400,
135 'numberofarticles' => 3600,
136 'numberoffiles' => 3600,
137 'numberofedits' => 3600,
138 'currentweek' => 3600,
139 'currentdow' => 3600,
142 'numberofusers' => 3600,
143 'numberofactiveusers' => 3600,
144 'numberofpages' => 3600,
145 'currentversion' => 86400,
146 'currenttimestamp' => 3600,
147 'localtimestamp' => 3600,
148 'pagesinnamespace' => 3600,
149 'numberofadmins' => 3600,
150 'numberofviews' => 3600,
151 'numberingroup' => 3600,
154 static public $mDoubleUnderscoreIDs = array(
170 static public $mSubstIDs = array(
175 static public $mObjects = array();
176 static public $mDoubleUnderscoreArray = null;
180 function __construct($id = 0, $syn = '', $cs = false) {
182 $this->mSynonyms
= (array)$syn;
183 $this->mCaseSensitive
= $cs;
185 $this->mRegexStart
= '';
186 $this->mVariableRegex
= '';
187 $this->mVariableStartToEndRegex
= '';
188 $this->mModified
= false;
192 * Factory: creates an object representing an ID
195 static function &get( $id ) {
196 wfProfileIn( __METHOD__
);
197 if ( !isset( self
::$mObjects[$id] ) ) {
198 $mw = new MagicWord();
200 self
::$mObjects[$id] = $mw;
202 wfProfileOut( __METHOD__
);
203 return self
::$mObjects[$id];
207 * Get an array of parser variable IDs
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 );
219 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
220 self
::$mVariableIDsInitialised = true;
222 return self
::$mVariableIDs;
226 * Get an array of parser substitution modifier IDs
228 static function getSubstIDs() {
229 return self
::$mSubstIDs;
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];
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 );
246 return self
::$mDoubleUnderscoreArray;
250 * Clear the self::$mObjects variable
251 * For use in parser tests
253 public static function clearCache() {
254 self
::$mObjects = array();
257 # Initialises this object with an ID
258 function load( $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" );
270 * Preliminary initialisation
273 function initRegex() {
274 #$variableClass = Title::legalChars();
275 # This was used for matching "$1" variables, but different uses of the feature will have
276 # different restrictions, which should be checked *after* the MagicWord has been matched,
280 foreach ( $this->mSynonyms
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 );
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}" );
294 * Gets a regex representing matching the word
296 function getRegex() {
297 if ($this->mRegex
== '' ) {
300 return $this->mRegex
;
304 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
305 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
306 * the complete expression
308 function getRegexCase() {
309 if ( $this->mRegex
=== '' )
312 return $this->mCaseSensitive ?
'' : 'iu';
316 * Gets a regex matching the word, if it is at the string start
318 function getRegexStart() {
319 if ($this->mRegex
== '' ) {
322 return $this->mRegexStart
;
326 * regex without the slashes and what not
328 function getBaseRegex() {
329 if ($this->mRegex
== '') {
332 return $this->mBaseRegex
;
336 * Returns true if the text contains the word
339 function match( $text ) {
340 return (bool)preg_match( $this->getRegex(), $text );
344 * Returns true if the text starts with the word
347 function matchStart( $text ) {
348 return (bool)preg_match( $this->getRegexStart(), $text );
352 * Returns NULL if there's no match, the value of $1 otherwise
353 * The return code is the matched string, if there's no variable
354 * part in the regex and the matched variable part ($1) if there
357 function matchVariableStartToEnd( $text ) {
359 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
360 if ( $matchcount == 0 ) {
363 # multiple matched parts (variable match); some will be empty because of
364 # synonyms. The variable will be the second non-empty one so remove any
365 # blank elements and re-sort the indices.
368 $matches = array_values(array_filter($matches));
370 if ( count($matches) == 1 ) { return $matches[0]; }
371 else { return $matches[1]; }
377 * Returns true if the text matches the word, and alters the
378 * input string, removing all instances of the word
380 function matchAndRemove( &$text ) {
381 $this->mFound
= false;
382 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
383 return $this->mFound
;
386 function matchStartAndRemove( &$text ) {
387 $this->mFound
= false;
388 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
389 return $this->mFound
;
393 * Used in matchAndRemove()
396 function pregRemoveAndRecord( ) {
397 $this->mFound
= true;
402 * Replaces the word with something else
404 function replace( $replacement, $subject, $limit=-1 ) {
405 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
406 $this->mModified
= !($res === $subject);
411 * Variable handling: {{SUBST:xxx}} style words
412 * Calls back a function to determine what to replace xxx with
413 * Input word must contain $1
415 function substituteCallback( $text, $callback ) {
416 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
417 $this->mModified
= !($res === $text);
422 * Matches the word, where $1 is a wildcard
424 function getVariableRegex() {
425 if ( $this->mVariableRegex
== '' ) {
428 return $this->mVariableRegex
;
432 * Matches the entire string, where $1 is a wildcard
434 function getVariableStartToEndRegex() {
435 if ( $this->mVariableStartToEndRegex
== '' ) {
438 return $this->mVariableStartToEndRegex
;
442 * Accesses the synonym list directly
444 function getSynonym( $i ) {
445 return $this->mSynonyms
[$i];
448 function getSynonyms() {
449 return $this->mSynonyms
;
453 * Returns true if the last call to replace() or substituteCallback()
454 * returned a modified text, otherwise false.
456 function getWasModified(){
457 return $this->mModified
;
461 * $magicarr is an associative array of (magic word ID => replacement)
462 * This method uses the php feature to do several replacements at the same time,
463 * thereby gaining some efficiency. The result is placed in the out variable
464 * $result. The return value is true if something was replaced.
467 function replaceMultiple( $magicarr, $subject, &$result ){
470 foreach( $magicarr as $id => $replacement ){
471 $mw = MagicWord
::get( $id );
472 $search[] = $mw->getRegex();
473 $replace[] = $replacement;
476 $result = preg_replace( $search, $replace, $subject );
477 return !($result === $subject);
481 * Adds all the synonyms of this MagicWord to an array, to allow quick
482 * lookup in a list of magic words
484 function addToArray( &$array, $value ) {
486 foreach ( $this->mSynonyms
as $syn ) {
487 $array[$wgContLang->lc($syn)] = $value;
491 function isCaseSensitive() {
492 return $this->mCaseSensitive
;
501 * Class for handling an array of magic words
504 class MagicWordArray
{
505 var $names = array();
507 var $baseRegex, $regex;
510 function __construct( $names = array() ) {
511 $this->names
= $names;
515 * Add a magic word by name
517 public function add( $name ) {
519 $this->names
[] = $name;
520 $this->hash
= $this->baseRegex
= $this->regex
= null;
524 * Add a number of magic words by name
526 public function addArray( $names ) {
527 $this->names
= array_merge( $this->names
, array_values( $names ) );
528 $this->hash
= $this->baseRegex
= $this->regex
= null;
532 * Get a 2-d hashtable for this array
535 if ( is_null( $this->hash
) ) {
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 ) {
543 $syn = $wgContLang->lc( $syn );
545 $this->hash
[$case][$syn] = $name;
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;
566 $this->baseRegex
[$case] .= '|' . $group;
571 return $this->baseRegex
;
575 * Get an unanchored regex that does not match parameters
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";
584 if ( $this->baseRegex
[1] !== '' ) {
585 $this->regex
[1] = "/{$base[1]}/S";
592 * Get a regex for matching variables with parameters
594 function getVariableRegex() {
595 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
599 * Get a regex anchored to the start of the string that does not match parameters
601 function getRegexStart() {
602 $base = $this->getBaseRegex();
603 $newRegex = array( '', '' );
604 if ( $base[0] !== '' ) {
605 $newRegex[0] = "/^(?:{$base[0]})/iuS";
607 if ( $base[1] !== '' ) {
608 $newRegex[1] = "/^(?:{$base[1]})/S";
614 * Get an anchored regex for matching variables with parameters
616 function getVariableStartToEndRegex() {
617 $base = $this->getBaseRegex();
618 $newRegex = array( '', '' );
619 if ( $base[0] !== '' ) {
620 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
622 if ( $base[1] !== '' ) {
623 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
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.
633 function parseMatch( $m ) {
635 while ( list( $key, $value ) = each( $m ) ) {
636 if ( $key === 0 ||
$value === '' ) {
639 $parts = explode( '_', $key, 2 );
640 if ( count( $parts ) != 2 ) {
641 // This shouldn't happen
643 throw new MWException( __METHOD__
. ': bad parameter name' );
645 list( /* $synIndex */, $magicName ) = $parts;
646 $paramValue = next( $m );
647 return array( $magicName, $paramValue );
649 // This shouldn't happen either
650 throw new MWException( __METHOD__
.': parameter not found' );
651 return array( false, false );
655 * Match some text, with parameter capture
656 * Returns an array with the magic word name in the first element and the
657 * parameter in the second element.
658 * Both elements are false if there was no match.
660 public function matchVariableStartToEnd( $text ) {
662 $regexes = $this->getVariableStartToEndRegex();
663 foreach ( $regexes as $regex ) {
664 if ( $regex !== '' ) {
666 if ( preg_match( $regex, $text, $m ) ) {
667 return $this->parseMatch( $m );
671 return array( false, false );
675 * Match some text, without parameter capture
676 * Returns the magic word name, or false if there was no capture
678 public function matchStartToEnd( $text ) {
679 $hash = $this->getHash();
680 if ( isset( $hash[1][$text] ) ) {
681 return $hash[1][$text];
684 $lc = $wgContLang->lc( $text );
685 if ( isset( $hash[0][$lc] ) ) {
686 return $hash[0][$lc];
692 * Returns an associative array, ID => param value, for all items that match
693 * Removes the matched items from the input string (passed by reference)
695 public function matchAndRemove( &$text ) {
697 $regexes = $this->getRegex();
698 foreach ( $regexes as $regex ) {
699 if ( $regex === '' ) {
702 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
703 foreach ( $matches as $m ) {
704 list( $name, $param ) = $this->parseMatch( $m );
705 $found[$name] = $param;
707 $text = preg_replace( $regex, '', $text );
713 * Return the ID of the magic word at the start of $text, and remove
714 * the prefix from $text.
715 * Return false if no match found and $text is not modified.
716 * Does not match parameters.
718 public function matchStartAndRemove( &$text ) {
719 $regexes = $this->getRegexStart();
720 foreach ( $regexes as $regex ) {
721 if ( $regex === '' ) {
724 preg_match( $regex, $text, $match );
726 list( $found, $param ) = $this->parseMatch( $match );
727 $text = substr( $text, strlen( $found ) +
1 );