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