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