Fixed regex in doMagicLinks (broken since r15976)
[mediawiki.git] / includes / MagicWord.php
blob92bd4dc45ff04644a74361a9b6771398e91185f4
1 <?php
2 /**
3 * File for magic words
4 * @package MediaWiki
5 * @subpackage Parser
6 */
8 /**
9 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
10 * Usage:
11 * if (MagicWord::get( 'redirect' )->match( $text ) )
13 * Possible future improvements:
14 * * Simultaneous searching for a number of magic words
15 * * MagicWord::$mObjects in shared memory
17 * Please avoid reading the data out of one of these objects and then writing
18 * special case code. If possible, add another match()-like function here.
20 * To add magic words in an extension, use the LanguageGetMagic hook. For
21 * magic words which are also Parser variables, add a MagicWordwgVariableIDs
22 * hook. Use string keys.
24 * @package MediaWiki
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 'numberofarticles',
46 'numberoffiles',
47 'sitename',
48 'server',
49 'servername',
50 'scriptpath',
51 'pagename',
52 'pagenamee',
53 'fullpagename',
54 'fullpagenamee',
55 'namespace',
56 'namespacee',
57 'currentweek',
58 'currentdow',
59 'revisionid',
60 'subpagename',
61 'subpagenamee',
62 'displaytitle',
63 'talkspace',
64 'talkspacee',
65 'subjectspace',
66 'subjectspacee',
67 'talkpagename',
68 'talkpagenamee',
69 'subjectpagename',
70 'subjectpagenamee',
71 'numberofusers',
72 'rawsuffix',
73 'newsectionlink',
74 'numberofpages',
75 'currentversion',
76 'basepagename',
77 'basepagenamee',
78 'urlencode',
79 'currenttimestamp',
80 'directionmark',
81 'language',
82 'contentlanguage',
83 'pagesinnamespace',
84 'numberofadmins',
87 static public $mObjects = array();
89 /**#@-*/
91 function MagicWord($id = 0, $syn = '', $cs = false) {
92 $this->mId = $id;
93 $this->mSynonyms = (array)$syn;
94 $this->mCaseSensitive = $cs;
95 $this->mRegex = '';
96 $this->mRegexStart = '';
97 $this->mVariableRegex = '';
98 $this->mVariableStartToEndRegex = '';
99 $this->mModified = false;
103 * Factory: creates an object representing an ID
104 * @static
106 static function &get( $id ) {
107 if (!array_key_exists( $id, self::$mObjects ) ) {
108 $mw = new MagicWord();
109 $mw->load( $id );
110 self::$mObjects[$id] = $mw;
112 return self::$mObjects[$id];
116 * Get an array of parser variable IDs
118 static function getVariableIDs() {
119 if ( !self::$mVariableIDsInitialised ) {
120 # Deprecated constant definition hook, available for extensions that need it
121 $magicWords = array();
122 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
123 foreach ( $magicWords as $word ) {
124 define( $word, $word );
127 # Get variable IDs
128 wfRunHooks( 'MagicWordwgVariableIDs', array( &self::$mVariableIDs ) );
129 self::$mVariableIDsInitialised = true;
131 return self::$mVariableIDs;
134 # Initialises this object with an ID
135 function load( $id ) {
136 global $wgContLang;
137 $this->mId = $id;
138 $wgContLang->getMagic( $this );
142 * Preliminary initialisation
143 * @private
145 function initRegex() {
146 #$variableClass = Title::legalChars();
147 # This was used for matching "$1" variables, but different uses of the feature will have
148 # different restrictions, which should be checked *after* the MagicWord has been matched,
149 # not here. - IMSoP
151 $escSyn = array();
152 foreach ( $this->mSynonyms as $synonym )
153 // In case a magic word contains /, like that's going to happen;)
154 $escSyn[] = preg_quote( $synonym, '/' );
155 $this->mBaseRegex = implode( '|', $escSyn );
157 $case = $this->mCaseSensitive ? '' : 'i';
158 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
159 $this->mRegexStart = "/^(?:{$this->mBaseRegex})/{$case}";
160 $this->mVariableRegex = str_replace( "\\$1", "(.*?)", $this->mRegex );
161 $this->mVariableStartToEndRegex = str_replace( "\\$1", "(.*?)",
162 "/^(?:{$this->mBaseRegex})$/{$case}" );
166 * Gets a regex representing matching the word
168 function getRegex() {
169 if ($this->mRegex == '' ) {
170 $this->initRegex();
172 return $this->mRegex;
176 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
177 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
178 * the complete expression
180 function getRegexCase() {
181 if ( $this->mRegex === '' )
182 $this->initRegex();
184 return $this->mCaseSensitive ? '' : 'i';
188 * Gets a regex matching the word, if it is at the string start
190 function getRegexStart() {
191 if ($this->mRegex == '' ) {
192 $this->initRegex();
194 return $this->mRegexStart;
198 * regex without the slashes and what not
200 function getBaseRegex() {
201 if ($this->mRegex == '') {
202 $this->initRegex();
204 return $this->mBaseRegex;
208 * Returns true if the text contains the word
209 * @return bool
211 function match( $text ) {
212 return preg_match( $this->getRegex(), $text );
216 * Returns true if the text starts with the word
217 * @return bool
219 function matchStart( $text ) {
220 return preg_match( $this->getRegexStart(), $text );
224 * Returns NULL if there's no match, the value of $1 otherwise
225 * The return code is the matched string, if there's no variable
226 * part in the regex and the matched variable part ($1) if there
227 * is one.
229 function matchVariableStartToEnd( $text ) {
230 $matches = array();
231 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
232 if ( $matchcount == 0 ) {
233 return NULL;
234 } else {
235 # multiple matched parts (variable match); some will be empty because of
236 # synonyms. The variable will be the second non-empty one so remove any
237 # blank elements and re-sort the indices.
238 # See also bug 6526
240 $matches = array_values(array_filter($matches));
242 if ( count($matches) == 1 ) { return $matches[0]; }
243 else { return $matches[1]; }
249 * Returns true if the text matches the word, and alters the
250 * input string, removing all instances of the word
252 function matchAndRemove( &$text ) {
253 $this->mFound = false;
254 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
255 return $this->mFound;
258 function matchStartAndRemove( &$text ) {
259 $this->mFound = false;
260 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
261 return $this->mFound;
265 * Used in matchAndRemove()
266 * @private
268 function pregRemoveAndRecord( $match ) {
269 $this->mFound = true;
270 return '';
274 * Replaces the word with something else
276 function replace( $replacement, $subject, $limit=-1 ) {
277 $res = preg_replace( $this->getRegex(), wfRegexReplacement( $replacement ), $subject, $limit );
278 $this->mModified = !($res === $subject);
279 return $res;
283 * Variable handling: {{SUBST:xxx}} style words
284 * Calls back a function to determine what to replace xxx with
285 * Input word must contain $1
287 function substituteCallback( $text, $callback ) {
288 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
289 $this->mModified = !($res === $text);
290 return $res;
294 * Matches the word, where $1 is a wildcard
296 function getVariableRegex() {
297 if ( $this->mVariableRegex == '' ) {
298 $this->initRegex();
300 return $this->mVariableRegex;
304 * Matches the entire string, where $1 is a wildcard
306 function getVariableStartToEndRegex() {
307 if ( $this->mVariableStartToEndRegex == '' ) {
308 $this->initRegex();
310 return $this->mVariableStartToEndRegex;
314 * Accesses the synonym list directly
316 function getSynonym( $i ) {
317 return $this->mSynonyms[$i];
320 function getSynonyms() {
321 return $this->mSynonyms;
325 * Returns true if the last call to replace() or substituteCallback()
326 * returned a modified text, otherwise false.
328 function getWasModified(){
329 return $this->mModified;
333 * $magicarr is an associative array of (magic word ID => replacement)
334 * This method uses the php feature to do several replacements at the same time,
335 * thereby gaining some efficiency. The result is placed in the out variable
336 * $result. The return value is true if something was replaced.
337 * @static
339 function replaceMultiple( $magicarr, $subject, &$result ){
340 $search = array();
341 $replace = array();
342 foreach( $magicarr as $id => $replacement ){
343 $mw = MagicWord::get( $id );
344 $search[] = $mw->getRegex();
345 $replace[] = $replacement;
348 $result = preg_replace( $search, $replace, $subject );
349 return !($result === $subject);
353 * Adds all the synonyms of this MagicWord to an array, to allow quick
354 * lookup in a list of magic words
356 function addToArray( &$array, $value ) {
357 foreach ( $this->mSynonyms as $syn ) {
358 $array[$syn] = $value;
362 function isCaseSensitive() {
363 return $this->mCaseSensitive;