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',
97 'numberofactiveusers',
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,
130 'localdayname' => 3600,
131 'localyear' => 86400,
134 'numberofarticles' => 3600,
135 'numberoffiles' => 3600,
136 'numberofedits' => 3600,
137 'currentweek' => 3600,
138 'currentdow' => 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,
153 static public $mDoubleUnderscoreIDs = array(
169 static public $mSubstIDs = array(
174 static public $mObjects = array();
175 static public $mDoubleUnderscoreArray = null;
179 function __construct($id = 0, $syn = '', $cs = false) {
181 $this->mSynonyms
= (array)$syn;
182 $this->mCaseSensitive
= $cs;
184 $this->mRegexStart
= '';
185 $this->mVariableRegex
= '';
186 $this->mVariableStartToEndRegex
= '';
187 $this->mModified
= false;
191 * Factory: creates an object representing an ID
194 static function &get( $id ) {
195 wfProfileIn( __METHOD__
);
196 if ( !isset( self
::$mObjects[$id] ) ) {
197 $mw = new MagicWord();
199 self
::$mObjects[$id] = $mw;
201 wfProfileOut( __METHOD__
);
202 return self
::$mObjects[$id];
206 * Get an array of parser variable IDs
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 );
218 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
219 self
::$mVariableIDsInitialised = true;
221 return self
::$mVariableIDs;
225 * Get an array of parser substitution modifier IDs
227 static function getSubstIDs() {
228 return self
::$mSubstIDs;
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];
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 );
245 return self
::$mDoubleUnderscoreArray;
249 * Clear the self::$mObjects variable
250 * For use in parser tests
252 public static function clearCache() {
253 self
::$mObjects = array();
256 # Initialises this object with an ID
257 function load( $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" );
269 * Preliminary initialisation
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,
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 );
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}" );
293 * Gets a regex representing matching the word
295 function getRegex() {
296 if ($this->mRegex
== '' ) {
299 return $this->mRegex
;
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
307 function getRegexCase() {
308 if ( $this->mRegex
=== '' )
311 return $this->mCaseSensitive ?
'' : 'iu';
315 * Gets a regex matching the word, if it is at the string start
317 function getRegexStart() {
318 if ($this->mRegex
== '' ) {
321 return $this->mRegexStart
;
325 * regex without the slashes and what not
327 function getBaseRegex() {
328 if ($this->mRegex
== '') {
331 return $this->mBaseRegex
;
335 * Returns true if the text contains the word
338 function match( $text ) {
339 return (bool)preg_match( $this->getRegex(), $text );
343 * Returns true if the text starts with the word
346 function matchStart( $text ) {
347 return (bool)preg_match( $this->getRegexStart(), $text );
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
356 function matchVariableStartToEnd( $text ) {
358 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
359 if ( $matchcount == 0 ) {
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.
367 $matches = array_values(array_filter($matches));
369 if ( count($matches) == 1 ) { return $matches[0]; }
370 else { return $matches[1]; }
376 * Returns true if the text matches the word, and alters the
377 * input string, removing all instances of the word
379 function matchAndRemove( &$text ) {
380 $this->mFound
= false;
381 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
382 return $this->mFound
;
385 function matchStartAndRemove( &$text ) {
386 $this->mFound
= false;
387 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
388 return $this->mFound
;
392 * Used in matchAndRemove()
395 function pregRemoveAndRecord( ) {
396 $this->mFound
= true;
401 * Replaces the word with something else
403 function replace( $replacement, $subject, $limit=-1 ) {
404 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
405 $this->mModified
= !($res === $subject);
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
414 function substituteCallback( $text, $callback ) {
415 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
416 $this->mModified
= !($res === $text);
421 * Matches the word, where $1 is a wildcard
423 function getVariableRegex() {
424 if ( $this->mVariableRegex
== '' ) {
427 return $this->mVariableRegex
;
431 * Matches the entire string, where $1 is a wildcard
433 function getVariableStartToEndRegex() {
434 if ( $this->mVariableStartToEndRegex
== '' ) {
437 return $this->mVariableStartToEndRegex
;
441 * Accesses the synonym list directly
443 function getSynonym( $i ) {
444 return $this->mSynonyms
[$i];
447 function getSynonyms() {
448 return $this->mSynonyms
;
452 * Returns true if the last call to replace() or substituteCallback()
453 * returned a modified text, otherwise false.
455 function getWasModified(){
456 return $this->mModified
;
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.
466 function replaceMultiple( $magicarr, $subject, &$result ){
469 foreach( $magicarr as $id => $replacement ){
470 $mw = MagicWord
::get( $id );
471 $search[] = $mw->getRegex();
472 $replace[] = $replacement;
475 $result = preg_replace( $search, $replace, $subject );
476 return !($result === $subject);
480 * Adds all the synonyms of this MagicWord to an array, to allow quick
481 * lookup in a list of magic words
483 function addToArray( &$array, $value ) {
485 foreach ( $this->mSynonyms
as $syn ) {
486 $array[$wgContLang->lc($syn)] = $value;
490 function isCaseSensitive() {
491 return $this->mCaseSensitive
;
500 * Class for handling an array of magic words
503 class MagicWordArray
{
504 var $names = array();
506 var $baseRegex, $regex;
509 function __construct( $names = array() ) {
510 $this->names
= $names;
514 * Add a magic word by name
516 public function add( $name ) {
518 $this->names
[] = $name;
519 $this->hash
= $this->baseRegex
= $this->regex
= null;
523 * Add a number of magic words by name
525 public function addArray( $names ) {
526 $this->names
= array_merge( $this->names
, array_values( $names ) );
527 $this->hash
= $this->baseRegex
= $this->regex
= null;
531 * Get a 2-d hashtable for this array
534 if ( is_null( $this->hash
) ) {
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 ) {
542 $syn = $wgContLang->lc( $syn );
544 $this->hash
[$case][$syn] = $name;
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;
565 $this->baseRegex
[$case] .= '|' . $group;
570 return $this->baseRegex
;
574 * Get an unanchored regex that does not match parameters
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";
583 if ( $this->baseRegex
[1] !== '' ) {
584 $this->regex
[1] = "/{$base[1]}/S";
591 * Get a regex for matching variables with parameters
593 function getVariableRegex() {
594 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
598 * Get a regex anchored to the start of the string that does not match parameters
600 function getRegexStart() {
601 $base = $this->getBaseRegex();
602 $newRegex = array( '', '' );
603 if ( $base[0] !== '' ) {
604 $newRegex[0] = "/^(?:{$base[0]})/iuS";
606 if ( $base[1] !== '' ) {
607 $newRegex[1] = "/^(?:{$base[1]})/S";
613 * Get an anchored regex for matching variables with parameters
615 function getVariableStartToEndRegex() {
616 $base = $this->getBaseRegex();
617 $newRegex = array( '', '' );
618 if ( $base[0] !== '' ) {
619 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
621 if ( $base[1] !== '' ) {
622 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
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.
632 function parseMatch( $m ) {
634 while ( list( $key, $value ) = each( $m ) ) {
635 if ( $key === 0 ||
$value === '' ) {
638 $parts = explode( '_', $key, 2 );
639 if ( count( $parts ) != 2 ) {
640 // This shouldn't happen
642 throw new MWException( __METHOD__
. ': bad parameter name' );
644 list( /* $synIndex */, $magicName ) = $parts;
645 $paramValue = next( $m );
646 return array( $magicName, $paramValue );
648 // This shouldn't happen either
649 throw new MWException( __METHOD__
.': parameter not found' );
650 return array( false, false );
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.
659 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, $param ) = $this->parseMatch( $m );
725 if ( strlen( $m[0] ) >= strlen( $text ) ) {
728 $text = substr( $text, strlen( $m[0] ) );