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(
166 static public $mObjects = array();
167 static public $mDoubleUnderscoreArray = null;
171 function __construct($id = 0, $syn = '', $cs = false) {
173 $this->mSynonyms
= (array)$syn;
174 $this->mCaseSensitive
= $cs;
176 $this->mRegexStart
= '';
177 $this->mVariableRegex
= '';
178 $this->mVariableStartToEndRegex
= '';
179 $this->mModified
= false;
183 * Factory: creates an object representing an ID
186 static function &get( $id ) {
187 wfProfileIn( __METHOD__
);
188 if (!array_key_exists( $id, self
::$mObjects ) ) {
189 $mw = new MagicWord();
191 self
::$mObjects[$id] = $mw;
193 wfProfileOut( __METHOD__
);
194 return self
::$mObjects[$id];
198 * Get an array of parser variable IDs
200 static function getVariableIDs() {
201 if ( !self
::$mVariableIDsInitialised ) {
202 # Deprecated constant definition hook, available for extensions that need it
203 $magicWords = array();
204 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
205 foreach ( $magicWords as $word ) {
206 define( $word, $word );
210 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
211 self
::$mVariableIDsInitialised = true;
213 return self
::$mVariableIDs;
216 /* Allow external reads of TTL array */
217 static function getCacheTTL($id) {
218 if (array_key_exists($id,self
::$mCacheTTLs)) {
219 return self
::$mCacheTTLs[$id];
225 /** Get a MagicWordArray of double-underscore entities */
226 static function getDoubleUnderscoreArray() {
227 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
228 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
230 return self
::$mDoubleUnderscoreArray;
233 # Initialises this object with an ID
234 function load( $id ) {
237 $wgContLang->getMagic( $this );
238 if ( !$this->mSynonyms
) {
239 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
240 #throw new MWException( "Error: invalid magic word '$id'" );
241 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
246 * Preliminary initialisation
249 function initRegex() {
250 #$variableClass = Title::legalChars();
251 # This was used for matching "$1" variables, but different uses of the feature will have
252 # different restrictions, which should be checked *after* the MagicWord has been matched,
256 foreach ( $this->mSynonyms
as $synonym )
257 // In case a magic word contains /, like that's going to happen;)
258 $escSyn[] = preg_quote( $synonym, '/' );
259 $this->mBaseRegex
= implode( '|', $escSyn );
261 $case = $this->mCaseSensitive ?
'' : 'iu';
262 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
263 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
264 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
265 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
266 "/^(?:{$this->mBaseRegex})$/{$case}" );
270 * Gets a regex representing matching the word
272 function getRegex() {
273 if ($this->mRegex
== '' ) {
276 return $this->mRegex
;
280 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
281 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
282 * the complete expression
284 function getRegexCase() {
285 if ( $this->mRegex
=== '' )
288 return $this->mCaseSensitive ?
'' : 'iu';
292 * Gets a regex matching the word, if it is at the string start
294 function getRegexStart() {
295 if ($this->mRegex
== '' ) {
298 return $this->mRegexStart
;
302 * regex without the slashes and what not
304 function getBaseRegex() {
305 if ($this->mRegex
== '') {
308 return $this->mBaseRegex
;
312 * Returns true if the text contains the word
315 function match( $text ) {
316 return preg_match( $this->getRegex(), $text );
320 * Returns true if the text starts with the word
323 function matchStart( $text ) {
324 return preg_match( $this->getRegexStart(), $text );
328 * Returns NULL if there's no match, the value of $1 otherwise
329 * The return code is the matched string, if there's no variable
330 * part in the regex and the matched variable part ($1) if there
333 function matchVariableStartToEnd( $text ) {
335 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
336 if ( $matchcount == 0 ) {
339 # multiple matched parts (variable match); some will be empty because of
340 # synonyms. The variable will be the second non-empty one so remove any
341 # blank elements and re-sort the indices.
344 $matches = array_values(array_filter($matches));
346 if ( count($matches) == 1 ) { return $matches[0]; }
347 else { return $matches[1]; }
353 * Returns true if the text matches the word, and alters the
354 * input string, removing all instances of the word
356 function matchAndRemove( &$text ) {
357 $this->mFound
= false;
358 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
359 return $this->mFound
;
362 function matchStartAndRemove( &$text ) {
363 $this->mFound
= false;
364 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
365 return $this->mFound
;
369 * Used in matchAndRemove()
372 function pregRemoveAndRecord( ) {
373 $this->mFound
= true;
378 * Replaces the word with something else
380 function replace( $replacement, $subject, $limit=-1 ) {
381 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
382 $this->mModified
= !($res === $subject);
387 * Variable handling: {{SUBST:xxx}} style words
388 * Calls back a function to determine what to replace xxx with
389 * Input word must contain $1
391 function substituteCallback( $text, $callback ) {
392 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
393 $this->mModified
= !($res === $text);
398 * Matches the word, where $1 is a wildcard
400 function getVariableRegex() {
401 if ( $this->mVariableRegex
== '' ) {
404 return $this->mVariableRegex
;
408 * Matches the entire string, where $1 is a wildcard
410 function getVariableStartToEndRegex() {
411 if ( $this->mVariableStartToEndRegex
== '' ) {
414 return $this->mVariableStartToEndRegex
;
418 * Accesses the synonym list directly
420 function getSynonym( $i ) {
421 return $this->mSynonyms
[$i];
424 function getSynonyms() {
425 return $this->mSynonyms
;
429 * Returns true if the last call to replace() or substituteCallback()
430 * returned a modified text, otherwise false.
432 function getWasModified(){
433 return $this->mModified
;
437 * $magicarr is an associative array of (magic word ID => replacement)
438 * This method uses the php feature to do several replacements at the same time,
439 * thereby gaining some efficiency. The result is placed in the out variable
440 * $result. The return value is true if something was replaced.
443 function replaceMultiple( $magicarr, $subject, &$result ){
446 foreach( $magicarr as $id => $replacement ){
447 $mw = MagicWord
::get( $id );
448 $search[] = $mw->getRegex();
449 $replace[] = $replacement;
452 $result = preg_replace( $search, $replace, $subject );
453 return !($result === $subject);
457 * Adds all the synonyms of this MagicWord to an array, to allow quick
458 * lookup in a list of magic words
460 function addToArray( &$array, $value ) {
462 foreach ( $this->mSynonyms
as $syn ) {
463 $array[$wgContLang->lc($syn)] = $value;
467 function isCaseSensitive() {
468 return $this->mCaseSensitive
;
477 * Class for handling an array of magic words
480 class MagicWordArray
{
481 var $names = array();
483 var $baseRegex, $regex;
486 function __construct( $names = array() ) {
487 $this->names
= $names;
491 * Add a magic word by name
493 public function add( $name ) {
495 $this->names
[] = $name;
496 $this->hash
= $this->baseRegex
= $this->regex
= null;
500 * Add a number of magic words by name
502 public function addArray( $names ) {
503 $this->names
= array_merge( $this->names
, array_values( $names ) );
504 $this->hash
= $this->baseRegex
= $this->regex
= null;
508 * Get a 2-d hashtable for this array
511 if ( is_null( $this->hash
) ) {
513 $this->hash
= array( 0 => array(), 1 => array() );
514 foreach ( $this->names
as $name ) {
515 $magic = MagicWord
::get( $name );
516 $case = intval( $magic->isCaseSensitive() );
517 foreach ( $magic->getSynonyms() as $syn ) {
519 $syn = $wgContLang->lc( $syn );
521 $this->hash
[$case][$syn] = $name;
531 function getBaseRegex() {
532 if ( is_null( $this->baseRegex
) ) {
533 $this->baseRegex
= array( 0 => '', 1 => '' );
534 foreach ( $this->names
as $name ) {
535 $magic = MagicWord
::get( $name );
536 $case = intval( $magic->isCaseSensitive() );
537 foreach ( $magic->getSynonyms() as $i => $syn ) {
538 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
539 if ( $this->baseRegex
[$case] === '' ) {
540 $this->baseRegex
[$case] = $group;
542 $this->baseRegex
[$case] .= '|' . $group;
547 return $this->baseRegex
;
551 * Get an unanchored regex
553 function getRegex() {
554 if ( is_null( $this->regex
) ) {
555 $base = $this->getBaseRegex();
556 $this->regex
= array( '', '' );
557 if ( $this->baseRegex
[0] !== '' ) {
558 $this->regex
[0] = "/{$base[0]}/iuS";
560 if ( $this->baseRegex
[1] !== '' ) {
561 $this->regex
[1] = "/{$base[1]}/S";
568 * Get a regex for matching variables
570 function getVariableRegex() {
571 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
575 * Get an anchored regex for matching variables
577 function getVariableStartToEndRegex() {
578 $base = $this->getBaseRegex();
579 $newRegex = array( '', '' );
580 if ( $base[0] !== '' ) {
581 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
583 if ( $base[1] !== '' ) {
584 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
590 * Parse a match array from preg_match
591 * Returns array(magic word ID, parameter value)
592 * If there is no parameter value, that element will be false.
594 function parseMatch( $m ) {
596 while ( list( $key, $value ) = each( $m ) ) {
597 if ( $key === 0 ||
$value === '' ) {
600 $parts = explode( '_', $key, 2 );
601 if ( count( $parts ) != 2 ) {
602 // This shouldn't happen
604 throw new MWException( __METHOD__
. ': bad parameter name' );
606 list( /* $synIndex */, $magicName ) = $parts;
607 $paramValue = next( $m );
608 return array( $magicName, $paramValue );
610 // This shouldn't happen either
611 throw new MWException( __METHOD__
.': parameter not found' );
612 return array( false, false );
616 * Match some text, with parameter capture
617 * Returns an array with the magic word name in the first element and the
618 * parameter in the second element.
619 * Both elements are false if there was no match.
621 public function matchVariableStartToEnd( $text ) {
623 $regexes = $this->getVariableStartToEndRegex();
624 foreach ( $regexes as $regex ) {
625 if ( $regex !== '' ) {
627 if ( preg_match( $regex, $text, $m ) ) {
628 return $this->parseMatch( $m );
632 return array( false, false );
636 * Match some text, without parameter capture
637 * Returns the magic word name, or false if there was no capture
639 public function matchStartToEnd( $text ) {
640 $hash = $this->getHash();
641 if ( isset( $hash[1][$text] ) ) {
642 return $hash[1][$text];
645 $lc = $wgContLang->lc( $text );
646 if ( isset( $hash[0][$lc] ) ) {
647 return $hash[0][$lc];
653 * Returns an associative array, ID => param value, for all items that match
654 * Removes the matched items from the input string (passed by reference)
656 public function matchAndRemove( &$text ) {
658 $regexes = $this->getRegex();
659 foreach ( $regexes as $regex ) {
660 if ( $regex === '' ) {
663 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
664 foreach ( $matches as $m ) {
665 list( $name, $param ) = $this->parseMatch( $m );
666 $found[$name] = $param;
668 $text = preg_replace( $regex, '', $text );