3 * File for magic words.
5 * See docs/magicword.txt.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
27 * This class encapsulates "magic words" such as "#redirect", __NOTOC__, etc.
31 * if (MagicWord::get( 'redirect' )->match( $text ) ) {
36 * Possible future improvements:
37 * * Simultaneous searching for a number of magic words
38 * * MagicWord::$mObjects in shared memory
40 * Please avoid reading the data out of one of these objects and then writing
41 * special case code. If possible, add another match()-like function here.
43 * To add magic words in an extension, use $magicWords in a file listed in
44 * $wgExtensionMessagesFiles[].
48 * $magicWords = array();
50 * $magicWords['en'] = array(
51 * 'magicwordkey' => array( 0, 'case_insensitive_magic_word' ),
52 * 'magicwordkey2' => array( 1, 'CASE_sensitive_magic_word2' ),
56 * For magic words which are also Parser variables, add a MagicWordwgVariableIDs
57 * hook. Use string keys.
71 public $mCaseSensitive;
77 private $mRegexStart = '';
80 private $mRegexStartToEnd = '';
83 private $mBaseRegex = '';
86 private $mVariableRegex = '';
89 private $mVariableStartToEndRegex = '';
92 private $mModified = false;
95 private $mFound = false;
97 static public $mVariableIDsInitialised = false;
98 static public $mVariableIDs = array(
103 'currentmonthnamegen',
104 'currentmonthabbrev',
163 'numberofactiveusers',
178 /* Array of caching hints for ParserCache */
179 static public $mCacheTTLs = array(
180 'currentmonth' => 86400,
181 'currentmonth1' => 86400,
182 'currentmonthname' => 86400,
183 'currentmonthnamegen' => 86400,
184 'currentmonthabbrev' => 86400,
185 'currentday' => 3600,
186 'currentday2' => 3600,
187 'currentdayname' => 3600,
188 'currentyear' => 86400,
189 'currenttime' => 3600,
190 'currenthour' => 3600,
191 'localmonth' => 86400,
192 'localmonth1' => 86400,
193 'localmonthname' => 86400,
194 'localmonthnamegen' => 86400,
195 'localmonthabbrev' => 86400,
198 'localdayname' => 3600,
199 'localyear' => 86400,
202 'numberofarticles' => 3600,
203 'numberoffiles' => 3600,
204 'numberofedits' => 3600,
205 'currentweek' => 3600,
206 'currentdow' => 3600,
209 'numberofusers' => 3600,
210 'numberofactiveusers' => 3600,
211 'numberofpages' => 3600,
212 'currentversion' => 86400,
213 'currenttimestamp' => 3600,
214 'localtimestamp' => 3600,
215 'pagesinnamespace' => 3600,
216 'numberofadmins' => 3600,
217 'numberingroup' => 3600,
220 static public $mDoubleUnderscoreIDs = array(
236 static public $mSubstIDs = array(
241 static public $mObjects = array();
242 static public $mDoubleUnderscoreArray = null;
246 function __construct( $id = 0, $syn = array(), $cs = false ) {
248 $this->mSynonyms
= (array)$syn;
249 $this->mCaseSensitive
= $cs;
253 * Factory: creates an object representing an ID
259 static function &get( $id ) {
260 if ( !isset( self
::$mObjects[$id] ) ) {
261 $mw = new MagicWord();
263 self
::$mObjects[$id] = $mw;
265 return self
::$mObjects[$id];
269 * Get an array of parser variable IDs
273 static function getVariableIDs() {
274 if ( !self
::$mVariableIDsInitialised ) {
276 Hooks
::run( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
277 self
::$mVariableIDsInitialised = true;
279 return self
::$mVariableIDs;
283 * Get an array of parser substitution modifier IDs
286 static function getSubstIDs() {
287 return self
::$mSubstIDs;
291 * Allow external reads of TTL array
296 static function getCacheTTL( $id ) {
297 if ( array_key_exists( $id, self
::$mCacheTTLs ) ) {
298 return self
::$mCacheTTLs[$id];
305 * Get a MagicWordArray of double-underscore entities
307 * @return MagicWordArray
309 static function getDoubleUnderscoreArray() {
310 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
311 Hooks
::run( 'GetDoubleUnderscoreIDs', array( &self
::$mDoubleUnderscoreIDs ) );
312 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
314 return self
::$mDoubleUnderscoreArray;
318 * Clear the self::$mObjects variable
319 * For use in parser tests
321 public static function clearCache() {
322 self
::$mObjects = array();
326 * Initialises this object with an ID
329 * @throws MWException
331 function load( $id ) {
333 wfProfileIn( __METHOD__
);
335 $wgContLang->getMagic( $this );
336 if ( !$this->mSynonyms
) {
337 $this->mSynonyms
= array( 'brionmademeputthishere' );
338 wfProfileOut( __METHOD__
);
339 throw new MWException( "Error: invalid magic word '$id'" );
341 wfProfileOut( __METHOD__
);
345 * Preliminary initialisation
348 function initRegex() {
349 // Sort the synonyms by length, descending, so that the longest synonym
350 // matches in precedence to the shortest
351 $synonyms = $this->mSynonyms
;
352 usort( $synonyms, array( $this, 'compareStringLength' ) );
355 foreach ( $synonyms as $synonym ) {
356 // In case a magic word contains /, like that's going to happen;)
357 $escSyn[] = preg_quote( $synonym, '/' );
359 $this->mBaseRegex
= implode( '|', $escSyn );
361 $case = $this->mCaseSensitive ?
'' : 'iu';
362 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
363 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
364 $this->mRegexStartToEnd
= "/^(?:{$this->mBaseRegex})$/{$case}";
365 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
366 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
367 "/^(?:{$this->mBaseRegex})$/{$case}" );
371 * A comparison function that returns -1, 0 or 1 depending on whether the
372 * first string is longer, the same length or shorter than the second
380 function compareStringLength( $s1, $s2 ) {
385 } elseif ( $l1 > $l2 ) {
393 * Gets a regex representing matching the word
397 function getRegex() {
398 if ( $this->mRegex
== '' ) {
401 return $this->mRegex
;
405 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
406 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
407 * the complete expression
411 function getRegexCase() {
412 if ( $this->mRegex
=== '' ) {
416 return $this->mCaseSensitive ?
'' : 'iu';
420 * Gets a regex matching the word, if it is at the string start
424 function getRegexStart() {
425 if ( $this->mRegex
== '' ) {
428 return $this->mRegexStart
;
432 * Gets a regex matching the word from start to end of a string
437 function getRegexStartToEnd() {
438 if ( $this->mRegexStartToEnd
== '' ) {
441 return $this->mRegexStartToEnd
;
445 * regex without the slashes and what not
449 function getBaseRegex() {
450 if ( $this->mRegex
== '' ) {
453 return $this->mBaseRegex
;
457 * Returns true if the text contains the word
459 * @param string $text
463 function match( $text ) {
464 return (bool)preg_match( $this->getRegex(), $text );
468 * Returns true if the text starts with the word
470 * @param string $text
474 function matchStart( $text ) {
475 return (bool)preg_match( $this->getRegexStart(), $text );
479 * Returns true if the text matched the word
481 * @param string $text
486 function matchStartToEnd( $text ) {
487 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
491 * Returns NULL if there's no match, the value of $1 otherwise
492 * The return code is the matched string, if there's no variable
493 * part in the regex and the matched variable part ($1) if there
496 * @param string $text
500 function matchVariableStartToEnd( $text ) {
502 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
503 if ( $matchcount == 0 ) {
506 # multiple matched parts (variable match); some will be empty because of
507 # synonyms. The variable will be the second non-empty one so remove any
508 # blank elements and re-sort the indices.
511 $matches = array_values( array_filter( $matches ) );
513 if ( count( $matches ) == 1 ) {
522 * Returns true if the text matches the word, and alters the
523 * input string, removing all instances of the word
525 * @param string $text
529 function matchAndRemove( &$text ) {
530 $this->mFound
= false;
531 $text = preg_replace_callback(
533 array( &$this, 'pregRemoveAndRecord' ),
537 return $this->mFound
;
541 * @param string $text
544 function matchStartAndRemove( &$text ) {
545 $this->mFound
= false;
546 $text = preg_replace_callback(
547 $this->getRegexStart(),
548 array( &$this, 'pregRemoveAndRecord' ),
552 return $this->mFound
;
556 * Used in matchAndRemove()
560 function pregRemoveAndRecord() {
561 $this->mFound
= true;
566 * Replaces the word with something else
568 * @param string $replacement
569 * @param string $subject
574 function replace( $replacement, $subject, $limit = -1 ) {
577 StringUtils
::escapeRegexReplacement( $replacement ),
581 $this->mModified
= $res !== $subject;
586 * Variable handling: {{SUBST:xxx}} style words
587 * Calls back a function to determine what to replace xxx with
588 * Input word must contain $1
590 * @param string $text
591 * @param callable $callback
595 function substituteCallback( $text, $callback ) {
596 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
597 $this->mModified
= $res !== $text;
602 * Matches the word, where $1 is a wildcard
606 function getVariableRegex() {
607 if ( $this->mVariableRegex
== '' ) {
610 return $this->mVariableRegex
;
614 * Matches the entire string, where $1 is a wildcard
618 function getVariableStartToEndRegex() {
619 if ( $this->mVariableStartToEndRegex
== '' ) {
622 return $this->mVariableStartToEndRegex
;
626 * Accesses the synonym list directly
632 function getSynonym( $i ) {
633 return $this->mSynonyms
[$i];
639 function getSynonyms() {
640 return $this->mSynonyms
;
644 * Returns true if the last call to replace() or substituteCallback()
645 * returned a modified text, otherwise false.
649 function getWasModified() {
650 return $this->mModified
;
654 * $magicarr is an associative array of (magic word ID => replacement)
655 * This method uses the php feature to do several replacements at the same time,
656 * thereby gaining some efficiency. The result is placed in the out variable
657 * $result. The return value is true if something was replaced.
658 * @deprecated since 1.25, unused
660 * @param array $magicarr
661 * @param string $subject
662 * @param string $result
666 function replaceMultiple( $magicarr, $subject, &$result ) {
667 wfDeprecated( __METHOD__
, '1.25' );
670 foreach ( $magicarr as $id => $replacement ) {
671 $mw = MagicWord
::get( $id );
672 $search[] = $mw->getRegex();
673 $replace[] = $replacement;
676 $result = preg_replace( $search, $replace, $subject );
677 return $result !== $subject;
681 * Adds all the synonyms of this MagicWord to an array, to allow quick
682 * lookup in a list of magic words
684 * @param array $array
685 * @param string $value
687 function addToArray( &$array, $value ) {
689 foreach ( $this->mSynonyms
as $syn ) {
690 $array[$wgContLang->lc( $syn )] = $value;
697 function isCaseSensitive() {
698 return $this->mCaseSensitive
;
710 * Class for handling an array of magic words
713 class MagicWordArray
{
715 public $names = array();
728 * @param array $names
730 function __construct( $names = array() ) {
731 $this->names
= $names;
735 * Add a magic word by name
737 * @param string $name
739 public function add( $name ) {
740 $this->names
[] = $name;
741 $this->hash
= $this->baseRegex
= $this->regex
= null;
745 * Add a number of magic words by name
747 * @param array $names
749 public function addArray( $names ) {
750 $this->names
= array_merge( $this->names
, array_values( $names ) );
751 $this->hash
= $this->baseRegex
= $this->regex
= null;
755 * Get a 2-d hashtable for this array
759 if ( is_null( $this->hash
) ) {
761 $this->hash
= array( 0 => array(), 1 => array() );
762 foreach ( $this->names
as $name ) {
763 $magic = MagicWord
::get( $name );
764 $case = intval( $magic->isCaseSensitive() );
765 foreach ( $magic->getSynonyms() as $syn ) {
767 $syn = $wgContLang->lc( $syn );
769 $this->hash
[$case][$syn] = $name;
780 function getBaseRegex() {
781 if ( is_null( $this->baseRegex
) ) {
782 $this->baseRegex
= array( 0 => '', 1 => '' );
783 foreach ( $this->names
as $name ) {
784 $magic = MagicWord
::get( $name );
785 $case = intval( $magic->isCaseSensitive() );
786 foreach ( $magic->getSynonyms() as $i => $syn ) {
787 // Group name must start with a non-digit in PCRE 8.34+
788 $it = strtr( $i, '0123456789', 'abcdefghij' );
789 $group = "(?P<{$it}_{$name}>" . preg_quote( $syn, '/' ) . ')';
790 if ( $this->baseRegex
[$case] === '' ) {
791 $this->baseRegex
[$case] = $group;
793 $this->baseRegex
[$case] .= '|' . $group;
798 return $this->baseRegex
;
802 * Get an unanchored regex that does not match parameters
805 function getRegex() {
806 if ( is_null( $this->regex
) ) {
807 $base = $this->getBaseRegex();
808 $this->regex
= array( '', '' );
809 if ( $this->baseRegex
[0] !== '' ) {
810 $this->regex
[0] = "/{$base[0]}/iuS";
812 if ( $this->baseRegex
[1] !== '' ) {
813 $this->regex
[1] = "/{$base[1]}/S";
820 * Get a regex for matching variables with parameters
824 function getVariableRegex() {
825 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
829 * Get a regex anchored to the start of the string that does not match parameters
833 function getRegexStart() {
834 $base = $this->getBaseRegex();
835 $newRegex = array( '', '' );
836 if ( $base[0] !== '' ) {
837 $newRegex[0] = "/^(?:{$base[0]})/iuS";
839 if ( $base[1] !== '' ) {
840 $newRegex[1] = "/^(?:{$base[1]})/S";
846 * Get an anchored regex for matching variables with parameters
850 function getVariableStartToEndRegex() {
851 $base = $this->getBaseRegex();
852 $newRegex = array( '', '' );
853 if ( $base[0] !== '' ) {
854 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
856 if ( $base[1] !== '' ) {
857 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
866 public function getNames() {
871 * Parse a match array from preg_match
872 * Returns array(magic word ID, parameter value)
873 * If there is no parameter value, that element will be false.
877 * @throws MWException
880 function parseMatch( $m ) {
882 while ( list( $key, $value ) = each( $m ) ) {
883 if ( $key === 0 ||
$value === '' ) {
886 $parts = explode( '_', $key, 2 );
887 if ( count( $parts ) != 2 ) {
888 // This shouldn't happen
890 throw new MWException( __METHOD__
. ': bad parameter name' );
892 list( /* $synIndex */, $magicName ) = $parts;
893 $paramValue = next( $m );
894 return array( $magicName, $paramValue );
896 // This shouldn't happen either
897 throw new MWException( __METHOD__
. ': parameter not found' );
901 * Match some text, with parameter capture
902 * Returns an array with the magic word name in the first element and the
903 * parameter in the second element.
904 * Both elements are false if there was no match.
906 * @param string $text
910 public function matchVariableStartToEnd( $text ) {
911 $regexes = $this->getVariableStartToEndRegex();
912 foreach ( $regexes as $regex ) {
913 if ( $regex !== '' ) {
915 if ( preg_match( $regex, $text, $m ) ) {
916 return $this->parseMatch( $m );
920 return array( false, false );
924 * Match some text, without parameter capture
925 * Returns the magic word name, or false if there was no capture
927 * @param string $text
929 * @return string|bool False on failure
931 public function matchStartToEnd( $text ) {
932 $hash = $this->getHash();
933 if ( isset( $hash[1][$text] ) ) {
934 return $hash[1][$text];
937 $lc = $wgContLang->lc( $text );
938 if ( isset( $hash[0][$lc] ) ) {
939 return $hash[0][$lc];
945 * Returns an associative array, ID => param value, for all items that match
946 * Removes the matched items from the input string (passed by reference)
948 * @param string $text
952 public function matchAndRemove( &$text ) {
954 $regexes = $this->getRegex();
955 foreach ( $regexes as $regex ) {
956 if ( $regex === '' ) {
959 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
960 foreach ( $matches as $m ) {
961 list( $name, $param ) = $this->parseMatch( $m );
962 $found[$name] = $param;
964 $text = preg_replace( $regex, '', $text );
970 * Return the ID of the magic word at the start of $text, and remove
971 * the prefix from $text.
972 * Return false if no match found and $text is not modified.
973 * Does not match parameters.
975 * @param string $text
977 * @return int|bool False on failure
979 public function matchStartAndRemove( &$text ) {
980 $regexes = $this->getRegexStart();
981 foreach ( $regexes as $regex ) {
982 if ( $regex === '' ) {
985 if ( preg_match( $regex, $text, $m ) ) {
986 list( $id, ) = $this->parseMatch( $m );
987 if ( strlen( $m[0] ) >= strlen( $text ) ) {
990 $text = substr( $text, strlen( $m[0] ) );