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