Actually, let's be a little pickier here.
[mediawiki.git] / includes / MagicWord.php
blob817683a57e0bc2325657d850831eff8c5f21c95c
1 <?php
2 /**
3 * File for magic words
4 * See docs/magicword.txt
6 * @addtogroup Parser
7 */
9 /**
10 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
11 * Usage:
12 * if (MagicWord::get( 'redirect' )->match( $text ) )
14 * Possible future improvements:
15 * * Simultaneous searching for a number of magic words
16 * * MagicWord::$mObjects in shared memory
18 * Please avoid reading the data out of one of these objects and then writing
19 * special case code. If possible, add another match()-like function here.
21 * To add magic words in an extension, use the LanguageGetMagic hook. For
22 * magic words which are also Parser variables, add a MagicWordwgVariableIDs
23 * hook. Use string keys.
26 class MagicWord {
27 /**#@+
28 * @private
30 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
31 var $mRegexStart, $mBaseRegex, $mVariableRegex;
32 var $mModified, $mFound;
34 static public $mVariableIDsInitialised = false;
35 static public $mVariableIDs = array(
36 'currentmonth',
37 'currentmonthname',
38 'currentmonthnamegen',
39 'currentmonthabbrev',
40 'currentday',
41 'currentday2',
42 'currentdayname',
43 'currentyear',
44 'currenttime',
45 'currenthour',
46 'localmonth',
47 'localmonthname',
48 'localmonthnamegen',
49 'localmonthabbrev',
50 'localday',
51 'localday2',
52 'localdayname',
53 'localyear',
54 'localtime',
55 'localhour',
56 'numberofarticles',
57 'numberoffiles',
58 'numberofedits',
59 'sitename',
60 'server',
61 'servername',
62 'scriptpath',
63 'pagename',
64 'pagenamee',
65 'fullpagename',
66 'fullpagenamee',
67 'namespace',
68 'namespacee',
69 'currentweek',
70 'currentdow',
71 'localweek',
72 'localdow',
73 'revisionid',
74 'revisionday',
75 'revisionday2',
76 'revisionmonth',
77 'revisionyear',
78 'revisiontimestamp',
79 'subpagename',
80 'subpagenamee',
81 'displaytitle',
82 'talkspace',
83 'talkspacee',
84 'subjectspace',
85 'subjectspacee',
86 'talkpagename',
87 'talkpagenamee',
88 'subjectpagename',
89 'subjectpagenamee',
90 'numberofusers',
91 'newsectionlink',
92 'numberofpages',
93 'currentversion',
94 'basepagename',
95 'basepagenamee',
96 'urlencode',
97 'currenttimestamp',
98 'localtimestamp',
99 'directionmark',
100 'language',
101 'contentlanguage',
102 'pagesinnamespace',
103 'numberofadmins',
104 'defaultsort',
107 /* Array of caching hints for ParserCache */
108 static public $mCacheTTLs = array (
109 'currentmonth' => 86400,
110 'currentmonthname' => 86400,
111 'currentmonthnamegen' => 86400,
112 'currentmonthabbrev' => 86400,
113 'currentday' => 3600,
114 'currentday2' => 3600,
115 'currentdayname' => 3600,
116 'currentyear' => 86400,
117 'currenttime' => 3600,
118 'currenthour' => 3600,
119 'localmonth' => 86400,
120 'localmonthname' => 86400,
121 'localmonthnamegen' => 86400,
122 'localmonthabbrev' => 86400,
123 'localday' => 3600,
124 'localday2' => 3600,
125 'localdayname' => 3600,
126 'localyear' => 86400,
127 'localtime' => 3600,
128 'localhour' => 3600,
129 'numberofarticles' => 3600,
130 'numberoffiles' => 3600,
131 'numberofedits' => 3600,
132 'currentweek' => 3600,
133 'currentdow' => 3600,
134 'localweek' => 3600,
135 'localdow' => 3600,
136 'numberofusers' => 3600,
137 'numberofpages' => 3600,
138 'currentversion' => 86400,
139 'currenttimestamp' => 3600,
140 'localtimestamp' => 3600,
141 'pagesinnamespace' => 3600,
142 'numberofadmins' => 3600,
145 static public $mDoubleUnderscoreIDs = array(
146 'notoc',
147 'nogallery',
148 'forcetoc',
149 'toc',
150 'noeditsection',
151 'newsectionlink',
152 'hiddencat',
156 static public $mObjects = array();
157 static public $mDoubleUnderscoreArray = null;
159 /**#@-*/
161 function __construct($id = 0, $syn = '', $cs = false) {
162 $this->mId = $id;
163 $this->mSynonyms = (array)$syn;
164 $this->mCaseSensitive = $cs;
165 $this->mRegex = '';
166 $this->mRegexStart = '';
167 $this->mVariableRegex = '';
168 $this->mVariableStartToEndRegex = '';
169 $this->mModified = false;
173 * Factory: creates an object representing an ID
174 * @static
176 static function &get( $id ) {
177 wfProfileIn( __METHOD__ );
178 if (!array_key_exists( $id, self::$mObjects ) ) {
179 $mw = new MagicWord();
180 $mw->load( $id );
181 self::$mObjects[$id] = $mw;
183 wfProfileOut( __METHOD__ );
184 return self::$mObjects[$id];
188 * Get an array of parser variable IDs
190 static function getVariableIDs() {
191 if ( !self::$mVariableIDsInitialised ) {
192 # Deprecated constant definition hook, available for extensions that need it
193 $magicWords = array();
194 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
195 foreach ( $magicWords as $word ) {
196 define( $word, $word );
199 # Get variable IDs
200 wfRunHooks( 'MagicWordwgVariableIDs', array( &self::$mVariableIDs ) );
201 self::$mVariableIDsInitialised = true;
203 return self::$mVariableIDs;
206 /* Allow external reads of TTL array */
207 static function getCacheTTL($id) {
208 if (array_key_exists($id,self::$mCacheTTLs)) {
209 return self::$mCacheTTLs[$id];
210 } else {
211 return -1;
215 /** Get a MagicWordArray of double-underscore entities */
216 static function getDoubleUnderscoreArray() {
217 if ( is_null( self::$mDoubleUnderscoreArray ) ) {
218 self::$mDoubleUnderscoreArray = new MagicWordArray( self::$mDoubleUnderscoreIDs );
220 return self::$mDoubleUnderscoreArray;
223 # Initialises this object with an ID
224 function load( $id ) {
225 global $wgContLang;
226 $this->mId = $id;
227 $wgContLang->getMagic( $this );
228 if ( !$this->mSynonyms ) {
229 $this->mSynonyms = array( 'dkjsagfjsgashfajsh' );
230 #throw new MWException( "Error: invalid magic word '$id'" );
231 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
236 * Preliminary initialisation
237 * @private
239 function initRegex() {
240 #$variableClass = Title::legalChars();
241 # This was used for matching "$1" variables, but different uses of the feature will have
242 # different restrictions, which should be checked *after* the MagicWord has been matched,
243 # not here. - IMSoP
245 $escSyn = array();
246 foreach ( $this->mSynonyms as $synonym )
247 // In case a magic word contains /, like that's going to happen;)
248 $escSyn[] = preg_quote( $synonym, '/' );
249 $this->mBaseRegex = implode( '|', $escSyn );
251 $case = $this->mCaseSensitive ? '' : 'iu';
252 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
253 $this->mRegexStart = "/^(?:{$this->mBaseRegex})/{$case}";
254 $this->mVariableRegex = str_replace( "\\$1", "(.*?)", $this->mRegex );
255 $this->mVariableStartToEndRegex = str_replace( "\\$1", "(.*?)",
256 "/^(?:{$this->mBaseRegex})$/{$case}" );
260 * Gets a regex representing matching the word
262 function getRegex() {
263 if ($this->mRegex == '' ) {
264 $this->initRegex();
266 return $this->mRegex;
270 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
271 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
272 * the complete expression
274 function getRegexCase() {
275 if ( $this->mRegex === '' )
276 $this->initRegex();
278 return $this->mCaseSensitive ? '' : 'iu';
282 * Gets a regex matching the word, if it is at the string start
284 function getRegexStart() {
285 if ($this->mRegex == '' ) {
286 $this->initRegex();
288 return $this->mRegexStart;
292 * regex without the slashes and what not
294 function getBaseRegex() {
295 if ($this->mRegex == '') {
296 $this->initRegex();
298 return $this->mBaseRegex;
302 * Returns true if the text contains the word
303 * @return bool
305 function match( $text ) {
306 return preg_match( $this->getRegex(), $text );
310 * Returns true if the text starts with the word
311 * @return bool
313 function matchStart( $text ) {
314 return preg_match( $this->getRegexStart(), $text );
318 * Returns NULL if there's no match, the value of $1 otherwise
319 * The return code is the matched string, if there's no variable
320 * part in the regex and the matched variable part ($1) if there
321 * is one.
323 function matchVariableStartToEnd( $text ) {
324 $matches = array();
325 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
326 if ( $matchcount == 0 ) {
327 return NULL;
328 } else {
329 # multiple matched parts (variable match); some will be empty because of
330 # synonyms. The variable will be the second non-empty one so remove any
331 # blank elements and re-sort the indices.
332 # See also bug 6526
334 $matches = array_values(array_filter($matches));
336 if ( count($matches) == 1 ) { return $matches[0]; }
337 else { return $matches[1]; }
343 * Returns true if the text matches the word, and alters the
344 * input string, removing all instances of the word
346 function matchAndRemove( &$text ) {
347 $this->mFound = false;
348 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
349 return $this->mFound;
352 function matchStartAndRemove( &$text ) {
353 $this->mFound = false;
354 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
355 return $this->mFound;
359 * Used in matchAndRemove()
360 * @private
362 function pregRemoveAndRecord( ) {
363 $this->mFound = true;
364 return '';
368 * Replaces the word with something else
370 function replace( $replacement, $subject, $limit=-1 ) {
371 $res = preg_replace( $this->getRegex(), StringUtils::escapeRegexReplacement( $replacement ), $subject, $limit );
372 $this->mModified = !($res === $subject);
373 return $res;
377 * Variable handling: {{SUBST:xxx}} style words
378 * Calls back a function to determine what to replace xxx with
379 * Input word must contain $1
381 function substituteCallback( $text, $callback ) {
382 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
383 $this->mModified = !($res === $text);
384 return $res;
388 * Matches the word, where $1 is a wildcard
390 function getVariableRegex() {
391 if ( $this->mVariableRegex == '' ) {
392 $this->initRegex();
394 return $this->mVariableRegex;
398 * Matches the entire string, where $1 is a wildcard
400 function getVariableStartToEndRegex() {
401 if ( $this->mVariableStartToEndRegex == '' ) {
402 $this->initRegex();
404 return $this->mVariableStartToEndRegex;
408 * Accesses the synonym list directly
410 function getSynonym( $i ) {
411 return $this->mSynonyms[$i];
414 function getSynonyms() {
415 return $this->mSynonyms;
419 * Returns true if the last call to replace() or substituteCallback()
420 * returned a modified text, otherwise false.
422 function getWasModified(){
423 return $this->mModified;
427 * $magicarr is an associative array of (magic word ID => replacement)
428 * This method uses the php feature to do several replacements at the same time,
429 * thereby gaining some efficiency. The result is placed in the out variable
430 * $result. The return value is true if something was replaced.
431 * @static
433 function replaceMultiple( $magicarr, $subject, &$result ){
434 $search = array();
435 $replace = array();
436 foreach( $magicarr as $id => $replacement ){
437 $mw = MagicWord::get( $id );
438 $search[] = $mw->getRegex();
439 $replace[] = $replacement;
442 $result = preg_replace( $search, $replace, $subject );
443 return !($result === $subject);
447 * Adds all the synonyms of this MagicWord to an array, to allow quick
448 * lookup in a list of magic words
450 function addToArray( &$array, $value ) {
451 global $wgContLang;
452 foreach ( $this->mSynonyms as $syn ) {
453 $array[$wgContLang->lc($syn)] = $value;
457 function isCaseSensitive() {
458 return $this->mCaseSensitive;
461 function getId() {
462 return $this->mId;
467 * Class for handling an array of magic words
469 class MagicWordArray {
470 var $names = array();
471 var $hash;
472 var $baseRegex, $regex;
473 var $matches;
475 function __construct( $names = array() ) {
476 $this->names = $names;
480 * Add a magic word by name
482 public function add( $name ) {
483 global $wgContLang;
484 $this->names[] = $name;
485 $this->hash = $this->baseRegex = $this->regex = null;
489 * Add a number of magic words by name
491 public function addArray( $names ) {
492 $this->names = array_merge( $this->names, array_values( $names ) );
493 $this->hash = $this->baseRegex = $this->regex = null;
497 * Get a 2-d hashtable for this array
499 function getHash() {
500 if ( is_null( $this->hash ) ) {
501 global $wgContLang;
502 $this->hash = array( 0 => array(), 1 => array() );
503 foreach ( $this->names as $name ) {
504 $magic = MagicWord::get( $name );
505 $case = intval( $magic->isCaseSensitive() );
506 foreach ( $magic->getSynonyms() as $syn ) {
507 if ( !$case ) {
508 $syn = $wgContLang->lc( $syn );
510 $this->hash[$case][$syn] = $name;
514 return $this->hash;
518 * Get the base regex
520 function getBaseRegex() {
521 if ( is_null( $this->baseRegex ) ) {
522 $this->baseRegex = array( 0 => '', 1 => '' );
523 foreach ( $this->names as $name ) {
524 $magic = MagicWord::get( $name );
525 $case = intval( $magic->isCaseSensitive() );
526 foreach ( $magic->getSynonyms() as $i => $syn ) {
527 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
528 if ( $this->baseRegex[$case] === '' ) {
529 $this->baseRegex[$case] = $group;
530 } else {
531 $this->baseRegex[$case] .= '|' . $group;
536 return $this->baseRegex;
540 * Get an unanchored regex
542 function getRegex() {
543 if ( is_null( $this->regex ) ) {
544 $base = $this->getBaseRegex();
545 $this->regex = array( '', '' );
546 if ( $this->baseRegex[0] !== '' ) {
547 $this->regex[0] = "/{$base[0]}/iuS";
549 if ( $this->baseRegex[1] !== '' ) {
550 $this->regex[1] = "/{$base[1]}/S";
553 return $this->regex;
557 * Get a regex for matching variables
559 function getVariableRegex() {
560 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
564 * Get an anchored regex for matching variables
566 function getVariableStartToEndRegex() {
567 $base = $this->getBaseRegex();
568 $newRegex = array( '', '' );
569 if ( $base[0] !== '' ) {
570 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
572 if ( $base[1] !== '' ) {
573 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
575 return $newRegex;
579 * Parse a match array from preg_match
580 * Returns array(magic word ID, parameter value)
581 * If there is no parameter value, that element will be false.
583 function parseMatch( $m ) {
584 reset( $m );
585 while ( list( $key, $value ) = each( $m ) ) {
586 if ( $key === 0 || $value === '' ) {
587 continue;
589 $parts = explode( '_', $key, 2 );
590 if ( count( $parts ) != 2 ) {
591 // This shouldn't happen
592 // continue;
593 throw new MWException( __METHOD__ . ': bad parameter name' );
595 list( /* $synIndex */, $magicName ) = $parts;
596 $paramValue = next( $m );
597 return array( $magicName, $paramValue );
599 // This shouldn't happen either
600 throw new MWException( __METHOD__.': parameter not found' );
601 return array( false, false );
605 * Match some text, with parameter capture
606 * Returns an array with the magic word name in the first element and the
607 * parameter in the second element.
608 * Both elements are false if there was no match.
610 public function matchVariableStartToEnd( $text ) {
611 global $wgContLang;
612 $regexes = $this->getVariableStartToEndRegex();
613 foreach ( $regexes as $regex ) {
614 if ( $regex !== '' ) {
615 $m = false;
616 if ( preg_match( $regex, $text, $m ) ) {
617 return $this->parseMatch( $m );
621 return array( false, false );
625 * Match some text, without parameter capture
626 * Returns the magic word name, or false if there was no capture
628 public function matchStartToEnd( $text ) {
629 $hash = $this->getHash();
630 if ( isset( $hash[1][$text] ) ) {
631 return $hash[1][$text];
633 global $wgContLang;
634 $lc = $wgContLang->lc( $text );
635 if ( isset( $hash[0][$lc] ) ) {
636 return $hash[0][$lc];
638 return false;
642 * Returns an associative array, ID => param value, for all items that match
643 * Removes the matched items from the input string (passed by reference)
645 public function matchAndRemove( &$text ) {
646 $found = array();
647 $regexes = $this->getRegex();
648 foreach ( $regexes as $regex ) {
649 if ( $regex === '' ) {
650 continue;
652 preg_match_all( $regex, $text, $matches, PREG_SET_ORDER );
653 foreach ( $matches as $m ) {
654 list( $name, $param ) = $this->parseMatch( $m );
655 $found[$name] = $param;
657 $text = preg_replace( $regex, '', $text );
659 return $found;