fix some spacing
[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
292 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
293 # Hook requested termination
294 wfProfileOut( __METHOD__ );
295 return;
296 }
297
298 // start rendering the page
299 $out->addHtml(
300 Xml::openElement(
301 'form',
302 array(
303 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
304 'method' => 'get',
305 'action' => $wgScript
306 )
307 )
308 );
309 $out->addHtml(
310 Xml::openElement( 'table', array( 'id' => 'mw-search-top-table', 'cellpadding' => 0, 'cellspacing' => 0 ) ) .
311 Xml::openElement( 'tr' ) .
312 Xml::openElement( 'td' ) . "\n" .
313 $this->shortDialog( $term ) .
314 Xml::closeElement('td') .
315 Xml::closeElement('tr') .
316 Xml::closeElement('table')
317 );
318
319 // Sometimes the search engine knows there are too many hits
320 if( $titleMatches instanceof SearchResultTooMany ) {
321 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
322 wfProfileOut( __METHOD__ );
323 return;
324 }
325
326 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
327 if( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
328 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
329 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
330 $out->addHTML( '</form>' );
331 // Empty query -- straight view of search form
332 wfProfileOut( __METHOD__ );
333 return;
334 }
335
336 // Get number of results
337 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
338 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
339 // Total initial query matches (possible false positives)
340 $num = $titleMatchesNum + $textMatchesNum;
341
342 // Get total actual results (after second filtering, if any)
343 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
344 $titleMatches->getTotalHits() : $titleMatchesNum;
345 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
346 $textMatches->getTotalHits() : $textMatchesNum;
347
348 // get total number of results if backend can calculate it
349 $totalRes = 0;
350 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
351 $totalRes += $titleMatches->getTotalHits();
352 if($textMatches && !is_null( $textMatches->getTotalHits() ))
353 $totalRes += $textMatches->getTotalHits();
354
355 // show number of results and current offset
356 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
357 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
358
359
360 $out->addHtml( Xml::closeElement( 'form' ) );
361 $out->addHtml( "<div class='searchresults'>" );
362
363 // prev/next links
364 if( $num || $this->offset ) {
365 // Show the create link ahead
366 $this->showCreateLink( $t );
367 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset, $this->limit,
368 $this->powerSearchOptions() + array( 'search' => $term ),
369 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
370 );
371 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
372 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
373 } else {
374 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
375 }
376
377 $out->parserOptions()->setEditSection( false );
378 if( $titleMatches ) {
379 if( $numTitleMatches > 0 ) {
380 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
381 $out->addHTML( $this->showMatches( $titleMatches ) );
382 }
383 $titleMatches->free();
384 }
385 if( $textMatches ) {
386 // output appropriate heading
387 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
388 // if no title matches the heading is redundant
389 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
390 } elseif( $totalRes == 0 ) {
391 # Don't show the 'no text matches' if we received title matches
392 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
393 }
394 // show interwiki results if any
395 if( $textMatches->hasInterwikiResults() ) {
396 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
397 }
398 // show results
399 if( $numTextMatches > 0 ) {
400 $out->addHTML( $this->showMatches( $textMatches ) );
401 }
402
403 $textMatches->free();
404 }
405 if( $num === 0 ) {
406 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
407 $this->showCreateLink( $t );
408 }
409 $out->addHtml( "</div>" );
410
411 if( $num || $this->offset ) {
412 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
413 }
414 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
415 wfProfileOut( __METHOD__ );
416 }
417
418 /**
419 * @param $t Title
420 */
421 protected function showCreateLink( $t ) {
422 // show direct page/create link if applicable
423
424 // Check DBkey !== '' in case of fragment link only.
425 if( is_null( $t ) || $t->getDBkey() === '' ) {
426 // invalid title
427 // preserve the paragraph for margins etc...
428 $this->getOutput()->addHtml( '<p></p>' );
429 return;
430 }
431
432 if( $t->isKnown() ) {
433 $messageName = 'searchmenu-exists';
434 } elseif( $t->userCan( 'create', $this->getUser() ) ) {
435 $messageName = 'searchmenu-new';
436 } else {
437 $messageName = 'searchmenu-new-nocreate';
438 }
439 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
440 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
441
442 // Extensions using the hook might still return an empty $messageName
443 if( $messageName ) {
444 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
445 } else {
446 // preserve the paragraph for margins etc...
447 $this->getOutput()->addHtml( '<p></p>' );
448 }
449 }
450
451 /**
452 * @param $term string
453 */
454 protected function setupPage( $term ) {
455 # Should advanced UI be used?
456 $this->searchAdvanced = ($this->profile === 'advanced');
457 $out = $this->getOutput();
458 if( strval( $term ) !== '' ) {
459 $out->setPageTitle( $this->msg( 'searchresults' ) );
460 $out->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams(
461 $this->msg( 'searchresults-title' )->rawParams( $term )->text()
462 ) );
463 }
464 // add javascript specific to special:search
465 $out->addModules( 'mediawiki.special.search' );
466 }
467
468 /**
469 * Extract "power search" namespace settings from the request object,
470 * returning a list of index numbers to search.
471 *
472 * @param $request WebRequest
473 * @return Array
474 */
475 protected function powerSearch( &$request ) {
476 $arr = array();
477 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
478 if( $request->getCheck( 'ns' . $ns ) ) {
479 $arr[] = $ns;
480 }
481 }
482
483 return $arr;
484 }
485
486 /**
487 * Reconstruct the 'power search' options for links
488 *
489 * @return Array
490 */
491 protected function powerSearchOptions() {
492 $opt = array();
493 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
494 if( $this->profile !== 'advanced' ) {
495 $opt['profile'] = $this->profile;
496 } else {
497 foreach( $this->namespaces as $n ) {
498 $opt['ns' . $n] = 1;
499 }
500 }
501 return $opt + $this->extraParams;
502 }
503
504 /**
505 * Show whole set of results
506 *
507 * @param $matches SearchResultSet
508 *
509 * @return string
510 */
511 protected function showMatches( &$matches ) {
512 global $wgContLang;
513 wfProfileIn( __METHOD__ );
514
515 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
516
517 $out = "";
518 $infoLine = $matches->getInfo();
519 if( !is_null($infoLine) ) {
520 $out .= "\n<!-- {$infoLine} -->\n";
521 }
522 $out .= "<ul class='mw-search-results'>\n";
523 $result = $matches->next();
524 while( $result ) {
525 $out .= $this->showHit( $result, $terms );
526 $result = $matches->next();
527 }
528 $out .= "</ul>\n";
529
530 // convert the whole thing to desired language variant
531 $out = $wgContLang->convert( $out );
532 wfProfileOut( __METHOD__ );
533 return $out;
534 }
535
536 /**
537 * Format a single hit result
538 *
539 * @param $result SearchResult
540 * @param $terms Array: terms to highlight
541 *
542 * @return string
543 */
544 protected function showHit( $result, $terms ) {
545 wfProfileIn( __METHOD__ );
546
547 if( $result->isBrokenTitle() ) {
548 wfProfileOut( __METHOD__ );
549 return "<!-- Broken link in search result -->\n";
550 }
551
552 $t = $result->getTitle();
553
554 $titleSnippet = $result->getTitleSnippet($terms);
555
556 if( $titleSnippet == '' )
557 $titleSnippet = null;
558
559 $link_t = clone $t;
560
561 wfRunHooks( 'ShowSearchHitTitle',
562 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
563
564 $link = Linker::linkKnown(
565 $link_t,
566 $titleSnippet
567 );
568
569 //If page content is not readable, just return the title.
570 //This is not quite safe, but better than showing excerpts from non-readable pages
571 //Note that hiding the entry entirely would screw up paging.
572 if( !$t->userCan( 'read', $this->getUser() ) ) {
573 wfProfileOut( __METHOD__ );
574 return "<li>{$link}</li>\n";
575 }
576
577 // If the page doesn't *exist*... our search index is out of date.
578 // The least confusing at this point is to drop the result.
579 // You may get less results, but... oh well. :P
580 if( $result->isMissingRevision() ) {
581 wfProfileOut( __METHOD__ );
582 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
583 }
584
585 // format redirects / relevant sections
586 $redirectTitle = $result->getRedirectTitle();
587 $redirectText = $result->getRedirectSnippet($terms);
588 $sectionTitle = $result->getSectionTitle();
589 $sectionText = $result->getSectionSnippet($terms);
590 $redirect = '';
591
592 if( !is_null($redirectTitle) ) {
593 if( $redirectText == '' )
594 $redirectText = null;
595
596 $redirect = "<span class='searchalttitle'>" .
597 $this->msg( 'search-redirect' )->rawParams(
598 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
599 "</span>";
600 }
601
602 $section = '';
603
604 if( !is_null($sectionTitle) ) {
605 if( $sectionText == '' )
606 $sectionText = null;
607
608 $section = "<span class='searchalttitle'>" .
609 $this->msg( 'search-section' )->rawParams(
610 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
611 "</span>";
612 }
613
614 // format text extract
615 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
616
617 $lang = $this->getLanguage();
618
619 // format score
620 if( is_null( $result->getScore() ) ) {
621 // Search engine doesn't report scoring info
622 $score = '';
623 } else {
624 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
625 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
626 . ' - ';
627 }
628
629 // format description
630 $byteSize = $result->getByteSize();
631 $wordCount = $result->getWordCount();
632 $timestamp = $result->getTimestamp();
633 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
634 ->numParams( $wordCount )->escaped();
635
636 if( $t->getNamespace() == NS_CATEGORY ) {
637 $cat = Category::newFromTitle( $t );
638 $size = $this->msg( 'search-result-category-size' )
639 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
640 ->escaped();
641 }
642
643 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
644
645 // link to related articles if supported
646 $related = '';
647 if( $result->hasRelated() ) {
648 $st = SpecialPage::getTitleFor( 'Search' );
649 $stParams = array_merge(
650 $this->powerSearchOptions(),
651 array(
652 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
653 ':' . $t->getPrefixedText(),
654 'fulltext' => $this->msg( 'search' )->text()
655 )
656 );
657
658 $related = ' -- ' . Linker::linkKnown(
659 $st,
660 $this->msg( 'search-relatedarticle' )->text(),
661 array(),
662 $stParams
663 );
664 }
665
666 // Include a thumbnail for media files...
667 if( $t->getNamespace() == NS_FILE ) {
668 $img = wfFindFile( $t );
669 if( $img ) {
670 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
671 if( $thumb ) {
672 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
673 wfProfileOut( __METHOD__ );
674 // Float doesn't seem to interact well with the bullets.
675 // Table messes up vertical alignment of the bullets.
676 // Bullets are therefore disabled (didn't look great anyway).
677 return "<li>" .
678 '<table class="searchResultImage">' .
679 '<tr>' .
680 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
681 $thumb->toHtml( array( 'desc-link' => true ) ) .
682 '</td>' .
683 '<td style="vertical-align: top;">' .
684 $link .
685 $extract .
686 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
687 '</td>' .
688 '</tr>' .
689 '</table>' .
690 "</li>\n";
691 }
692 }
693 }
694
695 $html = null;
696
697 if ( wfRunHooks( 'ShowSearchHit', array (
698 $this, $result, $terms,
699 &$link, &$redirect, &$section, &$extract,
700 &$score, &$size, &$date, &$related,
701 &$html
702 ) ) ) {
703 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
704 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
705 "</li>\n";
706 }
707
708 wfProfileOut( __METHOD__ );
709 return $html;
710 }
711
712 /**
713 * Show results from other wikis
714 *
715 * @param $matches SearchResultSet
716 * @param $query String
717 *
718 * @return string
719 */
720 protected function showInterwiki( &$matches, $query ) {
721 global $wgContLang;
722 wfProfileIn( __METHOD__ );
723 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
724
725 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
726 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
727 $out .= "<ul class='mw-search-iwresults'>\n";
728
729 // work out custom project captions
730 $customCaptions = array();
731 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
732 foreach( $customLines as $line ) {
733 $parts = explode( ":", $line, 2 );
734 if( count( $parts ) == 2 ) { // validate line
735 $customCaptions[$parts[0]] = $parts[1];
736 }
737 }
738
739 $prev = null;
740 $result = $matches->next();
741 while( $result ) {
742 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
743 $prev = $result->getInterwikiPrefix();
744 $result = $matches->next();
745 }
746 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
747 $out .= "</ul></div>\n";
748
749 // convert the whole thing to desired language variant
750 $out = $wgContLang->convert( $out );
751 wfProfileOut( __METHOD__ );
752 return $out;
753 }
754
755 /**
756 * Show single interwiki link
757 *
758 * @param $result SearchResult
759 * @param $lastInterwiki String
760 * @param $terms Array
761 * @param $query String
762 * @param $customCaptions Array: iw prefix -> caption
763 *
764 * @return string
765 */
766 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
767 wfProfileIn( __METHOD__ );
768
769 if( $result->isBrokenTitle() ) {
770 wfProfileOut( __METHOD__ );
771 return "<!-- Broken link in search result -->\n";
772 }
773
774 $t = $result->getTitle();
775
776 $titleSnippet = $result->getTitleSnippet($terms);
777
778 if( $titleSnippet == '' )
779 $titleSnippet = null;
780
781 $link = Linker::linkKnown(
782 $t,
783 $titleSnippet
784 );
785
786 // format redirect if any
787 $redirectTitle = $result->getRedirectTitle();
788 $redirectText = $result->getRedirectSnippet($terms);
789 $redirect = '';
790 if( !is_null($redirectTitle) ) {
791 if( $redirectText == '' )
792 $redirectText = null;
793
794 $redirect = "<span class='searchalttitle'>" .
795 $this->msg( 'search-redirect' )->rawParams(
796 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
797 "</span>";
798 }
799
800 $out = "";
801 // display project name
802 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
803 if( array_key_exists($t->getInterwiki(),$customCaptions) ) {
804 // captions from 'search-interwiki-custom'
805 $caption = $customCaptions[$t->getInterwiki()];
806 } else {
807 // default is to show the hostname of the other wiki which might suck
808 // if there are many wikis on one hostname
809 $parsed = wfParseUrl( $t->getFullURL() );
810 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
811 }
812 // "more results" link (special page stuff could be localized, but we might not know target lang)
813 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
814 $searchLink = Linker::linkKnown(
815 $searchTitle,
816 $this->msg( 'search-interwiki-more' )->text(),
817 array(),
818 array(
819 'search' => $query,
820 'fulltext' => 'Search'
821 )
822 );
823 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
824 {$searchLink}</span>{$caption}</div>\n<ul>";
825 }
826
827 $out .= "<li>{$link} {$redirect}</li>\n";
828 wfProfileOut( __METHOD__ );
829 return $out;
830 }
831
832 /**
833 * @param $profile
834 * @param $term
835 * @return String
836 */
837 protected function getProfileForm( $profile, $term ) {
838 // Hidden stuff
839 $opts = array();
840 $opts['redirs'] = $this->searchRedirects;
841 $opts['profile'] = $this->profile;
842
843 if ( $profile === 'advanced' ) {
844 return $this->powerSearchBox( $term, $opts );
845 } else {
846 $form = '';
847 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
848 return $form;
849 }
850 }
851
852 /**
853 * Generates the power search box at [[Special:Search]]
854 *
855 * @param $term String: search term
856 * @param $opts array
857 * @return String: HTML form
858 */
859 protected function powerSearchBox( $term, $opts ) {
860 // Groups namespaces into rows according to subject
861 $rows = array();
862 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
863 $subject = MWNamespace::getSubject( $namespace );
864 if( !array_key_exists( $subject, $rows ) ) {
865 $rows[$subject] = "";
866 }
867 $name = str_replace( '_', ' ', $name );
868 if( $name == '' ) {
869 $name = $this->msg( 'blanknamespace' )->text();
870 }
871 $rows[$subject] .=
872 Xml::openElement(
873 'td', array( 'style' => 'white-space: nowrap' )
874 ) .
875 Xml::checkLabel(
876 $name,
877 "ns{$namespace}",
878 "mw-search-ns{$namespace}",
879 in_array( $namespace, $this->namespaces )
880 ) .
881 Xml::closeElement( 'td' );
882 }
883 $rows = array_values( $rows );
884 $numRows = count( $rows );
885
886 // Lays out namespaces in multiple floating two-column tables so they'll
887 // be arranged nicely while still accommodating different screen widths
888 $namespaceTables = '';
889 for( $i = 0; $i < $numRows; $i += 4 ) {
890 $namespaceTables .= Xml::openElement(
891 'table',
892 array( 'cellpadding' => 0, 'cellspacing' => 0 )
893 );
894 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
895 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
896 }
897 $namespaceTables .= Xml::closeElement( 'table' );
898 }
899
900 $showSections = array( 'namespaceTables' => $namespaceTables );
901
902 // Show redirects check only if backend supports it
903 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
904 $showSections['redirects'] =
905 Xml::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects );
906 }
907
908 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
909
910 $hidden = '';
911 unset( $opts['redirs'] );
912 foreach( $opts as $key => $value ) {
913 $hidden .= Html::hidden( $key, $value );
914 }
915 // Return final output
916 return
917 Xml::openElement(
918 'fieldset',
919 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
920 ) .
921 Xml::element( 'legend', null, $this->msg('powersearch-legend' )->text() ) .
922 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
923 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
924 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
925 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
926 $hidden .
927 Xml::closeElement( 'fieldset' );
928 }
929
930 /**
931 * @return array
932 */
933 protected function getSearchProfiles() {
934 // Builds list of Search Types (profiles)
935 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
936
937 $profiles = array(
938 'default' => array(
939 'message' => 'searchprofile-articles',
940 'tooltip' => 'searchprofile-articles-tooltip',
941 'namespaces' => SearchEngine::defaultNamespaces(),
942 'namespace-messages' => SearchEngine::namespacesAsText(
943 SearchEngine::defaultNamespaces()
944 ),
945 ),
946 'images' => array(
947 'message' => 'searchprofile-images',
948 'tooltip' => 'searchprofile-images-tooltip',
949 'namespaces' => array( NS_FILE ),
950 ),
951 'help' => array(
952 'message' => 'searchprofile-project',
953 'tooltip' => 'searchprofile-project-tooltip',
954 'namespaces' => SearchEngine::helpNamespaces(),
955 'namespace-messages' => SearchEngine::namespacesAsText(
956 SearchEngine::helpNamespaces()
957 ),
958 ),
959 'all' => array(
960 'message' => 'searchprofile-everything',
961 'tooltip' => 'searchprofile-everything-tooltip',
962 'namespaces' => $nsAllSet,
963 ),
964 'advanced' => array(
965 'message' => 'searchprofile-advanced',
966 'tooltip' => 'searchprofile-advanced-tooltip',
967 'namespaces' => self::NAMESPACES_CURRENT,
968 )
969 );
970
971 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
972
973 foreach( $profiles as &$data ) {
974 if ( !is_array( $data['namespaces'] ) ) continue;
975 sort( $data['namespaces'] );
976 }
977
978 return $profiles;
979 }
980
981 /**
982 * @param $term
983 * @param $resultsShown
984 * @param $totalNum
985 * @return string
986 */
987 protected function formHeader( $term, $resultsShown, $totalNum ) {
988 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
989
990 $bareterm = $term;
991 if( $this->startsWithImage( $term ) ) {
992 // Deletes prefixes
993 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
994 }
995
996 $profiles = $this->getSearchProfiles();
997 $lang = $this->getLanguage();
998
999 // Outputs XML for Search Types
1000 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1001 $out .= Xml::openElement( 'ul' );
1002 foreach ( $profiles as $id => $profile ) {
1003 if ( !isset( $profile['parameters'] ) ) {
1004 $profile['parameters'] = array();
1005 }
1006 $profile['parameters']['profile'] = $id;
1007
1008 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1009 $lang->commaList( $profile['namespace-messages'] ) : null;
1010 $out .= Xml::tags(
1011 'li',
1012 array(
1013 'class' => $this->profile === $id ? 'current' : 'normal'
1014 ),
1015 $this->makeSearchLink(
1016 $bareterm,
1017 array(),
1018 $this->msg( $profile['message'] )->text(),
1019 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1020 $profile['parameters']
1021 )
1022 );
1023 }
1024 $out .= Xml::closeElement( 'ul' );
1025 $out .= Xml::closeElement('div') ;
1026
1027 // Results-info
1028 if ( $resultsShown > 0 ) {
1029 if ( $totalNum > 0 ) {
1030 $top = $this->msg( 'showingresultsheader' )
1031 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1032 ->params( wfEscapeWikiText( $term ) )
1033 ->numParams( $resultsShown )
1034 ->parse();
1035 } elseif ( $resultsShown >= $this->limit ) {
1036 $top = $this->msg( 'showingresults' )
1037 ->numParams( $this->limit, $this->offset + 1 )
1038 ->parse();
1039 } else {
1040 $top = $this->msg( 'showingresultsnum' )
1041 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1042 ->parse();
1043 }
1044 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1045 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1046 );
1047 }
1048
1049 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1050 $out .= Xml::closeElement('div');
1051
1052 return $out;
1053 }
1054
1055 /**
1056 * @param $term string
1057 * @return string
1058 */
1059 protected function shortDialog( $term ) {
1060 $out = Html::hidden( 'title', $this->getTitle()->getPrefixedText() );
1061 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1062 // Term box
1063 $out .= Html::input( 'search', $term, 'search', array(
1064 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1065 'size' => '50',
1066 'autofocus'
1067 ) ) . "\n";
1068 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1069 $out .= Xml::submitButton( $this->msg( 'searchbutton' )->text() ) . "\n";
1070 return $out . $this->didYouMeanHtml;
1071 }
1072
1073 /**
1074 * Make a search link with some target namespaces
1075 *
1076 * @param $term String
1077 * @param $namespaces Array ignored
1078 * @param $label String: link's text
1079 * @param $tooltip String: link's tooltip
1080 * @param $params Array: query string parameters
1081 * @return String: HTML fragment
1082 */
1083 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1084 $opt = $params;
1085 foreach( $namespaces as $n ) {
1086 $opt['ns' . $n] = 1;
1087 }
1088 $opt['redirs'] = $this->searchRedirects;
1089
1090 $stParams = array_merge(
1091 array(
1092 'search' => $term,
1093 'fulltext' => $this->msg( 'search' )->text()
1094 ),
1095 $opt
1096 );
1097
1098 return Xml::element(
1099 'a',
1100 array(
1101 'href' => $this->getTitle()->getLocalURL( $stParams ),
1102 'title' => $tooltip),
1103 $label
1104 );
1105 }
1106
1107 /**
1108 * Check if query starts with image: prefix
1109 *
1110 * @param $term String: the string to check
1111 * @return Boolean
1112 */
1113 protected function startsWithImage( $term ) {
1114 global $wgContLang;
1115
1116 $p = explode( ':', $term );
1117 if( count( $p ) > 1 ) {
1118 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1119 }
1120 return false;
1121 }
1122
1123 /**
1124 * Check if query starts with all: prefix
1125 *
1126 * @param $term String: the string to check
1127 * @return Boolean
1128 */
1129 protected function startsWithAll( $term ) {
1130
1131 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1132
1133 $p = explode( ':', $term );
1134 if( count( $p ) > 1 ) {
1135 return $p[0] == $allkeyword;
1136 }
1137 return false;
1138 }
1139
1140 /**
1141 * @since 1.18
1142 *
1143 * @return SearchEngine
1144 */
1145 public function getSearchEngine() {
1146 if ( $this->searchEngine === null ) {
1147 $this->searchEngine = SearchEngine::create();
1148 }
1149 return $this->searchEngine;
1150 }
1151
1152 /**
1153 * Users of hook SpecialSearchSetupEngine can use this to
1154 * add more params to links to not lose selection when
1155 * user navigates search results.
1156 * @since 1.18
1157 *
1158 * @param $key
1159 * @param $value
1160 */
1161 public function setExtraParam( $key, $value ) {
1162 $this->extraParams[$key] = $value;
1163 }
1164
1165 }