Fixed bug causing warnings. Fixed problem with repeated heavy SQL queries on non...
[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 var $all_titles = false;
13
14 function SearchEngine( $text )
15 {
16 # We display the query, so let's strip it for safety
17 #
18 global $wgDBmysql4;
19 $lc = SearchEngine::legalSearchChars() . "()";
20 if( $wgDBmysql4 ) $lc .= "\"~<>*+-";
21 $this->mUsertext = trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
22 $this->mSearchterms = array();
23 $this->mStrictMatching = true; # Google-style, add '+' on all terms
24 }
25
26 function queryNamespaces()
27 {
28 $namespaces = implode( ",", $this->namespacesToSearch );
29 if ($namespaces == "") {
30 $namespaces = "0";
31 }
32 return "AND cur_namespace IN (" . $namespaces . ")";
33 }
34
35 function searchRedirects()
36 {
37 if ( $this->doSearchRedirects ) {
38 return "";
39 } else {
40 return "AND cur_is_redirect=0 ";
41 }
42 }
43
44 /* private */ function initNamespaceCheckbox( $i )
45 {
46 global $wgUser, $wgNamespacesToBeSearchedDefault;
47
48 if ($wgUser->getID()) {
49 // User is logged in so we retrieve his default namespaces
50 return $wgUser->getOption( "searchNs".$i );
51 } else {
52 // User is not logged in so we give him the global default namespaces
53 return $wgNamespacesToBeSearchedDefault[ $i ];
54 }
55 }
56
57 # Display the "power search" footer. Does not actually perform the search,
58 # that is done by showResults()
59 function powersearch()
60 {
61 global $wgUser, $wgOut, $wgLang, $wgTitle;
62
63 $search = $_REQUEST['search'];
64 $searchx = $_REQUEST['searchx'];
65 $listredirs = $_REQUEST['redirs'];
66
67 $ret = wfMsg("powersearchtext"); # Text to be returned
68 $tempText = ""; # Temporary text, for substitution into $ret
69
70 if( isset( $_REQUEST["searchx"] ) ) {
71 $this->addtoquery["searchx"] = "1";
72 }
73
74 # Do namespace checkboxes
75 $namespaces = $wgLang->getNamespaces();
76 foreach ( $namespaces as $i => $namespace ) {
77 # Skip virtual namespaces
78 if ( $i < 0 ) {
79 continue;
80 }
81
82 $formVar = "ns$i";
83
84 # Initialise checkboxValues, either from defaults or from
85 # a previous invocation
86 if ( !isset( $searchx ) ) {
87 $checkboxValue = $this->initNamespaceCheckbox( $i );
88 } else {
89 $checkboxValue = $_REQUEST[$formVar];
90 }
91
92 $checked = "";
93 if ( $checkboxValue == 1 ) {
94 $checked = " checked";
95 $this->addtoquery["ns{$i}"] = 1;
96 array_push( $this->namespacesToSearch, $i );
97 }
98 $name = str_replace( "_", " ", $namespaces[$i] );
99 if ( "" == $name ) {
100 $name = wfMsg( "blanknamespace" );
101 }
102
103 if ( $tempText !== "" ) {
104 $tempText .= " ";
105 }
106 $tempText .= "<input type=checkbox value=\"1\" name=\"" .
107 "ns{$i}\"{$checked}>{$name}\n";
108 }
109 $ret = str_replace ( "$1", $tempText, $ret );
110
111 # List redirects checkbox
112
113 $checked = "";
114 if ( $listredirs == 1 ) {
115 $this->addtoquery["redirs"] = 1;
116 $checked = " checked";
117 }
118 $tempText = "<input type=checkbox value=1 name=\"redirs\"{$checked}>\n";
119 $ret = str_replace( "$2", $tempText, $ret );
120
121 # Search field
122
123 $tempText = "<input type=text name=\"search\" value=\"" .
124 htmlspecialchars( $search ) ."\" width=80>\n";
125 $ret = str_replace( "$3", $tempText, $ret );
126
127 # Searchx button
128
129 $tempText = "<input type=submit name=\"searchx\" value=\"" .
130 wfMsg("powersearch") . "\">\n";
131 $ret = str_replace( "$9", $tempText, $ret );
132
133 $ret = "<br><br>\n<form id=\"powersearch\" method=\"get\" " .
134 "action=\"" . wfLocalUrl( "" ) . "\">\n{$ret}\n</form>\n";
135
136 if ( isset ( $searchx ) ) {
137 if ( ! $listredirs ) {
138 $this->doSearchRedirects = false;
139 }
140 }
141 return $ret;
142 }
143
144 # Perform the search and construct the results page
145 function showResults()
146 {
147 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgDisableTextSearch;
148 global $wgInputEncoding;
149 $fname = "SearchEngine::showResults";
150
151 $search = $_REQUEST['search'];
152
153 $powersearch = $this->powersearch(); /* Need side-effects here? */
154
155 $wgOut->setPageTitle( wfMsg( "searchresults" ) );
156 $q = wfMsg( "searchquery", htmlspecialchars( $this->mUsertext ) );
157 $wgOut->setSubtitle( $q );
158 $wgOut->setArticleRelated( false );
159 $wgOut->setRobotpolicy( "noindex,nofollow" );
160
161 $sk = $wgUser->getSkin();
162 $header = wfMsg( "searchresulttext", $sk->makeKnownLink(
163 wfMsg( "searchhelppage" ), wfMsg( "searchingwikipedia" ) ) );
164 $wgOut->addHTML( $header );
165
166 $this->parseQuery();
167 if ( "" == $this->mTitlecond || "" == $this->mTextcond ) {
168 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
169 "<p>" . wfMsg( "badquerytext" ) );
170 return;
171 }
172 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
173
174 $searchnamespaces = $this->queryNamespaces();
175 $redircond = $this->searchRedirects();
176
177 if ( $wgDisableTextSearch ) {
178 $wgOut->addHTML( wfMsg( "searchdisabled", htmlspecialchars( $search ), $wgInputEncoding ) );
179 } else {
180 $sql = "SELECT cur_id,cur_namespace,cur_title," .
181 "cur_text FROM cur,searchindex " .
182 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
183 "{$searchnamespaces} {$redircond}" .
184 "LIMIT {$offset}, {$limit}";
185 $res1 = wfQuery( $sql, DB_READ, $fname );
186 $num = wfNumRows($res1);
187
188 $sk = $wgUser->getSkin();
189 $text = "";
190
191 $this->parseQuery();
192 if ( "" == $this->mTitlecond || "" == $this->mTextcond ) {
193 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
194 "<p>" . wfMsg( "badquerytext" ) );
195 return;
196 }
197 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
198
199 $searchnamespaces = $this->queryNamespaces();
200 $redircond = $this->searchRedirects();
201
202 $sql = "SELECT cur_id,cur_namespace,cur_title," .
203 "cur_text FROM cur,searchindex " .
204 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
205 "{$searchnamespaces} {$redircond}" .
206 "LIMIT {$offset}, {$limit}";
207 $res1 = wfQuery( $sql, DB_READ, $fname );
208 $num = wfNumRows($res1);
209
210 $sql = "SELECT cur_id,cur_namespace,cur_title," .
211 "cur_text FROM cur,searchindex " .
212 "WHERE cur_id=si_page AND {$this->mTextcond} " .
213 "{$searchnamespaces} {$redircond} " .
214 "LIMIT {$offset}, {$limit}";
215 $res2 = wfQuery( $sql, DB_READ, $fname );
216 $num = $num + wfNumRows($res2);
217
218 if ( $num == $limit ) {
219 $top = wfShowingResults( $offset, $limit);
220 } else {
221 $top = wfShowingResultsNum( $offset, $limit, $num );
222 }
223 $wgOut->addHTML( "<p>{$top}\n" );
224
225 # For powersearch
226
227 $a2l = "" ;
228 $akk = array_keys( $this->addtoquery ) ;
229 foreach ( $akk AS $ak ) {
230 $a2l .= "&{$ak}={$this->addtoquery[$ak]}" ;
231 }
232
233 $sl = wfViewPrevNext( $offset, $limit, "",
234 "search=" . wfUrlencode( $this->mUsertext ) . $a2l );
235 $wgOut->addHTML( "<br>{$sl}\n" );
236
237 $foundsome = false;
238
239 if ( 0 == wfNumRows( $res1 ) ) {
240 $wgOut->addHTML( "<h2>" . wfMsg( "notitlematches" ) .
241 "</h2>\n" );
242 } else {
243 $foundsome = true;
244 $off = $offset + 1;
245 $wgOut->addHTML( "<h2>" . wfMsg( "titlematches" ) .
246 "</h2>\n<ol start='{$off}'>" );
247
248 while ( $row = wfFetchObject( $res1 ) ) {
249 $this->showHit( $row );
250 }
251 wfFreeResult( $res1 );
252 $wgOut->addHTML( "</ol>\n" );
253 }
254
255 if ( 0 == wfNumRows( $res2 ) ) {
256 $wgOut->addHTML( "<h2>" . wfMsg( "notextmatches" ) .
257 "</h2>\n" );
258 } else {
259 $foundsome = true;
260 $off = $offset + 1;
261 $wgOut->addHTML( "<h2>" . wfMsg( "textmatches" ) . "</h2>\n" .
262 "<ol start='{$off}'>" );
263 while ( $row = wfFetchObject( $res2 ) ) {
264 $this->showHit( $row );
265 }
266 wfFreeResult( $res2 );
267 $wgOut->addHTML( "</ol>\n" );
268 }
269 if ( ! $foundsome ) {
270 $wgOut->addHTML( "<p>" . wfMsg( "nonefound" ) . "\n" );
271 }
272 $wgOut->addHTML( "<p>{$sl}\n" );
273 $wgOut->addHTML( $powersearch );
274 }
275 }
276
277 function legalSearchChars()
278 {
279 $lc = "A-Za-z_'0-9\\x80-\\xFF\\-";
280 return $lc;
281 }
282
283 function parseQuery()
284 {
285 global $wgDBminWordLen, $wgLang, $wgDBmysql4;
286
287 if( $wgDBmysql4 ) {
288 # Use cleaner boolean search if available
289 return $this->parseQuery4();
290 }
291
292 $lc = SearchEngine::legalSearchChars() . "()";
293 $q = preg_replace( "/([()])/", " \\1 ", $this->mUsertext );
294 $q = preg_replace( "/\\s+/", " ", $q );
295 $w = explode( " ", strtolower( trim( $q ) ) );
296
297 $last = $cond = "";
298 foreach ( $w as $word ) {
299 $word = $wgLang->stripForSearch( $word );
300 if ( "and" == $word || "or" == $word || "not" == $word
301 || "(" == $word || ")" == $word ) {
302 $cond .= " " . strtoupper( $word );
303 $last = "";
304 } else if ( strlen( $word ) < $wgDBminWordLen ) {
305 continue;
306 } else if ( FulltextStoplist::inList( $word ) ) {
307 continue;
308 } else {
309 if ( "" != $last ) { $cond .= " AND"; }
310 $cond .= " (MATCH (##field##) AGAINST ('" .
311 wfStrencode( $word ). "'))";
312 $last = $word;
313 array_push( $this->mSearchterms, "\\b" . $word . "\\b" );
314 }
315 }
316 if ( 0 == count( $this->mSearchterms ) ) { return; }
317
318 $this->mTitlecond = "(" . str_replace( "##field##",
319 "si_title", $cond ) . " )";
320
321 $this->mTextcond = "(" . str_replace( "##field##",
322 "si_text", $cond ) . " AND (cur_is_redirect=0) )";
323 }
324
325 function parseQuery4()
326 {
327 global $wgLang;
328 $lc = SearchEngine::legalSearchChars();
329 $searchon = "";
330 $this->mSearchterms = array();
331
332 # FIXME: This doesn't handle parenthetical expressions.
333 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
334 $this->mUsertext, $m, PREG_SET_ORDER ) ) {
335 foreach( $m as $terms ) {
336 if( $searchon !== "" ) $searchon .= " ";
337 if( $this->mStrictMatching && ($terms[1] == "") ) {
338 $terms[1] = "+";
339 }
340 $searchon .= $terms[1] . $wgLang->stripForSearch( $terms[2] );
341 if( $terms[3] ) {
342 $regexp = preg_quote( $terms[3] );
343 if( $terms[4] ) $regexp .= "[0-9A-Za-z_]+";
344 } else {
345 $regexp = preg_quote( str_replace( '"', '', $terms[2] ) );
346 }
347 $this->mSearchterms[] = $regexp;
348 }
349 wfDebug( "Would search with '$searchon'\n" );
350 wfDebug( "Match with /\b" . implode( '\b|\b', $this->mSearchterms ) . "\b/\n" );
351 } else {
352 wfDebug( "Can't understand search query '$this->mUsertext'\n" );
353 }
354
355 $searchon = wfStrencode( $searchon );
356 $this->mTitlecond = " MATCH(si_title) AGAINST('$searchon' IN BOOLEAN MODE)";
357 $this->mTextcond = " (MATCH(si_text) AGAINST('$searchon' IN BOOLEAN MODE) AND cur_is_redirect=0)";
358 }
359
360 function showHit( $row )
361 {
362 global $wgUser, $wgOut;
363
364 $t = Title::makeName( $row->cur_namespace, $row->cur_title );
365 $sk = $wgUser->getSkin();
366
367 $contextlines = $wgUser->getOption( "contextlines" );
368 if ( "" == $contextlines ) { $contextlines = 5; }
369 $contextchars = $wgUser->getOption( "contextchars" );
370 if ( "" == $contextchars ) { $contextchars = 50; }
371
372 $link = $sk->makeKnownLink( $t, "" );
373 $size = wfMsg( "nbytes", strlen( $row->cur_text ) );
374 $wgOut->addHTML( "<li>{$link} ({$size})" );
375
376 $lines = explode( "\n", $row->cur_text );
377 $pat1 = "/(.*)(" . implode( "|", $this->mSearchterms ) . ")(.*)/i";
378 $lineno = 0;
379
380 foreach ( $lines as $line ) {
381 if ( 0 == $contextlines ) { break; }
382 --$contextlines;
383 ++$lineno;
384 if ( ! preg_match( $pat1, $line, $m ) ) { continue; }
385
386 $pre = $m[1];
387 if ( 0 == $contextchars ) { $pre = "..."; }
388 else {
389 if ( strlen( $pre ) > $contextchars ) {
390 $pre = "..." . substr( $pre, -$contextchars );
391 }
392 }
393 $pre = wfEscapeHTML( $pre );
394
395 if ( count( $m ) < 3 ) { $post = ""; }
396 else { $post = $m[3]; }
397
398 if ( 0 == $contextchars ) { $post = "..."; }
399 else {
400 if ( strlen( $post ) > $contextchars ) {
401 $post = substr( $post, 0, $contextchars ) . "...";
402 }
403 }
404 $post = wfEscapeHTML( $post );
405 $found = wfEscapeHTML( $m[2] );
406
407 $line = "{$pre}{$found}{$post}";
408 $pat2 = "/(" . implode( "|", $this->mSearchterms ) . ")/i";
409 $line = preg_replace( $pat2,
410 "<font color='red'>\\1</font>", $line );
411
412 $wgOut->addHTML( "<br><small>{$lineno}: {$line}</small>\n" );
413 }
414 $wgOut->addHTML( "</li>\n" );
415 }
416
417 function goResult()
418 {
419 global $wgOut, $wgDisableTextSearch;
420 $fname = "SearchEngine::goResult";
421
422 $search = $_REQUEST['search'];
423
424 # First try to go to page as entered.
425 #
426 $t = Title::newFromText( $search );
427
428 # If the string cannot be used to create a title
429 if( false == $t ){
430 $this->showResults();
431 return;
432 }
433
434 if ( 0 != $t->getArticleID() ) {
435 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
436 return;
437 }
438
439 # Now try all lower case (i.e. first letter capitalized)
440 #
441 $t = Title::newFromText( strtolower( $search ) );
442 if ( 0 != $t->getArticleID() ) {
443 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
444 return;
445 }
446
447 # Now try capitalized string
448 #
449 $t = Title::newFromText( ucwords( strtolower( $search ) ) );
450 if ( 0 != $t->getArticleID() ) {
451 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
452 return;
453 }
454
455 # Now try all upper case
456 #
457 $t = Title::newFromText( strtoupper( $search ) );
458 if ( 0 != $t->getArticleID() ) {
459 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
460 return;
461 }
462 $wgOut->addHTML( wfMsg("nogomatch",
463 htmlspecialchars( wfLocalUrl( ucfirst($this->mUsertext), "action=edit") ) )
464 . "\n<p>" );
465
466 # Try a fuzzy title search
467 $anyhit = false;
468 global $wgDisableFuzzySearch;
469 if(! $wgDisableFuzzySearch ){
470 foreach( array(NS_MAIN, NS_WP, NS_USER, NS_IMAGE, NS_MEDIAWIKI) as $namespace){
471 $anyhit |= SearchEngine::doFuzzyTitleSearch( $search, $namespace );
472 }
473 }
474 if( ! $anyhit ){
475 $wgOut->addHTML( wfMsg("notitlematches") );
476 }
477 }
478
479 /* static */ function doFuzzyTitleSearch( $search, $namespace ){
480 global $wgLang, $wgOut;
481 $sstr = ucfirst($search);
482 $sstr = str_replace(" ", "_", $sstr);
483 $fuzzymatches = SearchEngine::fuzzyTitles( $sstr, $namespace );
484 $fuzzymatches = array_slice($fuzzymatches, 0, 10);
485 $slen = strlen( $search );
486 $wikitext = "";
487 foreach($fuzzymatches as $res){
488 $t = str_replace("_", " ", $res[1]);
489 $tfull = $wgLang->getNsText( $namespace ) . ":$t|$t";
490 if( $namespace == NS_MAIN )
491 $tfull = "$t";
492 $distance = $res[0];
493 $closeness = (strlen( $search ) - $distance) / strlen( $search );
494 $percent = intval( $closeness * 100 ) . "%";
495 $stars = str_repeat("*", ceil(5 * $closeness) );
496 $wikitext .= "* [[$tfull]] $percent ($stars)\n";
497 }
498 if( $wikitext ){
499 if( $namespace != NS_MAIN )
500 $wikitext = "=== " . $wgLang->getNsText( $namespace ) . " ===\n" . $wikitext;
501 $wgOut->addWikiText( $wikitext );
502 return true;
503 }
504 return false;
505 }
506
507 /* static */ function fuzzyTitles( $sstr, $namespace = NS_MAIN ){
508 $span = 0.10; // weed on title length before doing levenshtein.
509 $tolerance = 0.35; // allowed percentage of erronous characters
510 $slen = strlen($sstr);
511 $tolerance_count = ceil($tolerance * $slen);
512 $spanabs = ceil($slen * (1 + $span)) - $slen;
513 # print "Word: $sstr, len = $slen, range = [$min, $max], tolerance_count = $tolerance_count<BR>\n";
514 $result = array();
515 for( $i=0; $i <= $spanabs; $i++ ){
516 $titles = SearchEngine::getTitlesByLength( $slen + $i, $namespace );
517 if( $i != 0)
518 $titles = array_merge($titles, SearchEngine::getTitlesByLength( $slen - $i, $namespace ) );
519 foreach($titles as $t){
520 $d = levenshtein($sstr, $t);
521 if($d < $tolerance_count)
522 $result[] = array($d, $t);
523 $cnt++;
524 }
525 }
526 usort($result, "SearchEngine_pcmp");
527 return $result;
528 }
529
530 /* static */ function getTitlesByLength($aLength, $aNamespace = 0){
531 global $wgMemc, $wgDBname;
532
533 // to avoid multiple costly SELECTs in case of no memcached
534 if( $this->all_titles ){
535 if( isset( $this->all_titles[$aLength][$aNamespace] ) ){
536 return $this->all_titles[$aLength][$aNamespace];
537 } else {
538 return array();
539 }
540 }
541
542 $mkey = "$wgDBname:titlesbylength:$aLength:$aNamespace";
543 $mkeyts = "$wgDBname:titlesbylength:createtime";
544 $ts = $wgMemc->get( $mkeyts );
545 $result = $wgMemc->get( $mkey );
546
547 if( time() - $ts < 3600 ){
548 // note: in case of insufficient memcached space, we return
549 // an empty list instead of starting to hit the DB.
550 return is_array( $result ) ? $result : array();
551 }
552
553 $wgMemc->set( $mkeyts, time() );
554
555 $res = wfQuery("SELECT cur_title, cur_namespace FROM cur", DB_READ);
556 $titles = array(); // length, ns, [titles]
557 while( $obj = wfFetchObject( $res ) ){
558 $title = $obj->cur_title;
559 $ns = $obj->cur_namespace;
560 $len = strlen( $title );
561 $titles[$len][$ns][] = $title;
562 }
563 foreach($titles as $length => $length_arr){
564 foreach($length_arr as $ns => $title_arr){
565 $mkey = "$wgDBname:titlesbylength:$length:$ns";
566 $wgMemc->set( $mkey, $title_arr, 3600 * 24 );
567 }
568 }
569 $this->all_titles = $titles;
570 if( isset( $titles[$aLength][$aNamespace] ) )
571 return $titles[$aLength][$aNamespace];
572 else
573 return array();
574 }
575 }
576
577 /* private static */ function SearchEngine_pcmp($a, $b){ return $a[0] - $b[0]; }
578
579 ?>