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 $magicWords in a file listed in
24 * $wgExtensionMessagesFiles[].
28 * $magicWords = array();
30 * $magicWords['en'] = array(
31 * 'magicwordkey' => array( 0, 'case_insensitive_magic_word' ),
32 * 'magicwordkey2' => array( 1, 'CASE_sensitive_magic_word2' ),
35 * For magic words which are also Parser variables, add a MagicWordwgVariableIDs
36 * hook. Use string keys.
44 var $mId, $mSynonyms, $mCaseSensitive;
46 var $mRegexStart = '';
48 var $mVariableRegex = '';
49 var $mVariableStartToEndRegex = '';
50 var $mModified = false;
53 static public $mVariableIDsInitialised = false;
54 static public $mVariableIDs = array(
58 'currentmonthnamegen',
115 'numberofactiveusers',
128 /* Array of caching hints for ParserCache */
129 static public $mCacheTTLs = array (
130 'currentmonth' => 86400,
131 'currentmonth1' => 86400,
132 'currentmonthname' => 86400,
133 'currentmonthnamegen' => 86400,
134 'currentmonthabbrev' => 86400,
135 'currentday' => 3600,
136 'currentday2' => 3600,
137 'currentdayname' => 3600,
138 'currentyear' => 86400,
139 'currenttime' => 3600,
140 'currenthour' => 3600,
141 'localmonth' => 86400,
142 'localmonth1' => 86400,
143 'localmonthname' => 86400,
144 'localmonthnamegen' => 86400,
145 'localmonthabbrev' => 86400,
148 'localdayname' => 3600,
149 'localyear' => 86400,
152 'numberofarticles' => 3600,
153 'numberoffiles' => 3600,
154 'numberofedits' => 3600,
155 'currentweek' => 3600,
156 'currentdow' => 3600,
159 'numberofusers' => 3600,
160 'numberofactiveusers' => 3600,
161 'numberofpages' => 3600,
162 'currentversion' => 86400,
163 'currenttimestamp' => 3600,
164 'localtimestamp' => 3600,
165 'pagesinnamespace' => 3600,
166 'numberofadmins' => 3600,
167 'numberofviews' => 3600,
168 'numberingroup' => 3600,
171 static public $mDoubleUnderscoreIDs = array(
187 static public $mSubstIDs = array(
192 static public $mObjects = array();
193 static public $mDoubleUnderscoreArray = null;
197 function __construct($id = 0, $syn = array(), $cs = false) {
199 $this->mSynonyms
= (array)$syn;
200 $this->mCaseSensitive
= $cs;
204 * Factory: creates an object representing an ID
210 static function &get( $id ) {
211 if ( !isset( self
::$mObjects[$id] ) ) {
212 $mw = new MagicWord();
214 self
::$mObjects[$id] = $mw;
216 return self
::$mObjects[$id];
220 * Get an array of parser variable IDs
224 static function getVariableIDs() {
225 if ( !self
::$mVariableIDsInitialised ) {
227 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
228 self
::$mVariableIDsInitialised = true;
230 return self
::$mVariableIDs;
234 * Get an array of parser substitution modifier IDs
237 static function getSubstIDs() {
238 return self
::$mSubstIDs;
242 * Allow external reads of TTL array
247 static function getCacheTTL( $id ) {
248 if ( array_key_exists( $id, self
::$mCacheTTLs ) ) {
249 return self
::$mCacheTTLs[$id];
256 * Get a MagicWordArray of double-underscore entities
258 * @return MagicWordArray
260 static function getDoubleUnderscoreArray() {
261 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
262 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
264 return self
::$mDoubleUnderscoreArray;
268 * Clear the self::$mObjects variable
269 * For use in parser tests
271 public static function clearCache() {
272 self
::$mObjects = array();
276 * Initialises this object with an ID
280 function load( $id ) {
282 wfProfileIn( __METHOD__
);
284 $wgContLang->getMagic( $this );
285 if ( !$this->mSynonyms
) {
286 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
287 #throw new MWException( "Error: invalid magic word '$id'" );
288 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
290 wfProfileOut( __METHOD__
);
294 * Preliminary initialisation
297 function initRegex() {
298 // Sort the synonyms by length, descending, so that the longest synonym
299 // matches in precedence to the shortest
300 $synonyms = $this->mSynonyms
;
301 usort( $synonyms, array( $this, 'compareStringLength' ) );
304 foreach ( $synonyms as $synonym )
305 // In case a magic word contains /, like that's going to happen;)
306 $escSyn[] = preg_quote( $synonym, '/' );
307 $this->mBaseRegex
= implode( '|', $escSyn );
309 $case = $this->mCaseSensitive ?
'' : 'iu';
310 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
311 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
312 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
313 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
314 "/^(?:{$this->mBaseRegex})$/{$case}" );
318 * A comparison function that returns -1, 0 or 1 depending on whether the
319 * first string is longer, the same length or shorter than the second
327 function compareStringLength( $s1, $s2 ) {
332 } elseif ( $l1 > $l2 ) {
340 * Gets a regex representing matching the word
344 function getRegex() {
345 if ($this->mRegex
== '' ) {
348 return $this->mRegex
;
352 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
353 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
354 * the complete expression
358 function getRegexCase() {
359 if ( $this->mRegex
=== '' )
362 return $this->mCaseSensitive ?
'' : 'iu';
366 * Gets a regex matching the word, if it is at the string start
370 function getRegexStart() {
371 if ($this->mRegex
== '' ) {
374 return $this->mRegexStart
;
378 * regex without the slashes and what not
382 function getBaseRegex() {
383 if ($this->mRegex
== '') {
386 return $this->mBaseRegex
;
390 * Returns true if the text contains the word
392 * @param $text string
396 function match( $text ) {
397 return (bool)preg_match( $this->getRegex(), $text );
401 * Returns true if the text starts with the word
403 * @param $text string
407 function matchStart( $text ) {
408 return (bool)preg_match( $this->getRegexStart(), $text );
412 * Returns NULL if there's no match, the value of $1 otherwise
413 * The return code is the matched string, if there's no variable
414 * part in the regex and the matched variable part ($1) if there
417 * @param $text string
421 function matchVariableStartToEnd( $text ) {
423 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
424 if ( $matchcount == 0 ) {
427 # multiple matched parts (variable match); some will be empty because of
428 # synonyms. The variable will be the second non-empty one so remove any
429 # blank elements and re-sort the indices.
432 $matches = array_values(array_filter($matches));
434 if ( count($matches) == 1 ) {
444 * Returns true if the text matches the word, and alters the
445 * input string, removing all instances of the word
447 * @param $text string
451 function matchAndRemove( &$text ) {
452 $this->mFound
= false;
453 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
454 return $this->mFound
;
461 function matchStartAndRemove( &$text ) {
462 $this->mFound
= false;
463 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
464 return $this->mFound
;
468 * Used in matchAndRemove()
472 function pregRemoveAndRecord() {
473 $this->mFound
= true;
478 * Replaces the word with something else
480 * @param $replacement
486 function replace( $replacement, $subject, $limit = -1 ) {
487 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
488 $this->mModified
= !($res === $subject);
493 * Variable handling: {{SUBST:xxx}} style words
494 * Calls back a function to determine what to replace xxx with
495 * Input word must contain $1
497 * @param $text string
502 function substituteCallback( $text, $callback ) {
503 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
504 $this->mModified
= !($res === $text);
509 * Matches the word, where $1 is a wildcard
513 function getVariableRegex() {
514 if ( $this->mVariableRegex
== '' ) {
517 return $this->mVariableRegex
;
521 * Matches the entire string, where $1 is a wildcard
525 function getVariableStartToEndRegex() {
526 if ( $this->mVariableStartToEndRegex
== '' ) {
529 return $this->mVariableStartToEndRegex
;
533 * Accesses the synonym list directly
539 function getSynonym( $i ) {
540 return $this->mSynonyms
[$i];
546 function getSynonyms() {
547 return $this->mSynonyms
;
551 * Returns true if the last call to replace() or substituteCallback()
552 * returned a modified text, otherwise false.
556 function getWasModified(){
557 return $this->mModified
;
561 * $magicarr is an associative array of (magic word ID => replacement)
562 * This method uses the php feature to do several replacements at the same time,
563 * thereby gaining some efficiency. The result is placed in the out variable
564 * $result. The return value is true if something was replaced.
565 * @todo Should this be static? It doesn't seem to be used at all
573 function replaceMultiple( $magicarr, $subject, &$result ){
576 foreach( $magicarr as $id => $replacement ){
577 $mw = MagicWord
::get( $id );
578 $search[] = $mw->getRegex();
579 $replace[] = $replacement;
582 $result = preg_replace( $search, $replace, $subject );
583 return !($result === $subject);
587 * Adds all the synonyms of this MagicWord to an array, to allow quick
588 * lookup in a list of magic words
593 function addToArray( &$array, $value ) {
595 foreach ( $this->mSynonyms
as $syn ) {
596 $array[$wgContLang->lc($syn)] = $value;
603 function isCaseSensitive() {
604 return $this->mCaseSensitive
;
616 * Class for handling an array of magic words
619 class MagicWordArray
{
620 var $names = array();
622 var $baseRegex, $regex;
625 function __construct( $names = array() ) {
626 $this->names
= $names;
630 * Add a magic word by name
632 * @param $name string
634 public function add( $name ) {
635 $this->names
[] = $name;
636 $this->hash
= $this->baseRegex
= $this->regex
= null;
640 * Add a number of magic words by name
642 * @param $names array
644 public function addArray( $names ) {
645 $this->names
= array_merge( $this->names
, array_values( $names ) );
646 $this->hash
= $this->baseRegex
= $this->regex
= null;
650 * Get a 2-d hashtable for this array
653 if ( is_null( $this->hash
) ) {
655 $this->hash
= array( 0 => array(), 1 => array() );
656 foreach ( $this->names
as $name ) {
657 $magic = MagicWord
::get( $name );
658 $case = intval( $magic->isCaseSensitive() );
659 foreach ( $magic->getSynonyms() as $syn ) {
661 $syn = $wgContLang->lc( $syn );
663 $this->hash
[$case][$syn] = $name;
673 function getBaseRegex() {
674 if ( is_null( $this->baseRegex
) ) {
675 $this->baseRegex
= array( 0 => '', 1 => '' );
676 foreach ( $this->names
as $name ) {
677 $magic = MagicWord
::get( $name );
678 $case = intval( $magic->isCaseSensitive() );
679 foreach ( $magic->getSynonyms() as $i => $syn ) {
680 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
681 if ( $this->baseRegex
[$case] === '' ) {
682 $this->baseRegex
[$case] = $group;
684 $this->baseRegex
[$case] .= '|' . $group;
689 return $this->baseRegex
;
693 * Get an unanchored regex that does not match parameters
695 function getRegex() {
696 if ( is_null( $this->regex
) ) {
697 $base = $this->getBaseRegex();
698 $this->regex
= array( '', '' );
699 if ( $this->baseRegex
[0] !== '' ) {
700 $this->regex
[0] = "/{$base[0]}/iuS";
702 if ( $this->baseRegex
[1] !== '' ) {
703 $this->regex
[1] = "/{$base[1]}/S";
710 * Get a regex for matching variables with parameters
714 function getVariableRegex() {
715 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
719 * Get a regex anchored to the start of the string that does not match parameters
723 function getRegexStart() {
724 $base = $this->getBaseRegex();
725 $newRegex = array( '', '' );
726 if ( $base[0] !== '' ) {
727 $newRegex[0] = "/^(?:{$base[0]})/iuS";
729 if ( $base[1] !== '' ) {
730 $newRegex[1] = "/^(?:{$base[1]})/S";
736 * Get an anchored regex for matching variables with parameters
740 function getVariableStartToEndRegex() {
741 $base = $this->getBaseRegex();
742 $newRegex = array( '', '' );
743 if ( $base[0] !== '' ) {
744 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
746 if ( $base[1] !== '' ) {
747 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
753 * Parse a match array from preg_match
754 * Returns array(magic word ID, parameter value)
755 * If there is no parameter value, that element will be false.
761 function parseMatch( $m ) {
763 while ( list( $key, $value ) = each( $m ) ) {
764 if ( $key === 0 ||
$value === '' ) {
767 $parts = explode( '_', $key, 2 );
768 if ( count( $parts ) != 2 ) {
769 // This shouldn't happen
771 throw new MWException( __METHOD__
. ': bad parameter name' );
773 list( /* $synIndex */, $magicName ) = $parts;
774 $paramValue = next( $m );
775 return array( $magicName, $paramValue );
777 // This shouldn't happen either
778 throw new MWException( __METHOD__
.': parameter not found' );
782 * Match some text, with parameter capture
783 * Returns an array with the magic word name in the first element and the
784 * parameter in the second element.
785 * Both elements are false if there was no match.
787 * @param $text string
791 public function matchVariableStartToEnd( $text ) {
792 $regexes = $this->getVariableStartToEndRegex();
793 foreach ( $regexes as $regex ) {
794 if ( $regex !== '' ) {
796 if ( preg_match( $regex, $text, $m ) ) {
797 return $this->parseMatch( $m );
801 return array( false, false );
805 * Match some text, without parameter capture
806 * Returns the magic word name, or false if there was no capture
808 * @param $text string
810 * @return string|false
812 public function matchStartToEnd( $text ) {
813 $hash = $this->getHash();
814 if ( isset( $hash[1][$text] ) ) {
815 return $hash[1][$text];
818 $lc = $wgContLang->lc( $text );
819 if ( isset( $hash[0][$lc] ) ) {
820 return $hash[0][$lc];
826 * Returns an associative array, ID => param value, for all items that match
827 * Removes the matched items from the input string (passed by reference)
829 * @param $text string
833 public function matchAndRemove( &$text ) {
835 $regexes = $this->getRegex();
836 foreach ( $regexes as $regex ) {
837 if ( $regex === '' ) {
840 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
841 foreach ( $matches as $m ) {
842 list( $name, $param ) = $this->parseMatch( $m );
843 $found[$name] = $param;
845 $text = preg_replace( $regex, '', $text );
851 * Return the ID of the magic word at the start of $text, and remove
852 * the prefix from $text.
853 * Return false if no match found and $text is not modified.
854 * Does not match parameters.
856 * @param $text string
860 public function matchStartAndRemove( &$text ) {
861 $regexes = $this->getRegexStart();
862 foreach ( $regexes as $regex ) {
863 if ( $regex === '' ) {
866 if ( preg_match( $regex, $text, $m ) ) {
867 list( $id, ) = $this->parseMatch( $m );
868 if ( strlen( $m[0] ) >= strlen( $text ) ) {
871 $text = substr( $text, strlen( $m[0] ) );