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