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