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