Static code analysis housekeeping time... things that could be double-checked are...
[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 'numberofedits',
57 'sitename',
58 'server',
59 'servername',
60 'scriptpath',
61 'pagename',
62 'pagenamee',
63 'fullpagename',
64 'fullpagenamee',
65 'namespace',
66 'namespacee',
67 'currentweek',
68 'currentdow',
69 'localweek',
70 'localdow',
71 'revisionid',
72 'revisionday',
73 'revisionday2',
74 'revisionmonth',
75 'revisionyear',
76 'revisiontimestamp',
77 'subpagename',
78 'subpagenamee',
79 'displaytitle',
80 'talkspace',
81 'talkspacee',
82 'subjectspace',
83 'subjectspacee',
84 'talkpagename',
85 'talkpagenamee',
86 'subjectpagename',
87 'subjectpagenamee',
88 'numberofusers',
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 function getId() {
391 return $this->mId;
392 }
393 }
394
395 /**
396 * Class for handling an array of magic words
397 */
398 class MagicWordArray {
399 var $names = array();
400 var $hash;
401 var $baseRegex, $regex;
402
403 function __construct( $names = array() ) {
404 $this->names = $names;
405 }
406
407 /**
408 * Add a magic word by name
409 */
410 public function add( $name ) {
411 global $wgContLang;
412 $this->names[] = $name;
413 $this->hash = $this->baseRegex = $this->regex = null;
414 }
415
416 /**
417 * Add a number of magic words by name
418 */
419 public function addArray( $names ) {
420 $this->names = array_merge( $this->names, array_values( $names ) );
421 $this->hash = $this->baseRegex = $this->regex = null;
422 }
423
424 /**
425 * Get a 2-d hashtable for this array
426 */
427 function getHash() {
428 if ( is_null( $this->hash ) ) {
429 global $wgContLang;
430 $this->hash = array( 0 => array(), 1 => array() );
431 foreach ( $this->names as $name ) {
432 $magic = MagicWord::get( $name );
433 $case = intval( $magic->isCaseSensitive() );
434 foreach ( $magic->getSynonyms() as $syn ) {
435 if ( !$case ) {
436 $syn = $wgContLang->lc( $syn );
437 }
438 $this->hash[$case][$syn] = $name;
439 }
440 }
441 }
442 return $this->hash;
443 }
444
445 /**
446 * Get the base regex
447 */
448 function getBaseRegex() {
449 if ( is_null( $this->baseRegex ) ) {
450 $this->baseRegex = array( 0 => '', 1 => '' );
451 foreach ( $this->names as $name ) {
452 $magic = MagicWord::get( $name );
453 $case = intval( $magic->isCaseSensitive() );
454 foreach ( $magic->getSynonyms() as $i => $syn ) {
455 $group = "(?P<{$i}_{$name}>" . preg_quote( $syn, '/' ) . ')';
456 if ( $this->baseRegex[$case] === '' ) {
457 $this->baseRegex[$case] = $group;
458 } else {
459 $this->baseRegex[$case] .= '|' . $group;
460 }
461 }
462 }
463 }
464 return $this->baseRegex;
465 }
466
467 /**
468 * Get an unanchored regex
469 */
470 function getRegex() {
471 if ( is_null( $this->regex ) ) {
472 $base = $this->getBaseRegex();
473 $this->regex = array( '', '' );
474 if ( $this->baseRegex[0] !== '' ) {
475 $this->regex[0] = "/{$base[0]}/iuS";
476 }
477 if ( $this->baseRegex[1] !== '' ) {
478 $this->regex[1] = "/{$base[1]}/S";
479 }
480 }
481 return $this->regex;
482 }
483
484 /**
485 * Get a regex for matching variables
486 */
487 function getVariableRegex() {
488 return str_replace( "\\$1", "(.*?)", $this->getRegex() );
489 }
490
491 /**
492 * Get an anchored regex for matching variables
493 */
494 function getVariableStartToEndRegex() {
495 $base = $this->getBaseRegex();
496 $newRegex = array( '', '' );
497 if ( $base[0] !== '' ) {
498 $newRegex[0] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[0]})$/iuS" );
499 }
500 if ( $base[1] !== '' ) {
501 $newRegex[1] = str_replace( "\\$1", "(.*?)", "/^(?:{$base[1]})$/S" );
502 }
503 return $newRegex;
504 }
505
506 /**
507 * Parse a match array from preg_match
508 */
509 function parseMatch( $m ) {
510 reset( $m );
511 while ( list( $key, $value ) = each( $m ) ) {
512 if ( $key === 0 || $value === '' ) {
513 continue;
514 }
515 $parts = explode( '_', $key, 2 );
516 if ( count( $parts ) != 2 ) {
517 // This shouldn't happen
518 // continue;
519 throw new MWException( __METHOD__ . ': bad parameter name' );
520 }
521 list( /* $synIndex */, $magicName ) = $parts;
522 $paramValue = next( $m );
523 return array( $magicName, $paramValue );
524 }
525 // This shouldn't happen either
526 throw new MWException( __METHOD__.': parameter not found' );
527 return array( false, false );
528 }
529
530 /**
531 * Match some text, with parameter capture
532 * Returns an array with the magic word name in the first element and the
533 * parameter in the second element.
534 * Both elements are false if there was no match.
535 */
536 public function matchVariableStartToEnd( $text ) {
537 global $wgContLang;
538 $regexes = $this->getVariableStartToEndRegex();
539 foreach ( $regexes as $regex ) {
540 if ( $regex !== '' ) {
541 $m = false;
542 if ( preg_match( $regex, $text, $m ) ) {
543 return $this->parseMatch( $m );
544 }
545 }
546 }
547 return array( false, false );
548 }
549
550 /**
551 * Match some text, without parameter capture
552 * Returns the magic word name, or false if there was no capture
553 */
554 public function matchStartToEnd( $text ) {
555 $hash = $this->getHash();
556 if ( isset( $hash[1][$text] ) ) {
557 return $hash[1][$text];
558 }
559 global $wgContLang;
560 $lc = $wgContLang->lc( $text );
561 if ( isset( $hash[0][$lc] ) ) {
562 return $hash[0][$lc];
563 }
564 return false;
565 }
566 }