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