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',
93 'numberofactiveusers',
106 /* Array of caching hints for ParserCache */
107 static public $mCacheTTLs = array (
108 'currentmonth' => 86400,
109 'currentmonthname' => 86400,
110 'currentmonthnamegen' => 86400,
111 'currentmonthabbrev' => 86400,
112 'currentday' => 3600,
113 'currentday2' => 3600,
114 'currentdayname' => 3600,
115 'currentyear' => 86400,
116 'currenttime' => 3600,
117 'currenthour' => 3600,
118 'localmonth' => 86400,
119 'localmonthname' => 86400,
120 'localmonthnamegen' => 86400,
121 'localmonthabbrev' => 86400,
124 'localdayname' => 3600,
125 'localyear' => 86400,
128 'numberofarticles' => 3600,
129 'numberoffiles' => 3600,
130 'numberofedits' => 3600,
131 'currentweek' => 3600,
132 'currentdow' => 3600,
135 'numberofusers' => 3600,
136 'numberofactiveusers' => 3600,
137 'numberofpages' => 3600,
138 'currentversion' => 86400,
139 'currenttimestamp' => 3600,
140 'localtimestamp' => 3600,
141 'pagesinnamespace' => 3600,
142 'numberofadmins' => 3600,
143 'numberofviews' => 3600,
144 'numberingroup' => 3600,
147 static public $mDoubleUnderscoreIDs = array(
162 static public $mObjects = array();
163 static public $mDoubleUnderscoreArray = null;
167 function __construct($id = 0, $syn = '', $cs = false) {
169 $this->mSynonyms
= (array)$syn;
170 $this->mCaseSensitive
= $cs;
172 $this->mRegexStart
= '';
173 $this->mVariableRegex
= '';
174 $this->mVariableStartToEndRegex
= '';
175 $this->mModified
= false;
179 * Factory: creates an object representing an ID
182 static function &get( $id ) {
183 wfProfileIn( __METHOD__
);
184 if (!array_key_exists( $id, self
::$mObjects ) ) {
185 $mw = new MagicWord();
187 self
::$mObjects[$id] = $mw;
189 wfProfileOut( __METHOD__
);
190 return self
::$mObjects[$id];
194 * Get an array of parser variable IDs
196 static function getVariableIDs() {
197 if ( !self
::$mVariableIDsInitialised ) {
198 # Deprecated constant definition hook, available for extensions that need it
199 $magicWords = array();
200 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
201 foreach ( $magicWords as $word ) {
202 define( $word, $word );
206 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
207 self
::$mVariableIDsInitialised = true;
209 return self
::$mVariableIDs;
212 /* Allow external reads of TTL array */
213 static function getCacheTTL($id) {
214 if (array_key_exists($id,self
::$mCacheTTLs)) {
215 return self
::$mCacheTTLs[$id];
221 /** Get a MagicWordArray of double-underscore entities */
222 static function getDoubleUnderscoreArray() {
223 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
224 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
226 return self
::$mDoubleUnderscoreArray;
229 # Initialises this object with an ID
230 function load( $id ) {
233 $wgContLang->getMagic( $this );
234 if ( !$this->mSynonyms
) {
235 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
236 #throw new MWException( "Error: invalid magic word '$id'" );
237 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
242 * Preliminary initialisation
245 function initRegex() {
246 #$variableClass = Title::legalChars();
247 # This was used for matching "$1" variables, but different uses of the feature will have
248 # different restrictions, which should be checked *after* the MagicWord has been matched,
252 foreach ( $this->mSynonyms
as $synonym )
253 // In case a magic word contains /, like that's going to happen;)
254 $escSyn[] = preg_quote( $synonym, '/' );
255 $this->mBaseRegex
= implode( '|', $escSyn );
257 $case = $this->mCaseSensitive ?
'' : 'iu';
258 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
259 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
260 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
261 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
262 "/^(?:{$this->mBaseRegex})$/{$case}" );
266 * Gets a regex representing matching the word
268 function getRegex() {
269 if ($this->mRegex
== '' ) {
272 return $this->mRegex
;
276 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
277 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
278 * the complete expression
280 function getRegexCase() {
281 if ( $this->mRegex
=== '' )
284 return $this->mCaseSensitive ?
'' : 'iu';
288 * Gets a regex matching the word, if it is at the string start
290 function getRegexStart() {
291 if ($this->mRegex
== '' ) {
294 return $this->mRegexStart
;
298 * regex without the slashes and what not
300 function getBaseRegex() {
301 if ($this->mRegex
== '') {
304 return $this->mBaseRegex
;
308 * Returns true if the text contains the word
311 function match( $text ) {
312 return preg_match( $this->getRegex(), $text );
316 * Returns true if the text starts with the word
319 function matchStart( $text ) {
320 return preg_match( $this->getRegexStart(), $text );
324 * Returns NULL if there's no match, the value of $1 otherwise
325 * The return code is the matched string, if there's no variable
326 * part in the regex and the matched variable part ($1) if there
329 function matchVariableStartToEnd( $text ) {
331 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
332 if ( $matchcount == 0 ) {
335 # multiple matched parts (variable match); some will be empty because of
336 # synonyms. The variable will be the second non-empty one so remove any
337 # blank elements and re-sort the indices.
340 $matches = array_values(array_filter($matches));
342 if ( count($matches) == 1 ) { return $matches[0]; }
343 else { return $matches[1]; }
349 * Returns true if the text matches the word, and alters the
350 * input string, removing all instances of the word
352 function matchAndRemove( &$text ) {
353 $this->mFound
= false;
354 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
355 return $this->mFound
;
358 function matchStartAndRemove( &$text ) {
359 $this->mFound
= false;
360 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
361 return $this->mFound
;
365 * Used in matchAndRemove()
368 function pregRemoveAndRecord( ) {
369 $this->mFound
= true;
374 * Replaces the word with something else
376 function replace( $replacement, $subject, $limit=-1 ) {
377 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
378 $this->mModified
= !($res === $subject);
383 * Variable handling: {{SUBST:xxx}} style words
384 * Calls back a function to determine what to replace xxx with
385 * Input word must contain $1
387 function substituteCallback( $text, $callback ) {
388 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
389 $this->mModified
= !($res === $text);
394 * Matches the word, where $1 is a wildcard
396 function getVariableRegex() {
397 if ( $this->mVariableRegex
== '' ) {
400 return $this->mVariableRegex
;
404 * Matches the entire string, where $1 is a wildcard
406 function getVariableStartToEndRegex() {
407 if ( $this->mVariableStartToEndRegex
== '' ) {
410 return $this->mVariableStartToEndRegex
;
414 * Accesses the synonym list directly
416 function getSynonym( $i ) {
417 return $this->mSynonyms
[$i];
420 function getSynonyms() {
421 return $this->mSynonyms
;
425 * Returns true if the last call to replace() or substituteCallback()
426 * returned a modified text, otherwise false.
428 function getWasModified(){
429 return $this->mModified
;
433 * $magicarr is an associative array of (magic word ID => replacement)
434 * This method uses the php feature to do several replacements at the same time,
435 * thereby gaining some efficiency. The result is placed in the out variable
436 * $result. The return value is true if something was replaced.
439 function replaceMultiple( $magicarr, $subject, &$result ){
442 foreach( $magicarr as $id => $replacement ){
443 $mw = MagicWord
::get( $id );
444 $search[] = $mw->getRegex();
445 $replace[] = $replacement;
448 $result = preg_replace( $search, $replace, $subject );
449 return !($result === $subject);
453 * Adds all the synonyms of this MagicWord to an array, to allow quick
454 * lookup in a list of magic words
456 function addToArray( &$array, $value ) {
458 foreach ( $this->mSynonyms
as $syn ) {
459 $array[$wgContLang->lc($syn)] = $value;
463 function isCaseSensitive() {
464 return $this->mCaseSensitive
;
473 * Class for handling an array of magic words
476 class MagicWordArray
{
477 var $names = array();
479 var $baseRegex, $regex;
482 function __construct( $names = array() ) {
483 $this->names
= $names;
487 * Add a magic word by name
489 public function add( $name ) {
491 $this->names
[] = $name;
492 $this->hash
= $this->baseRegex
= $this->regex
= null;
496 * Add a number of magic words by name
498 public function addArray( $names ) {
499 $this->names
= array_merge( $this->names
, array_values( $names ) );
500 $this->hash
= $this->baseRegex
= $this->regex
= null;
504 * Get a 2-d hashtable for this array
507 if ( is_null( $this->hash
) ) {
509 $this->hash
= array( 0 => array(), 1 => array() );
510 foreach ( $this->names
as $name ) {
511 $magic = MagicWord
::get( $name );
512 $case = intval( $magic->isCaseSensitive() );
513 foreach ( $magic->getSynonyms() as $syn ) {
515 $syn = $wgContLang->lc( $syn );
517 $this->hash
[$case][$syn] = $name;
527 function getBaseRegex() {
528 if ( is_null( $this->baseRegex
) ) {
529 $this->baseRegex
= array( 0 => '', 1 => '' );
530 foreach ( $this->names
as $name ) {
531 $magic = MagicWord
::get( $name );
532 $case = intval( $magic->isCaseSensitive() );
533 foreach ( $magic->getSynonyms() as $i => $syn ) {
534 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
535 if ( $this->baseRegex
[$case] === '' ) {
536 $this->baseRegex
[$case] = $group;
538 $this->baseRegex
[$case] .= '|' . $group;
543 return $this->baseRegex
;
547 * Get an unanchored regex
549 function getRegex() {
550 if ( is_null( $this->regex
) ) {
551 $base = $this->getBaseRegex();
552 $this->regex
= array( '', '' );
553 if ( $this->baseRegex
[0] !== '' ) {
554 $this->regex
[0] = "/{$base[0]}/iuS";
556 if ( $this->baseRegex
[1] !== '' ) {
557 $this->regex
[1] = "/{$base[1]}/S";
564 * Get a regex for matching variables
566 function getVariableRegex() {
567 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
571 * Get an anchored regex for matching variables
573 function getVariableStartToEndRegex() {
574 $base = $this->getBaseRegex();
575 $newRegex = array( '', '' );
576 if ( $base[0] !== '' ) {
577 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
579 if ( $base[1] !== '' ) {
580 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
586 * Parse a match array from preg_match
587 * Returns array(magic word ID, parameter value)
588 * If there is no parameter value, that element will be false.
590 function parseMatch( $m ) {
592 while ( list( $key, $value ) = each( $m ) ) {
593 if ( $key === 0 ||
$value === '' ) {
596 $parts = explode( '_', $key, 2 );
597 if ( count( $parts ) != 2 ) {
598 // This shouldn't happen
600 throw new MWException( __METHOD__
. ': bad parameter name' );
602 list( /* $synIndex */, $magicName ) = $parts;
603 $paramValue = next( $m );
604 return array( $magicName, $paramValue );
606 // This shouldn't happen either
607 throw new MWException( __METHOD__
.': parameter not found' );
608 return array( false, false );
612 * Match some text, with parameter capture
613 * Returns an array with the magic word name in the first element and the
614 * parameter in the second element.
615 * Both elements are false if there was no match.
617 public function matchVariableStartToEnd( $text ) {
619 $regexes = $this->getVariableStartToEndRegex();
620 foreach ( $regexes as $regex ) {
621 if ( $regex !== '' ) {
623 if ( preg_match( $regex, $text, $m ) ) {
624 return $this->parseMatch( $m );
628 return array( false, false );
632 * Match some text, without parameter capture
633 * Returns the magic word name, or false if there was no capture
635 public function matchStartToEnd( $text ) {
636 $hash = $this->getHash();
637 if ( isset( $hash[1][$text] ) ) {
638 return $hash[1][$text];
641 $lc = $wgContLang->lc( $text );
642 if ( isset( $hash[0][$lc] ) ) {
643 return $hash[0][$lc];
649 * Returns an associative array, ID => param value, for all items that match
650 * Removes the matched items from the input string (passed by reference)
652 public function matchAndRemove( &$text ) {
654 $regexes = $this->getRegex();
655 foreach ( $regexes as $regex ) {
656 if ( $regex === '' ) {
659 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
660 foreach ( $matches as $m ) {
661 list( $name, $param ) = $this->parseMatch( $m );
662 $found[$name] = $param;
664 $text = preg_replace( $regex, '', $text );