4 * See docs/magicword.txt
10 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
12 * if (MagicWord::get( 'redirect' )->match( $text ) )
14 * Possible future improvements:
15 * * Simultaneous searching for a number of magic words
16 * * MagicWord::$mObjects in shared memory
18 * Please avoid reading the data out of one of these objects and then writing
19 * special case code. If possible, add another match()-like function here.
21 * To add magic words in an extension, use the LanguageGetMagic hook. For
22 * magic words which are also Parser variables, add a MagicWordwgVariableIDs
23 * hook. Use string keys.
30 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
31 var $mRegexStart, $mBaseRegex, $mVariableRegex;
32 var $mModified, $mFound;
34 static public $mVariableIDsInitialised = false;
35 static public $mVariableIDs = array(
38 'currentmonthnamegen',
107 /* Array of caching hints for ParserCache */
108 static public $mCacheTTLs = array (
109 'currentmonth' => 86400,
110 'currentmonthname' => 86400,
111 'currentmonthnamegen' => 86400,
112 'currentmonthabbrev' => 86400,
113 'currentday' => 3600,
114 'currentday2' => 3600,
115 'currentdayname' => 3600,
116 'currentyear' => 86400,
117 'currenttime' => 3600,
118 'currenthour' => 3600,
119 'localmonth' => 86400,
120 'localmonthname' => 86400,
121 'localmonthnamegen' => 86400,
122 'localmonthabbrev' => 86400,
125 'localdayname' => 3600,
126 'localyear' => 86400,
129 'numberofarticles' => 3600,
130 'numberoffiles' => 3600,
131 'numberofedits' => 3600,
132 'currentweek' => 3600,
133 'currentdow' => 3600,
136 'numberofusers' => 3600,
137 'numberofpages' => 3600,
138 'currentversion' => 86400,
139 'currenttimestamp' => 3600,
140 'localtimestamp' => 3600,
141 'pagesinnamespace' => 3600,
142 'numberofadmins' => 3600,
145 static public $mDoubleUnderscoreIDs = array(
156 static public $mObjects = array();
157 static public $mDoubleUnderscoreArray = null;
161 function __construct($id = 0, $syn = '', $cs = false) {
163 $this->mSynonyms
= (array)$syn;
164 $this->mCaseSensitive
= $cs;
166 $this->mRegexStart
= '';
167 $this->mVariableRegex
= '';
168 $this->mVariableStartToEndRegex
= '';
169 $this->mModified
= false;
173 * Factory: creates an object representing an ID
176 static function &get( $id ) {
177 wfProfileIn( __METHOD__
);
178 if (!array_key_exists( $id, self
::$mObjects ) ) {
179 $mw = new MagicWord();
181 self
::$mObjects[$id] = $mw;
183 wfProfileOut( __METHOD__
);
184 return self
::$mObjects[$id];
188 * Get an array of parser variable IDs
190 static function getVariableIDs() {
191 if ( !self
::$mVariableIDsInitialised ) {
192 # Deprecated constant definition hook, available for extensions that need it
193 $magicWords = array();
194 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
195 foreach ( $magicWords as $word ) {
196 define( $word, $word );
200 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
201 self
::$mVariableIDsInitialised = true;
203 return self
::$mVariableIDs;
206 /* Allow external reads of TTL array */
207 static function getCacheTTL($id) {
208 if (array_key_exists($id,self
::$mCacheTTLs)) {
209 return self
::$mCacheTTLs[$id];
215 /** Get a MagicWordArray of double-underscore entities */
216 static function getDoubleUnderscoreArray() {
217 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
218 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
220 return self
::$mDoubleUnderscoreArray;
223 # Initialises this object with an ID
224 function load( $id ) {
227 $wgContLang->getMagic( $this );
228 if ( !$this->mSynonyms
) {
229 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
230 #throw new MWException( "Error: invalid magic word '$id'" );
231 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
236 * Preliminary initialisation
239 function initRegex() {
240 #$variableClass = Title::legalChars();
241 # This was used for matching "$1" variables, but different uses of the feature will have
242 # different restrictions, which should be checked *after* the MagicWord has been matched,
246 foreach ( $this->mSynonyms
as $synonym )
247 // In case a magic word contains /, like that's going to happen;)
248 $escSyn[] = preg_quote( $synonym, '/' );
249 $this->mBaseRegex
= implode( '|', $escSyn );
251 $case = $this->mCaseSensitive ?
'' : 'iu';
252 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
253 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
254 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
255 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
256 "/^(?:{$this->mBaseRegex})$/{$case}" );
260 * Gets a regex representing matching the word
262 function getRegex() {
263 if ($this->mRegex
== '' ) {
266 return $this->mRegex
;
270 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
271 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
272 * the complete expression
274 function getRegexCase() {
275 if ( $this->mRegex
=== '' )
278 return $this->mCaseSensitive ?
'' : 'iu';
282 * Gets a regex matching the word, if it is at the string start
284 function getRegexStart() {
285 if ($this->mRegex
== '' ) {
288 return $this->mRegexStart
;
292 * regex without the slashes and what not
294 function getBaseRegex() {
295 if ($this->mRegex
== '') {
298 return $this->mBaseRegex
;
302 * Returns true if the text contains the word
305 function match( $text ) {
306 return preg_match( $this->getRegex(), $text );
310 * Returns true if the text starts with the word
313 function matchStart( $text ) {
314 return preg_match( $this->getRegexStart(), $text );
318 * Returns NULL if there's no match, the value of $1 otherwise
319 * The return code is the matched string, if there's no variable
320 * part in the regex and the matched variable part ($1) if there
323 function matchVariableStartToEnd( $text ) {
325 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
326 if ( $matchcount == 0 ) {
329 # multiple matched parts (variable match); some will be empty because of
330 # synonyms. The variable will be the second non-empty one so remove any
331 # blank elements and re-sort the indices.
334 $matches = array_values(array_filter($matches));
336 if ( count($matches) == 1 ) { return $matches[0]; }
337 else { return $matches[1]; }
343 * Returns true if the text matches the word, and alters the
344 * input string, removing all instances of the word
346 function matchAndRemove( &$text ) {
347 $this->mFound
= false;
348 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
349 return $this->mFound
;
352 function matchStartAndRemove( &$text ) {
353 $this->mFound
= false;
354 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
355 return $this->mFound
;
359 * Used in matchAndRemove()
362 function pregRemoveAndRecord( ) {
363 $this->mFound
= true;
368 * Replaces the word with something else
370 function replace( $replacement, $subject, $limit=-1 ) {
371 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
372 $this->mModified
= !($res === $subject);
377 * Variable handling: {{SUBST:xxx}} style words
378 * Calls back a function to determine what to replace xxx with
379 * Input word must contain $1
381 function substituteCallback( $text, $callback ) {
382 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
383 $this->mModified
= !($res === $text);
388 * Matches the word, where $1 is a wildcard
390 function getVariableRegex() {
391 if ( $this->mVariableRegex
== '' ) {
394 return $this->mVariableRegex
;
398 * Matches the entire string, where $1 is a wildcard
400 function getVariableStartToEndRegex() {
401 if ( $this->mVariableStartToEndRegex
== '' ) {
404 return $this->mVariableStartToEndRegex
;
408 * Accesses the synonym list directly
410 function getSynonym( $i ) {
411 return $this->mSynonyms
[$i];
414 function getSynonyms() {
415 return $this->mSynonyms
;
419 * Returns true if the last call to replace() or substituteCallback()
420 * returned a modified text, otherwise false.
422 function getWasModified(){
423 return $this->mModified
;
427 * $magicarr is an associative array of (magic word ID => replacement)
428 * This method uses the php feature to do several replacements at the same time,
429 * thereby gaining some efficiency. The result is placed in the out variable
430 * $result. The return value is true if something was replaced.
433 function replaceMultiple( $magicarr, $subject, &$result ){
436 foreach( $magicarr as $id => $replacement ){
437 $mw = MagicWord
::get( $id );
438 $search[] = $mw->getRegex();
439 $replace[] = $replacement;
442 $result = preg_replace( $search, $replace, $subject );
443 return !($result === $subject);
447 * Adds all the synonyms of this MagicWord to an array, to allow quick
448 * lookup in a list of magic words
450 function addToArray( &$array, $value ) {
452 foreach ( $this->mSynonyms
as $syn ) {
453 $array[$wgContLang->lc($syn)] = $value;
457 function isCaseSensitive() {
458 return $this->mCaseSensitive
;
467 * Class for handling an array of magic words
469 class MagicWordArray
{
470 var $names = array();
472 var $baseRegex, $regex;
475 function __construct( $names = array() ) {
476 $this->names
= $names;
480 * Add a magic word by name
482 public function add( $name ) {
484 $this->names
[] = $name;
485 $this->hash
= $this->baseRegex
= $this->regex
= null;
489 * Add a number of magic words by name
491 public function addArray( $names ) {
492 $this->names
= array_merge( $this->names
, array_values( $names ) );
493 $this->hash
= $this->baseRegex
= $this->regex
= null;
497 * Get a 2-d hashtable for this array
500 if ( is_null( $this->hash
) ) {
502 $this->hash
= array( 0 => array(), 1 => array() );
503 foreach ( $this->names
as $name ) {
504 $magic = MagicWord
::get( $name );
505 $case = intval( $magic->isCaseSensitive() );
506 foreach ( $magic->getSynonyms() as $syn ) {
508 $syn = $wgContLang->lc( $syn );
510 $this->hash
[$case][$syn] = $name;
520 function getBaseRegex() {
521 if ( is_null( $this->baseRegex
) ) {
522 $this->baseRegex
= array( 0 => '', 1 => '' );
523 foreach ( $this->names
as $name ) {
524 $magic = MagicWord
::get( $name );
525 $case = intval( $magic->isCaseSensitive() );
526 foreach ( $magic->getSynonyms() as $i => $syn ) {
527 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
528 if ( $this->baseRegex
[$case] === '' ) {
529 $this->baseRegex
[$case] = $group;
531 $this->baseRegex
[$case] .= '|' . $group;
536 return $this->baseRegex
;
540 * Get an unanchored regex
542 function getRegex() {
543 if ( is_null( $this->regex
) ) {
544 $base = $this->getBaseRegex();
545 $this->regex
= array( '', '' );
546 if ( $this->baseRegex
[0] !== '' ) {
547 $this->regex
[0] = "/{$base[0]}/iuS";
549 if ( $this->baseRegex
[1] !== '' ) {
550 $this->regex
[1] = "/{$base[1]}/S";
557 * Get a regex for matching variables
559 function getVariableRegex() {
560 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
564 * Get an anchored regex for matching variables
566 function getVariableStartToEndRegex() {
567 $base = $this->getBaseRegex();
568 $newRegex = array( '', '' );
569 if ( $base[0] !== '' ) {
570 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
572 if ( $base[1] !== '' ) {
573 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
579 * Parse a match array from preg_match
580 * Returns array(magic word ID, parameter value)
581 * If there is no parameter value, that element will be false.
583 function parseMatch( $m ) {
585 while ( list( $key, $value ) = each( $m ) ) {
586 if ( $key === 0 ||
$value === '' ) {
589 $parts = explode( '_', $key, 2 );
590 if ( count( $parts ) != 2 ) {
591 // This shouldn't happen
593 throw new MWException( __METHOD__
. ': bad parameter name' );
595 list( /* $synIndex */, $magicName ) = $parts;
596 $paramValue = next( $m );
597 return array( $magicName, $paramValue );
599 // This shouldn't happen either
600 throw new MWException( __METHOD__
.': parameter not found' );
601 return array( false, false );
605 * Match some text, with parameter capture
606 * Returns an array with the magic word name in the first element and the
607 * parameter in the second element.
608 * Both elements are false if there was no match.
610 public function matchVariableStartToEnd( $text ) {
612 $regexes = $this->getVariableStartToEndRegex();
613 foreach ( $regexes as $regex ) {
614 if ( $regex !== '' ) {
616 if ( preg_match( $regex, $text, $m ) ) {
617 return $this->parseMatch( $m );
621 return array( false, false );
625 * Match some text, without parameter capture
626 * Returns the magic word name, or false if there was no capture
628 public function matchStartToEnd( $text ) {
629 $hash = $this->getHash();
630 if ( isset( $hash[1][$text] ) ) {
631 return $hash[1][$text];
634 $lc = $wgContLang->lc( $text );
635 if ( isset( $hash[0][$lc] ) ) {
636 return $hash[0][$lc];
642 * Returns an associative array, ID => param value, for all items that match
643 * Removes the matched items from the input string (passed by reference)
645 public function matchAndRemove( &$text ) {
647 $regexes = $this->getRegex();
648 foreach ( $regexes as $regex ) {
649 if ( $regex === '' ) {
652 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
653 foreach ( $matches as $m ) {
654 list( $name, $param ) = $this->parseMatch( $m );
655 $found[$name] = $param;
657 $text = preg_replace( $regex, '', $text );