3 * See docs/magicword.txt.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * This class encapsulates "magic words" such as "#redirect", __NOTOC__, etc.
29 * if (MagicWord::get( 'redirect' )->match( $text ) ) {
34 * Possible future improvements:
35 * * Simultaneous searching for a number of magic words
36 * * MagicWord::$mObjects in shared memory
38 * Please avoid reading the data out of one of these objects and then writing
39 * special case code. If possible, add another match()-like function here.
41 * To add magic words in an extension, use $magicWords in a file listed in
42 * $wgExtensionMessagesFiles[].
48 * $magicWords['en'] = [
49 * 'magicwordkey' => [ 0, 'case_insensitive_magic_word' ],
50 * 'magicwordkey2' => [ 1, 'CASE_sensitive_magic_word2' ],
54 * For magic words which are also Parser variables, add a MagicWordwgVariableIDs
55 * hook. Use string keys.
69 public $mCaseSensitive;
75 private $mRegexStart = '';
78 private $mRegexStartToEnd = '';
81 private $mBaseRegex = '';
84 private $mVariableRegex = '';
87 private $mVariableStartToEndRegex = '';
90 private $mModified = false;
93 private $mFound = false;
96 public static $mVariableIDsInitialised = false;
99 public static $mVariableIDs = [
104 'currentmonthnamegen',
105 'currentmonthabbrev',
164 'numberofactiveusers',
180 /** Array of caching hints for ParserCache
181 * @var array [ string => int ]
183 public static $mCacheTTLs = [
184 'currentmonth' => 86400,
185 'currentmonth1' => 86400,
186 'currentmonthname' => 86400,
187 'currentmonthnamegen' => 86400,
188 'currentmonthabbrev' => 86400,
189 'currentday' => 3600,
190 'currentday2' => 3600,
191 'currentdayname' => 3600,
192 'currentyear' => 86400,
193 'currenttime' => 3600,
194 'currenthour' => 3600,
195 'localmonth' => 86400,
196 'localmonth1' => 86400,
197 'localmonthname' => 86400,
198 'localmonthnamegen' => 86400,
199 'localmonthabbrev' => 86400,
202 'localdayname' => 3600,
203 'localyear' => 86400,
206 'numberofarticles' => 3600,
207 'numberoffiles' => 3600,
208 'numberofedits' => 3600,
209 'currentweek' => 3600,
210 'currentdow' => 3600,
213 'numberofusers' => 3600,
214 'numberofactiveusers' => 3600,
215 'numberofpages' => 3600,
216 'currentversion' => 86400,
217 'currenttimestamp' => 3600,
218 'localtimestamp' => 3600,
219 'pagesinnamespace' => 3600,
220 'numberofadmins' => 3600,
221 'numberingroup' => 3600,
225 public static $mDoubleUnderscoreIDs = [
242 public static $mSubstIDs = [
247 /** @var array [ string => MagicWord ] */
248 public static $mObjects = [];
250 /** @var MagicWordArray */
251 public static $mDoubleUnderscoreArray = null;
256 * Create a new MagicWord object
258 * Use factory instead: MagicWord::get
260 * @param string|null $id The internal name of the magic word
261 * @param string[]|string $syn synonyms for the magic word
262 * @param bool $cs If magic word is case sensitive
264 public function __construct( $id = null, $syn = [], $cs = false ) {
266 $this->mSynonyms
= (array)$syn;
267 $this->mCaseSensitive
= $cs;
271 * Factory: creates an object representing an ID
273 * @param string $id The internal name of the magic word
277 public static function &get( $id ) {
278 if ( !isset( self
::$mObjects[$id] ) ) {
279 $mw = new MagicWord();
281 self
::$mObjects[$id] = $mw;
283 return self
::$mObjects[$id];
287 * Get an array of parser variable IDs
291 public static function getVariableIDs() {
292 if ( !self
::$mVariableIDsInitialised ) {
294 Hooks
::run( 'MagicWordwgVariableIDs', [ &self
::$mVariableIDs ] );
295 self
::$mVariableIDsInitialised = true;
297 return self
::$mVariableIDs;
301 * Get an array of parser substitution modifier IDs
304 public static function getSubstIDs() {
305 return self
::$mSubstIDs;
309 * Allow external reads of TTL array
314 public static function getCacheTTL( $id ) {
315 if ( array_key_exists( $id, self
::$mCacheTTLs ) ) {
316 return self
::$mCacheTTLs[$id];
323 * Get a MagicWordArray of double-underscore entities
325 * @return MagicWordArray
327 public static function getDoubleUnderscoreArray() {
328 if ( is_null( self
::$mDoubleUnderscoreArray ) ) {
329 Hooks
::run( 'GetDoubleUnderscoreIDs', [ &self
::$mDoubleUnderscoreIDs ] );
330 self
::$mDoubleUnderscoreArray = new MagicWordArray( self
::$mDoubleUnderscoreIDs );
332 return self
::$mDoubleUnderscoreArray;
336 * Clear the self::$mObjects variable
337 * For use in parser tests
339 public static function clearCache() {
340 self
::$mObjects = [];
344 * Initialises this object with an ID
347 * @throws MWException
349 public function load( $id ) {
352 $wgContLang->getMagic( $this );
353 if ( !$this->mSynonyms
) {
354 $this->mSynonyms
= [ 'brionmademeputthishere' ];
355 throw new MWException( "Error: invalid magic word '$id'" );
360 * Preliminary initialisation
363 public function initRegex() {
364 // Sort the synonyms by length, descending, so that the longest synonym
365 // matches in precedence to the shortest
366 $synonyms = $this->mSynonyms
;
367 usort( $synonyms, [ $this, 'compareStringLength' ] );
370 foreach ( $synonyms as $synonym ) {
371 // In case a magic word contains /, like that's going to happen;)
372 $escSyn[] = preg_quote( $synonym, '/' );
374 $this->mBaseRegex
= implode( '|', $escSyn );
376 $case = $this->mCaseSensitive ?
'' : 'iu';
377 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
378 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
379 $this->mRegexStartToEnd
= "/^(?:{$this->mBaseRegex})$/{$case}";
380 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
381 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
382 "/^(?:{$this->mBaseRegex})$/{$case}" );
386 * A comparison function that returns -1, 0 or 1 depending on whether the
387 * first string is longer, the same length or shorter than the second
395 public function compareStringLength( $s1, $s2 ) {
398 return $l2 <=> $l1; // descending
402 * Gets a regex representing matching the word
406 public function getRegex() {
407 if ( $this->mRegex
== '' ) {
410 return $this->mRegex
;
414 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
415 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
416 * the complete expression
420 public function getRegexCase() {
421 if ( $this->mRegex
=== '' ) {
425 return $this->mCaseSensitive ?
'' : 'iu';
429 * Gets a regex matching the word, if it is at the string start
433 public function getRegexStart() {
434 if ( $this->mRegex
== '' ) {
437 return $this->mRegexStart
;
441 * Gets a regex matching the word from start to end of a string
446 public function getRegexStartToEnd() {
447 if ( $this->mRegexStartToEnd
== '' ) {
450 return $this->mRegexStartToEnd
;
454 * regex without the slashes and what not
458 public function getBaseRegex() {
459 if ( $this->mRegex
== '' ) {
462 return $this->mBaseRegex
;
466 * Returns true if the text contains the word
468 * @param string $text
472 public function match( $text ) {
473 return (bool)preg_match( $this->getRegex(), $text );
477 * Returns true if the text starts with the word
479 * @param string $text
483 public function matchStart( $text ) {
484 return (bool)preg_match( $this->getRegexStart(), $text );
488 * Returns true if the text matched the word
490 * @param string $text
495 public function matchStartToEnd( $text ) {
496 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
500 * Returns NULL if there's no match, the value of $1 otherwise
501 * The return code is the matched string, if there's no variable
502 * part in the regex and the matched variable part ($1) if there
505 * @param string $text
509 public function matchVariableStartToEnd( $text ) {
511 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
512 if ( $matchcount == 0 ) {
515 # multiple matched parts (variable match); some will be empty because of
516 # synonyms. The variable will be the second non-empty one so remove any
517 # blank elements and re-sort the indices.
520 $matches = array_values( array_filter( $matches ) );
522 if ( count( $matches ) == 1 ) {
531 * Returns true if the text matches the word, and alters the
532 * input string, removing all instances of the word
534 * @param string &$text
538 public function matchAndRemove( &$text ) {
539 $this->mFound
= false;
540 $text = preg_replace_callback(
542 [ $this, 'pregRemoveAndRecord' ],
546 return $this->mFound
;
550 * @param string &$text
553 public function matchStartAndRemove( &$text ) {
554 $this->mFound
= false;
555 $text = preg_replace_callback(
556 $this->getRegexStart(),
557 [ $this, 'pregRemoveAndRecord' ],
561 return $this->mFound
;
565 * Used in matchAndRemove()
569 public function pregRemoveAndRecord() {
570 $this->mFound
= true;
575 * Replaces the word with something else
577 * @param string $replacement
578 * @param string $subject
583 public function replace( $replacement, $subject, $limit = -1 ) {
586 StringUtils
::escapeRegexReplacement( $replacement ),
590 $this->mModified
= $res !== $subject;
595 * Variable handling: {{SUBST:xxx}} style words
596 * Calls back a function to determine what to replace xxx with
597 * Input word must contain $1
599 * @param string $text
600 * @param callable $callback
604 public function substituteCallback( $text, $callback ) {
605 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
606 $this->mModified
= $res !== $text;
611 * Matches the word, where $1 is a wildcard
615 public function getVariableRegex() {
616 if ( $this->mVariableRegex
== '' ) {
619 return $this->mVariableRegex
;
623 * Matches the entire string, where $1 is a wildcard
627 public function getVariableStartToEndRegex() {
628 if ( $this->mVariableStartToEndRegex
== '' ) {
631 return $this->mVariableStartToEndRegex
;
635 * Accesses the synonym list directly
641 public function getSynonym( $i ) {
642 return $this->mSynonyms
[$i];
648 public function getSynonyms() {
649 return $this->mSynonyms
;
653 * Returns true if the last call to replace() or substituteCallback()
654 * returned a modified text, otherwise false.
658 public function getWasModified() {
659 return $this->mModified
;
663 * Adds all the synonyms of this MagicWord to an array, to allow quick
664 * lookup in a list of magic words
666 * @param string[] &$array
667 * @param string $value
669 public function addToArray( &$array, $value ) {
671 foreach ( $this->mSynonyms
as $syn ) {
672 $array[$wgContLang->lc( $syn )] = $value;
679 public function isCaseSensitive() {
680 return $this->mCaseSensitive
;
686 public function getId() {