Remove "include redirects" option from search
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 /**
3 * Implements Special:Search
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
29 */
30 class SpecialSearch extends SpecialPage {
31 /**
32 * Current search profile. Search profile is just a name that identifies
33 * the active search tab on the search page (content, help, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
37 * null|string
38 */
39 protected $profile;
40
41 /// Search engine
42 protected $searchEngine;
43
44 /// Search engine type, if not default
45 protected $searchEngineType;
46
47 /// For links
48 protected $extraParams = array();
49
50 /// No idea, apparently used by some other classes
51 protected $mPrefix;
52
53 /**
54 * @var int
55 */
56 protected $limit, $offset;
57
58 /**
59 * @var array
60 */
61 protected $namespaces;
62
63 /**
64 * @var string
65 */
66 protected $didYouMeanHtml, $fulltext;
67
68 const NAMESPACES_CURRENT = 'sense';
69
70 public function __construct() {
71 parent::__construct( 'Search' );
72 }
73
74 /**
75 * Entry point
76 *
77 * @param string $par or null
78 */
79 public function execute( $par ) {
80 $this->setHeaders();
81 $this->outputHeader();
82 $out = $this->getOutput();
83 $out->allowClickjacking();
84 $out->addModuleStyles( array(
85 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button'
86 ) );
87
88 // Strip underscores from title parameter; most of the time we'll want
89 // text form here. But don't strip underscores from actual text params!
90 $titleParam = str_replace( '_', ' ', $par );
91
92 $request = $this->getRequest();
93
94 // Fetch the search term
95 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
96
97 $this->load();
98
99 $this->searchEngineType = $request->getVal( 'srbackend' );
100
101 if ( $request->getVal( 'fulltext' )
102 || !is_null( $request->getVal( 'offset' ) )
103 ) {
104 $this->showResults( $search );
105 } else {
106 $this->goResult( $search );
107 }
108 }
109
110 /**
111 * Set up basic search parameters from the request and user settings.
112 *
113 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
114 */
115 public function load() {
116 $request = $this->getRequest();
117 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20 );
118 $this->mPrefix = $request->getVal( 'prefix', '' );
119
120 $user = $this->getUser();
121
122 # Extract manually requested namespaces
123 $nslist = $this->powerSearch( $request );
124 if ( !count( $nslist ) ) {
125 # Fallback to user preference
126 $nslist = SearchEngine::userNamespaces( $user );
127 }
128
129 $profile = null;
130 if ( !count( $nslist ) ) {
131 $profile = 'default';
132 }
133
134 $profile = $request->getVal( 'profile', $profile );
135 $profiles = $this->getSearchProfiles();
136 if ( $profile === null ) {
137 // BC with old request format
138 $profile = 'advanced';
139 foreach ( $profiles as $key => $data ) {
140 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
141 $profile = $key;
142 }
143 }
144 $this->namespaces = $nslist;
145 } elseif ( $profile === 'advanced' ) {
146 $this->namespaces = $nslist;
147 } else {
148 if ( isset( $profiles[$profile]['namespaces'] ) ) {
149 $this->namespaces = $profiles[$profile]['namespaces'];
150 } else {
151 // Unknown profile requested
152 $profile = 'default';
153 $this->namespaces = $profiles['default']['namespaces'];
154 }
155 }
156
157 $this->didYouMeanHtml = ''; # html of did you mean... link
158 $this->fulltext = $request->getVal( 'fulltext' );
159 $this->profile = $profile;
160 }
161
162 /**
163 * If an exact title match can be found, jump straight ahead to it.
164 *
165 * @param $term String
166 */
167 public function goResult( $term ) {
168 $this->setupPage( $term );
169 # Try to go to page as entered.
170 $t = Title::newFromText( $term );
171 # If the string cannot be used to create a title
172 if ( is_null( $t ) ) {
173 $this->showResults( $term );
174 return;
175 }
176 # If there's an exact or very near match, jump right there.
177 $t = SearchEngine::getNearMatch( $term );
178
179 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
180 # Hook requested termination
181 return;
182 }
183
184 if ( !is_null( $t ) ) {
185 $this->getOutput()->redirect( $t->getFullURL() );
186 return;
187 }
188 # No match, generate an edit URL
189 $t = Title::newFromText( $term );
190 if ( !is_null( $t ) ) {
191 global $wgGoToEdit;
192 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
193 wfDebugLog( 'nogomatch', $t->getFullText(), 'private' );
194
195 # If the feature is enabled, go straight to the edit page
196 if ( $wgGoToEdit ) {
197 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
198 return;
199 }
200 }
201 $this->showResults( $term );
202 }
203
204 /**
205 * @param $term String
206 */
207 public function showResults( $term ) {
208 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
209 wfProfileIn( __METHOD__ );
210
211 $search = $this->getSearchEngine();
212 $search->setLimitOffset( $this->limit, $this->offset );
213 $search->setNamespaces( $this->namespaces );
214 $search->prefix = $this->mPrefix;
215 $term = $search->transformSearchTerm( $term );
216
217 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
218
219 $this->setupPage( $term );
220
221 $out = $this->getOutput();
222
223 if ( $wgDisableTextSearch ) {
224 if ( $wgSearchForwardUrl ) {
225 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
226 $out->redirect( $url );
227 } else {
228 $out->addHTML(
229 Xml::openElement( 'fieldset' ) .
230 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
231 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
232 $this->msg( 'googlesearch' )->rawParams(
233 htmlspecialchars( $term ),
234 'UTF-8',
235 $this->msg( 'searchbutton' )->escaped()
236 )->text() .
237 Xml::closeElement( 'fieldset' )
238 );
239 }
240 wfProfileOut( __METHOD__ );
241 return;
242 }
243
244 $t = Title::newFromText( $term );
245 $showSuggestion = $t === null || !$t->isKnown();
246 $search->setShowSuggestion( $showSuggestion );
247
248 // fetch search results
249 $rewritten = $search->replacePrefixes( $term );
250
251 $titleMatches = $search->searchTitle( $rewritten );
252 if ( !( $titleMatches instanceof SearchResultTooMany ) ) {
253 $textMatches = $search->searchText( $rewritten );
254 }
255
256 $textStatus = null;
257 if ( $textMatches instanceof Status ) {
258 $textStatus = $textMatches;
259 $textMatches = null;
260 }
261
262 // did you mean... suggestions
263 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
264 $st = SpecialPage::getTitleFor( 'Search' );
265
266 # mirror Go/Search behavior of original request ..
267 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
268
269 if ( $this->fulltext != null ) {
270 $didYouMeanParams['fulltext'] = $this->fulltext;
271 }
272
273 $stParams = array_merge(
274 $didYouMeanParams,
275 $this->powerSearchOptions()
276 );
277
278 $suggestionSnippet = $textMatches->getSuggestionSnippet();
279
280 if ( $suggestionSnippet == '' ) {
281 $suggestionSnippet = null;
282 }
283
284 $suggestLink = Linker::linkKnown(
285 $st,
286 $suggestionSnippet,
287 array(),
288 $stParams
289 );
290
291 $this->didYouMeanHtml = '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
292 }
293
294 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
295 # Hook requested termination
296 wfProfileOut( __METHOD__ );
297 return;
298 }
299
300 // start rendering the page
301 $out->addHtml(
302 Xml::openElement(
303 'form',
304 array(
305 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
306 'method' => 'get',
307 'action' => $wgScript
308 )
309 )
310 );
311 $out->addHtml(
312 # This is an awful awful ID name. It's not a table, but we
313 # named it poorly from when this was a table so now we're
314 # stuck with it
315 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
316 $this->shortDialog( $term ) .
317 Xml::closeElement( 'div' )
318 );
319
320 // Sometimes the search engine knows there are too many hits
321 if ( $titleMatches instanceof SearchResultTooMany ) {
322 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
323 wfProfileOut( __METHOD__ );
324 return;
325 }
326
327 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
328 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
329 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
330 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
331 $out->addHTML( '</form>' );
332 // Empty query -- straight view of search form
333 wfProfileOut( __METHOD__ );
334 return;
335 }
336
337 // Get number of results
338 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
339 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
340 // Total initial query matches (possible false positives)
341 $num = $titleMatchesNum + $textMatchesNum;
342
343 // Get total actual results (after second filtering, if any)
344 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
345 $titleMatches->getTotalHits() : $titleMatchesNum;
346 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
347 $textMatches->getTotalHits() : $textMatchesNum;
348
349 // get total number of results if backend can calculate it
350 $totalRes = 0;
351 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
352 $totalRes += $titleMatches->getTotalHits();
353 }
354 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
355 $totalRes += $textMatches->getTotalHits();
356 }
357
358 // show number of results and current offset
359 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
360 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
361
362 $out->addHtml( Xml::closeElement( 'form' ) );
363 $out->addHtml( "<div class='searchresults'>" );
364
365 // prev/next links
366 if ( $num || $this->offset ) {
367 // Show the create link ahead
368 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
369 $prevnext = $this->getLanguage()->viewPrevNext( $this->getPageTitle(), $this->offset, $this->limit,
370 $this->powerSearchOptions() + array( 'search' => $term ),
371 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
372 );
373 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
374 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
375 } else {
376 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
377 }
378
379 $out->parserOptions()->setEditSection( false );
380 if ( $titleMatches ) {
381 if ( $numTitleMatches > 0 ) {
382 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
383 $out->addHTML( $this->showMatches( $titleMatches ) );
384 }
385 $titleMatches->free();
386 }
387 if ( $textMatches && !$textStatus ) {
388 // output appropriate heading
389 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
390 // if no title matches the heading is redundant
391 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
392 } elseif ( $totalRes == 0 ) {
393 # Don't show the 'no text matches' if we received title matches
394 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
395 }
396 // show interwiki results if any
397 if ( $textMatches->hasInterwikiResults() ) {
398 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
399 }
400 // show results
401 if ( $numTextMatches > 0 ) {
402 $out->addHTML( $this->showMatches( $textMatches ) );
403 }
404
405 $textMatches->free();
406 }
407 if ( $num === 0 ) {
408 if ( $textStatus ) {
409 $out->addHTML( '<div class="error">' .
410 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
411 } else {
412 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
413 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
414 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
415 }
416 }
417 $out->addHtml( "</div>" );
418
419 if ( $num || $this->offset ) {
420 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
421 }
422 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
423 wfProfileOut( __METHOD__ );
424 }
425
426 /**
427 * @param $t Title
428 * @param int $num The number of search results found
429 * @param $titleMatches null|SearchResultSet results from title search
430 * @param $textMatches null|SearchResultSet results from text search
431 */
432 protected function showCreateLink( $t, $num, $titleMatches, $textMatches ) {
433 // show direct page/create link if applicable
434
435 // Check DBkey !== '' in case of fragment link only.
436 if ( is_null( $t ) || $t->getDBkey() === '' ||
437 ( $titleMatches !== null && $titleMatches->searchContainedSyntax() ) ||
438 ( $textMatches !== null && $textMatches->searchContainedSyntax() ) ) {
439 // invalid title
440 // preserve the paragraph for margins etc...
441 $this->getOutput()->addHtml( '<p></p>' );
442 return;
443 }
444
445 if ( $t->isKnown() ) {
446 $messageName = 'searchmenu-exists';
447 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
448 $messageName = 'searchmenu-new';
449 } else {
450 $messageName = 'searchmenu-new-nocreate';
451 }
452 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message::numParam( $num ) );
453 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
454
455 // Extensions using the hook might still return an empty $messageName
456 if ( $messageName ) {
457 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
458 } else {
459 // preserve the paragraph for margins etc...
460 $this->getOutput()->addHtml( '<p></p>' );
461 }
462 }
463
464 /**
465 * @param $term string
466 */
467 protected function setupPage( $term ) {
468 # Should advanced UI be used?
469 $this->searchAdvanced = ( $this->profile === 'advanced' );
470 $out = $this->getOutput();
471 if ( strval( $term ) !== '' ) {
472 $out->setPageTitle( $this->msg( 'searchresults' ) );
473 $out->setHTMLTitle( $this->msg( 'pagetitle' )
474 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
475 ->inContentLanguage()->text()
476 );
477 }
478 // add javascript specific to special:search
479 $out->addModules( 'mediawiki.special.search' );
480 }
481
482 /**
483 * Extract "power search" namespace settings from the request object,
484 * returning a list of index numbers to search.
485 *
486 * @param $request WebRequest
487 * @return Array
488 */
489 protected function powerSearch( &$request ) {
490 $arr = array();
491 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
492 if ( $request->getCheck( 'ns' . $ns ) ) {
493 $arr[] = $ns;
494 }
495 }
496
497 return $arr;
498 }
499
500 /**
501 * Reconstruct the 'power search' options for links
502 *
503 * @return Array
504 */
505 protected function powerSearchOptions() {
506 $opt = array();
507 if ( $this->profile !== 'advanced' ) {
508 $opt['profile'] = $this->profile;
509 } else {
510 foreach ( $this->namespaces as $n ) {
511 $opt['ns' . $n] = 1;
512 }
513 }
514 return $opt + $this->extraParams;
515 }
516
517 /**
518 * Show whole set of results
519 *
520 * @param $matches SearchResultSet
521 *
522 * @return string
523 */
524 protected function showMatches( &$matches ) {
525 global $wgContLang;
526 wfProfileIn( __METHOD__ );
527
528 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
529
530 $out = "";
531 $infoLine = $matches->getInfo();
532 if ( !is_null( $infoLine ) ) {
533 $out .= "\n<!-- {$infoLine} -->\n";
534 }
535 $out .= "<ul class='mw-search-results'>\n";
536 $result = $matches->next();
537 while ( $result ) {
538 $out .= $this->showHit( $result, $terms );
539 $result = $matches->next();
540 }
541 $out .= "</ul>\n";
542
543 // convert the whole thing to desired language variant
544 $out = $wgContLang->convert( $out );
545 wfProfileOut( __METHOD__ );
546 return $out;
547 }
548
549 /**
550 * Format a single hit result
551 *
552 * @param $result SearchResult
553 * @param array $terms terms to highlight
554 *
555 * @return string
556 */
557 protected function showHit( $result, $terms ) {
558 wfProfileIn( __METHOD__ );
559
560 if ( $result->isBrokenTitle() ) {
561 wfProfileOut( __METHOD__ );
562 return "<!-- Broken link in search result -->\n";
563 }
564
565 $t = $result->getTitle();
566
567 $titleSnippet = $result->getTitleSnippet( $terms );
568
569 if ( $titleSnippet == '' ) {
570 $titleSnippet = null;
571 }
572
573 $link_t = clone $t;
574
575 wfRunHooks( 'ShowSearchHitTitle',
576 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
577
578 $link = Linker::linkKnown(
579 $link_t,
580 $titleSnippet
581 );
582
583 //If page content is not readable, just return the title.
584 //This is not quite safe, but better than showing excerpts from non-readable pages
585 //Note that hiding the entry entirely would screw up paging.
586 if ( !$t->userCan( 'read', $this->getUser() ) ) {
587 wfProfileOut( __METHOD__ );
588 return "<li>{$link}</li>\n";
589 }
590
591 // If the page doesn't *exist*... our search index is out of date.
592 // The least confusing at this point is to drop the result.
593 // You may get less results, but... oh well. :P
594 if ( $result->isMissingRevision() ) {
595 wfProfileOut( __METHOD__ );
596 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
597 }
598
599 // format redirects / relevant sections
600 $redirectTitle = $result->getRedirectTitle();
601 $redirectText = $result->getRedirectSnippet( $terms );
602 $sectionTitle = $result->getSectionTitle();
603 $sectionText = $result->getSectionSnippet( $terms );
604 $redirect = '';
605
606 if ( !is_null( $redirectTitle ) ) {
607 if ( $redirectText == '' ) {
608 $redirectText = null;
609 }
610
611 $redirect = "<span class='searchalttitle'>" .
612 $this->msg( 'search-redirect' )->rawParams(
613 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
614 "</span>";
615 }
616
617 $section = '';
618
619 if ( !is_null( $sectionTitle ) ) {
620 if ( $sectionText == '' ) {
621 $sectionText = null;
622 }
623
624 $section = "<span class='searchalttitle'>" .
625 $this->msg( 'search-section' )->rawParams(
626 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
627 "</span>";
628 }
629
630 // format text extract
631 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
632
633 $lang = $this->getLanguage();
634
635 // format score
636 if ( is_null( $result->getScore() ) ) {
637 // Search engine doesn't report scoring info
638 $score = '';
639 } else {
640 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
641 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
642 . ' - ';
643 }
644
645 // format description
646 $byteSize = $result->getByteSize();
647 $wordCount = $result->getWordCount();
648 $timestamp = $result->getTimestamp();
649 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
650 ->numParams( $wordCount )->escaped();
651
652 if ( $t->getNamespace() == NS_CATEGORY ) {
653 $cat = Category::newFromTitle( $t );
654 $size = $this->msg( 'search-result-category-size' )
655 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
656 ->escaped();
657 }
658
659 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
660
661 // link to related articles if supported
662 $related = '';
663 if ( $result->hasRelated() ) {
664 $st = SpecialPage::getTitleFor( 'Search' );
665 $stParams = array_merge(
666 $this->powerSearchOptions(),
667 array(
668 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
669 ':' . $t->getPrefixedText(),
670 'fulltext' => $this->msg( 'search' )->text()
671 )
672 );
673
674 $related = ' -- ' . Linker::linkKnown(
675 $st,
676 $this->msg( 'search-relatedarticle' )->text(),
677 array(),
678 $stParams
679 );
680 }
681
682 $fileMatch = '';
683 // Include a thumbnail for media files...
684 if ( $t->getNamespace() == NS_FILE ) {
685 $img = $result->getFile();
686 $img = $img ?: wfFindFile( $t );
687 if ( $result->isFileMatch() ) {
688 $fileMatch = "<span class='searchalttitle'>" .
689 $this->msg( 'search-file-match' )->escaped() . "</span>";
690 }
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} {$fileMatch}" .
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} {$fileMatch}</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();
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();
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['profile'] = $this->profile;
865
866 if ( $profile === 'advanced' ) {
867 return $this->powerSearchBox( $term, $opts );
868 } else {
869 $form = '';
870 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
871 return $form;
872 }
873 }
874
875 /**
876 * Generates the power search box at [[Special:Search]]
877 *
878 * @param string $term search term
879 * @param $opts array
880 * @return String: HTML form
881 */
882 protected function powerSearchBox( $term, $opts ) {
883 global $wgContLang;
884
885 // Groups namespaces into rows according to subject
886 $rows = array();
887 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
888 $subject = MWNamespace::getSubject( $namespace );
889 if ( !array_key_exists( $subject, $rows ) ) {
890 $rows[$subject] = "";
891 }
892
893 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
894 if ( $name == '' ) {
895 $name = $this->msg( 'blanknamespace' )->text();
896 }
897
898 $rows[$subject] .=
899 Xml::openElement(
900 'td', array( 'style' => 'white-space: nowrap' )
901 ) .
902 Xml::checkLabel(
903 $name,
904 "ns{$namespace}",
905 "mw-search-ns{$namespace}",
906 in_array( $namespace, $this->namespaces )
907 ) .
908 Xml::closeElement( 'td' );
909 }
910
911 $rows = array_values( $rows );
912 $numRows = count( $rows );
913
914 // Lays out namespaces in multiple floating two-column tables so they'll
915 // be arranged nicely while still accommodating different screen widths
916 $namespaceTables = '';
917 for ( $i = 0; $i < $numRows; $i += 4 ) {
918 $namespaceTables .= Xml::openElement(
919 'table',
920 array( 'cellpadding' => 0, 'cellspacing' => 0 )
921 );
922
923 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
924 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
925 }
926
927 $namespaceTables .= Xml::closeElement( 'table' );
928 }
929
930 $showSections = array( 'namespaceTables' => $namespaceTables );
931
932 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
933
934 $hidden = '';
935 foreach ( $opts as $key => $value ) {
936 $hidden .= Html::hidden( $key, $value );
937 }
938 // Return final output
939 return Xml::openElement(
940 'fieldset',
941 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
942 ) .
943 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
944 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
945 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
946 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
947 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
948 $hidden .
949 Xml::closeElement( 'fieldset' );
950 }
951
952 /**
953 * @return array
954 */
955 protected function getSearchProfiles() {
956 // Builds list of Search Types (profiles)
957 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
958
959 $profiles = array(
960 'default' => array(
961 'message' => 'searchprofile-articles',
962 'tooltip' => 'searchprofile-articles-tooltip',
963 'namespaces' => SearchEngine::defaultNamespaces(),
964 'namespace-messages' => SearchEngine::namespacesAsText(
965 SearchEngine::defaultNamespaces()
966 ),
967 ),
968 'images' => array(
969 'message' => 'searchprofile-images',
970 'tooltip' => 'searchprofile-images-tooltip',
971 'namespaces' => array( NS_FILE ),
972 ),
973 'help' => array(
974 'message' => 'searchprofile-project',
975 'tooltip' => 'searchprofile-project-tooltip',
976 'namespaces' => SearchEngine::helpNamespaces(),
977 'namespace-messages' => SearchEngine::namespacesAsText(
978 SearchEngine::helpNamespaces()
979 ),
980 ),
981 'all' => array(
982 'message' => 'searchprofile-everything',
983 'tooltip' => 'searchprofile-everything-tooltip',
984 'namespaces' => $nsAllSet,
985 ),
986 'advanced' => array(
987 'message' => 'searchprofile-advanced',
988 'tooltip' => 'searchprofile-advanced-tooltip',
989 'namespaces' => self::NAMESPACES_CURRENT,
990 )
991 );
992
993 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
994
995 foreach ( $profiles as &$data ) {
996 if ( !is_array( $data['namespaces'] ) ) {
997 continue;
998 }
999 sort( $data['namespaces'] );
1000 }
1001
1002 return $profiles;
1003 }
1004
1005 /**
1006 * @param $term
1007 * @param $resultsShown
1008 * @param $totalNum
1009 * @return string
1010 */
1011 protected function formHeader( $term, $resultsShown, $totalNum ) {
1012 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1013
1014 $bareterm = $term;
1015 if ( $this->startsWithImage( $term ) ) {
1016 // Deletes prefixes
1017 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1018 }
1019
1020 $profiles = $this->getSearchProfiles();
1021 $lang = $this->getLanguage();
1022
1023 // Outputs XML for Search Types
1024 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1025 $out .= Xml::openElement( 'ul' );
1026 foreach ( $profiles as $id => $profile ) {
1027 if ( !isset( $profile['parameters'] ) ) {
1028 $profile['parameters'] = array();
1029 }
1030 $profile['parameters']['profile'] = $id;
1031
1032 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1033 $lang->commaList( $profile['namespace-messages'] ) : null;
1034 $out .= Xml::tags(
1035 'li',
1036 array(
1037 'class' => $this->profile === $id ? 'current' : 'normal'
1038 ),
1039 $this->makeSearchLink(
1040 $bareterm,
1041 array(),
1042 $this->msg( $profile['message'] )->text(),
1043 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1044 $profile['parameters']
1045 )
1046 );
1047 }
1048 $out .= Xml::closeElement( 'ul' );
1049 $out .= Xml::closeElement( 'div' );
1050
1051 // Results-info
1052 if ( $resultsShown > 0 ) {
1053 if ( $totalNum > 0 ) {
1054 $top = $this->msg( 'showingresultsheader' )
1055 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1056 ->params( wfEscapeWikiText( $term ) )
1057 ->numParams( $resultsShown )
1058 ->parse();
1059 } elseif ( $resultsShown >= $this->limit ) {
1060 $top = $this->msg( 'showingresults' )
1061 ->numParams( $this->limit, $this->offset + 1 )
1062 ->parse();
1063 } else {
1064 $top = $this->msg( 'showingresultsnum' )
1065 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1066 ->parse();
1067 }
1068 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1069 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1070 );
1071 }
1072
1073 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1074 $out .= Xml::closeElement( 'div' );
1075
1076 return $out;
1077 }
1078
1079 /**
1080 * @param $term string
1081 * @return string
1082 */
1083 protected function shortDialog( $term ) {
1084 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1085 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1086 // Term box
1087 $out .= Html::input( 'search', $term, 'search', array(
1088 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1089 'size' => '50',
1090 'autofocus',
1091 'class' => 'mw-ui-input',
1092 ) ) . "\n";
1093 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1094 $out .= Xml::submitButton(
1095 $this->msg( 'searchbutton' )->text(),
1096 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1097 ) . "\n";
1098 return $out . $this->didYouMeanHtml;
1099 }
1100
1101 /**
1102 * Make a search link with some target namespaces
1103 *
1104 * @param $term String
1105 * @param array $namespaces ignored
1106 * @param string $label link's text
1107 * @param string $tooltip link's tooltip
1108 * @param array $params query string parameters
1109 * @return String: HTML fragment
1110 */
1111 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1112 $opt = $params;
1113 foreach ( $namespaces as $n ) {
1114 $opt['ns' . $n] = 1;
1115 }
1116
1117 $stParams = array_merge(
1118 array(
1119 'search' => $term,
1120 'fulltext' => $this->msg( 'search' )->text()
1121 ),
1122 $opt
1123 );
1124
1125 return Xml::element(
1126 'a',
1127 array(
1128 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1129 'title' => $tooltip
1130 ),
1131 $label
1132 );
1133 }
1134
1135 /**
1136 * Check if query starts with image: prefix
1137 *
1138 * @param string $term the string to check
1139 * @return Boolean
1140 */
1141 protected function startsWithImage( $term ) {
1142 global $wgContLang;
1143
1144 $p = explode( ':', $term );
1145 if ( count( $p ) > 1 ) {
1146 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1147 }
1148 return false;
1149 }
1150
1151 /**
1152 * Check if query starts with all: prefix
1153 *
1154 * @param string $term the string to check
1155 * @return Boolean
1156 */
1157 protected function startsWithAll( $term ) {
1158
1159 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1160
1161 $p = explode( ':', $term );
1162 if ( count( $p ) > 1 ) {
1163 return $p[0] == $allkeyword;
1164 }
1165 return false;
1166 }
1167
1168 /**
1169 * @since 1.18
1170 *
1171 * @return SearchEngine
1172 */
1173 public function getSearchEngine() {
1174 if ( $this->searchEngine === null ) {
1175 $this->searchEngine = $this->searchEngineType ?
1176 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1177 }
1178 return $this->searchEngine;
1179 }
1180
1181 /**
1182 * Current search profile.
1183 * @return null|string
1184 */
1185 function getProfile() {
1186 return $this->profile;
1187 }
1188
1189 /**
1190 * Current namespaces.
1191 * @return array
1192 */
1193 function getNamespaces() {
1194 return $this->namespaces;
1195 }
1196
1197 /**
1198 * Users of hook SpecialSearchSetupEngine can use this to
1199 * add more params to links to not lose selection when
1200 * user navigates search results.
1201 * @since 1.18
1202 *
1203 * @param $key
1204 * @param $value
1205 */
1206 public function setExtraParam( $key, $value ) {
1207 $this->extraParams[$key] = $value;
1208 }
1209
1210 protected function getGroupName() {
1211 return 'pages';
1212 }
1213 }