5 /* private */ var $mUsertext, $mSearchterms;
6 /* private */ var $mTitlecond, $mTextcond;
8 var $doSearchRedirects = true;
9 var $addtoquery = array();
10 var $namespacesToSearch = array();
12 var $all_titles = false;
14 function SearchEngine( $text )
16 # We display the query, so let's strip it for safety
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
26 function queryNamespaces()
28 $namespaces = implode( ",", $this->namespacesToSearch
);
29 if ($namespaces == "") {
32 return "AND cur_namespace IN (" . $namespaces . ")";
35 function searchRedirects()
37 if ( $this->doSearchRedirects
) {
40 return "AND cur_is_redirect=0 ";
44 /* private */ function initNamespaceCheckbox( $i )
46 global $wgUser, $wgNamespacesToBeSearchedDefault;
48 if ($wgUser->getID()) {
49 // User is logged in so we retrieve his default namespaces
50 return $wgUser->getOption( "searchNs".$i );
52 // User is not logged in so we give him the global default namespaces
53 return $wgNamespacesToBeSearchedDefault[ $i ];
57 # Display the "power search" footer. Does not actually perform the search,
58 # that is done by showResults()
59 function powersearch()
61 global $wgUser, $wgOut, $wgLang, $wgTitle;
63 $search = $_REQUEST['search'];
64 $searchx = $_REQUEST['searchx'];
65 $listredirs = $_REQUEST['redirs'];
67 $ret = wfMsg("powersearchtext"); # Text to be returned
68 $tempText = ""; # Temporary text, for substitution into $ret
70 if( isset( $_REQUEST["searchx"] ) ) {
71 $this->addtoquery
["searchx"] = "1";
74 # Do namespace checkboxes
75 $namespaces = $wgLang->getNamespaces();
76 foreach ( $namespaces as $i => $namespace ) {
77 # Skip virtual namespaces
84 # Initialise checkboxValues, either from defaults or from
85 # a previous invocation
86 if ( !isset( $searchx ) ) {
87 $checkboxValue = $this->initNamespaceCheckbox( $i );
89 $checkboxValue = $_REQUEST[$formVar];
93 if ( $checkboxValue == 1 ) {
94 $checked = " checked";
95 $this->addtoquery
["ns{$i}"] = 1;
96 array_push( $this->namespacesToSearch
, $i );
98 $name = str_replace( "_", " ", $namespaces[$i] );
100 $name = wfMsg( "blanknamespace" );
103 if ( $tempText !== "" ) {
106 $tempText .= "<input type=checkbox value=\"1\" name=\"" .
107 "ns{$i}\"{$checked}>{$name}\n";
109 $ret = str_replace ( "$1", $tempText, $ret );
111 # List redirects checkbox
114 if ( $listredirs == 1 ) {
115 $this->addtoquery
["redirs"] = 1;
116 $checked = " checked";
118 $tempText = "<input type=checkbox value=1 name=\"redirs\"{$checked}>\n";
119 $ret = str_replace( "$2", $tempText, $ret );
123 $tempText = "<input type=text name=\"search\" value=\"" .
124 htmlspecialchars( $search ) ."\" width=80>\n";
125 $ret = str_replace( "$3", $tempText, $ret );
129 $tempText = "<input type=submit name=\"searchx\" value=\"" .
130 wfMsg("powersearch") . "\">\n";
131 $ret = str_replace( "$9", $tempText, $ret );
133 $ret = "<br><br>\n<form id=\"powersearch\" method=\"get\" " .
134 "action=\"" . wfLocalUrl( "" ) . "\">\n{$ret}\n</form>\n";
136 if ( isset ( $searchx ) ) {
137 if ( ! $listredirs ) {
138 $this->doSearchRedirects
= false;
144 # Perform the search and construct the results page
145 function showResults()
147 global $wgUser, $wgTitle, $wgOut, $wgLang, $wgDisableTextSearch;
148 global $wgInputEncoding;
149 $fname = "SearchEngine::showResults";
151 $search = $_REQUEST['search'];
153 $powersearch = $this->powersearch(); /* Need side-effects here? */
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" );
161 $sk = $wgUser->getSkin();
162 $header = wfMsg( "searchresulttext", $sk->makeKnownLink(
163 wfMsg( "searchhelppage" ), wfMsg( "searchingwikipedia" ) ) );
164 $wgOut->addHTML( $header );
167 if ( "" == $this->mTitlecond ||
"" == $this->mTextcond
) {
168 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
169 "<p>" . wfMsg( "badquerytext" ) );
172 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
174 $searchnamespaces = $this->queryNamespaces();
175 $redircond = $this->searchRedirects();
177 if ( $wgDisableTextSearch ) {
178 $wgOut->addHTML( wfMsg( "searchdisabled", htmlspecialchars( $search ), $wgInputEncoding ) );
180 $sql = "SELECT cur_id,cur_namespace,cur_title," .
181 "cur_text FROM cur,searchindex " .
182 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
183 "{$searchnamespaces} {$redircond}" .
184 "LIMIT {$offset}, {$limit}";
185 $res1 = wfQuery( $sql, DB_READ
, $fname );
186 $num = wfNumRows($res1);
188 $sk = $wgUser->getSkin();
192 if ( "" == $this->mTitlecond ||
"" == $this->mTextcond
) {
193 $wgOut->addHTML( "<h2>" . wfMsg( "badquery" ) . "</h2>\n" .
194 "<p>" . wfMsg( "badquerytext" ) );
197 list( $limit, $offset ) = wfCheckLimits( 20, "searchlimit" );
199 $searchnamespaces = $this->queryNamespaces();
200 $redircond = $this->searchRedirects();
202 $sql = "SELECT cur_id,cur_namespace,cur_title," .
203 "cur_text FROM cur,searchindex " .
204 "WHERE cur_id=si_page AND {$this->mTitlecond} " .
205 "{$searchnamespaces} {$redircond}" .
206 "LIMIT {$offset}, {$limit}";
207 $res1 = wfQuery( $sql, DB_READ
, $fname );
208 $num = wfNumRows($res1);
210 $sql = "SELECT cur_id,cur_namespace,cur_title," .
211 "cur_text FROM cur,searchindex " .
212 "WHERE cur_id=si_page AND {$this->mTextcond} " .
213 "{$searchnamespaces} {$redircond} " .
214 "LIMIT {$offset}, {$limit}";
215 $res2 = wfQuery( $sql, DB_READ
, $fname );
216 $num = $num +
wfNumRows($res2);
218 if ( $num == $limit ) {
219 $top = wfShowingResults( $offset, $limit);
221 $top = wfShowingResultsNum( $offset, $limit, $num );
223 $wgOut->addHTML( "<p>{$top}\n" );
228 $akk = array_keys( $this->addtoquery
) ;
229 foreach ( $akk AS $ak ) {
230 $a2l .= "&{$ak}={$this->addtoquery[$ak]}" ;
233 $sl = wfViewPrevNext( $offset, $limit, "",
234 "search=" . wfUrlencode( $this->mUsertext
) . $a2l );
235 $wgOut->addHTML( "<br>{$sl}\n" );
239 if ( 0 == wfNumRows( $res1 ) ) {
240 $wgOut->addHTML( "<h2>" . wfMsg( "notitlematches" ) .
245 $wgOut->addHTML( "<h2>" . wfMsg( "titlematches" ) .
246 "</h2>\n<ol start='{$off}'>" );
248 while ( $row = wfFetchObject( $res1 ) ) {
249 $this->showHit( $row );
251 wfFreeResult( $res1 );
252 $wgOut->addHTML( "</ol>\n" );
255 if ( 0 == wfNumRows( $res2 ) ) {
256 $wgOut->addHTML( "<h2>" . wfMsg( "notextmatches" ) .
261 $wgOut->addHTML( "<h2>" . wfMsg( "textmatches" ) . "</h2>\n" .
262 "<ol start='{$off}'>" );
263 while ( $row = wfFetchObject( $res2 ) ) {
264 $this->showHit( $row );
266 wfFreeResult( $res2 );
267 $wgOut->addHTML( "</ol>\n" );
269 if ( ! $foundsome ) {
270 $wgOut->addHTML( "<p>" . wfMsg( "nonefound" ) . "\n" );
272 $wgOut->addHTML( "<p>{$sl}\n" );
273 $wgOut->addHTML( $powersearch );
277 function legalSearchChars()
279 $lc = "A-Za-z_'0-9\\x80-\\xFF\\-";
283 function parseQuery()
285 global $wgDBminWordLen, $wgLang, $wgDBmysql4;
288 # Use cleaner boolean search if available
289 return $this->parseQuery4();
292 $lc = SearchEngine
::legalSearchChars() . "()";
293 $q = preg_replace( "/([()])/", " \\1 ", $this->mUsertext
);
294 $q = preg_replace( "/\\s+/", " ", $q );
295 $w = explode( " ", strtolower( trim( $q ) ) );
298 foreach ( $w as $word ) {
299 $word = $wgLang->stripForSearch( $word );
300 if ( "and" == $word ||
"or" == $word ||
"not" == $word
301 ||
"(" == $word ||
")" == $word ) {
302 $cond .= " " . strtoupper( $word );
304 } else if ( strlen( $word ) < $wgDBminWordLen ) {
306 } else if ( FulltextStoplist
::inList( $word ) ) {
309 if ( "" != $last ) { $cond .= " AND"; }
310 $cond .= " (MATCH (##field##) AGAINST ('" .
311 wfStrencode( $word ). "'))";
313 array_push( $this->mSearchterms
, "\\b" . $word . "\\b" );
316 if ( 0 == count( $this->mSearchterms
) ) { return; }
318 $this->mTitlecond
= "(" . str_replace( "##field##",
319 "si_title", $cond ) . " )";
321 $this->mTextcond
= "(" . str_replace( "##field##",
322 "si_text", $cond ) . " AND (cur_is_redirect=0) )";
325 function parseQuery4()
328 $lc = SearchEngine
::legalSearchChars();
330 $this->mSearchterms
= array();
332 # FIXME: This doesn't handle parenthetical expressions.
333 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
334 $this->mUsertext
, $m, PREG_SET_ORDER
) ) {
335 foreach( $m as $terms ) {
336 if( $searchon !== "" ) $searchon .= " ";
337 if( $this->mStrictMatching
&& ($terms[1] == "") ) {
340 $searchon .= $terms[1] . $wgLang->stripForSearch( $terms[2] );
342 $regexp = preg_quote( $terms[3] );
343 if( $terms[4] ) $regexp .= "[0-9A-Za-z_]+";
345 $regexp = preg_quote( str_replace( '"', '', $terms[2] ) );
347 $this->mSearchterms
[] = $regexp;
349 wfDebug( "Would search with '$searchon'\n" );
350 wfDebug( "Match with /\b" . implode( '\b|\b', $this->mSearchterms
) . "\b/\n" );
352 wfDebug( "Can't understand search query '$this->mUsertext'\n" );
355 $searchon = wfStrencode( $searchon );
356 $this->mTitlecond
= " MATCH(si_title) AGAINST('$searchon' IN BOOLEAN MODE)";
357 $this->mTextcond
= " (MATCH(si_text) AGAINST('$searchon' IN BOOLEAN MODE) AND cur_is_redirect=0)";
360 function showHit( $row )
362 global $wgUser, $wgOut;
364 $t = Title
::makeName( $row->cur_namespace
, $row->cur_title
);
365 $sk = $wgUser->getSkin();
367 $contextlines = $wgUser->getOption( "contextlines" );
368 if ( "" == $contextlines ) { $contextlines = 5; }
369 $contextchars = $wgUser->getOption( "contextchars" );
370 if ( "" == $contextchars ) { $contextchars = 50; }
372 $link = $sk->makeKnownLink( $t, "" );
373 $size = wfMsg( "nbytes", strlen( $row->cur_text
) );
374 $wgOut->addHTML( "<li>{$link} ({$size})" );
376 $lines = explode( "\n", $row->cur_text
);
377 $pat1 = "/(.*)(" . implode( "|", $this->mSearchterms
) . ")(.*)/i";
380 foreach ( $lines as $line ) {
381 if ( 0 == $contextlines ) { break; }
384 if ( ! preg_match( $pat1, $line, $m ) ) { continue; }
387 if ( 0 == $contextchars ) { $pre = "..."; }
389 if ( strlen( $pre ) > $contextchars ) {
390 $pre = "..." . substr( $pre, -$contextchars );
393 $pre = wfEscapeHTML( $pre );
395 if ( count( $m ) < 3 ) { $post = ""; }
396 else { $post = $m[3]; }
398 if ( 0 == $contextchars ) { $post = "..."; }
400 if ( strlen( $post ) > $contextchars ) {
401 $post = substr( $post, 0, $contextchars ) . "...";
404 $post = wfEscapeHTML( $post );
405 $found = wfEscapeHTML( $m[2] );
407 $line = "{$pre}{$found}{$post}";
408 $pat2 = "/(" . implode( "|", $this->mSearchterms
) . ")/i";
409 $line = preg_replace( $pat2,
410 "<font color='red'>\\1</font>", $line );
412 $wgOut->addHTML( "<br><small>{$lineno}: {$line}</small>\n" );
414 $wgOut->addHTML( "</li>\n" );
419 global $wgOut, $wgDisableTextSearch;
420 $fname = "SearchEngine::goResult";
422 $search = $_REQUEST['search'];
424 # First try to go to page as entered.
426 $t = Title
::newFromText( $search );
428 # If the string cannot be used to create a title
430 $this->showResults();
434 if ( 0 != $t->getArticleID() ) {
435 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
439 # Now try all lower case (i.e. first letter capitalized)
441 $t = Title
::newFromText( strtolower( $search ) );
442 if ( 0 != $t->getArticleID() ) {
443 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
447 # Now try capitalized string
449 $t = Title
::newFromText( ucwords( strtolower( $search ) ) );
450 if ( 0 != $t->getArticleID() ) {
451 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
455 # Now try all upper case
457 $t = Title
::newFromText( strtoupper( $search ) );
458 if ( 0 != $t->getArticleID() ) {
459 $wgOut->redirect( wfLocalUrl( $t->getPrefixedURL() ) );
462 $wgOut->addHTML( wfMsg("nogomatch",
463 htmlspecialchars( wfLocalUrl( ucfirst($this->mUsertext
), "action=edit") ) )
466 # Try a fuzzy title search
468 global $wgDisableFuzzySearch;
469 if(! $wgDisableFuzzySearch ){
470 foreach( array(NS_MAIN
, NS_WP
, NS_USER
, NS_IMAGE
, NS_MEDIAWIKI
) as $namespace){
471 $anyhit |
= SearchEngine
::doFuzzyTitleSearch( $search, $namespace );
475 $wgOut->addHTML( wfMsg("notitlematches") );
479 /* static */ function doFuzzyTitleSearch( $search, $namespace ){
480 global $wgLang, $wgOut;
481 $sstr = ucfirst($search);
482 $sstr = str_replace(" ", "_", $sstr);
483 $fuzzymatches = SearchEngine
::fuzzyTitles( $sstr, $namespace );
484 $fuzzymatches = array_slice($fuzzymatches, 0, 10);
485 $slen = strlen( $search );
487 foreach($fuzzymatches as $res){
488 $t = str_replace("_", " ", $res[1]);
489 $tfull = $wgLang->getNsText( $namespace ) . ":$t|$t";
490 if( $namespace == NS_MAIN
)
493 $closeness = (strlen( $search ) - $distance) / strlen( $search );
494 $percent = intval( $closeness * 100 ) . "%";
495 $stars = str_repeat("*", ceil(5 * $closeness) );
496 $wikitext .= "* [[$tfull]] $percent ($stars)\n";
499 if( $namespace != NS_MAIN
)
500 $wikitext = "=== " . $wgLang->getNsText( $namespace ) . " ===\n" . $wikitext;
501 $wgOut->addWikiText( $wikitext );
507 /* static */ function fuzzyTitles( $sstr, $namespace = NS_MAIN
){
508 $span = 0.10; // weed on title length before doing levenshtein.
509 $tolerance = 0.35; // allowed percentage of erronous characters
510 $slen = strlen($sstr);
511 $tolerance_count = ceil($tolerance * $slen);
512 $spanabs = ceil($slen * (1 +
$span)) - $slen;
513 # print "Word: $sstr, len = $slen, range = [$min, $max], tolerance_count = $tolerance_count<BR>\n";
515 for( $i=0; $i <= $spanabs; $i++
){
516 $titles = SearchEngine
::getTitlesByLength( $slen +
$i, $namespace );
518 $titles = array_merge($titles, SearchEngine
::getTitlesByLength( $slen - $i, $namespace ) );
519 foreach($titles as $t){
520 $d = levenshtein($sstr, $t);
521 if($d < $tolerance_count)
522 $result[] = array($d, $t);
526 usort($result, "SearchEngine_pcmp");
530 /* static */ function getTitlesByLength($aLength, $aNamespace = 0){
531 global $wgMemc, $wgDBname;
533 // to avoid multiple costly SELECTs in case of no memcached
534 if( $this->all_titles
){
535 if( isset( $this->all_titles
[$aLength][$aNamespace] ) ){
536 return $this->all_titles
[$aLength][$aNamespace];
542 $mkey = "$wgDBname:titlesbylength:$aLength:$aNamespace";
543 $mkeyts = "$wgDBname:titlesbylength:createtime";
544 $ts = $wgMemc->get( $mkeyts );
545 $result = $wgMemc->get( $mkey );
547 if( time() - $ts < 3600 ){
548 // note: in case of insufficient memcached space, we return
549 // an empty list instead of starting to hit the DB.
550 return is_array( $result ) ?
$result : array();
553 $wgMemc->set( $mkeyts, time() );
555 $res = wfQuery("SELECT cur_title, cur_namespace FROM cur", DB_READ
);
556 $titles = array(); // length, ns, [titles]
557 while( $obj = wfFetchObject( $res ) ){
558 $title = $obj->cur_title
;
559 $ns = $obj->cur_namespace
;
560 $len = strlen( $title );
561 $titles[$len][$ns][] = $title;
563 foreach($titles as $length => $length_arr){
564 foreach($length_arr as $ns => $title_arr){
565 $mkey = "$wgDBname:titlesbylength:$length:$ns";
566 $wgMemc->set( $mkey, $title_arr, 3600 * 24 );
569 $this->all_titles
= $titles;
570 if( isset( $titles[$aLength][$aNamespace] ) )
571 return $titles[$aLength][$aNamespace];
577 /* private static */ function SearchEngine_pcmp($a, $b){ return $a[0] - $b[0]; }