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