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
24 use MediaWiki\MediaWikiServices
;
27 * This class encapsulates "magic words" such as "#redirect", __NOTOC__, etc.
31 * if ( $magicWordFactory->get( 'redirect' )->match( $text ) ) {
36 * Please avoid reading the data out of one of these objects and then writing
37 * special case code. If possible, add another match()-like function here.
39 * To add magic words in an extension, use $magicWords in a file listed in
40 * $wgExtensionMessagesFiles[].
46 * $magicWords['en'] = [
47 * 'magicwordkey' => [ 0, 'case_insensitive_magic_word' ],
48 * 'magicwordkey2' => [ 1, 'CASE_sensitive_magic_word2' ],
52 * For magic words which are also Parser variables, add a MagicWordwgVariableIDs
53 * hook. Use string keys.
67 public $mCaseSensitive;
73 private $mRegexStart = '';
76 private $mRegexStartToEnd = '';
79 private $mBaseRegex = '';
82 private $mVariableRegex = '';
85 private $mVariableStartToEndRegex = '';
88 private $mModified = false;
91 private $mFound = false;
99 * Create a new MagicWord object
101 * Use factory instead: MagicWordFactory::get
103 * @param string|null $id The internal name of the magic word
104 * @param string[]|string $syn synonyms for the magic word
105 * @param bool $cs If magic word is case sensitive
106 * @param Language|null $contLang Content language
108 public function __construct( $id = null, $syn = [], $cs = false, Language
$contLang = null ) {
110 $this->mSynonyms
= (array)$syn;
111 $this->mCaseSensitive
= $cs;
112 $this->contLang
= $contLang ?
: MediaWikiServices
::getInstance()->getContentLanguage();
116 * Factory: creates an object representing an ID
118 * @param string $id The internal name of the magic word
121 * @deprecated since 1.32, use MagicWordFactory::get
123 public static function get( $id ) {
124 wfDeprecated( __METHOD__
, '1.32' );
125 return MediaWikiServices
::getInstance()->getMagicWordFactory()->get( $id );
129 * Get an array of parser variable IDs
132 * @deprecated since 1.32, use MagicWordFactory::getVariableIDs
134 public static function getVariableIDs() {
135 wfDeprecated( __METHOD__
, '1.32' );
136 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getVariableIDs();
140 * Get an array of parser substitution modifier IDs
142 * @deprecated since 1.32, use MagicWordFactory::getSubstIDs
144 public static function getSubstIDs() {
145 wfDeprecated( __METHOD__
, '1.32' );
146 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getSubstIDs();
150 * Allow external reads of TTL array
154 * @deprecated since 1.32, use MagicWordFactory::getCacheTTL
156 public static function getCacheTTL( $id ) {
157 wfDeprecated( __METHOD__
, '1.32' );
158 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getCacheTTL( $id );
162 * Get a MagicWordArray of double-underscore entities
164 * @return MagicWordArray
165 * @deprecated since 1.32, use MagicWordFactory::getDoubleUnderscoreArray
167 public static function getDoubleUnderscoreArray() {
168 wfDeprecated( __METHOD__
, '1.32' );
169 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getDoubleUnderscoreArray();
173 * Initialises this object with an ID
176 * @throws MWException
178 public function load( $id ) {
180 $this->contLang
->getMagic( $this );
181 if ( !$this->mSynonyms
) {
182 $this->mSynonyms
= [ 'brionmademeputthishere' ];
183 throw new MWException( "Error: invalid magic word '$id'" );
188 * Preliminary initialisation
191 public function initRegex() {
192 // Sort the synonyms by length, descending, so that the longest synonym
193 // matches in precedence to the shortest
194 $synonyms = $this->mSynonyms
;
195 usort( $synonyms, [ $this, 'compareStringLength' ] );
198 foreach ( $synonyms as $synonym ) {
199 // In case a magic word contains /, like that's going to happen;)
200 $escSyn[] = preg_quote( $synonym, '/' );
202 $this->mBaseRegex
= implode( '|', $escSyn );
204 $case = $this->mCaseSensitive ?
'' : 'iu';
205 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
206 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
207 $this->mRegexStartToEnd
= "/^(?:{$this->mBaseRegex})$/{$case}";
208 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
209 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
210 "/^(?:{$this->mBaseRegex})$/{$case}" );
214 * A comparison function that returns -1, 0 or 1 depending on whether the
215 * first string is longer, the same length or shorter than the second
223 public function compareStringLength( $s1, $s2 ) {
226 return $l2 <=> $l1; // descending
230 * Gets a regex representing matching the word
234 public function getRegex() {
235 if ( $this->mRegex
== '' ) {
238 return $this->mRegex
;
242 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
243 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
244 * the complete expression
248 public function getRegexCase() {
249 if ( $this->mRegex
=== '' ) {
253 return $this->mCaseSensitive ?
'' : 'iu';
257 * Gets a regex matching the word, if it is at the string start
261 public function getRegexStart() {
262 if ( $this->mRegex
== '' ) {
265 return $this->mRegexStart
;
269 * Gets a regex matching the word from start to end of a string
274 public function getRegexStartToEnd() {
275 if ( $this->mRegexStartToEnd
== '' ) {
278 return $this->mRegexStartToEnd
;
282 * regex without the slashes and what not
286 public function getBaseRegex() {
287 if ( $this->mRegex
== '' ) {
290 return $this->mBaseRegex
;
294 * Returns true if the text contains the word
296 * @param string $text
300 public function match( $text ) {
301 return (bool)preg_match( $this->getRegex(), $text );
305 * Returns true if the text starts with the word
307 * @param string $text
311 public function matchStart( $text ) {
312 return (bool)preg_match( $this->getRegexStart(), $text );
316 * Returns true if the text matched the word
318 * @param string $text
323 public function matchStartToEnd( $text ) {
324 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
328 * Returns NULL if there's no match, the value of $1 otherwise
329 * The return code is the matched string, if there's no variable
330 * part in the regex and the matched variable part ($1) if there
333 * @param string $text
337 public function matchVariableStartToEnd( $text ) {
339 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
340 if ( $matchcount == 0 ) {
343 # multiple matched parts (variable match); some will be empty because of
344 # synonyms. The variable will be the second non-empty one so remove any
345 # blank elements and re-sort the indices.
348 $matches = array_values( array_filter( $matches ) );
350 if ( count( $matches ) == 1 ) {
359 * Returns true if the text matches the word, and alters the
360 * input string, removing all instances of the word
362 * @param string &$text
366 public function matchAndRemove( &$text ) {
367 $this->mFound
= false;
368 $text = preg_replace_callback(
370 [ $this, 'pregRemoveAndRecord' ],
374 return $this->mFound
;
378 * @param string &$text
381 public function matchStartAndRemove( &$text ) {
382 $this->mFound
= false;
383 $text = preg_replace_callback(
384 $this->getRegexStart(),
385 [ $this, 'pregRemoveAndRecord' ],
389 return $this->mFound
;
393 * Used in matchAndRemove()
397 public function pregRemoveAndRecord() {
398 $this->mFound
= true;
403 * Replaces the word with something else
405 * @param string $replacement
406 * @param string $subject
411 public function replace( $replacement, $subject, $limit = -1 ) {
414 StringUtils
::escapeRegexReplacement( $replacement ),
418 $this->mModified
= $res !== $subject;
423 * Variable handling: {{SUBST:xxx}} style words
424 * Calls back a function to determine what to replace xxx with
425 * Input word must contain $1
427 * @param string $text
428 * @param callable $callback
432 public function substituteCallback( $text, $callback ) {
433 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
434 $this->mModified
= $res !== $text;
439 * Matches the word, where $1 is a wildcard
443 public function getVariableRegex() {
444 if ( $this->mVariableRegex
== '' ) {
447 return $this->mVariableRegex
;
451 * Matches the entire string, where $1 is a wildcard
455 public function getVariableStartToEndRegex() {
456 if ( $this->mVariableStartToEndRegex
== '' ) {
459 return $this->mVariableStartToEndRegex
;
463 * Accesses the synonym list directly
469 public function getSynonym( $i ) {
470 return $this->mSynonyms
[$i];
476 public function getSynonyms() {
477 return $this->mSynonyms
;
481 * Returns true if the last call to replace() or substituteCallback()
482 * returned a modified text, otherwise false.
486 public function getWasModified() {
487 return $this->mModified
;
491 * Adds all the synonyms of this MagicWord to an array, to allow quick
492 * lookup in a list of magic words
494 * @param string[] &$array
495 * @param string $value
497 public function addToArray( &$array, $value ) {
498 foreach ( $this->mSynonyms
as $syn ) {
499 $array[$this->contLang
->lc( $syn )] = $value;
506 public function isCaseSensitive() {
507 return $this->mCaseSensitive
;
513 public function getId() {