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