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