Include additional analytics in Special:Search
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 /**
3 * Implements Special:Search
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
29 */
30 class SpecialSearch extends SpecialPage {
31 /**
32 * Current search profile. Search profile is just a name that identifies
33 * the active search tab on the search page (content, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
37 * @var null|string
38 */
39 protected $profile;
40
41 /** @var SearchEngine Search engine */
42 protected $searchEngine;
43
44 /** @var string Search engine type, if not default */
45 protected $searchEngineType;
46
47 /** @var array For links */
48 protected $extraParams = array();
49
50 /**
51 * @var string The prefix url parameter. Set on the searcher and the
52 * is expected to treat it as prefix filter on titles.
53 */
54 protected $mPrefix;
55
56 /**
57 * @var int
58 */
59 protected $limit, $offset;
60
61 /**
62 * @var array
63 */
64 protected $namespaces;
65
66 /**
67 * @var string
68 */
69 protected $fulltext;
70
71 /**
72 * @var bool
73 */
74 protected $runSuggestion = true;
75
76 const NAMESPACES_CURRENT = 'sense';
77
78 public function __construct() {
79 parent::__construct( 'Search' );
80 }
81
82 /**
83 * Entry point
84 *
85 * @param string $par
86 */
87 public function execute( $par ) {
88 $this->setHeaders();
89 $this->outputHeader();
90 $out = $this->getOutput();
91 $out->allowClickjacking();
92 $out->addModuleStyles( array(
93 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button',
94 'mediawiki.ui.input',
95 ) );
96
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 ) );
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->getQueryAfterRewrite() );
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->getQueryAfterRewriteSnippet() ?: 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 $pos = $this->offset;
653 while ( $result ) {
654 $out .= $this->showHit( $result, $terms, ++$pos );
655 $result = $matches->next();
656 }
657 $out .= "</ul>\n";
658
659 // convert the whole thing to desired language variant
660 $out = $wgContLang->convert( $out );
661
662 return $out;
663 }
664
665 /**
666 * Format a single hit result
667 *
668 * @param SearchResult $result
669 * @param array $terms Terms to highlight
670 * @param int $position Position within the search results, including offset.
671 *
672 * @return string
673 */
674 protected function showHit( $result, $terms, $position ) {
675
676 if ( $result->isBrokenTitle() ) {
677 return '';
678 }
679
680 $title = $result->getTitle();
681
682 $titleSnippet = $result->getTitleSnippet();
683
684 if ( $titleSnippet == '' ) {
685 $titleSnippet = null;
686 }
687
688 $link_t = clone $title;
689
690 Hooks::run( 'ShowSearchHitTitle',
691 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
692
693 $link = Linker::linkKnown(
694 $link_t,
695 $titleSnippet,
696 array( 'data-serp-pos' => $position ) // HTML attributes
697 );
698
699 //If page content is not readable, just return the title.
700 //This is not quite safe, but better than showing excerpts from non-readable pages
701 //Note that hiding the entry entirely would screw up paging.
702 if ( !$title->userCan( 'read', $this->getUser() ) ) {
703 return "<li>{$link}</li>\n";
704 }
705
706 // If the page doesn't *exist*... our search index is out of date.
707 // The least confusing at this point is to drop the result.
708 // You may get less results, but... oh well. :P
709 if ( $result->isMissingRevision() ) {
710 return '';
711 }
712
713 // format redirects / relevant sections
714 $redirectTitle = $result->getRedirectTitle();
715 $redirectText = $result->getRedirectSnippet();
716 $sectionTitle = $result->getSectionTitle();
717 $sectionText = $result->getSectionSnippet();
718 $categorySnippet = $result->getCategorySnippet();
719
720 $redirect = '';
721 if ( !is_null( $redirectTitle ) ) {
722 if ( $redirectText == '' ) {
723 $redirectText = null;
724 }
725
726 $redirect = "<span class='searchalttitle'>" .
727 $this->msg( 'search-redirect' )->rawParams(
728 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
729 "</span>";
730 }
731
732 $section = '';
733 if ( !is_null( $sectionTitle ) ) {
734 if ( $sectionText == '' ) {
735 $sectionText = null;
736 }
737
738 $section = "<span class='searchalttitle'>" .
739 $this->msg( 'search-section' )->rawParams(
740 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
741 "</span>";
742 }
743
744 $category = '';
745 if ( $categorySnippet ) {
746 $category = "<span class='searchalttitle'>" .
747 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
748 "</span>";
749 }
750
751 // format text extract
752 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
753
754 $lang = $this->getLanguage();
755
756 // format description
757 $byteSize = $result->getByteSize();
758 $wordCount = $result->getWordCount();
759 $timestamp = $result->getTimestamp();
760 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
761 ->numParams( $wordCount )->escaped();
762
763 if ( $title->getNamespace() == NS_CATEGORY ) {
764 $cat = Category::newFromTitle( $title );
765 $size = $this->msg( 'search-result-category-size' )
766 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
767 ->escaped();
768 }
769
770 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
771
772 $fileMatch = '';
773 // Include a thumbnail for media files...
774 if ( $title->getNamespace() == NS_FILE ) {
775 $img = $result->getFile();
776 $img = $img ?: wfFindFile( $title );
777 if ( $result->isFileMatch() ) {
778 $fileMatch = "<span class='searchalttitle'>" .
779 $this->msg( 'search-file-match' )->escaped() . "</span>";
780 }
781 if ( $img ) {
782 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
783 if ( $thumb ) {
784 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
785 // Float doesn't seem to interact well with the bullets.
786 // Table messes up vertical alignment of the bullets.
787 // Bullets are therefore disabled (didn't look great anyway).
788 return "<li>" .
789 '<table class="searchResultImage">' .
790 '<tr>' .
791 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
792 $thumb->toHtml( array( 'desc-link' => true ) ) .
793 '</td>' .
794 '<td style="vertical-align: top;">' .
795 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
796 $extract .
797 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
798 '</td>' .
799 '</tr>' .
800 '</table>' .
801 "</li>\n";
802 }
803 }
804 }
805
806 $html = null;
807
808 $score = '';
809 if ( Hooks::run( 'ShowSearchHit', array(
810 $this, $result, $terms,
811 &$link, &$redirect, &$section, &$extract,
812 &$score, &$size, &$date, &$related,
813 &$html
814 ) ) ) {
815 $html = "<li><div class='mw-search-result-heading'>" .
816 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
817 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
818 "</li>\n";
819 }
820
821 return $html;
822 }
823
824 /**
825 * Show results from other wikis
826 *
827 * @param SearchResultSet|array $matches
828 * @param string $query
829 *
830 * @return string
831 */
832 protected function showInterwiki( $matches, $query ) {
833 global $wgContLang;
834
835 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
836 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
837 $out .= "<ul class='mw-search-iwresults'>\n";
838
839 // work out custom project captions
840 $customCaptions = array();
841 // format per line <iwprefix>:<caption>
842 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
843 foreach ( $customLines as $line ) {
844 $parts = explode( ":", $line, 2 );
845 if ( count( $parts ) == 2 ) { // validate line
846 $customCaptions[$parts[0]] = $parts[1];
847 }
848 }
849
850 if ( !is_array( $matches ) ) {
851 $matches = array( $matches );
852 }
853
854 foreach ( $matches as $set ) {
855 $prev = null;
856 $result = $set->next();
857 while ( $result ) {
858 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
859 $prev = $result->getInterwikiPrefix();
860 $result = $set->next();
861 }
862 }
863
864 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
865 $out .= "</ul></div>\n";
866
867 // convert the whole thing to desired language variant
868 $out = $wgContLang->convert( $out );
869
870 return $out;
871 }
872
873 /**
874 * Show single interwiki link
875 *
876 * @param SearchResult $result
877 * @param string $lastInterwiki
878 * @param string $query
879 * @param array $customCaptions Interwiki prefix -> caption
880 *
881 * @return string
882 */
883 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
884
885 if ( $result->isBrokenTitle() ) {
886 return '';
887 }
888
889 $title = $result->getTitle();
890
891 $titleSnippet = $result->getTitleSnippet();
892
893 if ( $titleSnippet == '' ) {
894 $titleSnippet = null;
895 }
896
897 $link = Linker::linkKnown(
898 $title,
899 $titleSnippet
900 );
901
902 // format redirect if any
903 $redirectTitle = $result->getRedirectTitle();
904 $redirectText = $result->getRedirectSnippet();
905 $redirect = '';
906 if ( !is_null( $redirectTitle ) ) {
907 if ( $redirectText == '' ) {
908 $redirectText = null;
909 }
910
911 $redirect = "<span class='searchalttitle'>" .
912 $this->msg( 'search-redirect' )->rawParams(
913 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
914 "</span>";
915 }
916
917 $out = "";
918 // display project name
919 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
920 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
921 // captions from 'search-interwiki-custom'
922 $caption = $customCaptions[$title->getInterwiki()];
923 } else {
924 // default is to show the hostname of the other wiki which might suck
925 // if there are many wikis on one hostname
926 $parsed = wfParseUrl( $title->getFullURL() );
927 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
928 }
929 // "more results" link (special page stuff could be localized, but we might not know target lang)
930 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
931 $searchLink = Linker::linkKnown(
932 $searchTitle,
933 $this->msg( 'search-interwiki-more' )->text(),
934 array(),
935 array(
936 'search' => $query,
937 'fulltext' => 'Search'
938 )
939 );
940 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
941 {$searchLink}</span>{$caption}</div>\n<ul>";
942 }
943
944 $out .= "<li>{$link} {$redirect}</li>\n";
945
946 return $out;
947 }
948
949 /**
950 * Generates the power search box at [[Special:Search]]
951 *
952 * @param string $term Search term
953 * @param array $opts
954 * @return string HTML form
955 */
956 protected function powerSearchBox( $term, $opts ) {
957 global $wgContLang;
958
959 // Groups namespaces into rows according to subject
960 $rows = array();
961 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
962 $subject = MWNamespace::getSubject( $namespace );
963 if ( !array_key_exists( $subject, $rows ) ) {
964 $rows[$subject] = "";
965 }
966
967 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
968 if ( $name == '' ) {
969 $name = $this->msg( 'blanknamespace' )->text();
970 }
971
972 $rows[$subject] .=
973 Xml::openElement( 'td' ) .
974 Xml::checkLabel(
975 $name,
976 "ns{$namespace}",
977 "mw-search-ns{$namespace}",
978 in_array( $namespace, $this->namespaces )
979 ) .
980 Xml::closeElement( 'td' );
981 }
982
983 $rows = array_values( $rows );
984 $numRows = count( $rows );
985
986 // Lays out namespaces in multiple floating two-column tables so they'll
987 // be arranged nicely while still accommodating different screen widths
988 $namespaceTables = '';
989 for ( $i = 0; $i < $numRows; $i += 4 ) {
990 $namespaceTables .= Xml::openElement( 'table' );
991
992 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
993 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
994 }
995
996 $namespaceTables .= Xml::closeElement( 'table' );
997 }
998
999 $showSections = array( 'namespaceTables' => $namespaceTables );
1000
1001 Hooks::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1002
1003 $hidden = '';
1004 foreach ( $opts as $key => $value ) {
1005 $hidden .= Html::hidden( $key, $value );
1006 }
1007
1008 # Stuff to feed saveNamespaces()
1009 $remember = '';
1010 $user = $this->getUser();
1011 if ( $user->isLoggedIn() ) {
1012 $remember .= Xml::checkLabel(
1013 $this->msg( 'powersearch-remember' )->text(),
1014 'nsRemember',
1015 'mw-search-powersearch-remember',
1016 false,
1017 // The token goes here rather than in a hidden field so it
1018 // is only sent when necessary (not every form submission).
1019 array( 'value' => $user->getEditToken(
1020 'searchnamespace',
1021 $this->getRequest()
1022 ) )
1023 );
1024 }
1025
1026 // Return final output
1027 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1028 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1029 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1030 Xml::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1031 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1032 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1033 $hidden .
1034 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1035 $remember .
1036 Xml::closeElement( 'fieldset' );
1037 }
1038
1039 /**
1040 * @return array
1041 */
1042 protected function getSearchProfiles() {
1043 // Builds list of Search Types (profiles)
1044 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
1045
1046 $profiles = array(
1047 'default' => array(
1048 'message' => 'searchprofile-articles',
1049 'tooltip' => 'searchprofile-articles-tooltip',
1050 'namespaces' => SearchEngine::defaultNamespaces(),
1051 'namespace-messages' => SearchEngine::namespacesAsText(
1052 SearchEngine::defaultNamespaces()
1053 ),
1054 ),
1055 'images' => array(
1056 'message' => 'searchprofile-images',
1057 'tooltip' => 'searchprofile-images-tooltip',
1058 'namespaces' => array( NS_FILE ),
1059 ),
1060 'all' => array(
1061 'message' => 'searchprofile-everything',
1062 'tooltip' => 'searchprofile-everything-tooltip',
1063 'namespaces' => $nsAllSet,
1064 ),
1065 'advanced' => array(
1066 'message' => 'searchprofile-advanced',
1067 'tooltip' => 'searchprofile-advanced-tooltip',
1068 'namespaces' => self::NAMESPACES_CURRENT,
1069 )
1070 );
1071
1072 Hooks::run( 'SpecialSearchProfiles', array( &$profiles ) );
1073
1074 foreach ( $profiles as &$data ) {
1075 if ( !is_array( $data['namespaces'] ) ) {
1076 continue;
1077 }
1078 sort( $data['namespaces'] );
1079 }
1080
1081 return $profiles;
1082 }
1083
1084 /**
1085 * @param string $term
1086 * @return string
1087 */
1088 protected function searchProfileTabs( $term ) {
1089 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1090
1091 $bareterm = $term;
1092 if ( $this->startsWithImage( $term ) ) {
1093 // Deletes prefixes
1094 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1095 }
1096
1097 $profiles = $this->getSearchProfiles();
1098 $lang = $this->getLanguage();
1099
1100 // Outputs XML for Search Types
1101 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1102 $out .= Xml::openElement( 'ul' );
1103 foreach ( $profiles as $id => $profile ) {
1104 if ( !isset( $profile['parameters'] ) ) {
1105 $profile['parameters'] = array();
1106 }
1107 $profile['parameters']['profile'] = $id;
1108
1109 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1110 $lang->commaList( $profile['namespace-messages'] ) : null;
1111 $out .= Xml::tags(
1112 'li',
1113 array(
1114 'class' => $this->profile === $id ? 'current' : 'normal'
1115 ),
1116 $this->makeSearchLink(
1117 $bareterm,
1118 array(),
1119 $this->msg( $profile['message'] )->text(),
1120 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1121 $profile['parameters']
1122 )
1123 );
1124 }
1125 $out .= Xml::closeElement( 'ul' );
1126 $out .= Xml::closeElement( 'div' );
1127 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1128 $out .= Xml::closeElement( 'div' );
1129
1130 return $out;
1131 }
1132
1133 /**
1134 * @param string $term Search term
1135 * @return string
1136 */
1137 protected function searchOptions( $term ) {
1138 $out = '';
1139 $opts = array();
1140 $opts['profile'] = $this->profile;
1141
1142 if ( $this->isPowerSearch() ) {
1143 $out .= $this->powerSearchBox( $term, $opts );
1144 } else {
1145 $form = '';
1146 Hooks::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1147 $out .= $form;
1148 }
1149
1150 return $out;
1151 }
1152
1153 /**
1154 * @param string $term
1155 * @param int $resultsShown
1156 * @param int $totalNum
1157 * @return string
1158 */
1159 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1160 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1161 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1162 // Term box
1163 $out .= Html::input( 'search', $term, 'search', array(
1164 'id' => $this->isPowerSearch() ? 'powerSearchText' : 'searchText',
1165 'size' => '50',
1166 'autofocus' => trim( $term ) === '',
1167 'class' => 'mw-ui-input mw-ui-input-inline',
1168 ) ) . "\n";
1169 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1170 $out .= Html::submitButton(
1171 $this->msg( 'searchbutton' )->text(),
1172 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1173 array( 'mw-ui-progressive' )
1174 ) . "\n";
1175
1176 // Results-info
1177 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1178 $top = $this->msg( 'search-showingresults' )
1179 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1180 ->numParams( $resultsShown )
1181 ->parse();
1182 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1183 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1184 }
1185
1186 return $out;
1187 }
1188
1189 /**
1190 * Make a search link with some target namespaces
1191 *
1192 * @param string $term
1193 * @param array $namespaces Ignored
1194 * @param string $label Link's text
1195 * @param string $tooltip Link's tooltip
1196 * @param array $params Query string parameters
1197 * @return string HTML fragment
1198 */
1199 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1200 $opt = $params;
1201 foreach ( $namespaces as $n ) {
1202 $opt['ns' . $n] = 1;
1203 }
1204
1205 $stParams = array_merge(
1206 array(
1207 'search' => $term,
1208 'fulltext' => $this->msg( 'search' )->text()
1209 ),
1210 $opt
1211 );
1212
1213 return Xml::element(
1214 'a',
1215 array(
1216 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1217 'title' => $tooltip
1218 ),
1219 $label
1220 );
1221 }
1222
1223 /**
1224 * Check if query starts with image: prefix
1225 *
1226 * @param string $term The string to check
1227 * @return bool
1228 */
1229 protected function startsWithImage( $term ) {
1230 global $wgContLang;
1231
1232 $parts = explode( ':', $term );
1233 if ( count( $parts ) > 1 ) {
1234 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1235 }
1236
1237 return false;
1238 }
1239
1240 /**
1241 * Check if query starts with all: prefix
1242 *
1243 * @param string $term The string to check
1244 * @return bool
1245 */
1246 protected function startsWithAll( $term ) {
1247
1248 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1249
1250 $parts = explode( ':', $term );
1251 if ( count( $parts ) > 1 ) {
1252 return $parts[0] == $allkeyword;
1253 }
1254
1255 return false;
1256 }
1257
1258 /**
1259 * @since 1.18
1260 *
1261 * @return SearchEngine
1262 */
1263 public function getSearchEngine() {
1264 if ( $this->searchEngine === null ) {
1265 $this->searchEngine = $this->searchEngineType ?
1266 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1267 }
1268
1269 return $this->searchEngine;
1270 }
1271
1272 /**
1273 * Current search profile.
1274 * @return null|string
1275 */
1276 function getProfile() {
1277 return $this->profile;
1278 }
1279
1280 /**
1281 * Current namespaces.
1282 * @return array
1283 */
1284 function getNamespaces() {
1285 return $this->namespaces;
1286 }
1287
1288 /**
1289 * Users of hook SpecialSearchSetupEngine can use this to
1290 * add more params to links to not lose selection when
1291 * user navigates search results.
1292 * @since 1.18
1293 *
1294 * @param string $key
1295 * @param mixed $value
1296 */
1297 public function setExtraParam( $key, $value ) {
1298 $this->extraParams[$key] = $value;
1299 }
1300
1301 protected function getGroupName() {
1302 return 'pages';
1303 }
1304 }