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;
35 var $mRegexStart = '';
37 var $mVariableRegex = '';
38 var $mModified = false;
41 static public $mVariableIDsInitialised = false;
42 static public $mVariableIDs = array(
46 'currentmonthnamegen',
103 'numberofactiveusers',
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,
136 'localdayname' => 3600,
137 'localyear' => 86400,
140 'numberofarticles' => 3600,
141 'numberoffiles' => 3600,
142 'numberofedits' => 3600,
143 'currentweek' => 3600,
144 'currentdow' => 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,
159 static public $mDoubleUnderscoreIDs = array(
175 static public $mSubstIDs = array(
180 static public $mObjects = array();
181 static public $mDoubleUnderscoreArray = null;
185 function __construct($id = 0, $syn = array(), $cs = false) {
187 $this->mSynonyms
= (array)$syn;
188 $this->mCaseSensitive
= $cs;
192 * Factory: creates an object representing an ID
196 static function &get( $id ) {
197 wfProfileIn( __METHOD__
);
198 if ( !isset( self
::$mObjects[$id] ) ) {
199 $mw = new MagicWord();
201 self
::$mObjects[$id] = $mw;
203 wfProfileOut( __METHOD__
);
204 return self
::$mObjects[$id];
208 * Get an array of parser variable IDs
210 static function getVariableIDs() {
211 if ( !self
::$mVariableIDsInitialised ) {
212 # Deprecated constant definition hook, available for extensions that need it
213 $magicWords = array();
214 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
215 foreach ( $magicWords as $word ) {
216 define( $word, $word );
220 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
221 self
::$mVariableIDsInitialised = true;
223 return self
::$mVariableIDs;
227 * Get an array of parser substitution modifier IDs
229 static function getSubstIDs() {
230 return self
::$mSubstIDs;
233 /* Allow external reads of TTL array */
234 static function getCacheTTL($id) {
235 if (array_key_exists($id,self
::$mCacheTTLs)) {
236 return self
::$mCacheTTLs[$id];
242 /** Get a MagicWordArray of double-underscore entities */
243 static function getDoubleUnderscoreArray() {
244 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
245 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
247 return self
::$mDoubleUnderscoreArray;
251 * Clear the self::$mObjects variable
252 * For use in parser tests
254 public static function clearCache() {
255 self
::$mObjects = array();
258 # Initialises this object with an ID
259 function load( $id ) {
262 $wgContLang->getMagic( $this );
263 if ( !$this->mSynonyms
) {
264 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
265 #throw new MWException( "Error: invalid magic word '$id'" );
266 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
271 * Preliminary initialisation
274 function initRegex() {
275 // Sort the synonyms by length, descending, so that the longest synonym
276 // matches in precedence to the shortest
277 $synonyms = $this->mSynonyms
;
278 usort( $synonyms, array( $this, 'compareStringLength' ) );
281 foreach ( $synonyms as $synonym )
282 // In case a magic word contains /, like that's going to happen;)
283 $escSyn[] = preg_quote( $synonym, '/' );
284 $this->mBaseRegex
= implode( '|', $escSyn );
286 $case = $this->mCaseSensitive ?
'' : 'iu';
287 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
288 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
289 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
290 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
291 "/^(?:{$this->mBaseRegex})$/{$case}" );
295 * A comparison function that returns -1, 0 or 1 depending on whether the
296 * first string is longer, the same length or shorter than the second
299 function compareStringLength( $s1, $s2 ) {
304 } elseif ( $l1 > $l2 ) {
312 * Gets a regex representing matching the word
314 function getRegex() {
315 if ($this->mRegex
== '' ) {
318 return $this->mRegex
;
322 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
323 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
324 * the complete expression
326 function getRegexCase() {
327 if ( $this->mRegex
=== '' )
330 return $this->mCaseSensitive ?
'' : 'iu';
334 * Gets a regex matching the word, if it is at the string start
336 function getRegexStart() {
337 if ($this->mRegex
== '' ) {
340 return $this->mRegexStart
;
344 * regex without the slashes and what not
346 function getBaseRegex() {
347 if ($this->mRegex
== '') {
350 return $this->mBaseRegex
;
354 * Returns true if the text contains the word
357 function match( $text ) {
358 return (bool)preg_match( $this->getRegex(), $text );
362 * Returns true if the text starts with the word
365 function matchStart( $text ) {
366 return (bool)preg_match( $this->getRegexStart(), $text );
370 * Returns NULL if there's no match, the value of $1 otherwise
371 * The return code is the matched string, if there's no variable
372 * part in the regex and the matched variable part ($1) if there
375 function matchVariableStartToEnd( $text ) {
377 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
378 if ( $matchcount == 0 ) {
381 # multiple matched parts (variable match); some will be empty because of
382 # synonyms. The variable will be the second non-empty one so remove any
383 # blank elements and re-sort the indices.
386 $matches = array_values(array_filter($matches));
388 if ( count($matches) == 1 ) { return $matches[0]; }
389 else { return $matches[1]; }
395 * Returns true if the text matches the word, and alters the
396 * input string, removing all instances of the word
398 function matchAndRemove( &$text ) {
399 $this->mFound
= false;
400 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
401 return $this->mFound
;
404 function matchStartAndRemove( &$text ) {
405 $this->mFound
= false;
406 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
407 return $this->mFound
;
411 * Used in matchAndRemove()
414 function pregRemoveAndRecord( ) {
415 $this->mFound
= true;
420 * Replaces the word with something else
422 function replace( $replacement, $subject, $limit=-1 ) {
423 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
424 $this->mModified
= !($res === $subject);
429 * Variable handling: {{SUBST:xxx}} style words
430 * Calls back a function to determine what to replace xxx with
431 * Input word must contain $1
433 function substituteCallback( $text, $callback ) {
434 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
435 $this->mModified
= !($res === $text);
440 * Matches the word, where $1 is a wildcard
442 function getVariableRegex() {
443 if ( $this->mVariableRegex
== '' ) {
446 return $this->mVariableRegex
;
450 * Matches the entire string, where $1 is a wildcard
452 function getVariableStartToEndRegex() {
453 if ( $this->mVariableStartToEndRegex
== '' ) {
456 return $this->mVariableStartToEndRegex
;
460 * Accesses the synonym list directly
462 function getSynonym( $i ) {
463 return $this->mSynonyms
[$i];
466 function getSynonyms() {
467 return $this->mSynonyms
;
471 * Returns true if the last call to replace() or substituteCallback()
472 * returned a modified text, otherwise false.
474 function getWasModified(){
475 return $this->mModified
;
479 * $magicarr is an associative array of (magic word ID => replacement)
480 * This method uses the php feature to do several replacements at the same time,
481 * thereby gaining some efficiency. The result is placed in the out variable
482 * $result. The return value is true if something was replaced.
485 function replaceMultiple( $magicarr, $subject, &$result ){
488 foreach( $magicarr as $id => $replacement ){
489 $mw = MagicWord
::get( $id );
490 $search[] = $mw->getRegex();
491 $replace[] = $replacement;
494 $result = preg_replace( $search, $replace, $subject );
495 return !($result === $subject);
499 * Adds all the synonyms of this MagicWord to an array, to allow quick
500 * lookup in a list of magic words
502 function addToArray( &$array, $value ) {
504 foreach ( $this->mSynonyms
as $syn ) {
505 $array[$wgContLang->lc($syn)] = $value;
509 function isCaseSensitive() {
510 return $this->mCaseSensitive
;
519 * Class for handling an array of magic words
522 class MagicWordArray
{
523 var $names = array();
525 var $baseRegex, $regex;
528 function __construct( $names = array() ) {
529 $this->names
= $names;
533 * Add a magic word by name
535 public function add( $name ) {
536 $this->names
[] = $name;
537 $this->hash
= $this->baseRegex
= $this->regex
= null;
541 * Add a number of magic words by name
543 public function addArray( $names ) {
544 $this->names
= array_merge( $this->names
, array_values( $names ) );
545 $this->hash
= $this->baseRegex
= $this->regex
= null;
549 * Get a 2-d hashtable for this array
552 if ( is_null( $this->hash
) ) {
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 ) {
560 $syn = $wgContLang->lc( $syn );
562 $this->hash
[$case][$syn] = $name;
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;
583 $this->baseRegex
[$case] .= '|' . $group;
588 return $this->baseRegex
;
592 * Get an unanchored regex that does not match parameters
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";
601 if ( $this->baseRegex
[1] !== '' ) {
602 $this->regex
[1] = "/{$base[1]}/S";
609 * Get a regex for matching variables with parameters
611 function getVariableRegex() {
612 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
616 * Get a regex anchored to the start of the string that does not match parameters
618 function getRegexStart() {
619 $base = $this->getBaseRegex();
620 $newRegex = array( '', '' );
621 if ( $base[0] !== '' ) {
622 $newRegex[0] = "/^(?:{$base[0]})/iuS";
624 if ( $base[1] !== '' ) {
625 $newRegex[1] = "/^(?:{$base[1]})/S";
631 * Get an anchored regex for matching variables with parameters
633 function getVariableStartToEndRegex() {
634 $base = $this->getBaseRegex();
635 $newRegex = array( '', '' );
636 if ( $base[0] !== '' ) {
637 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
639 if ( $base[1] !== '' ) {
640 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
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.
650 function parseMatch( $m ) {
652 while ( list( $key, $value ) = each( $m ) ) {
653 if ( $key === 0 ||
$value === '' ) {
656 $parts = explode( '_', $key, 2 );
657 if ( count( $parts ) != 2 ) {
658 // This shouldn't happen
660 throw new MWException( __METHOD__
. ': bad parameter name' );
662 list( /* $synIndex */, $magicName ) = $parts;
663 $paramValue = next( $m );
664 return array( $magicName, $paramValue );
666 // This shouldn't happen either
667 throw new MWException( __METHOD__
.': parameter not found' );
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.
676 public function matchVariableStartToEnd( $text ) {
677 $regexes = $this->getVariableStartToEndRegex();
678 foreach ( $regexes as $regex ) {
679 if ( $regex !== '' ) {
681 if ( preg_match( $regex, $text, $m ) ) {
682 return $this->parseMatch( $m );
686 return array( false, false );
690 * Match some text, without parameter capture
691 * Returns the magic word name, or false if there was no capture
693 public function matchStartToEnd( $text ) {
694 $hash = $this->getHash();
695 if ( isset( $hash[1][$text] ) ) {
696 return $hash[1][$text];
699 $lc = $wgContLang->lc( $text );
700 if ( isset( $hash[0][$lc] ) ) {
701 return $hash[0][$lc];
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)
710 public function matchAndRemove( &$text ) {
712 $regexes = $this->getRegex();
713 foreach ( $regexes as $regex ) {
714 if ( $regex === '' ) {
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;
722 $text = preg_replace( $regex, '', $text );
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.
733 public function matchStartAndRemove( &$text ) {
734 $regexes = $this->getRegexStart();
735 foreach ( $regexes as $regex ) {
736 if ( $regex === '' ) {
739 if ( preg_match( $regex, $text, $m ) ) {
740 list( $id, ) = $this->parseMatch( $m );
741 if ( strlen( $m[0] ) >= strlen( $text ) ) {
744 $text = substr( $text, strlen( $m[0] ) );