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