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