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