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',
110 /* Array of caching hints for ParserCache */
111 static public $mCacheTTLs = array (
112 'currentmonth' => 86400,
113 'currentmonthname' => 86400,
114 'currentmonthnamegen' => 86400,
115 'currentmonthabbrev' => 86400,
116 'currentday' => 3600,
117 'currentday2' => 3600,
118 'currentdayname' => 3600,
119 'currentyear' => 86400,
120 'currenttime' => 3600,
121 'currenthour' => 3600,
122 'localmonth' => 86400,
123 'localmonthname' => 86400,
124 'localmonthnamegen' => 86400,
125 'localmonthabbrev' => 86400,
128 'localdayname' => 3600,
129 'localyear' => 86400,
132 'numberofarticles' => 3600,
133 'numberoffiles' => 3600,
134 'numberofedits' => 3600,
135 'currentweek' => 3600,
136 'currentdow' => 3600,
139 'numberofusers' => 3600,
140 'numberofpages' => 3600,
141 'currentversion' => 86400,
142 'currenttimestamp' => 3600,
143 'localtimestamp' => 3600,
144 'pagesinnamespace' => 3600,
145 'numberofadmins' => 3600,
148 static public $mDoubleUnderscoreIDs = array(
159 static public $mObjects = array();
160 static public $mDoubleUnderscoreArray = null;
164 function __construct($id = 0, $syn = '', $cs = false) {
166 $this->mSynonyms
= (array)$syn;
167 $this->mCaseSensitive
= $cs;
169 $this->mRegexStart
= '';
170 $this->mVariableRegex
= '';
171 $this->mVariableStartToEndRegex
= '';
172 $this->mModified
= false;
176 * Factory: creates an object representing an ID
179 static function &get( $id ) {
180 wfProfileIn( __METHOD__
);
181 if (!array_key_exists( $id, self
::$mObjects ) ) {
182 $mw = new MagicWord();
184 self
::$mObjects[$id] = $mw;
186 wfProfileOut( __METHOD__
);
187 return self
::$mObjects[$id];
191 * Get an array of parser variable IDs
193 static function getVariableIDs() {
194 if ( !self
::$mVariableIDsInitialised ) {
195 # Deprecated constant definition hook, available for extensions that need it
196 $magicWords = array();
197 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
198 foreach ( $magicWords as $word ) {
199 define( $word, $word );
203 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
204 self
::$mVariableIDsInitialised = true;
206 return self
::$mVariableIDs;
209 /* Allow external reads of TTL array */
210 static function getCacheTTL($id) {
211 if (array_key_exists($id,self
::$mCacheTTLs)) {
212 return self
::$mCacheTTLs[$id];
218 /** Get a MagicWordArray of double-underscore entities */
219 static function getDoubleUnderscoreArray() {
220 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
221 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
223 return self
::$mDoubleUnderscoreArray;
226 # Initialises this object with an ID
227 function load( $id ) {
230 $wgContLang->getMagic( $this );
231 if ( !$this->mSynonyms
) {
232 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
233 #throw new MWException( "Error: invalid magic word '$id'" );
234 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
239 * Preliminary initialisation
242 function initRegex() {
243 #$variableClass = Title::legalChars();
244 # This was used for matching "$1" variables, but different uses of the feature will have
245 # different restrictions, which should be checked *after* the MagicWord has been matched,
249 foreach ( $this->mSynonyms
as $synonym )
250 // In case a magic word contains /, like that's going to happen;)
251 $escSyn[] = preg_quote( $synonym, '/' );
252 $this->mBaseRegex
= implode( '|', $escSyn );
254 $case = $this->mCaseSensitive ?
'' : 'iu';
255 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
256 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
257 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
258 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
259 "/^(?:{$this->mBaseRegex})$/{$case}" );
263 * Gets a regex representing matching the word
265 function getRegex() {
266 if ($this->mRegex
== '' ) {
269 return $this->mRegex
;
273 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
274 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
275 * the complete expression
277 function getRegexCase() {
278 if ( $this->mRegex
=== '' )
281 return $this->mCaseSensitive ?
'' : 'iu';
285 * Gets a regex matching the word, if it is at the string start
287 function getRegexStart() {
288 if ($this->mRegex
== '' ) {
291 return $this->mRegexStart
;
295 * regex without the slashes and what not
297 function getBaseRegex() {
298 if ($this->mRegex
== '') {
301 return $this->mBaseRegex
;
305 * Returns true if the text contains the word
308 function match( $text ) {
309 return preg_match( $this->getRegex(), $text );
313 * Returns true if the text starts with the word
316 function matchStart( $text ) {
317 return preg_match( $this->getRegexStart(), $text );
321 * Returns NULL if there's no match, the value of $1 otherwise
322 * The return code is the matched string, if there's no variable
323 * part in the regex and the matched variable part ($1) if there
326 function matchVariableStartToEnd( $text ) {
328 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
329 if ( $matchcount == 0 ) {
332 # multiple matched parts (variable match); some will be empty because of
333 # synonyms. The variable will be the second non-empty one so remove any
334 # blank elements and re-sort the indices.
337 $matches = array_values(array_filter($matches));
339 if ( count($matches) == 1 ) { return $matches[0]; }
340 else { return $matches[1]; }
346 * Returns true if the text matches the word, and alters the
347 * input string, removing all instances of the word
349 function matchAndRemove( &$text ) {
350 $this->mFound
= false;
351 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
352 return $this->mFound
;
355 function matchStartAndRemove( &$text ) {
356 $this->mFound
= false;
357 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
358 return $this->mFound
;
362 * Used in matchAndRemove()
365 function pregRemoveAndRecord( ) {
366 $this->mFound
= true;
371 * Replaces the word with something else
373 function replace( $replacement, $subject, $limit=-1 ) {
374 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
375 $this->mModified
= !($res === $subject);
380 * Variable handling: {{SUBST:xxx}} style words
381 * Calls back a function to determine what to replace xxx with
382 * Input word must contain $1
384 function substituteCallback( $text, $callback ) {
385 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
386 $this->mModified
= !($res === $text);
391 * Matches the word, where $1 is a wildcard
393 function getVariableRegex() {
394 if ( $this->mVariableRegex
== '' ) {
397 return $this->mVariableRegex
;
401 * Matches the entire string, where $1 is a wildcard
403 function getVariableStartToEndRegex() {
404 if ( $this->mVariableStartToEndRegex
== '' ) {
407 return $this->mVariableStartToEndRegex
;
411 * Accesses the synonym list directly
413 function getSynonym( $i ) {
414 return $this->mSynonyms
[$i];
417 function getSynonyms() {
418 return $this->mSynonyms
;
422 * Returns true if the last call to replace() or substituteCallback()
423 * returned a modified text, otherwise false.
425 function getWasModified(){
426 return $this->mModified
;
430 * $magicarr is an associative array of (magic word ID => replacement)
431 * This method uses the php feature to do several replacements at the same time,
432 * thereby gaining some efficiency. The result is placed in the out variable
433 * $result. The return value is true if something was replaced.
436 function replaceMultiple( $magicarr, $subject, &$result ){
439 foreach( $magicarr as $id => $replacement ){
440 $mw = MagicWord
::get( $id );
441 $search[] = $mw->getRegex();
442 $replace[] = $replacement;
445 $result = preg_replace( $search, $replace, $subject );
446 return !($result === $subject);
450 * Adds all the synonyms of this MagicWord to an array, to allow quick
451 * lookup in a list of magic words
453 function addToArray( &$array, $value ) {
455 foreach ( $this->mSynonyms
as $syn ) {
456 $array[$wgContLang->lc($syn)] = $value;
460 function isCaseSensitive() {
461 return $this->mCaseSensitive
;
470 * Class for handling an array of magic words
473 class MagicWordArray
{
474 var $names = array();
476 var $baseRegex, $regex;
479 function __construct( $names = array() ) {
480 $this->names
= $names;
484 * Add a magic word by name
486 public function add( $name ) {
488 $this->names
[] = $name;
489 $this->hash
= $this->baseRegex
= $this->regex
= null;
493 * Add a number of magic words by name
495 public function addArray( $names ) {
496 $this->names
= array_merge( $this->names
, array_values( $names ) );
497 $this->hash
= $this->baseRegex
= $this->regex
= null;
501 * Get a 2-d hashtable for this array
504 if ( is_null( $this->hash
) ) {
506 $this->hash
= array( 0 => array(), 1 => array() );
507 foreach ( $this->names
as $name ) {
508 $magic = MagicWord
::get( $name );
509 $case = intval( $magic->isCaseSensitive() );
510 foreach ( $magic->getSynonyms() as $syn ) {
512 $syn = $wgContLang->lc( $syn );
514 $this->hash
[$case][$syn] = $name;
524 function getBaseRegex() {
525 if ( is_null( $this->baseRegex
) ) {
526 $this->baseRegex
= array( 0 => '', 1 => '' );
527 foreach ( $this->names
as $name ) {
528 $magic = MagicWord
::get( $name );
529 $case = intval( $magic->isCaseSensitive() );
530 foreach ( $magic->getSynonyms() as $i => $syn ) {
531 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
532 if ( $this->baseRegex
[$case] === '' ) {
533 $this->baseRegex
[$case] = $group;
535 $this->baseRegex
[$case] .= '|' . $group;
540 return $this->baseRegex
;
544 * Get an unanchored regex
546 function getRegex() {
547 if ( is_null( $this->regex
) ) {
548 $base = $this->getBaseRegex();
549 $this->regex
= array( '', '' );
550 if ( $this->baseRegex
[0] !== '' ) {
551 $this->regex
[0] = "/{$base[0]}/iuS";
553 if ( $this->baseRegex
[1] !== '' ) {
554 $this->regex
[1] = "/{$base[1]}/S";
561 * Get a regex for matching variables
563 function getVariableRegex() {
564 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
568 * Get an anchored regex for matching variables
570 function getVariableStartToEndRegex() {
571 $base = $this->getBaseRegex();
572 $newRegex = array( '', '' );
573 if ( $base[0] !== '' ) {
574 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
576 if ( $base[1] !== '' ) {
577 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
583 * Parse a match array from preg_match
584 * Returns array(magic word ID, parameter value)
585 * If there is no parameter value, that element will be false.
587 function parseMatch( $m ) {
589 while ( list( $key, $value ) = each( $m ) ) {
590 if ( $key === 0 ||
$value === '' ) {
593 $parts = explode( '_', $key, 2 );
594 if ( count( $parts ) != 2 ) {
595 // This shouldn't happen
597 throw new MWException( __METHOD__
. ': bad parameter name' );
599 list( /* $synIndex */, $magicName ) = $parts;
600 $paramValue = next( $m );
601 return array( $magicName, $paramValue );
603 // This shouldn't happen either
604 throw new MWException( __METHOD__
.': parameter not found' );
605 return array( false, false );
609 * Match some text, with parameter capture
610 * Returns an array with the magic word name in the first element and the
611 * parameter in the second element.
612 * Both elements are false if there was no match.
614 public function matchVariableStartToEnd( $text ) {
616 $regexes = $this->getVariableStartToEndRegex();
617 foreach ( $regexes as $regex ) {
618 if ( $regex !== '' ) {
620 if ( preg_match( $regex, $text, $m ) ) {
621 return $this->parseMatch( $m );
625 return array( false, false );
629 * Match some text, without parameter capture
630 * Returns the magic word name, or false if there was no capture
632 public function matchStartToEnd( $text ) {
633 $hash = $this->getHash();
634 if ( isset( $hash[1][$text] ) ) {
635 return $hash[1][$text];
638 $lc = $wgContLang->lc( $text );
639 if ( isset( $hash[0][$lc] ) ) {
640 return $hash[0][$lc];
646 * Returns an associative array, ID => param value, for all items that match
647 * Removes the matched items from the input string (passed by reference)
649 public function matchAndRemove( &$text ) {
651 $regexes = $this->getRegex();
652 foreach ( $regexes as $regex ) {
653 if ( $regex === '' ) {
656 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
657 foreach ( $matches as $m ) {
658 list( $name, $param ) = $this->parseMatch( $m );
659 $found[$name] = $param;
661 $text = preg_replace( $regex, '', $text );