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