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
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 #$variableClass = Title::legalChars();
276 # This was used for matching "$1" variables, but different uses of the feature will have
277 # different restrictions, which should be checked *after* the MagicWord has been matched,
281 foreach ( $this->mSynonyms
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 * Gets a regex representing matching the word
297 function getRegex() {
298 if ($this->mRegex
== '' ) {
301 return $this->mRegex
;
305 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
306 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
307 * the complete expression
309 function getRegexCase() {
310 if ( $this->mRegex
=== '' )
313 return $this->mCaseSensitive ?
'' : 'iu';
317 * Gets a regex matching the word, if it is at the string start
319 function getRegexStart() {
320 if ($this->mRegex
== '' ) {
323 return $this->mRegexStart
;
327 * regex without the slashes and what not
329 function getBaseRegex() {
330 if ($this->mRegex
== '') {
333 return $this->mBaseRegex
;
337 * Returns true if the text contains the word
340 function match( $text ) {
341 return (bool)preg_match( $this->getRegex(), $text );
345 * Returns true if the text starts with the word
348 function matchStart( $text ) {
349 return (bool)preg_match( $this->getRegexStart(), $text );
353 * Returns NULL if there's no match, the value of $1 otherwise
354 * The return code is the matched string, if there's no variable
355 * part in the regex and the matched variable part ($1) if there
358 function matchVariableStartToEnd( $text ) {
360 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
361 if ( $matchcount == 0 ) {
364 # multiple matched parts (variable match); some will be empty because of
365 # synonyms. The variable will be the second non-empty one so remove any
366 # blank elements and re-sort the indices.
369 $matches = array_values(array_filter($matches));
371 if ( count($matches) == 1 ) { return $matches[0]; }
372 else { return $matches[1]; }
378 * Returns true if the text matches the word, and alters the
379 * input string, removing all instances of the word
381 function matchAndRemove( &$text ) {
382 $this->mFound
= false;
383 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
384 return $this->mFound
;
387 function matchStartAndRemove( &$text ) {
388 $this->mFound
= false;
389 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
390 return $this->mFound
;
394 * Used in matchAndRemove()
397 function pregRemoveAndRecord( ) {
398 $this->mFound
= true;
403 * Replaces the word with something else
405 function replace( $replacement, $subject, $limit=-1 ) {
406 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
407 $this->mModified
= !($res === $subject);
412 * Variable handling: {{SUBST:xxx}} style words
413 * Calls back a function to determine what to replace xxx with
414 * Input word must contain $1
416 function substituteCallback( $text, $callback ) {
417 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
418 $this->mModified
= !($res === $text);
423 * Matches the word, where $1 is a wildcard
425 function getVariableRegex() {
426 if ( $this->mVariableRegex
== '' ) {
429 return $this->mVariableRegex
;
433 * Matches the entire string, where $1 is a wildcard
435 function getVariableStartToEndRegex() {
436 if ( $this->mVariableStartToEndRegex
== '' ) {
439 return $this->mVariableStartToEndRegex
;
443 * Accesses the synonym list directly
445 function getSynonym( $i ) {
446 return $this->mSynonyms
[$i];
449 function getSynonyms() {
450 return $this->mSynonyms
;
454 * Returns true if the last call to replace() or substituteCallback()
455 * returned a modified text, otherwise false.
457 function getWasModified(){
458 return $this->mModified
;
462 * $magicarr is an associative array of (magic word ID => replacement)
463 * This method uses the php feature to do several replacements at the same time,
464 * thereby gaining some efficiency. The result is placed in the out variable
465 * $result. The return value is true if something was replaced.
468 function replaceMultiple( $magicarr, $subject, &$result ){
471 foreach( $magicarr as $id => $replacement ){
472 $mw = MagicWord
::get( $id );
473 $search[] = $mw->getRegex();
474 $replace[] = $replacement;
477 $result = preg_replace( $search, $replace, $subject );
478 return !($result === $subject);
482 * Adds all the synonyms of this MagicWord to an array, to allow quick
483 * lookup in a list of magic words
485 function addToArray( &$array, $value ) {
487 foreach ( $this->mSynonyms
as $syn ) {
488 $array[$wgContLang->lc($syn)] = $value;
492 function isCaseSensitive() {
493 return $this->mCaseSensitive
;
502 * Class for handling an array of magic words
505 class MagicWordArray
{
506 var $names = array();
508 var $baseRegex, $regex;
511 function __construct( $names = array() ) {
512 $this->names
= $names;
516 * Add a magic word by name
518 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' );
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 ) {
660 $regexes = $this->getVariableStartToEndRegex();
661 foreach ( $regexes as $regex ) {
662 if ( $regex !== '' ) {
664 if ( preg_match( $regex, $text, $m ) ) {
665 return $this->parseMatch( $m );
669 return array( false, false );
673 * Match some text, without parameter capture
674 * Returns the magic word name, or false if there was no capture
676 public function matchStartToEnd( $text ) {
677 $hash = $this->getHash();
678 if ( isset( $hash[1][$text] ) ) {
679 return $hash[1][$text];
682 $lc = $wgContLang->lc( $text );
683 if ( isset( $hash[0][$lc] ) ) {
684 return $hash[0][$lc];
690 * Returns an associative array, ID => param value, for all items that match
691 * Removes the matched items from the input string (passed by reference)
693 public function matchAndRemove( &$text ) {
695 $regexes = $this->getRegex();
696 foreach ( $regexes as $regex ) {
697 if ( $regex === '' ) {
700 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
701 foreach ( $matches as $m ) {
702 list( $name, $param ) = $this->parseMatch( $m );
703 $found[$name] = $param;
705 $text = preg_replace( $regex, '', $text );
711 * Return the ID of the magic word at the start of $text, and remove
712 * the prefix from $text.
713 * Return false if no match found and $text is not modified.
714 * Does not match parameters.
716 public function matchStartAndRemove( &$text ) {
717 $regexes = $this->getRegexStart();
718 foreach ( $regexes as $regex ) {
719 if ( $regex === '' ) {
722 if ( preg_match( $regex, $text, $m ) ) {
723 list( $id, $param ) = $this->parseMatch( $m );
724 if ( strlen( $m[0] ) >= strlen( $text ) ) {
727 $text = substr( $text, strlen( $m[0] ) );