Fixed merge error
[mediawiki.git] / includes / MagicWord.php
blob91bc2c43f1e805503967155f7cc62cbceb01293c
1 <?
3 # This class encapsulates "magic words" such as #redirect, __NOTOC__, etc.
4 # Usage:
5 # if (MagicWord::get( MAG_REDIRECT )->match( $text ) )
6 #
7 # Possible future improvements:
8 # * Simultaneous searching for a number of magic words
9 # * $wgMagicWords in shared memory
11 # Please avoid reading the data out of one of these objects and then writing
12 # special case code. If possible, add another match()-like function here.
14 /*private*/ $wgMagicFound = false;
16 class MagicWord {
17 /*private*/ var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
18 /*private*/ var $mRegexStart, $mBaseRegex, $mVariableRegex;
20 function MagicWord($id = 0, $syn = "", $cs = false)
22 $this->mId = $id;
23 $this->mSynonyms = (array)$syn;
24 $this->mCaseSensitive = $cs;
25 $this->mRegex = "";
26 $this->mRegexStart = "";
27 $this->mVariableRegex = "";
30 /*static*/ function &get( $id )
32 global $wgMagicWords;
34 if (!array_key_exists( $id, $wgMagicWords ) ) {
35 $mw = new MagicWord();
36 $mw->load( $id );
37 $wgMagicWords[$id] = $mw;
39 return $wgMagicWords[$id];
42 function load( $id )
44 global $wgLang;
46 $this->mId = $id;
47 $wgLang->getMagic( $this );
50 /* private */ function initRegex()
52 $escSyn = array_map( "preg_quote", $this->mSynonyms );
53 $this->mBaseRegex = implode( "|", $escSyn );
54 $case = $this->mCaseSensitive ? "" : "i";
55 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
56 $this->mRegexStart = "/^{$this->mBaseRegex}/{$case}";
57 $this->mVariableRegex = str_replace( "\\$1", "([A-Za-z0-9_\-]*)", $this->mRegex );
60 function getRegex()
62 if ($this->mRegex == "" ) {
63 $this->initRegex();
65 return $this->mRegex;
68 function getRegexStart()
70 if ($this->mRegex == "" ) {
71 $this->initRegex();
73 return $this->mRegexStart;
76 function getBaseRegex()
78 if ($this->mRegex == "") {
79 $this->initRegex();
81 return $this->mBaseRegex;
84 function match( $text ) {
85 return preg_match( $this->getRegex(), $text );
88 function matchStart( $text )
90 return preg_match( $this->getRegexStart(), $text );
93 function matchAndRemove( &$text )
95 global $wgMagicFound;
96 $wgMagicFound = false;
97 $text = preg_replace_callback( $this->getRegex(), "pregRemoveAndRecord", $text );
98 return $wgMagicFound;
101 function replace( $replacement, $subject )
103 return preg_replace( $this->getRegex(), $replacement, $subject );
106 function substituteCallback( $text, $callback ) {
107 $regex = $this->getVariableRegex();
108 return preg_replace_callback( $this->getVariableRegex(), $callback, $text );
111 function getVariableRegex()
113 if ( $this->mVariableRegex == "" ) {
114 $this->initRegex();
116 return $this->mVariableRegex;
119 function getSynonym( $i ) {
120 return $this->mSynonyms[$i];
124 /*private*/ function pregRemoveAndRecord( $match )
126 global $wgMagicFound;
127 $wgMagicFound = true;
128 return "";