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(
167 static public $mObjects = array();
168 static public $mDoubleUnderscoreArray = null;
172 function __construct($id = 0, $syn = '', $cs = false) {
174 $this->mSynonyms
= (array)$syn;
175 $this->mCaseSensitive
= $cs;
177 $this->mRegexStart
= '';
178 $this->mVariableRegex
= '';
179 $this->mVariableStartToEndRegex
= '';
180 $this->mModified
= false;
184 * Factory: creates an object representing an ID
187 static function &get( $id ) {
188 wfProfileIn( __METHOD__
);
189 if ( !isset( self
::$mObjects[$id] ) ) {
190 $mw = new MagicWord();
192 self
::$mObjects[$id] = $mw;
194 wfProfileOut( __METHOD__
);
195 return self
::$mObjects[$id];
199 * Get an array of parser variable IDs
201 static function getVariableIDs() {
202 if ( !self
::$mVariableIDsInitialised ) {
203 # Deprecated constant definition hook, available for extensions that need it
204 $magicWords = array();
205 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
206 foreach ( $magicWords as $word ) {
207 define( $word, $word );
211 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
212 self
::$mVariableIDsInitialised = true;
214 return self
::$mVariableIDs;
217 /* Allow external reads of TTL array */
218 static function getCacheTTL($id) {
219 if (array_key_exists($id,self
::$mCacheTTLs)) {
220 return self
::$mCacheTTLs[$id];
226 /** Get a MagicWordArray of double-underscore entities */
227 static function getDoubleUnderscoreArray() {
228 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
229 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
231 return self
::$mDoubleUnderscoreArray;
235 * Clear the self::$mObjects variable
236 * For use in parser tests
238 public static function clearCache() {
239 self
::$mObjects = array();
242 # Initialises this object with an ID
243 function load( $id ) {
246 $wgContLang->getMagic( $this );
247 if ( !$this->mSynonyms
) {
248 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
249 #throw new MWException( "Error: invalid magic word '$id'" );
250 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
255 * Preliminary initialisation
258 function initRegex() {
259 #$variableClass = Title::legalChars();
260 # This was used for matching "$1" variables, but different uses of the feature will have
261 # different restrictions, which should be checked *after* the MagicWord has been matched,
265 foreach ( $this->mSynonyms
as $synonym )
266 // In case a magic word contains /, like that's going to happen;)
267 $escSyn[] = preg_quote( $synonym, '/' );
268 $this->mBaseRegex
= implode( '|', $escSyn );
270 $case = $this->mCaseSensitive ?
'' : 'iu';
271 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
272 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
273 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
274 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
275 "/^(?:{$this->mBaseRegex})$/{$case}" );
279 * Gets a regex representing matching the word
281 function getRegex() {
282 if ($this->mRegex
== '' ) {
285 return $this->mRegex
;
289 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
290 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
291 * the complete expression
293 function getRegexCase() {
294 if ( $this->mRegex
=== '' )
297 return $this->mCaseSensitive ?
'' : 'iu';
301 * Gets a regex matching the word, if it is at the string start
303 function getRegexStart() {
304 if ($this->mRegex
== '' ) {
307 return $this->mRegexStart
;
311 * regex without the slashes and what not
313 function getBaseRegex() {
314 if ($this->mRegex
== '') {
317 return $this->mBaseRegex
;
321 * Returns the number of times the text contains the word
324 function match( $text ) {
325 return preg_match( $this->getRegex(), $text );
329 * Returns if the text starts with the word
332 function matchStart( $text ) {
333 return preg_match( $this->getRegexStart(), $text );
337 * Returns NULL if there's no match, the value of $1 otherwise
338 * The return code is the matched string, if there's no variable
339 * part in the regex and the matched variable part ($1) if there
342 function matchVariableStartToEnd( $text ) {
344 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
345 if ( $matchcount == 0 ) {
348 # multiple matched parts (variable match); some will be empty because of
349 # synonyms. The variable will be the second non-empty one so remove any
350 # blank elements and re-sort the indices.
353 $matches = array_values(array_filter($matches));
355 if ( count($matches) == 1 ) { return $matches[0]; }
356 else { return $matches[1]; }
362 * Returns true if the text matches the word, and alters the
363 * input string, removing all instances of the word
365 function matchAndRemove( &$text ) {
366 $this->mFound
= false;
367 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
368 return $this->mFound
;
371 function matchStartAndRemove( &$text ) {
372 $this->mFound
= false;
373 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
374 return $this->mFound
;
378 * Used in matchAndRemove()
381 function pregRemoveAndRecord( ) {
382 $this->mFound
= true;
387 * Replaces the word with something else
389 function replace( $replacement, $subject, $limit=-1 ) {
390 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
391 $this->mModified
= !($res === $subject);
396 * Variable handling: {{SUBST:xxx}} style words
397 * Calls back a function to determine what to replace xxx with
398 * Input word must contain $1
400 function substituteCallback( $text, $callback ) {
401 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
402 $this->mModified
= !($res === $text);
407 * Matches the word, where $1 is a wildcard
409 function getVariableRegex() {
410 if ( $this->mVariableRegex
== '' ) {
413 return $this->mVariableRegex
;
417 * Matches the entire string, where $1 is a wildcard
419 function getVariableStartToEndRegex() {
420 if ( $this->mVariableStartToEndRegex
== '' ) {
423 return $this->mVariableStartToEndRegex
;
427 * Accesses the synonym list directly
429 function getSynonym( $i ) {
430 return $this->mSynonyms
[$i];
433 function getSynonyms() {
434 return $this->mSynonyms
;
438 * Returns true if the last call to replace() or substituteCallback()
439 * returned a modified text, otherwise false.
441 function getWasModified(){
442 return $this->mModified
;
446 * $magicarr is an associative array of (magic word ID => replacement)
447 * This method uses the php feature to do several replacements at the same time,
448 * thereby gaining some efficiency. The result is placed in the out variable
449 * $result. The return value is true if something was replaced.
452 function replaceMultiple( $magicarr, $subject, &$result ){
455 foreach( $magicarr as $id => $replacement ){
456 $mw = MagicWord
::get( $id );
457 $search[] = $mw->getRegex();
458 $replace[] = $replacement;
461 $result = preg_replace( $search, $replace, $subject );
462 return !($result === $subject);
466 * Adds all the synonyms of this MagicWord to an array, to allow quick
467 * lookup in a list of magic words
469 function addToArray( &$array, $value ) {
471 foreach ( $this->mSynonyms
as $syn ) {
472 $array[$wgContLang->lc($syn)] = $value;
476 function isCaseSensitive() {
477 return $this->mCaseSensitive
;
486 * Class for handling an array of magic words
489 class MagicWordArray
{
490 var $names = array();
492 var $baseRegex, $regex;
495 function __construct( $names = array() ) {
496 $this->names
= $names;
500 * Add a magic word by name
502 public function add( $name ) {
504 $this->names
[] = $name;
505 $this->hash
= $this->baseRegex
= $this->regex
= null;
509 * Add a number of magic words by name
511 public function addArray( $names ) {
512 $this->names
= array_merge( $this->names
, array_values( $names ) );
513 $this->hash
= $this->baseRegex
= $this->regex
= null;
517 * Get a 2-d hashtable for this array
520 if ( is_null( $this->hash
) ) {
522 $this->hash
= array( 0 => array(), 1 => array() );
523 foreach ( $this->names
as $name ) {
524 $magic = MagicWord
::get( $name );
525 $case = intval( $magic->isCaseSensitive() );
526 foreach ( $magic->getSynonyms() as $syn ) {
528 $syn = $wgContLang->lc( $syn );
530 $this->hash
[$case][$syn] = $name;
540 function getBaseRegex() {
541 if ( is_null( $this->baseRegex
) ) {
542 $this->baseRegex
= array( 0 => '', 1 => '' );
543 foreach ( $this->names
as $name ) {
544 $magic = MagicWord
::get( $name );
545 $case = intval( $magic->isCaseSensitive() );
546 foreach ( $magic->getSynonyms() as $i => $syn ) {
547 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
548 if ( $this->baseRegex
[$case] === '' ) {
549 $this->baseRegex
[$case] = $group;
551 $this->baseRegex
[$case] .= '|' . $group;
556 return $this->baseRegex
;
560 * Get an unanchored regex
562 function getRegex() {
563 if ( is_null( $this->regex
) ) {
564 $base = $this->getBaseRegex();
565 $this->regex
= array( '', '' );
566 if ( $this->baseRegex
[0] !== '' ) {
567 $this->regex
[0] = "/{$base[0]}/iuS";
569 if ( $this->baseRegex
[1] !== '' ) {
570 $this->regex
[1] = "/{$base[1]}/S";
577 * Get a regex for matching variables
579 function getVariableRegex() {
580 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
584 * Get an anchored regex for matching variables
586 function getVariableStartToEndRegex() {
587 $base = $this->getBaseRegex();
588 $newRegex = array( '', '' );
589 if ( $base[0] !== '' ) {
590 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
592 if ( $base[1] !== '' ) {
593 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
599 * Parse a match array from preg_match
600 * Returns array(magic word ID, parameter value)
601 * If there is no parameter value, that element will be false.
603 function parseMatch( $m ) {
605 while ( list( $key, $value ) = each( $m ) ) {
606 if ( $key === 0 ||
$value === '' ) {
609 $parts = explode( '_', $key, 2 );
610 if ( count( $parts ) != 2 ) {
611 // This shouldn't happen
613 throw new MWException( __METHOD__
. ': bad parameter name' );
615 list( /* $synIndex */, $magicName ) = $parts;
616 $paramValue = next( $m );
617 return array( $magicName, $paramValue );
619 // This shouldn't happen either
620 throw new MWException( __METHOD__
.': parameter not found' );
621 return array( false, false );
625 * Match some text, with parameter capture
626 * Returns an array with the magic word name in the first element and the
627 * parameter in the second element.
628 * Both elements are false if there was no match.
630 public function matchVariableStartToEnd( $text ) {
632 $regexes = $this->getVariableStartToEndRegex();
633 foreach ( $regexes as $regex ) {
634 if ( $regex !== '' ) {
636 if ( preg_match( $regex, $text, $m ) ) {
637 return $this->parseMatch( $m );
641 return array( false, false );
645 * Match some text, without parameter capture
646 * Returns the magic word name, or false if there was no capture
648 public function matchStartToEnd( $text ) {
649 $hash = $this->getHash();
650 if ( isset( $hash[1][$text] ) ) {
651 return $hash[1][$text];
654 $lc = $wgContLang->lc( $text );
655 if ( isset( $hash[0][$lc] ) ) {
656 return $hash[0][$lc];
662 * Returns an associative array, ID => param value, for all items that match
663 * Removes the matched items from the input string (passed by reference)
665 public function matchAndRemove( &$text ) {
667 $regexes = $this->getRegex();
668 foreach ( $regexes as $regex ) {
669 if ( $regex === '' ) {
672 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
673 foreach ( $matches as $m ) {
674 list( $name, $param ) = $this->parseMatch( $m );
675 $found[$name] = $param;
677 $text = preg_replace( $regex, '', $text );