826a7e9d0419643e355c3753b78025475781bc63
[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 }
159
160 /**
161 * Preliminary initialisation
162 * @private
163 */
164 function initRegex() {
165 #$variableClass = Title::legalChars();
166 # This was used for matching "$1" variables, but different uses of the feature will have
167 # different restrictions, which should be checked *after* the MagicWord has been matched,
168 # not here. - IMSoP
169
170 $escSyn = array();
171 foreach ( $this->mSynonyms as $synonym )
172 // In case a magic word contains /, like that's going to happen;)
173 $escSyn[] = preg_quote( $synonym, '/' );
174 $this->mBaseRegex = implode( '|', $escSyn );
175
176 $case = $this->mCaseSensitive ? '' : 'i';
177 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
178 $this->mRegexStart = "/^(?:{$this->mBaseRegex})/{$case}";
179 $this->mVariableRegex = str_replace( "\\$1", "(.*?)", $this->mRegex );
180 $this->mVariableStartToEndRegex = str_replace( "\\$1", "(.*?)",
181 "/^(?:{$this->mBaseRegex})$/{$case}" );
182 }
183
184 /**
185 * Gets a regex representing matching the word
186 */
187 function getRegex() {
188 if ($this->mRegex == '' ) {
189 $this->initRegex();
190 }
191 return $this->mRegex;
192 }
193
194 /**
195 * Gets the regexp case modifier to use, i.e. i or nothing, to be used if
196 * one is using MagicWord::getBaseRegex(), otherwise it'll be included in
197 * the complete expression
198 */
199 function getRegexCase() {
200 if ( $this->mRegex === '' )
201 $this->initRegex();
202
203 return $this->mCaseSensitive ? '' : 'i';
204 }
205
206 /**
207 * Gets a regex matching the word, if it is at the string start
208 */
209 function getRegexStart() {
210 if ($this->mRegex == '' ) {
211 $this->initRegex();
212 }
213 return $this->mRegexStart;
214 }
215
216 /**
217 * regex without the slashes and what not
218 */
219 function getBaseRegex() {
220 if ($this->mRegex == '') {
221 $this->initRegex();
222 }
223 return $this->mBaseRegex;
224 }
225
226 /**
227 * Returns true if the text contains the word
228 * @return bool
229 */
230 function match( $text ) {
231 return preg_match( $this->getRegex(), $text );
232 }
233
234 /**
235 * Returns true if the text starts with the word
236 * @return bool
237 */
238 function matchStart( $text ) {
239 return preg_match( $this->getRegexStart(), $text );
240 }
241
242 /**
243 * Returns NULL if there's no match, the value of $1 otherwise
244 * The return code is the matched string, if there's no variable
245 * part in the regex and the matched variable part ($1) if there
246 * is one.
247 */
248 function matchVariableStartToEnd( $text ) {
249 $matches = array();
250 $matchcount = preg_match( $this->getVariableStartToEndRegex(), $text, $matches );
251 if ( $matchcount == 0 ) {
252 return NULL;
253 } else {
254 # multiple matched parts (variable match); some will be empty because of
255 # synonyms. The variable will be the second non-empty one so remove any
256 # blank elements and re-sort the indices.
257 # See also bug 6526
258
259 $matches = array_values(array_filter($matches));
260
261 if ( count($matches) == 1 ) { return $matches[0]; }
262 else { return $matches[1]; }
263 }
264 }
265
266
267 /**
268 * Returns true if the text matches the word, and alters the
269 * input string, removing all instances of the word
270 */
271 function matchAndRemove( &$text ) {
272 $this->mFound = false;
273 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
274 return $this->mFound;
275 }
276
277 function matchStartAndRemove( &$text ) {
278 $this->mFound = false;
279 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
280 return $this->mFound;
281 }
282
283 /**
284 * Used in matchAndRemove()
285 * @private
286 **/
287 function pregRemoveAndRecord( $match ) {
288 $this->mFound = true;
289 return '';
290 }
291
292 /**
293 * Replaces the word with something else
294 */
295 function replace( $replacement, $subject, $limit=-1 ) {
296 $res = preg_replace( $this->getRegex(), wfRegexReplacement( $replacement ), $subject, $limit );
297 $this->mModified = !($res === $subject);
298 return $res;
299 }
300
301 /**
302 * Variable handling: {{SUBST:xxx}} style words
303 * Calls back a function to determine what to replace xxx with
304 * Input word must contain $1
305 */
306 function substituteCallback( $text, $callback ) {
307 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
308 $this->mModified = !($res === $text);
309 return $res;
310 }
311
312 /**
313 * Matches the word, where $1 is a wildcard
314 */
315 function getVariableRegex() {
316 if ( $this->mVariableRegex == '' ) {
317 $this->initRegex();
318 }
319 return $this->mVariableRegex;
320 }
321
322 /**
323 * Matches the entire string, where $1 is a wildcard
324 */
325 function getVariableStartToEndRegex() {
326 if ( $this->mVariableStartToEndRegex == '' ) {
327 $this->initRegex();
328 }
329 return $this->mVariableStartToEndRegex;
330 }
331
332 /**
333 * Accesses the synonym list directly
334 */
335 function getSynonym( $i ) {
336 return $this->mSynonyms[$i];
337 }
338
339 function getSynonyms() {
340 return $this->mSynonyms;
341 }
342
343 /**
344 * Returns true if the last call to replace() or substituteCallback()
345 * returned a modified text, otherwise false.
346 */
347 function getWasModified(){
348 return $this->mModified;
349 }
350
351 /**
352 * $magicarr is an associative array of (magic word ID => replacement)
353 * This method uses the php feature to do several replacements at the same time,
354 * thereby gaining some efficiency. The result is placed in the out variable
355 * $result. The return value is true if something was replaced.
356 * @static
357 **/
358 function replaceMultiple( $magicarr, $subject, &$result ){
359 $search = array();
360 $replace = array();
361 foreach( $magicarr as $id => $replacement ){
362 $mw = MagicWord::get( $id );
363 $search[] = $mw->getRegex();
364 $replace[] = $replacement;
365 }
366
367 $result = preg_replace( $search, $replace, $subject );
368 return !($result === $subject);
369 }
370
371 /**
372 * Adds all the synonyms of this MagicWord to an array, to allow quick
373 * lookup in a list of magic words
374 */
375 function addToArray( &$array, $value ) {
376 foreach ( $this->mSynonyms as $syn ) {
377 $array[$syn] = $value;
378 }
379 }
380
381 function isCaseSensitive() {
382 return $this->mCaseSensitive;
383 }
384 }
385
386 ?>