Go button: try all upper case before near match
[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 global $wgDBmysql4;
18 $lc = SearchEngine::legalSearchChars() . "()";
19 if( $wgDBmysql4 ) $lc .= "\"~<>*+-";
20 $this->mUsertext = trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
21 $this->mSearchterms = array();
22 }
23
24 function queryNamespaces()
25 {
26 return "cur_namespace IN (" . implode( ",", $this->namespacesToSearch ) . ")";
27 #return "1";
28 }
29
30 function searchRedirects()
31 {
32 if ( $this->doSearchRedirects ) return "";
33 return "AND cur_is_redirect=0 ";
34 }
35
36 function powersearch()
37 {
38 global $wgUser, $wgOut, $wgLang, $wgTitle;
39 $nscb = array();
40
41 $search = $_REQUEST['search'];
42 $searchx = $_REQUEST['searchx'];
43 $listredirs = $_REQUEST['redirs'];
44 $nscb[0] = $_REQUEST['ns0'];
45 $nscb[1] = $_REQUEST['ns1'];
46 $nscb[2] = $_REQUEST['ns2'];
47 $nscb[3] = $_REQUEST['ns3'];
48 $nscb[4] = $_REQUEST['ns4'];
49 $nscb[5] = $_REQUEST['ns5'];
50 $nscb[6] = $_REQUEST['ns6'];
51 $nscb[7] = $_REQUEST['ns7'];
52
53 if ( ! isset ( $searchx ) ) { /* First time here */
54 $nscb[0] = $listredirs = 1; /* All others should be unset */
55 }
56 $this->checkboxes["searchx"] = 1;
57 $ret = wfMsg("powersearchtext");
58
59 # Determine namespace checkboxes
60
61 $ns = $wgLang->getNamespaces();
62 array_shift( $ns ); /* Skip "Special" */
63
64 $r1 = "";
65 for ( $i = 0; $i < count( $ns ); ++$i ) {
66 $checked = "";
67 if ( $nscb[$i] == 1 ) {
68 $checked = " checked";
69 $this->addtoquery["ns{$i}"] = 1;
70 array_push( $this->namespacesToSearch, $i );
71 }
72 $name = str_replace( "_", " ", $ns[$i] );
73 if ( "" == $name ) { $name = "(Main)"; }
74
75 if ( 0 != $i ) { $r1 .= " "; }
76 $r1 .= "<input type=checkbox value=\"1\" name=\"" .
77 "ns{$i}\"{$checked}>{$name}\n";
78 }
79 $ret = str_replace ( "$1", $r1, $ret );
80
81 # List redirects checkbox
82
83 $checked = "";
84 if ( $listredirs == 1 ) {
85 $this->addtoquery["redirs"] = 1;
86 $checked = " checked";
87 }
88 $r2 = "<input type=checkbox value=1 name=\"redirs\"{$checked}>\n";
89 $ret = str_replace( "$2", $r2, $ret );
90
91 # Search field
92
93 $r3 = "<input type=text name=\"search\" value=\"" .
94 htmlspecialchars( $search ) ."\" width=80>\n";
95 $ret = str_replace( "$3", $r3, $ret );
96
97 # Searchx button
98
99 $r9 = "<input type=submit name=\"searchx\" value=\"" .
100 wfMsg("powersearch") . "\">\n";
101 $ret = str_replace( "$9", $r9, $ret );
102
103 $ret = "<br><br>\n<form id=\"powersearch\" method=\"get\" " .
104 "action=\"" . wfLocalUrl( "" ) . "\">\n{$ret}\n</form>\n";
105
106 if ( isset ( $searchx ) ) {
107 if ( ! $listredirs ) { $this->doSearchRedirects = false; }
108 }
109 return $ret;
110 }
111
112 function showResults()
113 {
114 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgDisableTextSearch;
115 $fname = "SearchEngine::showResults";
116
117 $search = $_REQUEST['search'];
118
119 $powersearch = $this->powersearch(); /* Need side-effects here? */
120
121 $wgOut->setPageTitle( wfMsg( "searchresults" ) );
122 $q = wfMsg( "searchquery", htmlspecialchars( $this->mUsertext ) );
123 $wgOut->setSubtitle( $q );
124 $wgOut->setArticleFlag( false );
125 $wgOut->setRobotpolicy( "noindex,nofollow" );
126
127 $sk = $wgUser->getSkin();
128 $text = wfMsg( "searchresulttext", $sk->makeKnownLink(
129 wfMsg( "searchhelppage" ), wfMsg( "searchingwikipedia" ) ) );
130 $wgOut->addHTML( $text );
131
132 $this->parseQuery();
133 if ( "" == $this->mTitlecond || "" == $this->mTextcond ) {
134 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
135 "<p>" . wfMsg( "badquerytext" ) );
136 return;
137 }
138 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
139
140 $searchnamespaces = $this->queryNamespaces();
141 $redircond = $this->searchRedirects();
142
143 $sql = "SELECT cur_id,cur_namespace,cur_title," .
144 "cur_text FROM cur,searchindex " .
145 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
146 "AND {$searchnamespaces} {$redircond}" .
147 "LIMIT {$offset}, {$limit}";
148 $res1 = wfQuery( $sql, $fname );
149 $num = wfNumRows($res1);
150
151 if ( $wgDisableTextSearch ) {
152 $res2 = 0;
153 } else {
154 $sql = "SELECT cur_id,cur_namespace,cur_title," .
155 "cur_text FROM cur,searchindex " .
156 "WHERE cur_id=si_page AND {$this->mTextcond} " .
157 "AND {$searchnamespaces} {$redircond} " .
158 "LIMIT {$offset}, {$limit}";
159 $res2 = wfQuery( $sql, $fname );
160 $num = $num + wfNumRows($res2);
161 }
162
163 if ( $num == $limit ) {
164 $top = wfShowingResults( $offset, $limit);
165 } else {
166 $top = wfShowingResultsNum( $offset, $limit, $num );
167 }
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, $wgDBmysql4;
235
236 if( $wgDBmysql4 ) {
237 # Use cleaner boolean search if available
238 return $this->parseQuery4();
239 }
240
241 $lc = SearchEngine::legalSearchChars() . "()";
242 $q = preg_replace( "/([()])/", " \\1 ", $this->mUsertext );
243 $q = preg_replace( "/\\s+/", " ", $q );
244 $w = explode( " ", strtolower( trim( $q ) ) );
245
246 $last = $cond = "";
247 foreach ( $w as $word ) {
248 $word = $wgLang->stripForSearch( $word );
249 if ( "and" == $word || "or" == $word || "not" == $word
250 || "(" == $word || ")" == $word ) {
251 $cond .= " " . strtoupper( $word );
252 $last = "";
253 } else if ( strlen( $word ) < $wgDBminWordLen ) {
254 continue;
255 } else if ( FulltextStoplist::inList( $word ) ) {
256 continue;
257 } else {
258 if ( "" != $last ) { $cond .= " AND"; }
259 $cond .= " (MATCH (##field##) AGAINST ('" .
260 wfStrencode( $word ). "'))";
261 $last = $word;
262 array_push( $this->mSearchterms, "\\b" . $word . "\\b" );
263 }
264 }
265 if ( 0 == count( $this->mSearchterms ) ) { return; }
266
267 $this->mTitlecond = "(" . str_replace( "##field##",
268 "si_title", $cond ) . " )";
269
270 $this->mTextcond = "(" . str_replace( "##field##",
271 "si_text", $cond ) . " AND (cur_is_redirect=0) )";
272 }
273
274 function parseQuery4()
275 {
276 # FIXME: not ready yet! Do not use.
277
278 global $wgLang;
279 $lc = SearchEngine::legalSearchChars();
280 #$q = preg_replace( "/([+-]?)([$lc]+)/e",
281 # "\"$1\" . \$wgLang->stripForSearch(\"$2\")",
282 # $this->mUsertext );
283
284 $q = $this->mUsertext;
285 $qq = wfStrencode( $q );
286 $this->mTitlecond = " MATCH(si_title) AGAINST('$qq' IN BOOLEAN MODE)";
287 $this->mTextcond = " (MATCH(si_text) AGAINST('$qq' IN BOOLEAN MODE) AND cur_is_redirect=0)";
288 }
289
290 function showHit( $row )
291 {
292 global $wgUser, $wgOut;
293
294 $t = Title::makeName( $row->cur_namespace, $row->cur_title );
295 $sk = $wgUser->getSkin();
296
297 $contextlines = $wgUser->getOption( "contextlines" );
298 if ( "" == $contextlines ) { $contextlines = 5; }
299 $contextchars = $wgUser->getOption( "contextchars" );
300 if ( "" == $contextchars ) { $contextchars = 50; }
301
302 $link = $sk->makeKnownLink( $t, "" );
303 $size = str_replace( "$1", strlen( $row->cur_text ), WfMsg( "nbytes" ) );
304 $wgOut->addHTML( "<li>{$link} ({$size})" );
305
306 $lines = explode( "\n", $row->cur_text );
307 $pat1 = "/(.*)(" . implode( "|", $this->mSearchterms ) . ")(.*)/i";
308 $lineno = 0;
309
310 foreach ( $lines as $line ) {
311 if ( 0 == $contextlines ) { break; }
312 --$contextlines;
313 ++$lineno;
314 if ( ! preg_match( $pat1, $line, $m ) ) { continue; }
315
316 $pre = $m[1];
317 if ( 0 == $contextchars ) { $pre = "..."; }
318 else {
319 if ( strlen( $pre ) > $contextchars ) {
320 $pre = "..." . substr( $pre, -$contextchars );
321 }
322 }
323 $pre = wfEscapeHTML( $pre );
324
325 if ( count( $m ) < 3 ) { $post = ""; }
326 else { $post = $m[3]; }
327
328 if ( 0 == $contextchars ) { $post = "..."; }
329 else {
330 if ( strlen( $post ) > $contextchars ) {
331 $post = substr( $post, 0, $contextchars ) . "...";
332 }
333 }
334 $post = wfEscapeHTML( $post );
335 $found = wfEscapeHTML( $m[2] );
336
337 $line = "{$pre}{$found}{$post}";
338 $pat2 = "/(" . implode( "|", $this->mSearchterms ) . ")/i";
339 $line = preg_replace( $pat2,
340 "<font color='red'>\\1</font>", $line );
341
342 $wgOut->addHTML( "<br><small>{$lineno}: {$line}</small>\n" );
343 }
344 $wgOut->addHTML( "</li>\n" );
345 }
346
347 function goResult()
348 {
349 global $wgOut, $wgArticle, $wgTitle;
350 $fname = "SearchEngine::goResult";
351
352 $search = $_REQUEST['search'];
353
354 # First try to go to page as entered
355 #
356 $wgArticle = new Article();
357 $wgTitle = Title::newFromText( $search );
358
359 if ( 0 != $wgArticle->getID() ) {
360 $wgArticle->view();
361 return;
362 }
363
364 # Now try all lower case (i.e. first letter capitalized)
365 #
366 $wgTitle = Title::newFromText( strtolower( $search ) );
367 if ( 0 != $wgArticle->getID() ) {
368 $wgArticle->view();
369 return;
370 }
371
372 # Now try capitalized string
373 #
374 $wgTitle=Title::newFromText( ucwords( strtolower( $search ) ) );
375 if ( 0 != $wgArticle->getID() ) {
376 $wgArticle->view();
377 return;
378 }
379
380 # Now try all upper case
381 #
382 $wgTitle = Title::newFromText( strtoupper( $search ) );
383 if ( 0 != $wgArticle->getID() ) {
384 $wgArticle->view();
385 return;
386 }
387
388 # Try a near match
389 #
390 $this->parseQuery();
391 $sql = "SELECT cur_id,cur_title,cur_namespace,si_page FROM cur,searchindex " .
392 "WHERE cur_id=si_page AND {$this->mTitlecond} ORDER BY cur_namespace LIMIT 1";
393
394 if ( "" != $this->mTitlecond ) {
395 $res = wfQuery( $sql, $fname );
396 }
397 if ( isset( $res ) && 0 != wfNumRows( $res ) ) {
398 $s = wfFetchObject( $res );
399
400 $wgTitle = Title::newFromDBkey( $s->cur_title );
401 $wgTitle->setNamespace( $s->cur_namespace );
402 $wgArticle->view();
403 return;
404 }
405 $wgOut->addHTML( str_replace( "$1",
406 wfLocalUrl( ucfirst($this->mUsertext) . "&action=edit"),
407 wfMsg("nogomatch")) . "\n<p>" );
408 $this->showResults();
409 }
410 }
411