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