(bug 15869) Nostalgia skin does not show page title in printable mode
[mediawiki.git] / includes / MagicWord.php
blob3f0888d4d31f3239881c780f54e5baf2db918fa8
1 <?php
2 /**
3 * File for magic words
4 * See docs/magicword.txt
6 * @file
7 * @ingroup Parser
8 */
10 /**
11 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
12 * Usage:
13 * if (MagicWord::get( 'redirect' )->match( $text ) )
15 * Possible future improvements:
16 * * Simultaneous searching for a number of magic words
17 * * MagicWord::$mObjects in shared memory
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.
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.
26 * @ingroup Parser
28 class MagicWord {
29 /**#@+
30 * @private
32 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
33 var $mRegexStart, $mBaseRegex, $mVariableRegex;
34 var $mModified, $mFound;
36 static public $mVariableIDsInitialised = false;
37 static public $mVariableIDs = array(
38 'currentmonth',
39 'currentmonthname',
40 'currentmonthnamegen',
41 'currentmonthabbrev',
42 'currentday',
43 'currentday2',
44 'currentdayname',
45 'currentyear',
46 'currenttime',
47 'currenthour',
48 'localmonth',
49 'localmonthname',
50 'localmonthnamegen',
51 'localmonthabbrev',
52 'localday',
53 'localday2',
54 'localdayname',
55 'localyear',
56 'localtime',
57 'localhour',
58 'numberofarticles',
59 'numberoffiles',
60 'numberofedits',
61 'sitename',
62 'server',
63 'servername',
64 'scriptpath',
65 'pagename',
66 'pagenamee',
67 'fullpagename',
68 'fullpagenamee',
69 'namespace',
70 'namespacee',
71 'currentweek',
72 'currentdow',
73 'localweek',
74 'localdow',
75 'revisionid',
76 'revisionday',
77 'revisionday2',
78 'revisionmonth',
79 'revisionyear',
80 'revisiontimestamp',
81 'subpagename',
82 'subpagenamee',
83 'displaytitle',
84 'talkspace',
85 'talkspacee',
86 'subjectspace',
87 'subjectspacee',
88 'talkpagename',
89 'talkpagenamee',
90 'subjectpagename',
91 'subjectpagenamee',
92 'numberofusers',
93 'newsectionlink',
94 'numberofpages',
95 'currentversion',
96 'basepagename',
97 'basepagenamee',
98 'urlencode',
99 'currenttimestamp',
100 'localtimestamp',
101 'directionmark',
102 'language',
103 'contentlanguage',
104 'pagesinnamespace',
105 'numberofadmins',
106 'defaultsort',
107 'pagesincategory',
108 'index',
109 'noindex',
110 'numberingroup',
113 /* Array of caching hints for ParserCache */
114 static public $mCacheTTLs = array (
115 'currentmonth' => 86400,
116 'currentmonthname' => 86400,
117 'currentmonthnamegen' => 86400,
118 'currentmonthabbrev' => 86400,
119 'currentday' => 3600,
120 'currentday2' => 3600,
121 'currentdayname' => 3600,
122 'currentyear' => 86400,
123 'currenttime' => 3600,
124 'currenthour' => 3600,
125 'localmonth' => 86400,
126 'localmonthname' => 86400,
127 'localmonthnamegen' => 86400,
128 'localmonthabbrev' => 86400,
129 'localday' => 3600,
130 'localday2' => 3600,
131 'localdayname' => 3600,
132 'localyear' => 86400,
133 'localtime' => 3600,
134 'localhour' => 3600,
135 'numberofarticles' => 3600,
136 'numberoffiles' => 3600,
137 'numberofedits' => 3600,
138 'currentweek' => 3600,
139 'currentdow' => 3600,
140 'localweek' => 3600,
141 'localdow' => 3600,
142 'numberofusers' => 3600,
143 'numberofpages' => 3600,
144 'currentversion' => 86400,
145 'currenttimestamp' => 3600,
146 'localtimestamp' => 3600,
147 'pagesinnamespace' => 3600,
148 'numberofadmins' => 3600,
149 'numberingroup' => 3600,
152 static public $mDoubleUnderscoreIDs = array(
153 'notoc',
154 'nogallery',
155 'forcetoc',
156 'toc',
157 'noeditsection',
158 'newsectionlink',
159 'hiddencat',
160 'index',
161 'noindex',
162 'staticredirect',
163 'noheader',
167 static public $mObjects = array();
168 static public $mDoubleUnderscoreArray = null;
170 /**#@-*/
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;
184 * Factory: creates an object representing an ID
185 * @static
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;
194 wfProfileOut( __METHOD__ );
195 return self::$mObjects[$id];
199 * Get an array of parser variable IDs
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 );
210 # Get variable IDs
211 wfRunHooks( 'MagicWordwgVariableIDs', array( &self::$mVariableIDs ) );
212 self::$mVariableIDsInitialised = true;
214 return self::$mVariableIDs;
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;
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 );
231 return self::$mDoubleUnderscoreArray;
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" );
247 * Preliminary initialisation
248 * @private
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
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 );
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}" );
271 * Gets a regex representing matching the word
273 function getRegex() {
274 if ($this->mRegex == '' ) {
275 $this->initRegex();
277 return $this->mRegex;
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
285 function getRegexCase() {
286 if ( $this->mRegex === '' )
287 $this->initRegex();
289 return $this->mCaseSensitive ? '' : 'iu';
293 * Gets a regex matching the word, if it is at the string start
295 function getRegexStart() {
296 if ($this->mRegex == '' ) {
297 $this->initRegex();
299 return $this->mRegexStart;
303 * regex without the slashes and what not
305 function getBaseRegex() {
306 if ($this->mRegex == '') {
307 $this->initRegex();
309 return $this->mBaseRegex;
313 * Returns true if the text contains the word
314 * @return bool
316 function match( $text ) {
317 return preg_match( $this->getRegex(), $text );
321 * Returns true if the text starts with the word
322 * @return bool
324 function matchStart( $text ) {
325 return preg_match( $this->getRegexStart(), $text );
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.
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
345 $matches = array_values(array_filter($matches));
347 if ( count($matches) == 1 ) { return $matches[0]; }
348 else { return $matches[1]; }
354 * Returns true if the text matches the word, and alters the
355 * input string, removing all instances of the word
357 function matchAndRemove( &$text ) {
358 $this->mFound = false;
359 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
360 return $this->mFound;
363 function matchStartAndRemove( &$text ) {
364 $this->mFound = false;
365 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
366 return $this->mFound;
370 * Used in matchAndRemove()
371 * @private
373 function pregRemoveAndRecord( ) {
374 $this->mFound = true;
375 return '';
379 * Replaces the word with something else
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;
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
392 function substituteCallback( $text, $callback ) {
393 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
394 $this->mModified = !($res === $text);
395 return $res;
399 * Matches the word, where $1 is a wildcard
401 function getVariableRegex() {
402 if ( $this->mVariableRegex == '' ) {
403 $this->initRegex();
405 return $this->mVariableRegex;
409 * Matches the entire string, where $1 is a wildcard
411 function getVariableStartToEndRegex() {
412 if ( $this->mVariableStartToEndRegex == '' ) {
413 $this->initRegex();
415 return $this->mVariableStartToEndRegex;
419 * Accesses the synonym list directly
421 function getSynonym( $i ) {
422 return $this->mSynonyms[$i];
425 function getSynonyms() {
426 return $this->mSynonyms;
430 * Returns true if the last call to replace() or substituteCallback()
431 * returned a modified text, otherwise false.
433 function getWasModified(){
434 return $this->mModified;
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
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;
453 $result = preg_replace( $search, $replace, $subject );
454 return !($result === $subject);
458 * Adds all the synonyms of this MagicWord to an array, to allow quick
459 * lookup in a list of magic words
461 function addToArray( &$array, $value ) {
462 global $wgContLang;
463 foreach ( $this->mSynonyms as $syn ) {
464 $array[$wgContLang->lc($syn)] = $value;
468 function isCaseSensitive() {
469 return $this->mCaseSensitive;
472 function getId() {
473 return $this->mId;
478 * Class for handling an array of magic words
479 * @ingroup Parser
481 class MagicWordArray {
482 var $names = array();
483 var $hash;
484 var $baseRegex, $regex;
485 var $matches;
487 function __construct( $names = array() ) {
488 $this->names = $names;
492 * Add a magic word by name
494 public function add( $name ) {
495 global $wgContLang;
496 $this->names[] = $name;
497 $this->hash = $this->baseRegex = $this->regex = null;
501 * Add a number of magic words by name
503 public function addArray( $names ) {
504 $this->names = array_merge( $this->names, array_values( $names ) );
505 $this->hash = $this->baseRegex = $this->regex = null;
509 * Get a 2-d hashtable for this array
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 );
522 $this->hash[$case][$syn] = $name;
526 return $this->hash;
530 * Get the base regex
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;
548 return $this->baseRegex;
552 * Get an unanchored regex
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";
561 if ( $this->baseRegex[1] !== '' ) {
562 $this->regex[1] = "/{$base[1]}/S";
565 return $this->regex;
569 * Get a regex for matching variables
571 function getVariableRegex() {
572 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
576 * Get an anchored regex for matching variables
578 function getVariableStartToEndRegex() {
579 $base = $this->getBaseRegex();
580 $newRegex = array( '', '' );
581 if ( $base[0] !== '' ) {
582 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
584 if ( $base[1] !== '' ) {
585 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
587 return $newRegex;
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.
595 function parseMatch( $m ) {
596 reset( $m );
597 while ( list( $key, $value ) = each( $m ) ) {
598 if ( $key === 0 || $value === '' ) {
599 continue;
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' );
607 list( /* $synIndex */, $magicName ) = $parts;
608 $paramValue = next( $m );
609 return array( $magicName, $paramValue );
611 // This shouldn't happen either
612 throw new MWException( __METHOD__.': parameter not found' );
613 return array( false, false );
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.
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 );
633 return array( false, false );
637 * Match some text, without parameter capture
638 * Returns the magic word name, or false if there was no capture
640 public function matchStartToEnd( $text ) {
641 $hash = $this->getHash();
642 if ( isset( $hash[1][$text] ) ) {
643 return $hash[1][$text];
645 global $wgContLang;
646 $lc = $wgContLang->lc( $text );
647 if ( isset( $hash[0][$lc] ) ) {
648 return $hash[0][$lc];
650 return false;
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)
657 public function matchAndRemove( &$text ) {
658 $found = array();
659 $regexes = $this->getRegex();
660 foreach ( $regexes as $regex ) {
661 if ( $regex === '' ) {
662 continue;
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;
669 $text = preg_replace( $regex, '', $text );
671 return $found;