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