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',
114 /* Array of caching hints for ParserCache */
115 static public $mCacheTTLs = array (
116 'currentmonth' => 86400,
117 'currentmonthname' => 86400,
118 'currentmonthnamegen' => 86400,
119 'currentmonthabbrev' => 86400,
120 'currentday' => 3600,
121 'currentday2' => 3600,
122 'currentdayname' => 3600,
123 'currentyear' => 86400,
124 'currenttime' => 3600,
125 'currenthour' => 3600,
126 'localmonth' => 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 'numberofpages' => 3600,
145 'currentversion' => 86400,
146 'currenttimestamp' => 3600,
147 'localtimestamp' => 3600,
148 'pagesinnamespace' => 3600,
149 'numberofadmins' => 3600,
150 'numberofviews' => 3600,
151 'numberingroup' => 3600,
154 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 (!array_key_exists( $id, self
::$mObjects ) ) {
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;
236 # Initialises this object with an ID
237 function load( $id ) {
240 $wgContLang->getMagic( $this );
241 if ( !$this->mSynonyms
) {
242 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
243 #throw new MWException( "Error: invalid magic word '$id'" );
244 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
249 * Preliminary initialisation
252 function initRegex() {
253 #$variableClass = Title::legalChars();
254 # This was used for matching "$1" variables, but different uses of the feature will have
255 # different restrictions, which should be checked *after* the MagicWord has been matched,
259 foreach ( $this->mSynonyms
as $synonym )
260 // In case a magic word contains /, like that's going to happen;)
261 $escSyn[] = preg_quote( $synonym, '/' );
262 $this->mBaseRegex
= implode( '|', $escSyn );
264 $case = $this->mCaseSensitive ?
'' : 'iu';
265 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
266 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
267 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
268 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
269 "/^(?:{$this->mBaseRegex})$/{$case}" );
273 * Gets a regex representing matching the word
275 function getRegex() {
276 if ($this->mRegex
== '' ) {
279 return $this->mRegex
;
283 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
284 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
285 * the complete expression
287 function getRegexCase() {
288 if ( $this->mRegex
=== '' )
291 return $this->mCaseSensitive ?
'' : 'iu';
295 * Gets a regex matching the word, if it is at the string start
297 function getRegexStart() {
298 if ($this->mRegex
== '' ) {
301 return $this->mRegexStart
;
305 * regex without the slashes and what not
307 function getBaseRegex() {
308 if ($this->mRegex
== '') {
311 return $this->mBaseRegex
;
315 * Returns true if the text contains the word
318 function match( $text ) {
319 return preg_match( $this->getRegex(), $text );
323 * Returns true if the text starts with the word
326 function matchStart( $text ) {
327 return preg_match( $this->getRegexStart(), $text );
331 * Returns NULL if there's no match, the value of $1 otherwise
332 * The return code is the matched string, if there's no variable
333 * part in the regex and the matched variable part ($1) if there
336 function matchVariableStartToEnd( $text ) {
338 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
339 if ( $matchcount == 0 ) {
342 # multiple matched parts (variable match); some will be empty because of
343 # synonyms. The variable will be the second non-empty one so remove any
344 # blank elements and re-sort the indices.
347 $matches = array_values(array_filter($matches));
349 if ( count($matches) == 1 ) { return $matches[0]; }
350 else { return $matches[1]; }
356 * Returns true if the text matches the word, and alters the
357 * input string, removing all instances of the word
359 function matchAndRemove( &$text ) {
360 $this->mFound
= false;
361 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
362 return $this->mFound
;
365 function matchStartAndRemove( &$text ) {
366 $this->mFound
= false;
367 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
368 return $this->mFound
;
372 * Used in matchAndRemove()
375 function pregRemoveAndRecord( ) {
376 $this->mFound
= true;
381 * Replaces the word with something else
383 function replace( $replacement, $subject, $limit=-1 ) {
384 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
385 $this->mModified
= !($res === $subject);
390 * Variable handling: {{SUBST:xxx}} style words
391 * Calls back a function to determine what to replace xxx with
392 * Input word must contain $1
394 function substituteCallback( $text, $callback ) {
395 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
396 $this->mModified
= !($res === $text);
401 * Matches the word, where $1 is a wildcard
403 function getVariableRegex() {
404 if ( $this->mVariableRegex
== '' ) {
407 return $this->mVariableRegex
;
411 * Matches the entire string, where $1 is a wildcard
413 function getVariableStartToEndRegex() {
414 if ( $this->mVariableStartToEndRegex
== '' ) {
417 return $this->mVariableStartToEndRegex
;
421 * Accesses the synonym list directly
423 function getSynonym( $i ) {
424 return $this->mSynonyms
[$i];
427 function getSynonyms() {
428 return $this->mSynonyms
;
432 * Returns true if the last call to replace() or substituteCallback()
433 * returned a modified text, otherwise false.
435 function getWasModified(){
436 return $this->mModified
;
440 * $magicarr is an associative array of (magic word ID => replacement)
441 * This method uses the php feature to do several replacements at the same time,
442 * thereby gaining some efficiency. The result is placed in the out variable
443 * $result. The return value is true if something was replaced.
446 function replaceMultiple( $magicarr, $subject, &$result ){
449 foreach( $magicarr as $id => $replacement ){
450 $mw = MagicWord
::get( $id );
451 $search[] = $mw->getRegex();
452 $replace[] = $replacement;
455 $result = preg_replace( $search, $replace, $subject );
456 return !($result === $subject);
460 * Adds all the synonyms of this MagicWord to an array, to allow quick
461 * lookup in a list of magic words
463 function addToArray( &$array, $value ) {
465 foreach ( $this->mSynonyms
as $syn ) {
466 $array[$wgContLang->lc($syn)] = $value;
470 function isCaseSensitive() {
471 return $this->mCaseSensitive
;
480 * Class for handling an array of magic words
483 class MagicWordArray
{
484 var $names = array();
486 var $baseRegex, $regex;
489 function __construct( $names = array() ) {
490 $this->names
= $names;
494 * Add a magic word by name
496 public function add( $name ) {
498 $this->names
[] = $name;
499 $this->hash
= $this->baseRegex
= $this->regex
= null;
503 * Add a number of magic words by name
505 public function addArray( $names ) {
506 $this->names
= array_merge( $this->names
, array_values( $names ) );
507 $this->hash
= $this->baseRegex
= $this->regex
= null;
511 * Get a 2-d hashtable for this array
514 if ( is_null( $this->hash
) ) {
516 $this->hash
= array( 0 => array(), 1 => array() );
517 foreach ( $this->names
as $name ) {
518 $magic = MagicWord
::get( $name );
519 $case = intval( $magic->isCaseSensitive() );
520 foreach ( $magic->getSynonyms() as $syn ) {
522 $syn = $wgContLang->lc( $syn );
524 $this->hash
[$case][$syn] = $name;
534 function getBaseRegex() {
535 if ( is_null( $this->baseRegex
) ) {
536 $this->baseRegex
= array( 0 => '', 1 => '' );
537 foreach ( $this->names
as $name ) {
538 $magic = MagicWord
::get( $name );
539 $case = intval( $magic->isCaseSensitive() );
540 foreach ( $magic->getSynonyms() as $i => $syn ) {
541 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
542 if ( $this->baseRegex
[$case] === '' ) {
543 $this->baseRegex
[$case] = $group;
545 $this->baseRegex
[$case] .= '|' . $group;
550 return $this->baseRegex
;
554 * Get an unanchored regex
556 function getRegex() {
557 if ( is_null( $this->regex
) ) {
558 $base = $this->getBaseRegex();
559 $this->regex
= array( '', '' );
560 if ( $this->baseRegex
[0] !== '' ) {
561 $this->regex
[0] = "/{$base[0]}/iuS";
563 if ( $this->baseRegex
[1] !== '' ) {
564 $this->regex
[1] = "/{$base[1]}/S";
571 * Get a regex for matching variables
573 function getVariableRegex() {
574 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
578 * Get an anchored regex for matching variables
580 function getVariableStartToEndRegex() {
581 $base = $this->getBaseRegex();
582 $newRegex = array( '', '' );
583 if ( $base[0] !== '' ) {
584 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
586 if ( $base[1] !== '' ) {
587 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
593 * Parse a match array from preg_match
594 * Returns array(magic word ID, parameter value)
595 * If there is no parameter value, that element will be false.
597 function parseMatch( $m ) {
599 while ( list( $key, $value ) = each( $m ) ) {
600 if ( $key === 0 ||
$value === '' ) {
603 $parts = explode( '_', $key, 2 );
604 if ( count( $parts ) != 2 ) {
605 // This shouldn't happen
607 throw new MWException( __METHOD__
. ': bad parameter name' );
609 list( /* $synIndex */, $magicName ) = $parts;
610 $paramValue = next( $m );
611 return array( $magicName, $paramValue );
613 // This shouldn't happen either
614 throw new MWException( __METHOD__
.': parameter not found' );
615 return array( false, false );
619 * Match some text, with parameter capture
620 * Returns an array with the magic word name in the first element and the
621 * parameter in the second element.
622 * Both elements are false if there was no match.
624 public function matchVariableStartToEnd( $text ) {
626 $regexes = $this->getVariableStartToEndRegex();
627 foreach ( $regexes as $regex ) {
628 if ( $regex !== '' ) {
630 if ( preg_match( $regex, $text, $m ) ) {
631 return $this->parseMatch( $m );
635 return array( false, false );
639 * Match some text, without parameter capture
640 * Returns the magic word name, or false if there was no capture
642 public function matchStartToEnd( $text ) {
643 $hash = $this->getHash();
644 if ( isset( $hash[1][$text] ) ) {
645 return $hash[1][$text];
648 $lc = $wgContLang->lc( $text );
649 if ( isset( $hash[0][$lc] ) ) {
650 return $hash[0][$lc];
656 * Returns an associative array, ID => param value, for all items that match
657 * Removes the matched items from the input string (passed by reference)
659 public function matchAndRemove( &$text ) {
661 $regexes = $this->getRegex();
662 foreach ( $regexes as $regex ) {
663 if ( $regex === '' ) {
666 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
667 foreach ( $matches as $m ) {
668 list( $name, $param ) = $this->parseMatch( $m );
669 $found[$name] = $param;
671 $text = preg_replace( $regex, '', $text );