Remove completely useless implementation of getInfo()
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 /**
3 * Implements Special:Search
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
29 */
30 class SpecialSearch extends SpecialPage {
31 /**
32 * Current search profile. Search profile is just a name that identifies
33 * the active search tab on the search page (content, help, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
37 * null|string
38 */
39 protected $profile;
40
41 /// Search engine
42 protected $searchEngine;
43
44 /// Search engine type, if not default
45 protected $searchEngineType;
46
47 /// For links
48 protected $extraParams = array();
49
50 /// No idea, apparently used by some other classes
51 protected $mPrefix;
52
53 /**
54 * @var int
55 */
56 protected $limit, $offset;
57
58 /**
59 * @var array
60 */
61 protected $namespaces;
62
63 /**
64 * @var bool
65 */
66 protected $searchRedirects;
67
68 /**
69 * @var string
70 */
71 protected $didYouMeanHtml, $fulltext;
72
73 const NAMESPACES_CURRENT = 'sense';
74
75 public function __construct() {
76 parent::__construct( 'Search' );
77 }
78
79 /**
80 * Entry point
81 *
82 * @param string $par or null
83 */
84 public function execute( $par ) {
85 $this->setHeaders();
86 $this->outputHeader();
87 $out = $this->getOutput();
88 $out->allowClickjacking();
89 $out->addModuleStyles( array(
90 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button'
91 ) );
92
93 // Strip underscores from title parameter; most of the time we'll want
94 // text form here. But don't strip underscores from actual text params!
95 $titleParam = str_replace( '_', ' ', $par );
96
97 $request = $this->getRequest();
98
99 // Fetch the search term
100 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
101
102 $this->load();
103
104 $this->searchEngineType = $request->getVal( 'srbackend' );
105
106 if ( $request->getVal( 'fulltext' )
107 || !is_null( $request->getVal( 'offset' ) )
108 ) {
109 $this->showResults( $search );
110 } else {
111 $this->goResult( $search );
112 }
113 }
114
115 /**
116 * Set up basic search parameters from the request and user settings.
117 *
118 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
119 */
120 public function load() {
121 $request = $this->getRequest();
122 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20 );
123 $this->mPrefix = $request->getVal( 'prefix', '' );
124
125 $user = $this->getUser();
126
127 # Extract manually requested namespaces
128 $nslist = $this->powerSearch( $request );
129 if ( !count( $nslist ) ) {
130 # Fallback to user preference
131 $nslist = SearchEngine::userNamespaces( $user );
132 }
133
134 $profile = null;
135 if ( !count( $nslist ) ) {
136 $profile = 'default';
137 }
138
139 $profile = $request->getVal( 'profile', $profile );
140 $profiles = $this->getSearchProfiles();
141 if ( $profile === null ) {
142 // BC with old request format
143 $profile = 'advanced';
144 foreach ( $profiles as $key => $data ) {
145 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
146 $profile = $key;
147 }
148 }
149 $this->namespaces = $nslist;
150 } elseif ( $profile === 'advanced' ) {
151 $this->namespaces = $nslist;
152 } else {
153 if ( isset( $profiles[$profile]['namespaces'] ) ) {
154 $this->namespaces = $profiles[$profile]['namespaces'];
155 } else {
156 // Unknown profile requested
157 $profile = 'default';
158 $this->namespaces = $profiles['default']['namespaces'];
159 }
160 }
161
162 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
163 $default = $request->getBool( 'profile' ) ? 0 : 1;
164 $this->searchRedirects = $request->getBool( 'redirs', $default ) ? 1 : 0;
165 $this->didYouMeanHtml = ''; # html of did you mean... link
166 $this->fulltext = $request->getVal( 'fulltext' );
167 $this->profile = $profile;
168 }
169
170 /**
171 * If an exact title match can be found, jump straight ahead to it.
172 *
173 * @param $term String
174 */
175 public function goResult( $term ) {
176 $this->setupPage( $term );
177 # Try to go to page as entered.
178 $t = Title::newFromText( $term );
179 # If the string cannot be used to create a title
180 if ( is_null( $t ) ) {
181 $this->showResults( $term );
182 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->getFullText(), '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 = "<ul class='mw-search-results'>\n";
542 $result = $matches->next();
543 while ( $result ) {
544 $out .= $this->showHit( $result, $terms );
545 $result = $matches->next();
546 }
547 $out .= "</ul>\n";
548
549 // convert the whole thing to desired language variant
550 $out = $wgContLang->convert( $out );
551 wfProfileOut( __METHOD__ );
552 return $out;
553 }
554
555 /**
556 * Format a single hit result
557 *
558 * @param $result SearchResult
559 * @param array $terms terms to highlight
560 *
561 * @return string
562 */
563 protected function showHit( $result, $terms ) {
564 wfProfileIn( __METHOD__ );
565
566 if ( $result->isBrokenTitle() ) {
567 wfProfileOut( __METHOD__ );
568 return "<!-- Broken link in search result -->\n";
569 }
570
571 $t = $result->getTitle();
572
573 $titleSnippet = $result->getTitleSnippet( $terms );
574
575 if ( $titleSnippet == '' ) {
576 $titleSnippet = null;
577 }
578
579 $link_t = clone $t;
580
581 wfRunHooks( 'ShowSearchHitTitle',
582 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
583
584 $link = Linker::linkKnown(
585 $link_t,
586 $titleSnippet
587 );
588
589 //If page content is not readable, just return the title.
590 //This is not quite safe, but better than showing excerpts from non-readable pages
591 //Note that hiding the entry entirely would screw up paging.
592 if ( !$t->userCan( 'read', $this->getUser() ) ) {
593 wfProfileOut( __METHOD__ );
594 return "<li>{$link}</li>\n";
595 }
596
597 // If the page doesn't *exist*... our search index is out of date.
598 // The least confusing at this point is to drop the result.
599 // You may get less results, but... oh well. :P
600 if ( $result->isMissingRevision() ) {
601 wfProfileOut( __METHOD__ );
602 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
603 }
604
605 // format redirects / relevant sections
606 $redirectTitle = $result->getRedirectTitle();
607 $redirectText = $result->getRedirectSnippet( $terms );
608 $sectionTitle = $result->getSectionTitle();
609 $sectionText = $result->getSectionSnippet( $terms );
610 $redirect = '';
611
612 if ( !is_null( $redirectTitle ) ) {
613 if ( $redirectText == '' ) {
614 $redirectText = null;
615 }
616
617 $redirect = "<span class='searchalttitle'>" .
618 $this->msg( 'search-redirect' )->rawParams(
619 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
620 "</span>";
621 }
622
623 $section = '';
624
625 if ( !is_null( $sectionTitle ) ) {
626 if ( $sectionText == '' ) {
627 $sectionText = null;
628 }
629
630 $section = "<span class='searchalttitle'>" .
631 $this->msg( 'search-section' )->rawParams(
632 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
633 "</span>";
634 }
635
636 // format text extract
637 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
638
639 $lang = $this->getLanguage();
640
641 // format score
642 if ( is_null( $result->getScore() ) ) {
643 // Search engine doesn't report scoring info
644 $score = '';
645 } else {
646 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
647 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
648 . ' - ';
649 }
650
651 // format description
652 $byteSize = $result->getByteSize();
653 $wordCount = $result->getWordCount();
654 $timestamp = $result->getTimestamp();
655 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
656 ->numParams( $wordCount )->escaped();
657
658 if ( $t->getNamespace() == NS_CATEGORY ) {
659 $cat = Category::newFromTitle( $t );
660 $size = $this->msg( 'search-result-category-size' )
661 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
662 ->escaped();
663 }
664
665 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
666
667 // link to related articles if supported
668 $related = '';
669 if ( $result->hasRelated() ) {
670 $st = SpecialPage::getTitleFor( 'Search' );
671 $stParams = array_merge(
672 $this->powerSearchOptions(),
673 array(
674 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
675 ':' . $t->getPrefixedText(),
676 'fulltext' => $this->msg( 'search' )->text()
677 )
678 );
679
680 $related = ' -- ' . Linker::linkKnown(
681 $st,
682 $this->msg( 'search-relatedarticle' )->text(),
683 array(),
684 $stParams
685 );
686 }
687
688 $fileMatch = '';
689 // Include a thumbnail for media files...
690 if ( $t->getNamespace() == NS_FILE ) {
691 $img = $result->getFile();
692 $img = $img ?: wfFindFile( $t );
693 if ( $result->isFileMatch() ) {
694 $fileMatch = "<span class='searchalttitle'>" .
695 $this->msg( 'search-file-match' )->escaped() . "</span>";
696 }
697 if ( $img ) {
698 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
699 if ( $thumb ) {
700 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
701 wfProfileOut( __METHOD__ );
702 // Float doesn't seem to interact well with the bullets.
703 // Table messes up vertical alignment of the bullets.
704 // Bullets are therefore disabled (didn't look great anyway).
705 return "<li>" .
706 '<table class="searchResultImage">' .
707 '<tr>' .
708 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
709 $thumb->toHtml( array( 'desc-link' => true ) ) .
710 '</td>' .
711 '<td style="vertical-align: top;">' .
712 "{$link} {$fileMatch}" .
713 $extract .
714 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
715 '</td>' .
716 '</tr>' .
717 '</table>' .
718 "</li>\n";
719 }
720 }
721 }
722
723 $html = null;
724
725 if ( wfRunHooks( 'ShowSearchHit', array(
726 $this, $result, $terms,
727 &$link, &$redirect, &$section, &$extract,
728 &$score, &$size, &$date, &$related,
729 &$html
730 ) ) ) {
731 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
732 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
733 "</li>\n";
734 }
735
736 wfProfileOut( __METHOD__ );
737 return $html;
738 }
739
740 /**
741 * Show results from other wikis
742 *
743 * @param $matches SearchResultSet
744 * @param $query String
745 *
746 * @return string
747 */
748 protected function showInterwiki( $matches, $query ) {
749 global $wgContLang;
750 wfProfileIn( __METHOD__ );
751 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
752
753 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
754 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
755 $out .= "<ul class='mw-search-iwresults'>\n";
756
757 // work out custom project captions
758 $customCaptions = array();
759 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
760 foreach ( $customLines as $line ) {
761 $parts = explode( ":", $line, 2 );
762 if ( count( $parts ) == 2 ) { // validate line
763 $customCaptions[$parts[0]] = $parts[1];
764 }
765 }
766
767 $prev = null;
768 $result = $matches->next();
769 while ( $result ) {
770 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
771 $prev = $result->getInterwikiPrefix();
772 $result = $matches->next();
773 }
774 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
775 $out .= "</ul></div>\n";
776
777 // convert the whole thing to desired language variant
778 $out = $wgContLang->convert( $out );
779 wfProfileOut( __METHOD__ );
780 return $out;
781 }
782
783 /**
784 * Show single interwiki link
785 *
786 * @param $result SearchResult
787 * @param $lastInterwiki String
788 * @param $terms Array
789 * @param $query String
790 * @param array $customCaptions iw prefix -> caption
791 *
792 * @return string
793 */
794 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
795 wfProfileIn( __METHOD__ );
796
797 if ( $result->isBrokenTitle() ) {
798 wfProfileOut( __METHOD__ );
799 return "<!-- Broken link in search result -->\n";
800 }
801
802 $t = $result->getTitle();
803
804 $titleSnippet = $result->getTitleSnippet();
805
806 if ( $titleSnippet == '' ) {
807 $titleSnippet = null;
808 }
809
810 $link = Linker::linkKnown(
811 $t,
812 $titleSnippet
813 );
814
815 // format redirect if any
816 $redirectTitle = $result->getRedirectTitle();
817 $redirectText = $result->getRedirectSnippet();
818 $redirect = '';
819 if ( !is_null( $redirectTitle ) ) {
820 if ( $redirectText == '' ) {
821 $redirectText = null;
822 }
823
824 $redirect = "<span class='searchalttitle'>" .
825 $this->msg( 'search-redirect' )->rawParams(
826 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
827 "</span>";
828 }
829
830 $out = "";
831 // display project name
832 if ( is_null( $lastInterwiki ) || $lastInterwiki != $t->getInterwiki() ) {
833 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
834 // captions from 'search-interwiki-custom'
835 $caption = $customCaptions[$t->getInterwiki()];
836 } else {
837 // default is to show the hostname of the other wiki which might suck
838 // if there are many wikis on one hostname
839 $parsed = wfParseUrl( $t->getFullURL() );
840 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
841 }
842 // "more results" link (special page stuff could be localized, but we might not know target lang)
843 $searchTitle = Title::newFromText( $t->getInterwiki() . ":Special:Search" );
844 $searchLink = Linker::linkKnown(
845 $searchTitle,
846 $this->msg( 'search-interwiki-more' )->text(),
847 array(),
848 array(
849 'search' => $query,
850 'fulltext' => 'Search'
851 )
852 );
853 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
854 {$searchLink}</span>{$caption}</div>\n<ul>";
855 }
856
857 $out .= "<li>{$link} {$redirect}</li>\n";
858 wfProfileOut( __METHOD__ );
859 return $out;
860 }
861
862 /**
863 * @param $profile
864 * @param $term
865 * @return String
866 */
867 protected function getProfileForm( $profile, $term ) {
868 // Hidden stuff
869 $opts = array();
870 $opts['redirs'] = $this->searchRedirects;
871 $opts['profile'] = $this->profile;
872
873 if ( $profile === 'advanced' ) {
874 return $this->powerSearchBox( $term, $opts );
875 } else {
876 $form = '';
877 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
878 return $form;
879 }
880 }
881
882 /**
883 * Generates the power search box at [[Special:Search]]
884 *
885 * @param string $term search term
886 * @param $opts array
887 * @return String: HTML form
888 */
889 protected function powerSearchBox( $term, $opts ) {
890 global $wgContLang;
891
892 // Groups namespaces into rows according to subject
893 $rows = array();
894 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
895 $subject = MWNamespace::getSubject( $namespace );
896 if ( !array_key_exists( $subject, $rows ) ) {
897 $rows[$subject] = "";
898 }
899
900 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
901 if ( $name == '' ) {
902 $name = $this->msg( 'blanknamespace' )->text();
903 }
904
905 $rows[$subject] .=
906 Xml::openElement(
907 'td', array( 'style' => 'white-space: nowrap' )
908 ) .
909 Xml::checkLabel(
910 $name,
911 "ns{$namespace}",
912 "mw-search-ns{$namespace}",
913 in_array( $namespace, $this->namespaces )
914 ) .
915 Xml::closeElement( 'td' );
916 }
917
918 $rows = array_values( $rows );
919 $numRows = count( $rows );
920
921 // Lays out namespaces in multiple floating two-column tables so they'll
922 // be arranged nicely while still accommodating different screen widths
923 $namespaceTables = '';
924 for ( $i = 0; $i < $numRows; $i += 4 ) {
925 $namespaceTables .= Xml::openElement(
926 'table',
927 array( 'cellpadding' => 0, 'cellspacing' => 0 )
928 );
929
930 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
931 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
932 }
933
934 $namespaceTables .= Xml::closeElement( 'table' );
935 }
936
937 $showSections = array( 'namespaceTables' => $namespaceTables );
938
939 // Show redirects check only if backend supports it
940 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
941 $showSections['redirects'] =
942 Xml::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects );
943 }
944
945 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
946
947 $hidden = '';
948 unset( $opts['redirs'] );
949 foreach ( $opts as $key => $value ) {
950 $hidden .= Html::hidden( $key, $value );
951 }
952 // Return final output
953 return Xml::openElement(
954 'fieldset',
955 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
956 ) .
957 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
958 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
959 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
960 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
961 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
962 $hidden .
963 Xml::closeElement( 'fieldset' );
964 }
965
966 /**
967 * @return array
968 */
969 protected function getSearchProfiles() {
970 // Builds list of Search Types (profiles)
971 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
972
973 $profiles = array(
974 'default' => array(
975 'message' => 'searchprofile-articles',
976 'tooltip' => 'searchprofile-articles-tooltip',
977 'namespaces' => SearchEngine::defaultNamespaces(),
978 'namespace-messages' => SearchEngine::namespacesAsText(
979 SearchEngine::defaultNamespaces()
980 ),
981 ),
982 'images' => array(
983 'message' => 'searchprofile-images',
984 'tooltip' => 'searchprofile-images-tooltip',
985 'namespaces' => array( NS_FILE ),
986 ),
987 'help' => array(
988 'message' => 'searchprofile-project',
989 'tooltip' => 'searchprofile-project-tooltip',
990 'namespaces' => SearchEngine::helpNamespaces(),
991 'namespace-messages' => SearchEngine::namespacesAsText(
992 SearchEngine::helpNamespaces()
993 ),
994 ),
995 'all' => array(
996 'message' => 'searchprofile-everything',
997 'tooltip' => 'searchprofile-everything-tooltip',
998 'namespaces' => $nsAllSet,
999 ),
1000 'advanced' => array(
1001 'message' => 'searchprofile-advanced',
1002 'tooltip' => 'searchprofile-advanced-tooltip',
1003 'namespaces' => self::NAMESPACES_CURRENT,
1004 )
1005 );
1006
1007 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1008
1009 foreach ( $profiles as &$data ) {
1010 if ( !is_array( $data['namespaces'] ) ) {
1011 continue;
1012 }
1013 sort( $data['namespaces'] );
1014 }
1015
1016 return $profiles;
1017 }
1018
1019 /**
1020 * @param $term
1021 * @param $resultsShown
1022 * @param $totalNum
1023 * @return string
1024 */
1025 protected function formHeader( $term, $resultsShown, $totalNum ) {
1026 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1027
1028 $bareterm = $term;
1029 if ( $this->startsWithImage( $term ) ) {
1030 // Deletes prefixes
1031 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1032 }
1033
1034 $profiles = $this->getSearchProfiles();
1035 $lang = $this->getLanguage();
1036
1037 // Outputs XML for Search Types
1038 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1039 $out .= Xml::openElement( 'ul' );
1040 foreach ( $profiles as $id => $profile ) {
1041 if ( !isset( $profile['parameters'] ) ) {
1042 $profile['parameters'] = array();
1043 }
1044 $profile['parameters']['profile'] = $id;
1045
1046 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1047 $lang->commaList( $profile['namespace-messages'] ) : null;
1048 $out .= Xml::tags(
1049 'li',
1050 array(
1051 'class' => $this->profile === $id ? 'current' : 'normal'
1052 ),
1053 $this->makeSearchLink(
1054 $bareterm,
1055 array(),
1056 $this->msg( $profile['message'] )->text(),
1057 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1058 $profile['parameters']
1059 )
1060 );
1061 }
1062 $out .= Xml::closeElement( 'ul' );
1063 $out .= Xml::closeElement( 'div' );
1064
1065 // Results-info
1066 if ( $resultsShown > 0 ) {
1067 if ( $totalNum > 0 ) {
1068 $top = $this->msg( 'showingresultsheader' )
1069 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1070 ->params( wfEscapeWikiText( $term ) )
1071 ->numParams( $resultsShown )
1072 ->parse();
1073 } elseif ( $resultsShown >= $this->limit ) {
1074 $top = $this->msg( 'showingresults' )
1075 ->numParams( $this->limit, $this->offset + 1 )
1076 ->parse();
1077 } else {
1078 $top = $this->msg( 'showingresultsnum' )
1079 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1080 ->parse();
1081 }
1082 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1083 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1084 );
1085 }
1086
1087 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1088 $out .= Xml::closeElement( 'div' );
1089
1090 return $out;
1091 }
1092
1093 /**
1094 * @param $term string
1095 * @return string
1096 */
1097 protected function shortDialog( $term ) {
1098 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1099 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1100 // Term box
1101 $out .= Html::input( 'search', $term, 'search', array(
1102 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1103 'size' => '50',
1104 'autofocus',
1105 'class' => 'mw-ui-input',
1106 ) ) . "\n";
1107 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1108 $out .= Xml::submitButton(
1109 $this->msg( 'searchbutton' )->text(),
1110 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1111 ) . "\n";
1112 return $out . $this->didYouMeanHtml;
1113 }
1114
1115 /**
1116 * Make a search link with some target namespaces
1117 *
1118 * @param $term String
1119 * @param array $namespaces ignored
1120 * @param string $label link's text
1121 * @param string $tooltip link's tooltip
1122 * @param array $params query string parameters
1123 * @return String: HTML fragment
1124 */
1125 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1126 $opt = $params;
1127 foreach ( $namespaces as $n ) {
1128 $opt['ns' . $n] = 1;
1129 }
1130 $opt['redirs'] = $this->searchRedirects;
1131
1132 $stParams = array_merge(
1133 array(
1134 'search' => $term,
1135 'fulltext' => $this->msg( 'search' )->text()
1136 ),
1137 $opt
1138 );
1139
1140 return Xml::element(
1141 'a',
1142 array(
1143 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1144 'title' => $tooltip
1145 ),
1146 $label
1147 );
1148 }
1149
1150 /**
1151 * Check if query starts with image: prefix
1152 *
1153 * @param string $term the string to check
1154 * @return Boolean
1155 */
1156 protected function startsWithImage( $term ) {
1157 global $wgContLang;
1158
1159 $p = explode( ':', $term );
1160 if ( count( $p ) > 1 ) {
1161 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1162 }
1163 return false;
1164 }
1165
1166 /**
1167 * Check if query starts with all: prefix
1168 *
1169 * @param string $term the string to check
1170 * @return Boolean
1171 */
1172 protected function startsWithAll( $term ) {
1173
1174 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1175
1176 $p = explode( ':', $term );
1177 if ( count( $p ) > 1 ) {
1178 return $p[0] == $allkeyword;
1179 }
1180 return false;
1181 }
1182
1183 /**
1184 * @since 1.18
1185 *
1186 * @return SearchEngine
1187 */
1188 public function getSearchEngine() {
1189 if ( $this->searchEngine === null ) {
1190 $this->searchEngine = $this->searchEngineType ?
1191 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1192 }
1193 return $this->searchEngine;
1194 }
1195
1196 /**
1197 * Current search profile.
1198 * @return null|string
1199 */
1200 function getProfile() {
1201 return $this->profile;
1202 }
1203
1204 /**
1205 * Current namespaces.
1206 * @return array
1207 */
1208 function getNamespaces() {
1209 return $this->namespaces;
1210 }
1211
1212 /**
1213 * Users of hook SpecialSearchSetupEngine can use this to
1214 * add more params to links to not lose selection when
1215 * user navigates search results.
1216 * @since 1.18
1217 *
1218 * @param $key
1219 * @param $value
1220 */
1221 public function setExtraParam( $key, $value ) {
1222 $this->extraParams[$key] = $value;
1223 }
1224
1225 protected function getGroupName() {
1226 return 'pages';
1227 }
1228 }