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