new Block object, block expiry, optional sysop blocks
[lhc/web/wiklou.git] / includes / MagicWord.php
1 <?
2
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
10 #
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.
13
14 /*private*/ $wgMagicFound = false;
15
16 class MagicWord {
17 /*private*/ var $mId, $mSynonyms, $mCaseSensitive, $mRegex;
18 /*private*/ var $mRegexStart, $mBaseRegex;
19
20 function MagicWord($id = 0, $syn = "", $cs = false)
21 {
22 $this->mId = $id;
23 $this->mSynonyms = (array)$syn;
24 $this->mCaseSensitive = $cs;
25 $this->mRegex = "";
26 $this->mRegexStart = "";
27 }
28
29 /*static*/ function &get( $id )
30 {
31 global $wgMagicWords;
32
33 if (!array_key_exists( $id, $wgMagicWords ) ) {
34 $mw = new MagicWord();
35 $mw->load( $id );
36 $wgMagicWords[$id] = $mw;
37 }
38 return $wgMagicWords[$id];
39 }
40
41 function load( $id )
42 {
43 global $wgLang;
44
45 $this->mId = $id;
46 $wgLang->getMagic( $this );
47 }
48
49 /* private */ function initRegex()
50 {
51 $escSyn = array_map( "preg_quote", $this->mSynonyms );
52 $this->mBaseRegex = implode( "|", $escSyn );
53 $case = $this->mCaseSensitive ? "" : "i";
54 $this->mRegex = "/{$this->mBaseRegex}/{$case}";
55 $this->mRegexStart = "/^{$this->mBaseRegex}/{$case}";
56 }
57
58 function getRegex()
59 {
60 if ($this->mRegex == "" ) {
61 $this->initRegex();
62 }
63 return $this->mRegex;
64 }
65
66 function getRegexStart()
67 {
68 if ($this->mRegex == "" ) {
69 $this->initRegex();
70 }
71 return $this->mRegexStart;
72 }
73
74 function getBaseRegex()
75 {
76 if ($this->mRegex == "") {
77 $this->initRegex();
78 }
79 return $this->mBaseRegex;
80 }
81
82 function match( $text ) {
83 return preg_match( $this->getRegex(), $text );
84 }
85
86 function matchStart( $text )
87 {
88 return preg_match( $this->getRegexStart(), $text );
89 }
90
91 function matchAndRemove( &$text )
92 {
93 global $wgMagicFound;
94 $wgMagicFound = false;
95 $text = preg_replace_callback( $this->getRegex(), "pregRemoveAndRecord", $text );
96 return $wgMagicFound;
97 }
98
99 function replace( $replacement, $subject )
100 {
101 return preg_replace( $this->getRegex(), $replacement, $subject );
102 }
103 }
104
105 /*private*/ function pregRemoveAndRecord( $match )
106 {
107 global $wgMagicFound;
108 $wgMagicFound = true;
109 return "";
110 }
111
112 ?>