5 * See docs/magicword.txt
12 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
14 * if (MagicWord::get( 'redirect' )->match( $text ) )
16 * Possible future improvements:
17 * * Simultaneous searching for a number of magic words
18 * * MagicWord::$mObjects in shared memory
20 * Please avoid reading the data out of one of these objects and then writing
21 * special case code. If possible, add another match()-like function here.
23 * To add magic words in an extension, use the LanguageGetMagic hook. For
24 * magic words which are also Parser variables, add a MagicWordwgVariableIDs
25 * hook. Use string keys.
33 var $mId, $mSynonyms, $mCaseSensitive;
35 var $mRegexStart = '';
37 var $mVariableRegex = '';
38 var $mVariableStartToEndRegex = '';
39 var $mModified = false;
42 static public $mVariableIDsInitialised = false;
43 static public $mVariableIDs = array(
47 'currentmonthnamegen',
105 'numberofactiveusers',
118 /* Array of caching hints for ParserCache */
119 static public $mCacheTTLs = array (
120 'currentmonth' => 86400,
121 'currentmonth1' => 86400,
122 'currentmonthname' => 86400,
123 'currentmonthnamegen' => 86400,
124 'currentmonthabbrev' => 86400,
125 'currentday' => 3600,
126 'currentday2' => 3600,
127 'currentdayname' => 3600,
128 'currentyear' => 86400,
129 'currenttime' => 3600,
130 'currenthour' => 3600,
131 'localmonth' => 86400,
132 'localmonth1' => 86400,
133 'localmonthname' => 86400,
134 'localmonthnamegen' => 86400,
135 'localmonthabbrev' => 86400,
138 'localdayname' => 3600,
139 'localyear' => 86400,
142 'numberofarticles' => 3600,
143 'numberoffiles' => 3600,
144 'numberofedits' => 3600,
145 'currentweek' => 3600,
146 'currentdow' => 3600,
149 'numberofusers' => 3600,
150 'numberofactiveusers' => 3600,
151 'numberofpages' => 3600,
152 'currentversion' => 86400,
153 'currenttimestamp' => 3600,
154 'localtimestamp' => 3600,
155 'pagesinnamespace' => 3600,
156 'numberofadmins' => 3600,
157 'numberofviews' => 3600,
158 'numberingroup' => 3600,
161 static public $mDoubleUnderscoreIDs = array(
177 static public $mSubstIDs = array(
182 static public $mObjects = array();
183 static public $mDoubleUnderscoreArray = null;
187 function __construct($id = 0, $syn = array(), $cs = false) {
189 $this->mSynonyms
= (array)$syn;
190 $this->mCaseSensitive
= $cs;
194 * Factory: creates an object representing an ID
200 static function &get( $id ) {
201 if ( !isset( self
::$mObjects[$id] ) ) {
202 $mw = new MagicWord();
204 self
::$mObjects[$id] = $mw;
206 return self
::$mObjects[$id];
210 * Get an array of parser variable IDs
214 static function getVariableIDs() {
215 if ( !self
::$mVariableIDsInitialised ) {
216 # Deprecated constant definition hook, available for extensions that need it
217 $magicWords = array();
218 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
219 foreach ( $magicWords as $word ) {
220 define( $word, $word );
224 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
225 self
::$mVariableIDsInitialised = true;
227 return self
::$mVariableIDs;
231 * Get an array of parser substitution modifier IDs
234 static function getSubstIDs() {
235 return self
::$mSubstIDs;
239 * Allow external reads of TTL array
244 static function getCacheTTL( $id ) {
245 if ( array_key_exists( $id, self
::$mCacheTTLs ) ) {
246 return self
::$mCacheTTLs[$id];
253 * Get a MagicWordArray of double-underscore entities
255 * @return MagicWordArray
257 static function getDoubleUnderscoreArray() {
258 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
259 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
261 return self
::$mDoubleUnderscoreArray;
265 * Clear the self::$mObjects variable
266 * For use in parser tests
268 public static function clearCache() {
269 self
::$mObjects = array();
273 * Initialises this object with an ID
277 function load( $id ) {
279 wfProfileIn( __METHOD__
);
281 $wgContLang->getMagic( $this );
282 if ( !$this->mSynonyms
) {
283 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
284 #throw new MWException( "Error: invalid magic word '$id'" );
285 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
287 wfProfileOut( __METHOD__
);
291 * Preliminary initialisation
294 function initRegex() {
295 // Sort the synonyms by length, descending, so that the longest synonym
296 // matches in precedence to the shortest
297 $synonyms = $this->mSynonyms
;
298 usort( $synonyms, array( $this, 'compareStringLength' ) );
301 foreach ( $synonyms as $synonym )
302 // In case a magic word contains /, like that's going to happen;)
303 $escSyn[] = preg_quote( $synonym, '/' );
304 $this->mBaseRegex
= implode( '|', $escSyn );
306 $case = $this->mCaseSensitive ?
'' : 'iu';
307 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
308 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
309 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
310 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
311 "/^(?:{$this->mBaseRegex})$/{$case}" );
315 * A comparison function that returns -1, 0 or 1 depending on whether the
316 * first string is longer, the same length or shorter than the second
324 function compareStringLength( $s1, $s2 ) {
329 } elseif ( $l1 > $l2 ) {
337 * Gets a regex representing matching the word
341 function getRegex() {
342 if ($this->mRegex
== '' ) {
345 return $this->mRegex
;
349 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
350 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
351 * the complete expression
355 function getRegexCase() {
356 if ( $this->mRegex
=== '' )
359 return $this->mCaseSensitive ?
'' : 'iu';
363 * Gets a regex matching the word, if it is at the string start
367 function getRegexStart() {
368 if ($this->mRegex
== '' ) {
371 return $this->mRegexStart
;
375 * regex without the slashes and what not
379 function getBaseRegex() {
380 if ($this->mRegex
== '') {
383 return $this->mBaseRegex
;
387 * Returns true if the text contains the word
389 * @param $text string
393 function match( $text ) {
394 return (bool)preg_match( $this->getRegex(), $text );
398 * Returns true if the text starts with the word
400 * @param $text string
404 function matchStart( $text ) {
405 return (bool)preg_match( $this->getRegexStart(), $text );
409 * Returns NULL if there's no match, the value of $1 otherwise
410 * The return code is the matched string, if there's no variable
411 * part in the regex and the matched variable part ($1) if there
414 * @param $text string
418 function matchVariableStartToEnd( $text ) {
420 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
421 if ( $matchcount == 0 ) {
424 # multiple matched parts (variable match); some will be empty because of
425 # synonyms. The variable will be the second non-empty one so remove any
426 # blank elements and re-sort the indices.
429 $matches = array_values(array_filter($matches));
431 if ( count($matches) == 1 ) {
441 * Returns true if the text matches the word, and alters the
442 * input string, removing all instances of the word
444 * @param $text string
448 function matchAndRemove( &$text ) {
449 $this->mFound
= false;
450 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
451 return $this->mFound
;
458 function matchStartAndRemove( &$text ) {
459 $this->mFound
= false;
460 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
461 return $this->mFound
;
465 * Used in matchAndRemove()
469 function pregRemoveAndRecord() {
470 $this->mFound
= true;
475 * Replaces the word with something else
477 * @param $replacement
483 function replace( $replacement, $subject, $limit = -1 ) {
484 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
485 $this->mModified
= !($res === $subject);
490 * Variable handling: {{SUBST:xxx}} style words
491 * Calls back a function to determine what to replace xxx with
492 * Input word must contain $1
494 * @param $text string
499 function substituteCallback( $text, $callback ) {
500 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
501 $this->mModified
= !($res === $text);
506 * Matches the word, where $1 is a wildcard
510 function getVariableRegex() {
511 if ( $this->mVariableRegex
== '' ) {
514 return $this->mVariableRegex
;
518 * Matches the entire string, where $1 is a wildcard
522 function getVariableStartToEndRegex() {
523 if ( $this->mVariableStartToEndRegex
== '' ) {
526 return $this->mVariableStartToEndRegex
;
530 * Accesses the synonym list directly
536 function getSynonym( $i ) {
537 return $this->mSynonyms
[$i];
543 function getSynonyms() {
544 return $this->mSynonyms
;
548 * Returns true if the last call to replace() or substituteCallback()
549 * returned a modified text, otherwise false.
553 function getWasModified(){
554 return $this->mModified
;
558 * $magicarr is an associative array of (magic word ID => replacement)
559 * This method uses the php feature to do several replacements at the same time,
560 * thereby gaining some efficiency. The result is placed in the out variable
561 * $result. The return value is true if something was replaced.
562 * @todo Should this be static? It doesn't seem to be used at all
570 function replaceMultiple( $magicarr, $subject, &$result ){
573 foreach( $magicarr as $id => $replacement ){
574 $mw = MagicWord
::get( $id );
575 $search[] = $mw->getRegex();
576 $replace[] = $replacement;
579 $result = preg_replace( $search, $replace, $subject );
580 return !($result === $subject);
584 * Adds all the synonyms of this MagicWord to an array, to allow quick
585 * lookup in a list of magic words
590 function addToArray( &$array, $value ) {
592 foreach ( $this->mSynonyms
as $syn ) {
593 $array[$wgContLang->lc($syn)] = $value;
600 function isCaseSensitive() {
601 return $this->mCaseSensitive
;
613 * Class for handling an array of magic words
616 class MagicWordArray
{
617 var $names = array();
619 var $baseRegex, $regex;
622 function __construct( $names = array() ) {
623 $this->names
= $names;
627 * Add a magic word by name
629 * @param $name string
631 public function add( $name ) {
632 $this->names
[] = $name;
633 $this->hash
= $this->baseRegex
= $this->regex
= null;
637 * Add a number of magic words by name
639 * @param $names array
641 public function addArray( $names ) {
642 $this->names
= array_merge( $this->names
, array_values( $names ) );
643 $this->hash
= $this->baseRegex
= $this->regex
= null;
647 * Get a 2-d hashtable for this array
650 if ( is_null( $this->hash
) ) {
652 $this->hash
= array( 0 => array(), 1 => array() );
653 foreach ( $this->names
as $name ) {
654 $magic = MagicWord
::get( $name );
655 $case = intval( $magic->isCaseSensitive() );
656 foreach ( $magic->getSynonyms() as $syn ) {
658 $syn = $wgContLang->lc( $syn );
660 $this->hash
[$case][$syn] = $name;
670 function getBaseRegex() {
671 if ( is_null( $this->baseRegex
) ) {
672 $this->baseRegex
= array( 0 => '', 1 => '' );
673 foreach ( $this->names
as $name ) {
674 $magic = MagicWord
::get( $name );
675 $case = intval( $magic->isCaseSensitive() );
676 foreach ( $magic->getSynonyms() as $i => $syn ) {
677 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
678 if ( $this->baseRegex
[$case] === '' ) {
679 $this->baseRegex
[$case] = $group;
681 $this->baseRegex
[$case] .= '|' . $group;
686 return $this->baseRegex
;
690 * Get an unanchored regex that does not match parameters
692 function getRegex() {
693 if ( is_null( $this->regex
) ) {
694 $base = $this->getBaseRegex();
695 $this->regex
= array( '', '' );
696 if ( $this->baseRegex
[0] !== '' ) {
697 $this->regex
[0] = "/{$base[0]}/iuS";
699 if ( $this->baseRegex
[1] !== '' ) {
700 $this->regex
[1] = "/{$base[1]}/S";
707 * Get a regex for matching variables with parameters
711 function getVariableRegex() {
712 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
716 * Get a regex anchored to the start of the string that does not match parameters
720 function getRegexStart() {
721 $base = $this->getBaseRegex();
722 $newRegex = array( '', '' );
723 if ( $base[0] !== '' ) {
724 $newRegex[0] = "/^(?:{$base[0]})/iuS";
726 if ( $base[1] !== '' ) {
727 $newRegex[1] = "/^(?:{$base[1]})/S";
733 * Get an anchored regex for matching variables with parameters
737 function getVariableStartToEndRegex() {
738 $base = $this->getBaseRegex();
739 $newRegex = array( '', '' );
740 if ( $base[0] !== '' ) {
741 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
743 if ( $base[1] !== '' ) {
744 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
750 * Parse a match array from preg_match
751 * Returns array(magic word ID, parameter value)
752 * If there is no parameter value, that element will be false.
758 function parseMatch( $m ) {
760 while ( list( $key, $value ) = each( $m ) ) {
761 if ( $key === 0 ||
$value === '' ) {
764 $parts = explode( '_', $key, 2 );
765 if ( count( $parts ) != 2 ) {
766 // This shouldn't happen
768 throw new MWException( __METHOD__
. ': bad parameter name' );
770 list( /* $synIndex */, $magicName ) = $parts;
771 $paramValue = next( $m );
772 return array( $magicName, $paramValue );
774 // This shouldn't happen either
775 throw new MWException( __METHOD__
.': parameter not found' );
779 * Match some text, with parameter capture
780 * Returns an array with the magic word name in the first element and the
781 * parameter in the second element.
782 * Both elements are false if there was no match.
784 * @param $text string
788 public function matchVariableStartToEnd( $text ) {
789 $regexes = $this->getVariableStartToEndRegex();
790 foreach ( $regexes as $regex ) {
791 if ( $regex !== '' ) {
793 if ( preg_match( $regex, $text, $m ) ) {
794 return $this->parseMatch( $m );
798 return array( false, false );
802 * Match some text, without parameter capture
803 * Returns the magic word name, or false if there was no capture
805 * @param $text string
807 * @return string|false
809 public function matchStartToEnd( $text ) {
810 $hash = $this->getHash();
811 if ( isset( $hash[1][$text] ) ) {
812 return $hash[1][$text];
815 $lc = $wgContLang->lc( $text );
816 if ( isset( $hash[0][$lc] ) ) {
817 return $hash[0][$lc];
823 * Returns an associative array, ID => param value, for all items that match
824 * Removes the matched items from the input string (passed by reference)
826 * @param $text string
830 public function matchAndRemove( &$text ) {
832 $regexes = $this->getRegex();
833 foreach ( $regexes as $regex ) {
834 if ( $regex === '' ) {
837 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
838 foreach ( $matches as $m ) {
839 list( $name, $param ) = $this->parseMatch( $m );
840 $found[$name] = $param;
842 $text = preg_replace( $regex, '', $text );
848 * Return the ID of the magic word at the start of $text, and remove
849 * the prefix from $text.
850 * Return false if no match found and $text is not modified.
851 * Does not match parameters.
853 * @param $text string
857 public function matchStartAndRemove( &$text ) {
858 $regexes = $this->getRegexStart();
859 foreach ( $regexes as $regex ) {
860 if ( $regex === '' ) {
863 if ( preg_match( $regex, $text, $m ) ) {
864 list( $id, ) = $this->parseMatch( $m );
865 if ( strlen( $m[0] ) >= strlen( $text ) ) {
868 $text = substr( $text, strlen( $m[0] ) );