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