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