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 return MediaWikiServices
::getInstance()->getMagicWordFactory()->get( $id );
132 * Get an array of parser variable IDs
135 * @deprecated since 1.32, use MagicWordFactory::getVariableIDs
137 public static function getVariableIDs() {
138 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getVariableIDs();
142 * Get an array of parser substitution modifier IDs
144 * @deprecated since 1.32, use MagicWordFactory::getSubstIDs
146 public static function getSubstIDs() {
147 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getSubstIDs();
151 * Allow external reads of TTL array
155 * @deprecated since 1.32, use MagicWordFactory::getCacheTTL
157 public static function getCacheTTL( $id ) {
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 return MediaWikiServices
::getInstance()->getMagicWordFactory()->getDoubleUnderscoreArray();
172 * Initialises this object with an ID
175 * @throws MWException
177 public function load( $id ) {
179 $this->contLang
->getMagic( $this );
180 if ( !$this->mSynonyms
) {
181 $this->mSynonyms
= [ 'brionmademeputthishere' ];
182 throw new MWException( "Error: invalid magic word '$id'" );
187 * Preliminary initialisation
190 public function initRegex() {
191 // Sort the synonyms by length, descending, so that the longest synonym
192 // matches in precedence to the shortest
193 $synonyms = $this->mSynonyms
;
194 usort( $synonyms, [ $this, 'compareStringLength' ] );
197 foreach ( $synonyms as $synonym ) {
198 // In case a magic word contains /, like that's going to happen;)
199 $escSyn[] = preg_quote( $synonym, '/' );
201 $this->mBaseRegex
= implode( '|', $escSyn );
203 $case = $this->mCaseSensitive ?
'' : 'iu';
204 $this->mRegex
= "/{$this->mBaseRegex}/{$case}";
205 $this->mRegexStart
= "/^(?:{$this->mBaseRegex})/{$case}";
206 $this->mRegexStartToEnd
= "/^(?:{$this->mBaseRegex})$/{$case}";
207 $this->mVariableRegex
= str_replace( "\\$1", "(.*?)", $this->mRegex
);
208 $this->mVariableStartToEndRegex
= str_replace( "\\$1", "(.*?)",
209 "/^(?:{$this->mBaseRegex})$/{$case}" );
213 * A comparison function that returns -1, 0 or 1 depending on whether the
214 * first string is longer, the same length or shorter than the second
222 public function compareStringLength( $s1, $s2 ) {
225 return $l2 <=> $l1; // descending
229 * Gets a regex representing matching the word
233 public function getRegex() {
234 if ( $this->mRegex
== '' ) {
237 return $this->mRegex
;
241 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
242 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
243 * the complete expression
247 public function getRegexCase() {
248 if ( $this->mRegex
=== '' ) {
252 return $this->mCaseSensitive ?
'' : 'iu';
256 * Gets a regex matching the word, if it is at the string start
260 public function getRegexStart() {
261 if ( $this->mRegex
== '' ) {
264 return $this->mRegexStart
;
268 * Gets a regex matching the word from start to end of a string
273 public function getRegexStartToEnd() {
274 if ( $this->mRegexStartToEnd
== '' ) {
277 return $this->mRegexStartToEnd
;
281 * regex without the slashes and what not
285 public function getBaseRegex() {
286 if ( $this->mRegex
== '' ) {
289 return $this->mBaseRegex
;
293 * Returns true if the text contains the word
295 * @param string $text
299 public function match( $text ) {
300 return (bool)preg_match( $this->getRegex(), $text );
304 * Returns true if the text starts with the word
306 * @param string $text
310 public function matchStart( $text ) {
311 return (bool)preg_match( $this->getRegexStart(), $text );
315 * Returns true if the text matched the word
317 * @param string $text
322 public function matchStartToEnd( $text ) {
323 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
327 * Returns NULL if there's no match, the value of $1 otherwise
328 * The return code is the matched string, if there's no variable
329 * part in the regex and the matched variable part ($1) if there
332 * @param string $text
336 public function matchVariableStartToEnd( $text ) {
338 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
339 if ( $matchcount == 0 ) {
342 # multiple matched parts (variable match); some will be empty because of
343 # synonyms. The variable will be the second non-empty one so remove any
344 # blank elements and re-sort the indices.
347 $matches = array_values( array_filter( $matches ) );
349 if ( count( $matches ) == 1 ) {
358 * Returns true if the text matches the word, and alters the
359 * input string, removing all instances of the word
361 * @param string &$text
365 public function matchAndRemove( &$text ) {
366 $this->mFound
= false;
367 $text = preg_replace_callback(
369 [ $this, 'pregRemoveAndRecord' ],
373 return $this->mFound
;
377 * @param string &$text
380 public function matchStartAndRemove( &$text ) {
381 $this->mFound
= false;
382 $text = preg_replace_callback(
383 $this->getRegexStart(),
384 [ $this, 'pregRemoveAndRecord' ],
388 return $this->mFound
;
392 * Used in matchAndRemove()
396 public function pregRemoveAndRecord() {
397 $this->mFound
= true;
402 * Replaces the word with something else
404 * @param string $replacement
405 * @param string $subject
410 public function replace( $replacement, $subject, $limit = -1 ) {
413 StringUtils
::escapeRegexReplacement( $replacement ),
417 $this->mModified
= $res !== $subject;
422 * Variable handling: {{SUBST:xxx}} style words
423 * Calls back a function to determine what to replace xxx with
424 * Input word must contain $1
426 * @param string $text
427 * @param callable $callback
431 public function substituteCallback( $text, $callback ) {
432 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
433 $this->mModified
= $res !== $text;
438 * Matches the word, where $1 is a wildcard
442 public function getVariableRegex() {
443 if ( $this->mVariableRegex
== '' ) {
446 return $this->mVariableRegex
;
450 * Matches the entire string, where $1 is a wildcard
454 public function getVariableStartToEndRegex() {
455 if ( $this->mVariableStartToEndRegex
== '' ) {
458 return $this->mVariableStartToEndRegex
;
462 * Accesses the synonym list directly
468 public function getSynonym( $i ) {
469 return $this->mSynonyms
[$i];
475 public function getSynonyms() {
476 return $this->mSynonyms
;
480 * Returns true if the last call to replace() or substituteCallback()
481 * returned a modified text, otherwise false.
485 public function getWasModified() {
486 return $this->mModified
;
490 * Adds all the synonyms of this MagicWord to an array, to allow quick
491 * lookup in a list of magic words
493 * @param string[] &$array
494 * @param string $value
496 public function addToArray( &$array, $value ) {
497 foreach ( $this->mSynonyms
as $syn ) {
498 $array[$this->contLang
->lc( $syn )] = $value;
505 public function isCaseSensitive() {
506 return $this->mCaseSensitive
;
512 public function getId() {