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