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