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