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