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