* (bug 7459) Magic word variables are always case sensitive
[lhc/web/wiklou.git] / includes / MagicWord.php
1 <?php
2 /**
3 * File for magic words
4 * @package MediaWiki
5 * @subpackage Parser
6 */
7
8 /**
9 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
10 * Usage:
11 * if (MagicWord::get( 'redirect' )->match( $text ) )
12 *
13 * Possible future improvements:
14 * * Simultaneous searching for a number of magic words
15 * * MagicWord::$mObjects in shared memory
16 *
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.
19 *
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.
23 *
24 * @package MediaWiki
25 */
26 class MagicWord {
27 /**#@+
28 * @private
29 */
30 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
31 var $mRegexStart, $mBaseRegex, $mVariableRegex;
32 var $mModified, $mFound;
33
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 'sitename',
59 'server',
60 'servername',
61 'scriptpath',
62 'pagename',
63 'pagenamee',
64 'fullpagename',
65 'fullpagenamee',
66 'namespace',
67 'namespacee',
68 'currentweek',
69 'currentdow',
70 'localweek',
71 'localdow',
72 'revisionid',
73 'revisionday',
74 'revisionday2',
75 'revisionmonth',
76 'revisionyear',
77 'revisiontimestamp',
78 'subpagename',
79 'subpagenamee',
80 'displaytitle',
81 'talkspace',
82 'talkspacee',
83 'subjectspace',
84 'subjectspacee',
85 'talkpagename',
86 'talkpagenamee',
87 'subjectpagename',
88 'subjectpagenamee',
89 'numberofusers',
90 'rawsuffix',
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 );
105
106 static public $mObjects = array();
107
108 /**#@-*/
109
110 function MagicWord($id = 0, $syn = '', $cs = false) {
111 $this->mId = $id;
112 $this->mSynonyms = (array)$syn;
113 $this->mCaseSensitive = $cs;
114 $this->mRegex = '';
115 $this->mRegexStart = '';
116 $this->mVariableRegex = '';
117 $this->mVariableStartToEndRegex = '';
118 $this->mModified = false;
119 }
120
121 /**
122 * Factory: creates an object representing an ID
123 * @static
124 */
125 static function &get( $id ) {
126 if (!array_key_exists( $id, self::$mObjects ) ) {
127 $mw = new MagicWord();
128 $mw->load( $id );
129 self::$mObjects[$id] = $mw;
130 }
131 return self::$mObjects[$id];
132 }
133
134 /**
135 * Get an array of parser variable IDs
136 */
137 static function getVariableIDs() {
138 if ( !self::$mVariableIDsInitialised ) {
139 # Deprecated constant definition hook, available for extensions that need it
140 $magicWords = array();
141 wfRunHooks( 'MagicWordMagicWords', array( &$magicWords ) );
142 foreach ( $magicWords as $word ) {
143 define( $word, $word );
144 }
145
146 # Get variable IDs
147 wfRunHooks( 'MagicWordwgVariableIDs', array( &self::$mVariableIDs ) );
148 self::$mVariableIDsInitialised = true;
149 }
150 return self::$mVariableIDs;
151 }
152
153 # Initialises this object with an ID
154 function load( $id ) {
155 global $wgContLang;
156 $this->mId = $id;
157 $wgContLang->getMagic( $this );
158 if ( !$this->mSynonyms ) {
159 $this->mSynonyms = array( 'dkjsagfjsgashfajsh' );
160 #throw new MWException( "Error: invalid magic word '$id'" );
161 wfDebugLog( 'exception', "Error: invalid magic word '$id'\n" );
162 }
163 }
164
165 /**
166 * Preliminary initialisation
167 * @private
168 */
169 function initRegex() {
170 #$variableClass = Title::legalChars();
171 # This was used for matching "$1" variables, but different uses of the feature will have
172 # different restrictions, which should be checked *after* the MagicWord has been matched,
173 # not here. - IMSoP
174
175 $escSyn = array();
176 foreach ( $this->mSynonyms as $synonym )
177 // In case a magic word contains /, like that's going to happen;)
178 $escSyn[] = preg_quote( $synonym, '/' );
179 $this->mBaseRegex = implode( '|', $escSyn );
180
181 $case = $this->mCaseSensitive ? '' : 'iu';
182 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
183 $this->mRegexStart = "/^(?:{$this->mBaseRegex})/{$case}";
184 $this->mVariableRegex = str_replace( "\\$1", "(.*?)", $this->mRegex );
185 $this->mVariableStartToEndRegex = str_replace( "\\$1", "(.*?)",
186 "/^(?:{$this->mBaseRegex})$/{$case}" );
187 }
188
189 /**
190 * Gets a regex representing matching the word
191 */
192 function getRegex() {
193 if ($this->mRegex == '' ) {
194 $this->initRegex();
195 }
196 return $this->mRegex;
197 }
198
199 /**
200 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
201 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
202 * the complete expression
203 */
204 function getRegexCase() {
205 if ( $this->mRegex === '' )
206 $this->initRegex();
207
208 return $this->mCaseSensitive ? '' : 'iu';
209 }
210
211 /**
212 * Gets a regex matching the word, if it is at the string start
213 */
214 function getRegexStart() {
215 if ($this->mRegex == '' ) {
216 $this->initRegex();
217 }
218 return $this->mRegexStart;
219 }
220
221 /**
222 * regex without the slashes and what not
223 */
224 function getBaseRegex() {
225 if ($this->mRegex == '') {
226 $this->initRegex();
227 }
228 return $this->mBaseRegex;
229 }
230
231 /**
232 * Returns true if the text contains the word
233 * @return bool
234 */
235 function match( $text ) {
236 return preg_match( $this->getRegex(), $text );
237 }
238
239 /**
240 * Returns true if the text starts with the word
241 * @return bool
242 */
243 function matchStart( $text ) {
244 return preg_match( $this->getRegexStart(), $text );
245 }
246
247 /**
248 * Returns NULL if there's no match, the value of $1 otherwise
249 * The return code is the matched string, if there's no variable
250 * part in the regex and the matched variable part ($1) if there
251 * is one.
252 */
253 function matchVariableStartToEnd( $text ) {
254 $matches = array();
255 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
256 if ( $matchcount == 0 ) {
257 return NULL;
258 } else {
259 # multiple matched parts (variable match); some will be empty because of
260 # synonyms. The variable will be the second non-empty one so remove any
261 # blank elements and re-sort the indices.
262 # See also bug 6526
263
264 $matches = array_values(array_filter($matches));
265
266 if ( count($matches) == 1 ) { return $matches[0]; }
267 else { return $matches[1]; }
268 }
269 }
270
271
272 /**
273 * Returns true if the text matches the word, and alters the
274 * input string, removing all instances of the word
275 */
276 function matchAndRemove( &$text ) {
277 $this->mFound = false;
278 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
279 return $this->mFound;
280 }
281
282 function matchStartAndRemove( &$text ) {
283 $this->mFound = false;
284 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
285 return $this->mFound;
286 }
287
288 /**
289 * Used in matchAndRemove()
290 * @private
291 **/
292 function pregRemoveAndRecord( $match ) {
293 $this->mFound = true;
294 return '';
295 }
296
297 /**
298 * Replaces the word with something else
299 */
300 function replace( $replacement, $subject, $limit=-1 ) {
301 $res = preg_replace( $this->getRegex(), wfRegexReplacement( $replacement ), $subject, $limit );
302 $this->mModified = !($res === $subject);
303 return $res;
304 }
305
306 /**
307 * Variable handling: {{SUBST:xxx}} style words
308 * Calls back a function to determine what to replace xxx with
309 * Input word must contain $1
310 */
311 function substituteCallback( $text, $callback ) {
312 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
313 $this->mModified = !($res === $text);
314 return $res;
315 }
316
317 /**
318 * Matches the word, where $1 is a wildcard
319 */
320 function getVariableRegex() {
321 if ( $this->mVariableRegex == '' ) {
322 $this->initRegex();
323 }
324 return $this->mVariableRegex;
325 }
326
327 /**
328 * Matches the entire string, where $1 is a wildcard
329 */
330 function getVariableStartToEndRegex() {
331 if ( $this->mVariableStartToEndRegex == '' ) {
332 $this->initRegex();
333 }
334 return $this->mVariableStartToEndRegex;
335 }
336
337 /**
338 * Accesses the synonym list directly
339 */
340 function getSynonym( $i ) {
341 return $this->mSynonyms[$i];
342 }
343
344 function getSynonyms() {
345 return $this->mSynonyms;
346 }
347
348 /**
349 * Returns true if the last call to replace() or substituteCallback()
350 * returned a modified text, otherwise false.
351 */
352 function getWasModified(){
353 return $this->mModified;
354 }
355
356 /**
357 * $magicarr is an associative array of (magic word ID => replacement)
358 * This method uses the php feature to do several replacements at the same time,
359 * thereby gaining some efficiency. The result is placed in the out variable
360 * $result. The return value is true if something was replaced.
361 * @static
362 **/
363 function replaceMultiple( $magicarr, $subject, &$result ){
364 $search = array();
365 $replace = array();
366 foreach( $magicarr as $id => $replacement ){
367 $mw = MagicWord::get( $id );
368 $search[] = $mw->getRegex();
369 $replace[] = $replacement;
370 }
371
372 $result = preg_replace( $search, $replace, $subject );
373 return !($result === $subject);
374 }
375
376 /**
377 * Adds all the synonyms of this MagicWord to an array, to allow quick
378 * lookup in a list of magic words
379 */
380 function addToArray( &$array, $value ) {
381 global $wgContLang;
382 foreach ( $this->mSynonyms as $syn ) {
383 $array[$wgContLang->lc($syn)] = $value;
384 }
385 }
386
387 function isCaseSensitive() {
388 return $this->mCaseSensitive;
389 }
390 }
391
392 ?>