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(
40 'currentmonthnamegen',
112 /* Array of caching hints for ParserCache */
113 static public $mCacheTTLs = array (
114 'currentmonth' => 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 '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 'numberofpages' => 3600,
143 'currentversion' => 86400,
144 'currenttimestamp' => 3600,
145 'localtimestamp' => 3600,
146 'pagesinnamespace' => 3600,
147 'numberofadmins' => 3600,
150 static public $mDoubleUnderscoreIDs = array(
164 static public $mObjects = array();
165 static public $mDoubleUnderscoreArray = null;
169 function __construct($id = 0, $syn = '', $cs = false) {
171 $this->mSynonyms
= (array)$syn;
172 $this->mCaseSensitive
= $cs;
174 $this->mRegexStart
= '';
175 $this->mVariableRegex
= '';
176 $this->mVariableStartToEndRegex
= '';
177 $this->mModified
= false;
181 * Factory: creates an object representing an ID
184 static function &get( $id ) {
185 wfProfileIn( __METHOD__
);
186 if (!array_key_exists( $id, self
::$mObjects ) ) {
187 $mw = new MagicWord();
189 self
::$mObjects[$id] = $mw;
191 wfProfileOut( __METHOD__
);
192 return self
::$mObjects[$id];
196 * Get an array of parser variable IDs
198 static function getVariableIDs() {
199 if ( !self
::$mVariableIDsInitialised ) {
200 # Deprecated constant definition hook, available for extensions that need it
201 $magicWords = array();
202 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
203 foreach ( $magicWords as $word ) {
204 define( $word, $word );
208 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
209 self
::$mVariableIDsInitialised = true;
211 return self
::$mVariableIDs;
214 /* Allow external reads of TTL array */
215 static function getCacheTTL($id) {
216 if (array_key_exists($id,self
::$mCacheTTLs)) {
217 return self
::$mCacheTTLs[$id];
223 /** Get a MagicWordArray of double-underscore entities */
224 static function getDoubleUnderscoreArray() {
225 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
226 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
228 return self
::$mDoubleUnderscoreArray;
231 # Initialises this object with an ID
232 function load( $id ) {
235 $wgContLang->getMagic( $this );
236 if ( !$this->mSynonyms
) {
237 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
238 #throw new MWException( "Error: invalid magic word '$id'" );
239 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
244 * Preliminary initialisation
247 function initRegex() {
248 #$variableClass = Title::legalChars();
249 # This was used for matching "$1" variables, but different uses of the feature will have
250 # different restrictions, which should be checked *after* the MagicWord has been matched,
254 foreach ( $this->mSynonyms
as $synonym )
255 // In case a magic word contains /, like that's going to happen;)
256 $escSyn[] = preg_quote( $synonym, '/' );
257 $this->mBaseRegex
= implode( '|', $escSyn );
259 $case = $this->mCaseSensitive ?
'' : 'iu';
260 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
261 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
262 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
263 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
264 "/^(?:{$this->mBaseRegex})$/{$case}" );
268 * Gets a regex representing matching the word
270 function getRegex() {
271 if ($this->mRegex
== '' ) {
274 return $this->mRegex
;
278 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
279 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
280 * the complete expression
282 function getRegexCase() {
283 if ( $this->mRegex
=== '' )
286 return $this->mCaseSensitive ?
'' : 'iu';
290 * Gets a regex matching the word, if it is at the string start
292 function getRegexStart() {
293 if ($this->mRegex
== '' ) {
296 return $this->mRegexStart
;
300 * regex without the slashes and what not
302 function getBaseRegex() {
303 if ($this->mRegex
== '') {
306 return $this->mBaseRegex
;
310 * Returns true if the text contains the word
313 function match( $text ) {
314 return preg_match( $this->getRegex(), $text );
318 * Returns true if the text starts with the word
321 function matchStart( $text ) {
322 return preg_match( $this->getRegexStart(), $text );
326 * Returns NULL if there's no match, the value of $1 otherwise
327 * The return code is the matched string, if there's no variable
328 * part in the regex and the matched variable part ($1) if there
331 function matchVariableStartToEnd( $text ) {
333 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
334 if ( $matchcount == 0 ) {
337 # multiple matched parts (variable match); some will be empty because of
338 # synonyms. The variable will be the second non-empty one so remove any
339 # blank elements and re-sort the indices.
342 $matches = array_values(array_filter($matches));
344 if ( count($matches) == 1 ) { return $matches[0]; }
345 else { return $matches[1]; }
351 * Returns true if the text matches the word, and alters the
352 * input string, removing all instances of the word
354 function matchAndRemove( &$text ) {
355 $this->mFound
= false;
356 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
357 return $this->mFound
;
360 function matchStartAndRemove( &$text ) {
361 $this->mFound
= false;
362 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
363 return $this->mFound
;
367 * Used in matchAndRemove()
370 function pregRemoveAndRecord( ) {
371 $this->mFound
= true;
376 * Replaces the word with something else
378 function replace( $replacement, $subject, $limit=-1 ) {
379 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
380 $this->mModified
= !($res === $subject);
385 * Variable handling: {{SUBST:xxx}} style words
386 * Calls back a function to determine what to replace xxx with
387 * Input word must contain $1
389 function substituteCallback( $text, $callback ) {
390 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
391 $this->mModified
= !($res === $text);
396 * Matches the word, where $1 is a wildcard
398 function getVariableRegex() {
399 if ( $this->mVariableRegex
== '' ) {
402 return $this->mVariableRegex
;
406 * Matches the entire string, where $1 is a wildcard
408 function getVariableStartToEndRegex() {
409 if ( $this->mVariableStartToEndRegex
== '' ) {
412 return $this->mVariableStartToEndRegex
;
416 * Accesses the synonym list directly
418 function getSynonym( $i ) {
419 return $this->mSynonyms
[$i];
422 function getSynonyms() {
423 return $this->mSynonyms
;
427 * Returns true if the last call to replace() or substituteCallback()
428 * returned a modified text, otherwise false.
430 function getWasModified(){
431 return $this->mModified
;
435 * $magicarr is an associative array of (magic word ID => replacement)
436 * This method uses the php feature to do several replacements at the same time,
437 * thereby gaining some efficiency. The result is placed in the out variable
438 * $result. The return value is true if something was replaced.
441 function replaceMultiple( $magicarr, $subject, &$result ){
444 foreach( $magicarr as $id => $replacement ){
445 $mw = MagicWord
::get( $id );
446 $search[] = $mw->getRegex();
447 $replace[] = $replacement;
450 $result = preg_replace( $search, $replace, $subject );
451 return !($result === $subject);
455 * Adds all the synonyms of this MagicWord to an array, to allow quick
456 * lookup in a list of magic words
458 function addToArray( &$array, $value ) {
460 foreach ( $this->mSynonyms
as $syn ) {
461 $array[$wgContLang->lc($syn)] = $value;
465 function isCaseSensitive() {
466 return $this->mCaseSensitive
;
475 * Class for handling an array of magic words
478 class MagicWordArray
{
479 var $names = array();
481 var $baseRegex, $regex;
484 function __construct( $names = array() ) {
485 $this->names
= $names;
489 * Add a magic word by name
491 public function add( $name ) {
493 $this->names
[] = $name;
494 $this->hash
= $this->baseRegex
= $this->regex
= null;
498 * Add a number of magic words by name
500 public function addArray( $names ) {
501 $this->names
= array_merge( $this->names
, array_values( $names ) );
502 $this->hash
= $this->baseRegex
= $this->regex
= null;
506 * Get a 2-d hashtable for this array
509 if ( is_null( $this->hash
) ) {
511 $this->hash
= array( 0 => array(), 1 => array() );
512 foreach ( $this->names
as $name ) {
513 $magic = MagicWord
::get( $name );
514 $case = intval( $magic->isCaseSensitive() );
515 foreach ( $magic->getSynonyms() as $syn ) {
517 $syn = $wgContLang->lc( $syn );
519 $this->hash
[$case][$syn] = $name;
529 function getBaseRegex() {
530 if ( is_null( $this->baseRegex
) ) {
531 $this->baseRegex
= array( 0 => '', 1 => '' );
532 foreach ( $this->names
as $name ) {
533 $magic = MagicWord
::get( $name );
534 $case = intval( $magic->isCaseSensitive() );
535 foreach ( $magic->getSynonyms() as $i => $syn ) {
536 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
537 if ( $this->baseRegex
[$case] === '' ) {
538 $this->baseRegex
[$case] = $group;
540 $this->baseRegex
[$case] .= '|' . $group;
545 return $this->baseRegex
;
549 * Get an unanchored regex
551 function getRegex() {
552 if ( is_null( $this->regex
) ) {
553 $base = $this->getBaseRegex();
554 $this->regex
= array( '', '' );
555 if ( $this->baseRegex
[0] !== '' ) {
556 $this->regex
[0] = "/{$base[0]}/iuS";
558 if ( $this->baseRegex
[1] !== '' ) {
559 $this->regex
[1] = "/{$base[1]}/S";
566 * Get a regex for matching variables
568 function getVariableRegex() {
569 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
573 * Get an anchored regex for matching variables
575 function getVariableStartToEndRegex() {
576 $base = $this->getBaseRegex();
577 $newRegex = array( '', '' );
578 if ( $base[0] !== '' ) {
579 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
581 if ( $base[1] !== '' ) {
582 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
588 * Parse a match array from preg_match
589 * Returns array(magic word ID, parameter value)
590 * If there is no parameter value, that element will be false.
592 function parseMatch( $m ) {
594 while ( list( $key, $value ) = each( $m ) ) {
595 if ( $key === 0 ||
$value === '' ) {
598 $parts = explode( '_', $key, 2 );
599 if ( count( $parts ) != 2 ) {
600 // This shouldn't happen
602 throw new MWException( __METHOD__
. ': bad parameter name' );
604 list( /* $synIndex */, $magicName ) = $parts;
605 $paramValue = next( $m );
606 return array( $magicName, $paramValue );
608 // This shouldn't happen either
609 throw new MWException( __METHOD__
.': parameter not found' );
610 return array( false, false );
614 * Match some text, with parameter capture
615 * Returns an array with the magic word name in the first element and the
616 * parameter in the second element.
617 * Both elements are false if there was no match.
619 public function matchVariableStartToEnd( $text ) {
621 $regexes = $this->getVariableStartToEndRegex();
622 foreach ( $regexes as $regex ) {
623 if ( $regex !== '' ) {
625 if ( preg_match( $regex, $text, $m ) ) {
626 return $this->parseMatch( $m );
630 return array( false, false );
634 * Match some text, without parameter capture
635 * Returns the magic word name, or false if there was no capture
637 public function matchStartToEnd( $text ) {
638 $hash = $this->getHash();
639 if ( isset( $hash[1][$text] ) ) {
640 return $hash[1][$text];
643 $lc = $wgContLang->lc( $text );
644 if ( isset( $hash[0][$lc] ) ) {
645 return $hash[0][$lc];
651 * Returns an associative array, ID => param value, for all items that match
652 * Removes the matched items from the input string (passed by reference)
654 public function matchAndRemove( &$text ) {
656 $regexes = $this->getRegex();
657 foreach ( $regexes as $regex ) {
658 if ( $regex === '' ) {
661 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
662 foreach ( $matches as $m ) {
663 list( $name, $param ) = $this->parseMatch( $m );
664 $found[$name] = $param;
666 $text = preg_replace( $regex, '', $text );