ef38ee7e2304a5ceb38b78e7c0fa9c8c5d5288f8
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 /**
3 * Implements Special:Search
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
29 */
30 class SpecialSearch extends SpecialPage {
31 /**
32 * Current search profile. Search profile is just a name that identifies
33 * the active search tab on the search page (content, help, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
37 * @var null|string
38 */
39 protected $profile;
40
41 /// Search engine
42 protected $searchEngine;
43
44 /// For links
45 protected $extraParams = array();
46
47 /// No idea, apparently used by some other classes
48 protected $mPrefix;
49
50 /**
51 * @var int
52 */
53 protected $limit, $offset;
54
55 /**
56 * @var array
57 */
58 protected $namespaces;
59
60 /**
61 * @var bool
62 */
63 protected $searchRedirects;
64
65 /**
66 * @var string
67 */
68 protected $didYouMeanHtml, $fulltext;
69
70 const NAMESPACES_CURRENT = 'sense';
71
72 public function __construct() {
73 parent::__construct( 'Search' );
74 }
75
76 /**
77 * Entry point
78 *
79 * @param $par String or null
80 */
81 public function execute( $par ) {
82 $this->setHeaders();
83 $this->outputHeader();
84 $out = $this->getOutput();
85 $out->allowClickjacking();
86 $out->addModuleStyles( 'mediawiki.special' );
87
88 // Strip underscores from title parameter; most of the time we'll want
89 // text form here. But don't strip underscores from actual text params!
90 $titleParam = str_replace( '_', ' ', $par );
91
92 $request = $this->getRequest();
93
94 // Fetch the search term
95 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
96
97 $this->load();
98
99 if ( $request->getVal( 'fulltext' )
100 || !is_null( $request->getVal( 'offset' ) )
101 || !is_null( $request->getVal( 'searchx' ) ) )
102 {
103 $this->showResults( $search );
104 } else {
105 $this->goResult( $search );
106 }
107 }
108
109 /**
110 * Set up basic search parameters from the request and user settings.
111 */
112 public function load() {
113 $request = $this->getRequest();
114 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
115 $this->mPrefix = $request->getVal( 'prefix', '' );
116
117 $user = $this->getUser();
118 # Extract manually requested namespaces
119 $nslist = $this->powerSearch( $request );
120 $this->profile = $profile = $request->getVal( 'profile', null );
121 $profiles = $this->getSearchProfiles();
122 if ( $profile === null) {
123 // BC with old request format
124 $this->profile = 'advanced';
125 if ( count( $nslist ) ) {
126 foreach( $profiles as $key => $data ) {
127 if ( $nslist === $data['namespaces'] && $key !== 'advanced') {
128 $this->profile = $key;
129 }
130 }
131 $this->namespaces = $nslist;
132 } else {
133 $this->namespaces = SearchEngine::userNamespaces( $user );
134 }
135 } elseif ( $profile === 'advanced' ) {
136 $this->namespaces = $nslist;
137 } else {
138 if ( isset( $profiles[$profile]['namespaces'] ) ) {
139 $this->namespaces = $profiles[$profile]['namespaces'];
140 } else {
141 // Unknown profile requested
142 $this->profile = 'default';
143 $this->namespaces = $profiles['default']['namespaces'];
144 }
145 }
146
147 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
148 $default = $request->getBool( 'profile' ) ? 0 : 1;
149 $this->searchRedirects = $request->getBool( 'redirs', $default ) ? 1 : 0;
150 $this->didYouMeanHtml = ''; # html of did you mean... link
151 $this->fulltext = $request->getVal('fulltext');
152 }
153
154 /**
155 * If an exact title match can be found, jump straight ahead to it.
156 *
157 * @param $term String
158 */
159 public function goResult( $term ) {
160 $this->setupPage( $term );
161 # Try to go to page as entered.
162 $t = Title::newFromText( $term );
163 # If the string cannot be used to create a title
164 if( is_null( $t ) ) {
165 return $this->showResults( $term );
166 }
167 # If there's an exact or very near match, jump right there.
168 $t = SearchEngine::getNearMatch( $term );
169
170 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
171 # Hook requested termination
172 return;
173 }
174
175 if( !is_null( $t ) ) {
176 $this->getOutput()->redirect( $t->getFullURL() );
177 return;
178 }
179 # No match, generate an edit URL
180 $t = Title::newFromText( $term );
181 if( !is_null( $t ) ) {
182 global $wgGoToEdit;
183 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
184 wfDebugLog( 'nogomatch', $t->getText(), false );
185
186 # If the feature is enabled, go straight to the edit page
187 if( $wgGoToEdit ) {
188 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
189 return;
190 }
191 }
192 return $this->showResults( $term );
193 }
194
195 /**
196 * @param $term String
197 */
198 public function showResults( $term ) {
199 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
200 wfProfileIn( __METHOD__ );
201
202 $search = $this->getSearchEngine();
203 $search->setLimitOffset( $this->limit, $this->offset );
204 $search->setNamespaces( $this->namespaces );
205 $search->showRedirects = $this->searchRedirects; // BC
206 $search->setFeatureData( 'list-redirects', $this->searchRedirects );
207 $search->prefix = $this->mPrefix;
208 $term = $search->transformSearchTerm($term);
209
210 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
211
212 $this->setupPage( $term );
213
214 $out = $this->getOutput();
215
216 if ( $wgDisableTextSearch ) {
217 if ( $wgSearchForwardUrl ) {
218 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
219 $out->redirect( $url );
220 } else {
221 $out->addHTML(
222 Xml::openElement( 'fieldset' ) .
223 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
224 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
225 wfMsg( 'googlesearch',
226 htmlspecialchars( $term ),
227 htmlspecialchars( 'UTF-8' ),
228 htmlspecialchars( wfMsg( 'searchbutton' ) )
229 ) .
230 Xml::closeElement( 'fieldset' )
231 );
232 }
233 wfProfileOut( __METHOD__ );
234 return;
235 }
236
237 $t = Title::newFromText( $term );
238
239 // fetch search results
240 $rewritten = $search->replacePrefixes($term);
241
242 $titleMatches = $search->searchTitle( $rewritten );
243 if( !( $titleMatches instanceof SearchResultTooMany ) ) {
244 $textMatches = $search->searchText( $rewritten );
245 }
246
247 // did you mean... suggestions
248 if( $textMatches && $textMatches->hasSuggestion() ) {
249 $st = SpecialPage::getTitleFor( 'Search' );
250
251 # mirror Go/Search behaviour of original request ..
252 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
253
254 if( $this->fulltext != null ) {
255 $didYouMeanParams['fulltext'] = $this->fulltext;
256 }
257
258 $stParams = array_merge(
259 $didYouMeanParams,
260 $this->powerSearchOptions()
261 );
262
263 $suggestionSnippet = $textMatches->getSuggestionSnippet();
264
265 if( $suggestionSnippet == '' ) {
266 $suggestionSnippet = null;
267 }
268
269 $suggestLink = Linker::linkKnown(
270 $st,
271 $suggestionSnippet,
272 array(),
273 $stParams
274 );
275
276 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
277 }
278 // start rendering the page
279 $out->addHtml(
280 Xml::openElement(
281 'form',
282 array(
283 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
284 'method' => 'get',
285 'action' => $wgScript
286 )
287 )
288 );
289 $out->addHtml(
290 Xml::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
291 Xml::openElement( 'tr' ) .
292 Xml::openElement( 'td' ) . "\n" .
293 $this->shortDialog( $term ) .
294 Xml::closeElement('td') .
295 Xml::closeElement('tr') .
296 Xml::closeElement('table')
297 );
298
299 // Sometimes the search engine knows there are too many hits
300 if( $titleMatches instanceof SearchResultTooMany ) {
301 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
302 wfProfileOut( __METHOD__ );
303 return;
304 }
305
306 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
307 if( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
308 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
309 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
310 $out->addHTML( '</form>' );
311 // Empty query -- straight view of search form
312 wfProfileOut( __METHOD__ );
313 return;
314 }
315
316 // Get number of results
317 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
318 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
319 // Total initial query matches (possible false positives)
320 $num = $titleMatchesNum + $textMatchesNum;
321
322 // Get total actual results (after second filtering, if any)
323 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
324 $titleMatches->getTotalHits() : $titleMatchesNum;
325 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
326 $textMatches->getTotalHits() : $textMatchesNum;
327
328 // get total number of results if backend can calculate it
329 $totalRes = 0;
330 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
331 $totalRes += $titleMatches->getTotalHits();
332 if($textMatches && !is_null( $textMatches->getTotalHits() ))
333 $totalRes += $textMatches->getTotalHits();
334
335 // show number of results and current offset
336 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
337 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
338
339
340 $out->addHtml( Xml::closeElement( 'form' ) );
341 $out->addHtml( "<div class='searchresults'>" );
342
343 // prev/next links
344 if( $num || $this->offset ) {
345 // Show the create link ahead
346 $this->showCreateLink( $t );
347 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
348 SpecialPage::getTitleFor( 'Search' ),
349 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
350 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
351 );
352 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
353 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
354 } else {
355 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
356 }
357
358 $out->parserOptions()->setEditSection( false );
359 if( $titleMatches ) {
360 if( $numTitleMatches > 0 ) {
361 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
362 $out->addHTML( $this->showMatches( $titleMatches ) );
363 }
364 $titleMatches->free();
365 }
366 if( $textMatches ) {
367 // output appropriate heading
368 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
369 // if no title matches the heading is redundant
370 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
371 } elseif( $totalRes == 0 ) {
372 # Don't show the 'no text matches' if we received title matches
373 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
374 }
375 // show interwiki results if any
376 if( $textMatches->hasInterwikiResults() ) {
377 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
378 }
379 // show results
380 if( $numTextMatches > 0 ) {
381 $out->addHTML( $this->showMatches( $textMatches ) );
382 }
383
384 $textMatches->free();
385 }
386 if( $num === 0 ) {
387 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
388 $this->showCreateLink( $t );
389 }
390 $out->addHtml( "</div>" );
391
392 if( $num || $this->offset ) {
393 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
394 }
395 wfProfileOut( __METHOD__ );
396 }
397
398 /**
399 * @param $t Title
400 */
401 protected function showCreateLink( $t ) {
402 // show direct page/create link if applicable
403 // Check DBkey !== '' in case of fragment link only.
404 $messageName = null;
405 if( !is_null($t) && $t->getDBkey() !== '' ) {
406 if( $t->isKnown() ) {
407 $messageName = 'searchmenu-exists';
408 } elseif( $t->userCan( 'create' ) ) {
409 $messageName = 'searchmenu-new';
410 } else {
411 $messageName = 'searchmenu-new-nocreate';
412 }
413 }
414 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
415 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
416
417 if( $messageName ) {
418 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
419 } else {
420 // preserve the paragraph for margins etc...
421 $this->getOutput()->addHtml( '<p></p>' );
422 }
423 }
424
425 /**
426 * @param $term string
427 */
428 protected function setupPage( $term ) {
429 # Should advanced UI be used?
430 $this->searchAdvanced = ($this->profile === 'advanced');
431 $out = $this->getOutput();
432 if( strval( $term ) !== '' ) {
433 $out->setPageTitle( wfMsg( 'searchresults') );
434 $out->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
435 }
436 // add javascript specific to special:search
437 $out->addModules( 'mediawiki.special.search' );
438 }
439
440 /**
441 * Extract "power search" namespace settings from the request object,
442 * returning a list of index numbers to search.
443 *
444 * @param $request WebRequest
445 * @return Array
446 */
447 protected function powerSearch( &$request ) {
448 $arr = array();
449 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
450 if( $request->getCheck( 'ns' . $ns ) ) {
451 $arr[] = $ns;
452 }
453 }
454
455 return $arr;
456 }
457
458 /**
459 * Reconstruct the 'power search' options for links
460 *
461 * @return Array
462 */
463 protected function powerSearchOptions() {
464 $opt = array();
465 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
466 if( $this->profile !== 'advanced' ) {
467 $opt['profile'] = $this->profile;
468 } else {
469 foreach( $this->namespaces as $n ) {
470 $opt['ns' . $n] = 1;
471 }
472 }
473 return $opt + $this->extraParams;
474 }
475
476 /**
477 * Show whole set of results
478 *
479 * @param $matches SearchResultSet
480 *
481 * @return string
482 */
483 protected function showMatches( &$matches ) {
484 global $wgContLang;
485 wfProfileIn( __METHOD__ );
486
487 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
488
489 $out = "";
490 $infoLine = $matches->getInfo();
491 if( !is_null($infoLine) ) {
492 $out .= "\n<!-- {$infoLine} -->\n";
493 }
494 $out .= "<ul class='mw-search-results'>\n";
495 while( $result = $matches->next() ) {
496 $out .= $this->showHit( $result, $terms );
497 }
498 $out .= "</ul>\n";
499
500 // convert the whole thing to desired language variant
501 $out = $wgContLang->convert( $out );
502 wfProfileOut( __METHOD__ );
503 return $out;
504 }
505
506 /**
507 * Format a single hit result
508 *
509 * @param $result SearchResult
510 * @param $terms Array: terms to highlight
511 *
512 * @return string
513 */
514 protected function showHit( $result, $terms ) {
515 wfProfileIn( __METHOD__ );
516
517 if( $result->isBrokenTitle() ) {
518 wfProfileOut( __METHOD__ );
519 return "<!-- Broken link in search result -->\n";
520 }
521
522 $t = $result->getTitle();
523
524 $titleSnippet = $result->getTitleSnippet($terms);
525
526 if( $titleSnippet == '' )
527 $titleSnippet = null;
528
529 $link_t = clone $t;
530
531 wfRunHooks( 'ShowSearchHitTitle',
532 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
533
534 $link = Linker::linkKnown(
535 $link_t,
536 $titleSnippet
537 );
538
539 //If page content is not readable, just return the title.
540 //This is not quite safe, but better than showing excerpts from non-readable pages
541 //Note that hiding the entry entirely would screw up paging.
542 if( !$t->userCanRead() ) {
543 wfProfileOut( __METHOD__ );
544 return "<li>{$link}</li>\n";
545 }
546
547 // If the page doesn't *exist*... our search index is out of date.
548 // The least confusing at this point is to drop the result.
549 // You may get less results, but... oh well. :P
550 if( $result->isMissingRevision() ) {
551 wfProfileOut( __METHOD__ );
552 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
553 }
554
555 // format redirects / relevant sections
556 $redirectTitle = $result->getRedirectTitle();
557 $redirectText = $result->getRedirectSnippet($terms);
558 $sectionTitle = $result->getSectionTitle();
559 $sectionText = $result->getSectionSnippet($terms);
560 $redirect = '';
561
562 if( !is_null($redirectTitle) ) {
563 if( $redirectText == '' )
564 $redirectText = null;
565
566 $redirect = "<span class='searchalttitle'>" .
567 wfMsg(
568 'search-redirect',
569 Linker::linkKnown(
570 $redirectTitle,
571 $redirectText
572 )
573 ) .
574 "</span>";
575 }
576
577 $section = '';
578
579 if( !is_null($sectionTitle) ) {
580 if( $sectionText == '' )
581 $sectionText = null;
582
583 $section = "<span class='searchalttitle'>" .
584 wfMsg(
585 'search-section', Linker::linkKnown(
586 $sectionTitle,
587 $sectionText
588 )
589 ) .
590 "</span>";
591 }
592
593 // format text extract
594 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
595
596 $lang = $this->getLang();
597
598 // format score
599 if( is_null( $result->getScore() ) ) {
600 // Search engine doesn't report scoring info
601 $score = '';
602 } else {
603 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
604 $score = wfMsg( 'search-result-score', $lang->formatNum( $percent ) )
605 . ' - ';
606 }
607
608 // format description
609 $byteSize = $result->getByteSize();
610 $wordCount = $result->getWordCount();
611 $timestamp = $result->getTimestamp();
612 $size = wfMsgExt(
613 'search-result-size',
614 array( 'parsemag', 'escape' ),
615 $lang->formatSize( $byteSize ),
616 $lang->formatNum( $wordCount )
617 );
618
619 if( $t->getNamespace() == NS_CATEGORY ) {
620 $cat = Category::newFromTitle( $t );
621 $size = wfMsgExt(
622 'search-result-category-size',
623 array( 'parsemag', 'escape' ),
624 $lang->formatNum( $cat->getPageCount() ),
625 $lang->formatNum( $cat->getSubcatCount() ),
626 $lang->formatNum( $cat->getFileCount() )
627 );
628 }
629
630 $date = $lang->timeanddate( $timestamp );
631
632 // link to related articles if supported
633 $related = '';
634 if( $result->hasRelated() ) {
635 $st = SpecialPage::getTitleFor( 'Search' );
636 $stParams = array_merge(
637 $this->powerSearchOptions(),
638 array(
639 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
640 'fulltext' => wfMsg( 'search' )
641 )
642 );
643
644 $related = ' -- ' . Linker::linkKnown(
645 $st,
646 wfMsg('search-relatedarticle'),
647 array(),
648 $stParams
649 );
650 }
651
652 // Include a thumbnail for media files...
653 if( $t->getNamespace() == NS_FILE ) {
654 $img = wfFindFile( $t );
655 if( $img ) {
656 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
657 if( $thumb ) {
658 $desc = wfMsg( 'parentheses', $img->getShortDesc() );
659 wfProfileOut( __METHOD__ );
660 // Float doesn't seem to interact well with the bullets.
661 // Table messes up vertical alignment of the bullets.
662 // Bullets are therefore disabled (didn't look great anyway).
663 return "<li>" .
664 '<table class="searchResultImage">' .
665 '<tr>' .
666 '<td width="120" align="center" valign="top">' .
667 $thumb->toHtml( array( 'desc-link' => true ) ) .
668 '</td>' .
669 '<td valign="top">' .
670 $link .
671 $extract .
672 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
673 '</td>' .
674 '</tr>' .
675 '</table>' .
676 "</li>\n";
677 }
678 }
679 }
680
681 wfProfileOut( __METHOD__ );
682 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
683 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
684 "</li>\n";
685
686 }
687
688 /**
689 * Show results from other wikis
690 *
691 * @param $matches SearchResultSet
692 * @param $query String
693 *
694 * @return string
695 */
696 protected function showInterwiki( &$matches, $query ) {
697 global $wgContLang;
698 wfProfileIn( __METHOD__ );
699 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
700
701 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
702 wfMsg('search-interwiki-caption')."</div>\n";
703 $out .= "<ul class='mw-search-iwresults'>\n";
704
705 // work out custom project captions
706 $customCaptions = array();
707 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
708 foreach($customLines as $line) {
709 $parts = explode(":",$line,2);
710 if(count($parts) == 2) // validate line
711 $customCaptions[$parts[0]] = $parts[1];
712 }
713
714 $prev = null;
715 while( $result = $matches->next() ) {
716 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
717 $prev = $result->getInterwikiPrefix();
718 }
719 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
720 $out .= "</ul></div>\n";
721
722 // convert the whole thing to desired language variant
723 $out = $wgContLang->convert( $out );
724 wfProfileOut( __METHOD__ );
725 return $out;
726 }
727
728 /**
729 * Show single interwiki link
730 *
731 * @param $result SearchResult
732 * @param $lastInterwiki String
733 * @param $terms Array
734 * @param $query String
735 * @param $customCaptions Array: iw prefix -> caption
736 *
737 * @return string
738 */
739 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
740 wfProfileIn( __METHOD__ );
741
742 if( $result->isBrokenTitle() ) {
743 wfProfileOut( __METHOD__ );
744 return "<!-- Broken link in search result -->\n";
745 }
746
747 $t = $result->getTitle();
748
749 $titleSnippet = $result->getTitleSnippet($terms);
750
751 if( $titleSnippet == '' )
752 $titleSnippet = null;
753
754 $link = Linker::linkKnown(
755 $t,
756 $titleSnippet
757 );
758
759 // format redirect if any
760 $redirectTitle = $result->getRedirectTitle();
761 $redirectText = $result->getRedirectSnippet($terms);
762 $redirect = '';
763 if( !is_null($redirectTitle) ) {
764 if( $redirectText == '' )
765 $redirectText = null;
766
767 $redirect = "<span class='searchalttitle'>" .
768 wfMsg(
769 'search-redirect',
770 Linker::linkKnown(
771 $redirectTitle,
772 $redirectText
773 )
774 ) .
775 "</span>";
776 }
777
778 $out = "";
779 // display project name
780 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
781 if( array_key_exists($t->getInterwiki(),$customCaptions) ) {
782 // captions from 'search-interwiki-custom'
783 $caption = $customCaptions[$t->getInterwiki()];
784 } else {
785 // default is to show the hostname of the other wiki which might suck
786 // if there are many wikis on one hostname
787 $parsed = wfParseUrl( $t->getFullURL() );
788 $caption = wfMsg('search-interwiki-default', $parsed['host']);
789 }
790 // "more results" link (special page stuff could be localized, but we might not know target lang)
791 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
792 $searchLink = Linker::linkKnown(
793 $searchTitle,
794 wfMsg('search-interwiki-more'),
795 array(),
796 array(
797 'search' => $query,
798 'fulltext' => 'Search'
799 )
800 );
801 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
802 {$searchLink}</span>{$caption}</div>\n<ul>";
803 }
804
805 $out .= "<li>{$link} {$redirect}</li>\n";
806 wfProfileOut( __METHOD__ );
807 return $out;
808 }
809
810 /**
811 * @param $profile
812 * @param $term
813 * @return String
814 */
815 protected function getProfileForm( $profile, $term ) {
816 // Hidden stuff
817 $opts = array();
818 $opts['redirs'] = $this->searchRedirects;
819 $opts['profile'] = $this->profile;
820
821 if ( $profile === 'advanced' ) {
822 return $this->powerSearchBox( $term, $opts );
823 } else {
824 $form = '';
825 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
826 return $form;
827 }
828 }
829
830 /**
831 * Generates the power search box at [[Special:Search]]
832 *
833 * @param $term String: search term
834 * @param $opts array
835 * @return String: HTML form
836 */
837 protected function powerSearchBox( $term, $opts ) {
838 // Groups namespaces into rows according to subject
839 $rows = array();
840 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
841 $subject = MWNamespace::getSubject( $namespace );
842 if( !array_key_exists( $subject, $rows ) ) {
843 $rows[$subject] = "";
844 }
845 $name = str_replace( '_', ' ', $name );
846 if( $name == '' ) {
847 $name = wfMsg( 'blanknamespace' );
848 }
849 $rows[$subject] .=
850 Xml::openElement(
851 'td', array( 'style' => 'white-space: nowrap' )
852 ) .
853 Xml::checkLabel(
854 $name,
855 "ns{$namespace}",
856 "mw-search-ns{$namespace}",
857 in_array( $namespace, $this->namespaces )
858 ) .
859 Xml::closeElement( 'td' );
860 }
861 $rows = array_values( $rows );
862 $numRows = count( $rows );
863
864 // Lays out namespaces in multiple floating two-column tables so they'll
865 // be arranged nicely while still accommodating different screen widths
866 $namespaceTables = '';
867 for( $i = 0; $i < $numRows; $i += 4 ) {
868 $namespaceTables .= Xml::openElement(
869 'table',
870 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
871 );
872 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
873 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
874 }
875 $namespaceTables .= Xml::closeElement( 'table' );
876 }
877
878 $showSections = array( 'namespaceTables' => $namespaceTables );
879
880 // Show redirects check only if backend supports it
881 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
882 $showSections['redirects'] =
883 Xml::checkLabel( wfMsg( 'powersearch-redir' ), 'redirs', 'redirs', $this->searchRedirects );
884 }
885
886 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
887
888 $hidden = '';
889 unset( $opts['redirs'] );
890 foreach( $opts as $key => $value ) {
891 $hidden .= Html::hidden( $key, $value );
892 }
893 // Return final output
894 return
895 Xml::openElement(
896 'fieldset',
897 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
898 ) .
899 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
900 Xml::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
901 Xml::tags(
902 'div',
903 array( 'id' => 'mw-search-togglebox' ),
904 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
905 Xml::element(
906 'input',
907 array(
908 'type'=>'button',
909 'id' => 'mw-search-toggleall',
910 'value' => wfMsg( 'powersearch-toggleall' )
911 )
912 ) .
913 Xml::element(
914 'input',
915 array(
916 'type'=>'button',
917 'id' => 'mw-search-togglenone',
918 'value' => wfMsg( 'powersearch-togglenone' )
919 )
920 )
921 ) .
922 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
923 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
924 $hidden .
925 Xml::closeElement( 'fieldset' );
926 }
927
928 /**
929 * @return array
930 */
931 protected function getSearchProfiles() {
932 // Builds list of Search Types (profiles)
933 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
934
935 $profiles = array(
936 'default' => array(
937 'message' => 'searchprofile-articles',
938 'tooltip' => 'searchprofile-articles-tooltip',
939 'namespaces' => SearchEngine::defaultNamespaces(),
940 'namespace-messages' => SearchEngine::namespacesAsText(
941 SearchEngine::defaultNamespaces()
942 ),
943 ),
944 'images' => array(
945 'message' => 'searchprofile-images',
946 'tooltip' => 'searchprofile-images-tooltip',
947 'namespaces' => array( NS_FILE ),
948 ),
949 'help' => array(
950 'message' => 'searchprofile-project',
951 'tooltip' => 'searchprofile-project-tooltip',
952 'namespaces' => SearchEngine::helpNamespaces(),
953 'namespace-messages' => SearchEngine::namespacesAsText(
954 SearchEngine::helpNamespaces()
955 ),
956 ),
957 'all' => array(
958 'message' => 'searchprofile-everything',
959 'tooltip' => 'searchprofile-everything-tooltip',
960 'namespaces' => $nsAllSet,
961 ),
962 'advanced' => array(
963 'message' => 'searchprofile-advanced',
964 'tooltip' => 'searchprofile-advanced-tooltip',
965 'namespaces' => self::NAMESPACES_CURRENT,
966 )
967 );
968
969 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
970
971 foreach( $profiles as &$data ) {
972 if ( !is_array( $data['namespaces'] ) ) continue;
973 sort( $data['namespaces'] );
974 }
975
976 return $profiles;
977 }
978
979 /**
980 * @param $term
981 * @param $resultsShown
982 * @param $totalNum
983 * @return string
984 */
985 protected function formHeader( $term, $resultsShown, $totalNum ) {
986 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
987
988 $bareterm = $term;
989 if( $this->startsWithImage( $term ) ) {
990 // Deletes prefixes
991 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
992 }
993
994 $profiles = $this->getSearchProfiles();
995 $lang = $this->getLang();
996
997 // Outputs XML for Search Types
998 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
999 $out .= Xml::openElement( 'ul' );
1000 foreach ( $profiles as $id => $profile ) {
1001 if ( !isset( $profile['parameters'] ) ) {
1002 $profile['parameters'] = array();
1003 }
1004 $profile['parameters']['profile'] = $id;
1005
1006 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1007 $lang->commaList( $profile['namespace-messages'] ) : null;
1008 $out .= Xml::tags(
1009 'li',
1010 array(
1011 'class' => $this->profile === $id ? 'current' : 'normal'
1012 ),
1013 $this->makeSearchLink(
1014 $bareterm,
1015 array(),
1016 wfMsg( $profile['message'] ),
1017 wfMsg( $profile['tooltip'], $tooltipParam ),
1018 $profile['parameters']
1019 )
1020 );
1021 }
1022 $out .= Xml::closeElement( 'ul' );
1023 $out .= Xml::closeElement('div') ;
1024
1025 // Results-info
1026 if ( $resultsShown > 0 ) {
1027 if ( $totalNum > 0 ){
1028 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
1029 $lang->formatNum( $this->offset + 1 ),
1030 $lang->formatNum( $this->offset + $resultsShown ),
1031 $lang->formatNum( $totalNum ),
1032 wfEscapeWikiText( $term ),
1033 $lang->formatNum( $resultsShown )
1034 );
1035 } elseif ( $resultsShown >= $this->limit ) {
1036 $top = wfShowingResults( $this->offset, $this->limit );
1037 } else {
1038 $top = wfMsgExt( 'showingresultsnum', array( 'parseinline' ),
1039 $lang->formatNum( $this->limit ),
1040 $lang->formatNum( $this->offset + 1 ),
1041 $lang->formatNum( $resultsShown )
1042 );
1043 }
1044 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1045 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1046 );
1047 }
1048
1049 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1050 $out .= Xml::closeElement('div');
1051
1052 return $out;
1053 }
1054
1055 /**
1056 * @param $term string
1057 * @return string
1058 */
1059 protected function shortDialog( $term ) {
1060 $out = Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1061 // Term box
1062 $out .= Html::input( 'search', $term, 'search', array(
1063 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1064 'size' => '50',
1065 'autofocus'
1066 ) ) . "\n";
1067 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1068 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
1069 return $out . $this->didYouMeanHtml;
1070 }
1071
1072 /**
1073 * Make a search link with some target namespaces
1074 *
1075 * @param $term String
1076 * @param $namespaces Array ignored
1077 * @param $label String: link's text
1078 * @param $tooltip String: link's tooltip
1079 * @param $params Array: query string parameters
1080 * @return String: HTML fragment
1081 */
1082 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1083 $opt = $params;
1084 foreach( $namespaces as $n ) {
1085 $opt['ns' . $n] = 1;
1086 }
1087 $opt['redirs'] = $this->searchRedirects;
1088
1089 $stParams = array_merge(
1090 array(
1091 'search' => $term,
1092 'fulltext' => wfMsg( 'search' )
1093 ),
1094 $opt
1095 );
1096
1097 return Xml::element(
1098 'a',
1099 array(
1100 'href' => $this->getTitle()->getLocalURL( $stParams ),
1101 'title' => $tooltip),
1102 $label
1103 );
1104 }
1105
1106 /**
1107 * Check if query starts with image: prefix
1108 *
1109 * @param $term String: the string to check
1110 * @return Boolean
1111 */
1112 protected function startsWithImage( $term ) {
1113 global $wgContLang;
1114
1115 $p = explode( ':', $term );
1116 if( count( $p ) > 1 ) {
1117 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1118 }
1119 return false;
1120 }
1121
1122 /**
1123 * Check if query starts with all: prefix
1124 *
1125 * @param $term String: the string to check
1126 * @return Boolean
1127 */
1128 protected function startsWithAll( $term ) {
1129
1130 $allkeyword = wfMsgForContent('searchall');
1131
1132 $p = explode( ':', $term );
1133 if( count( $p ) > 1 ) {
1134 return $p[0] == $allkeyword;
1135 }
1136 return false;
1137 }
1138
1139 /**
1140 * @since 1.18
1141 *
1142 * @return SearchEngine
1143 */
1144 public function getSearchEngine() {
1145 if ( $this->searchEngine === null ) {
1146 $this->searchEngine = SearchEngine::create();
1147 }
1148 return $this->searchEngine;
1149 }
1150
1151 /**
1152 * Users of hook SpecialSearchSetupEngine can use this to
1153 * add more params to links to not lose selection when
1154 * user navigates search results.
1155 * @since 1.18
1156 *
1157 * @param $key
1158 * @param $value
1159 */
1160 public function setExtraParam( $key, $value ) {
1161 $this->extraParams[$key] = $value;
1162 }
1163
1164 }