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',
113 /* Array of caching hints for ParserCache */
114 static public $mCacheTTLs = array (
115 'currentmonth' => 86400,
116 'currentmonthname' => 86400,
117 'currentmonthnamegen' => 86400,
118 'currentmonthabbrev' => 86400,
119 'currentday' => 3600,
120 'currentday2' => 3600,
121 'currentdayname' => 3600,
122 'currentyear' => 86400,
123 'currenttime' => 3600,
124 'currenthour' => 3600,
125 'localmonth' => 86400,
126 'localmonthname' => 86400,
127 'localmonthnamegen' => 86400,
128 'localmonthabbrev' => 86400,
131 'localdayname' => 3600,
132 'localyear' => 86400,
135 'numberofarticles' => 3600,
136 'numberoffiles' => 3600,
137 'numberofedits' => 3600,
138 'currentweek' => 3600,
139 'currentdow' => 3600,
142 'numberofusers' => 3600,
143 'numberofpages' => 3600,
144 'currentversion' => 86400,
145 'currenttimestamp' => 3600,
146 'localtimestamp' => 3600,
147 'pagesinnamespace' => 3600,
148 'numberofadmins' => 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 (!array_key_exists( $id, self
::$mObjects ) ) {
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;
234 # Initialises this object with an ID
235 function load( $id ) {
238 $wgContLang->getMagic( $this );
239 if ( !$this->mSynonyms
) {
240 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
241 #throw new MWException( "Error: invalid magic word '$id'" );
242 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
247 * Preliminary initialisation
250 function initRegex() {
251 #$variableClass = Title::legalChars();
252 # This was used for matching "$1" variables, but different uses of the feature will have
253 # different restrictions, which should be checked *after* the MagicWord has been matched,
257 foreach ( $this->mSynonyms
as $synonym )
258 // In case a magic word contains /, like that's going to happen;)
259 $escSyn[] = preg_quote( $synonym, '/' );
260 $this->mBaseRegex
= implode( '|', $escSyn );
262 $case = $this->mCaseSensitive ?
'' : 'iu';
263 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
264 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
265 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
266 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
267 "/^(?:{$this->mBaseRegex})$/{$case}" );
271 * Gets a regex representing matching the word
273 function getRegex() {
274 if ($this->mRegex
== '' ) {
277 return $this->mRegex
;
281 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
282 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
283 * the complete expression
285 function getRegexCase() {
286 if ( $this->mRegex
=== '' )
289 return $this->mCaseSensitive ?
'' : 'iu';
293 * Gets a regex matching the word, if it is at the string start
295 function getRegexStart() {
296 if ($this->mRegex
== '' ) {
299 return $this->mRegexStart
;
303 * regex without the slashes and what not
305 function getBaseRegex() {
306 if ($this->mRegex
== '') {
309 return $this->mBaseRegex
;
313 * Returns true if the text contains the word
316 function match( $text ) {
317 return preg_match( $this->getRegex(), $text );
321 * Returns true if the text starts with the word
324 function matchStart( $text ) {
325 return preg_match( $this->getRegexStart(), $text );
329 * Returns NULL if there's no match, the value of $1 otherwise
330 * The return code is the matched string, if there's no variable
331 * part in the regex and the matched variable part ($1) if there
334 function matchVariableStartToEnd( $text ) {
336 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
337 if ( $matchcount == 0 ) {
340 # multiple matched parts (variable match); some will be empty because of
341 # synonyms. The variable will be the second non-empty one so remove any
342 # blank elements and re-sort the indices.
345 $matches = array_values(array_filter($matches));
347 if ( count($matches) == 1 ) { return $matches[0]; }
348 else { return $matches[1]; }
354 * Returns true if the text matches the word, and alters the
355 * input string, removing all instances of the word
357 function matchAndRemove( &$text ) {
358 $this->mFound
= false;
359 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
360 return $this->mFound
;
363 function matchStartAndRemove( &$text ) {
364 $this->mFound
= false;
365 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
366 return $this->mFound
;
370 * Used in matchAndRemove()
373 function pregRemoveAndRecord( ) {
374 $this->mFound
= true;
379 * Replaces the word with something else
381 function replace( $replacement, $subject, $limit=-1 ) {
382 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
383 $this->mModified
= !($res === $subject);
388 * Variable handling: {{SUBST:xxx}} style words
389 * Calls back a function to determine what to replace xxx with
390 * Input word must contain $1
392 function substituteCallback( $text, $callback ) {
393 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
394 $this->mModified
= !($res === $text);
399 * Matches the word, where $1 is a wildcard
401 function getVariableRegex() {
402 if ( $this->mVariableRegex
== '' ) {
405 return $this->mVariableRegex
;
409 * Matches the entire string, where $1 is a wildcard
411 function getVariableStartToEndRegex() {
412 if ( $this->mVariableStartToEndRegex
== '' ) {
415 return $this->mVariableStartToEndRegex
;
419 * Accesses the synonym list directly
421 function getSynonym( $i ) {
422 return $this->mSynonyms
[$i];
425 function getSynonyms() {
426 return $this->mSynonyms
;
430 * Returns true if the last call to replace() or substituteCallback()
431 * returned a modified text, otherwise false.
433 function getWasModified(){
434 return $this->mModified
;
438 * $magicarr is an associative array of (magic word ID => replacement)
439 * This method uses the php feature to do several replacements at the same time,
440 * thereby gaining some efficiency. The result is placed in the out variable
441 * $result. The return value is true if something was replaced.
444 function replaceMultiple( $magicarr, $subject, &$result ){
447 foreach( $magicarr as $id => $replacement ){
448 $mw = MagicWord
::get( $id );
449 $search[] = $mw->getRegex();
450 $replace[] = $replacement;
453 $result = preg_replace( $search, $replace, $subject );
454 return !($result === $subject);
458 * Adds all the synonyms of this MagicWord to an array, to allow quick
459 * lookup in a list of magic words
461 function addToArray( &$array, $value ) {
463 foreach ( $this->mSynonyms
as $syn ) {
464 $array[$wgContLang->lc($syn)] = $value;
468 function isCaseSensitive() {
469 return $this->mCaseSensitive
;
478 * Class for handling an array of magic words
481 class MagicWordArray
{
482 var $names = array();
484 var $baseRegex, $regex;
487 function __construct( $names = array() ) {
488 $this->names
= $names;
492 * Add a magic word by name
494 public function add( $name ) {
496 $this->names
[] = $name;
497 $this->hash
= $this->baseRegex
= $this->regex
= null;
501 * Add a number of magic words by name
503 public function addArray( $names ) {
504 $this->names
= array_merge( $this->names
, array_values( $names ) );
505 $this->hash
= $this->baseRegex
= $this->regex
= null;
509 * Get a 2-d hashtable for this array
512 if ( is_null( $this->hash
) ) {
514 $this->hash
= array( 0 => array(), 1 => array() );
515 foreach ( $this->names
as $name ) {
516 $magic = MagicWord
::get( $name );
517 $case = intval( $magic->isCaseSensitive() );
518 foreach ( $magic->getSynonyms() as $syn ) {
520 $syn = $wgContLang->lc( $syn );
522 $this->hash
[$case][$syn] = $name;
532 function getBaseRegex() {
533 if ( is_null( $this->baseRegex
) ) {
534 $this->baseRegex
= array( 0 => '', 1 => '' );
535 foreach ( $this->names
as $name ) {
536 $magic = MagicWord
::get( $name );
537 $case = intval( $magic->isCaseSensitive() );
538 foreach ( $magic->getSynonyms() as $i => $syn ) {
539 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
540 if ( $this->baseRegex
[$case] === '' ) {
541 $this->baseRegex
[$case] = $group;
543 $this->baseRegex
[$case] .= '|' . $group;
548 return $this->baseRegex
;
552 * Get an unanchored regex
554 function getRegex() {
555 if ( is_null( $this->regex
) ) {
556 $base = $this->getBaseRegex();
557 $this->regex
= array( '', '' );
558 if ( $this->baseRegex
[0] !== '' ) {
559 $this->regex
[0] = "/{$base[0]}/iuS";
561 if ( $this->baseRegex
[1] !== '' ) {
562 $this->regex
[1] = "/{$base[1]}/S";
569 * Get a regex for matching variables
571 function getVariableRegex() {
572 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
576 * Get an anchored regex for matching variables
578 function getVariableStartToEndRegex() {
579 $base = $this->getBaseRegex();
580 $newRegex = array( '', '' );
581 if ( $base[0] !== '' ) {
582 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
584 if ( $base[1] !== '' ) {
585 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
591 * Parse a match array from preg_match
592 * Returns array(magic word ID, parameter value)
593 * If there is no parameter value, that element will be false.
595 function parseMatch( $m ) {
597 while ( list( $key, $value ) = each( $m ) ) {
598 if ( $key === 0 ||
$value === '' ) {
601 $parts = explode( '_', $key, 2 );
602 if ( count( $parts ) != 2 ) {
603 // This shouldn't happen
605 throw new MWException( __METHOD__
. ': bad parameter name' );
607 list( /* $synIndex */, $magicName ) = $parts;
608 $paramValue = next( $m );
609 return array( $magicName, $paramValue );
611 // This shouldn't happen either
612 throw new MWException( __METHOD__
.': parameter not found' );
613 return array( false, false );
617 * Match some text, with parameter capture
618 * Returns an array with the magic word name in the first element and the
619 * parameter in the second element.
620 * Both elements are false if there was no match.
622 public function matchVariableStartToEnd( $text ) {
624 $regexes = $this->getVariableStartToEndRegex();
625 foreach ( $regexes as $regex ) {
626 if ( $regex !== '' ) {
628 if ( preg_match( $regex, $text, $m ) ) {
629 return $this->parseMatch( $m );
633 return array( false, false );
637 * Match some text, without parameter capture
638 * Returns the magic word name, or false if there was no capture
640 public function matchStartToEnd( $text ) {
641 $hash = $this->getHash();
642 if ( isset( $hash[1][$text] ) ) {
643 return $hash[1][$text];
646 $lc = $wgContLang->lc( $text );
647 if ( isset( $hash[0][$lc] ) ) {
648 return $hash[0][$lc];
654 * Returns an associative array, ID => param value, for all items that match
655 * Removes the matched items from the input string (passed by reference)
657 public function matchAndRemove( &$text ) {
659 $regexes = $this->getRegex();
660 foreach ( $regexes as $regex ) {
661 if ( $regex === '' ) {
664 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
665 foreach ( $matches as $m ) {
666 list( $name, $param ) = $this->parseMatch( $m );
667 $found[$name] = $param;
669 $text = preg_replace( $regex, '', $text );