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