5 * See docs/magicword.txt
12 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
14 * if (MagicWord::get( 'redirect' )->match( $text ) )
16 * Possible future improvements:
17 * * Simultaneous searching for a number of magic words
18 * * MagicWord::$mObjects in shared memory
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.
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.
33 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
34 var $mRegexStart, $mBaseRegex, $mVariableRegex;
35 var $mModified, $mFound;
37 static public $mVariableIDsInitialised = false;
38 static public $mVariableIDs = array(
42 'currentmonthnamegen',
99 'numberofactiveusers',
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,
132 'localdayname' => 3600,
133 'localyear' => 86400,
136 'numberofarticles' => 3600,
137 'numberoffiles' => 3600,
138 'numberofedits' => 3600,
139 'currentweek' => 3600,
140 'currentdow' => 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,
155 static public $mDoubleUnderscoreIDs = array(
171 static public $mSubstIDs = array(
176 static public $mObjects = array();
177 static public $mDoubleUnderscoreArray = null;
181 function __construct($id = 0, $syn = '', $cs = false) {
183 $this->mSynonyms
= (array)$syn;
184 $this->mCaseSensitive
= $cs;
186 $this->mRegexStart
= '';
187 $this->mVariableRegex
= '';
188 $this->mVariableStartToEndRegex
= '';
189 $this->mModified
= false;
193 * Factory: creates an object representing an ID
197 static function &get( $id ) {
198 wfProfileIn( __METHOD__
);
199 if ( !isset( self
::$mObjects[$id] ) ) {
200 $mw = new MagicWord();
202 self
::$mObjects[$id] = $mw;
204 wfProfileOut( __METHOD__
);
205 return self
::$mObjects[$id];
209 * Get an array of parser variable IDs
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 );
221 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
222 self
::$mVariableIDsInitialised = true;
224 return self
::$mVariableIDs;
228 * Get an array of parser substitution modifier IDs
230 static function getSubstIDs() {
231 return self
::$mSubstIDs;
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];
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 );
248 return self
::$mDoubleUnderscoreArray;
252 * Clear the self::$mObjects variable
253 * For use in parser tests
255 public static function clearCache() {
256 self
::$mObjects = array();
259 # Initialises this object with an ID
260 function load( $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" );
272 * Preliminary initialisation
275 function initRegex() {
276 #$variableClass = Title::legalChars();
277 # This was used for matching "$1" variables, but different uses of the feature will have
278 # different restrictions, which should be checked *after* the MagicWord has been matched,
282 foreach ( $this->mSynonyms
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 );
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}" );
296 * Gets a regex representing matching the word
298 function getRegex() {
299 if ($this->mRegex
== '' ) {
302 return $this->mRegex
;
306 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
307 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
308 * the complete expression
310 function getRegexCase() {
311 if ( $this->mRegex
=== '' )
314 return $this->mCaseSensitive ?
'' : 'iu';
318 * Gets a regex matching the word, if it is at the string start
320 function getRegexStart() {
321 if ($this->mRegex
== '' ) {
324 return $this->mRegexStart
;
328 * regex without the slashes and what not
330 function getBaseRegex() {
331 if ($this->mRegex
== '') {
334 return $this->mBaseRegex
;
338 * Returns true if the text contains the word
341 function match( $text ) {
342 return (bool)preg_match( $this->getRegex(), $text );
346 * Returns true if the text starts with the word
349 function matchStart( $text ) {
350 return (bool)preg_match( $this->getRegexStart(), $text );
354 * Returns NULL if there's no match, the value of $1 otherwise
355 * The return code is the matched string, if there's no variable
356 * part in the regex and the matched variable part ($1) if there
359 function matchVariableStartToEnd( $text ) {
361 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
362 if ( $matchcount == 0 ) {
365 # multiple matched parts (variable match); some will be empty because of
366 # synonyms. The variable will be the second non-empty one so remove any
367 # blank elements and re-sort the indices.
370 $matches = array_values(array_filter($matches));
372 if ( count($matches) == 1 ) { return $matches[0]; }
373 else { return $matches[1]; }
379 * Returns true if the text matches the word, and alters the
380 * input string, removing all instances of the word
382 function matchAndRemove( &$text ) {
383 $this->mFound
= false;
384 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
385 return $this->mFound
;
388 function matchStartAndRemove( &$text ) {
389 $this->mFound
= false;
390 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
391 return $this->mFound
;
395 * Used in matchAndRemove()
398 function pregRemoveAndRecord( ) {
399 $this->mFound
= true;
404 * Replaces the word with something else
406 function replace( $replacement, $subject, $limit=-1 ) {
407 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
408 $this->mModified
= !($res === $subject);
413 * Variable handling: {{SUBST:xxx}} style words
414 * Calls back a function to determine what to replace xxx with
415 * Input word must contain $1
417 function substituteCallback( $text, $callback ) {
418 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
419 $this->mModified
= !($res === $text);
424 * Matches the word, where $1 is a wildcard
426 function getVariableRegex() {
427 if ( $this->mVariableRegex
== '' ) {
430 return $this->mVariableRegex
;
434 * Matches the entire string, where $1 is a wildcard
436 function getVariableStartToEndRegex() {
437 if ( $this->mVariableStartToEndRegex
== '' ) {
440 return $this->mVariableStartToEndRegex
;
444 * Accesses the synonym list directly
446 function getSynonym( $i ) {
447 return $this->mSynonyms
[$i];
450 function getSynonyms() {
451 return $this->mSynonyms
;
455 * Returns true if the last call to replace() or substituteCallback()
456 * returned a modified text, otherwise false.
458 function getWasModified(){
459 return $this->mModified
;
463 * $magicarr is an associative array of (magic word ID => replacement)
464 * This method uses the php feature to do several replacements at the same time,
465 * thereby gaining some efficiency. The result is placed in the out variable
466 * $result. The return value is true if something was replaced.
469 function replaceMultiple( $magicarr, $subject, &$result ){
472 foreach( $magicarr as $id => $replacement ){
473 $mw = MagicWord
::get( $id );
474 $search[] = $mw->getRegex();
475 $replace[] = $replacement;
478 $result = preg_replace( $search, $replace, $subject );
479 return !($result === $subject);
483 * Adds all the synonyms of this MagicWord to an array, to allow quick
484 * lookup in a list of magic words
486 function addToArray( &$array, $value ) {
488 foreach ( $this->mSynonyms
as $syn ) {
489 $array[$wgContLang->lc($syn)] = $value;
493 function isCaseSensitive() {
494 return $this->mCaseSensitive
;
503 * Class for handling an array of magic words
506 class MagicWordArray
{
507 var $names = array();
509 var $baseRegex, $regex;
512 function __construct( $names = array() ) {
513 $this->names
= $names;
517 * Add a magic word by name
519 public function add( $name ) {
520 $this->names
[] = $name;
521 $this->hash
= $this->baseRegex
= $this->regex
= null;
525 * Add a number of magic words by name
527 public function addArray( $names ) {
528 $this->names
= array_merge( $this->names
, array_values( $names ) );
529 $this->hash
= $this->baseRegex
= $this->regex
= null;
533 * Get a 2-d hashtable for this array
536 if ( is_null( $this->hash
) ) {
538 $this->hash
= array( 0 => array(), 1 => array() );
539 foreach ( $this->names
as $name ) {
540 $magic = MagicWord
::get( $name );
541 $case = intval( $magic->isCaseSensitive() );
542 foreach ( $magic->getSynonyms() as $syn ) {
544 $syn = $wgContLang->lc( $syn );
546 $this->hash
[$case][$syn] = $name;
556 function getBaseRegex() {
557 if ( is_null( $this->baseRegex
) ) {
558 $this->baseRegex
= array( 0 => '', 1 => '' );
559 foreach ( $this->names
as $name ) {
560 $magic = MagicWord
::get( $name );
561 $case = intval( $magic->isCaseSensitive() );
562 foreach ( $magic->getSynonyms() as $i => $syn ) {
563 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
564 if ( $this->baseRegex
[$case] === '' ) {
565 $this->baseRegex
[$case] = $group;
567 $this->baseRegex
[$case] .= '|' . $group;
572 return $this->baseRegex
;
576 * Get an unanchored regex that does not match parameters
578 function getRegex() {
579 if ( is_null( $this->regex
) ) {
580 $base = $this->getBaseRegex();
581 $this->regex
= array( '', '' );
582 if ( $this->baseRegex
[0] !== '' ) {
583 $this->regex
[0] = "/{$base[0]}/iuS";
585 if ( $this->baseRegex
[1] !== '' ) {
586 $this->regex
[1] = "/{$base[1]}/S";
593 * Get a regex for matching variables with parameters
595 function getVariableRegex() {
596 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
600 * Get a regex anchored to the start of the string that does not match parameters
602 function getRegexStart() {
603 $base = $this->getBaseRegex();
604 $newRegex = array( '', '' );
605 if ( $base[0] !== '' ) {
606 $newRegex[0] = "/^(?:{$base[0]})/iuS";
608 if ( $base[1] !== '' ) {
609 $newRegex[1] = "/^(?:{$base[1]})/S";
615 * Get an anchored regex for matching variables with parameters
617 function getVariableStartToEndRegex() {
618 $base = $this->getBaseRegex();
619 $newRegex = array( '', '' );
620 if ( $base[0] !== '' ) {
621 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
623 if ( $base[1] !== '' ) {
624 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
630 * Parse a match array from preg_match
631 * Returns array(magic word ID, parameter value)
632 * If there is no parameter value, that element will be false.
634 function parseMatch( $m ) {
636 while ( list( $key, $value ) = each( $m ) ) {
637 if ( $key === 0 ||
$value === '' ) {
640 $parts = explode( '_', $key, 2 );
641 if ( count( $parts ) != 2 ) {
642 // This shouldn't happen
644 throw new MWException( __METHOD__
. ': bad parameter name' );
646 list( /* $synIndex */, $magicName ) = $parts;
647 $paramValue = next( $m );
648 return array( $magicName, $paramValue );
650 // This shouldn't happen either
651 throw new MWException( __METHOD__
.': parameter not found' );
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 ) {
661 $regexes = $this->getVariableStartToEndRegex();
662 foreach ( $regexes as $regex ) {
663 if ( $regex !== '' ) {
665 if ( preg_match( $regex, $text, $m ) ) {
666 return $this->parseMatch( $m );
670 return array( false, false );
674 * Match some text, without parameter capture
675 * Returns the magic word name, or false if there was no capture
677 public function matchStartToEnd( $text ) {
678 $hash = $this->getHash();
679 if ( isset( $hash[1][$text] ) ) {
680 return $hash[1][$text];
683 $lc = $wgContLang->lc( $text );
684 if ( isset( $hash[0][$lc] ) ) {
685 return $hash[0][$lc];
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)
694 public function matchAndRemove( &$text ) {
696 $regexes = $this->getRegex();
697 foreach ( $regexes as $regex ) {
698 if ( $regex === '' ) {
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;
706 $text = preg_replace( $regex, '', $text );
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.
717 public function matchStartAndRemove( &$text ) {
718 $regexes = $this->getRegexStart();
719 foreach ( $regexes as $regex ) {
720 if ( $regex === '' ) {
723 if ( preg_match( $regex, $text, $m ) ) {
724 list( $id, ) = $this->parseMatch( $m );
725 if ( strlen( $m[0] ) >= strlen( $text ) ) {
728 $text = substr( $text, strlen( $m[0] ) );