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