3f208ea53d3bbacb448e5ee377f41c7664ce3617
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',
109 /* Array of caching hints for ParserCache */
110 static public $mCacheTTLs = array (
111 'currentmonth' => 86400,
112 'currentmonthname' => 86400,
113 'currentmonthnamegen' => 86400,
114 'currentmonthabbrev' => 86400,
115 'currentday' => 3600,
116 'currentday2' => 3600,
117 'currentdayname' => 3600,
118 'currentyear' => 86400,
119 'currenttime' => 3600,
120 'currenthour' => 3600,
121 'localmonth' => 86400,
122 'localmonthname' => 86400,
123 'localmonthnamegen' => 86400,
124 'localmonthabbrev' => 86400,
127 'localdayname' => 3600,
128 'localyear' => 86400,
131 'numberofarticles' => 3600,
132 'numberoffiles' => 3600,
133 'numberofedits' => 3600,
134 'currentweek' => 3600,
135 'currentdow' => 3600,
138 'numberofusers' => 3600,
139 'numberofpages' => 3600,
140 'currentversion' => 86400,
141 'currenttimestamp' => 3600,
142 'localtimestamp' => 3600,
143 'pagesinnamespace' => 3600,
144 'numberofadmins' => 3600,
147 static public $mObjects = array();
151 function __construct($id = 0, $syn = '', $cs = false) {
153 $this->mSynonyms
= (array)$syn;
154 $this->mCaseSensitive
= $cs;
156 $this->mRegexStart
= '';
157 $this->mVariableRegex
= '';
158 $this->mVariableStartToEndRegex
= '';
159 $this->mModified
= false;
163 * Factory: creates an object representing an ID
166 static function &get( $id ) {
167 wfProfileIn( __METHOD__
);
168 if (!array_key_exists( $id, self
::$mObjects ) ) {
169 $mw = new MagicWord();
171 self
::$mObjects[$id] = $mw;
173 wfProfileOut( __METHOD__
);
174 return self
::$mObjects[$id];
178 * Get an array of parser variable IDs
180 static function getVariableIDs() {
181 if ( !self
::$mVariableIDsInitialised ) {
182 # Deprecated constant definition hook, available for extensions that need it
183 $magicWords = array();
184 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
185 foreach ( $magicWords as $word ) {
186 define( $word, $word );
190 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
191 self
::$mVariableIDsInitialised = true;
193 return self
::$mVariableIDs;
196 /* Allow external reads of TTL array */
197 static function getCacheTTL($id) {
198 if (array_key_exists($id,self
::$mCacheTTLs)) {
199 return self
::$mCacheTTLs[$id];
206 # Initialises this object with an ID
207 function load( $id ) {
210 $wgContLang->getMagic( $this );
211 if ( !$this->mSynonyms
) {
212 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
213 #throw new MWException( "Error: invalid magic word '$id'" );
214 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
219 * Preliminary initialisation
222 function initRegex() {
223 #$variableClass = Title::legalChars();
224 # This was used for matching "$1" variables, but different uses of the feature will have
225 # different restrictions, which should be checked *after* the MagicWord has been matched,
229 foreach ( $this->mSynonyms
as $synonym )
230 // In case a magic word contains /, like that's going to happen;)
231 $escSyn[] = preg_quote( $synonym, '/' );
232 $this->mBaseRegex
= implode( '|', $escSyn );
234 $case = $this->mCaseSensitive ?
'' : 'iu';
235 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
236 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
237 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
238 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
239 "/^(?:{$this->mBaseRegex})$/{$case}" );
243 * Gets a regex representing matching the word
245 function getRegex() {
246 if ($this->mRegex
== '' ) {
249 return $this->mRegex
;
253 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
254 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
255 * the complete expression
257 function getRegexCase() {
258 if ( $this->mRegex
=== '' )
261 return $this->mCaseSensitive ?
'' : 'iu';
265 * Gets a regex matching the word, if it is at the string start
267 function getRegexStart() {
268 if ($this->mRegex
== '' ) {
271 return $this->mRegexStart
;
275 * regex without the slashes and what not
277 function getBaseRegex() {
278 if ($this->mRegex
== '') {
281 return $this->mBaseRegex
;
285 * Returns true if the text contains the word
288 function match( $text ) {
289 return preg_match( $this->getRegex(), $text );
293 * Returns true if the text starts with the word
296 function matchStart( $text ) {
297 return preg_match( $this->getRegexStart(), $text );
301 * Returns NULL if there's no match, the value of $1 otherwise
302 * The return code is the matched string, if there's no variable
303 * part in the regex and the matched variable part ($1) if there
306 function matchVariableStartToEnd( $text ) {
308 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
309 if ( $matchcount == 0 ) {
312 # multiple matched parts (variable match); some will be empty because of
313 # synonyms. The variable will be the second non-empty one so remove any
314 # blank elements and re-sort the indices.
317 $matches = array_values(array_filter($matches));
319 if ( count($matches) == 1 ) { return $matches[0]; }
320 else { return $matches[1]; }
326 * Returns true if the text matches the word, and alters the
327 * input string, removing all instances of the word
329 function matchAndRemove( &$text ) {
330 $this->mFound
= false;
331 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
332 return $this->mFound
;
335 function matchStartAndRemove( &$text ) {
336 $this->mFound
= false;
337 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
338 return $this->mFound
;
342 * Used in matchAndRemove()
345 function pregRemoveAndRecord( ) {
346 $this->mFound
= true;
351 * Replaces the word with something else
353 function replace( $replacement, $subject, $limit=-1 ) {
354 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
355 $this->mModified
= !($res === $subject);
360 * Variable handling: {{SUBST:xxx}} style words
361 * Calls back a function to determine what to replace xxx with
362 * Input word must contain $1
364 function substituteCallback( $text, $callback ) {
365 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
366 $this->mModified
= !($res === $text);
371 * Matches the word, where $1 is a wildcard
373 function getVariableRegex() {
374 if ( $this->mVariableRegex
== '' ) {
377 return $this->mVariableRegex
;
381 * Matches the entire string, where $1 is a wildcard
383 function getVariableStartToEndRegex() {
384 if ( $this->mVariableStartToEndRegex
== '' ) {
387 return $this->mVariableStartToEndRegex
;
391 * Accesses the synonym list directly
393 function getSynonym( $i ) {
394 return $this->mSynonyms
[$i];
397 function getSynonyms() {
398 return $this->mSynonyms
;
402 * Returns true if the last call to replace() or substituteCallback()
403 * returned a modified text, otherwise false.
405 function getWasModified(){
406 return $this->mModified
;
410 * $magicarr is an associative array of (magic word ID => replacement)
411 * This method uses the php feature to do several replacements at the same time,
412 * thereby gaining some efficiency. The result is placed in the out variable
413 * $result. The return value is true if something was replaced.
416 function replaceMultiple( $magicarr, $subject, &$result ){
419 foreach( $magicarr as $id => $replacement ){
420 $mw = MagicWord
::get( $id );
421 $search[] = $mw->getRegex();
422 $replace[] = $replacement;
425 $result = preg_replace( $search, $replace, $subject );
426 return !($result === $subject);
430 * Adds all the synonyms of this MagicWord to an array, to allow quick
431 * lookup in a list of magic words
433 function addToArray( &$array, $value ) {
435 foreach ( $this->mSynonyms
as $syn ) {
436 $array[$wgContLang->lc($syn)] = $value;
440 function isCaseSensitive() {
441 return $this->mCaseSensitive
;
450 * Class for handling an array of magic words
452 class MagicWordArray
{
453 var $names = array();
455 var $baseRegex, $regex;
457 function __construct( $names = array() ) {
458 $this->names
= $names;
462 * Add a magic word by name
464 public function add( $name ) {
466 $this->names
[] = $name;
467 $this->hash
= $this->baseRegex
= $this->regex
= null;
471 * Add a number of magic words by name
473 public function addArray( $names ) {
474 $this->names
= array_merge( $this->names
, array_values( $names ) );
475 $this->hash
= $this->baseRegex
= $this->regex
= null;
479 * Get a 2-d hashtable for this array
482 if ( is_null( $this->hash
) ) {
484 $this->hash
= array( 0 => array(), 1 => array() );
485 foreach ( $this->names
as $name ) {
486 $magic = MagicWord
::get( $name );
487 $case = intval( $magic->isCaseSensitive() );
488 foreach ( $magic->getSynonyms() as $syn ) {
490 $syn = $wgContLang->lc( $syn );
492 $this->hash
[$case][$syn] = $name;
502 function getBaseRegex() {
503 if ( is_null( $this->baseRegex
) ) {
504 $this->baseRegex
= array( 0 => '', 1 => '' );
505 foreach ( $this->names
as $name ) {
506 $magic = MagicWord
::get( $name );
507 $case = intval( $magic->isCaseSensitive() );
508 foreach ( $magic->getSynonyms() as $i => $syn ) {
509 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
510 if ( $this->baseRegex
[$case] === '' ) {
511 $this->baseRegex
[$case] = $group;
513 $this->baseRegex
[$case] .= '|' . $group;
518 return $this->baseRegex
;
522 * Get an unanchored regex
524 function getRegex() {
525 if ( is_null( $this->regex
) ) {
526 $base = $this->getBaseRegex();
527 $this->regex
= array( '', '' );
528 if ( $this->baseRegex
[0] !== '' ) {
529 $this->regex
[0] = "/{$base[0]}/iuS";
531 if ( $this->baseRegex
[1] !== '' ) {
532 $this->regex
[1] = "/{$base[1]}/S";
539 * Get a regex for matching variables
541 function getVariableRegex() {
542 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
546 * Get an anchored regex for matching variables
548 function getVariableStartToEndRegex() {
549 $base = $this->getBaseRegex();
550 $newRegex = array( '', '' );
551 if ( $base[0] !== '' ) {
552 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
554 if ( $base[1] !== '' ) {
555 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
561 * Parse a match array from preg_match
563 function parseMatch( $m ) {
565 while ( list( $key, $value ) = each( $m ) ) {
566 if ( $key === 0 ||
$value === '' ) {
569 $parts = explode( '_', $key, 2 );
570 if ( count( $parts ) != 2 ) {
571 // This shouldn't happen
573 throw new MWException( __METHOD__
. ': bad parameter name' );
575 list( /* $synIndex */, $magicName ) = $parts;
576 $paramValue = next( $m );
577 return array( $magicName, $paramValue );
579 // This shouldn't happen either
580 throw new MWException( __METHOD__
.': parameter not found' );
581 return array( false, false );
585 * Match some text, with parameter capture
586 * Returns an array with the magic word name in the first element and the
587 * parameter in the second element.
588 * Both elements are false if there was no match.
590 public function matchVariableStartToEnd( $text ) {
592 $regexes = $this->getVariableStartToEndRegex();
593 foreach ( $regexes as $regex ) {
594 if ( $regex !== '' ) {
596 if ( preg_match( $regex, $text, $m ) ) {
597 return $this->parseMatch( $m );
601 return array( false, false );
605 * Match some text, without parameter capture
606 * Returns the magic word name, or false if there was no capture
608 public function matchStartToEnd( $text ) {
609 $hash = $this->getHash();
610 if ( isset( $hash[1][$text] ) ) {
611 return $hash[1][$text];
614 $lc = $wgContLang->lc( $text );
615 if ( isset( $hash[0][$lc] ) ) {
616 return $hash[0][$lc];