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