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