aboutsummaryrefslogtreecommitdiffstats
path: root/includes/parser/MagicWord.php
blob: 027fe81671f126f9773c3724ff695ee5c5a56c9c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

namespace MediaWiki\Parser;

use MediaWiki\Language\Language;
use MediaWiki\MediaWikiServices;
use StringUtils;
use UnexpectedValueException;

/**
 * This class encapsulates "magic words" such as "#redirect", __NOTOC__, etc.
 *
 * See docs/magicword.md.
 *
 * @par Usage:
 * @code
 *     if ( $magicWordFactory->get( 'redirect' )->match( $text ) ) {
 *       // some code
 *     }
 * @endcode
 *
 * Please avoid reading the data out of one of these objects and then writing
 * special case code. If possible, add another match()-like function here.
 *
 * To add magic words in an extension, use $magicWords in a file listed in
 * $wgExtensionMessagesFiles[].
 *
 * @par Example:
 * @code
 * $magicWords = [];
 *
 * $magicWords['en'] = [
 *   'magicwordkey' => [ 0, 'case_insensitive_magic_word' ],
 *   'magicwordkey2' => [ 1, 'CASE_sensitive_magic_word2' ],
 * ];
 * @endcode
 *
 * For magic words which name Parser double underscore names, add a
 * GetDoubleUnderscoreIDs hook. Use string keys.
 *
 * For magic words which name Parser magic variables, add a GetMagicVariableIDs
 * hook. Use string keys.
 *
 * @since 1.1
 * @ingroup Parser
 */
class MagicWord {

	/** @var string|null Potentially null for a short time before {@see load} is called */
	public $mId;

	/** @var string[] */
	public array $mSynonyms;

	/** @var bool */
	public $mCaseSensitive;

	private ?string $mBaseRegex = null;

	private Language $contLang;

	/**
	 * @internal Use {@see MagicWordFactory::get} instead
	 * @param string|null $id Preload internal name of the magic word
	 * @param string[]|string $syn Preload synonyms for the magic word
	 * @param bool $cs If magic word is case sensitive
	 * @param Language|null $contentLanguage
	 */
	public function __construct( $id = null, $syn = [], $cs = false, Language $contentLanguage = null ) {
		$this->mId = $id;
		$this->mSynonyms = (array)$syn;
		$this->mCaseSensitive = $cs;
		$this->contLang = $contentLanguage ?: MediaWikiServices::getInstance()->getContentLanguage();
	}

	/**
	 * Load synonym data from {@see LocalisationCache}.
	 *
	 * @internal For use by {@see MagicWordFactory::get} only
	 * @since 1.1
	 * @param string $id
	 */
	public function load( $id ): void {
		$this->mId = $id;
		$this->contLang->getMagic( $this );
		if ( !$this->mSynonyms ) {
			throw new UnexpectedValueException( "Error: invalid magic word '$id'" );
		}
	}

	/**
	 * Create a regex to match the magic word in wikitext
	 *
	 * @since 1.1
	 * @return string
	 */
	public function getRegex(): string {
		return '/' . $this->getBaseRegex() . '/' . $this->getRegexCase();
	}

	/**
	 * Get the regexp case modifier ("iu" or empty string).
	 *
	 * This is for building custom regexes that include {@see getBaseRegex}.
	 * The other getter methods return complete expressions that include this already.
	 *
	 * @internal Exposed for {@see Parser::cleanSig} only
	 * @return string
	 */
	public function getRegexCase(): string {
		return $this->mCaseSensitive ? '' : 'iu';
	}

	/**
	 * Create a regex to match the word at the start of a line in wikitext
	 *
	 * @since 1.1
	 * @return string
	 */
	public function getRegexStart(): string {
		return '/^(?:' . $this->getBaseRegex() . ')/' . $this->getRegexCase();
	}

	/**
	 * Create a regex to match the word as the only thing on a line of wikitext
	 *
	 * @since 1.23
	 * @return string
	 */
	public function getRegexStartToEnd(): string {
		return '/^(?:' . $this->getBaseRegex() . ')$/' . $this->getRegexCase();
	}

