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