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