Fix parsing of multi-word expressions; by default behave more like google, with requi...
[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 $this->mStrictMatching = true; # Google-style, add '+' on all terms
23 }
24
25 function queryNamespaces()
26 {
27 $namespaces = implode( ",", $this->namespacesToSearch );
28 if ($namespaces == "") {
29 $namespaces = "0";
30 }
31 return "AND cur_namespace IN (" . $namespaces . ")";
32 #return "1";
33 }
34
35 function searchRedirects()
36 {
37 if ( $this->doSearchRedirects ) return "";
38 return "AND cur_is_redirect=0 ";
39 }
40
41 /* private */ function initNamespaceCheckbox( $i )
42 {
43 global $wgUser, $wgNamespacesToBeSearchedDefault;
44
45
46 if ($wgUser->getID()) {
47 // User is logged in so we retrieve his default namespaces
48 return $wgUser->getOption( "searchNs".$i );
49 }
50 else {
51 // User is not logged in so we give him the global default namespaces
52 return $wgNamespacesToBeSearchedDefault[ $i ];
53 }
54 }
55
56 # Display the "power search" footer. Does not actually perform the search,
57 # that is done by showResults()
58 function powersearch()
59 {
60 global $wgUser, $wgOut, $wgLang, $wgTitle;
61
62 $search = $_REQUEST['search'];
63 $searchx = $_REQUEST['searchx'];
64 $listredirs = $_REQUEST['redirs'];
65
66 $ret = wfMsg("powersearchtext"); # Text to be returned
67 $tempText = ""; # Temporary text, for substitution into $ret
68
69 if( isset( $_REQUEST["searchx"] ) ) {
70 $this->addtoquery["searchx"] = "1";
71 }
72
73 # Do namespace checkboxes
74 $namespaces = $wgLang->getNamespaces();
75 foreach ( $namespaces as $i => $namespace ) {
76 # Skip virtual namespaces
77 if ( $i < 0 ) {
78 continue;
79 }
80
81 $formVar = "ns$i";
82
83 # Initialise checkboxValues, either from defaults or from
84 # a previous invocation
85 if ( !isset( $searchx ) ) {
86 $checkboxValue = $this->initNamespaceCheckbox( $i );
87 } else {
88 $checkboxValue = $_REQUEST[$formVar];
89 }
90
91 $checked = "";
92 if ( $checkboxValue == 1 ) {
93 $checked = " checked";
94 $this->addtoquery["ns{$i}"] = 1;
95 array_push( $this->namespacesToSearch, $i );
96 }
97 $name = str_replace( "_", " ", $namespaces[$i] );
98 if ( "" == $name ) {
99 $name = wfMsg( "blanknamespace" );
100 }
101
102 if ( $tempText !== "" ) {
103 $tempText .= " ";
104 }
105 $tempText .= "<input type=checkbox value=\"1\" name=\"" .
106 "ns{$i}\"{$checked}>{$name}\n";
107 }
108 $ret = str_replace ( "$1", $tempText, $ret );
109
110 # List redirects checkbox
111
112 $checked = "";
113 if ( $listredirs == 1 ) {
114 $this->addtoquery["redirs"] = 1;
115 $checked = " checked";
116 }
117 $tempText = "<input type=checkbox value=1 name=\"redirs\"{$checked}>\n";
118 $ret = str_replace( "$2", $tempText, $ret );
119
120 # Search field
121
122 $tempText = "<input type=text name=\"search\" value=\"" .
123 htmlspecialchars( $search ) ."\" width=80>\n";
124 $ret = str_replace( "$3", $tempText, $ret );
125
126 # Searchx button
127
128 $tempText = "<input type=submit name=\"searchx\" value=\"" .
129 wfMsg("powersearch") . "\">\n";
130 $ret = str_replace( "$9", $tempText, $ret );
131
132 $ret = "<br><br>\n<form id=\"powersearch\" method=\"get\" " .
133 "action=\"" . wfLocalUrl( "" ) . "\">\n{$ret}\n</form>\n";
134
135 if ( isset ( $searchx ) ) {
136 if ( ! $listredirs ) {
137 $this->doSearchRedirects = false;
138 }
139 }
140 return $ret;
141 }
142
143 # Perform the search and construct the results page
144 function showResults()
145 {
146 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgDisableTextSearch;
147 global $wgInputEncoding;
148 $fname = "SearchEngine::showResults";
149
150 $search = $_REQUEST['search'];
151
152 $powersearch = $this->powersearch(); /* Need side-effects here? */
153
154 $wgOut->setPageTitle( wfMsg( "searchresults" ) );
155 $q = wfMsg( "searchquery", htmlspecialchars( $this->mUsertext ) );
156 $wgOut->setSubtitle( $q );
157 $wgOut->setArticleFlag( false );
158 $wgOut->setRobotpolicy( "noindex,nofollow" );
159
160 $sk = $wgUser->getSkin();
161 $text = wfMsg( "searchresulttext", $sk->makeKnownLink(
162 wfMsg( "searchhelppage" ), wfMsg( "searchingwikipedia" ) ) );
163 $wgOut->addHTML( $text );
164
165 $this->parseQuery();
166 if ( "" == $this->mTitlecond || "" == $this->mTextcond ) {
167 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
168 "<p>" . wfMsg( "badquerytext" ) );
169 return;
170 }
171 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
172
173 $searchnamespaces = $this->queryNamespaces();
174 $redircond = $this->searchRedirects();
175
176 if ( $wgDisableTextSearch ) {
177 $wgOut->addHTML( wfMsg( "searchdisabled", htmlspecialchars( $search ), $wgInputEncoding ) );
178 } else {
179 $sql = "SELECT cur_id,cur_namespace,cur_title," .
180 "cur_text FROM cur,searchindex " .
181 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
182 "{$searchnamespaces} {$redircond}" .
183 "LIMIT {$offset}, {$limit}";
184 $res1 = wfQuery( $sql, DB_READ, $fname );
185 $num = wfNumRows($res1);
186
187 $sk = $wgUser->getSkin();
188 $text = wfMsg( "searchresulttext", $sk->makeKnownLink(
189 wfMsg( "searchhelppage" ), wfMsg( "searchingwikipedia" ) ) );
190 $wgOut->addHTML( $text );
191
192 $this->parseQuery();
193 if ( "" == $this->mTitlecond || "" == $this->mTextcond ) {
194 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
195 "<p>" . wfMsg( "badquerytext" ) );
196 return;
197 }
198 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
199
200 $searchnamespaces = $this->queryNamespaces();
201 $redircond = $this->searchRedirects();
202
203 $sql = "SELECT cur_id,cur_namespace,cur_title," .
204 "cur_text FROM cur,searchindex " .
205 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
206 "{$searchnamespaces} {$redircond}" .
207 "LIMIT {$offset}, {$limit}";
208 $res1 = wfQuery( $sql, DB_READ, $fname );
209 $num = wfNumRows($res1);
210
211 $sql = "SELECT cur_id,cur_namespace,cur_title," .
212 "cur_text FROM cur,searchindex " .
213 "WHERE cur_id=si_page AND {$this->mTextcond} " .
214 "{$searchnamespaces} {$redircond} " .
215 "LIMIT {$offset}, {$limit}";
216 $res2 = wfQuery( $sql, DB_READ, $fname );
217 $num = $num + wfNumRows($res2);
218
219 if ( $num == $limit ) {
220 $top = wfShowingResults( $offset, $limit);
221 } else {
222 $top = wfShowingResultsNum( $offset, $limit, $num );
223 }
224 $wgOut->addHTML( "<p>{$top}\n" );
225
226 # For powersearch
227
228 $a2l = "" ;
229 $akk = array_keys( $this->addtoquery ) ;
230 foreach ( $akk AS $ak ) {
231 $a2l .= "&{$ak}={$this->addtoquery[$ak]}" ;
232 }
233
234 $sl = wfViewPrevNext( $offset, $limit, "",
235 "search=" . wfUrlencode( $this->mUsertext ) . $a2l );
236 $wgOut->addHTML( "<br>{$sl}\n" );
237
238 $foundsome = false;
239
240 if ( 0 == wfNumRows( $res1 ) ) {
241 $wgOut->addHTML( "<h2>" . wfMsg( "notitlematches" ) .
242 "</h2>\n" );
243 } else {
244 $foundsome = true;
245 $off = $offset + 1;
246 $wgOut->addHTML( "<h2>" . wfMsg( "titlematches" ) .
247 "</h2>\n<ol start='{$off}'>" );
248
249 while ( $row = wfFetchObject( $res1 ) ) {
250 $this->showHit( $row );
251 }
252 wfFreeResult( $res1 );
253 $wgOut->addHTML( "</ol>\n" );
254 }
255
256 if ( 0 == wfNumRows( $res2 ) ) {
257 $wgOut->addHTML( "<h2>" . wfMsg( "notextmatches" ) .
258 "</h2>\n" );
259 } else {
260 $foundsome = true;
261 $off = $offset + 1;
262 $wgOut->addHTML( "<h2>" . wfMsg( "textmatches" ) . "</h2>\n" .
263 "<ol start='{$off}'>" );
264 while ( $row = wfFetchObject( $res2 ) ) {
265 $this->showHit( $row );
266 }
267 wfFreeResult( $res2 );
268 $wgOut->addHTML( "</ol>\n" );
269 }
270 if ( ! $foundsome ) {
271 $wgOut->addHTML( "<p>" . wfMsg( "nonefound" ) . "\n" );
272 }
273 $wgOut->addHTML( "<p>{$sl}\n" );
274 $wgOut->addHTML( $powersearch );
275 }
276 }
277
278 function legalSearchChars()
279 {
280 $lc = "A-Za-z_'0-9\\x80-\\xFF\\-";
281 return $lc;
282 }
283
284 function parseQuery()
285 {
286 global $wgDBminWordLen, $wgLang, $wgDBmysql4;
287
288 if( $wgDBmysql4 ) {
289 # Use cleaner boolean search if available
290 return $this->parseQuery4();
291 }
292
293 $lc = SearchEngine::legalSearchChars() . "()";
294 $q = preg_replace( "/([()])/", " \\1 ", $this->mUsertext );
295 $q = preg_replace( "/\\s+/", " ", $q );
296 $w = explode( " ", strtolower( trim( $q ) ) );
297
298 $last = $cond = "";
299 foreach ( $w as $word ) {
300 $word = $wgLang->stripForSearch( $word );
301 if ( "and" == $word || "or" == $word || "not" == $word
302 || "(" == $word || ")" == $word ) {
303 $cond .= " " . strtoupper( $word );
304 $last = "";
305 } else if ( strlen( $word ) < $wgDBminWordLen ) {
306 continue;
307 } else if ( FulltextStoplist::inList( $word ) ) {
308 continue;
309 } else {
310 if ( "" != $last ) { $cond .= " AND"; }
311 $cond .= " (MATCH (##field##) AGAINST ('" .
312 wfStrencode( $word ). "'))";
313 $last = $word;
314 array_push( $this->mSearchterms, "\\b" . $word . "\\b" );
315 }
316 }
317 if ( 0 == count( $this->mSearchterms ) ) { return; }
318
319 $this->mTitlecond = "(" . str_replace( "##field##",
320 "si_title", $cond ) . " )";
321
322 $this->mTextcond = "(" . str_replace( "##field##",
323 "si_text", $cond ) . " AND (cur_is_redirect=0) )";
324 }
325
326 function parseQuery4()
327 {
328 global $wgLang;
329 $lc = SearchEngine::legalSearchChars();
330 $searchon = "";
331 $this->mSearchterms = array();
332
333 # FIXME: This doesn't handle parenthetical expressions.
334 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
335 $this->mUsertext, $m, PREG_SET_ORDER ) ) {
336 foreach( $m as $terms ) {
337 if( $searchon !== "" ) $searchon .= " ";
338 if( $this->mStrictMatching && ($terms[1] == "") ) {
339 $terms[1] = "+";
340 }
341 $searchon .= $terms[1] . $wgLang->stripForSearch( $terms[2] );
342 if( $terms[3] ) {
343 $regexp = preg_quote( $terms[3] );
344 if( $terms[4] ) $regexp .= "[0-9A-Za-z_]+";
345 } else {
346 $regexp = preg_quote( str_replace( '"', '', $terms[2] ) );
347 }
348 $this->mSearchterms[] = $regexp;
349 }
350 wfDebug( "Would search with '$searchon'\n" );
351 wfDebug( "Match with /\b" . implode( '\b|\b', $this->mSearchterms ) . "\b/\n" );
352 } else {
353 wfDebug( "Can't understand search query '$this->mUsertext'\n" );
354 }
355
356 $searchon = wfStrencode( $searchon );
357 $this->mTitlecond = " MATCH(si_title) AGAINST('$searchon' IN BOOLEAN MODE)";
358 $this->mTextcond = " (MATCH(si_text) AGAINST('$searchon' IN BOOLEAN MODE) AND cur_is_redirect=0)";
359 }
360
361 function showHit( $row )
362 {
363 global $wgUser, $wgOut;
364
365 $t = Title::makeName( $row->cur_namespace, $row->cur_title );
366 $sk = $wgUser->getSkin();
367
368 $contextlines = $wgUser->getOption( "contextlines" );
369 if ( "" == $contextlines ) { $contextlines = 5; }
370 $contextchars = $wgUser->getOption( "contextchars" );
371 if ( "" == $contextchars ) { $contextchars = 50; }
372
373 $link = $sk->makeKnownLink( $t, "" );
374 $size = wfMsg( "nbytes", strlen( $row->cur_text ) );
375 $wgOut->addHTML( "<li>{$link} ({$size})" );
376
377 $lines = explode( "\n", $row->cur_text );
378 $pat1 = "/(.*)(" . implode( "|", $this->mSearchterms ) . ")(.*)/i";
379 $lineno = 0;
380
381 foreach ( $lines as $line ) {
382 if ( 0 == $contextlines ) { break; }
383 --$contextlines;
384 ++$lineno;
385 if ( ! preg_match( $pat1, $line, $m ) ) { continue; }
386
387 $pre = $m[1];
388 if ( 0 == $contextchars ) { $pre = "..."; }
389 else {
390 if ( strlen( $pre ) > $contextchars ) {
391 $pre = "..." . substr( $pre, -$contextchars );
392 }
393 }
394 $pre = wfEscapeHTML( $pre );
395
396 if ( count( $m ) < 3 ) { $post = ""; }
397 else { $post = $m[3]; }
398
399 if ( 0 == $contextchars ) { $post = "..."; }
400 else {
401 if ( strlen( $post ) > $contextchars ) {
402 $post = substr( $post, 0, $contextchars ) . "...";
403 }
404 }
405 $post = wfEscapeHTML( $post );
406 $found = wfEscapeHTML( $m[2] );
407
408 $line = "{$pre}{$found}{$post}";
409 $pat2 = "/(" . implode( "|", $this->mSearchterms ) . ")/i";
410 $line = preg_replace( $pat2,
411 "<font color='red'>\\1</font>", $line );
412
413 $wgOut->addHTML( "<br><small>{$lineno}: {$line}</small>\n" );
414 }
415 $wgOut->addHTML( "</li>\n" );
416 }
417
418 function goResult()
419 {
420 global $wgOut, $wgDisableTextSearch;
421 $fname = "SearchEngine::goResult";
422
423 $search = $_REQUEST['search'];
424
425 # First try to go to page as entered.
426 #
427 $t = Title::newFromText( $search );
428
429 # If the string cannot be used to create a title
430 if( false == $t ){
431 $this->showResults();
432 return;
433 }
434
435 if ( 0 != $t->getArticleID() ) {
436 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
437 return;
438 }
439
440 # Now try all lower case (i.e. first letter capitalized)
441 #
442 $t = Title::newFromText( strtolower( $search ) );
443 if ( 0 != $t->getArticleID() ) {
444 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
445 return;
446 }
447
448 # Now try capitalized string
449 #
450 $t = Title::newFromText( ucwords( strtolower( $search ) ) );
451 if ( 0 != $t->getArticleID() ) {
452 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
453 return;
454 }
455
456 # Now try all upper case
457 #
458 $t = Title::newFromText( strtoupper( $search ) );
459 if ( 0 != $t->getArticleID() ) {
460 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
461 return;
462 }
463
464 # Try a near match
465 #
466 if( !$wgDisableTextSearch ) {
467 $this->parseQuery();
468 $sql = "SELECT cur_id,cur_title,cur_namespace,si_page FROM cur,searchindex " .
469 "WHERE cur_id=si_page AND {$this->mTitlecond} ORDER BY cur_namespace LIMIT 1";
470
471 if ( "" != $this->mTitlecond ) {
472 $res = wfQuery( $sql, DB_READ, $fname );
473 }
474 if ( isset( $res ) && 0 != wfNumRows( $res ) ) {
475 $s = wfFetchObject( $res );
476
477 $t = Title::makeTitle( $s->cur_namespace, $s->cur_title );
478 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
479 return;
480 }
481 }
482 $wgOut->addHTML( wfMsg("nogomatch",
483 htmlspecialchars( wfLocalUrl( ucfirst($this->mUsertext), "action=edit") ) )
484 . "\n<p>" );
485 $this->showResults();
486 }
487 }
488
489 ?>