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 ) {
334 $wgContLang->getMagic( $this );
335 if ( !$this->mSynonyms
) {
336 $this->mSynonyms
= array( 'brionmademeputthishere' );
337 throw new MWException( "Error: invalid magic word '$id'" );
342 * Preliminary initialisation
345 function initRegex() {
346 // Sort the synonyms by length, descending, so that the longest synonym
347 // matches in precedence to the shortest
348 $synonyms = $this->mSynonyms
;
349 usort( $synonyms, array( $this, 'compareStringLength' ) );
352 foreach ( $synonyms as $synonym ) {
353 // In case a magic word contains /, like that's going to happen;)
354 $escSyn[] = preg_quote( $synonym, '/' );
356 $this->mBaseRegex
= implode( '|', $escSyn );
358 $case = $this->mCaseSensitive ?
'' : 'iu';
359 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
360 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
361 $this->mRegexStartToEnd
= "/^(?:{$this->mBaseRegex})$/{$case}";
362 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
363 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
364 "/^(?:{$this->mBaseRegex})$/{$case}" );
368 * A comparison function that returns -1, 0 or 1 depending on whether the
369 * first string is longer, the same length or shorter than the second
377 function compareStringLength( $s1, $s2 ) {
382 } elseif ( $l1 > $l2 ) {
390 * Gets a regex representing matching the word
394 function getRegex() {
395 if ( $this->mRegex
== '' ) {
398 return $this->mRegex
;
402 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
403 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
404 * the complete expression
408 function getRegexCase() {
409 if ( $this->mRegex
=== '' ) {
413 return $this->mCaseSensitive ?
'' : 'iu';
417 * Gets a regex matching the word, if it is at the string start
421 function getRegexStart() {
422 if ( $this->mRegex
== '' ) {
425 return $this->mRegexStart
;
429 * Gets a regex matching the word from start to end of a string
434 function getRegexStartToEnd() {
435 if ( $this->mRegexStartToEnd
== '' ) {
438 return $this->mRegexStartToEnd
;
442 * regex without the slashes and what not
446 function getBaseRegex() {
447 if ( $this->mRegex
== '' ) {
450 return $this->mBaseRegex
;
454 * Returns true if the text contains the word
456 * @param string $text
460 function match( $text ) {
461 return (bool)preg_match( $this->getRegex(), $text );
465 * Returns true if the text starts with the word
467 * @param string $text
471 function matchStart( $text ) {
472 return (bool)preg_match( $this->getRegexStart(), $text );
476 * Returns true if the text matched the word
478 * @param string $text
483 function matchStartToEnd( $text ) {
484 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
488 * Returns NULL if there's no match, the value of $1 otherwise
489 * The return code is the matched string, if there's no variable
490 * part in the regex and the matched variable part ($1) if there
493 * @param string $text
497 function matchVariableStartToEnd( $text ) {
499 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
500 if ( $matchcount == 0 ) {
503 # multiple matched parts (variable match); some will be empty because of
504 # synonyms. The variable will be the second non-empty one so remove any
505 # blank elements and re-sort the indices.
508 $matches = array_values( array_filter( $matches ) );
510 if ( count( $matches ) == 1 ) {
519 * Returns true if the text matches the word, and alters the
520 * input string, removing all instances of the word
522 * @param string $text
526 function matchAndRemove( &$text ) {
527 $this->mFound
= false;
528 $text = preg_replace_callback(
530 array( &$this, 'pregRemoveAndRecord' ),
534 return $this->mFound
;
538 * @param string $text
541 function matchStartAndRemove( &$text ) {
542 $this->mFound
= false;
543 $text = preg_replace_callback(
544 $this->getRegexStart(),
545 array( &$this, 'pregRemoveAndRecord' ),
549 return $this->mFound
;
553 * Used in matchAndRemove()
557 function pregRemoveAndRecord() {
558 $this->mFound
= true;
563 * Replaces the word with something else
565 * @param string $replacement
566 * @param string $subject
571 function replace( $replacement, $subject, $limit = -1 ) {
574 StringUtils
::escapeRegexReplacement( $replacement ),
578 $this->mModified
= $res !== $subject;
583 * Variable handling: {{SUBST:xxx}} style words
584 * Calls back a function to determine what to replace xxx with
585 * Input word must contain $1
587 * @param string $text
588 * @param callable $callback
592 function substituteCallback( $text, $callback ) {
593 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
594 $this->mModified
= $res !== $text;
599 * Matches the word, where $1 is a wildcard
603 function getVariableRegex() {
604 if ( $this->mVariableRegex
== '' ) {
607 return $this->mVariableRegex
;
611 * Matches the entire string, where $1 is a wildcard
615 function getVariableStartToEndRegex() {
616 if ( $this->mVariableStartToEndRegex
== '' ) {
619 return $this->mVariableStartToEndRegex
;
623 * Accesses the synonym list directly
629 function getSynonym( $i ) {
630 return $this->mSynonyms
[$i];
636 function getSynonyms() {
637 return $this->mSynonyms
;
641 * Returns true if the last call to replace() or substituteCallback()
642 * returned a modified text, otherwise false.
646 function getWasModified() {
647 return $this->mModified
;
651 * $magicarr is an associative array of (magic word ID => replacement)
652 * This method uses the php feature to do several replacements at the same time,
653 * thereby gaining some efficiency. The result is placed in the out variable
654 * $result. The return value is true if something was replaced.
655 * @deprecated since 1.25, unused
657 * @param array $magicarr
658 * @param string $subject
659 * @param string $result
663 function replaceMultiple( $magicarr, $subject, &$result ) {
664 wfDeprecated( __METHOD__
, '1.25' );
667 foreach ( $magicarr as $id => $replacement ) {
668 $mw = MagicWord
::get( $id );
669 $search[] = $mw->getRegex();
670 $replace[] = $replacement;
673 $result = preg_replace( $search, $replace, $subject );
674 return $result !== $subject;
678 * Adds all the synonyms of this MagicWord to an array, to allow quick
679 * lookup in a list of magic words
681 * @param array $array
682 * @param string $value
684 function addToArray( &$array, $value ) {
686 foreach ( $this->mSynonyms
as $syn ) {
687 $array[$wgContLang->lc( $syn )] = $value;
694 function isCaseSensitive() {
695 return $this->mCaseSensitive
;
707 * Class for handling an array of magic words
710 class MagicWordArray
{
712 public $names = array();
725 * @param array $names
727 function __construct( $names = array() ) {
728 $this->names
= $names;
732 * Add a magic word by name
734 * @param string $name
736 public function add( $name ) {
737 $this->names
[] = $name;
738 $this->hash
= $this->baseRegex
= $this->regex
= null;
742 * Add a number of magic words by name
744 * @param array $names
746 public function addArray( $names ) {
747 $this->names
= array_merge( $this->names
, array_values( $names ) );
748 $this->hash
= $this->baseRegex
= $this->regex
= null;
752 * Get a 2-d hashtable for this array
756 if ( is_null( $this->hash
) ) {
758 $this->hash
= array( 0 => array(), 1 => array() );
759 foreach ( $this->names
as $name ) {
760 $magic = MagicWord
::get( $name );
761 $case = intval( $magic->isCaseSensitive() );
762 foreach ( $magic->getSynonyms() as $syn ) {
764 $syn = $wgContLang->lc( $syn );
766 $this->hash
[$case][$syn] = $name;
777 function getBaseRegex() {
778 if ( is_null( $this->baseRegex
) ) {
779 $this->baseRegex
= array( 0 => '', 1 => '' );
780 foreach ( $this->names
as $name ) {
781 $magic = MagicWord
::get( $name );
782 $case = intval( $magic->isCaseSensitive() );
783 foreach ( $magic->getSynonyms() as $i => $syn ) {
784 // Group name must start with a non-digit in PCRE 8.34+
785 $it = strtr( $i, '0123456789', 'abcdefghij' );
786 $group = "(?P<{$it}_{$name}>" . preg_quote( $syn, '/' ) . ')';
787 if ( $this->baseRegex
[$case] === '' ) {
788 $this->baseRegex
[$case] = $group;
790 $this->baseRegex
[$case] .= '|' . $group;
795 return $this->baseRegex
;
799 * Get an unanchored regex that does not match parameters
802 function getRegex() {
803 if ( is_null( $this->regex
) ) {
804 $base = $this->getBaseRegex();
805 $this->regex
= array( '', '' );
806 if ( $this->baseRegex
[0] !== '' ) {
807 $this->regex
[0] = "/{$base[0]}/iuS";
809 if ( $this->baseRegex
[1] !== '' ) {
810 $this->regex
[1] = "/{$base[1]}/S";
817 * Get a regex for matching variables with parameters
821 function getVariableRegex() {
822 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
826 * Get a regex anchored to the start of the string that does not match parameters
830 function getRegexStart() {
831 $base = $this->getBaseRegex();
832 $newRegex = array( '', '' );
833 if ( $base[0] !== '' ) {
834 $newRegex[0] = "/^(?:{$base[0]})/iuS";
836 if ( $base[1] !== '' ) {
837 $newRegex[1] = "/^(?:{$base[1]})/S";
843 * Get an anchored regex for matching variables with parameters
847 function getVariableStartToEndRegex() {
848 $base = $this->getBaseRegex();
849 $newRegex = array( '', '' );
850 if ( $base[0] !== '' ) {
851 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
853 if ( $base[1] !== '' ) {
854 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
863 public function getNames() {
868 * Parse a match array from preg_match
869 * Returns array(magic word ID, parameter value)
870 * If there is no parameter value, that element will be false.
874 * @throws MWException
877 function parseMatch( $m ) {
879 while ( list( $key, $value ) = each( $m ) ) {
880 if ( $key === 0 ||
$value === '' ) {
883 $parts = explode( '_', $key, 2 );
884 if ( count( $parts ) != 2 ) {
885 // This shouldn't happen
887 throw new MWException( __METHOD__
. ': bad parameter name' );
889 list( /* $synIndex */, $magicName ) = $parts;
890 $paramValue = next( $m );
891 return array( $magicName, $paramValue );
893 // This shouldn't happen either
894 throw new MWException( __METHOD__
. ': parameter not found' );
898 * Match some text, with parameter capture
899 * Returns an array with the magic word name in the first element and the
900 * parameter in the second element.
901 * Both elements are false if there was no match.
903 * @param string $text
907 public function matchVariableStartToEnd( $text ) {
908 $regexes = $this->getVariableStartToEndRegex();
909 foreach ( $regexes as $regex ) {
910 if ( $regex !== '' ) {
912 if ( preg_match( $regex, $text, $m ) ) {
913 return $this->parseMatch( $m );
917 return array( false, false );
921 * Match some text, without parameter capture
922 * Returns the magic word name, or false if there was no capture
924 * @param string $text
926 * @return string|bool False on failure
928 public function matchStartToEnd( $text ) {
929 $hash = $this->getHash();
930 if ( isset( $hash[1][$text] ) ) {
931 return $hash[1][$text];
934 $lc = $wgContLang->lc( $text );
935 if ( isset( $hash[0][$lc] ) ) {
936 return $hash[0][$lc];
942 * Returns an associative array, ID => param value, for all items that match
943 * Removes the matched items from the input string (passed by reference)
945 * @param string $text
949 public function matchAndRemove( &$text ) {
951 $regexes = $this->getRegex();
952 foreach ( $regexes as $regex ) {
953 if ( $regex === '' ) {
956 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
957 foreach ( $matches as $m ) {
958 list( $name, $param ) = $this->parseMatch( $m );
959 $found[$name] = $param;
961 $text = preg_replace( $regex, '', $text );
967 * Return the ID of the magic word at the start of $text, and remove
968 * the prefix from $text.
969 * Return false if no match found and $text is not modified.
970 * Does not match parameters.
972 * @param string $text
974 * @return int|bool False on failure
976 public function matchStartAndRemove( &$text ) {
977 $regexes = $this->getRegexStart();
978 foreach ( $regexes as $regex ) {
979 if ( $regex === '' ) {
982 if ( preg_match( $regex, $text, $m ) ) {
983 list( $id, ) = $this->parseMatch( $m );
984 if ( strlen( $m[0] ) >= strlen( $text ) ) {
987 $text = substr( $text, strlen( $m[0] ) );