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',
96 'numberofactiveusers',
109 /* Array of caching hints for ParserCache */
110 static public $mCacheTTLs = array (
111 'currentmonth' => 86400,
112 'currentmonth1' => 86400,
113 'currentmonthname' => 86400,
114 'currentmonthnamegen' => 86400,
115 'currentmonthabbrev' => 86400,
116 'currentday' => 3600,
117 'currentday2' => 3600,
118 'currentdayname' => 3600,
119 'currentyear' => 86400,
120 'currenttime' => 3600,
121 'currenthour' => 3600,
122 'localmonth' => 86400,
123 'localmonth1' => 86400,
124 'localmonthname' => 86400,
125 'localmonthnamegen' => 86400,
126 'localmonthabbrev' => 86400,
129 'localdayname' => 3600,
130 'localyear' => 86400,
133 'numberofarticles' => 3600,
134 'numberoffiles' => 3600,
135 'numberofedits' => 3600,
136 'currentweek' => 3600,
137 'currentdow' => 3600,
140 'numberofusers' => 3600,
141 'numberofactiveusers' => 3600,
142 'numberofpages' => 3600,
143 'currentversion' => 86400,
144 'currenttimestamp' => 3600,
145 'localtimestamp' => 3600,
146 'pagesinnamespace' => 3600,
147 'numberofadmins' => 3600,
148 'numberofviews' => 3600,
149 'numberingroup' => 3600,
152 static public $mDoubleUnderscoreIDs = array(
169 static public $mObjects = array();
170 static public $mDoubleUnderscoreArray = null;
174 function __construct($id = 0, $syn = '', $cs = false) {
176 $this->mSynonyms
= (array)$syn;
177 $this->mCaseSensitive
= $cs;
179 $this->mRegexStart
= '';
180 $this->mVariableRegex
= '';
181 $this->mVariableStartToEndRegex
= '';
182 $this->mModified
= false;
186 * Factory: creates an object representing an ID
189 static function &get( $id ) {
190 wfProfileIn( __METHOD__
);
191 if ( !isset( self
::$mObjects[$id] ) ) {
192 $mw = new MagicWord();
194 self
::$mObjects[$id] = $mw;
196 wfProfileOut( __METHOD__
);
197 return self
::$mObjects[$id];
201 * Get an array of parser variable IDs
203 static function getVariableIDs() {
204 if ( !self
::$mVariableIDsInitialised ) {
205 # Deprecated constant definition hook, available for extensions that need it
206 $magicWords = array();
207 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
208 foreach ( $magicWords as $word ) {
209 define( $word, $word );
213 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
214 self
::$mVariableIDsInitialised = true;
216 return self
::$mVariableIDs;
219 /* Allow external reads of TTL array */
220 static function getCacheTTL($id) {
221 if (array_key_exists($id,self
::$mCacheTTLs)) {
222 return self
::$mCacheTTLs[$id];
228 /** Get a MagicWordArray of double-underscore entities */
229 static function getDoubleUnderscoreArray() {
230 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
231 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
233 return self
::$mDoubleUnderscoreArray;
237 * Clear the self::$mObjects variable
238 * For use in parser tests
240 public static function clearCache() {
241 self
::$mObjects = array();
244 # Initialises this object with an ID
245 function load( $id ) {
248 $wgContLang->getMagic( $this );
249 if ( !$this->mSynonyms
) {
250 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
251 #throw new MWException( "Error: invalid magic word '$id'" );
252 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
257 * Preliminary initialisation
260 function initRegex() {
261 #$variableClass = Title::legalChars();
262 # This was used for matching "$1" variables, but different uses of the feature will have
263 # different restrictions, which should be checked *after* the MagicWord has been matched,
267 foreach ( $this->mSynonyms
as $synonym )
268 // In case a magic word contains /, like that's going to happen;)
269 $escSyn[] = preg_quote( $synonym, '/' );
270 $this->mBaseRegex
= implode( '|', $escSyn );
272 $case = $this->mCaseSensitive ?
'' : 'iu';
273 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
274 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
275 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
276 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
277 "/^(?:{$this->mBaseRegex})$/{$case}" );
281 * Gets a regex representing matching the word
283 function getRegex() {
284 if ($this->mRegex
== '' ) {
287 return $this->mRegex
;
291 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
292 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
293 * the complete expression
295 function getRegexCase() {
296 if ( $this->mRegex
=== '' )
299 return $this->mCaseSensitive ?
'' : 'iu';
303 * Gets a regex matching the word, if it is at the string start
305 function getRegexStart() {
306 if ($this->mRegex
== '' ) {
309 return $this->mRegexStart
;
313 * regex without the slashes and what not
315 function getBaseRegex() {
316 if ($this->mRegex
== '') {
319 return $this->mBaseRegex
;
323 * Returns true if the text contains the word
326 function match( $text ) {
327 return (bool)preg_match( $this->getRegex(), $text );
331 * Returns true if the text starts with the word
334 function matchStart( $text ) {
335 return (bool)preg_match( $this->getRegexStart(), $text );
339 * Returns NULL if there's no match, the value of $1 otherwise
340 * The return code is the matched string, if there's no variable
341 * part in the regex and the matched variable part ($1) if there
344 function matchVariableStartToEnd( $text ) {
346 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
347 if ( $matchcount == 0 ) {
350 # multiple matched parts (variable match); some will be empty because of
351 # synonyms. The variable will be the second non-empty one so remove any
352 # blank elements and re-sort the indices.
355 $matches = array_values(array_filter($matches));
357 if ( count($matches) == 1 ) { return $matches[0]; }
358 else { return $matches[1]; }
364 * Returns true if the text matches the word, and alters the
365 * input string, removing all instances of the word
367 function matchAndRemove( &$text ) {
368 $this->mFound
= false;
369 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
370 return $this->mFound
;
373 function matchStartAndRemove( &$text ) {
374 $this->mFound
= false;
375 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
376 return $this->mFound
;
380 * Used in matchAndRemove()
383 function pregRemoveAndRecord( ) {
384 $this->mFound
= true;
389 * Replaces the word with something else
391 function replace( $replacement, $subject, $limit=-1 ) {
392 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
393 $this->mModified
= !($res === $subject);
398 * Variable handling: {{SUBST:xxx}} style words
399 * Calls back a function to determine what to replace xxx with
400 * Input word must contain $1
402 function substituteCallback( $text, $callback ) {
403 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
404 $this->mModified
= !($res === $text);
409 * Matches the word, where $1 is a wildcard
411 function getVariableRegex() {
412 if ( $this->mVariableRegex
== '' ) {
415 return $this->mVariableRegex
;
419 * Matches the entire string, where $1 is a wildcard
421 function getVariableStartToEndRegex() {
422 if ( $this->mVariableStartToEndRegex
== '' ) {
425 return $this->mVariableStartToEndRegex
;
429 * Accesses the synonym list directly
431 function getSynonym( $i ) {
432 return $this->mSynonyms
[$i];
435 function getSynonyms() {
436 return $this->mSynonyms
;
440 * Returns true if the last call to replace() or substituteCallback()
441 * returned a modified text, otherwise false.
443 function getWasModified(){
444 return $this->mModified
;
448 * $magicarr is an associative array of (magic word ID => replacement)
449 * This method uses the php feature to do several replacements at the same time,
450 * thereby gaining some efficiency. The result is placed in the out variable
451 * $result. The return value is true if something was replaced.
454 function replaceMultiple( $magicarr, $subject, &$result ){
457 foreach( $magicarr as $id => $replacement ){
458 $mw = MagicWord
::get( $id );
459 $search[] = $mw->getRegex();
460 $replace[] = $replacement;
463 $result = preg_replace( $search, $replace, $subject );
464 return !($result === $subject);
468 * Adds all the synonyms of this MagicWord to an array, to allow quick
469 * lookup in a list of magic words
471 function addToArray( &$array, $value ) {
473 foreach ( $this->mSynonyms
as $syn ) {
474 $array[$wgContLang->lc($syn)] = $value;
478 function isCaseSensitive() {
479 return $this->mCaseSensitive
;
488 * Class for handling an array of magic words
491 class MagicWordArray
{
492 var $names = array();
494 var $baseRegex, $regex;
497 function __construct( $names = array() ) {
498 $this->names
= $names;
502 * Add a magic word by name
504 public function add( $name ) {
506 $this->names
[] = $name;
507 $this->hash
= $this->baseRegex
= $this->regex
= null;
511 * Add a number of magic words by name
513 public function addArray( $names ) {
514 $this->names
= array_merge( $this->names
, array_values( $names ) );
515 $this->hash
= $this->baseRegex
= $this->regex
= null;
519 * Get a 2-d hashtable for this array
522 if ( is_null( $this->hash
) ) {
524 $this->hash
= array( 0 => array(), 1 => array() );
525 foreach ( $this->names
as $name ) {
526 $magic = MagicWord
::get( $name );
527 $case = intval( $magic->isCaseSensitive() );
528 foreach ( $magic->getSynonyms() as $syn ) {
530 $syn = $wgContLang->lc( $syn );
532 $this->hash
[$case][$syn] = $name;
542 function getBaseRegex() {
543 if ( is_null( $this->baseRegex
) ) {
544 $this->baseRegex
= array( 0 => '', 1 => '' );
545 foreach ( $this->names
as $name ) {
546 $magic = MagicWord
::get( $name );
547 $case = intval( $magic->isCaseSensitive() );
548 foreach ( $magic->getSynonyms() as $i => $syn ) {
549 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
550 if ( $this->baseRegex
[$case] === '' ) {
551 $this->baseRegex
[$case] = $group;
553 $this->baseRegex
[$case] .= '|' . $group;
558 return $this->baseRegex
;
562 * Get an unanchored regex
564 function getRegex() {
565 if ( is_null( $this->regex
) ) {
566 $base = $this->getBaseRegex();
567 $this->regex
= array( '', '' );
568 if ( $this->baseRegex
[0] !== '' ) {
569 $this->regex
[0] = "/{$base[0]}/iuS";
571 if ( $this->baseRegex
[1] !== '' ) {
572 $this->regex
[1] = "/{$base[1]}/S";
579 * Get a regex for matching variables
581 function getVariableRegex() {
582 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
586 * Get an anchored regex for matching variables
588 function getVariableStartToEndRegex() {
589 $base = $this->getBaseRegex();
590 $newRegex = array( '', '' );
591 if ( $base[0] !== '' ) {
592 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
594 if ( $base[1] !== '' ) {
595 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
601 * Parse a match array from preg_match
602 * Returns array(magic word ID, parameter value)
603 * If there is no parameter value, that element will be false.
605 function parseMatch( $m ) {
607 while ( list( $key, $value ) = each( $m ) ) {
608 if ( $key === 0 ||
$value === '' ) {
611 $parts = explode( '_', $key, 2 );
612 if ( count( $parts ) != 2 ) {
613 // This shouldn't happen
615 throw new MWException( __METHOD__
. ': bad parameter name' );
617 list( /* $synIndex */, $magicName ) = $parts;
618 $paramValue = next( $m );
619 return array( $magicName, $paramValue );
621 // This shouldn't happen either
622 throw new MWException( __METHOD__
.': parameter not found' );
623 return array( false, false );
627 * Match some text, with parameter capture
628 * Returns an array with the magic word name in the first element and the
629 * parameter in the second element.
630 * Both elements are false if there was no match.
632 public function matchVariableStartToEnd( $text ) {
634 $regexes = $this->getVariableStartToEndRegex();
635 foreach ( $regexes as $regex ) {
636 if ( $regex !== '' ) {
638 if ( preg_match( $regex, $text, $m ) ) {
639 return $this->parseMatch( $m );
643 return array( false, false );
647 * Match some text, without parameter capture
648 * Returns the magic word name, or false if there was no capture
650 public function matchStartToEnd( $text ) {
651 $hash = $this->getHash();
652 if ( isset( $hash[1][$text] ) ) {
653 return $hash[1][$text];
656 $lc = $wgContLang->lc( $text );
657 if ( isset( $hash[0][$lc] ) ) {
658 return $hash[0][$lc];
664 * Returns an associative array, ID => param value, for all items that match
665 * Removes the matched items from the input string (passed by reference)
667 public function matchAndRemove( &$text ) {
669 $regexes = $this->getRegex();
670 foreach ( $regexes as $regex ) {
671 if ( $regex === '' ) {
674 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
675 foreach ( $matches as $m ) {
676 list( $name, $param ) = $this->parseMatch( $m );
677 $found[$name] = $param;
679 $text = preg_replace( $regex, '', $text );