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