Merge "Use MediaWiki\SuppressWarnings around trigger_error('') instead @"
[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;
113
114 if ( !$contLang ) {
115 $this->contLang = MediaWikiServices::getInstance()->getContentLanguage();
116 }
117 }
118
119 /**
120 * Factory: creates an object representing an ID
121 *
122 * @param string $id The internal name of the magic word
123 *
124 * @return MagicWord
125 * @deprecated since 1.32, use MagicWordFactory::get
126 */
127 public static function get( $id ) {
128 return MediaWikiServices::getInstance()->getMagicWordFactory()->get( $id );
129 }
130
131 /**
132 * Get an array of parser variable IDs
133 *
134 * @return string[]
135 * @deprecated since 1.32, use MagicWordFactory::getVariableIDs
136 */
137 public static function getVariableIDs() {
138 return MediaWikiServices::getInstance()->getMagicWordFactory()->getVariableIDs();
139 }
140
141 /**
142 * Get an array of parser substitution modifier IDs
143 * @return string[]
144 * @deprecated since 1.32, use MagicWordFactory::getSubstIDs
145 */
146 public static function getSubstIDs() {
147 return MediaWikiServices::getInstance()->getMagicWordFactory()->getSubstIDs();
148 }
149
150 /**
151 * Allow external reads of TTL array
152 *
153 * @param string $id
154 * @return int
155 * @deprecated since 1.32, use MagicWordFactory::getCacheTTL
156 */
157 public static function getCacheTTL( $id ) {
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 return MediaWikiServices::getInstance()->getMagicWordFactory()->getDoubleUnderscoreArray();
169 }
170
171 /**
172 * Initialises this object with an ID
173 *
174 * @param string $id
175 * @throws MWException
176 */
177 public function load( $id ) {
178 $this->mId = $id;
179 $this->contLang->getMagic( $this );
180 if ( !$this->mSynonyms ) {
181 $this->mSynonyms = [ 'brionmademeputthishere' ];
182 throw new MWException( "Error: invalid magic word '$id'" );
183 }
184 }
185
186 /**
187 * Preliminary initialisation
188 * @private
189 */
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' ] );
195
196 $escSyn = [];
197 foreach ( $synonyms as $synonym ) {
198 // In case a magic word contains /, like that's going to happen;)
199 $escSyn[] = preg_quote( $synonym, '/' );
200 }
201 $this->mBaseRegex = implode( '|', $escSyn );
202
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}" );
210 }
211
212 /**
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
215 * string.
216 *
217 * @param string $s1
218 * @param string $s2
219 *
220 * @return int
221 */
222 public function compareStringLength( $s1, $s2 ) {
223 $l1 = strlen( $s1 );
224 $l2 = strlen( $s2 );
225 return $l2 <=> $l1; // descending
226 }
227
228 /**
229 * Gets a regex representing matching the word
230 *
231 * @return string
232 */
233 public function getRegex() {
234 if ( $this->mRegex == '' ) {
235 $this->initRegex();
236 }
237 return $this->mRegex;
238 }
239
240 /**
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
244 *
245 * @return string
246 */
247 public function getRegexCase() {
248 if ( $this->mRegex === '' ) {
249 $this->initRegex();
250 }
251
252 return $this->mCaseSensitive ? '' : 'iu';
253 }
254
255 /**
256 * Gets a regex matching the word, if it is at the string start
257 *
258 * @return string
259 */
260 public function getRegexStart() {
261 if ( $this->mRegex == '' ) {
262 $this->initRegex();
263 }
264 return $this->mRegexStart;
265 }
266
267 /**
268 * Gets a regex matching the word from start to end of a string
269 *
270 * @return string
271 * @since 1.23
272 */
273 public function getRegexStartToEnd() {
274 if ( $this->mRegexStartToEnd == '' ) {
275 $this->initRegex();
276 }
277 return $this->mRegexStartToEnd;
278 }
279
280 /**
281 * regex without the slashes and what not
282 *
283 * @return string
284 */
285 public function getBaseRegex() {
286 if ( $this->mRegex == '' ) {
287 $this->initRegex();
288 }
289 return $this->mBaseRegex;
290 }
291
292 /**
293 * Returns true if the text contains the word
294 *
295 * @param string $text
296 *
297 * @return bool
298 */
299 public function match( $text ) {
300 return (bool)preg_match( $this->getRegex(), $text );
301 }
302
303 /**
304 * Returns true if the text starts with the word
305 *
306 * @param string $text
307 *
308 * @return bool
309 */
310 public function matchStart( $text ) {
311 return (bool)preg_match( $this->getRegexStart(), $text );
312 }
313
314 /**
315 * Returns true if the text matched the word
316 *
317 * @param string $text
318 *
319 * @return bool
320 * @since 1.23
321 */
322 public function matchStartToEnd( $text ) {
323 return (bool)preg_match( $this->getRegexStartToEnd(), $text );
324 }
325
326 /**
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
330 * is one.
331 *
332 * @param string $text
333 *
334 * @return string
335 */
336 public function matchVariableStartToEnd( $text ) {
337 $matches = [];
338 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
339 if ( $matchcount == 0 ) {
340 return null;
341 } else {
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.
345 # See also T8526
346
347 $matches = array_values( array_filter( $matches ) );
348
349 if ( count( $matches ) == 1 ) {
350 return $matches[0];
351 } else {
352 return $matches[1];
353 }
354 }
355 }
356
357 /**
358 * Returns true if the text matches the word, and alters the
359 * input string, removing all instances of the word
360 *
361 * @param string &$text
362 *
363 * @return bool
364 */
365 public function matchAndRemove( &$text ) {
366 $this->mFound = false;
367 $text = preg_replace_callback(
368 $this->getRegex(),
369 [ $this, 'pregRemoveAndRecord' ],
370 $text
371 );
372
373 return $this->mFound;
374 }
375
376 /**
377 * @param string &$text
378 * @return bool
379 */
380 public function matchStartAndRemove( &$text ) {
381 $this->mFound = false;
382 $text = preg_replace_callback(
383 $this->getRegexStart(),
384 [ $this, 'pregRemoveAndRecord' ],
385 $text
386 );
387
388 return $this->mFound;
389 }
390
391 /**
392 * Used in matchAndRemove()
393 *
394 * @return string
395 */
396 public function pregRemoveAndRecord() {
397 $this->mFound = true;
398 return '';
399 }
400
401 /**
402 * Replaces the word with something else
403 *
404 * @param string $replacement
405 * @param string $subject
406 * @param int $limit
407 *
408 * @return string
409 */
410 public function replace( $replacement, $subject, $limit = -1 ) {
411 $res = preg_replace(
412 $this->getRegex(),
413 StringUtils::escapeRegexReplacement( $replacement ),
414 $subject,
415 $limit
416 );
417 $this->mModified = $res !== $subject;
418 return $res;
419 }
420
421 /**
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
425 *
426 * @param string $text
427 * @param callable $callback
428 *
429 * @return string
430 */
431 public function substituteCallback( $text, $callback ) {
432 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
433 $this->mModified = $res !== $text;
434 return $res;
435 }
436
437 /**
438 * Matches the word, where $1 is a wildcard
439 *
440 * @return string
441 */
442 public function getVariableRegex() {
443 if ( $this->mVariableRegex == '' ) {
444 $this->initRegex();
445 }
446 return $this->mVariableRegex;
447 }
448
449 /**
450 * Matches the entire string, where $1 is a wildcard
451 *
452 * @return string
453 */
454 public function getVariableStartToEndRegex() {
455 if ( $this->mVariableStartToEndRegex == '' ) {
456 $this->initRegex();
457 }
458 return $this->mVariableStartToEndRegex;
459 }
460
461 /**
462 * Accesses the synonym list directly
463 *
464 * @param int $i
465 *
466 * @return string
467 */
468 public function getSynonym( $i ) {
469 return $this->mSynonyms[$i];
470 }
471
472 /**
473 * @return string[]
474 */
475 public function getSynonyms() {
476 return $this->mSynonyms;
477 }
478
479 /**
480 * Returns true if the last call to replace() or substituteCallback()
481 * returned a modified text, otherwise false.
482 *
483 * @return bool
484 */
485 public function getWasModified() {
486 return $this->mModified;
487 }
488
489 /**
490 * Adds all the synonyms of this MagicWord to an array, to allow quick
491 * lookup in a list of magic words
492 *
493 * @param string[] &$array
494 * @param string $value
495 */
496 public function addToArray( &$array, $value ) {
497 foreach ( $this->mSynonyms as $syn ) {
498 $array[$this->contLang->lc( $syn )] = $value;
499 }
500 }
501
502 /**
503 * @return bool
504 */
505 public function isCaseSensitive() {
506 return $this->mCaseSensitive;
507 }
508
509 /**
510 * @return string
511 */
512 public function getId() {
513 return $this->mId;
514 }
515 }