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