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(
163 static public $mObjects = array();
164 static public $mDoubleUnderscoreArray = null;
168 function __construct($id = 0, $syn = '', $cs = false) {
170 $this->mSynonyms
= (array)$syn;
171 $this->mCaseSensitive
= $cs;
173 $this->mRegexStart
= '';
174 $this->mVariableRegex
= '';
175 $this->mVariableStartToEndRegex
= '';
176 $this->mModified
= false;
180 * Factory: creates an object representing an ID
183 static function &get( $id ) {
184 wfProfileIn( __METHOD__
);
185 if (!array_key_exists( $id, self
::$mObjects ) ) {
186 $mw = new MagicWord();
188 self
::$mObjects[$id] = $mw;
190 wfProfileOut( __METHOD__
);
191 return self
::$mObjects[$id];
195 * Get an array of parser variable IDs
197 static function getVariableIDs() {
198 if ( !self
::$mVariableIDsInitialised ) {
199 # Deprecated constant definition hook, available for extensions that need it
200 $magicWords = array();
201 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
202 foreach ( $magicWords as $word ) {
203 define( $word, $word );
207 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
208 self
::$mVariableIDsInitialised = true;
210 return self
::$mVariableIDs;
213 /* Allow external reads of TTL array */
214 static function getCacheTTL($id) {
215 if (array_key_exists($id,self
::$mCacheTTLs)) {
216 return self
::$mCacheTTLs[$id];
222 /** Get a MagicWordArray of double-underscore entities */
223 static function getDoubleUnderscoreArray() {
224 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
225 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
227 return self
::$mDoubleUnderscoreArray;
230 # Initialises this object with an ID
231 function load( $id ) {
234 $wgContLang->getMagic( $this );
235 if ( !$this->mSynonyms
) {
236 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
237 #throw new MWException( "Error: invalid magic word '$id'" );
238 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
243 * Preliminary initialisation
246 function initRegex() {
247 #$variableClass = Title::legalChars();
248 # This was used for matching "$1" variables, but different uses of the feature will have
249 # different restrictions, which should be checked *after* the MagicWord has been matched,
253 foreach ( $this->mSynonyms
as $synonym )
254 // In case a magic word contains /, like that's going to happen;)
255 $escSyn[] = preg_quote( $synonym, '/' );
256 $this->mBaseRegex
= implode( '|', $escSyn );
258 $case = $this->mCaseSensitive ?
'' : 'iu';
259 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
260 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
261 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
262 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
263 "/^(?:{$this->mBaseRegex})$/{$case}" );
267 * Gets a regex representing matching the word
269 function getRegex() {
270 if ($this->mRegex
== '' ) {
273 return $this->mRegex
;
277 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
278 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
279 * the complete expression
281 function getRegexCase() {
282 if ( $this->mRegex
=== '' )
285 return $this->mCaseSensitive ?
'' : 'iu';
289 * Gets a regex matching the word, if it is at the string start
291 function getRegexStart() {
292 if ($this->mRegex
== '' ) {
295 return $this->mRegexStart
;
299 * regex without the slashes and what not
301 function getBaseRegex() {
302 if ($this->mRegex
== '') {
305 return $this->mBaseRegex
;
309 * Returns true if the text contains the word
312 function match( $text ) {
313 return preg_match( $this->getRegex(), $text );
317 * Returns true if the text starts with the word
320 function matchStart( $text ) {
321 return preg_match( $this->getRegexStart(), $text );
325 * Returns NULL if there's no match, the value of $1 otherwise
326 * The return code is the matched string, if there's no variable
327 * part in the regex and the matched variable part ($1) if there
330 function matchVariableStartToEnd( $text ) {
332 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
333 if ( $matchcount == 0 ) {
336 # multiple matched parts (variable match); some will be empty because of
337 # synonyms. The variable will be the second non-empty one so remove any
338 # blank elements and re-sort the indices.
341 $matches = array_values(array_filter($matches));
343 if ( count($matches) == 1 ) { return $matches[0]; }
344 else { return $matches[1]; }
350 * Returns true if the text matches the word, and alters the
351 * input string, removing all instances of the word
353 function matchAndRemove( &$text ) {
354 $this->mFound
= false;
355 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
356 return $this->mFound
;
359 function matchStartAndRemove( &$text ) {
360 $this->mFound
= false;
361 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
362 return $this->mFound
;
366 * Used in matchAndRemove()
369 function pregRemoveAndRecord( ) {
370 $this->mFound
= true;
375 * Replaces the word with something else
377 function replace( $replacement, $subject, $limit=-1 ) {
378 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
379 $this->mModified
= !($res === $subject);
384 * Variable handling: {{SUBST:xxx}} style words
385 * Calls back a function to determine what to replace xxx with
386 * Input word must contain $1
388 function substituteCallback( $text, $callback ) {
389 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
390 $this->mModified
= !($res === $text);
395 * Matches the word, where $1 is a wildcard
397 function getVariableRegex() {
398 if ( $this->mVariableRegex
== '' ) {
401 return $this->mVariableRegex
;
405 * Matches the entire string, where $1 is a wildcard
407 function getVariableStartToEndRegex() {
408 if ( $this->mVariableStartToEndRegex
== '' ) {
411 return $this->mVariableStartToEndRegex
;
415 * Accesses the synonym list directly
417 function getSynonym( $i ) {
418 return $this->mSynonyms
[$i];
421 function getSynonyms() {
422 return $this->mSynonyms
;
426 * Returns true if the last call to replace() or substituteCallback()
427 * returned a modified text, otherwise false.
429 function getWasModified(){
430 return $this->mModified
;
434 * $magicarr is an associative array of (magic word ID => replacement)
435 * This method uses the php feature to do several replacements at the same time,
436 * thereby gaining some efficiency. The result is placed in the out variable
437 * $result. The return value is true if something was replaced.
440 function replaceMultiple( $magicarr, $subject, &$result ){
443 foreach( $magicarr as $id => $replacement ){
444 $mw = MagicWord
::get( $id );
445 $search[] = $mw->getRegex();
446 $replace[] = $replacement;
449 $result = preg_replace( $search, $replace, $subject );
450 return !($result === $subject);
454 * Adds all the synonyms of this MagicWord to an array, to allow quick
455 * lookup in a list of magic words
457 function addToArray( &$array, $value ) {
459 foreach ( $this->mSynonyms
as $syn ) {
460 $array[$wgContLang->lc($syn)] = $value;
464 function isCaseSensitive() {
465 return $this->mCaseSensitive
;
474 * Class for handling an array of magic words
477 class MagicWordArray
{
478 var $names = array();
480 var $baseRegex, $regex;
483 function __construct( $names = array() ) {
484 $this->names
= $names;
488 * Add a magic word by name
490 public function add( $name ) {
492 $this->names
[] = $name;
493 $this->hash
= $this->baseRegex
= $this->regex
= null;
497 * Add a number of magic words by name
499 public function addArray( $names ) {
500 $this->names
= array_merge( $this->names
, array_values( $names ) );
501 $this->hash
= $this->baseRegex
= $this->regex
= null;
505 * Get a 2-d hashtable for this array
508 if ( is_null( $this->hash
) ) {
510 $this->hash
= array( 0 => array(), 1 => array() );
511 foreach ( $this->names
as $name ) {
512 $magic = MagicWord
::get( $name );
513 $case = intval( $magic->isCaseSensitive() );
514 foreach ( $magic->getSynonyms() as $syn ) {
516 $syn = $wgContLang->lc( $syn );
518 $this->hash
[$case][$syn] = $name;
528 function getBaseRegex() {
529 if ( is_null( $this->baseRegex
) ) {
530 $this->baseRegex
= array( 0 => '', 1 => '' );
531 foreach ( $this->names
as $name ) {
532 $magic = MagicWord
::get( $name );
533 $case = intval( $magic->isCaseSensitive() );
534 foreach ( $magic->getSynonyms() as $i => $syn ) {
535 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
536 if ( $this->baseRegex
[$case] === '' ) {
537 $this->baseRegex
[$case] = $group;
539 $this->baseRegex
[$case] .= '|' . $group;
544 return $this->baseRegex
;
548 * Get an unanchored regex
550 function getRegex() {
551 if ( is_null( $this->regex
) ) {
552 $base = $this->getBaseRegex();
553 $this->regex
= array( '', '' );
554 if ( $this->baseRegex
[0] !== '' ) {
555 $this->regex
[0] = "/{$base[0]}/iuS";
557 if ( $this->baseRegex
[1] !== '' ) {
558 $this->regex
[1] = "/{$base[1]}/S";
565 * Get a regex for matching variables
567 function getVariableRegex() {
568 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
572 * Get an anchored regex for matching variables
574 function getVariableStartToEndRegex() {
575 $base = $this->getBaseRegex();
576 $newRegex = array( '', '' );
577 if ( $base[0] !== '' ) {
578 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
580 if ( $base[1] !== '' ) {
581 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
587 * Parse a match array from preg_match
588 * Returns array(magic word ID, parameter value)
589 * If there is no parameter value, that element will be false.
591 function parseMatch( $m ) {
593 while ( list( $key, $value ) = each( $m ) ) {
594 if ( $key === 0 ||
$value === '' ) {
597 $parts = explode( '_', $key, 2 );
598 if ( count( $parts ) != 2 ) {
599 // This shouldn't happen
601 throw new MWException( __METHOD__
. ': bad parameter name' );
603 list( /* $synIndex */, $magicName ) = $parts;
604 $paramValue = next( $m );
605 return array( $magicName, $paramValue );
607 // This shouldn't happen either
608 throw new MWException( __METHOD__
.': parameter not found' );
609 return array( false, false );
613 * Match some text, with parameter capture
614 * Returns an array with the magic word name in the first element and the
615 * parameter in the second element.
616 * Both elements are false if there was no match.
618 public function matchVariableStartToEnd( $text ) {
620 $regexes = $this->getVariableStartToEndRegex();
621 foreach ( $regexes as $regex ) {
622 if ( $regex !== '' ) {
624 if ( preg_match( $regex, $text, $m ) ) {
625 return $this->parseMatch( $m );
629 return array( false, false );
633 * Match some text, without parameter capture
634 * Returns the magic word name, or false if there was no capture
636 public function matchStartToEnd( $text ) {
637 $hash = $this->getHash();
638 if ( isset( $hash[1][$text] ) ) {
639 return $hash[1][$text];
642 $lc = $wgContLang->lc( $text );
643 if ( isset( $hash[0][$lc] ) ) {
644 return $hash[0][$lc];
650 * Returns an associative array, ID => param value, for all items that match
651 * Removes the matched items from the input string (passed by reference)
653 public function matchAndRemove( &$text ) {
655 $regexes = $this->getRegex();
656 foreach ( $regexes as $regex ) {
657 if ( $regex === '' ) {
660 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
661 foreach ( $matches as $m ) {
662 list( $name, $param ) = $this->parseMatch( $m );
663 $found[$name] = $param;
665 $text = preg_replace( $regex, '', $text );