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.
65 var $mId, $mSynonyms, $mCaseSensitive;
67 var $mRegexStart = '';
69 var $mVariableRegex = '';
70 var $mVariableStartToEndRegex = '';
71 var $mModified = false;
74 static public $mVariableIDsInitialised = false;
75 static public $mVariableIDs = array(
79 'currentmonthnamegen',
139 'numberofactiveusers',
155 /* Array of caching hints for ParserCache */
156 static public $mCacheTTLs = array(
157 'currentmonth' => 86400,
158 'currentmonth1' => 86400,
159 'currentmonthname' => 86400,
160 'currentmonthnamegen' => 86400,
161 'currentmonthabbrev' => 86400,
162 'currentday' => 3600,
163 'currentday2' => 3600,
164 'currentdayname' => 3600,
165 'currentyear' => 86400,
166 'currenttime' => 3600,
167 'currenthour' => 3600,
168 'localmonth' => 86400,
169 'localmonth1' => 86400,
170 'localmonthname' => 86400,
171 'localmonthnamegen' => 86400,
172 'localmonthabbrev' => 86400,
175 'localdayname' => 3600,
176 'localyear' => 86400,
179 'numberofarticles' => 3600,
180 'numberoffiles' => 3600,
181 'numberofedits' => 3600,
182 'currentweek' => 3600,
183 'currentdow' => 3600,
186 'numberofusers' => 3600,
187 'numberofactiveusers' => 3600,
188 'numberofpages' => 3600,
189 'currentversion' => 86400,
190 'currenttimestamp' => 3600,
191 'localtimestamp' => 3600,
192 'pagesinnamespace' => 3600,
193 'numberofadmins' => 3600,
194 'numberofviews' => 3600,
195 'numberingroup' => 3600,
198 static public $mDoubleUnderscoreIDs = array(
214 static public $mSubstIDs = array(
219 static public $mObjects = array();
220 static public $mDoubleUnderscoreArray = null;
224 function __construct( $id = 0, $syn = array(), $cs = false ) {
226 $this->mSynonyms
= (array)$syn;
227 $this->mCaseSensitive
= $cs;
231 * Factory: creates an object representing an ID
237 static function &get( $id ) {
238 if ( !isset( self
::$mObjects[$id] ) ) {
239 $mw = new MagicWord();
241 self
::$mObjects[$id] = $mw;
243 return self
::$mObjects[$id];
247 * Get an array of parser variable IDs
251 static function getVariableIDs() {
252 if ( !self
::$mVariableIDsInitialised ) {
254 wfRunHooks( 'MagicWordwgVariableIDs', array( &self
::$mVariableIDs ) );
255 self
::$mVariableIDsInitialised = true;
257 return self
::$mVariableIDs;
261 * Get an array of parser substitution modifier IDs
264 static function getSubstIDs() {
265 return self
::$mSubstIDs;
269 * Allow external reads of TTL array
274 static function getCacheTTL( $id ) {
275 if ( array_key_exists( $id, self
::$mCacheTTLs ) ) {
276 return self
::$mCacheTTLs[$id];
283 * Get a MagicWordArray of double-underscore entities
285 * @return MagicWordArray
287 static function getDoubleUnderscoreArray() {
288 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
289 wfRunHooks( 'GetDoubleUnderscoreIDs', array( &self
::$mDoubleUnderscoreIDs ) );
290 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
292 return self
::$mDoubleUnderscoreArray;
296 * Clear the self::$mObjects variable
297 * For use in parser tests
299 public static function clearCache() {
300 self
::$mObjects = array();
304 * Initialises this object with an ID
307 * @throws MWException
309 function load( $id ) {
311 wfProfileIn( __METHOD__
);
313 $wgContLang->getMagic( $this );
314 if ( !$this->mSynonyms
) {
315 $this->mSynonyms
= array( 'brionmademeputthishere' );
316 wfProfileOut( __METHOD__
);
317 throw new MWException( "Error: invalid magic word '$id'" );
319 wfProfileOut( __METHOD__
);
323 * Preliminary initialisation
326 function initRegex() {
327 // Sort the synonyms by length, descending, so that the longest synonym
328 // matches in precedence to the shortest
329 $synonyms = $this->mSynonyms
;
330 usort( $synonyms, array( $this, 'compareStringLength' ) );
333 foreach ( $synonyms as $synonym ) {
334 // In case a magic word contains /, like that's going to happen;)
335 $escSyn[] = preg_quote( $synonym, '/' );
337 $this->mBaseRegex
= implode( '|', $escSyn );
339 $case = $this->mCaseSensitive ?
'' : 'iu';
340 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
341 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
342 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
343 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
344 "/^(?:{$this->mBaseRegex})$/{$case}" );
348 * A comparison function that returns -1, 0 or 1 depending on whether the
349 * first string is longer, the same length or shorter than the second
357 function compareStringLength( $s1, $s2 ) {
362 } elseif ( $l1 > $l2 ) {
370 * Gets a regex representing matching the word
374 function getRegex() {
375 if ( $this->mRegex
== '' ) {
378 return $this->mRegex
;
382 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
383 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
384 * the complete expression
388 function getRegexCase() {
389 if ( $this->mRegex
=== '' ) {
393 return $this->mCaseSensitive ?
'' : 'iu';
397 * Gets a regex matching the word, if it is at the string start
401 function getRegexStart() {
402 if ( $this->mRegex
== '' ) {
405 return $this->mRegexStart
;
409 * regex without the slashes and what not
413 function getBaseRegex() {
414 if ( $this->mRegex
== '' ) {
417 return $this->mBaseRegex
;
421 * Returns true if the text contains the word
423 * @param $text string
427 function match( $text ) {
428 return (bool)preg_match( $this->getRegex(), $text );
432 * Returns true if the text starts with the word
434 * @param $text string
438 function matchStart( $text ) {
439 return (bool)preg_match( $this->getRegexStart(), $text );
443 * Returns NULL if there's no match, the value of $1 otherwise
444 * The return code is the matched string, if there's no variable
445 * part in the regex and the matched variable part ($1) if there
448 * @param $text string
452 function matchVariableStartToEnd( $text ) {
454 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
455 if ( $matchcount == 0 ) {
458 # multiple matched parts (variable match); some will be empty because of
459 # synonyms. The variable will be the second non-empty one so remove any
460 # blank elements and re-sort the indices.
463 $matches = array_values( array_filter( $matches ) );
465 if ( count( $matches ) == 1 ) {
474 * Returns true if the text matches the word, and alters the
475 * input string, removing all instances of the word
477 * @param $text string
481 function matchAndRemove( &$text ) {
482 $this->mFound
= false;
483 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
484 return $this->mFound
;
491 function matchStartAndRemove( &$text ) {
492 $this->mFound
= false;
493 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
494 return $this->mFound
;
498 * Used in matchAndRemove()
502 function pregRemoveAndRecord() {
503 $this->mFound
= true;
508 * Replaces the word with something else
510 * @param $replacement
516 function replace( $replacement, $subject, $limit = -1 ) {
517 $res = preg_replace( $this->getRegex(), StringUtils
::escapeRegexReplacement( $replacement ), $subject, $limit );
518 $this->mModified
= $res !== $subject;
523 * Variable handling: {{SUBST:xxx}} style words
524 * Calls back a function to determine what to replace xxx with
525 * Input word must contain $1
527 * @param $text string
532 function substituteCallback( $text, $callback ) {
533 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
534 $this->mModified
= $res !== $text;
539 * Matches the word, where $1 is a wildcard
543 function getVariableRegex() {
544 if ( $this->mVariableRegex
== '' ) {
547 return $this->mVariableRegex
;
551 * Matches the entire string, where $1 is a wildcard
555 function getVariableStartToEndRegex() {
556 if ( $this->mVariableStartToEndRegex
== '' ) {
559 return $this->mVariableStartToEndRegex
;
563 * Accesses the synonym list directly
569 function getSynonym( $i ) {
570 return $this->mSynonyms
[$i];
576 function getSynonyms() {
577 return $this->mSynonyms
;
581 * Returns true if the last call to replace() or substituteCallback()
582 * returned a modified text, otherwise false.
586 function getWasModified() {
587 return $this->mModified
;
591 * $magicarr is an associative array of (magic word ID => replacement)
592 * This method uses the php feature to do several replacements at the same time,
593 * thereby gaining some efficiency. The result is placed in the out variable
594 * $result. The return value is true if something was replaced.
595 * @todo Should this be static? It doesn't seem to be used at all
603 function replaceMultiple( $magicarr, $subject, &$result ) {
606 foreach ( $magicarr as $id => $replacement ) {
607 $mw = MagicWord
::get( $id );
608 $search[] = $mw->getRegex();
609 $replace[] = $replacement;
612 $result = preg_replace( $search, $replace, $subject );
613 return $result !== $subject;
617 * Adds all the synonyms of this MagicWord to an array, to allow quick
618 * lookup in a list of magic words
623 function addToArray( &$array, $value ) {
625 foreach ( $this->mSynonyms
as $syn ) {
626 $array[$wgContLang->lc( $syn )] = $value;
633 function isCaseSensitive() {
634 return $this->mCaseSensitive
;
646 * Class for handling an array of magic words
649 class MagicWordArray
{
650 var $names = array();
652 var $baseRegex, $regex;
656 * @param $names array
658 function __construct( $names = array() ) {
659 $this->names
= $names;
663 * Add a magic word by name
665 * @param $name string
667 public function add( $name ) {
668 $this->names
[] = $name;
669 $this->hash
= $this->baseRegex
= $this->regex
= null;
673 * Add a number of magic words by name
675 * @param $names array
677 public function addArray( $names ) {
678 $this->names
= array_merge( $this->names
, array_values( $names ) );
679 $this->hash
= $this->baseRegex
= $this->regex
= null;
683 * Get a 2-d hashtable for this array
686 if ( is_null( $this->hash
) ) {
688 $this->hash
= array( 0 => array(), 1 => array() );
689 foreach ( $this->names
as $name ) {
690 $magic = MagicWord
::get( $name );
691 $case = intval( $magic->isCaseSensitive() );
692 foreach ( $magic->getSynonyms() as $syn ) {
694 $syn = $wgContLang->lc( $syn );
696 $this->hash
[$case][$syn] = $name;
706 function getBaseRegex() {
707 if ( is_null( $this->baseRegex
) ) {
708 $this->baseRegex
= array( 0 => '', 1 => '' );
709 foreach ( $this->names
as $name ) {
710 $magic = MagicWord
::get( $name );
711 $case = intval( $magic->isCaseSensitive() );
712 foreach ( $magic->getSynonyms() as $i => $syn ) {
713 // Group name must start with a non-digit in PCRE 8.34+
714 $it = strtr( $i, '0123456789', 'abcdefghij' );
715 $group = "(?P<{$it}_{$name}>" . preg_quote( $syn, '/' ) . ')';
716 if ( $this->baseRegex
[$case] === '' ) {
717 $this->baseRegex
[$case] = $group;
719 $this->baseRegex
[$case] .= '|' . $group;
724 return $this->baseRegex
;
728 * Get an unanchored regex that does not match parameters
730 function getRegex() {
731 if ( is_null( $this->regex
) ) {
732 $base = $this->getBaseRegex();
733 $this->regex
= array( '', '' );
734 if ( $this->baseRegex
[0] !== '' ) {
735 $this->regex
[0] = "/{$base[0]}/iuS";
737 if ( $this->baseRegex
[1] !== '' ) {
738 $this->regex
[1] = "/{$base[1]}/S";
745 * Get a regex for matching variables with parameters
749 function getVariableRegex() {
750 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
754 * Get a regex anchored to the start of the string that does not match parameters
758 function getRegexStart() {
759 $base = $this->getBaseRegex();
760 $newRegex = array( '', '' );
761 if ( $base[0] !== '' ) {
762 $newRegex[0] = "/^(?:{$base[0]})/iuS";
764 if ( $base[1] !== '' ) {
765 $newRegex[1] = "/^(?:{$base[1]})/S";
771 * Get an anchored regex for matching variables with parameters
775 function getVariableStartToEndRegex() {
776 $base = $this->getBaseRegex();
777 $newRegex = array( '', '' );
778 if ( $base[0] !== '' ) {
779 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
781 if ( $base[1] !== '' ) {
782 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
791 public function getNames() {
796 * Parse a match array from preg_match
797 * Returns array(magic word ID, parameter value)
798 * If there is no parameter value, that element will be false.
802 * @throws MWException
805 function parseMatch( $m ) {
807 while ( list( $key, $value ) = each( $m ) ) {
808 if ( $key === 0 ||
$value === '' ) {
811 $parts = explode( '_', $key, 2 );
812 if ( count( $parts ) != 2 ) {
813 // This shouldn't happen
815 throw new MWException( __METHOD__
. ': bad parameter name' );
817 list( /* $synIndex */, $magicName ) = $parts;
818 $paramValue = next( $m );
819 return array( $magicName, $paramValue );
821 // This shouldn't happen either
822 throw new MWException( __METHOD__
. ': parameter not found' );
826 * Match some text, with parameter capture
827 * Returns an array with the magic word name in the first element and the
828 * parameter in the second element.
829 * Both elements are false if there was no match.
831 * @param $text string
835 public function matchVariableStartToEnd( $text ) {
836 $regexes = $this->getVariableStartToEndRegex();
837 foreach ( $regexes as $regex ) {
838 if ( $regex !== '' ) {
840 if ( preg_match( $regex, $text, $m ) ) {
841 return $this->parseMatch( $m );
845 return array( false, false );
849 * Match some text, without parameter capture
850 * Returns the magic word name, or false if there was no capture
852 * @param $text string
854 * @return string|bool False on failure
856 public function matchStartToEnd( $text ) {
857 $hash = $this->getHash();
858 if ( isset( $hash[1][$text] ) ) {
859 return $hash[1][$text];
862 $lc = $wgContLang->lc( $text );
863 if ( isset( $hash[0][$lc] ) ) {
864 return $hash[0][$lc];
870 * Returns an associative array, ID => param value, for all items that match
871 * Removes the matched items from the input string (passed by reference)
873 * @param $text string
877 public function matchAndRemove( &$text ) {
879 $regexes = $this->getRegex();
880 foreach ( $regexes as $regex ) {
881 if ( $regex === '' ) {
884 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER
);
885 foreach ( $matches as $m ) {
886 list( $name, $param ) = $this->parseMatch( $m );
887 $found[$name] = $param;
889 $text = preg_replace( $regex, '', $text );
895 * Return the ID of the magic word at the start of $text, and remove
896 * the prefix from $text.
897 * Return false if no match found and $text is not modified.
898 * Does not match parameters.
900 * @param $text string
902 * @return int|bool False on failure
904 public function matchStartAndRemove( &$text ) {
905 $regexes = $this->getRegexStart();
906 foreach ( $regexes as $regex ) {
907 if ( $regex === '' ) {
910 if ( preg_match( $regex, $text, $m ) ) {
911 list( $id, ) = $this->parseMatch( $m );
912 if ( strlen( $m[0] ) >= strlen( $text ) ) {
915 $text = substr( $text, strlen( $m[0] ) );