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