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