Load balancing enabled in places where it's thought to be reasonably safe
[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 function setupPage() {
147 global $wgOut;
148 $wgOut->setPageTitle( wfMsg( "searchresults" ) );
149 $q = wfMsg( "searchquery", htmlspecialchars( $this->mUsertext ) );
150 $wgOut->setSubtitle( $q );
151 $wgOut->setArticleRelated( false );
152 $wgOut->setRobotpolicy( "noindex,nofollow" );
153 }
154
155 # Perform the search and construct the results page
156 function showResults()
157 {
158 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgRequest;
159 global $wgDisableTextSearch, $wgInputEncoding;
160 global $wgLoadBalancer;
161
162 $wgLoadBalancer->force(-1);
163
164 $fname = "SearchEngine::showResults";
165
166 $search = $wgRequest->getText( 'search' );
167
168 $powersearch = $this->powersearch(); /* Need side-effects here? */
169
170 $this->setupPage();
171
172 $sk = $wgUser->getSkin();
173 $header = wfMsg( "searchresulttext", $sk->makeKnownLink(
174 wfMsg( "searchhelppage" ), wfMsg( "searchingwikipedia" ) ) );
175 $wgOut->addHTML( $header );
176
177 $this->parseQuery();
178 if ( "" == $this->mTitlecond || "" == $this->mTextcond ) {
179 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
180 "<p>" . wfMsg( "badquerytext" ) . "</p>\n" );
181 return;
182 }
183 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
184
185 $searchnamespaces = $this->queryNamespaces();
186 $redircond = $this->searchRedirects();
187
188 if ( $wgDisableTextSearch ) {
189 $wgOut->addHTML( wfMsg( "searchdisabled" ) );
190 $wgOut->addHTML( wfMsg( "googlesearch", htmlspecialchars( $search ), $GLOBALS['wgInputEncoding'] ) );
191 } else {
192 $sql = "SELECT cur_id,cur_namespace,cur_title," .
193 "cur_text FROM cur,searchindex " .
194 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
195 "{$searchnamespaces} {$redircond}" .
196 "LIMIT {$offset}, {$limit}";
197 $res1 = wfQuery( $sql, DB_READ, $fname );
198 $num = wfNumRows($res1);
199
200 $sk = $wgUser->getSkin();
201 $text = "";
202
203 $this->parseQuery();
204 if ( "" == $this->mTitlecond || "" == $this->mTextcond ) {
205 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
206 "<p>" . wfMsg( "badquerytext" ) . "</p>\n" );
207 return;
208 }
209 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
210
211 $searchnamespaces = $this->queryNamespaces();
212 $redircond = $this->searchRedirects();
213
214 $sql = "SELECT cur_id,cur_namespace,cur_title," .
215 "cur_text FROM cur,searchindex " .
216 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
217 "{$searchnamespaces} {$redircond}" .
218 "LIMIT {$offset}, {$limit}";
219 $res1 = wfQuery( $sql, DB_READ, $fname );
220 $num = wfNumRows($res1);
221
222 $sql = "SELECT cur_id,cur_namespace,cur_title," .
223 "cur_text FROM cur,searchindex " .
224 "WHERE cur_id=si_page AND {$this->mTextcond} " .
225 "{$searchnamespaces} {$redircond} " .
226 "LIMIT {$offset}, {$limit}";
227 $res2 = wfQuery( $sql, DB_READ, $fname );
228 $num = $num + wfNumRows($res2);
229
230 if ( $num == $limit ) {
231 $top = wfShowingResults( $offset, $limit);
232 } else {
233 $top = wfShowingResultsNum( $offset, $limit, $num );
234 }
235 $wgOut->addHTML( "<p>{$top}</p>\n" );
236
237 # For powersearch
238
239 $a2l = "" ;
240 $akk = array_keys( $this->addtoquery ) ;
241 foreach ( $akk AS $ak ) {
242 $a2l .= "&{$ak}={$this->addtoquery[$ak]}" ;
243 }
244
245 $sl = wfViewPrevNext( $offset, $limit, "",
246 "search=" . wfUrlencode( $this->mUsertext ) . $a2l );
247 $wgOut->addHTML( "<br />{$sl}\n" );
248
249 $foundsome = false;
250
251 if ( 0 == wfNumRows( $res1 ) ) {
252 $wgOut->addHTML( "<h2>" . wfMsg( "notitlematches" ) .
253 "</h2>\n" );
254 } else {
255 $foundsome = true;
256 $off = $offset + 1;
257 $wgOut->addHTML( "<h2>" . wfMsg( "titlematches" ) .
258 "</h2>\n<ol start='{$off}'>" );
259
260 while ( $row = wfFetchObject( $res1 ) ) {
261 $this->showHit( $row );
262 }
263 wfFreeResult( $res1 );
264 $wgOut->addHTML( "</ol>\n" );
265 }
266
267 if ( 0 == wfNumRows( $res2 ) ) {
268 $wgOut->addHTML( "<h2>" . wfMsg( "notextmatches" ) .
269 "</h2>\n" );
270 } else {
271 $foundsome = true;
272 $off = $offset + 1;
273 $wgOut->addHTML( "<h2>" . wfMsg( "textmatches" ) . "</h2>\n" .
274 "<ol start='{$off}'>" );
275 while ( $row = wfFetchObject( $res2 ) ) {
276 $this->showHit( $row );
277 }
278 wfFreeResult( $res2 );
279 $wgOut->addHTML( "</ol>\n" );
280 }
281 if ( ! $foundsome ) {
282 $wgOut->addHTML( "<p>" . wfMsg( "nonefound" ) . "</p>\n" );
283 }
284 $wgOut->addHTML( "<p>{$sl}</p>\n" );
285 $wgOut->addHTML( $powersearch );
286 }
287 $wgLoadBalancer->force(0);
288 }
289
290 function legalSearchChars()
291 {
292 $lc = "A-Za-z_'0-9\\x80-\\xFF\\-";
293 return $lc;
294 }
295
296 function parseQuery()
297 {
298 global $wgDBminWordLen, $wgLang, $wgDBmysql4;
299
300 if( $wgDBmysql4 ) {
301 # Use cleaner boolean search if available
302 return $this->parseQuery4();
303 }
304 # on non mysql4 database: get list of words we don't want to search for
305 require_once( "FulltextStoplist.php" );
306
307 $lc = SearchEngine::legalSearchChars() . "()";
308 $q = preg_replace( "/([()])/", " \\1 ", $this->mUsertext );
309 $q = preg_replace( "/\\s+/", " ", $q );
310 $w = explode( " ", strtolower( trim( $q ) ) );
311
312 $last = $cond = "";
313 foreach ( $w as $word ) {
314 $word = $wgLang->stripForSearch( $word );
315 if ( "and" == $word || "or" == $word || "not" == $word
316 || "(" == $word || ")" == $word ) {
317 $cond .= " " . strtoupper( $word );
318 $last = "";
319 } else if ( strlen( $word ) < $wgDBminWordLen ) {
320 continue;
321 } else if ( FulltextStoplist::inList( $word ) ) {
322 continue;
323 } else {
324 if ( "" != $last ) { $cond .= " AND"; }
325 $cond .= " (MATCH (##field##) AGAINST ('" .
326 wfStrencode( $word ). "'))";
327 $last = $word;
328 array_push( $this->mSearchterms, "\\b" . $word . "\\b" );
329 }
330 }
331 if ( 0 == count( $this->mSearchterms ) ) { return; }
332
333 $this->mTitlecond = "(" . str_replace( "##field##",
334 "si_title", $cond ) . " )";
335
336 $this->mTextcond = "(" . str_replace( "##field##",
337 "si_text", $cond ) . " AND (cur_is_redirect=0) )";
338 }
339
340 function parseQuery4()
341 {
342 global $wgLang;
343 $lc = SearchEngine::legalSearchChars();
344 $searchon = "";
345 $this->mSearchterms = array();
346
347 # FIXME: This doesn't handle parenthetical expressions.
348 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
349 $this->mUsertext, $m, PREG_SET_ORDER ) ) {
350 foreach( $m as $terms ) {
351 if( $searchon !== "" ) $searchon .= " ";
352 if( $this->mStrictMatching && ($terms[1] == "") ) {
353 $terms[1] = "+";
354 }
355 $searchon .= $terms[1] . $wgLang->stripForSearch( $terms[2] );
356 if( $terms[3] ) {
357 $regexp = preg_quote( $terms[3] );
358 if( $terms[4] ) $regexp .= "[0-9A-Za-z_]+";
359 } else {
360 $regexp = preg_quote( str_replace( '"', '', $terms[2] ) );
361 }
362 $this->mSearchterms[] = $regexp;
363 }
364 wfDebug( "Would search with '$searchon'\n" );
365 wfDebug( "Match with /\b" . implode( '\b|\b', $this->mSearchterms ) . "\b/\n" );
366 } else {
367 wfDebug( "Can't understand search query '$this->mUsertext'\n" );
368 }
369
370 $searchon = wfStrencode( $searchon );
371 $this->mTitlecond = " MATCH(si_title) AGAINST('$searchon' IN BOOLEAN MODE)";
372 $this->mTextcond = " (MATCH(si_text) AGAINST('$searchon' IN BOOLEAN MODE) AND cur_is_redirect=0)";
373 }
374
375 function showHit( $row )
376 {
377 global $wgUser, $wgOut;
378
379 $t = Title::makeName( $row->cur_namespace, $row->cur_title );
380 $sk = $wgUser->getSkin();
381
382 $contextlines = $wgUser->getOption( "contextlines" );
383 if ( "" == $contextlines ) { $contextlines = 5; }
384 $contextchars = $wgUser->getOption( "contextchars" );
385 if ( "" == $contextchars ) { $contextchars = 50; }
386
387 $link = $sk->makeKnownLink( $t, "" );
388 $size = wfMsg( "nbytes", strlen( $row->cur_text ) );
389 $wgOut->addHTML( "<li>{$link} ({$size})" );
390
391 $lines = explode( "\n", $row->cur_text );
392 $pat1 = "/(.*)(" . implode( "|", $this->mSearchterms ) . ")(.*)/i";
393 $lineno = 0;
394
395 foreach ( $lines as $line ) {
396 if ( 0 == $contextlines ) { break; }
397 --$contextlines;
398 ++$lineno;
399 if ( ! preg_match( $pat1, $line, $m ) ) { continue; }
400
401 $pre = $m[1];
402 if ( 0 == $contextchars ) { $pre = "..."; }
403 else {
404 if ( strlen( $pre ) > $contextchars ) {
405 $pre = "..." . substr( $pre, -$contextchars );
406 }
407 }
408 $pre = wfEscapeHTML( $pre );
409
410 if ( count( $m ) < 3 ) { $post = ""; }
411 else { $post = $m[3]; }
412
413 if ( 0 == $contextchars ) { $post = "..."; }
414 else {
415 if ( strlen( $post ) > $contextchars ) {
416 $post = substr( $post, 0, $contextchars ) . "...";
417 }
418 }
419 $post = wfEscapeHTML( $post );
420 $found = wfEscapeHTML( $m[2] );
421
422 $line = "{$pre}{$found}{$post}";
423 $pat2 = "/(" . implode( "|", $this->mSearchterms ) . ")/i";
424 $line = preg_replace( $pat2,
425 "<font color='red'>\\1</font>", $line );
426
427 $wgOut->addHTML( "<br /><small>{$lineno}: {$line}</small>\n" );
428 }
429 $wgOut->addHTML( "</li>\n" );
430 }
431
432 function goResult()
433 {
434 global $wgOut, $wgRequest, $wgGoToEdit;
435 global $wgDisableTextSearch;
436 $fname = "SearchEngine::goResult";
437
438 $search = trim( $wgRequest->getText( "search" ) );
439
440 # Try to go to page as entered.
441 #
442 $t = Title::newFromText( $search );
443
444 # If the string cannot be used to create a title
445 if( false == $t ){
446 $this->showResults();
447 return;
448 }
449
450 # Exact match? No need to look further.
451 if ( $t->getNamespace() == NS_SPECIAL || 0 != $t->getArticleID() ) {
452 $wgOut->redirect( $t->getFullURL() );
453 return;
454 }
455
456 # Now try all lower case (i.e. first letter capitalized)
457 #
458 $t = Title::newFromText( strtolower( $search ) );
459 if ( 0 != $t->getArticleID() ) {
460 $wgOut->redirect( $t->getFullURL() );
461 return;
462 }
463
464 # Now try capitalized string
465 #
466 $t = Title::newFromText( ucwords( strtolower( $search ) ) );
467 if ( 0 != $t->getArticleID() ) {
468 $wgOut->redirect( $t->getFullURL() );
469 return;
470 }
471
472 # Now try all upper case
473 #
474 $t = Title::newFromText( strtoupper( $search ) );
475 if ( 0 != $t->getArticleID() ) {
476 $wgOut->redirect( $t->getFullURL() );
477 return;
478 }
479
480 # Entering an IP address goes to the contributions page
481 if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $search ) ) {
482 $title = Title::makeTitle( NS_SPECIAL, "Contributions" );
483 $wgOut->redirect( $title->getFullUrl( "target=$search" ) );
484 return;
485 }
486
487 # No match, generate an edit URL
488 $t = Title::newFromText( $this->mUsertext );
489
490 # If the feature is enabled, go straight to the edit page
491 if ( $wgGoToEdit ) {
492 $wgOut->redirect( $t->getFullURL( "action=edit" ) );
493 return;
494 }
495
496 if( $t ) {
497 $editurl = $t->escapeLocalURL( "action=edit" );
498 } else {
499 $editurl = ""; # ??
500 }
501 $wgOut->addHTML( "<p>" . wfMsg("nogomatch", $editurl ) . "</p>\n" );
502
503 # Try a fuzzy title search
504 $anyhit = false;
505 global $wgDisableFuzzySearch;
506 if(! $wgDisableFuzzySearch ){
507 foreach( array(NS_MAIN, NS_WP, NS_USER, NS_IMAGE, NS_MEDIAWIKI) as $namespace){
508 $anyhit |= SearchEngine::doFuzzyTitleSearch( $search, $namespace );
509 }
510 }
511
512 if( ! $anyhit ){
513 return $this->showResults();
514 }
515 }
516
517 /* static */ function doFuzzyTitleSearch( $search, $namespace ){
518 global $wgLang, $wgOut;
519
520 $this->setupPage();
521
522 $sstr = ucfirst($search);
523 $sstr = str_replace(" ", "_", $sstr);
524 $fuzzymatches = SearchEngine::fuzzyTitles( $sstr, $namespace );
525 $fuzzymatches = array_slice($fuzzymatches, 0, 10);
526 $slen = strlen( $search );
527 $wikitext = "";
528 foreach($fuzzymatches as $res){
529 $t = str_replace("_", " ", $res[1]);
530 $tfull = $wgLang->getNsText( $namespace ) . ":$t|$t";
531 if( $namespace == NS_MAIN )
532 $tfull = "$t";
533 $distance = $res[0];
534 $closeness = (strlen( $search ) - $distance) / strlen( $search );
535 $percent = intval( $closeness * 100 ) . "%";
536 $stars = str_repeat("*", ceil(5 * $closeness) );
537 $wikitext .= "* [[$tfull]] $percent ($stars)\n";
538 }
539 if( $wikitext ){
540 if( $namespace != NS_MAIN )
541 $wikitext = "=== " . $wgLang->getNsText( $namespace ) . " ===\n" . $wikitext;
542 $wgOut->addWikiText( $wikitext );
543 return true;
544 }
545 return false;
546 }
547
548 /* static */ function fuzzyTitles( $sstr, $namespace = NS_MAIN ){
549 $span = 0.10; // weed on title length before doing levenshtein.
550 $tolerance = 0.35; // allowed percentage of erronous characters
551 $slen = strlen($sstr);
552 $tolerance_count = ceil($tolerance * $slen);
553 $spanabs = ceil($slen * (1 + $span)) - $slen;
554 # print "Word: $sstr, len = $slen, range = [$min, $max], tolerance_count = $tolerance_count<BR>\n";
555 $result = array();
556 $cnt = 0;
557 for( $i=0; $i <= $spanabs; $i++ ){
558 $titles = SearchEngine::getTitlesByLength( $slen + $i, $namespace );
559 if( $i != 0) {
560 $titles = array_merge($titles, SearchEngine::getTitlesByLength( $slen - $i, $namespace ) );
561 }
562 foreach($titles as $t){
563 $d = levenshtein($sstr, $t);
564 if($d < $tolerance_count)
565 $result[] = array($d, $t);
566 $cnt++;
567 }
568 }
569 usort($result, "SearchEngine_pcmp");
570 return $result;
571 }
572
573 /* static */ function getTitlesByLength($aLength, $aNamespace = 0){
574 global $wgMemc, $wgDBname;
575
576 // to avoid multiple costly SELECTs in case of no memcached
577 if( $this->all_titles ){
578 if( isset( $this->all_titles[$aLength][$aNamespace] ) ){
579 return $this->all_titles[$aLength][$aNamespace];
580 } else {
581 return array();
582 }
583 }
584
585 $mkey = "$wgDBname:titlesbylength:$aLength:$aNamespace";
586 $mkeyts = "$wgDBname:titlesbylength:createtime";
587 $ts = $wgMemc->get( $mkeyts );
588 $result = $wgMemc->get( $mkey );
589
590 if( time() - $ts < 3600 ){
591 // note: in case of insufficient memcached space, we return
592 // an empty list instead of starting to hit the DB.
593 return is_array( $result ) ? $result : array();
594 }
595
596 $wgMemc->set( $mkeyts, time() );
597
598 $res = wfQuery("SELECT cur_title, cur_namespace FROM cur", DB_READ);
599 $titles = array(); // length, ns, [titles]
600 while( $obj = wfFetchObject( $res ) ){
601 $title = $obj->cur_title;
602 $ns = $obj->cur_namespace;
603 $len = strlen( $title );
604 $titles[$len][$ns][] = $title;
605 }
606 foreach($titles as $length => $length_arr){
607 foreach($length_arr as $ns => $title_arr){
608 $mkey = "$wgDBname:titlesbylength:$length:$ns";
609 $wgMemc->set( $mkey, $title_arr, 3600 * 24 );
610 }
611 }
612 $this->all_titles = $titles;
613 if( isset( $titles[$aLength][$aNamespace] ) )
614 return $titles[$aLength][$aNamespace];
615 else
616 return array();
617 }
618 }
619
620 /* private static */ function SearchEngine_pcmp($a, $b){ return $a[0] - $b[0]; }
621
622 ?>