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