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