Ajax suggestions:
[lhc/web/wiklou.git] / includes / SpecialSearch.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * Run text & title search and display the output
22 * @addtogroup SpecialPage
23 */
24
25 /**
26 * Entry point
27 *
28 * @param $par String: (default '')
29 */
30 function wfSpecialSearch( $par = '' ) {
31 global $wgRequest, $wgUser;
32
33 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $par ) );
34 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
35 if( $wgRequest->getVal( 'fulltext' )
36 || !is_null( $wgRequest->getVal( 'offset' ))
37 || !is_null( $wgRequest->getVal( 'searchx' ))) {
38 $searchPage->showResults( $search, 'search' );
39 } else {
40 $searchPage->goResult( $search );
41 }
42 }
43
44 /**
45 * implements Special:Search - Run text & title search and display the output
46 * @addtogroup SpecialPage
47 */
48 class SpecialSearch {
49
50 /**
51 * Set up basic search parameters from the request and user settings.
52 * Typically you'll pass $wgRequest and $wgUser.
53 *
54 * @param WebRequest $request
55 * @param User $user
56 * @public
57 */
58 function SpecialSearch( &$request, &$user ) {
59 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
60
61 $this->namespaces = $this->powerSearch( $request );
62 if( empty( $this->namespaces ) ) {
63 $this->namespaces = SearchEngine::userNamespaces( $user );
64 }
65
66 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
67 }
68
69 /**
70 * If an exact title match can be found, jump straight ahead to it.
71 * @param string $term
72 * @public
73 */
74 function goResult( $term ) {
75 global $wgOut;
76 global $wgGoToEdit;
77
78 $this->setupPage( $term );
79
80 # Try to go to page as entered.
81 $t = Title::newFromText( $term );
82
83 # If the string cannot be used to create a title
84 if( is_null( $t ) ){
85 return $this->showResults( $term );
86 }
87
88 # If there's an exact or very near match, jump right there.
89 $t = SearchEngine::getNearMatch( $term );
90 if( !is_null( $t ) ) {
91 $wgOut->redirect( $t->getFullURL() );
92 return;
93 }
94
95 # No match, generate an edit URL
96 $t = Title::newFromText( $term );
97 if( ! is_null( $t ) ) {
98 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
99 # If the feature is enabled, go straight to the edit page
100 if ( $wgGoToEdit ) {
101 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
102 return;
103 }
104 }
105 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
106 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
107 } else {
108 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
109 }
110
111 return $this->showResults( $term );
112 }
113
114 /**
115 * @param string $term
116 * @public
117 */
118 function showResults( $term ) {
119 $fname = 'SpecialSearch::showResults';
120 wfProfileIn( $fname );
121 global $wgOut, $wgUser;
122 $sk = $wgUser->getSkin();
123
124 $this->setupPage( $term );
125
126 $wgOut->addWikiMsg( 'searchresulttext' );
127
128 if( '' === trim( $term ) ) {
129 // Empty query -- straight view of search form
130 $wgOut->setSubtitle( '' );
131 $wgOut->addHTML( $this->powerSearchBox( $term ) );
132 $wgOut->addHTML( $this->powerSearchFocus() );
133 wfProfileOut( $fname );
134 return;
135 }
136
137 global $wgDisableTextSearch;
138 if ( $wgDisableTextSearch ) {
139 global $wgForwardSearchUrl;
140 if( $wgForwardSearchUrl ) {
141 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
142 $wgOut->redirect( $url );
143 return;
144 }
145 global $wgInputEncoding;
146 $wgOut->addHTML(
147 Xml::openElement( 'fieldset' ) .
148 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
149 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
150 wfMsg( 'googlesearch',
151 htmlspecialchars( $term ),
152 htmlspecialchars( $wgInputEncoding ),
153 htmlspecialchars( wfMsg( 'searchbutton' ) )
154 ) .
155 Xml::closeElement( 'fieldset' )
156 );
157 wfProfileOut( $fname );
158 return;
159 }
160
161 $wgOut->addHTML( $this->shortDialog( $term ) );
162
163 $search = SearchEngine::create();
164 $search->setLimitOffset( $this->limit, $this->offset );
165 $search->setNamespaces( $this->namespaces );
166 $search->showRedirects = $this->searchRedirects;
167 $rewritten = $search->replacePrefixes($term);
168
169 $titleMatches = $search->searchTitle( $rewritten );
170
171 // Sometimes the search engine knows there are too many hits
172 if ($titleMatches instanceof SearchResultTooMany) {
173 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
174 $wgOut->addHTML( $this->powerSearchBox( $term ) );
175 $wgOut->addHTML( $this->powerSearchFocus() );
176 wfProfileOut( $fname );
177 return;
178 }
179
180 $textMatches = $search->searchText( $rewritten );
181
182 // did you mean... suggestions
183 if($textMatches && $textMatches->hasSuggestion()){
184 $st = SpecialPage::getTitleFor( 'Search' );
185 $stParams = wfArrayToCGI( array(
186 'search' => $textMatches->getSuggestionQuery(),
187 'fulltext' => wfMsg('search')),
188 $this->powerSearchOptions());
189
190 $suggestLink = '<a href="'.$st->escapeLocalURL($stParams).'">'.
191 $textMatches->getSuggestionSnippet().'</a>';
192
193 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
194 }
195
196 // show number of results
197 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
198 + ( $textMatches ? $textMatches->numRows() : 0);
199 $totalNum = 0;
200 if($titleMatches && !is_null($titleMatches->getTotalHits()))
201 $totalNum += $titleMatches->getTotalHits();
202 if($textMatches && !is_null($textMatches->getTotalHits()))
203 $totalNum += $textMatches->getTotalHits();
204 if ( $num > 0 ) {
205 if ( $totalNum > 0 ){
206 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
207 $this->offset+1, $this->offset+$num, $totalNum );
208 } elseif ( $num >= $this->limit ) {
209 $top = wfShowingResults( $this->offset, $this->limit );
210 } else {
211 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
212 }
213 $wgOut->addHTML( "<p>{$top}</p>\n" );
214 }
215
216 // prev/next links
217 if( $num || $this->offset ) {
218 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
219 SpecialPage::getTitleFor( 'Search' ),
220 wfArrayToCGI(
221 $this->powerSearchOptions(),
222 array( 'search' => $term ) ),
223 ($num < $this->limit) );
224 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
225 wfRunHooks( 'SpecialSearchResults', array( $term, $titleMatches, $textMatches ) );
226 } else {
227 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
228 }
229
230 if( $titleMatches ) {
231 if( $titleMatches->numRows() ) {
232 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
233 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
234 } else {
235 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
236 }
237 $titleMatches->free();
238 }
239
240 if( $textMatches ) {
241 // output appropriate heading
242 if( $textMatches->numRows() ) {
243 if($titleMatches)
244 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
245 else // if no title matches the heading is redundant
246 $wgOut->addHTML("<hr/>");
247 } elseif( $num == 0 ) {
248 # Don't show the 'no text matches' if we received title matches
249 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
250 }
251 // show interwiki results if any
252 if( $textMatches->hasInterwikiResults() )
253 $wgOut->addHtml( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
254 // show results
255 if( $textMatches->numRows() )
256 $wgOut->addHTML( $this->showMatches( $textMatches ) );
257
258 $textMatches->free();
259 }
260
261 if ( $num == 0 ) {
262 $wgOut->addWikiMsg( 'nonefound' );
263 }
264 if( $num || $this->offset ) {
265 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
266 }
267 $wgOut->addHTML( $this->powerSearchBox( $term ) );
268 wfProfileOut( $fname );
269 }
270
271 #------------------------------------------------------------------
272 # Private methods below this line
273
274 /**
275 *
276 */
277 function setupPage( $term ) {
278 global $wgOut;
279 if( !empty( $term ) )
280 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
281 $subtitlemsg = ( Title::newFromText( $term ) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
282 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
283 $wgOut->setArticleRelated( false );
284 $wgOut->setRobotpolicy( 'noindex,nofollow' );
285 }
286
287 /**
288 * Extract "power search" namespace settings from the request object,
289 * returning a list of index numbers to search.
290 *
291 * @param WebRequest $request
292 * @return array
293 * @private
294 */
295 function powerSearch( &$request ) {
296 $arr = array();
297 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
298 if( $request->getCheck( 'ns' . $ns ) ) {
299 $arr[] = $ns;
300 }
301 }
302 return $arr;
303 }
304
305 /**
306 * Reconstruct the 'power search' options for links
307 * @return array
308 * @private
309 */
310 function powerSearchOptions() {
311 $opt = array();
312 foreach( $this->namespaces as $n ) {
313 $opt['ns' . $n] = 1;
314 }
315 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
316 return $opt;
317 }
318
319 /**
320 * Show whole set of results
321 *
322 * @param SearchResultSet $matches
323 */
324 function showMatches( &$matches ) {
325 $fname = 'SpecialSearch::showMatches';
326 wfProfileIn( $fname );
327
328 global $wgContLang;
329 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
330
331 $out = "";
332
333 $infoLine = $matches->getInfo();
334 if( !is_null($infoLine) )
335 $out .= "\n<!-- {$infoLine} -->\n";
336
337
338 $off = $this->offset + 1;
339 $out .= "<ul start='{$off}' class='mw-search-results'>\n";
340
341 while( $result = $matches->next() ) {
342 $out .= $this->showHit( $result, $terms );
343 }
344 $out .= "</ul>\n";
345
346 // convert the whole thing to desired language variant
347 global $wgContLang;
348 $out = $wgContLang->convert( $out );
349 wfProfileOut( $fname );
350 return $out;
351 }
352
353 /**
354 * Format a single hit result
355 * @param SearchResult $result
356 * @param array $terms terms to highlight
357 */
358 function showHit( $result, $terms ) {
359 $fname = 'SpecialSearch::showHit';
360 wfProfileIn( $fname );
361 global $wgUser, $wgContLang, $wgLang;
362
363 if( $result->isBrokenTitle() ) {
364 wfProfileOut( $fname );
365 return "<!-- Broken link in search result -->\n";
366 }
367
368 $t = $result->getTitle();
369 $sk = $wgUser->getSkin();
370
371 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
372
373 //If page content is not readable, just return the title.
374 //This is not quite safe, but better than showing excerpts from non-readable pages
375 //Note that hiding the entry entirely would screw up paging.
376 if (!$t->userCanRead()) {
377 return "<li>{$link}</li>\n";
378 }
379
380 // If the page doesn't *exist*... our search index is out of date.
381 // The least confusing at this point is to drop the result.
382 // You may get less results, but... oh well. :P
383 if( $result->isMissingRevision() ) {
384 return "<!-- missing page " .
385 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
386 }
387
388 // format redirects / relevant sections
389 $redirectTitle = $result->getRedirectTitle();
390 $redirectText = $result->getRedirectSnippet($terms);
391 $sectionTitle = $result->getSectionTitle();
392 $sectionText = $result->getSectionSnippet($terms);
393 $redirect = '';
394 if( !is_null($redirectTitle) )
395 $redirect = "<span class='searchalttitle'>"
396 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
397 ."</span>";
398 $section = '';
399 if( !is_null($sectionTitle) )
400 $section = "<span class='searchalttitle'>"
401 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
402 ."</span>";
403
404 // format text extract
405 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
406
407 // format score
408 if( is_null( $result->getScore() ) ) {
409 // Search engine doesn't report scoring info
410 $score = '';
411 } else {
412 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
413 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
414 . ' - ';
415 }
416
417 // format description
418 $byteSize = $result->getByteSize();
419 $wordCount = $result->getWordCount();
420 $timestamp = $result->getTimestamp();
421 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
422 $sk->formatSize( $byteSize ),
423 $wordCount );
424 $date = $wgLang->timeanddate( $timestamp );
425
426 // link to related articles if supported
427 $related = '';
428 if( $result->hasRelated() ){
429 $st = SpecialPage::getTitleFor( 'Search' );
430 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
431 array('search' => wfMsg('searchrelated').':'.$t->getPrefixedText(),
432 'fulltext' => wfMsg('search') ));
433
434 $related = ' -- <a href="'.$st->escapeLocalURL($stParams).'">'.
435 wfMsg('search-relatedarticle').'</a>';
436 }
437
438 // Include a thumbnail for media files...
439 if( $t->getNamespace() == NS_IMAGE ) {
440 $img = wfFindFile( $t );
441 if( $img ) {
442 $thumb = $img->getThumbnail( 120, 120 );
443 if( $thumb ) {
444 $desc = $img->getShortDesc();
445 wfProfileOut( $fname );
446 // Ugly table. :D
447 // Float doesn't seem to interact well with the bullets.
448 // Table messes up vertical alignment of the bullet, but I'm
449 // not sure what more I can do about that. :(
450 return "<li>" .
451 '<table class="searchResultImage">' .
452 '<tr>' .
453 '<td width="120" align="center">' .
454 $thumb->toHtml( array( 'desc-link' => true ) ) .
455 '</td>' .
456 '<td valign="top">' .
457 $link .
458 $extract .
459 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
460 '</td>' .
461 '</tr>' .
462 '</table>' .
463 "</li>\n";
464 }
465 }
466 }
467
468 wfProfileOut( $fname );
469 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
470 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
471 "</li>\n";
472
473 }
474
475 /**
476 * Show results from other wikis
477 *
478 * @param SearchResultSet $matches
479 */
480 function showInterwiki( &$matches, $query ) {
481 $fname = 'SpecialSearch::showInterwiki';
482 wfProfileIn( $fname );
483
484 global $wgContLang;
485 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
486
487 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
488 $off = $this->offset + 1;
489 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
490
491 // work out custom project captions
492 $customCaptions = array();
493 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
494 foreach($customLines as $line){
495 $parts = explode(":",$line,2);
496 if(count($parts) == 2) // validate line
497 $customCaptions[$parts[0]] = $parts[1];
498 }
499
500
501 $prev = null;
502 while( $result = $matches->next() ) {
503 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
504 $prev = $result->getInterwikiPrefix();
505 }
506 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
507 $out .= "</ul></div>\n";
508
509 // convert the whole thing to desired language variant
510 global $wgContLang;
511 $out = $wgContLang->convert( $out );
512 wfProfileOut( $fname );
513 return $out;
514 }
515
516 /**
517 * Show single interwiki link
518 *
519 * @param SearchResult $result
520 * @param string $lastInterwiki
521 * @param array $terms
522 * @param string $query
523 * @param array $customCaptions iw prefix -> caption
524 */
525 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions){
526 $fname = 'SpecialSearch::showInterwikiHit';
527 wfProfileIn( $fname );
528 global $wgUser, $wgContLang, $wgLang;
529
530 if( $result->isBrokenTitle() ) {
531 wfProfileOut( $fname );
532 return "<!-- Broken link in search result -->\n";
533 }
534
535 $t = $result->getTitle();
536 $sk = $wgUser->getSkin();
537
538 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
539
540 // format redirect if any
541 $redirectTitle = $result->getRedirectTitle();
542 $redirectText = $result->getRedirectSnippet($terms);
543 $redirect = '';
544 if( !is_null($redirectTitle) )
545 $redirect = "<span class='searchalttitle'>"
546 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
547 ."</span>";
548
549 $out = "";
550 // display project name
551 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()){
552 if( key_exists($t->getInterwiki(),$customCaptions) )
553 // captions from 'search-interwiki-custom'
554 $caption = $customCaptions[$t->getInterwiki()];
555 else{
556 // default is to show the hostname of the other wiki which might suck
557 // if there are many wikis on one hostname
558 $parsed = parse_url($t->getFullURL());
559 $caption = wfMsg('search-interwiki-default', $parsed['host']);
560 }
561 // "more results" link (special page stuff could be localized, but we might not know target lang)
562 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
563 $searchLink = $sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
564 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
565 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
566 }
567
568 $out .= "<li>{$link} {$redirect}</li>\n";
569 wfProfileOut( $fname );
570 return $out;
571 }
572
573
574 /**
575 * Generates the power search box at bottom of [[Special:Search]]
576 * @param $term string: search term
577 * @return $out string: HTML form
578 */
579 function powerSearchBox( $term ) {
580 global $wgScript;
581
582 $namespaces = '';
583 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
584 $name = str_replace( '_', ' ', $name );
585 if( '' == $name ) {
586 $name = wfMsg( 'blanknamespace' );
587 }
588 $namespaces .= Xml::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
589 Xml::checkLabel( $name, "ns{$ns}", $name, in_array( $ns, $this->namespaces ) ) .
590 Xml::closeElement( 'span' ) . "\n";
591 }
592
593 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1' ) );
594 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
595 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
596
597 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
598 Xml::openElement( 'fieldset' ) .
599 Xml::element( 'legend', array( ), wfMsg( 'powersearch-legend' ) ) .
600 Xml::hidden( 'title', 'Special:Search' ) .
601 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
602 $namespaces, $redirect, $searchField,
603 '', '', '', '', '', # Dummy placeholders
604 $searchButton ) .
605 Xml::closeElement( 'fieldset' ) .
606 Xml::closeElement( 'form' );
607
608 return $out;
609 }
610
611 function powerSearchFocus() {
612 return "<script type='text/javascript'>" .
613 "document.getElementById('powerSearchText').focus();" .
614 "</script>";
615 }
616
617 function shortDialog($term) {
618 global $wgScript;
619
620 $out = Xml::openElement( 'form', array(
621 'id' => 'search',
622 'method' => 'get',
623 'action' => $wgScript
624 ));
625 $out .= Xml::hidden( 'title', 'Special:Search' );
626 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
627 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
628 if( in_array( $ns, $this->namespaces ) ) {
629 $out .= Xml::hidden( "ns{$ns}", '1' );
630 }
631 }
632 $out .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
633 $out .= Xml::closeElement( 'form' );
634
635 return $out;
636 }
637 }