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',
108 /* Array of caching hints for ParserCache */
109 static public $mCacheTTLs = array (
110 'currentmonth' => 86400,
111 'currentmonthname' => 86400,
112 'currentmonthnamegen' => 86400,
113 'currentmonthabbrev' => 86400,
114 'currentday' => 3600,
115 'currentday2' => 3600,
116 'currentdayname' => 3600,
117 'currentyear' => 86400,
118 'currenttime' => 3600,
119 'currenthour' => 3600,
120 'localmonth' => 86400,
121 'localmonthname' => 86400,
122 'localmonthnamegen' => 86400,
123 'localmonthabbrev' => 86400,
126 'localdayname' => 3600,
127 'localyear' => 86400,
130 'numberofarticles' => 3600,
131 'numberoffiles' => 3600,
132 'numberofedits' => 3600,
133 'currentweek' => 3600,
134 'currentdow' => 3600,
137 'numberofusers' => 3600,
138 'numberofpages' => 3600,
139 'currentversion' => 86400,
140 'currenttimestamp' => 3600,
141 'localtimestamp' => 3600,
142 'pagesinnamespace' => 3600,
143 'numberofadmins' => 3600,
146 static public $mDoubleUnderscoreIDs = array(
157 static public $mObjects = array();
158 static public $mDoubleUnderscoreArray = null;
162 function __construct($id = 0, $syn = '', $cs = false) {
164 $this->mSynonyms
= (array)$syn;
165 $this->mCaseSensitive
= $cs;
167 $this->mRegexStart
= '';
168 $this->mVariableRegex
= '';
169 $this->mVariableStartToEndRegex
= '';
170 $this->mModified
= false;
174 * Factory: creates an object representing an ID
177 static function &get( $id ) {
178 wfProfileIn( __METHOD__
);
179 if (!array_key_exists( $id, self
::$mObjects ) ) {
180 $mw = new MagicWord();
182 self
::$mObjects[$id] = $mw;
184 wfProfileOut( __METHOD__
);
185 return self
::$mObjects[$id];
189 * Get an array of parser variable IDs
191 static function getVariableIDs() {
192 if ( !self
::$mVariableIDsInitialised ) {
193 # Deprecated constant definition hook, available for extensions that need it
194 $magicWords = array();
195 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
196 foreach ( $magicWords as $word ) {
197 define( $word, $word );
201 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
202 self
::$mVariableIDsInitialised = true;
204 return self
::$mVariableIDs;
207 /* Allow external reads of TTL array */
208 static function getCacheTTL($id) {
209 if (array_key_exists($id,self
::$mCacheTTLs)) {
210 return self
::$mCacheTTLs[$id];
216 /** Get a MagicWordArray of double-underscore entities */
217 static function getDoubleUnderscoreArray() {
218 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
219 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
221 return self
::$mDoubleUnderscoreArray;
224 # Initialises this object with an ID
225 function load( $id ) {
228 $wgContLang->getMagic( $this );
229 if ( !$this->mSynonyms
) {
230 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
231 #throw new MWException( "Error: invalid magic word '$id'" );
232 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
237 * Preliminary initialisation
240 function initRegex() {
241 #$variableClass = Title::legalChars();
242 # This was used for matching "$1" variables, but different uses of the feature will have
243 # different restrictions, which should be checked *after* the MagicWord has been matched,
247 foreach ( $this->mSynonyms
as $synonym )
248 // In case a magic word contains /, like that's going to happen;)
249 $escSyn[] = preg_quote( $synonym, '/' );
250 $this->mBaseRegex
= implode( '|', $escSyn );
252 $case = $this->mCaseSensitive ?
'' : 'iu';
253 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
254 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
255 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
256 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
257 "/^(?:{$this->mBaseRegex})$/{$case}" );
261 * Gets a regex representing matching the word
263 function getRegex() {
264 if ($this->mRegex
== '' ) {
267 return $this->mRegex
;
271 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
272 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
273 * the complete expression
275 function getRegexCase() {
276 if ( $this->mRegex
=== '' )
279 return $this->mCaseSensitive ?
'' : 'iu';
283 * Gets a regex matching the word, if it is at the string start
285 function getRegexStart() {
286 if ($this->mRegex
== '' ) {
289 return $this->mRegexStart
;
293 * regex without the slashes and what not
295 function getBaseRegex() {
296 if ($this->mRegex
== '') {
299 return $this->mBaseRegex
;
303 * Returns true if the text contains the word
306 function match( $text ) {
307 return preg_match( $this->getRegex(), $text );
311 * Returns true if the text starts with the word
314 function matchStart( $text ) {
315 return preg_match( $this->getRegexStart(), $text );
319 * Returns NULL if there's no match, the value of $1 otherwise
320 * The return code is the matched string, if there's no variable
321 * part in the regex and the matched variable part ($1) if there
324 function matchVariableStartToEnd( $text ) {
326 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
327 if ( $matchcount == 0 ) {
330 # multiple matched parts (variable match); some will be empty because of
331 # synonyms. The variable will be the second non-empty one so remove any
332 # blank elements and re-sort the indices.
335 $matches = array_values(array_filter($matches));
337 if ( count($matches) == 1 ) { return $matches[0]; }
338 else { return $matches[1]; }
344 * Returns true if the text matches the word, and alters the
345 * input string, removing all instances of the word
347 function matchAndRemove( &$text ) {
348 $this->mFound
= false;
349 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
350 return $this->mFound
;
353 function matchStartAndRemove( &$text ) {
354 $this->mFound
= false;
355 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
356 return $this->mFound
;
360 * Used in matchAndRemove()
363 function pregRemoveAndRecord( ) {
364 $this->mFound
= true;
369 * Replaces the word with something else
371 function replace( $replacement, $subject, $limit=-1 ) {
372 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
373 $this->mModified
= !($res === $subject);
378 * Variable handling: {{SUBST:xxx}} style words
379 * Calls back a function to determine what to replace xxx with
380 * Input word must contain $1
382 function substituteCallback( $text, $callback ) {
383 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
384 $this->mModified
= !($res === $text);
389 * Matches the word, where $1 is a wildcard
391 function getVariableRegex() {
392 if ( $this->mVariableRegex
== '' ) {
395 return $this->mVariableRegex
;
399 * Matches the entire string, where $1 is a wildcard
401 function getVariableStartToEndRegex() {
402 if ( $this->mVariableStartToEndRegex
== '' ) {
405 return $this->mVariableStartToEndRegex
;
409 * Accesses the synonym list directly
411 function getSynonym( $i ) {
412 return $this->mSynonyms
[$i];
415 function getSynonyms() {
416 return $this->mSynonyms
;
420 * Returns true if the last call to replace() or substituteCallback()
421 * returned a modified text, otherwise false.
423 function getWasModified(){
424 return $this->mModified
;
428 * $magicarr is an associative array of (magic word ID => replacement)
429 * This method uses the php feature to do several replacements at the same time,
430 * thereby gaining some efficiency. The result is placed in the out variable
431 * $result. The return value is true if something was replaced.
434 function replaceMultiple( $magicarr, $subject, &$result ){
437 foreach( $magicarr as $id => $replacement ){
438 $mw = MagicWord
::get( $id );
439 $search[] = $mw->getRegex();
440 $replace[] = $replacement;
443 $result = preg_replace( $search, $replace, $subject );
444 return !($result === $subject);
448 * Adds all the synonyms of this MagicWord to an array, to allow quick
449 * lookup in a list of magic words
451 function addToArray( &$array, $value ) {
453 foreach ( $this->mSynonyms
as $syn ) {
454 $array[$wgContLang->lc($syn)] = $value;
458 function isCaseSensitive() {
459 return $this->mCaseSensitive
;
468 * Class for handling an array of magic words
470 class MagicWordArray
{
471 var $names = array();
473 var $baseRegex, $regex;
476 function __construct( $names = array() ) {
477 $this->names
= $names;
481 * Add a magic word by name
483 public function add( $name ) {
485 $this->names
[] = $name;
486 $this->hash
= $this->baseRegex
= $this->regex
= null;
490 * Add a number of magic words by name
492 public function addArray( $names ) {
493 $this->names
= array_merge( $this->names
, array_values( $names ) );
494 $this->hash
= $this->baseRegex
= $this->regex
= null;
498 * Get a 2-d hashtable for this array
501 if ( is_null( $this->hash
) ) {
503 $this->hash
= array( 0 => array(), 1 => array() );
504 foreach ( $this->names
as $name ) {
505 $magic = MagicWord
::get( $name );
506 $case = intval( $magic->isCaseSensitive() );
507 foreach ( $magic->getSynonyms() as $syn ) {
509 $syn = $wgContLang->lc( $syn );
511 $this->hash
[$case][$syn] = $name;
521 function getBaseRegex() {
522 if ( is_null( $this->baseRegex
) ) {
523 $this->baseRegex
= array( 0 => '', 1 => '' );
524 foreach ( $this->names
as $name ) {
525 $magic = MagicWord
::get( $name );
526 $case = intval( $magic->isCaseSensitive() );
527 foreach ( $magic->getSynonyms() as $i => $syn ) {
528 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
529 if ( $this->baseRegex
[$case] === '' ) {
530 $this->baseRegex
[$case] = $group;
532 $this->baseRegex
[$case] .= '|' . $group;
537 return $this->baseRegex
;
541 * Get an unanchored regex
543 function getRegex() {
544 if ( is_null( $this->regex
) ) {
545 $base = $this->getBaseRegex();
546 $this->regex
= array( '', '' );
547 if ( $this->baseRegex
[0] !== '' ) {
548 $this->regex
[0] = "/{$base[0]}/iuS";
550 if ( $this->baseRegex
[1] !== '' ) {
551 $this->regex
[1] = "/{$base[1]}/S";
558 * Get a regex for matching variables
560 function getVariableRegex() {
561 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
565 * Get an anchored regex for matching variables
567 function getVariableStartToEndRegex() {
568 $base = $this->getBaseRegex();
569 $newRegex = array( '', '' );
570 if ( $base[0] !== '' ) {
571 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
573 if ( $base[1] !== '' ) {
574 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
580 * Parse a match array from preg_match
581 * Returns array(magic word ID, parameter value)
582 * If there is no parameter value, that element will be false.
584 function parseMatch( $m ) {
586 while ( list( $key, $value ) = each( $m ) ) {
587 if ( $key === 0 ||
$value === '' ) {
590 $parts = explode( '_', $key, 2 );
591 if ( count( $parts ) != 2 ) {
592 // This shouldn't happen
594 throw new MWException( __METHOD__
. ': bad parameter name' );
596 list( /* $synIndex */, $magicName ) = $parts;
597 $paramValue = next( $m );
598 return array( $magicName, $paramValue );
600 // This shouldn't happen either
601 throw new MWException( __METHOD__
.': parameter not found' );
602 return array( false, false );
606 * Match some text, with parameter capture
607 * Returns an array with the magic word name in the first element and the
608 * parameter in the second element.
609 * Both elements are false if there was no match.
611 public function matchVariableStartToEnd( $text ) {
613 $regexes = $this->getVariableStartToEndRegex();
614 foreach ( $regexes as $regex ) {
615 if ( $regex !== '' ) {
617 if ( preg_match( $regex, $text, $m ) ) {
618 return $this->parseMatch( $m );
622 return array( false, false );
626 * Match some text, without parameter capture
627 * Returns the magic word name, or false if there was no capture
629 public function matchStartToEnd( $text ) {
630 $hash = $this->getHash();
631 if ( isset( $hash[1][$text] ) ) {
632 return $hash[1][$text];
635 $lc = $wgContLang->lc( $text );
636 if ( isset( $hash[0][$lc] ) ) {
637 return $hash[0][$lc];
643 * Returns an associative array, ID => param value, for all items that match
644 * Removes the matched items from the input string (passed by reference)
646 public function matchAndRemove( &$text ) {
648 $regexes = $this->getRegex();
649 foreach ( $regexes as $regex ) {
650 if ( $regex === '' ) {
653 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
654 foreach ( $matches as $m ) {
655 list( $name, $param ) = $this->parseMatch( $m );
656 $found[$name] = $param;
658 $text = preg_replace( $regex, '', $text );