8 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
10 * if (MagicWord::get( 'redirect' )->match( $text ) )
12 * Possible future improvements:
13 * * Simultaneous searching for a number of magic words
14 * * MagicWord::$mObjects in shared memory
16 * Please avoid reading the data out of one of these objects and then writing
17 * special case code. If possible, add another match()-like function here.
19 * To add magic words in an extension, use the LanguageGetMagic hook. For
20 * magic words which are also Parser variables, add a MagicWordwgVariableIDs
21 * hook. Use string keys.
28 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
29 var $mRegexStart, $mBaseRegex, $mVariableRegex;
30 var $mModified, $mFound;
32 static public $mVariableIDsInitialised = false;
33 static public $mVariableIDs = array(
36 'currentmonthnamegen',
105 /* Array of caching hints for ParserCache */
106 static public $mCacheTTLs = array (
107 'currentmonth' => 86400,
108 'currentmonthname' => 86400,
109 'currentmonthnamegen' => 86400,
110 'currentmonthabbrev' => 86400,
111 'currentday' => 3600,
112 'currentday2' => 3600,
113 'currentdayname' => 3600,
114 'currentyear' => 86400,
115 'currenttime' => 3600,
116 'currenthour' => 3600,
117 'localmonth' => 86400,
118 'localmonthname' => 86400,
119 'localmonthnamegen' => 86400,
120 'localmonthabbrev' => 86400,
123 'localdayname' => 3600,
124 'localyear' => 86400,
127 'numberofarticles' => 3600,
128 'numberoffiles' => 3600,
129 'numberofedits' => 3600,
130 'currentweek' => 3600,
131 'currentdow' => 3600,
134 'numberofusers' => 3600,
135 'numberofpages' => 3600,
136 'currentversion' => 86400,
137 'currenttimestamp' => 3600,
138 'localtimestamp' => 3600,
139 'pagesinnamespace' => 3600,
140 'numberofadmins' => 3600,
143 static public $mObjects = array();
147 function __construct($id = 0, $syn = '', $cs = false) {
149 $this->mSynonyms
= (array)$syn;
150 $this->mCaseSensitive
= $cs;
152 $this->mRegexStart
= '';
153 $this->mVariableRegex
= '';
154 $this->mVariableStartToEndRegex
= '';
155 $this->mModified
= false;
159 * Factory: creates an object representing an ID
162 static function &get( $id ) {
163 wfProfileIn( __METHOD__
);
164 if (!array_key_exists( $id, self
::$mObjects ) ) {
165 $mw = new MagicWord();
167 self
::$mObjects[$id] = $mw;
169 wfProfileOut( __METHOD__
);
170 return self
::$mObjects[$id];
174 * Get an array of parser variable IDs
176 static function getVariableIDs() {
177 if ( !self
::$mVariableIDsInitialised ) {
178 # Deprecated constant definition hook, available for extensions that need it
179 $magicWords = array();
180 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
181 foreach ( $magicWords as $word ) {
182 define( $word, $word );
186 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
187 self
::$mVariableIDsInitialised = true;
189 return self
::$mVariableIDs;
192 /* Allow external reads of TTL array */
193 static function getCacheTTL($id) {
194 if (array_key_exists($id,self
::$mCacheTTLs)) {
195 return self
::$mCacheTTLs[$id];
202 # Initialises this object with an ID
203 function load( $id ) {
206 $wgContLang->getMagic( $this );
207 if ( !$this->mSynonyms
) {
208 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
209 #throw new MWException( "Error: invalid magic word '$id'" );
210 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
215 * Preliminary initialisation
218 function initRegex() {
219 #$variableClass = Title::legalChars();
220 # This was used for matching "$1" variables, but different uses of the feature will have
221 # different restrictions, which should be checked *after* the MagicWord has been matched,
225 foreach ( $this->mSynonyms
as $synonym )
226 // In case a magic word contains /, like that's going to happen;)
227 $escSyn[] = preg_quote( $synonym, '/' );
228 $this->mBaseRegex
= implode( '|', $escSyn );
230 $case = $this->mCaseSensitive ?
'' : 'iu';
231 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
232 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
233 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
234 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
235 "/^(?:{$this->mBaseRegex})$/{$case}" );
239 * Gets a regex representing matching the word
241 function getRegex() {
242 if ($this->mRegex
== '' ) {
245 return $this->mRegex
;
249 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
250 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
251 * the complete expression
253 function getRegexCase() {
254 if ( $this->mRegex
=== '' )
257 return $this->mCaseSensitive ?
'' : 'iu';
261 * Gets a regex matching the word, if it is at the string start
263 function getRegexStart() {
264 if ($this->mRegex
== '' ) {
267 return $this->mRegexStart
;
271 * regex without the slashes and what not
273 function getBaseRegex() {
274 if ($this->mRegex
== '') {
277 return $this->mBaseRegex
;
281 * Returns true if the text contains the word
284 function match( $text ) {
285 return preg_match( $this->getRegex(), $text );
289 * Returns true if the text starts with the word
292 function matchStart( $text ) {
293 return preg_match( $this->getRegexStart(), $text );
297 * Returns NULL if there's no match, the value of $1 otherwise
298 * The return code is the matched string, if there's no variable
299 * part in the regex and the matched variable part ($1) if there
302 function matchVariableStartToEnd( $text ) {
304 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
305 if ( $matchcount == 0 ) {
308 # multiple matched parts (variable match); some will be empty because of
309 # synonyms. The variable will be the second non-empty one so remove any
310 # blank elements and re-sort the indices.
313 $matches = array_values(array_filter($matches));
315 if ( count($matches) == 1 ) { return $matches[0]; }
316 else { return $matches[1]; }
322 * Returns true if the text matches the word, and alters the
323 * input string, removing all instances of the word
325 function matchAndRemove( &$text ) {
326 $this->mFound
= false;
327 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
328 return $this->mFound
;
331 function matchStartAndRemove( &$text ) {
332 $this->mFound
= false;
333 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
334 return $this->mFound
;
338 * Used in matchAndRemove()
341 function pregRemoveAndRecord( ) {
342 $this->mFound
= true;
347 * Replaces the word with something else
349 function replace( $replacement, $subject, $limit=-1 ) {
350 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
351 $this->mModified
= !($res === $subject);
356 * Variable handling: {{SUBST:xxx}} style words
357 * Calls back a function to determine what to replace xxx with
358 * Input word must contain $1
360 function substituteCallback( $text, $callback ) {
361 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
362 $this->mModified
= !($res === $text);
367 * Matches the word, where $1 is a wildcard
369 function getVariableRegex() {
370 if ( $this->mVariableRegex
== '' ) {
373 return $this->mVariableRegex
;
377 * Matches the entire string, where $1 is a wildcard
379 function getVariableStartToEndRegex() {
380 if ( $this->mVariableStartToEndRegex
== '' ) {
383 return $this->mVariableStartToEndRegex
;
387 * Accesses the synonym list directly
389 function getSynonym( $i ) {
390 return $this->mSynonyms
[$i];
393 function getSynonyms() {
394 return $this->mSynonyms
;
398 * Returns true if the last call to replace() or substituteCallback()
399 * returned a modified text, otherwise false.
401 function getWasModified(){
402 return $this->mModified
;
406 * $magicarr is an associative array of (magic word ID => replacement)
407 * This method uses the php feature to do several replacements at the same time,
408 * thereby gaining some efficiency. The result is placed in the out variable
409 * $result. The return value is true if something was replaced.
412 function replaceMultiple( $magicarr, $subject, &$result ){
415 foreach( $magicarr as $id => $replacement ){
416 $mw = MagicWord
::get( $id );
417 $search[] = $mw->getRegex();
418 $replace[] = $replacement;
421 $result = preg_replace( $search, $replace, $subject );
422 return !($result === $subject);
426 * Adds all the synonyms of this MagicWord to an array, to allow quick
427 * lookup in a list of magic words
429 function addToArray( &$array, $value ) {
431 foreach ( $this->mSynonyms
as $syn ) {
432 $array[$wgContLang->lc($syn)] = $value;
436 function isCaseSensitive() {
437 return $this->mCaseSensitive
;
446 * Class for handling an array of magic words
448 class MagicWordArray
{
449 var $names = array();
451 var $baseRegex, $regex;
453 function __construct( $names = array() ) {
454 $this->names
= $names;
458 * Add a magic word by name
460 public function add( $name ) {
462 $this->names
[] = $name;
463 $this->hash
= $this->baseRegex
= $this->regex
= null;
467 * Add a number of magic words by name
469 public function addArray( $names ) {
470 $this->names
= array_merge( $this->names
, array_values( $names ) );
471 $this->hash
= $this->baseRegex
= $this->regex
= null;
475 * Get a 2-d hashtable for this array
478 if ( is_null( $this->hash
) ) {
480 $this->hash
= array( 0 => array(), 1 => array() );
481 foreach ( $this->names
as $name ) {
482 $magic = MagicWord
::get( $name );
483 $case = intval( $magic->isCaseSensitive() );
484 foreach ( $magic->getSynonyms() as $syn ) {
486 $syn = $wgContLang->lc( $syn );
488 $this->hash
[$case][$syn] = $name;
498 function getBaseRegex() {
499 if ( is_null( $this->baseRegex
) ) {
500 $this->baseRegex
= array( 0 => '', 1 => '' );
501 foreach ( $this->names
as $name ) {
502 $magic = MagicWord
::get( $name );
503 $case = intval( $magic->isCaseSensitive() );
504 foreach ( $magic->getSynonyms() as $i => $syn ) {
505 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
506 if ( $this->baseRegex
[$case] === '' ) {
507 $this->baseRegex
[$case] = $group;
509 $this->baseRegex
[$case] .= '|' . $group;
514 return $this->baseRegex
;
518 * Get an unanchored regex
520 function getRegex() {
521 if ( is_null( $this->regex
) ) {
522 $base = $this->getBaseRegex();
523 $this->regex
= array( '', '' );
524 if ( $this->baseRegex
[0] !== '' ) {
525 $this->regex
[0] = "/{$base[0]}/iuS";
527 if ( $this->baseRegex
[1] !== '' ) {
528 $this->regex
[1] = "/{$base[1]}/S";
535 * Get a regex for matching variables
537 function getVariableRegex() {
538 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
542 * Get an anchored regex for matching variables
544 function getVariableStartToEndRegex() {
545 $base = $this->getBaseRegex();
546 $newRegex = array( '', '' );
547 if ( $base[0] !== '' ) {
548 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
550 if ( $base[1] !== '' ) {
551 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
557 * Parse a match array from preg_match
559 function parseMatch( $m ) {
561 while ( list( $key, $value ) = each( $m ) ) {
562 if ( $key === 0 ||
$value === '' ) {
565 $parts = explode( '_', $key, 2 );
566 if ( count( $parts ) != 2 ) {
567 // This shouldn't happen
569 throw new MWException( __METHOD__
. ': bad parameter name' );
571 list( /* $synIndex */, $magicName ) = $parts;
572 $paramValue = next( $m );
573 return array( $magicName, $paramValue );
575 // This shouldn't happen either
576 throw new MWException( __METHOD__
.': parameter not found' );
577 return array( false, false );
581 * Match some text, with parameter capture
582 * Returns an array with the magic word name in the first element and the
583 * parameter in the second element.
584 * Both elements are false if there was no match.
586 public function matchVariableStartToEnd( $text ) {
588 $regexes = $this->getVariableStartToEndRegex();
589 foreach ( $regexes as $regex ) {
590 if ( $regex !== '' ) {
592 if ( preg_match( $regex, $text, $m ) ) {
593 return $this->parseMatch( $m );
597 return array( false, false );
601 * Match some text, without parameter capture
602 * Returns the magic word name, or false if there was no capture
604 public function matchStartToEnd( $text ) {
605 $hash = $this->getHash();
606 if ( isset( $hash[1][$text] ) ) {
607 return $hash[1][$text];
610 $lc = $wgContLang->lc( $text );
611 if ( isset( $hash[0][$lc] ) ) {
612 return $hash[0][$lc];