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