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