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