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