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