	/**
	 * Get the middle of {@see getRegex}, without the surrounding slashes or modifiers
	 *
	 * @internal Exposed for {@see Parser::cleanSig} only
	 * @since 1.1
	 * @return string
	 */
	public function getBaseRegex(): string {
		if ( $this->mBaseRegex === null ) {
			// Sort the synonyms by length, descending, so that the longest synonym
			// matches in precedence to the shortest
			$synonyms = $this->mSynonyms;
			usort( $synonyms, static fn ( $a, $b ) => strlen( $b ) <=> strlen( $a ) );
			foreach ( $synonyms as &$synonym ) {
				$synonym = preg_quote( $synonym, '/' );
			}
			$this->mBaseRegex = implode( '|', $synonyms );
		}
		return $this->mBaseRegex;
	}

	/**
	 * Check if given wikitext contains the magic word
	 *
	 * @since 1.1
	 * @param string $text
	 * @return bool
	 */
	public function match( $text ): bool {
		return (bool)preg_match( $this->getRegex(), $text );
	}

	/**
	 * Check if given wikitext contains the word as the only thing on a line
	 *
	 * @param string $text
	 * @return bool
	 * @since 1.23
	 */
	public function matchStartToEnd( $text ): bool {
		return (bool)preg_match( $this->getRegexStartToEnd(), $text );
	}

	/**
	 * Remove any matches of this magic word from a given text
	 *
	 * Returns true if the text contains one or more matches, and alters the
	 * input string to remove all instances of the magic word.
	 *
	 * @since 1.1
	 * @param string &$text
	 * @return bool
	 */
	public function matchAndRemove( &$text ): bool {
		$text = preg_replace( $this->getRegex(), '', $text, -1, $count );
		return (bool)$count;
	}

	/**
	 * @param string &$text
	 * @return bool
	 */
	public function matchStartAndRemove( &$text ): bool {
		$text = preg_replace( $this->getRegexStart(), '', $text, -1, $count );
		return (bool)$count;
	}

	/**
	 * Replace any matches of this word with something else
	 *
	 * @since 1.1
	 * @param string $replacement
	 * @param string $subject
	 * @param int $limit
	 * @return string
	 */
	public function replace( $replacement, $subject, $limit = -1 ) {
		$res = preg_replace(
			$this->getRegex(),
			StringUtils::escapeRegexReplacement( $replacement ),
			$subject,
			$limit
		);
		return $res;
	}

	/**
	 * Get one of the synonyms
	 *
	 * This exists primarily for calling `getSynonym( 0 )`, which is how
	 * you can obtain the preferred name of a magic word according to the
	 * current wiki's content language. For example, when demonstrating or
	 * semi-automatically creating content that uses a given magic word.
	 *
	 * This works because {@see LocalisationCache} merges magic word data by
	 * appending fallback languages (i.e. "en") after to the language's
	 * own data, and each language's `Messages*.php` file lists the
	 * preferred/canonical form as the first value.
	 *
	 * Calling this with a number other than 0 is unsupported and may
	 * fail.
	 *
	 * @since 1.1
	 * @param int $i
	 * @return string
	 */
	public function getSynonym( $i ) {
		return $this->mSynonyms[$i];
	}

	/**
	 * Get full list of synonyms
	 *
	 * @since 1.7
	 * @return string[]
	 */
	public function getSynonyms(): array {
		return $this->mSynonyms;
	}

	/**
	 * @since 1.7
	 * @return bool
	 */
	public function isCaseSensitive() {
		return $this->mCaseSensitive;
	}

	/**
	 * @return string
	 * @deprecated since 1.42 Internal method should not be used
	 */
	public function getId() {
		wfDeprecated( __METHOD__, '1.42' );
		return $this->mId;
	}
}

/** @deprecated class alias since 1.40 */
class_alias( MagicWord::class, 'MagicWord' );