ParamValidator: Flag as unstable for 1.34
[lhc/web/wiklou.git] / includes / MagicWord.php
1 <?php
2 /**
3 * See docs/magicword.txt.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Parser
22 */
23
24 use MediaWiki\MediaWikiServices;
25
26 /**
27 * This class encapsulates "magic words" such as "#redirect", __NOTOC__, etc.
28 *
29 * @par Usage:
30 * @code
31 * if ( $magicWordFactory->get( 'redirect' )->match( $text ) ) {
32 * // some code
33 * }
34 * @endcode
35 *
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.
38 *
39 * To add magic words in an extension, use $magicWords in a file listed in
40 * $wgExtensionMessagesFiles[].
41 *
42 * @par Example:
43 * @code
44 * $magicWords = [];
45 *
46 * $magicWords['en'] = [
47 * 'magicwordkey' => [ 0, 'case_insensitive_magic_word' ],
48 * 'magicwordkey2' => [ 1, 'CASE_sensitive_magic_word2' ],
49 * ];
50 * @endcode
51 *
52 * For magic words which are also Parser variables, add a MagicWordwgVariableIDs
53 * hook. Use string keys.
54 *
55 * @ingroup Parser
56 */
57 class MagicWord {
58 /** #@- */
59
60 /** @var string */
61 public $mId;
62
63 /** @var string[] */
64 public $mSynonyms;
65
66 /** @var bool */
67 public $mCaseSensitive;
68
69 /** @var string */
70 private $mRegex = '';
71
72 /** @var string */
73 private $mRegexStart = '';
74
75 /** @var string */
76 private $mRegexStartToEnd = '';
77
78 /** @var string */
79 private $mBaseRegex = '';
80
81 /** @var string */
82 private $mVariableRegex = '';
83
84 /** @var string */
85 private $mVariableStartToEndRegex = '';
86
87 /** @var bool */
88 private $mModified = false;
89
90 /** @var bool */
91 private $mFound = false;
92
93 /** @var Language */
94 private $contLang;
95
96 /** #@- */
97
98 /**
99 * Create a new MagicWord object
100 *
101 * Use factory instead: MagicWordFactory::get
102 *
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
107 */
108 public function __construct( $id = null, $syn = [], $cs = false, Language $contLang = null ) {
109 $this->mId = $id;
110 $this->mSynonyms = (array)$syn;
111 $this->mCaseSensitive = $cs;
112 $this->contLang = $contLang ?: MediaWikiServices::getInstance()->getContentLanguage();
113 }
114
115 /**
116 * Factory: creates an object representing an ID
117 *
118 * @param string $id The internal name of the magic word
119 *
120 * @return MagicWord
121 * @deprecated since 1.32, use MagicWordFactory::get
122 */
123 public static function get( $id ) {
124 wfDeprecated( __METHOD__, '1.32' );
125 return MediaWikiServices::getInstance()->getMagicWordFactory()->get( $id );
126 }
127
128 /**
129 * Get an array of parser variable IDs
130 *
131 * @return string[]
132 * @deprecated since 1.32, use MagicWordFactory::getVariableIDs
133 */
134 public static function getVariableIDs() {
135 wfDeprecated( __METHOD__, '1.32' );
136 return MediaWikiServices::getInstance()->getMagicWordFactory()->getVariableIDs();
137 }
138
139 /**
140 * Get an array of parser substitution modifier IDs
141 * @return string[]
142 * @deprecated since 1.32, use MagicWordFactory::getSubstIDs
143 */
144 public static function getSubstIDs() {
145 wfDeprecated( __METHOD__, '1.32' );
146 return MediaWikiServices::getInstance()->getMagicWordFactory()->getSubstIDs();
147 }
148
149 /**
150 * Allow external reads of TTL array
151 *
152 * @param string $id
153 * @return int
154 * @deprecated since 1.32, use MagicWordFactory::getCacheTTL
155 */
156 public static function getCacheTTL( $id ) {
157 wfDeprecated( __METHOD__, '1.32' );
158 return MediaWikiServices::getInstance()->getMagicWordFactory()->getCacheTTL( $id );
159 }
160
161 /**
162 * Get a MagicWordArray of double-underscore entities
163 *
164 * @return MagicWordArray
165 * @deprecated since 1.32, use MagicWordFactory::getDoubleUnderscoreArray
166 */
167 public static function getDoubleUnderscoreArray() {
168 wfDeprecated( __METHOD__, '1.32' );
169 return MediaWikiServices::getInstance()->getMagicWordFactory()->getDoubleUnderscoreArray();
170 }
171
172 /**
173 * Initialises this object with an ID
174 *
175 * @param string $id
176 * @throws MWException
177 */
178 public function load( $id ) {
179 $this->mId = $id;
180 $this->contLang->getMagic( $this );
181 if ( !$this->mSynonyms ) {
182 $this->mSynonyms = [ 'brionmademeputthishere' ];
183 throw new MWException( "Error: invalid magic word '$id'" );
184 }
185 }
186
187 /**
188 * Preliminary initialisation
189 * @private
190 */
191 public function initRegex() {
192 // Sort the synonyms by length, descending, so that the longest synonym
193 // matches in precedence to the shortest
194 $synonyms = $this->mSynonyms;
195 usort( $synonyms, [ $this, 'compareStringLength' ] );
196
197 $escSyn = [];
198 foreach ( $synonyms as $synonym ) {
199 // In case a magic word contains /, like that's going to happen;)
200 $escSyn[] = preg_quote( $synonym, '/' );
201 }
202 $this->mBaseRegex = implode( '|', $escSyn );
203
204 $case = $this->mCaseSensitive ? '' : 'iu';
205 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
206 $this->mRegexStart = "/^(?:{$this->mBaseRegex})/{$case}";
207 $this->mRegexStartToEnd = "/^(?:{$this->mBaseRegex})$/{$case}";
208 $this->mVariableRegex = str_replace( "\\$1", "(.*?)", $this->mRegex );
209 $this->mVariableStartToEndRegex = str_replace( "\\$1", "(.*?)",
210 "/^(?:{$this->mBaseRegex})$/{$case}" );
211 }
212
213 /**
214 * A comparison function that returns -1, 0 or 1 depending on whether the
215 * first string is longer, the same length or shorter than the second
216 * string.
217 *
218 * @param string $s1
219 * @param string $s2
220 *
221 * @return int
222 */
223 public function compareStringLength( $s1, $s2 ) {
224 $l1 = strlen( $s1 );
225 $l2 = strlen( $s2 );
226 return $l2 <=> $l1; // descending
227 }
228
229 /**
230 * Gets a regex representing matching the word
231 *
232 * @return string
233 */
234 public function getRegex() {
235 if ( $this->mRegex == '' ) {
236 $this->initRegex();
237 }
238 return $this->mRegex;
239 }
240
241 /**
242 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
243 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
244 * the complete expression
245 *
246 * @return string
247 */
248 public function getRegexCase() {
249 if ( $this->mRegex === '' ) {
250 $this->initRegex();
251 }
252
253 return $this->mCaseSensitive ? '' : 'iu';
254 }
255
256 /**
257 * Gets a regex matching the word, if it is at the string start
258 *
259 * @return string
260 */
261 public function getRegexStart() {
262 if ( $this->mRegex == '' ) {
263 $this->initRegex();
264 }
265 return $this->mRegexStart;
266 }
267
268 /**
269 * Gets a regex matching the word from start to end of a string
270 *
271 * @return string
272 * @since 1.23
273 */
274 public function getRegexStartToEnd() {
275 if ( $this->mRegexStartToEnd == '' ) {
276 $this->initRegex();
277 }
278 return $this->mRegexStartToEnd;
279 }
280
281 /**
282 * regex without the slashes and what not
283 *
284 * @return string
285 */
286 public function getBaseRegex() {
287 if ( $this->mRegex == '' ) {
288 $this->initRegex();
289 }
290 return $this->mBaseRegex;
291 }
292
293 /**
294 * Returns true if the text contains the word
295 *
296 * @param string $text
297 *
298 * @return bool
299 */
300 public function match( $text ) {
301 return (bool)preg_match( $this->getRegex(), $text );
302 }
303
304 /**
305 * Returns true if the text starts with the word
306 *
307 * @param string $text
308 *
309 * @return bool
310 */
311 public function matchStart( $text ) {
312 return (bool)preg_match( $this->getRegexStart(), $text );
313 }
314
315 /**
316 * Returns true if the text matched the word
317 *
318 * @param string $text
319 *
320 * @return bool
321 * @since 1.23
322 */
323 public function matchStartToEnd( $text ) {
324 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
325 }
326
327 /**
328 * Returns NULL if there's no match, the value of $1 otherwise
329 * The return code is the matched string, if there's no variable
330 * part in the regex and the matched variable part ($1) if there
331 * is one.
332 *
333 * @param string $text
334 *
335 * @return string
336 */
337 public function matchVariableStartToEnd( $text ) {
338 $matches = [];
339 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
340 if ( $matchcount == 0 ) {
341 return null;
342 } else {
343 # multiple matched parts (variable match); some will be empty because of
344 # synonyms. The variable will be the second non-empty one so remove any
345 # blank elements and re-sort the indices.
346 # See also T8526
347
348 $matches = array_values( array_filter( $matches ) );
349
350 if ( count( $matches ) == 1 ) {
351 return $matches[0];
352 } else {
353 return $matches[1];
354 }
355 }
356 }
357
358 /**
359 * Returns true if the text matches the word, and alters the
360 * input string, removing all instances of the word
361 *
362 * @param string &$text
363 *
364 * @return bool
365 */
366 public function matchAndRemove( &$text ) {
367 $this->mFound = false;
368 $text = preg_replace_callback(
369 $this->getRegex(),
370 [ $this, 'pregRemoveAndRecord' ],
371 $text
372 );
373
374 return $this->mFound;
375 }
376
377 /**
378 * @param string &$text
379 * @return bool
380 */
381 public function matchStartAndRemove( &$text ) {
382 $this->mFound = false;
383 $text = preg_replace_callback(
384 $this->getRegexStart(),
385 [ $this, 'pregRemoveAndRecord' ],
386 $text
387 );
388
389 return $this->mFound;
390 }
391
392 /**
393 * Used in matchAndRemove()
394 *
395 * @return string
396 */
397 public function pregRemoveAndRecord() {
398 $this->mFound = true;
399 return '';
400 }
401
402 /**
403 * Replaces the word with something else
404 *
405 * @param string $replacement
406 * @param string $subject
407 * @param int $limit
408 *
409 * @return string
410 */
411 public function replace( $replacement, $subject, $limit = -1 ) {
412 $res = preg_replace(
413 $this->getRegex(),
414 StringUtils::escapeRegexReplacement( $replacement ),
415 $subject,
416 $limit
417 );
418 $this->mModified = $res !== $subject;
419 return $res;
420 }
421
422 /**
423 * Variable handling: {{SUBST:xxx}} style words
424 * Calls back a function to determine what to replace xxx with
425 * Input word must contain $1
426 *
427 * @param string $text
428 * @param callable $callback
429 *
430 * @return string
431 */
432 public function substituteCallback( $text, $callback ) {
433 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
434 $this->mModified = $res !== $text;
435 return $res;
436 }
437
438 /**
439 * Matches the word, where $1 is a wildcard
440 *
441 * @return string
442 */
443 public function getVariableRegex() {
444 if ( $this->mVariableRegex == '' ) {
445 $this->initRegex();
446 }
447 return $this->mVariableRegex;
448 }
449
450 /**
451 * Matches the entire string, where $1 is a wildcard
452 *
453 * @return string
454 */
455 public function getVariableStartToEndRegex() {
456 if ( $this->mVariableStartToEndRegex == '' ) {
457 $this->initRegex();
458 }
459 return $this->mVariableStartToEndRegex;
460 }
461
462 /**
463 * Accesses the synonym list directly
464 *
465 * @param int $i
466 *
467 * @return string
468 */
469 public function getSynonym( $i ) {
470 return $this->mSynonyms[$i];
471 }
472
473 /**
474 * @return string[]
475 */
476 public function getSynonyms() {
477 return $this->mSynonyms;
478 }
479
480 /**
481 * Returns true if the last call to replace() or substituteCallback()
482 * returned a modified text, otherwise false.
483 *
484 * @return bool
485 */
486 public function getWasModified() {
487 return $this->mModified;
488 }
489
490 /**
491 * Adds all the synonyms of this MagicWord to an array, to allow quick
492 * lookup in a list of magic words
493 *
494 * @param string[] &$array
495 * @param string $value
496 */
497 public function addToArray( &$array, $value ) {
498 foreach ( $this->mSynonyms as $syn ) {
499 $array[$this->contLang->lc( $syn )] = $value;
500 }
501 }
502
503 /**
504 * @return bool
505 */
506 public function isCaseSensitive() {
507 return $this->mCaseSensitive;
508 }
509
510 /**
511 * @return string
512 */
513 public function getId() {
514 return $this->mId;
515 }
516 }