3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Parser
;
23 use MediaWiki\Language\Language
;
24 use MediaWiki\MediaWikiServices
;
26 use UnexpectedValueException
;
29 * This class encapsulates "magic words" such as "#redirect", __NOTOC__, etc.
31 * See docs/magicword.md.
35 * if ( $magicWordFactory->get( 'redirect' )->match( $text ) ) {
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[].
50 * $magicWords['en'] = [
51 * 'magicwordkey' => [ 0, 'case_insensitive_magic_word' ],
52 * 'magicwordkey2' => [ 1, 'CASE_sensitive_magic_word2' ],
56 * For magic words which name Parser double underscore names, add a
57 * GetDoubleUnderscoreIDs hook. Use string keys.
59 * For magic words which name Parser magic variables, add a GetMagicVariableIDs
60 * hook. Use string keys.
67 /** @var string|null Potentially null for a short time before {@see load} is called */
71 public array $mSynonyms;
74 public $mCaseSensitive;
76 private ?
string $mBaseRegex = null;
78 private Language
$contLang;
81 * @internal Use {@see MagicWordFactory::get} instead
82 * @param string|null $id Preload internal name of the magic word
83 * @param string[]|string $syn Preload synonyms for the magic word
84 * @param bool $cs If magic word is case sensitive
85 * @param Language|null $contentLanguage
87 public function __construct( $id = null, $syn = [], $cs = false, ?Language
$contentLanguage = null ) {
89 $this->mSynonyms
= (array)$syn;
90 $this->mCaseSensitive
= $cs;
91 $this->contLang
= $contentLanguage ?
: MediaWikiServices
::getInstance()->getContentLanguage();
95 * Load synonym data from {@see LocalisationCache}.
97 * @internal For use by {@see MagicWordFactory::get} only
101 public function load( $id ): void
{
103 $this->contLang
->getMagic( $this );
104 if ( !$this->mSynonyms
) {
105 throw new UnexpectedValueException( "Error: invalid magic word '$id'" );
110 * Create a regex to match the magic word in wikitext
115 public function getRegex(): string {
116 return '/' . $this->getBaseRegex() . '/' . $this->getRegexCase();
120 * Get the regexp case modifier ("iu" or empty string).
122 * This is for building custom regexes that include {@see getBaseRegex}.
123 * The other getter methods return complete expressions that include this already.
125 * @internal Exposed for {@see Parser::cleanSig} only
128 public function getRegexCase(): string {
129 return $this->mCaseSensitive ?
'' : 'iu';
133 * Create a regex to match the word at the start of a line in wikitext
138 public function getRegexStart(): string {
139 return '/^(?:' . $this->getBaseRegex() . ')/' . $this->getRegexCase();
143 * Create a regex to match the word as the only thing on a line of wikitext
148 public function getRegexStartToEnd(): string {
149 return '/^(?:' . $this->getBaseRegex() . ')$/' . $this->getRegexCase();
153 * Get the middle of {@see getRegex}, without the surrounding slashes or modifiers
155 * @internal Exposed for {@see Parser::cleanSig} only
159 public function getBaseRegex(): string {
160 if ( $this->mBaseRegex
=== null ) {
161 // Sort the synonyms by length, descending, so that the longest synonym
162 // matches in precedence to the shortest
163 $synonyms = $this->mSynonyms
;
164 usort( $synonyms, static fn ( $a, $b ) => strlen( $b ) <=> strlen( $a ) );
165 foreach ( $synonyms as &$synonym ) {
166 $synonym = preg_quote( $synonym, '/' );
168 $this->mBaseRegex
= implode( '|', $synonyms );
170 return $this->mBaseRegex
;
174 * Check if given wikitext contains the magic word
177 * @param string $text
180 public function match( $text ): bool {
181 return (bool)preg_match( $this->getRegex(), $text );
185 * Check if given wikitext contains the word as the only thing on a line
187 * @param string $text
191 public function matchStartToEnd( $text ): bool {
192 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
196 * Remove any matches of this magic word from a given text
198 * Returns true if the text contains one or more matches, and alters the
199 * input string to remove all instances of the magic word.
202 * @param string &$text
205 public function matchAndRemove( &$text ): bool {
206 $text = preg_replace( $this->getRegex(), '', $text, -1, $count );
211 * @param string &$text
214 public function matchStartAndRemove( &$text ): bool {
215 $text = preg_replace( $this->getRegexStart(), '', $text, -1, $count );
220 * Replace any matches of this word with something else
223 * @param string $replacement
224 * @param string $subject
228 public function replace( $replacement, $subject, $limit = -1 ) {
231 StringUtils
::escapeRegexReplacement( $replacement ),
239 * Get one of the synonyms
241 * This exists primarily for calling `getSynonym( 0 )`, which is how
242 * you can obtain the preferred name of a magic word according to the
243 * current wiki's content language. For example, when demonstrating or
244 * semi-automatically creating content that uses a given magic word.
246 * This works because {@see LocalisationCache} merges magic word data by
247 * appending fallback languages (i.e. "en") after to the language's
248 * own data, and each language's `Messages*.php` file lists the
249 * preferred/canonical form as the first value.
251 * Calling this with a number other than 0 is unsupported and may
258 public function getSynonym( $i ) {
259 return $this->mSynonyms
[$i];
263 * Get full list of synonyms
268 public function getSynonyms(): array {
269 return $this->mSynonyms
;
276 public function isCaseSensitive() {
277 return $this->mCaseSensitive
;
282 * @deprecated since 1.42 Internal method should not be used
284 public function getId() {
285 wfDeprecated( __METHOD__
, '1.42' );
290 /** @deprecated class alias since 1.40 */
291 class_alias( MagicWord
::class, 'MagicWord' );