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;
115 $this->contLang
= MediaWikiServices
::getInstance()->getContentLanguage();
120 * Factory: creates an object representing an ID
122 * @param string $id The internal name of the magic word
125 * @deprecated since 1.32, use MagicWordFactory::get
127 public static function get( $id ) {
128 wfDeprecated( __METHOD__
, '1.32' );
129 return MediaWikiServices
::getInstance()->getMagicWordFactory()->get( $id );
133 * Get an array of parser variable IDs
136 * @deprecated since 1.32, use MagicWordFactory::getVariableIDs
138 public static function getVariableIDs() {
139 wfDeprecated( __METHOD__
, '1.32' );
140 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getVariableIDs();
144 * Get an array of parser substitution modifier IDs
146 * @deprecated since 1.32, use MagicWordFactory::getSubstIDs
148 public static function getSubstIDs() {
149 wfDeprecated( __METHOD__
, '1.32' );
150 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getSubstIDs();
154 * Allow external reads of TTL array
158 * @deprecated since 1.32, use MagicWordFactory::getCacheTTL
160 public static function getCacheTTL( $id ) {
161 wfDeprecated( __METHOD__
, '1.32' );
162 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getCacheTTL( $id );
166 * Get a MagicWordArray of double-underscore entities
168 * @return MagicWordArray
169 * @deprecated since 1.32, use MagicWordFactory::getDoubleUnderscoreArray
171 public static function getDoubleUnderscoreArray() {
172 wfDeprecated( __METHOD__
, '1.32' );
173 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getDoubleUnderscoreArray();
177 * Initialises this object with an ID
180 * @throws MWException
182 public function load( $id ) {
184 $this->contLang
->getMagic( $this );
185 if ( !$this->mSynonyms
) {
186 $this->mSynonyms
= [ 'brionmademeputthishere' ];
187 throw new MWException( "Error: invalid magic word '$id'" );
192 * Preliminary initialisation
195 public function initRegex() {
196 // Sort the synonyms by length, descending, so that the longest synonym
197 // matches in precedence to the shortest
198 $synonyms = $this->mSynonyms
;
199 usort( $synonyms, [ $this, 'compareStringLength' ] );
202 foreach ( $synonyms as $synonym ) {
203 // In case a magic word contains /, like that's going to happen;)
204 $escSyn[] = preg_quote( $synonym, '/' );
206 $this->mBaseRegex
= implode( '|', $escSyn );
208 $case = $this->mCaseSensitive ?
'' : 'iu';
209 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
210 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
211 $this->mRegexStartToEnd
= "/^(?:{$this->mBaseRegex})$/{$case}";
212 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
213 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
214 "/^(?:{$this->mBaseRegex})$/{$case}" );
218 * A comparison function that returns -1, 0 or 1 depending on whether the
219 * first string is longer, the same length or shorter than the second
227 public function compareStringLength( $s1, $s2 ) {
230 return $l2 <=> $l1; // descending
234 * Gets a regex representing matching the word
238 public function getRegex() {
239 if ( $this->mRegex
== '' ) {
242 return $this->mRegex
;
246 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
247 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
248 * the complete expression
252 public function getRegexCase() {
253 if ( $this->mRegex
=== '' ) {
257 return $this->mCaseSensitive ?
'' : 'iu';
261 * Gets a regex matching the word, if it is at the string start
265 public function getRegexStart() {
266 if ( $this->mRegex
== '' ) {
269 return $this->mRegexStart
;
273 * Gets a regex matching the word from start to end of a string
278 public function getRegexStartToEnd() {
279 if ( $this->mRegexStartToEnd
== '' ) {
282 return $this->mRegexStartToEnd
;
286 * regex without the slashes and what not
290 public function getBaseRegex() {
291 if ( $this->mRegex
== '' ) {
294 return $this->mBaseRegex
;
298 * Returns true if the text contains the word
300 * @param string $text
304 public function match( $text ) {
305 return (bool)preg_match( $this->getRegex(), $text );
309 * Returns true if the text starts with the word
311 * @param string $text
315 public function matchStart( $text ) {
316 return (bool)preg_match( $this->getRegexStart(), $text );
320 * Returns true if the text matched the word
322 * @param string $text
327 public function matchStartToEnd( $text ) {
328 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
332 * Returns NULL if there's no match, the value of $1 otherwise
333 * The return code is the matched string, if there's no variable
334 * part in the regex and the matched variable part ($1) if there
337 * @param string $text
341 public function matchVariableStartToEnd( $text ) {
343 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
344 if ( $matchcount == 0 ) {
347 # multiple matched parts (variable match); some will be empty because of
348 # synonyms. The variable will be the second non-empty one so remove any
349 # blank elements and re-sort the indices.
352 $matches = array_values( array_filter( $matches ) );
354 if ( count( $matches ) == 1 ) {
363 * Returns true if the text matches the word, and alters the
364 * input string, removing all instances of the word
366 * @param string &$text
370 public function matchAndRemove( &$text ) {
371 $this->mFound
= false;
372 $text = preg_replace_callback(
374 [ $this, 'pregRemoveAndRecord' ],
378 return $this->mFound
;
382 * @param string &$text
385 public function matchStartAndRemove( &$text ) {
386 $this->mFound
= false;
387 $text = preg_replace_callback(
388 $this->getRegexStart(),
389 [ $this, 'pregRemoveAndRecord' ],
393 return $this->mFound
;
397 * Used in matchAndRemove()
401 public function pregRemoveAndRecord() {
402 $this->mFound
= true;
407 * Replaces the word with something else
409 * @param string $replacement
410 * @param string $subject
415 public function replace( $replacement, $subject, $limit = -1 ) {
418 StringUtils
::escapeRegexReplacement( $replacement ),
422 $this->mModified
= $res !== $subject;
427 * Variable handling: {{SUBST:xxx}} style words
428 * Calls back a function to determine what to replace xxx with
429 * Input word must contain $1
431 * @param string $text
432 * @param callable $callback
436 public function substituteCallback( $text, $callback ) {
437 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
438 $this->mModified
= $res !== $text;
443 * Matches the word, where $1 is a wildcard
447 public function getVariableRegex() {
448 if ( $this->mVariableRegex
== '' ) {
451 return $this->mVariableRegex
;
455 * Matches the entire string, where $1 is a wildcard
459 public function getVariableStartToEndRegex() {
460 if ( $this->mVariableStartToEndRegex
== '' ) {
463 return $this->mVariableStartToEndRegex
;
467 * Accesses the synonym list directly
473 public function getSynonym( $i ) {
474 return $this->mSynonyms
[$i];
480 public function getSynonyms() {
481 return $this->mSynonyms
;
485 * Returns true if the last call to replace() or substituteCallback()
486 * returned a modified text, otherwise false.
490 public function getWasModified() {
491 return $this->mModified
;
495 * Adds all the synonyms of this MagicWord to an array, to allow quick
496 * lookup in a list of magic words
498 * @param string[] &$array
499 * @param string $value
501 public function addToArray( &$array, $value ) {
502 foreach ( $this->mSynonyms
as $syn ) {
503 $array[$this->contLang
->lc( $syn )] = $value;
510 public function isCaseSensitive() {
511 return $this->mCaseSensitive
;
517 public function getId() {