Revisions: Style action links in old revision notices as links
[mediawiki.git] / includes / parser / MagicWord.php
blobb21f3a42c0cf6cf75986d44a88bb231553c4daff
1 <?php
2 /**
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
18 * @file
21 namespace MediaWiki\Parser;
23 use MediaWiki\Language\Language;
24 use MediaWiki\MediaWikiServices;
25 use StringUtils;
26 use UnexpectedValueException;
28 /**
29 * This class encapsulates "magic words" such as "#redirect", __NOTOC__, etc.
31 * See docs/magicword.md.
33 * @par Usage:
34 * @code
35 * if ( $magicWordFactory->get( 'redirect' )->match( $text ) ) {
36 * // some code
37 * }
38 * @endcode
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[].
46 * @par Example:
47 * @code
48 * $magicWords = [];
50 * $magicWords['en'] = [
51 * 'magicwordkey' => [ 0, 'case_insensitive_magic_word' ],
52 * 'magicwordkey2' => [ 1, 'CASE_sensitive_magic_word2' ],
53 * ];
54 * @endcode
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.
62 * @since 1.1
63 * @ingroup Parser
65 class MagicWord {
67 /** @var string|null Potentially null for a short time before {@see load} is called */
68 public $mId;
70 /** @var string[] */
71 public array $mSynonyms;
73 /** @var bool */
74 public $mCaseSensitive;
76 private ?string $mBaseRegex = null;
78 private Language $contLang;
80 /**
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 ) {
88 $this->mId = $id;
89 $this->mSynonyms = (array)$syn;
90 $this->mCaseSensitive = $cs;
91 $this->contLang = $contentLanguage ?: MediaWikiServices::getInstance()->getContentLanguage();
94 /**
95 * Load synonym data from {@see LocalisationCache}.
97 * @internal For use by {@see MagicWordFactory::get} only
98 * @since 1.1
99 * @param string $id
101 public function load( $id ): void {
102 $this->mId = $id;
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
112 * @since 1.1
113 * @return string
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
126 * @return string
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
135 * @since 1.1
136 * @return string
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
145 * @since 1.23
146 * @return string
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
156 * @since 1.1
157 * @return string
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
176 * @since 1.1
177 * @param string $text
178 * @return bool
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
188 * @return bool
189 * @since 1.23
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.
201 * @since 1.1
202 * @param string &$text
203 * @return bool
205 public function matchAndRemove( &$text ): bool {
206 $text = preg_replace( $this->getRegex(), '', $text, -1, $count );
207 return (bool)$count;
211 * @param string &$text
212 * @return bool
214 public function matchStartAndRemove( &$text ): bool {
215 $text = preg_replace( $this->getRegexStart(), '', $text, -1, $count );
216 return (bool)$count;
220 * Replace any matches of this word with something else
222 * @since 1.1
223 * @param string $replacement
224 * @param string $subject
225 * @param int $limit
226 * @return string
228 public function replace( $replacement, $subject, $limit = -1 ) {
229 $res = preg_replace(
230 $this->getRegex(),
231 StringUtils::escapeRegexReplacement( $replacement ),
232 $subject,
233 $limit
235 return $res;
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
252 * fail.
254 * @since 1.1
255 * @param int $i
256 * @return string
258 public function getSynonym( $i ) {
259 return $this->mSynonyms[$i];
263 * Get full list of synonyms
265 * @since 1.7
266 * @return string[]
268 public function getSynonyms(): array {
269 return $this->mSynonyms;
273 * @since 1.7
274 * @return bool
276 public function isCaseSensitive() {
277 return $this->mCaseSensitive;
281 * @return string
282 * @deprecated since 1.42 Internal method should not be used
284 public function getId() {
285 wfDeprecated( __METHOD__, '1.42' );
286 return $this->mId;
290 /** @deprecated class alias since 1.40 */
291 class_alias( MagicWord::class, 'MagicWord' );