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