Merge "Revert "Limit searches at 500 per page""
[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 );
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(), 'private' );
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 $showSuggestion = $t === null || !$t->isKnown();
257 $search->setShowSuggestion( $showSuggestion );
258
259 // fetch search results
260 $rewritten = $search->replacePrefixes( $term );
261
262 $titleMatches = $search->searchTitle( $rewritten );
263 if ( !( $titleMatches instanceof SearchResultTooMany ) ) {
264 $textMatches = $search->searchText( $rewritten );
265 }
266
267 $textStatus = null;
268 if ( $textMatches instanceof Status ) {
269 $textStatus = $textMatches;
270 $textMatches = null;
271 }
272
273 // did you mean... suggestions
274 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
275 $st = SpecialPage::getTitleFor( 'Search' );
276
277 # mirror Go/Search behavior of original request ..
278 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
279
280 if ( $this->fulltext != null ) {
281 $didYouMeanParams['fulltext'] = $this->fulltext;
282 }
283
284 $stParams = array_merge(
285 $didYouMeanParams,
286 $this->powerSearchOptions()
287 );
288
289 $suggestionSnippet = $textMatches->getSuggestionSnippet();
290
291 if ( $suggestionSnippet == '' ) {
292 $suggestionSnippet = null;
293 }
294
295 $suggestLink = Linker::linkKnown(
296 $st,
297 $suggestionSnippet,
298 array(),
299 $stParams
300 );
301
302 $this->didYouMeanHtml = '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
303 }
304
305 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
306 # Hook requested termination
307 wfProfileOut( __METHOD__ );
308 return;
309 }
310
311 // start rendering the page
312 $out->addHtml(
313 Xml::openElement(
314 'form',
315 array(
316 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
317 'method' => 'get',
318 'action' => $wgScript
319 )
320 )
321 );
322 $out->addHtml(
323 # This is an awful awful ID name. It's not a table, but we
324 # named it poorly from when this was a table so now we're
325 # stuck with it
326 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
327 $this->shortDialog( $term ) .
328 Xml::closeElement( 'div' )
329 );
330
331 // Sometimes the search engine knows there are too many hits
332 if ( $titleMatches instanceof SearchResultTooMany ) {
333 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
334 wfProfileOut( __METHOD__ );
335 return;
336 }
337
338 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
339 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
340 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
341 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
342 $out->addHTML( '</form>' );
343 // Empty query -- straight view of search form
344 wfProfileOut( __METHOD__ );
345 return;
346 }
347
348 // Get number of results
349 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
350 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
351 // Total initial query matches (possible false positives)
352 $num = $titleMatchesNum + $textMatchesNum;
353
354 // Get total actual results (after second filtering, if any)
355 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
356 $titleMatches->getTotalHits() : $titleMatchesNum;
357 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
358 $textMatches->getTotalHits() : $textMatchesNum;
359
360 // get total number of results if backend can calculate it
361 $totalRes = 0;
362 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
363 $totalRes += $titleMatches->getTotalHits();
364 }
365 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
366 $totalRes += $textMatches->getTotalHits();
367 }
368
369 // show number of results and current offset
370 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
371 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
372
373 $out->addHtml( Xml::closeElement( 'form' ) );
374 $out->addHtml( "<div class='searchresults'>" );
375
376 // prev/next links
377 if ( $num || $this->offset ) {
378 // Show the create link ahead
379 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
380 $prevnext = $this->getLanguage()->viewPrevNext( $this->getPageTitle(), $this->offset, $this->limit,
381 $this->powerSearchOptions() + array( 'search' => $term ),
382 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
383 );
384 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
385 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
386 } else {
387 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
388 }
389
390 $out->parserOptions()->setEditSection( false );
391 if ( $titleMatches ) {
392 if ( $numTitleMatches > 0 ) {
393 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
394 $out->addHTML( $this->showMatches( $titleMatches ) );
395 }
396 $titleMatches->free();
397 }
398 if ( $textMatches && !$textStatus ) {
399 // output appropriate heading
400 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
401 // if no title matches the heading is redundant
402 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
403 } elseif ( $totalRes == 0 ) {
404 # Don't show the 'no text matches' if we received title matches
405 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
406 }
407 // show interwiki results if any
408 if ( $textMatches->hasInterwikiResults() ) {
409 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
410 }
411 // show results
412 if ( $numTextMatches > 0 ) {
413 $out->addHTML( $this->showMatches( $textMatches ) );
414 }
415
416 $textMatches->free();
417 }
418 if ( $num === 0 ) {
419 if ( $textStatus ) {
420 $out->addHTML( '<div class="error">' .
421 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
422 } else {
423 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
424 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
425 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
426 }
427 }
428 $out->addHtml( "</div>" );
429
430 if ( $num || $this->offset ) {
431 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
432 }
433 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
434 wfProfileOut( __METHOD__ );
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 // invalid title
451 // preserve the paragraph for margins etc...
452 $this->getOutput()->addHtml( '<p></p>' );
453 return;
454 }
455
456 if ( $t->isKnown() ) {
457 $messageName = 'searchmenu-exists';
458 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
459 $messageName = 'searchmenu-new';
460 } else {
461 $messageName = 'searchmenu-new-nocreate';
462 }
463 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message::numParam( $num ) );
464 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
465
466 // Extensions using the hook might still return an empty $messageName
467 if ( $messageName ) {
468 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
469 } else {
470 // preserve the paragraph for margins etc...
471 $this->getOutput()->addHtml( '<p></p>' );
472 }
473 }
474
475 /**
476 * @param $term string
477 */
478 protected function setupPage( $term ) {
479 # Should advanced UI be used?
480 $this->searchAdvanced = ( $this->profile === 'advanced' );
481 $out = $this->getOutput();
482 if ( strval( $term ) !== '' ) {
483 $out->setPageTitle( $this->msg( 'searchresults' ) );
484 $out->setHTMLTitle( $this->msg( 'pagetitle' )
485 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
486 ->inContentLanguage()->text()
487 );
488 }
489 // add javascript specific to special:search
490 $out->addModules( 'mediawiki.special.search' );
491 }
492
493 /**
494 * Extract "power search" namespace settings from the request object,
495 * returning a list of index numbers to search.
496 *
497 * @param $request WebRequest
498 * @return Array
499 */
500 protected function powerSearch( &$request ) {
501 $arr = array();
502 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
503 if ( $request->getCheck( 'ns' . $ns ) ) {
504 $arr[] = $ns;
505 }
506 }
507
508 return $arr;
509 }
510
511 /**
512 * Reconstruct the 'power search' options for links
513 *
514 * @return Array
515 */
516 protected function powerSearchOptions() {
517 $opt = array();
518 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
519 if ( $this->profile !== 'advanced' ) {
520 $opt['profile'] = $this->profile;
521 } else {
522 foreach ( $this->namespaces as $n ) {
523 $opt['ns' . $n] = 1;
524 }
525 }
526 return $opt + $this->extraParams;
527 }
528
529 /**
530 * Show whole set of results
531 *
532 * @param $matches SearchResultSet
533 *
534 * @return string
535 */
536 protected function showMatches( &$matches ) {
537 global $wgContLang;
538 wfProfileIn( __METHOD__ );
539
540 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
541
542 $out = "";
543 $infoLine = $matches->getInfo();
544 if ( !is_null( $infoLine ) ) {
545 $out .= "\n<!-- {$infoLine} -->\n";
546 }
547 $out .= "<ul class='mw-search-results'>\n";
548 $result = $matches->next();
549 while ( $result ) {
550 $out .= $this->showHit( $result, $terms );
551 $result = $matches->next();
552 }
553 $out .= "</ul>\n";
554
555 // convert the whole thing to desired language variant
556 $out = $wgContLang->convert( $out );
557 wfProfileOut( __METHOD__ );
558 return $out;
559 }
560
561 /**
562 * Format a single hit result
563 *
564 * @param $result SearchResult
565 * @param array $terms terms to highlight
566 *
567 * @return string
568 */
569 protected function showHit( $result, $terms ) {
570 wfProfileIn( __METHOD__ );
571
572 if ( $result->isBrokenTitle() ) {
573 wfProfileOut( __METHOD__ );
574 return "<!-- Broken link in search result -->\n";
575 }
576
577 $t = $result->getTitle();
578
579 $titleSnippet = $result->getTitleSnippet( $terms );
580
581 if ( $titleSnippet == '' ) {
582 $titleSnippet = null;
583 }
584
585 $link_t = clone $t;
586
587 wfRunHooks( 'ShowSearchHitTitle',
588 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
589
590 $link = Linker::linkKnown(
591 $link_t,
592 $titleSnippet
593 );
594
595 //If page content is not readable, just return the title.
596 //This is not quite safe, but better than showing excerpts from non-readable pages
597 //Note that hiding the entry entirely would screw up paging.
598 if ( !$t->userCan( 'read', $this->getUser() ) ) {
599 wfProfileOut( __METHOD__ );
600 return "<li>{$link}</li>\n";
601 }
602
603 // If the page doesn't *exist*... our search index is out of date.
604 // The least confusing at this point is to drop the result.
605 // You may get less results, but... oh well. :P
606 if ( $result->isMissingRevision() ) {
607 wfProfileOut( __METHOD__ );
608 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
609 }
610
611 // format redirects / relevant sections
612 $redirectTitle = $result->getRedirectTitle();
613 $redirectText = $result->getRedirectSnippet( $terms );
614 $sectionTitle = $result->getSectionTitle();
615 $sectionText = $result->getSectionSnippet( $terms );
616 $redirect = '';
617
618 if ( !is_null( $redirectTitle ) ) {
619 if ( $redirectText == '' ) {
620 $redirectText = null;
621 }
622
623 $redirect = "<span class='searchalttitle'>" .
624 $this->msg( 'search-redirect' )->rawParams(
625 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
626 "</span>";
627 }
628
629 $section = '';
630
631 if ( !is_null( $sectionTitle ) ) {
632 if ( $sectionText == '' ) {
633 $sectionText = null;
634 }
635
636 $section = "<span class='searchalttitle'>" .
637 $this->msg( 'search-section' )->rawParams(
638 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
639 "</span>";
640 }
641
642 // format text extract
643 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
644
645 $lang = $this->getLanguage();
646
647 // format score
648 if ( is_null( $result->getScore() ) ) {
649 // Search engine doesn't report scoring info
650 $score = '';
651 } else {
652 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
653 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
654 . ' - ';
655 }
656
657 // format description
658 $byteSize = $result->getByteSize();
659 $wordCount = $result->getWordCount();
660 $timestamp = $result->getTimestamp();
661 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
662 ->numParams( $wordCount )->escaped();
663
664 if ( $t->getNamespace() == NS_CATEGORY ) {
665 $cat = Category::newFromTitle( $t );
666 $size = $this->msg( 'search-result-category-size' )
667 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
668 ->escaped();
669 }
670
671 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
672
673 // link to related articles if supported
674 $related = '';
675 if ( $result->hasRelated() ) {
676 $st = SpecialPage::getTitleFor( 'Search' );
677 $stParams = array_merge(
678 $this->powerSearchOptions(),
679 array(
680 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
681 ':' . $t->getPrefixedText(),
682 'fulltext' => $this->msg( 'search' )->text()
683 )
684 );
685
686 $related = ' -- ' . Linker::linkKnown(
687 $st,
688 $this->msg( 'search-relatedarticle' )->text(),
689 array(),
690 $stParams
691 );
692 }
693
694 $fileMatch = '';
695 // Include a thumbnail for media files...
696 if ( $t->getNamespace() == NS_FILE ) {
697 $img = $result->getFile();
698 $img = $img ?: wfFindFile( $t );
699 if ( $result->isFileMatch() ) {
700 $fileMatch = "<span class='searchalttitle'>" .
701 $this->msg( 'search-file-match' )->escaped() . "</span>";
702 }
703 if ( $img ) {
704 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
705 if ( $thumb ) {
706 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
707 wfProfileOut( __METHOD__ );
708 // Float doesn't seem to interact well with the bullets.
709 // Table messes up vertical alignment of the bullets.
710 // Bullets are therefore disabled (didn't look great anyway).
711 return "<li>" .
712 '<table class="searchResultImage">' .
713 '<tr>' .
714 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
715 $thumb->toHtml( array( 'desc-link' => true ) ) .
716 '</td>' .
717 '<td style="vertical-align: top;">' .
718 "{$link} {$fileMatch}" .
719 $extract .
720 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
721 '</td>' .
722 '</tr>' .
723 '</table>' .
724 "</li>\n";
725 }
726 }
727 }
728
729 $html = null;
730
731 if ( wfRunHooks( 'ShowSearchHit', array(
732 $this, $result, $terms,
733 &$link, &$redirect, &$section, &$extract,
734 &$score, &$size, &$date, &$related,
735 &$html
736 ) ) ) {
737 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
738 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
739 "</li>\n";
740 }
741
742 wfProfileOut( __METHOD__ );
743 return $html;
744 }
745
746 /**
747 * Show results from other wikis
748 *
749 * @param $matches SearchResultSet
750 * @param $query String
751 *
752 * @return string
753 */
754 protected function showInterwiki( $matches, $query ) {
755 global $wgContLang;
756 wfProfileIn( __METHOD__ );
757 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
758
759 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
760 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
761 $out .= "<ul class='mw-search-iwresults'>\n";
762
763 // work out custom project captions
764 $customCaptions = array();
765 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
766 foreach ( $customLines as $line ) {
767 $parts = explode( ":", $line, 2 );
768 if ( count( $parts ) == 2 ) { // validate line
769 $customCaptions[$parts[0]] = $parts[1];
770 }
771 }
772
773 $prev = null;
774 $result = $matches->next();
775 while ( $result ) {
776 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
777 $prev = $result->getInterwikiPrefix();
778 $result = $matches->next();
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 wfProfileOut( __METHOD__ );
786 return $out;
787 }
788
789 /**
790 * Show single interwiki link
791 *
792 * @param $result SearchResult
793 * @param $lastInterwiki String
794 * @param $terms Array
795 * @param $query String
796 * @param array $customCaptions iw prefix -> caption
797 *
798 * @return string
799 */
800 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
801 wfProfileIn( __METHOD__ );
802
803 if ( $result->isBrokenTitle() ) {
804 wfProfileOut( __METHOD__ );
805 return "<!-- Broken link in search result -->\n";
806 }
807
808 $t = $result->getTitle();
809
810 $titleSnippet = $result->getTitleSnippet( $terms );
811
812 if ( $titleSnippet == '' ) {
813 $titleSnippet = null;
814 }
815
816 $link = Linker::linkKnown(
817 $t,
818 $titleSnippet
819 );
820
821 // format redirect if any
822 $redirectTitle = $result->getRedirectTitle();
823 $redirectText = $result->getRedirectSnippet( $terms );
824 $redirect = '';
825 if ( !is_null( $redirectTitle ) ) {
826 if ( $redirectText == '' ) {
827 $redirectText = null;
828 }
829
830 $redirect = "<span class='searchalttitle'>" .
831 $this->msg( 'search-redirect' )->rawParams(
832 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
833 "</span>";
834 }
835
836 $out = "";
837 // display project name
838 if ( is_null( $lastInterwiki ) || $lastInterwiki != $t->getInterwiki() ) {
839 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
840 // captions from 'search-interwiki-custom'
841 $caption = $customCaptions[$t->getInterwiki()];
842 } else {
843 // default is to show the hostname of the other wiki which might suck
844 // if there are many wikis on one hostname
845 $parsed = wfParseUrl( $t->getFullURL() );
846 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
847 }
848 // "more results" link (special page stuff could be localized, but we might not know target lang)
849 $searchTitle = Title::newFromText( $t->getInterwiki() . ":Special:Search" );
850 $searchLink = Linker::linkKnown(
851 $searchTitle,
852 $this->msg( 'search-interwiki-more' )->text(),
853 array(),
854 array(
855 'search' => $query,
856 'fulltext' => 'Search'
857 )
858 );
859 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
860 {$searchLink}</span>{$caption}</div>\n<ul>";
861 }
862
863 $out .= "<li>{$link} {$redirect}</li>\n";
864 wfProfileOut( __METHOD__ );
865 return $out;
866 }
867
868 /**
869 * @param $profile
870 * @param $term
871 * @return String
872 */
873 protected function getProfileForm( $profile, $term ) {
874 // Hidden stuff
875 $opts = array();
876 $opts['redirs'] = $this->searchRedirects;
877 $opts['profile'] = $this->profile;
878
879 if ( $profile === 'advanced' ) {
880 return $this->powerSearchBox( $term, $opts );
881 } else {
882 $form = '';
883 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
884 return $form;
885 }
886 }
887
888 /**
889 * Generates the power search box at [[Special:Search]]
890 *
891 * @param string $term search term
892 * @param $opts array
893 * @return String: HTML form
894 */
895 protected function powerSearchBox( $term, $opts ) {
896 global $wgContLang;
897
898 // Groups namespaces into rows according to subject
899 $rows = array();
900 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
901 $subject = MWNamespace::getSubject( $namespace );
902 if ( !array_key_exists( $subject, $rows ) ) {
903 $rows[$subject] = "";
904 }
905
906 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
907 if ( $name == '' ) {
908 $name = $this->msg( 'blanknamespace' )->text();
909 }
910
911 $rows[$subject] .=
912 Xml::openElement(
913 'td', array( 'style' => 'white-space: nowrap' )
914 ) .
915 Xml::checkLabel(
916 $name,
917 "ns{$namespace}",
918 "mw-search-ns{$namespace}",
919 in_array( $namespace, $this->namespaces )
920 ) .
921 Xml::closeElement( 'td' );
922 }
923
924 $rows = array_values( $rows );
925 $numRows = count( $rows );
926
927 // Lays out namespaces in multiple floating two-column tables so they'll
928 // be arranged nicely while still accommodating different screen widths
929 $namespaceTables = '';
930 for ( $i = 0; $i < $numRows; $i += 4 ) {
931 $namespaceTables .= Xml::openElement(
932 'table',
933 array( 'cellpadding' => 0, 'cellspacing' => 0 )
934 );
935
936 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
937 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
938 }
939
940 $namespaceTables .= Xml::closeElement( 'table' );
941 }
942
943 $showSections = array( 'namespaceTables' => $namespaceTables );
944
945 // Show redirects check only if backend supports it
946 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
947 $showSections['redirects'] =
948 Xml::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects );
949 }
950
951 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
952
953 $hidden = '';
954 unset( $opts['redirs'] );
955 foreach ( $opts as $key => $value ) {
956 $hidden .= Html::hidden( $key, $value );
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 return $out . $this->didYouMeanHtml;
1119 }
1120
1121 /**
1122 * Make a search link with some target namespaces
1123 *
1124 * @param $term String
1125 * @param array $namespaces ignored
1126 * @param string $label link's text
1127 * @param string $tooltip link's tooltip
1128 * @param array $params query string parameters
1129 * @return String: HTML fragment
1130 */
1131 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1132 $opt = $params;
1133 foreach ( $namespaces as $n ) {
1134 $opt['ns' . $n] = 1;
1135 }
1136 $opt['redirs'] = $this->searchRedirects;
1137
1138 $stParams = array_merge(
1139 array(
1140 'search' => $term,
1141 'fulltext' => $this->msg( 'search' )->text()
1142 ),
1143 $opt
1144 );
1145
1146 return Xml::element(
1147 'a',
1148 array(
1149 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1150 'title' => $tooltip
1151 ),
1152 $label
1153 );
1154 }
1155
1156 /**
1157 * Check if query starts with image: prefix
1158 *
1159 * @param string $term the string to check
1160 * @return Boolean
1161 */
1162 protected function startsWithImage( $term ) {
1163 global $wgContLang;
1164
1165 $p = explode( ':', $term );
1166 if ( count( $p ) > 1 ) {
1167 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1168 }
1169 return false;
1170 }
1171
1172 /**
1173 * Check if query starts with all: prefix
1174 *
1175 * @param string $term the string to check
1176 * @return Boolean
1177 */
1178 protected function startsWithAll( $term ) {
1179
1180 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1181
1182 $p = explode( ':', $term );
1183 if ( count( $p ) > 1 ) {
1184 return $p[0] == $allkeyword;
1185 }
1186 return false;
1187 }
1188
1189 /**
1190 * @since 1.18
1191 *
1192 * @return SearchEngine
1193 */
1194 public function getSearchEngine() {
1195 if ( $this->searchEngine === null ) {
1196 $this->searchEngine = $this->searchEngineType ?
1197 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1198 }
1199 return $this->searchEngine;
1200 }
1201
1202 /**
1203 * Current search profile.
1204 * @return null|string
1205 */
1206 function getProfile() {
1207 return $this->profile;
1208 }
1209
1210 /**
1211 * Current namespaces.
1212 * @return array
1213 */
1214 function getNamespaces() {
1215 return $this->namespaces;
1216 }
1217
1218 /**
1219 * Users of hook SpecialSearchSetupEngine can use this to
1220 * add more params to links to not lose selection when
1221 * user navigates search results.
1222 * @since 1.18
1223 *
1224 * @param $key
1225 * @param $value
1226 */
1227 public function setExtraParam( $key, $value ) {
1228 $this->extraParams[$key] = $value;
1229 }
1230
1231 protected function getGroupName() {
1232 return 'pages';
1233 }
1234 }