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