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