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