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