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