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