Follow-up to r37968: forgot to commit the change setRobotpolicy -> setRobotPolicy...
[lhc/web/wiklou.git] / includes / MagicWord.php
1 <?php
2 /**
3 * File for magic words
4 * See docs/magicword.txt
5 *
6 * @file
7 * @ingroup Parser
8 */
9
10 /**
11 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
12 * Usage:
13 * if (MagicWord::get( 'redirect' )->match( $text ) )
14 *
15 * Possible future improvements:
16 * * Simultaneous searching for a number of magic words
17 * * MagicWord::$mObjects in shared memory
18 *
19 * Please avoid reading the data out of one of these objects and then writing
20 * special case code. If possible, add another match()-like function here.
21 *
22 * To add magic words in an extension, use the LanguageGetMagic hook. For
23 * magic words which are also Parser variables, add a MagicWordwgVariableIDs
24 * hook. Use string keys.
25 *
26 * @ingroup Parser
27 */
28 class MagicWord {
29 /**#@+
30 * @private
31 */
32 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
33 var $mRegexStart, $mBaseRegex, $mVariableRegex;
34 var $mModified, $mFound;
35
36 static public $mVariableIDsInitialised = false;
37 static public $mVariableIDs = array(
38 'currentmonth',
39 'currentmonthname',
40 'currentmonthnamegen',
41 'currentmonthabbrev',
42 'currentday',
43 'currentday2',
44 'currentdayname',
45 'currentyear',
46 'currenttime',
47 'currenthour',
48 'localmonth',
49 'localmonthname',
50 'localmonthnamegen',
51 'localmonthabbrev',
52 'localday',
53 'localday2',
54 'localdayname',
55 'localyear',
56 'localtime',
57 'localhour',
58 'numberofarticles',
59 'numberoffiles',
60 'numberofedits',
61 'sitename',
62 'server',
63 'servername',
64 'scriptpath',
65 'pagename',
66 'pagenamee',
67 'fullpagename',
68 'fullpagenamee',
69 'namespace',
70 'namespacee',
71 'currentweek',
72 'currentdow',
73 'localweek',
74 'localdow',
75 'revisionid',
76 'revisionday',
77 'revisionday2',
78 'revisionmonth',
79 'revisionyear',
80 'revisiontimestamp',
81 'subpagename',
82 'subpagenamee',
83 'displaytitle',
84 'talkspace',
85 'talkspacee',
86 'subjectspace',
87 'subjectspacee',
88 'talkpagename',
89 'talkpagenamee',
90 'subjectpagename',
91 'subjectpagenamee',
92 'numberofusers',
93 'newsectionlink',
94 'numberofpages',
95 'currentversion',
96 'basepagename',
97 'basepagenamee',
98 'urlencode',
99 'currenttimestamp',
100 'localtimestamp',
101 'directionmark',
102 'language',
103 'contentlanguage',
104 'pagesinnamespace',
105 'numberofadmins',
106 'defaultsort',
107 'pagesincategory',
108 'index',
109 'noindex',
110 );
111
112 /* Array of caching hints for ParserCache */
113 static public $mCacheTTLs = array (
114 'currentmonth' => 86400,
115 'currentmonthname' => 86400,
116 'currentmonthnamegen' => 86400,
117 'currentmonthabbrev' => 86400,
118 'currentday' => 3600,
119 'currentday2' => 3600,
120 'currentdayname' => 3600,
121 'currentyear' => 86400,
122 'currenttime' => 3600,
123 'currenthour' => 3600,
124 'localmonth' => 86400,
125 'localmonthname' => 86400,
126 'localmonthnamegen' => 86400,
127 'localmonthabbrev' => 86400,
128 'localday' => 3600,
129 'localday2' => 3600,
130 'localdayname' => 3600,
131 'localyear' => 86400,
132 'localtime' => 3600,
133 'localhour' => 3600,
134 'numberofarticles' => 3600,
135 'numberoffiles' => 3600,
136 'numberofedits' => 3600,
137 'currentweek' => 3600,
138 'currentdow' => 3600,
139 'localweek' => 3600,
140 'localdow' => 3600,
141 'numberofusers' => 3600,
142 'numberofpages' => 3600,
143 'currentversion' => 86400,
144 'currenttimestamp' => 3600,
145 'localtimestamp' => 3600,
146 'pagesinnamespace' => 3600,
147 'numberofadmins' => 3600,
148 );
149
150 static public $mDoubleUnderscoreIDs = array(
151 'notoc',
152 'nogallery',
153 'forcetoc',
154 'toc',
155 'noeditsection',
156 'newsectionlink',
157 'hiddencat',
158 'index',
159 'noindex',
160 );
161
162
163 static public $mObjects = array();
164 static public $mDoubleUnderscoreArray = null;
165
166 /**#@-*/
167
168 function __construct($id = 0, $syn = '', $cs = false) {
169 $this->mId = $id;
170 $this->mSynonyms = (array)$syn;
171 $this->mCaseSensitive = $cs;
172 $this->mRegex = '';
173 $this->mRegexStart = '';
174 $this->mVariableRegex = '';
175 $this->mVariableStartToEndRegex = '';
176 $this->mModified = false;
177 }
178
179 /**
180 * Factory: creates an object representing an ID
181 * @static
182 */
183 static function &get( $id ) {
184 wfProfileIn( __METHOD__ );
185 if (!array_key_exists( $id, self::$mObjects ) ) {
186 $mw = new MagicWord();
187 $mw->load( $id );
188 self::$mObjects[$id] = $mw;
189 }
190 wfProfileOut( __METHOD__ );
191 return self::$mObjects[$id];
192 }
193
194 /**
195 * Get an array of parser variable IDs
196 */
197 static function getVariableIDs() {
198 if ( !self::$mVariableIDsInitialised ) {
199 # Deprecated constant definition hook, available for extensions that need it
200 $magicWords = array();
201 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
202 foreach ( $magicWords as $word ) {
203 define( $word, $word );
204 }
205
206 # Get variable IDs
207 wfRunHooks( 'MagicWordwgVariableIDs', array( &self::$mVariableIDs ) );
208 self::$mVariableIDsInitialised = true;
209 }
210 return self::$mVariableIDs;
211 }
212
213 /* Allow external reads of TTL array */
214 static function getCacheTTL($id) {
215 if (array_key_exists($id,self::$mCacheTTLs)) {
216 return self::$mCacheTTLs[$id];
217 } else {
218 return -1;
219 }
220 }
221
222 /** Get a MagicWordArray of double-underscore entities */
223 static function getDoubleUnderscoreArray() {
224 if ( is_null( self::$mDoubleUnderscoreArray ) ) {
225 self::$mDoubleUnderscoreArray = new MagicWordArray( self::$mDoubleUnderscoreIDs );
226 }
227 return self::$mDoubleUnderscoreArray;
228 }
229
230 # Initialises this object with an ID
231 function load( $id ) {
232 global $wgContLang;
233 $this->mId = $id;
234 $wgContLang->getMagic( $this );
235 if ( !$this->mSynonyms ) {
236 $this->mSynonyms = array( 'dkjsagfjsgashfajsh' );
237 #throw new MWException( "Error: invalid magic word '$id'" );
238 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
239 }
240 }
241
242 /**
243 * Preliminary initialisation
244 * @private
245 */
246 function initRegex() {
247 #$variableClass = Title::legalChars();
248 # This was used for matching "$1" variables, but different uses of the feature will have
249 # different restrictions, which should be checked *after* the MagicWord has been matched,
250 # not here. - IMSoP
251
252 $escSyn = array();
253 foreach ( $this->mSynonyms as $synonym )
254 // In case a magic word contains /, like that's going to happen;)
255 $escSyn[] = preg_quote( $synonym, '/' );
256 $this->mBaseRegex = implode( '|', $escSyn );
257
258 $case = $this->mCaseSensitive ? '' : 'iu';
259 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
260 $this->mRegexStart = "/^(?:{$this->mBaseRegex})/{$case}";
261 $this->mVariableRegex = str_replace( "\\$1", "(.*?)", $this->mRegex );
262 $this->mVariableStartToEndRegex = str_replace( "\\$1", "(.*?)",
263 "/^(?:{$this->mBaseRegex})$/{$case}" );
264 }
265
266 /**
267 * Gets a regex representing matching the word
268 */
269 function getRegex() {
270 if ($this->mRegex == '' ) {
271 $this->initRegex();
272 }
273 return $this->mRegex;
274 }
275
276 /**
277 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
278 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
279 * the complete expression
280 */
281 function getRegexCase() {
282 if ( $this->mRegex === '' )
283 $this->initRegex();
284
285 return $this->mCaseSensitive ? '' : 'iu';
286 }
287
288 /**
289 * Gets a regex matching the word, if it is at the string start
290 */
291 function getRegexStart() {
292 if ($this->mRegex == '' ) {
293 $this->initRegex();
294 }
295 return $this->mRegexStart;
296 }
297
298 /**
299 * regex without the slashes and what not
300 */
301 function getBaseRegex() {
302 if ($this->mRegex == '') {
303 $this->initRegex();
304 }
305 return $this->mBaseRegex;
306 }
307
308 /**
309 * Returns true if the text contains the word
310 * @return bool
311 */
312 function match( $text ) {
313 return preg_match( $this->getRegex(), $text );
314 }
315
316 /**
317 * Returns true if the text starts with the word
318 * @return bool
319 */
320 function matchStart( $text ) {
321 return preg_match( $this->getRegexStart(), $text );
322 }
323
324 /**
325 * Returns NULL if there's no match, the value of $1 otherwise
326 * The return code is the matched string, if there's no variable
327 * part in the regex and the matched variable part ($1) if there
328 * is one.
329 */
330 function matchVariableStartToEnd( $text ) {
331 $matches = array();
332 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
333 if ( $matchcount == 0 ) {
334 return NULL;
335 } else {
336 # multiple matched parts (variable match); some will be empty because of
337 # synonyms. The variable will be the second non-empty one so remove any
338 # blank elements and re-sort the indices.
339 # See also bug 6526
340
341 $matches = array_values(array_filter($matches));
342
343 if ( count($matches) == 1 ) { return $matches[0]; }
344 else { return $matches[1]; }
345 }
346 }
347
348
349 /**
350 * Returns true if the text matches the word, and alters the
351 * input string, removing all instances of the word
352 */
353 function matchAndRemove( &$text ) {
354 $this->mFound = false;
355 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
356 return $this->mFound;
357 }
358
359 function matchStartAndRemove( &$text ) {
360 $this->mFound = false;
361 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
362 return $this->mFound;
363 }
364
365 /**
366 * Used in matchAndRemove()
367 * @private
368 **/
369 function pregRemoveAndRecord( ) {
370 $this->mFound = true;
371 return '';
372 }
373
374 /**
375 * Replaces the word with something else
376 */
377 function replace( $replacement, $subject, $limit=-1 ) {
378 $res = preg_replace( $this->getRegex(), StringUtils::escapeRegexReplacement( $replacement ), $subject, $limit );
379 $this->mModified = !($res === $subject);
380 return $res;
381 }
382
383 /**
384 * Variable handling: {{SUBST:xxx}} style words
385 * Calls back a function to determine what to replace xxx with
386 * Input word must contain $1
387 */
388 function substituteCallback( $text, $callback ) {
389 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
390 $this->mModified = !($res === $text);
391 return $res;
392 }
393
394 /**
395 * Matches the word, where $1 is a wildcard
396 */
397 function getVariableRegex() {
398 if ( $this->mVariableRegex == '' ) {
399 $this->initRegex();
400 }
401 return $this->mVariableRegex;
402 }
403
404 /**
405 * Matches the entire string, where $1 is a wildcard
406 */
407 function getVariableStartToEndRegex() {
408 if ( $this->mVariableStartToEndRegex == '' ) {
409 $this->initRegex();
410 }
411 return $this->mVariableStartToEndRegex;
412 }
413
414 /**
415 * Accesses the synonym list directly
416 */
417 function getSynonym( $i ) {
418 return $this->mSynonyms[$i];
419 }
420
421 function getSynonyms() {
422 return $this->mSynonyms;
423 }
424
425 /**
426 * Returns true if the last call to replace() or substituteCallback()
427 * returned a modified text, otherwise false.
428 */
429 function getWasModified(){
430 return $this->mModified;
431 }
432
433 /**
434 * $magicarr is an associative array of (magic word ID => replacement)
435 * This method uses the php feature to do several replacements at the same time,
436 * thereby gaining some efficiency. The result is placed in the out variable
437 * $result. The return value is true if something was replaced.
438 * @static
439 **/
440 function replaceMultiple( $magicarr, $subject, &$result ){
441 $search = array();
442 $replace = array();
443 foreach( $magicarr as $id => $replacement ){
444 $mw = MagicWord::get( $id );
445 $search[] = $mw->getRegex();
446 $replace[] = $replacement;
447 }
448
449 $result = preg_replace( $search, $replace, $subject );
450 return !($result === $subject);
451 }
452
453 /**
454 * Adds all the synonyms of this MagicWord to an array, to allow quick
455 * lookup in a list of magic words
456 */
457 function addToArray( &$array, $value ) {
458 global $wgContLang;
459 foreach ( $this->mSynonyms as $syn ) {
460 $array[$wgContLang->lc($syn)] = $value;
461 }
462 }
463
464 function isCaseSensitive() {
465 return $this->mCaseSensitive;
466 }
467
468 function getId() {
469 return $this->mId;
470 }
471 }
472
473 /**
474 * Class for handling an array of magic words
475 * @ingroup Parser
476 */
477 class MagicWordArray {
478 var $names = array();
479 var $hash;
480 var $baseRegex, $regex;
481 var $matches;
482
483 function __construct( $names = array() ) {
484 $this->names = $names;
485 }
486
487 /**
488 * Add a magic word by name
489 */
490 public function add( $name ) {
491 global $wgContLang;
492 $this->names[] = $name;
493 $this->hash = $this->baseRegex = $this->regex = null;
494 }
495
496 /**
497 * Add a number of magic words by name
498 */
499 public function addArray( $names ) {
500 $this->names = array_merge( $this->names, array_values( $names ) );
501 $this->hash = $this->baseRegex = $this->regex = null;
502 }
503
504 /**
505 * Get a 2-d hashtable for this array
506 */
507 function getHash() {
508 if ( is_null( $this->hash ) ) {
509 global $wgContLang;
510 $this->hash = array( 0 => array(), 1 => array() );
511 foreach ( $this->names as $name ) {
512 $magic = MagicWord::get( $name );
513 $case = intval( $magic->isCaseSensitive() );
514 foreach ( $magic->getSynonyms() as $syn ) {
515 if ( !$case ) {
516 $syn = $wgContLang->lc( $syn );
517 }
518 $this->hash[$case][$syn] = $name;
519 }
520 }
521 }
522 return $this->hash;
523 }
524
525 /**
526 * Get the base regex
527 */
528 function getBaseRegex() {
529 if ( is_null( $this->baseRegex ) ) {
530 $this->baseRegex = array( 0 => '', 1 => '' );
531 foreach ( $this->names as $name ) {
532 $magic = MagicWord::get( $name );
533 $case = intval( $magic->isCaseSensitive() );
534 foreach ( $magic->getSynonyms() as $i => $syn ) {
535 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
536 if ( $this->baseRegex[$case] === '' ) {
537 $this->baseRegex[$case] = $group;
538 } else {
539 $this->baseRegex[$case] .= '|' . $group;
540 }
541 }
542 }
543 }
544 return $this->baseRegex;
545 }
546
547 /**
548 * Get an unanchored regex
549 */
550 function getRegex() {
551 if ( is_null( $this->regex ) ) {
552 $base = $this->getBaseRegex();
553 $this->regex = array( '', '' );
554 if ( $this->baseRegex[0] !== '' ) {
555 $this->regex[0] = "/{$base[0]}/iuS";
556 }
557 if ( $this->baseRegex[1] !== '' ) {
558 $this->regex[1] = "/{$base[1]}/S";
559 }
560 }
561 return $this->regex;
562 }
563
564 /**
565 * Get a regex for matching variables
566 */
567 function getVariableRegex() {
568 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
569 }
570
571 /**
572 * Get an anchored regex for matching variables
573 */
574 function getVariableStartToEndRegex() {
575 $base = $this->getBaseRegex();
576 $newRegex = array( '', '' );
577 if ( $base[0] !== '' ) {
578 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
579 }
580 if ( $base[1] !== '' ) {
581 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
582 }
583 return $newRegex;
584 }
585
586 /**
587 * Parse a match array from preg_match
588 * Returns array(magic word ID, parameter value)
589 * If there is no parameter value, that element will be false.
590 */
591 function parseMatch( $m ) {
592 reset( $m );
593 while ( list( $key, $value ) = each( $m ) ) {
594 if ( $key === 0 || $value === '' ) {
595 continue;
596 }
597 $parts = explode( '_', $key, 2 );
598 if ( count( $parts ) != 2 ) {
599 // This shouldn't happen
600 // continue;
601 throw new MWException( __METHOD__ . ': bad parameter name' );
602 }
603 list( /* $synIndex */, $magicName ) = $parts;
604 $paramValue = next( $m );
605 return array( $magicName, $paramValue );
606 }
607 // This shouldn't happen either
608 throw new MWException( __METHOD__.': parameter not found' );
609 return array( false, false );
610 }
611
612 /**
613 * Match some text, with parameter capture
614 * Returns an array with the magic word name in the first element and the
615 * parameter in the second element.
616 * Both elements are false if there was no match.
617 */
618 public function matchVariableStartToEnd( $text ) {
619 global $wgContLang;
620 $regexes = $this->getVariableStartToEndRegex();
621 foreach ( $regexes as $regex ) {
622 if ( $regex !== '' ) {
623 $m = false;
624 if ( preg_match( $regex, $text, $m ) ) {
625 return $this->parseMatch( $m );
626 }
627 }
628 }
629 return array( false, false );
630 }
631
632 /**
633 * Match some text, without parameter capture
634 * Returns the magic word name, or false if there was no capture
635 */
636 public function matchStartToEnd( $text ) {
637 $hash = $this->getHash();
638 if ( isset( $hash[1][$text] ) ) {
639 return $hash[1][$text];
640 }
641 global $wgContLang;
642 $lc = $wgContLang->lc( $text );
643 if ( isset( $hash[0][$lc] ) ) {
644 return $hash[0][$lc];
645 }
646 return false;
647 }
648
649 /**
650 * Returns an associative array, ID => param value, for all items that match
651 * Removes the matched items from the input string (passed by reference)
652 */
653 public function matchAndRemove( &$text ) {
654 $found = array();
655 $regexes = $this->getRegex();
656 foreach ( $regexes as $regex ) {
657 if ( $regex === '' ) {
658 continue;
659 }
660 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER );
661 foreach ( $matches as $m ) {
662 list( $name, $param ) = $this->parseMatch( $m );
663 $found[$name] = $param;
664 }
665 $text = preg_replace( $regex, '', $text );
666 }
667 return $found;
668 }
669 }