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