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',
114 /* Array of caching hints for ParserCache */
115 static public $mCacheTTLs = array (
116 'currentmonth' => 86400,
117 'currentmonthname' => 86400,
118 'currentmonthnamegen' => 86400,
119 'currentmonthabbrev' => 86400,
120 'currentday' => 3600,
121 'currentday2' => 3600,
122 'currentdayname' => 3600,
123 'currentyear' => 86400,
124 'currenttime' => 3600,
125 'currenthour' => 3600,
126 'localmonth' => 86400,
127 'localmonthname' => 86400,
128 'localmonthnamegen' => 86400,
129 'localmonthabbrev' => 86400,
132 'localdayname' => 3600,
133 'localyear' => 86400,
136 'numberofarticles' => 3600,
137 'numberoffiles' => 3600,
138 'numberofedits' => 3600,
139 'currentweek' => 3600,
140 'currentdow' => 3600,
143 'numberofusers' => 3600,
144 'numberofpages' => 3600,
145 'currentversion' => 86400,
146 'currenttimestamp' => 3600,
147 'localtimestamp' => 3600,
148 'pagesinnamespace' => 3600,
149 'numberofadmins' => 3600,
150 'numberofviews' => 3600,
151 'numberingroup' => 3600,
154 static public $mDoubleUnderscoreIDs = array(
168 static public $mObjects = array();
169 static public $mDoubleUnderscoreArray = null;
173 function __construct($id = 0, $syn = '', $cs = false) {
175 $this->mSynonyms
= (array)$syn;
176 $this->mCaseSensitive
= $cs;
178 $this->mRegexStart
= '';
179 $this->mVariableRegex
= '';
180 $this->mVariableStartToEndRegex
= '';
181 $this->mModified
= false;
185 * Factory: creates an object representing an ID
188 static function &get( $id ) {
189 wfProfileIn( __METHOD__
);
190 if (!array_key_exists( $id, self
::$mObjects ) ) {
191 $mw = new MagicWord();
193 self
::$mObjects[$id] = $mw;
195 wfProfileOut( __METHOD__
);
196 return self
::$mObjects[$id];
200 * Get an array of parser variable IDs
202 static function getVariableIDs() {
203 if ( !self
::$mVariableIDsInitialised ) {
204 # Deprecated constant definition hook, available for extensions that need it
205 $magicWords = array();
206 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
207 foreach ( $magicWords as $word ) {
208 define( $word, $word );
212 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
213 self
::$mVariableIDsInitialised = true;
215 return self
::$mVariableIDs;
218 /* Allow external reads of TTL array */
219 static function getCacheTTL($id) {
220 if (array_key_exists($id,self
::$mCacheTTLs)) {
221 return self
::$mCacheTTLs[$id];
227 /** Get a MagicWordArray of double-underscore entities */
228 static function getDoubleUnderscoreArray() {
229 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
230 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
232 return self
::$mDoubleUnderscoreArray;
235 # Initialises this object with an ID
236 function load( $id ) {
239 $wgContLang->getMagic( $this );
240 if ( !$this->mSynonyms
) {
241 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
242 #throw new MWException( "Error: invalid magic word '$id'" );
243 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
248 * Preliminary initialisation
251 function initRegex() {
252 #$variableClass = Title::legalChars();
253 # This was used for matching "$1" variables, but different uses of the feature will have
254 # different restrictions, which should be checked *after* the MagicWord has been matched,
258 foreach ( $this->mSynonyms
as $synonym )
259 // In case a magic word contains /, like that's going to happen;)
260 $escSyn[] = preg_quote( $synonym, '/' );
261 $this->mBaseRegex
= implode( '|', $escSyn );
263 $case = $this->mCaseSensitive ?
'' : 'iu';
264 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
265 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
266 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
267 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
268 "/^(?:{$this->mBaseRegex})$/{$case}" );
272 * Gets a regex representing matching the word
274 function getRegex() {
275 if ($this->mRegex
== '' ) {
278 return $this->mRegex
;
282 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
283 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
284 * the complete expression
286 function getRegexCase() {
287 if ( $this->mRegex
=== '' )
290 return $this->mCaseSensitive ?
'' : 'iu';
294 * Gets a regex matching the word, if it is at the string start
296 function getRegexStart() {
297 if ($this->mRegex
== '' ) {
300 return $this->mRegexStart
;
304 * regex without the slashes and what not
306 function getBaseRegex() {
307 if ($this->mRegex
== '') {
310 return $this->mBaseRegex
;
314 * Returns true if the text contains the word
317 function match( $text ) {
318 return preg_match( $this->getRegex(), $text );
322 * Returns true if the text starts with the word
325 function matchStart( $text ) {
326 return preg_match( $this->getRegexStart(), $text );
330 * Returns NULL if there's no match, the value of $1 otherwise
331 * The return code is the matched string, if there's no variable
332 * part in the regex and the matched variable part ($1) if there
335 function matchVariableStartToEnd( $text ) {
337 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
338 if ( $matchcount == 0 ) {
341 # multiple matched parts (variable match); some will be empty because of
342 # synonyms. The variable will be the second non-empty one so remove any
343 # blank elements and re-sort the indices.
346 $matches = array_values(array_filter($matches));
348 if ( count($matches) == 1 ) { return $matches[0]; }
349 else { return $matches[1]; }
355 * Returns true if the text matches the word, and alters the
356 * input string, removing all instances of the word
358 function matchAndRemove( &$text ) {
359 $this->mFound
= false;
360 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
361 return $this->mFound
;
364 function matchStartAndRemove( &$text ) {
365 $this->mFound
= false;
366 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
367 return $this->mFound
;
371 * Used in matchAndRemove()
374 function pregRemoveAndRecord( ) {
375 $this->mFound
= true;
380 * Replaces the word with something else
382 function replace( $replacement, $subject, $limit=-1 ) {
383 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
384 $this->mModified
= !($res === $subject);
389 * Variable handling: {{SUBST:xxx}} style words
390 * Calls back a function to determine what to replace xxx with
391 * Input word must contain $1
393 function substituteCallback( $text, $callback ) {
394 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
395 $this->mModified
= !($res === $text);
400 * Matches the word, where $1 is a wildcard
402 function getVariableRegex() {
403 if ( $this->mVariableRegex
== '' ) {
406 return $this->mVariableRegex
;
410 * Matches the entire string, where $1 is a wildcard
412 function getVariableStartToEndRegex() {
413 if ( $this->mVariableStartToEndRegex
== '' ) {
416 return $this->mVariableStartToEndRegex
;
420 * Accesses the synonym list directly
422 function getSynonym( $i ) {
423 return $this->mSynonyms
[$i];
426 function getSynonyms() {
427 return $this->mSynonyms
;
431 * Returns true if the last call to replace() or substituteCallback()
432 * returned a modified text, otherwise false.
434 function getWasModified(){
435 return $this->mModified
;
439 * $magicarr is an associative array of (magic word ID => replacement)
440 * This method uses the php feature to do several replacements at the same time,
441 * thereby gaining some efficiency. The result is placed in the out variable
442 * $result. The return value is true if something was replaced.
445 function replaceMultiple( $magicarr, $subject, &$result ){
448 foreach( $magicarr as $id => $replacement ){
449 $mw = MagicWord
::get( $id );
450 $search[] = $mw->getRegex();
451 $replace[] = $replacement;
454 $result = preg_replace( $search, $replace, $subject );
455 return !($result === $subject);
459 * Adds all the synonyms of this MagicWord to an array, to allow quick
460 * lookup in a list of magic words
462 function addToArray( &$array, $value ) {
464 foreach ( $this->mSynonyms
as $syn ) {
465 $array[$wgContLang->lc($syn)] = $value;
469 function isCaseSensitive() {
470 return $this->mCaseSensitive
;
479 * Class for handling an array of magic words
482 class MagicWordArray
{
483 var $names = array();
485 var $baseRegex, $regex;
488 function __construct( $names = array() ) {
489 $this->names
= $names;
493 * Add a magic word by name
495 public function add( $name ) {
497 $this->names
[] = $name;
498 $this->hash
= $this->baseRegex
= $this->regex
= null;
502 * Add a number of magic words by name
504 public function addArray( $names ) {
505 $this->names
= array_merge( $this->names
, array_values( $names ) );
506 $this->hash
= $this->baseRegex
= $this->regex
= null;
510 * Get a 2-d hashtable for this array
513 if ( is_null( $this->hash
) ) {
515 $this->hash
= array( 0 => array(), 1 => array() );
516 foreach ( $this->names
as $name ) {
517 $magic = MagicWord
::get( $name );
518 $case = intval( $magic->isCaseSensitive() );
519 foreach ( $magic->getSynonyms() as $syn ) {
521 $syn = $wgContLang->lc( $syn );
523 $this->hash
[$case][$syn] = $name;
533 function getBaseRegex() {
534 if ( is_null( $this->baseRegex
) ) {
535 $this->baseRegex
= array( 0 => '', 1 => '' );
536 foreach ( $this->names
as $name ) {
537 $magic = MagicWord
::get( $name );
538 $case = intval( $magic->isCaseSensitive() );
539 foreach ( $magic->getSynonyms() as $i => $syn ) {
540 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
541 if ( $this->baseRegex
[$case] === '' ) {
542 $this->baseRegex
[$case] = $group;
544 $this->baseRegex
[$case] .= '|' . $group;
549 return $this->baseRegex
;
553 * Get an unanchored regex
555 function getRegex() {
556 if ( is_null( $this->regex
) ) {
557 $base = $this->getBaseRegex();
558 $this->regex
= array( '', '' );
559 if ( $this->baseRegex
[0] !== '' ) {
560 $this->regex
[0] = "/{$base[0]}/iuS";
562 if ( $this->baseRegex
[1] !== '' ) {
563 $this->regex
[1] = "/{$base[1]}/S";
570 * Get a regex for matching variables
572 function getVariableRegex() {
573 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
577 * Get an anchored regex for matching variables
579 function getVariableStartToEndRegex() {
580 $base = $this->getBaseRegex();
581 $newRegex = array( '', '' );
582 if ( $base[0] !== '' ) {
583 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
585 if ( $base[1] !== '' ) {
586 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
592 * Parse a match array from preg_match
593 * Returns array(magic word ID, parameter value)
594 * If there is no parameter value, that element will be false.
596 function parseMatch( $m ) {
598 while ( list( $key, $value ) = each( $m ) ) {
599 if ( $key === 0 ||
$value === '' ) {
602 $parts = explode( '_', $key, 2 );
603 if ( count( $parts ) != 2 ) {
604 // This shouldn't happen
606 throw new MWException( __METHOD__
. ': bad parameter name' );
608 list( /* $synIndex */, $magicName ) = $parts;
609 $paramValue = next( $m );
610 return array( $magicName, $paramValue );
612 // This shouldn't happen either
613 throw new MWException( __METHOD__
.': parameter not found' );
614 return array( false, false );
618 * Match some text, with parameter capture
619 * Returns an array with the magic word name in the first element and the
620 * parameter in the second element.
621 * Both elements are false if there was no match.
623 public function matchVariableStartToEnd( $text ) {
625 $regexes = $this->getVariableStartToEndRegex();
626 foreach ( $regexes as $regex ) {
627 if ( $regex !== '' ) {
629 if ( preg_match( $regex, $text, $m ) ) {
630 return $this->parseMatch( $m );
634 return array( false, false );
638 * Match some text, without parameter capture
639 * Returns the magic word name, or false if there was no capture
641 public function matchStartToEnd( $text ) {
642 $hash = $this->getHash();
643 if ( isset( $hash[1][$text] ) ) {
644 return $hash[1][$text];
647 $lc = $wgContLang->lc( $text );
648 if ( isset( $hash[0][$lc] ) ) {
649 return $hash[0][$lc];
655 * Returns an associative array, ID => param value, for all items that match
656 * Removes the matched items from the input string (passed by reference)
658 public function matchAndRemove( &$text ) {
660 $regexes = $this->getRegex();
661 foreach ( $regexes as $regex ) {
662 if ( $regex === '' ) {
665 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
666 foreach ( $matches as $m ) {
667 list( $name, $param ) = $this->parseMatch( $m );
668 $found[$name] = $param;
670 $text = preg_replace( $regex, '', $text );