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 if (!array_key_exists( $id, self
::$mObjects ) ) {
164 $mw = new MagicWord();
166 self
::$mObjects[$id] = $mw;
168 return self
::$mObjects[$id];
172 * Get an array of parser variable IDs
174 static function getVariableIDs() {
175 if ( !self
::$mVariableIDsInitialised ) {
176 # Deprecated constant definition hook, available for extensions that need it
177 $magicWords = array();
178 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
179 foreach ( $magicWords as $word ) {
180 define( $word, $word );
184 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
185 self
::$mVariableIDsInitialised = true;
187 return self
::$mVariableIDs;
190 /* Allow external reads of TTL array */
191 static function getCacheTTL($id) {
192 if (array_key_exists($id,self
::$mCacheTTLs)) {
193 return self
::$mCacheTTLs[$id];
200 # Initialises this object with an ID
201 function load( $id ) {
204 $wgContLang->getMagic( $this );
205 if ( !$this->mSynonyms
) {
206 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
207 #throw new MWException( "Error: invalid magic word '$id'" );
208 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
213 * Preliminary initialisation
216 function initRegex() {
217 #$variableClass = Title::legalChars();
218 # This was used for matching "$1" variables, but different uses of the feature will have
219 # different restrictions, which should be checked *after* the MagicWord has been matched,
223 foreach ( $this->mSynonyms
as $synonym )
224 // In case a magic word contains /, like that's going to happen;)
225 $escSyn[] = preg_quote( $synonym, '/' );
226 $this->mBaseRegex
= implode( '|', $escSyn );
228 $case = $this->mCaseSensitive ?
'' : 'iu';
229 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
230 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
231 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
232 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
233 "/^(?:{$this->mBaseRegex})$/{$case}" );
237 * Gets a regex representing matching the word
239 function getRegex() {
240 if ($this->mRegex
== '' ) {
243 return $this->mRegex
;
247 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
248 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
249 * the complete expression
251 function getRegexCase() {
252 if ( $this->mRegex
=== '' )
255 return $this->mCaseSensitive ?
'' : 'iu';
259 * Gets a regex matching the word, if it is at the string start
261 function getRegexStart() {
262 if ($this->mRegex
== '' ) {
265 return $this->mRegexStart
;
269 * regex without the slashes and what not
271 function getBaseRegex() {
272 if ($this->mRegex
== '') {
275 return $this->mBaseRegex
;
279 * Returns true if the text contains the word
282 function match( $text ) {
283 return preg_match( $this->getRegex(), $text );
287 * Returns true if the text starts with the word
290 function matchStart( $text ) {
291 return preg_match( $this->getRegexStart(), $text );
295 * Returns NULL if there's no match, the value of $1 otherwise
296 * The return code is the matched string, if there's no variable
297 * part in the regex and the matched variable part ($1) if there
300 function matchVariableStartToEnd( $text ) {
302 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
303 if ( $matchcount == 0 ) {
306 # multiple matched parts (variable match); some will be empty because of
307 # synonyms. The variable will be the second non-empty one so remove any
308 # blank elements and re-sort the indices.
311 $matches = array_values(array_filter($matches));
313 if ( count($matches) == 1 ) { return $matches[0]; }
314 else { return $matches[1]; }
320 * Returns true if the text matches the word, and alters the
321 * input string, removing all instances of the word
323 function matchAndRemove( &$text ) {
324 $this->mFound
= false;
325 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
326 return $this->mFound
;
329 function matchStartAndRemove( &$text ) {
330 $this->mFound
= false;
331 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
332 return $this->mFound
;
336 * Used in matchAndRemove()
339 function pregRemoveAndRecord( ) {
340 $this->mFound
= true;
345 * Replaces the word with something else
347 function replace( $replacement, $subject, $limit=-1 ) {
348 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
349 $this->mModified
= !($res === $subject);
354 * Variable handling: {{SUBST:xxx}} style words
355 * Calls back a function to determine what to replace xxx with
356 * Input word must contain $1
358 function substituteCallback( $text, $callback ) {
359 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
360 $this->mModified
= !($res === $text);
365 * Matches the word, where $1 is a wildcard
367 function getVariableRegex() {
368 if ( $this->mVariableRegex
== '' ) {
371 return $this->mVariableRegex
;
375 * Matches the entire string, where $1 is a wildcard
377 function getVariableStartToEndRegex() {
378 if ( $this->mVariableStartToEndRegex
== '' ) {
381 return $this->mVariableStartToEndRegex
;
385 * Accesses the synonym list directly
387 function getSynonym( $i ) {
388 return $this->mSynonyms
[$i];
391 function getSynonyms() {
392 return $this->mSynonyms
;
396 * Returns true if the last call to replace() or substituteCallback()
397 * returned a modified text, otherwise false.
399 function getWasModified(){
400 return $this->mModified
;
404 * $magicarr is an associative array of (magic word ID => replacement)
405 * This method uses the php feature to do several replacements at the same time,
406 * thereby gaining some efficiency. The result is placed in the out variable
407 * $result. The return value is true if something was replaced.
410 function replaceMultiple( $magicarr, $subject, &$result ){
413 foreach( $magicarr as $id => $replacement ){
414 $mw = MagicWord
::get( $id );
415 $search[] = $mw->getRegex();
416 $replace[] = $replacement;
419 $result = preg_replace( $search, $replace, $subject );
420 return !($result === $subject);
424 * Adds all the synonyms of this MagicWord to an array, to allow quick
425 * lookup in a list of magic words
427 function addToArray( &$array, $value ) {
429 foreach ( $this->mSynonyms
as $syn ) {
430 $array[$wgContLang->lc($syn)] = $value;
434 function isCaseSensitive() {
435 return $this->mCaseSensitive
;
444 * Class for handling an array of magic words
446 class MagicWordArray
{
447 var $names = array();
449 var $baseRegex, $regex;
451 function __construct( $names = array() ) {
452 $this->names
= $names;
456 * Add a magic word by name
458 public function add( $name ) {
460 $this->names
[] = $name;
461 $this->hash
= $this->baseRegex
= $this->regex
= null;
465 * Add a number of magic words by name
467 public function addArray( $names ) {
468 $this->names
= array_merge( $this->names
, array_values( $names ) );
469 $this->hash
= $this->baseRegex
= $this->regex
= null;
473 * Get a 2-d hashtable for this array
476 if ( is_null( $this->hash
) ) {
478 $this->hash
= array( 0 => array(), 1 => array() );
479 foreach ( $this->names
as $name ) {
480 $magic = MagicWord
::get( $name );
481 $case = intval( $magic->isCaseSensitive() );
482 foreach ( $magic->getSynonyms() as $syn ) {
484 $syn = $wgContLang->lc( $syn );
486 $this->hash
[$case][$syn] = $name;
496 function getBaseRegex() {
497 if ( is_null( $this->baseRegex
) ) {
498 $this->baseRegex
= array( 0 => '', 1 => '' );
499 foreach ( $this->names
as $name ) {
500 $magic = MagicWord
::get( $name );
501 $case = intval( $magic->isCaseSensitive() );
502 foreach ( $magic->getSynonyms() as $i => $syn ) {
503 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
504 if ( $this->baseRegex
[$case] === '' ) {
505 $this->baseRegex
[$case] = $group;
507 $this->baseRegex
[$case] .= '|' . $group;
512 return $this->baseRegex
;
516 * Get an unanchored regex
518 function getRegex() {
519 if ( is_null( $this->regex
) ) {
520 $base = $this->getBaseRegex();
521 $this->regex
= array( '', '' );
522 if ( $this->baseRegex
[0] !== '' ) {
523 $this->regex
[0] = "/{$base[0]}/iuS";
525 if ( $this->baseRegex
[1] !== '' ) {
526 $this->regex
[1] = "/{$base[1]}/S";
533 * Get a regex for matching variables
535 function getVariableRegex() {
536 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
540 * Get an anchored regex for matching variables
542 function getVariableStartToEndRegex() {
543 $base = $this->getBaseRegex();
544 $newRegex = array( '', '' );
545 if ( $base[0] !== '' ) {
546 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
548 if ( $base[1] !== '' ) {
549 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
555 * Parse a match array from preg_match
557 function parseMatch( $m ) {
559 while ( list( $key, $value ) = each( $m ) ) {
560 if ( $key === 0 ||
$value === '' ) {
563 $parts = explode( '_', $key, 2 );
564 if ( count( $parts ) != 2 ) {
565 // This shouldn't happen
567 throw new MWException( __METHOD__
. ': bad parameter name' );
569 list( /* $synIndex */, $magicName ) = $parts;
570 $paramValue = next( $m );
571 return array( $magicName, $paramValue );
573 // This shouldn't happen either
574 throw new MWException( __METHOD__
.': parameter not found' );
575 return array( false, false );
579 * Match some text, with parameter capture
580 * Returns an array with the magic word name in the first element and the
581 * parameter in the second element.
582 * Both elements are false if there was no match.
584 public function matchVariableStartToEnd( $text ) {
586 $regexes = $this->getVariableStartToEndRegex();
587 foreach ( $regexes as $regex ) {
588 if ( $regex !== '' ) {
590 if ( preg_match( $regex, $text, $m ) ) {
591 return $this->parseMatch( $m );
595 return array( false, false );
599 * Match some text, without parameter capture
600 * Returns the magic word name, or false if there was no capture
602 public function matchStartToEnd( $text ) {
603 $hash = $this->getHash();
604 if ( isset( $hash[1][$text] ) ) {
605 return $hash[1][$text];
608 $lc = $wgContLang->lc( $text );
609 if ( isset( $hash[0][$lc] ) ) {
610 return $hash[0][$lc];