Initial revision
[lhc/web/wiklou.git] / includes / SearchEngine.php
1 <?
2 # See search.doc
3
4 class SearchEngine {
5 /* private */ var $mUsertext, $mSearchterms;
6 /* private */ var $mTitlecond, $mTextcond;
7
8 var $doSearchRedirects = true;
9 var $addtoquery = array();
10 var $namespacesToSearch = array();
11 var $alternateTitle;
12
13 function SearchEngine( $text )
14 {
15 # We display the query, so let's strip it for safety
16 #
17 $lc = SearchEngine::legalSearchChars() . "()";
18 $this->mUsertext = trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
19 $this->mSearchterms = array();
20 }
21
22 function queryNamespaces()
23 {
24 return "cur_namespace IN (" . implode( ",", $this->namespacesToSearch ) . ")";
25 #return "1";
26 }
27
28 function searchRedirects()
29 {
30 if ( $this->doSearchRedirects ) return "";
31 return "AND cur_is_redirect=0 ";
32 }
33
34 function powersearch()
35 {
36 global $wgUser, $wgOut, $wgLang, $wgTitle;
37 $nscb = array();
38
39 $search = $_REQUEST['search'];
40 $searchx = $_REQUEST['searchx'];
41 $listredirs = $_REQUEST['redirs'];
42 $nscb[0] = $_REQUEST['ns0'];
43 $nscb[1] = $_REQUEST['ns1'];
44 $nscb[2] = $_REQUEST['ns2'];
45 $nscb[3] = $_REQUEST['ns3'];
46 $nscb[4] = $_REQUEST['ns4'];
47 $nscb[5] = $_REQUEST['ns5'];
48 $nscb[6] = $_REQUEST['ns6'];
49 $nscb[7] = $_REQUEST['ns7'];
50
51 if ( ! isset ( $searchx ) ) { /* First time here */
52 $nscb[0] = $listredirs = 1; /* All others should be unset */
53 }
54 $this->checkboxes["searchx"] = 1;
55 $ret = wfMsg("powersearchtext");
56
57 # Determine namespace checkboxes
58
59 $ns = $wgLang->getNamespaces();
60 array_shift( $ns ); /* Skip "Special" */
61
62 $r1 = "";
63 for ( $i = 0; $i < count( $ns ); ++$i ) {
64 $checked = "";
65 if ( $nscb[$i] == 1 ) {
66 $checked = " checked";
67 $this->addtoquery["ns{$i}"] = 1;
68 array_push( $this->namespacesToSearch, $i );
69 }
70 $name = str_replace( "_", " ", $ns[$i] );
71 if ( "" == $name ) { $name = "(Main)"; }
72
73 if ( 0 != $i ) { $r1 .= " "; }
74 $r1 .= "<input type=checkbox value=\"1\" name=\"" .
75 "ns{$i}\"{$checked}>{$name}\n";
76 }
77 $ret = str_replace ( "$1", $r1, $ret );
78
79 # List redirects checkbox
80
81 $checked = "";
82 if ( $listredirs == 1 ) {
83 $this->addtoquery["redirs"] = 1;
84 $checked = " checked";
85 }
86 $r2 = "<input type=checkbox value=1 name=\"redirs\"{$checked}>\n";
87 $ret = str_replace( "$2", $r2, $ret );
88
89 # Search field
90
91 $r3 = "<input type=text name=\"search\" value=\"" .
92 htmlspecialchars( $search ) ."\" width=80>\n";
93 $ret = str_replace( "$3", $r3, $ret );
94
95 # Searchx button
96
97 $r9 = "<input type=submit name=\"searchx\" value=\"" .
98 wfMsg("powersearch") . "\">\n";
99 $ret = str_replace( "$9", $r9, $ret );
100
101 $ret = "<br><br>\n<form id=\"powersearch\" method=\"get\" " .
102 "action=\"" . wfLocalUrl( "" ) . "\">\n{$ret}\n</form>\n";
103
104 if ( isset ( $searchx ) ) {
105 if ( ! $listredirs ) { $this->doSearchRedirects = false; }
106 }
107 return $ret;
108 }
109
110 function showResults()
111 {
112 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgDisableTextSearch;
113 $fname = "SearchEngine::showResults";
114
115 $offset = $_REQUEST['offset'];
116 $limit = $_REQUEST['limit'];
117 $search = $_REQUEST['search'];
118
119 $powersearch = $this->powersearch(); /* Need side-effects here? */
120
121 $wgOut->setPageTitle( wfMsg( "searchresults" ) );
122 $q = str_replace( "$1", $this->mUsertext,
123 wfMsg( "searchquery" ) );
124 $wgOut->setSubtitle( $q );
125 $wgOut->setArticleFlag( false );
126 $wgOut->setRobotpolicy( "noindex,nofollow" );
127
128 $sk = $wgUser->getSkin();
129 $text = str_replace( "$1", $sk->makeKnownLink(
130 wfMsg( "searchhelppage" ), wfMsg( "searchingwikipedia" ) ),
131 wfMsg( "searchresulttext" ) );
132 $wgOut->addHTML( $text );
133
134 $this->parseQuery();
135 if ( "" == $this->mTitlecond || "" == $this->mTextcond ) {
136 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
137 "<p>" . wfMsg( "badquerytext" ) );
138 return;
139 }
140 if ( ! isset( $limit ) ) {
141 $limit = $wgUser->getOption( "searchlimit" );
142 if ( ! $limit ) { $limit = 20; }
143 }
144 if ( ! $offset ) { $offset = 0; }
145
146 $searchnamespaces = $this->queryNamespaces();
147 $redircond = $this->searchRedirects();
148
149 $sql = "SELECT cur_id,cur_namespace,cur_title," .
150 "cur_text FROM cur,searchindex " .
151 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
152 "AND {$searchnamespaces} {$redircond}" .
153 "LIMIT {$offset}, {$limit}";
154 $res1 = wfQuery( $sql, $fname );
155
156 if ( $wgDisableTextSearch ) {
157 $res2 = 0;
158 } else {
159 $sql = "SELECT cur_id,cur_namespace,cur_title," .
160 "cur_text FROM cur,searchindex " .
161 "WHERE cur_id=si_page AND {$this->mTextcond} " .
162 "AND {$searchnamespaces} {$redircond} " .
163 "LIMIT {$offset}, {$limit}";
164 $res2 = wfQuery( $sql, $fname );
165 }
166
167 $top = wfShowingResults( $offset, $limit );
168 $wgOut->addHTML( "<p>{$top}\n" );
169
170 # For powersearch
171
172 $a2l = "" ;
173 $akk = array_keys( $this->addtoquery ) ;
174 foreach ( $akk AS $ak ) {
175 $a2l .= "&{$ak}={$this->addtoquery[$ak]}" ;
176 }
177
178 $sl = wfViewPrevNext( $offset, $limit, "",
179 "search=" . wfUrlencode( $this->mUsertext ) . $a2l );
180 $wgOut->addHTML( "<br>{$sl}\n" );
181
182 $foundsome = false;
183
184 if ( 0 == wfNumRows( $res1 ) ) {
185 $wgOut->addHTML( "<h2>" . wfMsg( "notitlematches" ) .
186 "</h2>\n" );
187 } else {
188 $foundsome = true;
189 $off = $offset + 1;
190 $wgOut->addHTML( "<h2>" . wfMsg( "titlematches" ) .
191 "</h2>\n<ol start='{$off}'>" );
192
193 while ( $row = wfFetchObject( $res1 ) ) {
194 $this->showHit( $row );
195 }
196 wfFreeResult( $res1 );
197 $wgOut->addHTML( "</ol>\n" );
198 }
199
200 if ( $wgDisableTextSearch ) {
201 $wgOut->addHTML( str_replace( "$1",
202 htmlspecialchars( $search ), wfMsg( "searchdisabled" ) ) );
203 } else {
204 if ( 0 == wfNumRows( $res2 ) ) {
205 $wgOut->addHTML( "<h2>" . wfMsg( "notextmatches" ) .
206 "</h2>\n" );
207 } else {
208 $foundsome = true;
209 $off = $offset + 1;
210 $wgOut->addHTML( "<h2>" . wfMsg( "textmatches" ) . "</h2>\n" .
211 "<ol start='{$off}'>" );
212 while ( $row = wfFetchObject( $res2 ) ) {
213 $this->showHit( $row );
214 }
215 wfFreeResult( $res2 );
216 $wgOut->addHTML( "</ol>\n" );
217 }
218 }
219 if ( ! $foundsome ) {
220 $wgOut->addHTML( "<p>" . wfMsg( "nonefound" ) . "\n" );
221 }
222 $wgOut->addHTML( "<p>{$sl}\n" );
223 $wgOut->addHTML( $powersearch );
224 }
225
226 function legalSearchChars()
227 {
228 $lc = "A-Za-z_'0-9\\x80-\\xFF\\-";
229 return $lc;
230 }
231
232 function parseQuery()
233 {
234 global $wgDBminWordLen, $wgLang;
235
236 $lc = SearchEngine::legalSearchChars() . "()";
237 $q = preg_replace( "/([()])/", " \\1 ", $this->mUsertext );
238 $q = preg_replace( "/\\s+/", " ", $q );
239 $w = explode( " ", strtolower( trim( $q ) ) );
240
241 $last = $cond = "";
242 foreach ( $w as $word ) {
243 $word = $wgLang->stripForSearch( $word );
244 if ( "and" == $word || "or" == $word || "not" == $word
245 || "(" == $word || ")" == $word ) {
246 $cond .= " " . strtoupper( $word );
247 $last = "";
248 } else if ( strlen( $word ) < $wgDBminWordLen ) {
249 continue;
250 } else if ( FulltextStoplist::inList( $word ) ) {
251 continue;
252 } else {
253 if ( "" != $last ) { $cond .= " AND"; }
254 $cond .= " (MATCH (##field##) AGAINST ('" .
255 wfStrencode( $word ). "'))";
256 $last = $word;
257 array_push( $this->mSearchterms, "\\b" . $word . "\\b" );
258 }
259 }
260 if ( 0 == count( $this->mSearchterms ) ) { return; }
261
262 # To disable boolean:
263 # $cond = "MATCH (##field##) AGAINST('" . wfStrencode( $q ) . "')";
264
265 $this->mTitlecond = "(" . str_replace( "##field##",
266 "si_title", $cond ) . " )";
267
268 $this->mTextcond = "(" . str_replace( "##field##",
269 "si_text", $cond ) . " AND (cur_is_redirect=0) )";
270 }
271
272 function showHit( $row )
273 {
274 global $wgUser, $wgOut;
275
276 $t = Title::makeName( $row->cur_namespace, $row->cur_title );
277 $sk = $wgUser->getSkin();
278
279 $contextlines = $wgUser->getOption( "contextlines" );
280 if ( "" == $contextlines ) { $contextlines = 5; }
281 $contextchars = $wgUser->getOption( "contextchars" );
282 if ( "" == $contextchars ) { $contextchars = 50; }
283
284 $link = $sk->makeKnownLink( $t, "" );
285 $size = str_replace( "$1", strlen( $row->cur_text ), WfMsg( "nbytes" ) );
286 $wgOut->addHTML( "<li>{$link} ({$size})" );
287
288 $lines = explode( "\n", $row->cur_text );
289 $pat1 = "/(.*)(" . implode( "|", $this->mSearchterms ) . ")(.*)/i";
290 $lineno = 0;
291
292 foreach ( $lines as $line ) {
293 if ( 0 == $contextlines ) { break; }
294 --$contextlines;
295 ++$lineno;
296 if ( ! preg_match( $pat1, $line, $m ) ) { continue; }
297
298 $pre = $m[1];
299 if ( 0 == $contextchars ) { $pre = "..."; }
300 else {
301 if ( strlen( $pre ) > $contextchars ) {
302 $pre = "..." . substr( $pre, -$contextchars );
303 }
304 }
305 $pre = wfEscapeHTML( $pre );
306
307 if ( count( $m ) < 3 ) { $post = ""; }
308 else { $post = $m[3]; }
309
310 if ( 0 == $contextchars ) { $post = "..."; }
311 else {
312 if ( strlen( $post ) > $contextchars ) {
313 $post = substr( $post, 0, $contextchars ) . "...";
314 }
315 }
316 $post = wfEscapeHTML( $post );
317 $found = wfEscapeHTML( $m[2] );
318
319 $line = "{$pre}{$found}{$post}";
320 $pat2 = "/(" . implode( "|", $this->mSearchterms ) . ")/i";
321 $line = preg_replace( $pat2,
322 "<font color='red'>\\1</font>", $line );
323
324 $wgOut->addHTML( "<br><small>{$lineno}: {$line}</small>\n" );
325 }
326 $wgOut->addHTML( "</li>\n" );
327 }
328
329 function goResult()
330 {
331 global $wgOut, $wgArticle, $wgTitle;
332 $fname = "SearchEngine::goResult";
333
334 $search = $_REQUEST['search'];
335
336 # First try to go to page as entered
337 #
338 $wgArticle = new Article();
339 $wgTitle = Title::newFromText( $search );
340
341 if ( 0 != $wgArticle->getID() ) {
342 $wgArticle->view();
343 return;
344 }
345
346 # Now try all lower case (i.e. first letter capitalized)
347 #
348 $wgTitle = Title::newFromText( strtolower( $search ) );
349 if ( 0 != $wgArticle->getID() ) {
350 $wgArticle->view();
351 return;
352 }
353
354 # Now try capitalized string
355 #
356 $wgTitle=Title::newFromText( ucwords( strtolower( $search ) ) );
357 if ( 0 != $wgArticle->getID() ) {
358 $wgArticle->view();
359 return;
360 }
361
362 # Try a near match
363 #
364 $this->parseQuery();
365 $sql = "SELECT cur_id,cur_title,cur_namespace,si_page FROM cur,searchindex " .
366 "WHERE cur_id=si_page AND {$this->mTitlecond} LIMIT 1";
367
368 if ( "" != $this->mTitlecond ) {
369 $res = wfQuery( $sql, $fname );
370 }
371 if ( isset( $res ) && 0 != wfNumRows( $res ) ) {
372 $s = wfFetchObject( $res );
373
374 $wgTitle = Title::newFromDBkey( $s->cur_title );
375 $wgTitle->setNamespace( $s->cur_namespace );
376 $wgArticle->view();
377 return;
378 }
379 $wgOut->addHTML( wfMsg("nogomatch") . "\n<p>" );
380 $this->showResults();
381 }
382 }
383