Changed how the search UI is rendered.
[lhc/web/wiklou.git] / includes / specials / 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 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * Entry point
28 *
29 * @param $par String: (default '')
30 */
31 function wfSpecialSearch( $par = '' ) {
32 global $wgRequest, $wgUser, $wgUseOldSearchUI;
33 // Strip underscores from title parameter; most of the time we'll want
34 // text form here. But don't strip underscores from actual text params!
35 $titleParam = str_replace( '_', ' ', $par );
36 // Fetch the search term
37 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
38 $class = $wgUseOldSearchUI ? 'SpecialSearchOld' : 'SpecialSearch';
39 $searchPage = new $class( $wgRequest, $wgUser );
40 if( $wgRequest->getVal( 'fulltext' )
41 || !is_null( $wgRequest->getVal( 'offset' ))
42 || !is_null( $wgRequest->getVal( 'searchx' )) )
43 {
44 $searchPage->showResults( $search );
45 } else {
46 $searchPage->goResult( $search );
47 }
48 }
49
50 /**
51 * implements Special:Search - Run text & title search and display the output
52 * @ingroup SpecialPage
53 */
54 class SpecialSearch {
55
56 /**
57 * Set up basic search parameters from the request and user settings.
58 * Typically you'll pass $wgRequest and $wgUser.
59 *
60 * @param WebRequest $request
61 * @param User $user
62 * @public
63 */
64 function __construct( &$request, &$user ) {
65 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
66 $this->mPrefix = $request->getVal('prefix', '');
67 # Extract requested namespaces
68 $this->namespaces = $this->powerSearch( $request );
69 if( empty( $this->namespaces ) ) {
70 $this->namespaces = SearchEngine::userNamespaces( $user );
71 }
72 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
73 $this->searchAdvanced = $request->getVal( 'advanced' );
74 $this->active = 'advanced';
75 $this->sk = $user->getSkin();
76 $this->didYouMeanHtml = ''; # html of did you mean... link
77 $this->fulltext = $request->getVal('fulltext');
78 }
79
80 /**
81 * If an exact title match can be found, jump straight ahead to it.
82 * @param string $term
83 */
84 public function goResult( $term ) {
85 global $wgOut;
86 $this->setupPage( $term );
87 # Try to go to page as entered.
88 $t = Title::newFromText( $term );
89 # If the string cannot be used to create a title
90 if( is_null( $t ) ) {
91 return $this->showResults( $term );
92 }
93 # If there's an exact or very near match, jump right there.
94 $t = SearchEngine::getNearMatch( $term );
95 if( !is_null( $t ) ) {
96 $wgOut->redirect( $t->getFullURL() );
97 return;
98 }
99 # No match, generate an edit URL
100 $t = Title::newFromText( $term );
101 if( !is_null( $t ) ) {
102 global $wgGoToEdit;
103 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
104 # If the feature is enabled, go straight to the edit page
105 if( $wgGoToEdit ) {
106 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
107 return;
108 }
109 }
110 return $this->showResults( $term );
111 }
112
113 /**
114 * @param string $term
115 */
116 public function showResults( $term ) {
117 global $wgOut, $wgUser, $wgDisableTextSearch, $wgContLang, $wgScript;
118 wfProfileIn( __METHOD__ );
119
120 $sk = $wgUser->getSkin();
121
122 $this->searchEngine = SearchEngine::create();
123 $search =& $this->searchEngine;
124 $search->setLimitOffset( $this->limit, $this->offset );
125 $search->setNamespaces( $this->namespaces );
126 $search->showRedirects = $this->searchRedirects;
127 $search->prefix = $this->mPrefix;
128 $term = $search->transformSearchTerm($term);
129
130 $this->setupPage( $term );
131
132 if( $wgDisableTextSearch ) {
133 global $wgSearchForwardUrl;
134 if( $wgSearchForwardUrl ) {
135 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
136 $wgOut->redirect( $url );
137 wfProfileOut( __METHOD__ );
138 return;
139 }
140 global $wgInputEncoding;
141 $wgOut->addHTML(
142 Xml::openElement( 'fieldset' ) .
143 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
144 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
145 wfMsg( 'googlesearch',
146 htmlspecialchars( $term ),
147 htmlspecialchars( $wgInputEncoding ),
148 htmlspecialchars( wfMsg( 'searchbutton' ) )
149 ) .
150 Xml::closeElement( 'fieldset' )
151 );
152 wfProfileOut( __METHOD__ );
153 return;
154 }
155
156 $t = Title::newFromText( $term );
157
158 // fetch search results
159 $rewritten = $search->replacePrefixes($term);
160
161 $titleMatches = $search->searchTitle( $rewritten );
162 if( !($titleMatches instanceof SearchResultTooMany))
163 $textMatches = $search->searchText( $rewritten );
164
165 // did you mean... suggestions
166 if( $textMatches && $textMatches->hasSuggestion() ) {
167 $st = SpecialPage::getTitleFor( 'Search' );
168
169 # mirror Go/Search behaviour of original request ..
170 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
171
172 if($this->fulltext != NULL)
173 $didYouMeanParams['fulltext'] = $this->fulltext;
174
175 $stParams = array_merge(
176 $didYouMeanParams,
177 $this->powerSearchOptions()
178 );
179
180 $suggestionSnippet = $textMatches->getSuggestionSnippet();
181
182 if( $suggestionSnippet == '' )
183 $suggestionSnippet = null;
184
185 $suggestLink = $sk->linkKnown(
186 $st,
187 $suggestionSnippet,
188 array(),
189 $stParams
190 );
191
192 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
193 }
194 // start rendering the page
195 $wgOut->addHtml(
196 Xml::openElement(
197 'form',
198 array(
199 'id' => ( $this->searchAdvanced ? 'powersearch' : 'search' ),
200 'method' => 'get',
201 'action' => $wgScript
202 )
203 )
204 );
205 $wgOut->addHtml(
206 Xml::openElement( 'table', array( 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
207 Xml::openElement( 'tr' ) .
208 Xml::openElement( 'td' ) . "\n" .
209 $this->shortDialog( $term ) .
210 Xml::closeElement('td') .
211 Xml::closeElement('tr') .
212 Xml::closeElement('table')
213 );
214
215 // Sometimes the search engine knows there are too many hits
216 if( $titleMatches instanceof SearchResultTooMany ) {
217 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
218 wfProfileOut( __METHOD__ );
219 return;
220 }
221
222 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
223 if( '' === trim( $term ) || $filePrefix === trim( $term ) ) {
224 $wgOut->addHTML( $this->searchFocus() );
225 $wgOut->addHTML( $this->formHeader($term, 0, 0));
226 if( $this->searchAdvanced ) {
227 $wgOut->addHTML( $this->powerSearchBox( $term ) );
228 }
229 // Empty query -- straight view of search form
230 wfProfileOut( __METHOD__ );
231 return;
232 }
233
234 // Get number of results
235 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
236 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
237 // Total initial query matches (possible false positives)
238 $num = $titleMatchesNum + $textMatchesNum;
239
240 // Get total actual results (after second filtering, if any)
241 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
242 $titleMatches->getTotalHits() : $titleMatchesNum;
243 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
244 $textMatches->getTotalHits() : $textMatchesNum;
245
246 // get total number of results if backend can calculate it
247 $totalRes = 0;
248 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
249 $totalRes += $titleMatches->getTotalHits();
250 if($textMatches && !is_null( $textMatches->getTotalHits() ))
251 $totalRes += $textMatches->getTotalHits();
252
253 // show number of results and current offset
254 $wgOut->addHTML( $this->formHeader($term, $num, $totalRes));
255 if( $this->searchAdvanced ) {
256 $wgOut->addHTML( $this->powerSearchBox( $term ) );
257 }
258
259 $wgOut->addHtml( Xml::closeElement( 'form' ) );
260 $wgOut->addHtml( "<div class='searchresults'>" );
261
262 // show direct page/create link
263 if( !is_null($t) && ($this->active=='default' || $this->active=='all') ) {
264 if( !$t->exists() ) {
265 $wgOut->addWikiMsg( 'searchmenu-new', wfEscapeWikiText( $t->getPrefixedText() ) );
266 } else {
267 $wgOut->addWikiMsg( 'searchmenu-exists', wfEscapeWikiText( $t->getPrefixedText() ) );
268 }
269 }
270
271 // prev/next links
272 if( $num || $this->offset ) {
273 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
274 SpecialPage::getTitleFor( 'Search' ),
275 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
276 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
277 );
278 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
279 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
280 } else {
281 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
282 }
283
284 if( $titleMatches ) {
285 if( $numTitleMatches > 0 ) {
286 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
287 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
288 }
289 $titleMatches->free();
290 }
291 if( $textMatches ) {
292 // output appropriate heading
293 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
294 // if no title matches the heading is redundant
295 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
296 } elseif( $totalRes == 0 ) {
297 # Don't show the 'no text matches' if we received title matches
298 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
299 }
300 // show interwiki results if any
301 if( $textMatches->hasInterwikiResults() ) {
302 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
303 }
304 // show results
305 if( $numTextMatches > 0 ) {
306 $wgOut->addHTML( $this->showMatches( $textMatches ) );
307 }
308
309 $textMatches->free();
310 }
311 if( $num === 0 ) {
312 $wgOut->addWikiMsg( 'search-nonefound' );
313 }
314 $wgOut->addHtml( "</div>" );
315 if( $num === 0 ) {
316 $wgOut->addHTML( $this->searchFocus() );
317 }
318
319 if( $num || $this->offset ) {
320 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
321 }
322 wfProfileOut( __METHOD__ );
323 }
324
325 /**
326 *
327 */
328 protected function setupPage( $term ) {
329 global $wgOut;
330 // Figure out the active search profile header
331 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
332 if( $this->searchAdvanced )
333 $this->active = 'advanced';
334 else if( $this->namespaces === array(NS_FILE) || $this->startsWithImage( $term ) )
335 $this->active = 'images';
336 elseif( $this->namespaces === $nsAllSet || $this->startsWithAll( $term ) )
337 $this->active = 'all';
338 elseif( $this->namespaces === SearchEngine::defaultNamespaces() )
339 $this->active = 'default';
340 elseif( $this->namespaces === SearchEngine::helpNamespaces() )
341 $this->active = 'help';
342 else
343 $this->active = 'advanced';
344 # Should advanced UI be used?
345 $this->searchAdvanced = ($this->active === 'advanced');
346 if( !empty( $term ) ) {
347 $wgOut->setPageTitle( wfMsg( 'searchresults') );
348 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
349 }
350 $wgOut->setArticleRelated( false );
351 $wgOut->setRobotPolicy( 'noindex,nofollow' );
352 // add javascript specific to special:search
353 $wgOut->addScriptFile( 'search.js' );
354 }
355
356 /**
357 * Extract "power search" namespace settings from the request object,
358 * returning a list of index numbers to search.
359 *
360 * @param WebRequest $request
361 * @return array
362 */
363 protected function powerSearch( &$request ) {
364 $arr = array();
365 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
366 if( $request->getCheck( 'ns' . $ns ) ) {
367 $arr[] = $ns;
368 }
369 }
370 return $arr;
371 }
372
373 /**
374 * Reconstruct the 'power search' options for links
375 * @return array
376 */
377 protected function powerSearchOptions() {
378 $opt = array();
379 foreach( $this->namespaces as $n ) {
380 $opt['ns' . $n] = 1;
381 }
382 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
383 if( $this->searchAdvanced ) {
384 $opt['advanced'] = $this->searchAdvanced;
385 }
386 return $opt;
387 }
388
389 /**
390 * Show whole set of results
391 *
392 * @param SearchResultSet $matches
393 */
394 protected function showMatches( &$matches ) {
395 global $wgContLang;
396 wfProfileIn( __METHOD__ );
397
398 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
399
400 $out = "";
401 $infoLine = $matches->getInfo();
402 if( !is_null($infoLine) ) {
403 $out .= "\n<!-- {$infoLine} -->\n";
404 }
405 $off = $this->offset + 1;
406 $out .= "<ul class='mw-search-results'>\n";
407 while( $result = $matches->next() ) {
408 $out .= $this->showHit( $result, $terms );
409 }
410 $out .= "</ul>\n";
411
412 // convert the whole thing to desired language variant
413 $out = $wgContLang->convert( $out );
414 wfProfileOut( __METHOD__ );
415 return $out;
416 }
417
418 /**
419 * Format a single hit result
420 * @param SearchResult $result
421 * @param array $terms terms to highlight
422 */
423 protected function showHit( $result, $terms ) {
424 global $wgContLang, $wgLang, $wgUser;
425 wfProfileIn( __METHOD__ );
426
427 if( $result->isBrokenTitle() ) {
428 wfProfileOut( __METHOD__ );
429 return "<!-- Broken link in search result -->\n";
430 }
431
432 $sk = $wgUser->getSkin();
433 $t = $result->getTitle();
434
435 $titleSnippet = $result->getTitleSnippet($terms);
436
437 if( $titleSnippet == '' )
438 $titleSnippet = null;
439
440 $link = $this->sk->linkKnown(
441 $t,
442 $titleSnippet
443 );
444
445 //If page content is not readable, just return the title.
446 //This is not quite safe, but better than showing excerpts from non-readable pages
447 //Note that hiding the entry entirely would screw up paging.
448 if( !$t->userCanRead() ) {
449 wfProfileOut( __METHOD__ );
450 return "<li>{$link}</li>\n";
451 }
452
453 // If the page doesn't *exist*... our search index is out of date.
454 // The least confusing at this point is to drop the result.
455 // You may get less results, but... oh well. :P
456 if( $result->isMissingRevision() ) {
457 wfProfileOut( __METHOD__ );
458 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
459 }
460
461 // format redirects / relevant sections
462 $redirectTitle = $result->getRedirectTitle();
463 $redirectText = $result->getRedirectSnippet($terms);
464 $sectionTitle = $result->getSectionTitle();
465 $sectionText = $result->getSectionSnippet($terms);
466 $redirect = '';
467
468 if( !is_null($redirectTitle) ) {
469 if( $redirectText == '' )
470 $redirectText = null;
471
472 $redirect = "<span class='searchalttitle'>" .
473 wfMsg(
474 'search-redirect',
475 $this->sk->linkKnown(
476 $redirectTitle,
477 $redirectText
478 )
479 ) .
480 "</span>";
481 }
482
483 $section = '';
484
485
486 if( !is_null($sectionTitle) ) {
487 if( $sectionText == '' )
488 $sectionText = null;
489
490 $section = "<span class='searchalttitle'>" .
491 wfMsg(
492 'search-section', $this->sk->linkKnown(
493 $sectionTitle,
494 $sectionText
495 )
496 ) .
497 "</span>";
498 }
499
500 // format text extract
501 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
502
503 // format score
504 if( is_null( $result->getScore() ) ) {
505 // Search engine doesn't report scoring info
506 $score = '';
507 } else {
508 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
509 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
510 . ' - ';
511 }
512
513 // format description
514 $byteSize = $result->getByteSize();
515 $wordCount = $result->getWordCount();
516 $timestamp = $result->getTimestamp();
517 $size = wfMsgExt(
518 'search-result-size',
519 array( 'parsemag', 'escape' ),
520 $this->sk->formatSize( $byteSize ),
521 $wordCount
522 );
523 $date = $wgLang->timeanddate( $timestamp );
524
525 // link to related articles if supported
526 $related = '';
527 if( $result->hasRelated() ) {
528 $st = SpecialPage::getTitleFor( 'Search' );
529 $stParams = array_merge(
530 $this->powerSearchOptions(),
531 array(
532 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
533 'fulltext' => wfMsg( 'search' )
534 )
535 );
536
537 $related = ' -- ' . $sk->linkKnown(
538 $st,
539 wfMsg('search-relatedarticle'),
540 array(),
541 $stParams
542 );
543 }
544
545 // Include a thumbnail for media files...
546 if( $t->getNamespace() == NS_FILE ) {
547 $img = wfFindFile( $t );
548 if( $img ) {
549 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
550 if( $thumb ) {
551 $desc = $img->getShortDesc();
552 wfProfileOut( __METHOD__ );
553 // Float doesn't seem to interact well with the bullets.
554 // Table messes up vertical alignment of the bullets.
555 // Bullets are therefore disabled (didn't look great anyway).
556 return "<li>" .
557 '<table class="searchResultImage">' .
558 '<tr>' .
559 '<td width="120" align="center" valign="top">' .
560 $thumb->toHtml( array( 'desc-link' => true ) ) .
561 '</td>' .
562 '<td valign="top">' .
563 $link .
564 $extract .
565 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
566 '</td>' .
567 '</tr>' .
568 '</table>' .
569 "</li>\n";
570 }
571 }
572 }
573
574 wfProfileOut( __METHOD__ );
575 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
576 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
577 "</li>\n";
578
579 }
580
581 /**
582 * Show results from other wikis
583 *
584 * @param SearchResultSet $matches
585 */
586 protected function showInterwiki( &$matches, $query ) {
587 global $wgContLang;
588 wfProfileIn( __METHOD__ );
589 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
590
591 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
592 wfMsg('search-interwiki-caption')."</div>\n";
593 $off = $this->offset + 1;
594 $out .= "<ul class='mw-search-iwresults'>\n";
595
596 // work out custom project captions
597 $customCaptions = array();
598 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
599 foreach($customLines as $line) {
600 $parts = explode(":",$line,2);
601 if(count($parts) == 2) // validate line
602 $customCaptions[$parts[0]] = $parts[1];
603 }
604
605 $prev = null;
606 while( $result = $matches->next() ) {
607 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
608 $prev = $result->getInterwikiPrefix();
609 }
610 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
611 $out .= "</ul></div>\n";
612
613 // convert the whole thing to desired language variant
614 $out = $wgContLang->convert( $out );
615 wfProfileOut( __METHOD__ );
616 return $out;
617 }
618
619 /**
620 * Show single interwiki link
621 *
622 * @param SearchResult $result
623 * @param string $lastInterwiki
624 * @param array $terms
625 * @param string $query
626 * @param array $customCaptions iw prefix -> caption
627 */
628 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
629 wfProfileIn( __METHOD__ );
630 global $wgContLang, $wgLang;
631
632 if( $result->isBrokenTitle() ) {
633 wfProfileOut( __METHOD__ );
634 return "<!-- Broken link in search result -->\n";
635 }
636
637 $t = $result->getTitle();
638
639 $titleSnippet = $result->getTitleSnippet($terms);
640
641 if( $titleSnippet == '' )
642 $titleSnippet = null;
643
644 $link = $this->sk->linkKnown(
645 $t,
646 $titleSnippet
647 );
648
649 // format redirect if any
650 $redirectTitle = $result->getRedirectTitle();
651 $redirectText = $result->getRedirectSnippet($terms);
652 $redirect = '';
653 if( !is_null($redirectTitle) ) {
654 if( $redirectText == '' )
655 $redirectText = null;
656
657 $redirect = "<span class='searchalttitle'>" .
658 wfMsg(
659 'search-redirect',
660 $this->sk->linkKnown(
661 $redirectTitle,
662 $redirectText
663 )
664 ) .
665 "</span>";
666 }
667
668 $out = "";
669 // display project name
670 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
671 if( key_exists($t->getInterwiki(),$customCaptions) )
672 // captions from 'search-interwiki-custom'
673 $caption = $customCaptions[$t->getInterwiki()];
674 else{
675 // default is to show the hostname of the other wiki which might suck
676 // if there are many wikis on one hostname
677 $parsed = parse_url($t->getFullURL());
678 $caption = wfMsg('search-interwiki-default', $parsed['host']);
679 }
680 // "more results" link (special page stuff could be localized, but we might not know target lang)
681 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
682 $searchLink = $this->sk->linkKnown(
683 $searchTitle,
684 wfMsg('search-interwiki-more'),
685 array(),
686 array(
687 'search' => $query,
688 'fulltext' => 'Search'
689 )
690 );
691 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
692 {$searchLink}</span>{$caption}</div>\n<ul>";
693 }
694
695 $out .= "<li>{$link} {$redirect}</li>\n";
696 wfProfileOut( __METHOD__ );
697 return $out;
698 }
699
700
701 /**
702 * Generates the power search box at bottom of [[Special:Search]]
703 * @param $term string: search term
704 * @return $out string: HTML form
705 */
706 protected function powerSearchBox( $term ) {
707 global $wgScript, $wgContLang;
708
709 // Groups namespaces into rows according to subject
710 $rows = array();
711 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
712 $subject = MWNamespace::getSubject( $namespace );
713 if( !array_key_exists( $subject, $rows ) ) {
714 $rows[$subject] = "";
715 }
716 $name = str_replace( '_', ' ', $name );
717 if( $name == '' ) {
718 $name = wfMsg( 'blanknamespace' );
719 }
720 $rows[$subject] .=
721 Xml::openElement(
722 'td', array( 'style' => 'white-space: nowrap' )
723 ) .
724 Xml::checkLabel(
725 $name,
726 "ns{$namespace}",
727 "mw-search-ns{$namespace}",
728 in_array( $namespace, $this->namespaces )
729 ) .
730 Xml::closeElement( 'td' );
731 }
732 $rows = array_values( $rows );
733 $numRows = count( $rows );
734
735 // Lays out namespaces in multiple floating two-column tables so they'll
736 // be arranged nicely while still accommodating different screen widths
737 $namespaceTables = '';
738 for( $i = 0; $i < $numRows; $i += 4 ) {
739 $namespaceTables .= Xml::openElement(
740 'table',
741 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
742 );
743 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
744 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
745 }
746 $namespaceTables .= Xml::closeElement( 'table' );
747 }
748 // Show redirects check only if backend supports it
749 $redirects = '';
750 if( $this->searchEngine->acceptListRedirects() ) {
751 $redirects =
752 Xml::check(
753 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' )
754 ) .
755 ' ' .
756 Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
757 }
758 // Return final output
759 return
760 Xml::openElement(
761 'fieldset',
762 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
763 ) .
764 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
765 Xml::element( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
766 Xml::tags(
767 'div',
768 array( 'id' => 'mw-search-togglebox' ),
769 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
770 Xml::element(
771 'input',
772 array(
773 'type'=>'button',
774 'id' => 'mw-search-toggleall',
775 'onclick' => 'mwToggleSearchCheckboxes("all");',
776 'value' => wfMsg( 'powersearch-toggleall' )
777 )
778 ) .
779 Xml::element(
780 'input',
781 array(
782 'type'=>'button',
783 'id' => 'mw-search-togglenone',
784 'onclick' => 'mwToggleSearchCheckboxes("none");',
785 'value' => wfMsg( 'powersearch-togglenone'
786 )
787 )
788 )
789 ) .
790 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
791 $namespaceTables .
792 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
793 $redirects .
794 Xml::hidden( 'title', SpecialPage::getTitleFor( 'Search' )->getPrefixedText() ) .
795 Xml::hidden( 'advanced', $this->searchAdvanced ) .
796 Xml::hidden( 'fulltext', 'Advanced search' ) .
797 Xml::closeElement( 'fieldset' );
798 }
799
800 protected function searchFocus() {
801 global $wgJsMimeType;
802 return "<script type=\"$wgJsMimeType\">" .
803 "hookEvent(\"load\", function() {" .
804 "document.getElementById('searchText').focus();" .
805 "});" .
806 "</script>";
807 }
808
809 protected function formHeader( $term, $resultsShown, $totalNum ) {
810 global $wgContLang, $wgCanonicalNamespaceNames, $wgLang;
811
812 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
813
814 $bareterm = $term;
815 if( $this->startsWithImage( $term ) ) {
816 // Deletes prefixes
817 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
818 }
819 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
820
821 // Builds list of Search Types (profiles)
822 $profiles = array(
823 'default' => array(
824 'message' => 'searchprofile-articles',
825 'tooltip' => 'searchprofile-articles-tooltip',
826 'namespaces' => SearchEngine::defaultNamespaces(),
827 'namespace-messages' => SearchEngine::namespacesAsText(
828 SearchEngine::defaultNamespaces()
829 ),
830 ),
831 'images' => array(
832 'message' => 'searchprofile-images',
833 'tooltip' => 'searchprofile-images-tooltip',
834 'namespaces' => array( NS_FILE ),
835 ),
836 'help' => array(
837 'message' => 'searchprofile-project',
838 'tooltip' => 'searchprofile-project-tooltip',
839 'namespaces' => SearchEngine::helpNamespaces(),
840 'namespace-messages' => SearchEngine::namespacesAsText(
841 SearchEngine::helpNamespaces()
842 ),
843 ),
844 'all' => array(
845 'message' => 'searchprofile-everything',
846 'tooltip' => 'searchprofile-everything-tooltip',
847 'namespaces' => $nsAllSet,
848 ),
849 'advanced' => array(
850 'message' => 'searchprofile-advanced',
851 'tooltip' => 'searchprofile-advanced-tooltip',
852 'namespaces' => $this->namespaces,
853 'parameters' => array( 'advanced' => 1 ),
854 )
855 );
856 // Outputs XML for Search Types
857 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
858 $out .= Xml::openElement( 'ul' );
859 foreach ( $profiles as $id => $profile ) {
860 $tooltipParam = isset( $profile['namespace-messages'] ) ?
861 $wgLang->commaList( $profile['namespace-messages'] ) : null;
862 $out .= Xml::tags(
863 'li',
864 array(
865 'class' => $this->active == $id ? 'current' : 'normal'
866 ),
867 $this->makeSearchLink(
868 $bareterm,
869 $profile['namespaces'],
870 wfMsg( $profile['message'] ),
871 wfMsg( $profile['tooltip'], $tooltipParam ),
872 isset( $profile['parameters'] ) ? $profile['parameters'] : array()
873 )
874 );
875 }
876 $out .= Xml::closeElement( 'ul' );
877 $out .= Xml::closeElement('div') ;
878
879 // Results-info
880 if ( $resultsShown > 0 ) {
881 if ( $totalNum > 0 ){
882 $top = wfMsgExt('showingresultsheader', array( 'parseinline' ),
883 $this->offset+1, $this->offset+$resultsShown, $totalNum, $term, $resultsShown );
884 } elseif ( $resultsShown >= $this->limit ) {
885 $top = wfShowingResults( $this->offset, $this->limit );
886 } else {
887 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
888 }
889 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
890 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
891 );
892 }
893
894 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
895 $out .= Xml::closeElement('div');
896
897 // Adds hidden namespace fields
898 if ( !$this->searchAdvanced ) {
899 foreach( $this->namespaces as $ns ) {
900 $out .= Xml::hidden( "ns{$ns}", '1' );
901 }
902 }
903
904 return $out;
905 }
906
907 protected function shortDialog( $term ) {
908 $searchTitle = SpecialPage::getTitleFor( 'Search' );
909 $searchable = SearchEngine::searchableNamespaces();
910 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
911 // Keep redirect setting
912 $out .= Xml::hidden( "redirs", (int)$this->searchRedirects );
913 // Term box
914 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . "\n";
915 $out .= Xml::hidden( 'fulltext', 'Search' );
916 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
917 return $out . $this->didYouMeanHtml;
918 }
919
920 /** Make a search link with some target namespaces */
921 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
922 $opt = $params;
923 foreach( $namespaces as $n ) {
924 $opt['ns' . $n] = 1;
925 }
926 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
927
928 $st = SpecialPage::getTitleFor( 'Search' );
929 $stParams = array_merge(
930 array(
931 'search' => $term,
932 'fulltext' => wfMsg( 'search' )
933 ),
934 $opt
935 );
936
937 return Xml::element(
938 'a',
939 array(
940 'href' => $st->getLocalURL( $stParams ),
941 'title' => $tooltip,
942 'onmousedown' => 'mwSearchHeaderClick(this);',
943 'onkeydown' => 'mwSearchHeaderClick(this);'),
944 $label
945 );
946 }
947
948 /** Check if query starts with image: prefix */
949 protected function startsWithImage( $term ) {
950 global $wgContLang;
951
952 $p = explode( ':', $term );
953 if( count( $p ) > 1 ) {
954 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
955 }
956 return false;
957 }
958
959 /** Check if query starts with all: prefix */
960 protected function startsWithAll( $term ) {
961
962 $allkeyword = wfMsgForContent('searchall');
963
964 $p = explode( ':', $term );
965 if( count( $p ) > 1 ) {
966 return $p[0] == $allkeyword;
967 }
968 return false;
969 }
970 }
971
972 /**
973 * implements Special:Search - Run text & title search and display the output
974 * @ingroup SpecialPage
975 */
976 class SpecialSearchOld {
977
978 /**
979 * Set up basic search parameters from the request and user settings.
980 * Typically you'll pass $wgRequest and $wgUser.
981 *
982 * @param WebRequest $request
983 * @param User $user
984 * @public
985 */
986 function __construct( &$request, &$user ) {
987 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
988 $this->mPrefix = $request->getVal('prefix', '');
989 $this->namespaces = $this->powerSearch( $request );
990 if( empty( $this->namespaces ) ) {
991 $this->namespaces = SearchEngine::userNamespaces( $user );
992 }
993
994 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
995 $this->fulltext = $request->getVal('fulltext');
996 }
997
998 /**
999 * If an exact title match can be found, jump straight ahead to it.
1000 * @param string $term
1001 * @public
1002 */
1003 function goResult( $term ) {
1004 global $wgOut;
1005 global $wgGoToEdit;
1006
1007 $this->setupPage( $term );
1008
1009 # Try to go to page as entered.
1010 $t = Title::newFromText( $term );
1011
1012 # If the string cannot be used to create a title
1013 if( is_null( $t ) ){
1014 return $this->showResults( $term );
1015 }
1016
1017 # If there's an exact or very near match, jump right there.
1018 $t = SearchEngine::getNearMatch( $term );
1019 if( !is_null( $t ) ) {
1020 $wgOut->redirect( $t->getFullURL() );
1021 return;
1022 }
1023
1024 # No match, generate an edit URL
1025 $t = Title::newFromText( $term );
1026 if( ! is_null( $t ) ) {
1027 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
1028 # If the feature is enabled, go straight to the edit page
1029 if ( $wgGoToEdit ) {
1030 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
1031 return;
1032 }
1033 }
1034
1035 $extra = $wgOut->parse( '=='.wfMsgNoTrans( 'notitlematches' )."==\n" );
1036 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
1037 $extra .= wfMsgExt( 'noexactmatch', 'parse', wfEscapeWikiText( $term ) );
1038 } else {
1039 $extra .= wfMsgExt( 'noexactmatch-nocreate', 'parse', wfEscapeWikiText( $term ) );
1040 }
1041
1042 $this->showResults( $term, $extra );
1043 }
1044
1045 /**
1046 * @param string $term
1047 * @param string $extra Extra HTML to add after "did you mean"
1048 */
1049 public function showResults( $term, $extra = '' ) {
1050 wfProfileIn( __METHOD__ );
1051 global $wgOut, $wgUser;
1052 $sk = $wgUser->getSkin();
1053
1054 $search = SearchEngine::create();
1055 $search->setLimitOffset( $this->limit, $this->offset );
1056 $search->setNamespaces( $this->namespaces );
1057 $search->showRedirects = $this->searchRedirects;
1058 $search->prefix = $this->mPrefix;
1059 $term = $search->transformSearchTerm($term);
1060
1061 $this->setupPage( $term );
1062
1063 $rewritten = $search->replacePrefixes($term);
1064 $titleMatches = $search->searchTitle( $rewritten );
1065 $textMatches = $search->searchText( $rewritten );
1066
1067 // did you mean... suggestions
1068 if($textMatches && $textMatches->hasSuggestion()){
1069 $st = SpecialPage::getTitleFor( 'Search' );
1070
1071 # mirror Go/Search behaviour of original request
1072 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
1073 if($this->fulltext != NULL)
1074 $didYouMeanParams['fulltext'] = $this->fulltext;
1075 $stParams = array_merge(
1076 $didYouMeanParams,
1077 $this->powerSearchOptions()
1078 );
1079
1080 $suggestionSnippet = $textMatches->getSuggestionSnippet();
1081
1082 if( $suggestionSnippet )
1083 $suggestionSnippet = null;
1084
1085 $suggestLink = $sk->linkKnown(
1086 $st,
1087 $suggestionSnippet,
1088 array(),
1089 $stParams
1090 );
1091
1092 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
1093 }
1094
1095 $wgOut->addHTML( $extra );
1096
1097 $wgOut->wrapWikiMsg( "<div class='mw-searchresult'>\n$1</div>", 'searchresulttext' );
1098
1099 if( '' === trim( $term ) ) {
1100 // Empty query -- straight view of search form
1101 $wgOut->setSubtitle( '' );
1102 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1103 $wgOut->addHTML( $this->powerSearchFocus() );
1104 wfProfileOut( __METHOD__ );
1105 return;
1106 }
1107
1108 global $wgDisableTextSearch;
1109 if ( $wgDisableTextSearch ) {
1110 global $wgSearchForwardUrl;
1111 if( $wgSearchForwardUrl ) {
1112 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
1113 $wgOut->redirect( $url );
1114 wfProfileOut( __METHOD__ );
1115 return;
1116 }
1117 global $wgInputEncoding;
1118 $wgOut->addHTML(
1119 Xml::openElement( 'fieldset' ) .
1120 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
1121 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
1122 wfMsg( 'googlesearch',
1123 htmlspecialchars( $term ),
1124 htmlspecialchars( $wgInputEncoding ),
1125 htmlspecialchars( wfMsg( 'searchbutton' ) )
1126 ) .
1127 Xml::closeElement( 'fieldset' )
1128 );
1129 wfProfileOut( __METHOD__ );
1130 return;
1131 }
1132
1133 $wgOut->addHTML( $this->shortDialog( $term ) );
1134
1135 // Sometimes the search engine knows there are too many hits
1136 if ($titleMatches instanceof SearchResultTooMany) {
1137 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
1138 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1139 $wgOut->addHTML( $this->powerSearchFocus() );
1140 wfProfileOut( __METHOD__ );
1141 return;
1142 }
1143
1144 // show number of results
1145 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
1146 + ( $textMatches ? $textMatches->numRows() : 0);
1147 $totalNum = 0;
1148 if($titleMatches && !is_null($titleMatches->getTotalHits()))
1149 $totalNum += $titleMatches->getTotalHits();
1150 if($textMatches && !is_null($textMatches->getTotalHits()))
1151 $totalNum += $textMatches->getTotalHits();
1152 if ( $num > 0 ) {
1153 if ( $totalNum > 0 ){
1154 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
1155 $this->offset+1, $this->offset+$num, $totalNum, $num );
1156 } elseif ( $num >= $this->limit ) {
1157 $top = wfShowingResults( $this->offset, $this->limit );
1158 } else {
1159 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
1160 }
1161 $wgOut->addHTML( "<p class='mw-search-numberresults'>{$top}</p>\n" );
1162 }
1163
1164 // prev/next links
1165 if( $num || $this->offset ) {
1166 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
1167 SpecialPage::getTitleFor( 'Search' ),
1168 wfArrayToCGI(
1169 $this->powerSearchOptions(),
1170 array( 'search' => $term ) ),
1171 ($num < $this->limit) );
1172 $wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
1173 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
1174 } else {
1175 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
1176 }
1177
1178 if( $titleMatches ) {
1179 if( $titleMatches->numRows() ) {
1180 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
1181 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
1182 }
1183 $titleMatches->free();
1184 }
1185
1186 if( $textMatches ) {
1187 // output appropriate heading
1188 if( $textMatches->numRows() ) {
1189 if($titleMatches)
1190 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
1191 else // if no title matches the heading is redundant
1192 $wgOut->addHTML("<hr/>");
1193 } elseif( $num == 0 ) {
1194 # Don't show the 'no text matches' if we received title matches
1195 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
1196 }
1197 // show interwiki results if any
1198 if( $textMatches->hasInterwikiResults() )
1199 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
1200 // show results
1201 if( $textMatches->numRows() )
1202 $wgOut->addHTML( $this->showMatches( $textMatches ) );
1203
1204 $textMatches->free();
1205 }
1206
1207 if ( $num == 0 ) {
1208 $wgOut->addWikiMsg( 'nonefound' );
1209 }
1210 if( $num || $this->offset ) {
1211 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
1212 }
1213 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1214 wfProfileOut( __METHOD__ );
1215 }
1216
1217 #------------------------------------------------------------------
1218 # Private methods below this line
1219
1220 /**
1221 *
1222 */
1223 function setupPage( $term ) {
1224 global $wgOut;
1225 if( !empty( $term ) ){
1226 $wgOut->setPageTitle( wfMsg( 'searchresults') );
1227 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term) ) );
1228 }
1229 $subtitlemsg = ( Title::newFromText( $term ) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
1230 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
1231 $wgOut->setArticleRelated( false );
1232 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1233 }
1234
1235 /**
1236 * Extract "power search" namespace settings from the request object,
1237 * returning a list of index numbers to search.
1238 *
1239 * @param WebRequest $request
1240 * @return array
1241 * @private
1242 */
1243 function powerSearch( &$request ) {
1244 $arr = array();
1245 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1246 if( $request->getCheck( 'ns' . $ns ) ) {
1247 $arr[] = $ns;
1248 }
1249 }
1250 return $arr;
1251 }
1252
1253 /**
1254 * Reconstruct the 'power search' options for links
1255 * @return array
1256 * @private
1257 */
1258 function powerSearchOptions() {
1259 $opt = array();
1260 foreach( $this->namespaces as $n ) {
1261 $opt['ns' . $n] = 1;
1262 }
1263 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
1264 return $opt;
1265 }
1266
1267 /**
1268 * Show whole set of results
1269 *
1270 * @param SearchResultSet $matches
1271 */
1272 function showMatches( &$matches ) {
1273 wfProfileIn( __METHOD__ );
1274
1275 global $wgContLang;
1276 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1277
1278 $out = "";
1279
1280 $infoLine = $matches->getInfo();
1281 if( !is_null($infoLine) )
1282 $out .= "\n<!-- {$infoLine} -->\n";
1283
1284
1285 $off = $this->offset + 1;
1286 $out .= "<ul class='mw-search-results'>\n";
1287
1288 while( $result = $matches->next() ) {
1289 $out .= $this->showHit( $result, $terms );
1290 }
1291 $out .= "</ul>\n";
1292
1293 // convert the whole thing to desired language variant
1294 global $wgContLang;
1295 $out = $wgContLang->convert( $out );
1296 wfProfileOut( __METHOD__ );
1297 return $out;
1298 }
1299
1300 /**
1301 * Format a single hit result
1302 * @param SearchResult $result
1303 * @param array $terms terms to highlight
1304 */
1305 function showHit( $result, $terms ) {
1306 wfProfileIn( __METHOD__ );
1307 global $wgUser, $wgContLang, $wgLang;
1308
1309 if( $result->isBrokenTitle() ) {
1310 wfProfileOut( __METHOD__ );
1311 return "<!-- Broken link in search result -->\n";
1312 }
1313
1314 $t = $result->getTitle();
1315 $sk = $wgUser->getSkin();
1316
1317 $titleSnippet = $result->getTitleSnippet($terms);
1318
1319 if( $titleSnippet == '' )
1320 $titleSnippet = null;
1321
1322 $link = $sk->linkKnown(
1323 $t,
1324 $titleSnippet
1325 );
1326
1327 //If page content is not readable, just return the title.
1328 //This is not quite safe, but better than showing excerpts from non-readable pages
1329 //Note that hiding the entry entirely would screw up paging.
1330 if (!$t->userCanRead()) {
1331 wfProfileOut( __METHOD__ );
1332 return "<li>{$link}</li>\n";
1333 }
1334
1335 // If the page doesn't *exist*... our search index is out of date.
1336 // The least confusing at this point is to drop the result.
1337 // You may get less results, but... oh well. :P
1338 if( $result->isMissingRevision() ) {
1339 wfProfileOut( __METHOD__ );
1340 return "<!-- missing page " .
1341 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
1342 }
1343
1344 // format redirects / relevant sections
1345 $redirectTitle = $result->getRedirectTitle();
1346 $redirectText = $result->getRedirectSnippet($terms);
1347 $sectionTitle = $result->getSectionTitle();
1348 $sectionText = $result->getSectionSnippet($terms);
1349 $redirect = '';
1350 if( !is_null($redirectTitle) ) {
1351 if( $redirectText == '' )
1352 $redirectText = null;
1353
1354 $redirect = "<span class='searchalttitle'>" .
1355 wfMsg(
1356 'search-redirect',
1357 $sk->linkKnown(
1358 $redirectTitle,
1359 $redirectText
1360 )
1361 ) .
1362 "</span>";
1363 }
1364
1365 $section = '';
1366
1367 if( !is_null($sectionTitle) ) {
1368 if( $sectionText == '' )
1369 $sectionText = null;
1370
1371 $section = "<span class='searchalttitle'>" .
1372 wfMsg(
1373 'search-section',
1374 $sk->linkKnown(
1375 $sectionTitle,
1376 $sectionText
1377 )
1378 ) .
1379 "</span>";
1380 }
1381
1382 // format text extract
1383 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
1384
1385 // format score
1386 if( is_null( $result->getScore() ) ) {
1387 // Search engine doesn't report scoring info
1388 $score = '';
1389 } else {
1390 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
1391 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
1392 . ' - ';
1393 }
1394
1395 // format description
1396 $byteSize = $result->getByteSize();
1397 $wordCount = $result->getWordCount();
1398 $timestamp = $result->getTimestamp();
1399 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
1400 $sk->formatSize( $byteSize ),
1401 $wordCount );
1402 $date = $wgLang->timeanddate( $timestamp );
1403
1404 // link to related articles if supported
1405 $related = '';
1406 if( $result->hasRelated() ){
1407 $st = SpecialPage::getTitleFor( 'Search' );
1408 $stParams = array_merge(
1409 $this->powerSearchOptions(),
1410 array(
1411 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
1412 'fulltext' => wfMsg( 'search' )
1413 )
1414 );
1415
1416 $related = ' -- ' . $sk->linkKnown(
1417 $st,
1418 wfMsg('search-relatedarticle'),
1419 array(),
1420 $stParams
1421 );
1422 }
1423
1424 // Include a thumbnail for media files...
1425 if( $t->getNamespace() == NS_FILE ) {
1426 $img = wfFindFile( $t );
1427 if( $img ) {
1428 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
1429 if( $thumb ) {
1430 $desc = $img->getShortDesc();
1431 wfProfileOut( __METHOD__ );
1432 // Ugly table. :D
1433 // Float doesn't seem to interact well with the bullets.
1434 // Table messes up vertical alignment of the bullet, but I'm
1435 // not sure what more I can do about that. :(
1436 return "<li>" .
1437 '<table class="searchResultImage">' .
1438 '<tr>' .
1439 '<td width="120" align="center">' .
1440 $thumb->toHtml( array( 'desc-link' => true ) ) .
1441 '</td>' .
1442 '<td valign="top">' .
1443 $link .
1444 $extract .
1445 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
1446 '</td>' .
1447 '</tr>' .
1448 '</table>' .
1449 "</li>\n";
1450 }
1451 }
1452 }
1453
1454 wfProfileOut( __METHOD__ );
1455 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
1456 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
1457 "</li>\n";
1458
1459 }
1460
1461 /**
1462 * Show results from other wikis
1463 *
1464 * @param SearchResultSet $matches
1465 */
1466 function showInterwiki( &$matches, $query ) {
1467 wfProfileIn( __METHOD__ );
1468
1469 global $wgContLang;
1470 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1471
1472 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
1473 $off = $this->offset + 1;
1474 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
1475
1476 // work out custom project captions
1477 $customCaptions = array();
1478 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
1479 foreach($customLines as $line){
1480 $parts = explode(":",$line,2);
1481 if(count($parts) == 2) // validate line
1482 $customCaptions[$parts[0]] = $parts[1];
1483 }
1484
1485
1486 $prev = null;
1487 while( $result = $matches->next() ) {
1488 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
1489 $prev = $result->getInterwikiPrefix();
1490 }
1491 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
1492 $out .= "</ul></div>\n";
1493
1494 // convert the whole thing to desired language variant
1495 global $wgContLang;
1496 $out = $wgContLang->convert( $out );
1497 wfProfileOut( __METHOD__ );
1498 return $out;
1499 }
1500
1501 /**
1502 * Show single interwiki link
1503 *
1504 * @param SearchResult $result
1505 * @param string $lastInterwiki
1506 * @param array $terms
1507 * @param string $query
1508 * @param array $customCaptions iw prefix -> caption
1509 */
1510 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
1511 wfProfileIn( __METHOD__ );
1512 global $wgUser, $wgContLang, $wgLang;
1513
1514 if( $result->isBrokenTitle() ) {
1515 wfProfileOut( __METHOD__ );
1516 return "<!-- Broken link in search result -->\n";
1517 }
1518
1519 $t = $result->getTitle();
1520 $sk = $wgUser->getSkin();
1521
1522 $titleSnippet = $result->getTitleSnippet($terms);
1523
1524 if( $titleSnippet == '' )
1525 $titleSnippet = null;
1526
1527 $link = $sk->linkKnown(
1528 $t,
1529 $titleSnippet
1530 );
1531
1532 // format redirect if any
1533 $redirectTitle = $result->getRedirectTitle();
1534 $redirectText = $result->getRedirectSnippet($terms);
1535 $redirect = '';
1536 if( !is_null($redirectTitle) ) {
1537 if( $redirectText == '' )
1538 $redirectText = null;
1539
1540 $redirect = "<span class='searchalttitle'>" .
1541 wfMsg(
1542 'search-redirect',
1543 $sk->linkKnown(
1544 $redirectTitle,
1545 $redirectText
1546 )
1547 ) .
1548 "</span>";
1549 }
1550
1551 $out = "";
1552 // display project name
1553 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()){
1554 if( key_exists($t->getInterwiki(),$customCaptions) )
1555 // captions from 'search-interwiki-custom'
1556 $caption = $customCaptions[$t->getInterwiki()];
1557 else{
1558 // default is to show the hostname of the other wiki which might suck
1559 // if there are many wikis on one hostname
1560 $parsed = parse_url($t->getFullURL());
1561 $caption = wfMsg('search-interwiki-default', $parsed['host']);
1562 }
1563 // "more results" link (special page stuff could be localized, but we might not know target lang)
1564 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
1565 $searchLink = $sk->linkKnown(
1566 $searchTitle,
1567 wfMsg( 'search-interwiki-more' ),
1568 array(),
1569 array(
1570 'search' => $query,
1571 'fulltext' => 'Search'
1572 )
1573 );
1574 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
1575 }
1576
1577 $out .= "<li>{$link} {$redirect}</li>\n";
1578 wfProfileOut( __METHOD__ );
1579 return $out;
1580 }
1581
1582
1583 /**
1584 * Generates the power search box at bottom of [[Special:Search]]
1585 * @param $term string: search term
1586 * @return $out string: HTML form
1587 */
1588 function powerSearchBox( $term ) {
1589 global $wgScript, $wgContLang;
1590
1591 $namespaces = SearchEngine::searchableNamespaces();
1592
1593 // group namespaces into rows according to subject; try not to make too
1594 // many assumptions about namespace numbering
1595 $rows = array();
1596 foreach( $namespaces as $ns => $name ) {
1597 $subj = MWNamespace::getSubject( $ns );
1598 if( !array_key_exists( $subj, $rows ) ) {
1599 $rows[$subj] = "";
1600 }
1601 $name = str_replace( '_', ' ', $name );
1602 if( '' == $name ) {
1603 $name = wfMsg( 'blanknamespace' );
1604 }
1605 $rows[$subj] .= Xml::openElement( 'td', array( 'style' => 'white-space: nowrap' ) ) .
1606 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
1607 Xml::closeElement( 'td' ) . "\n";
1608 }
1609 $rows = array_values( $rows );
1610 $numRows = count( $rows );
1611
1612 // lay out namespaces in multiple floating two-column tables so they'll
1613 // be arranged nicely while still accommodating different screen widths
1614 $rowsPerTable = 3; // seems to look nice
1615
1616 // float to the right on RTL wikis
1617 $tableStyle = ( $wgContLang->isRTL() ?
1618 'float: right; margin: 0 0 1em 1em' :
1619 'float: left; margin: 0 1em 1em 0' );
1620
1621 $tables = "";
1622 for( $i = 0; $i < $numRows; $i += $rowsPerTable ) {
1623 $tables .= Xml::openElement( 'table', array( 'style' => $tableStyle ) );
1624 for( $j = $i; $j < $i + $rowsPerTable && $j < $numRows; $j++ ) {
1625 $tables .= "<tr>\n" . $rows[$j] . "</tr>";
1626 }
1627 $tables .= Xml::closeElement( 'table' ) . "\n";
1628 }
1629
1630 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
1631 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
1632 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
1633 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ) ) . "\n";
1634 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1635 $searchHiddens = Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
1636 $searchHiddens .= Xml::hidden( 'fulltext', 'Advanced search' ) . "\n";
1637
1638 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
1639 Xml::fieldset( wfMsg( 'powersearch-legend' ),
1640 "<p>" .
1641 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
1642 "</p>\n" .
1643 $tables .
1644 "<hr style=\"clear: both\" />\n" .
1645 "<p>" .
1646 $redirect . " " . $redirectLabel .
1647 "</p>\n" .
1648 wfMsgExt( 'powersearch-field', array( 'parseinline' ) ) .
1649 "&nbsp;" .
1650 $searchField .
1651 "&nbsp;" .
1652 $searchHiddens .
1653 $searchButton ) .
1654 "</form>";
1655
1656 return $out;
1657 }
1658
1659 function powerSearchFocus() {
1660 global $wgJsMimeType;
1661 return "<script type=\"$wgJsMimeType\">" .
1662 "hookEvent(\"load\", function(){" .
1663 "document.getElementById('powerSearchText').focus();" .
1664 "});" .
1665 "</script>";
1666 }
1667
1668 function shortDialog($term) {
1669 global $wgScript;
1670
1671 $out = Xml::openElement( 'form', array(
1672 'id' => 'search',
1673 'method' => 'get',
1674 'action' => $wgScript
1675 ));
1676 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1677 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
1678 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1679 if( in_array( $ns, $this->namespaces ) ) {
1680 $out .= Xml::hidden( "ns{$ns}", '1' );
1681 }
1682 }
1683 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() );
1684 $out .= Xml::hidden( 'fulltext', 'Search' );
1685 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
1686 $out .= Xml::closeElement( 'form' );
1687
1688 return $out;
1689 }
1690 }