fc7eeb17d52327c33c0b9df7b05dfcd324487807
[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 $out->addJsConfigVars( array( 'searchTerm' => $search ) );
119 $this->searchEngineType = $request->getVal( 'srbackend' );
120
121 if ( $request->getVal( 'fulltext' )
122 || !is_null( $request->getVal( 'offset' ) )
123 ) {
124 $this->showResults( $search );
125 } else {
126 $this->goResult( $search );
127 }
128 }
129
130 /**
131 * Set up basic search parameters from the request and user settings.
132 *
133 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
134 */
135 public function load() {
136 $request = $this->getRequest();
137 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
138 $this->mPrefix = $request->getVal( 'prefix', '' );
139
140 $user = $this->getUser();
141
142 # Extract manually requested namespaces
143 $nslist = $this->powerSearch( $request );
144 if ( !count( $nslist ) ) {
145 # Fallback to user preference
146 $nslist = SearchEngine::userNamespaces( $user );
147 }
148
149 $profile = null;
150 if ( !count( $nslist ) ) {
151 $profile = 'default';
152 }
153
154 $profile = $request->getVal( 'profile', $profile );
155 $profiles = $this->getSearchProfiles();
156 if ( $profile === null ) {
157 // BC with old request format
158 $profile = 'advanced';
159 foreach ( $profiles as $key => $data ) {
160 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
161 $profile = $key;
162 }
163 }
164 $this->namespaces = $nslist;
165 } elseif ( $profile === 'advanced' ) {
166 $this->namespaces = $nslist;
167 } else {
168 if ( isset( $profiles[$profile]['namespaces'] ) ) {
169 $this->namespaces = $profiles[$profile]['namespaces'];
170 } else {
171 // Unknown profile requested
172 $profile = 'default';
173 $this->namespaces = $profiles['default']['namespaces'];
174 }
175 }
176
177 $this->fulltext = $request->getVal( 'fulltext' );
178 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', true );
179 $this->profile = $profile;
180 }
181
182 /**
183 * If an exact title match can be found, jump straight ahead to it.
184 *
185 * @param string $term
186 */
187 public function goResult( $term ) {
188 $this->setupPage( $term );
189 # Try to go to page as entered.
190 $title = Title::newFromText( $term );
191 # If the string cannot be used to create a title
192 if ( is_null( $title ) ) {
193 $this->showResults( $term );
194
195 return;
196 }
197 # If there's an exact or very near match, jump right there.
198 $title = SearchEngine::getNearMatch( $term );
199
200 if ( !is_null( $title ) ) {
201 $this->getOutput()->redirect( $title->getFullURL() );
202
203 return;
204 }
205 # No match, generate an edit URL
206 $title = Title::newFromText( $term );
207 if ( !is_null( $title ) ) {
208 Hooks::run( 'SpecialSearchNogomatch', array( &$title ) );
209 }
210 $this->showResults( $term );
211 }
212
213 /**
214 * @param string $term
215 */
216 public function showResults( $term ) {
217 global $wgContLang;
218
219 $search = $this->getSearchEngine();
220 $search->setFeatureData( 'rewrite', $this->runSuggestion );
221 $search->setLimitOffset( $this->limit, $this->offset );
222 $search->setNamespaces( $this->namespaces );
223 $search->prefix = $this->mPrefix;
224 $term = $search->transformSearchTerm( $term );
225
226 Hooks::run( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
227
228 $this->setupPage( $term );
229
230 $out = $this->getOutput();
231
232 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
233 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
234 if ( $searchFowardUrl ) {
235 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
236 $out->redirect( $url );
237 } else {
238 $out->addHTML(
239 Xml::openElement( 'fieldset' ) .
240 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
241 Xml::element(
242 'p',
243 array( 'class' => 'mw-searchdisabled' ),
244 $this->msg( 'searchdisabled' )->text()
245 ) .
246 $this->msg( 'googlesearch' )->rawParams(
247 htmlspecialchars( $term ),
248 'UTF-8',
249 $this->msg( 'searchbutton' )->escaped()
250 )->text() .
251 Xml::closeElement( 'fieldset' )
252 );
253 }
254
255 return;
256 }
257
258 $title = Title::newFromText( $term );
259 $showSuggestion = $title === null || !$title->isKnown();
260 $search->setShowSuggestion( $showSuggestion );
261
262 // fetch search results
263 $rewritten = $search->replacePrefixes( $term );
264
265 $titleMatches = $search->searchTitle( $rewritten );
266 $textMatches = $search->searchText( $rewritten );
267
268 $textStatus = null;
269 if ( $textMatches instanceof Status ) {
270 $textStatus = $textMatches;
271 $textMatches = null;
272 }
273
274 // did you mean... suggestions
275 $didYouMeanHtml = '';
276 if ( $showSuggestion && $textMatches && !$textStatus ) {
277 if ( $textMatches->hasRewrittenQuery() ) {
278 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
279 } elseif ( $textMatches->hasSuggestion() ) {
280 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
281 }
282 }
283
284 if ( !Hooks::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
285 # Hook requested termination
286 return;
287 }
288
289 // start rendering the page
290 $out->addHtml(
291 Xml::openElement(
292 'form',
293 array(
294 'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
295 'method' => 'get',
296 'action' => wfScript(),
297 )
298 )
299 );
300
301 // Get number of results
302 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
303 if ( $titleMatches ) {
304 $titleMatchesNum = $titleMatches->numRows();
305 $numTitleMatches = $titleMatches->getTotalHits();
306 }
307 if ( $textMatches ) {
308 $textMatchesNum = $textMatches->numRows();
309 $numTextMatches = $textMatches->getTotalHits();
310 }
311 $num = $titleMatchesNum + $textMatchesNum;
312 $totalRes = $numTitleMatches + $numTextMatches;
313
314 $out->addHtml(
315 # This is an awful awful ID name. It's not a table, but we
316 # named it poorly from when this was a table so now we're
317 # stuck with it
318 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
319 $this->shortDialog( $term, $num, $totalRes ) .
320 Xml::closeElement( 'div' ) .
321 $this->searchProfileTabs( $term ) .
322 $this->searchOptions( $term ) .
323 Xml::closeElement( 'form' ) .
324 $didYouMeanHtml
325 );
326
327 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
328 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
329 // Empty query -- straight view of search form
330 return;
331 }
332
333 $out->addHtml( "<div class='searchresults'>" );
334
335 // prev/next links
336 $prevnext = null;
337 if ( $num || $this->offset ) {
338 // Show the create link ahead
339 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
340 if ( $totalRes > $this->limit || $this->offset ) {
341 if ( $this->searchEngineType !== null ) {
342 $this->setExtraParam( 'srbackend', $this->searchEngineType );
343 }
344 $prevnext = $this->getLanguage()->viewPrevNext(
345 $this->getPageTitle(),
346 $this->offset,
347 $this->limit,
348 $this->powerSearchOptions() + array( 'search' => $term ),
349 $this->limit + $this->offset >= $totalRes
350 );
351 }
352 }
353 Hooks::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
354
355 $out->parserOptions()->setEditSection( false );
356 if ( $titleMatches ) {
357 if ( $numTitleMatches > 0 ) {
358 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
359 $out->addHTML( $this->showMatches( $titleMatches ) );
360 }
361 $titleMatches->free();
362 }
363 if ( $textMatches && !$textStatus ) {
364 // output appropriate heading
365 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
366 // if no title matches the heading is redundant
367 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
368 }
369
370 // show results
371 if ( $numTextMatches > 0 ) {
372 $out->addHTML( $this->showMatches( $textMatches ) );
373 }
374 // show interwiki results if any
375 if ( $textMatches->hasInterwikiResults() ) {
376 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
377 }
378
379 $textMatches->free();
380 }
381 if ( $num === 0 ) {
382 if ( $textStatus ) {
383 $out->addHTML( '<div class="error">' .
384 $textStatus->getMessage( 'search-error' ) . '</div>' );
385 } else {
386 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
387 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
388 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
389 }
390 }
391
392 $out->addHTML( '<div class="visualClear"></div>' );
393 if ( $prevnext ) {
394 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
395 }
396
397 $out->addHtml( "</div>" );
398
399 Hooks::run( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
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 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
420 }
421
422 /**
423 * Generates HTML shown to the user when we have a suggestion about a query
424 * that might give more results than their current query.
425 */
426 protected function getDidYouMeanHtml( SearchResultSet $textMatches ) {
427 # mirror Go/Search behavior of original request ..
428 $params = array( 'search' => $textMatches->getSuggestionQuery() );
429 if ( $this->fulltext != null ) {
430 $params['fulltext'] = $this->fulltext;
431 }
432 $stParams = array_merge( $params, $this->powerSearchOptions() );
433
434 $suggest = Linker::linkKnown(
435 $this->getPageTitle(),
436 $textMatches->getSuggestionSnippet() ?: null,
437 array( 'id' => 'mw-search-DYM-suggestion' ),
438 $stParams
439 );
440
441 # HTML of did you mean... search suggestion link
442 return Html::rawElement(
443 'div',
444 array( 'class' => 'searchdidyoumean' ),
445 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
446 );
447 }
448
449 /**
450 * Generates HTML shown to user when their query has been internally rewritten,
451 * and the results of the rewritten query are being returned.
452 *
453 * @param string $term The users search input
454 * @param SearchResultSet $textMatches The response to the users initial search request
455 * @return string HTML linking the user to their original $term query, and the one
456 * suggested by $textMatches.
457 */
458 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet $textMatches ) {
459 // Showing results for '$rewritten'
460 // Search instead for '$orig'
461
462 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
463 if ( $this->fulltext != null ) {
464 $params['fulltext'] = $this->fulltext;
465 }
466 $stParams = array_merge( $params, $this->powerSearchOptions() );
467
468 $rewritten = Linker::linkKnown(
469 $this->getPageTitle(),
470 $textMatches->getQueryAfterRewriteSnippet() ?: null,
471 array( 'id' => 'mw-search-DYM-rewritten' ),
472 $stParams
473 );
474
475 $stParams['search'] = $term;
476 $stParams['runsuggestion'] = 0;
477 $original = Linker::linkKnown(
478 $this->getPageTitle(),
479 htmlspecialchars( $term ),
480 array( 'id' => 'mw-search-DYM-original' ),
481 $stParams
482 );
483
484 return Html::rawElement(
485 'div',
486 array( 'class' => 'searchdidyoumean' ),
487 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
488 );
489 }
490
491 /**
492 * @param Title $title
493 * @param int $num The number of search results found
494 * @param null|SearchResultSet $titleMatches Results from title search
495 * @param null|SearchResultSet $textMatches Results from text search
496 */
497 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
498 // show direct page/create link if applicable
499
500 // Check DBkey !== '' in case of fragment link only.
501 if ( is_null( $title ) || $title->getDBkey() === ''
502 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
503 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
504 ) {
505 // invalid title
506 // preserve the paragraph for margins etc...
507 $this->getOutput()->addHtml( '<p></p>' );
508
509 return;
510 }
511
512 $messageName = 'searchmenu-new-nocreate';
513 $linkClass = 'mw-search-createlink';
514
515 if ( !$title->isExternal() ) {
516 if ( $title->isKnown() ) {
517 $messageName = 'searchmenu-exists';
518 $linkClass = 'mw-search-exists';
519 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
520 $messageName = 'searchmenu-new';
521 }
522 }
523
524 $params = array(
525 $messageName,
526 wfEscapeWikiText( $title->getPrefixedText() ),
527 Message::numParam( $num )
528 );
529 Hooks::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
530
531 // Extensions using the hook might still return an empty $messageName
532 if ( $messageName ) {
533 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
534 } else {
535 // preserve the paragraph for margins etc...
536 $this->getOutput()->addHtml( '<p></p>' );
537 }
538 }
539
540 /**
541 * @param string $term
542 */
543 protected function setupPage( $term ) {
544 $out = $this->getOutput();
545 if ( strval( $term ) !== '' ) {
546 $out->setPageTitle( $this->msg( 'searchresults' ) );
547 $out->setHTMLTitle( $this->msg( 'pagetitle' )
548 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
549 ->inContentLanguage()->text()
550 );
551 }
552 // add javascript specific to special:search
553 $out->addModules( 'mediawiki.special.search' );
554 }
555
556 /**
557 * Return true if current search is a power (advanced) search
558 *
559 * @return bool
560 */
561 protected function isPowerSearch() {
562 return $this->profile === 'advanced';
563 }
564
565 /**
566 * Extract "power search" namespace settings from the request object,
567 * returning a list of index numbers to search.
568 *
569 * @param WebRequest $request
570 * @return array
571 */
572 protected function powerSearch( &$request ) {
573 $arr = array();
574 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
575 if ( $request->getCheck( 'ns' . $ns ) ) {
576 $arr[] = $ns;
577 }
578 }
579
580 return $arr;
581 }
582
583 /**
584 * Reconstruct the 'power search' options for links
585 *
586 * @return array
587 */
588 protected function powerSearchOptions() {
589 $opt = array();
590 if ( !$this->isPowerSearch() ) {
591 $opt['profile'] = $this->profile;
592 } else {
593 foreach ( $this->namespaces as $n ) {
594 $opt['ns' . $n] = 1;
595 }
596 }
597
598 return $opt + $this->extraParams;
599 }
600
601 /**
602 * Save namespace preferences when we're supposed to
603 *
604 * @return bool Whether we wrote something
605 */
606 protected function saveNamespaces() {
607 $user = $this->getUser();
608 $request = $this->getRequest();
609
610 if ( $user->isLoggedIn() &&
611 $user->matchEditToken(
612 $request->getVal( 'nsRemember' ),
613 'searchnamespace',
614 $request
615 ) && !wfReadOnly()
616 ) {
617 // Reset namespace preferences: namespaces are not searched
618 // when they're not mentioned in the URL parameters.
619 foreach ( MWNamespace::getValidNamespaces() as $n ) {
620 $user->setOption( 'searchNs' . $n, false );
621 }
622 // The request parameters include all the namespaces to be searched.
623 // Even if they're the same as an existing profile, they're not eaten.
624 foreach ( $this->namespaces as $n ) {
625 $user->setOption( 'searchNs' . $n, true );
626 }
627
628 $user->saveSettings();
629 return true;
630 }
631
632 return false;
633 }
634
635 /**
636 * Show whole set of results
637 *
638 * @param SearchResultSet $matches
639 *
640 * @return string
641 */
642 protected function showMatches( &$matches ) {
643 global $wgContLang;
644
645 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
646
647 $out = "<ul class='mw-search-results'>\n";
648 $result = $matches->next();
649 $pos = $this->offset;
650 while ( $result ) {
651 $out .= $this->showHit( $result, $terms, ++$pos );
652 $result = $matches->next();
653 }
654 $out .= "</ul>\n";
655
656 // convert the whole thing to desired language variant
657 $out = $wgContLang->convert( $out );
658
659 return $out;
660 }
661
662 /**
663 * Format a single hit result
664 *
665 * @param SearchResult $result
666 * @param array $terms Terms to highlight
667 * @param int $position Position within the search results, including offset.
668 *
669 * @return string
670 */
671 protected function showHit( $result, $terms, $position ) {
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 array( 'data-serp-pos' => $position ) // HTML attributes
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 }