5 * See docs/magicword.txt
12 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
16 * if (MagicWord::get( 'redirect' )->match( $text ) ) {
21 * Possible future improvements:
22 * * Simultaneous searching for a number of magic words
23 * * MagicWord::$mObjects in shared memory
25 * Please avoid reading the data out of one of these objects and then writing
26 * special case code. If possible, add another match()-like function here.
28 * To add magic words in an extension, use $magicWords in a file listed in
29 * $wgExtensionMessagesFiles[].
33 * $magicWords = array();
35 * $magicWords['en'] = array(
36 * 'magicwordkey' => array( 0, 'case_insensitive_magic_word' ),
37 * 'magicwordkey2' => array( 1, 'CASE_sensitive_magic_word2' ),
41 * For magic words which are also Parser variables, add a MagicWordwgVariableIDs
42 * hook. Use string keys.
50 var $mId, $mSynonyms, $mCaseSensitive;
52 var $mRegexStart = '';
54 var $mVariableRegex = '';
55 var $mVariableStartToEndRegex = '';
56 var $mModified = false;
59 static public $mVariableIDsInitialised = false;
60 static public $mVariableIDs = array(
64 'currentmonthnamegen',
121 'numberofactiveusers',
134 /* Array of caching hints for ParserCache */
135 static public $mCacheTTLs = array (
136 'currentmonth' => 86400,
137 'currentmonth1' => 86400,
138 'currentmonthname' => 86400,
139 'currentmonthnamegen' => 86400,
140 'currentmonthabbrev' => 86400,
141 'currentday' => 3600,
142 'currentday2' => 3600,
143 'currentdayname' => 3600,
144 'currentyear' => 86400,
145 'currenttime' => 3600,
146 'currenthour' => 3600,
147 'localmonth' => 86400,
148 'localmonth1' => 86400,
149 'localmonthname' => 86400,
150 'localmonthnamegen' => 86400,
151 'localmonthabbrev' => 86400,
154 'localdayname' => 3600,
155 'localyear' => 86400,
158 'numberofarticles' => 3600,
159 'numberoffiles' => 3600,
160 'numberofedits' => 3600,
161 'currentweek' => 3600,
162 'currentdow' => 3600,
165 'numberofusers' => 3600,
166 'numberofactiveusers' => 3600,
167 'numberofpages' => 3600,
168 'currentversion' => 86400,
169 'currenttimestamp' => 3600,
170 'localtimestamp' => 3600,
171 'pagesinnamespace' => 3600,
172 'numberofadmins' => 3600,
173 'numberofviews' => 3600,
174 'numberingroup' => 3600,
177 static public $mDoubleUnderscoreIDs = array(
193 static public $mSubstIDs = array(
198 static public $mObjects = array();
199 static public $mDoubleUnderscoreArray = null;
203 function __construct($id = 0, $syn = array(), $cs = false) {
205 $this->mSynonyms
= (array)$syn;
206 $this->mCaseSensitive
= $cs;
210 * Factory: creates an object representing an ID
216 static function &get( $id ) {
217 if ( !isset( self
::$mObjects[$id] ) ) {
218 $mw = new MagicWord();
220 self
::$mObjects[$id] = $mw;
222 return self
::$mObjects[$id];
226 * Get an array of parser variable IDs
230 static function getVariableIDs() {
231 if ( !self
::$mVariableIDsInitialised ) {
233 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
234 self
::$mVariableIDsInitialised = true;
236 return self
::$mVariableIDs;
240 * Get an array of parser substitution modifier IDs
243 static function getSubstIDs() {
244 return self
::$mSubstIDs;
248 * Allow external reads of TTL array
253 static function getCacheTTL( $id ) {
254 if ( array_key_exists( $id, self
::$mCacheTTLs ) ) {
255 return self
::$mCacheTTLs[$id];
262 * Get a MagicWordArray of double-underscore entities
264 * @return MagicWordArray
266 static function getDoubleUnderscoreArray() {
267 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
268 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
270 return self
::$mDoubleUnderscoreArray;
274 * Clear the self::$mObjects variable
275 * For use in parser tests
277 public static function clearCache() {
278 self
::$mObjects = array();
282 * Initialises this object with an ID
286 function load( $id ) {
288 wfProfileIn( __METHOD__
);
290 $wgContLang->getMagic( $this );
291 if ( !$this->mSynonyms
) {
292 $this->mSynonyms
= array( 'dkjsagfjsgashfajsh' );
293 #throw new MWException( "Error: invalid magic word '$id'" );
294 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
296 wfProfileOut( __METHOD__
);
300 * Preliminary initialisation
303 function initRegex() {
304 // Sort the synonyms by length, descending, so that the longest synonym
305 // matches in precedence to the shortest
306 $synonyms = $this->mSynonyms
;
307 usort( $synonyms, array( $this, 'compareStringLength' ) );
310 foreach ( $synonyms as $synonym )
311 // In case a magic word contains /, like that's going to happen;)
312 $escSyn[] = preg_quote( $synonym, '/' );
313 $this->mBaseRegex
= implode( '|', $escSyn );
315 $case = $this->mCaseSensitive ?
'' : 'iu';
316 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
317 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
318 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
319 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
320 "/^(?:{$this->mBaseRegex})$/{$case}" );
324 * A comparison function that returns -1, 0 or 1 depending on whether the
325 * first string is longer, the same length or shorter than the second
333 function compareStringLength( $s1, $s2 ) {
338 } elseif ( $l1 > $l2 ) {
346 * Gets a regex representing matching the word
350 function getRegex() {
351 if ($this->mRegex
== '' ) {
354 return $this->mRegex
;
358 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
359 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
360 * the complete expression
364 function getRegexCase() {
365 if ( $this->mRegex
=== '' )
368 return $this->mCaseSensitive ?
'' : 'iu';
372 * Gets a regex matching the word, if it is at the string start
376 function getRegexStart() {
377 if ($this->mRegex
== '' ) {
380 return $this->mRegexStart
;
384 * regex without the slashes and what not
388 function getBaseRegex() {
389 if ($this->mRegex
== '') {
392 return $this->mBaseRegex
;
396 * Returns true if the text contains the word
398 * @param $text string
402 function match( $text ) {
403 return (bool)preg_match( $this->getRegex(), $text );
407 * Returns true if the text starts with the word
409 * @param $text string
413 function matchStart( $text ) {
414 return (bool)preg_match( $this->getRegexStart(), $text );
418 * Returns NULL if there's no match, the value of $1 otherwise
419 * The return code is the matched string, if there's no variable
420 * part in the regex and the matched variable part ($1) if there
423 * @param $text string
427 function matchVariableStartToEnd( $text ) {
429 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
430 if ( $matchcount == 0 ) {
433 # multiple matched parts (variable match); some will be empty because of
434 # synonyms. The variable will be the second non-empty one so remove any
435 # blank elements and re-sort the indices.
438 $matches = array_values(array_filter($matches));
440 if ( count($matches) == 1 ) {
450 * Returns true if the text matches the word, and alters the
451 * input string, removing all instances of the word
453 * @param $text string
457 function matchAndRemove( &$text ) {
458 $this->mFound
= false;
459 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
460 return $this->mFound
;
467 function matchStartAndRemove( &$text ) {
468 $this->mFound
= false;
469 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
470 return $this->mFound
;
474 * Used in matchAndRemove()
478 function pregRemoveAndRecord() {
479 $this->mFound
= true;
484 * Replaces the word with something else
486 * @param $replacement
492 function replace( $replacement, $subject, $limit = -1 ) {
493 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
494 $this->mModified
= !($res === $subject);
499 * Variable handling: {{SUBST:xxx}} style words
500 * Calls back a function to determine what to replace xxx with
501 * Input word must contain $1
503 * @param $text string
508 function substituteCallback( $text, $callback ) {
509 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
510 $this->mModified
= !($res === $text);
515 * Matches the word, where $1 is a wildcard
519 function getVariableRegex() {
520 if ( $this->mVariableRegex
== '' ) {
523 return $this->mVariableRegex
;
527 * Matches the entire string, where $1 is a wildcard
531 function getVariableStartToEndRegex() {
532 if ( $this->mVariableStartToEndRegex
== '' ) {
535 return $this->mVariableStartToEndRegex
;
539 * Accesses the synonym list directly
545 function getSynonym( $i ) {
546 return $this->mSynonyms
[$i];
552 function getSynonyms() {
553 return $this->mSynonyms
;
557 * Returns true if the last call to replace() or substituteCallback()
558 * returned a modified text, otherwise false.
562 function getWasModified(){
563 return $this->mModified
;
567 * $magicarr is an associative array of (magic word ID => replacement)
568 * This method uses the php feature to do several replacements at the same time,
569 * thereby gaining some efficiency. The result is placed in the out variable
570 * $result. The return value is true if something was replaced.
571 * @todo Should this be static? It doesn't seem to be used at all
579 function replaceMultiple( $magicarr, $subject, &$result ){
582 foreach( $magicarr as $id => $replacement ){
583 $mw = MagicWord
::get( $id );
584 $search[] = $mw->getRegex();
585 $replace[] = $replacement;
588 $result = preg_replace( $search, $replace, $subject );
589 return !($result === $subject);
593 * Adds all the synonyms of this MagicWord to an array, to allow quick
594 * lookup in a list of magic words
599 function addToArray( &$array, $value ) {
601 foreach ( $this->mSynonyms
as $syn ) {
602 $array[$wgContLang->lc($syn)] = $value;
609 function isCaseSensitive() {
610 return $this->mCaseSensitive
;
622 * Class for handling an array of magic words
625 class MagicWordArray
{
626 var $names = array();
628 var $baseRegex, $regex;
631 function __construct( $names = array() ) {
632 $this->names
= $names;
636 * Add a magic word by name
638 * @param $name string
640 public function add( $name ) {
641 $this->names
[] = $name;
642 $this->hash
= $this->baseRegex
= $this->regex
= null;
646 * Add a number of magic words by name
648 * @param $names array
650 public function addArray( $names ) {
651 $this->names
= array_merge( $this->names
, array_values( $names ) );
652 $this->hash
= $this->baseRegex
= $this->regex
= null;
656 * Get a 2-d hashtable for this array
659 if ( is_null( $this->hash
) ) {
661 $this->hash
= array( 0 => array(), 1 => array() );
662 foreach ( $this->names
as $name ) {
663 $magic = MagicWord
::get( $name );
664 $case = intval( $magic->isCaseSensitive() );
665 foreach ( $magic->getSynonyms() as $syn ) {
667 $syn = $wgContLang->lc( $syn );
669 $this->hash
[$case][$syn] = $name;
679 function getBaseRegex() {
680 if ( is_null( $this->baseRegex
) ) {
681 $this->baseRegex
= array( 0 => '', 1 => '' );
682 foreach ( $this->names
as $name ) {
683 $magic = MagicWord
::get( $name );
684 $case = intval( $magic->isCaseSensitive() );
685 foreach ( $magic->getSynonyms() as $i => $syn ) {
686 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
687 if ( $this->baseRegex
[$case] === '' ) {
688 $this->baseRegex
[$case] = $group;
690 $this->baseRegex
[$case] .= '|' . $group;
695 return $this->baseRegex
;
699 * Get an unanchored regex that does not match parameters
701 function getRegex() {
702 if ( is_null( $this->regex
) ) {
703 $base = $this->getBaseRegex();
704 $this->regex
= array( '', '' );
705 if ( $this->baseRegex
[0] !== '' ) {
706 $this->regex
[0] = "/{$base[0]}/iuS";
708 if ( $this->baseRegex
[1] !== '' ) {
709 $this->regex
[1] = "/{$base[1]}/S";
716 * Get a regex for matching variables with parameters
720 function getVariableRegex() {
721 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
725 * Get a regex anchored to the start of the string that does not match parameters
729 function getRegexStart() {
730 $base = $this->getBaseRegex();
731 $newRegex = array( '', '' );
732 if ( $base[0] !== '' ) {
733 $newRegex[0] = "/^(?:{$base[0]})/iuS";
735 if ( $base[1] !== '' ) {
736 $newRegex[1] = "/^(?:{$base[1]})/S";
742 * Get an anchored regex for matching variables with parameters
746 function getVariableStartToEndRegex() {
747 $base = $this->getBaseRegex();
748 $newRegex = array( '', '' );
749 if ( $base[0] !== '' ) {
750 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
752 if ( $base[1] !== '' ) {
753 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
759 * Parse a match array from preg_match
760 * Returns array(magic word ID, parameter value)
761 * If there is no parameter value, that element will be false.
767 function parseMatch( $m ) {
769 while ( list( $key, $value ) = each( $m ) ) {
770 if ( $key === 0 ||
$value === '' ) {
773 $parts = explode( '_', $key, 2 );
774 if ( count( $parts ) != 2 ) {
775 // This shouldn't happen
777 throw new MWException( __METHOD__
. ': bad parameter name' );
779 list( /* $synIndex */, $magicName ) = $parts;
780 $paramValue = next( $m );
781 return array( $magicName, $paramValue );
783 // This shouldn't happen either
784 throw new MWException( __METHOD__
.': parameter not found' );
788 * Match some text, with parameter capture
789 * Returns an array with the magic word name in the first element and the
790 * parameter in the second element.
791 * Both elements are false if there was no match.
793 * @param $text string
797 public function matchVariableStartToEnd( $text ) {
798 $regexes = $this->getVariableStartToEndRegex();
799 foreach ( $regexes as $regex ) {
800 if ( $regex !== '' ) {
802 if ( preg_match( $regex, $text, $m ) ) {
803 return $this->parseMatch( $m );
807 return array( false, false );
811 * Match some text, without parameter capture
812 * Returns the magic word name, or false if there was no capture
814 * @param $text string
816 * @return string|bool False on failure
818 public function matchStartToEnd( $text ) {
819 $hash = $this->getHash();
820 if ( isset( $hash[1][$text] ) ) {
821 return $hash[1][$text];
824 $lc = $wgContLang->lc( $text );
825 if ( isset( $hash[0][$lc] ) ) {
826 return $hash[0][$lc];
832 * Returns an associative array, ID => param value, for all items that match
833 * Removes the matched items from the input string (passed by reference)
835 * @param $text string
839 public function matchAndRemove( &$text ) {
841 $regexes = $this->getRegex();
842 foreach ( $regexes as $regex ) {
843 if ( $regex === '' ) {
846 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
847 foreach ( $matches as $m ) {
848 list( $name, $param ) = $this->parseMatch( $m );
849 $found[$name] = $param;
851 $text = preg_replace( $regex, '', $text );
857 * Return the ID of the magic word at the start of $text, and remove
858 * the prefix from $text.
859 * Return false if no match found and $text is not modified.
860 * Does not match parameters.
862 * @param $text string
864 * @return int|bool False on failure
866 public function matchStartAndRemove( &$text ) {
867 $regexes = $this->getRegexStart();
868 foreach ( $regexes as $regex ) {
869 if ( $regex === '' ) {
872 if ( preg_match( $regex, $text, $m ) ) {
873 list( $id, ) = $this->parseMatch( $m );
874 if ( strlen( $m[0] ) >= strlen( $text ) ) {
877 $text = substr( $text, strlen( $m[0] ) );