It helps when you don't break things...
[mediawiki.git] / includes / MagicWord.php
blob2ad02e488b255106d37430eb19f3e42ec0a3920f
1 <?php
2 /**
3 * File for magic words
4 * @addtogroup Parser
5 */
7 /**
8 * This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
9 * Usage:
10 * if (MagicWord::get( 'redirect' )->match( $text ) )
12 * Possible future improvements:
13 * * Simultaneous searching for a number of magic words
14 * * MagicWord::$mObjects in shared memory
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.
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.
24 class MagicWord {
25 /**#@+
26 * @private
28 var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
29 var $mRegexStart, $mBaseRegex, $mVariableRegex;
30 var $mModified, $mFound;
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',
105 static public $mObjects = array();
107 /**#@-*/
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;
121 * Factory: creates an object representing an ID
122 * @static
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;
130 return self::$mObjects[$id];
134 * Get an array of parser variable IDs
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 );
145 # Get variable IDs
146 wfRunHooks( 'MagicWordwgVariableIDs', array( &self::$mVariableIDs ) );
147 self::$mVariableIDsInitialised = true;
149 return self::$mVariableIDs;
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" );
165 * Preliminary initialisation
166 * @private
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
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 );
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}" );
189 * Gets a regex representing matching the word
191 function getRegex() {
192 if ($this->mRegex == '' ) {
193 $this->initRegex();
195 return $this->mRegex;
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
203 function getRegexCase() {
204 if ( $this->mRegex === '' )
205 $this->initRegex();
207 return $this->mCaseSensitive ? '' : 'iu';
211 * Gets a regex matching the word, if it is at the string start
213 function getRegexStart() {
214 if ($this->mRegex == '' ) {
215 $this->initRegex();
217 return $this->mRegexStart;
221 * regex without the slashes and what not
223 function getBaseRegex() {
224 if ($this->mRegex == '') {
225 $this->initRegex();
227 return $this->mBaseRegex;
231 * Returns true if the text contains the word
232 * @return bool
234 function match( $text ) {
235 return preg_match( $this->getRegex(), $text );
239 * Returns true if the text starts with the word
240 * @return bool
242 function matchStart( $text ) {
243 return preg_match( $this->getRegexStart(), $text );
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.
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
263 $matches = array_values(array_filter($matches));
265 if ( count($matches) == 1 ) { return $matches[0]; }
266 else { return $matches[1]; }
272 * Returns true if the text matches the word, and alters the
273 * input string, removing all instances of the word
275 function matchAndRemove( &$text ) {
276 $this->mFound = false;
277 $text = preg_replace_callback( $this->getRegex(), array( &$this, 'pregRemoveAndRecord' ), $text );
278 return $this->mFound;
281 function matchStartAndRemove( &$text ) {
282 $this->mFound = false;
283 $text = preg_replace_callback( $this->getRegexStart(), array( &$this, 'pregRemoveAndRecord' ), $text );
284 return $this->mFound;
288 * Used in matchAndRemove()
289 * @private
291 function pregRemoveAndRecord( ) {
292 $this->mFound = true;
293 return '';
297 * Replaces the word with something else
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;
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
310 function substituteCallback( $text, $callback ) {
311 $res = preg_replace_callback( $this->getVariableRegex(), $callback, $text );
312 $this->mModified = !($res === $text);
313 return $res;
317 * Matches the word, where $1 is a wildcard
319 function getVariableRegex() {
320 if ( $this->mVariableRegex == '' ) {
321 $this->initRegex();
323 return $this->mVariableRegex;
327 * Matches the entire string, where $1 is a wildcard
329 function getVariableStartToEndRegex() {
330 if ( $this->mVariableStartToEndRegex == '' ) {
331 $this->initRegex();
333 return $this->mVariableStartToEndRegex;
337 * Accesses the synonym list directly
339 function getSynonym( $i ) {
340 return $this->mSynonyms[$i];
343 function getSynonyms() {
344 return $this->mSynonyms;
348 * Returns true if the last call to replace() or substituteCallback()
349 * returned a modified text, otherwise false.
351 function getWasModified(){
352 return $this->mModified;
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
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;
371 $result = preg_replace( $search, $replace, $subject );
372 return !($result === $subject);
376 * Adds all the synonyms of this MagicWord to an array, to allow quick
377 * lookup in a list of magic words
379 function addToArray( &$array, $value ) {
380 global $wgContLang;
381 foreach ( $this->mSynonyms as $syn ) {
382 $array[$wgContLang->lc($syn)] = $value;
386 function isCaseSensitive() {
387 return $this->mCaseSensitive;