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