Follow-up for r50207: mysql won't estimate total number of hits, so don't show it...
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * Run text & title search and display the output
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * Entry point
28 *
29 * @param $par String: (default '')
30 */
31 function wfSpecialSearch( $par = '' ) {
32 global $wgRequest, $wgUser, $wgUseOldSearchUI;
33 // Strip underscores from title parameter; most of the time we'll want
34 // text form here. But don't strip underscores from actual text params!
35 $titleParam = str_replace( '_', ' ', $par );
36 // Fetch the search term
37 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
38 $class = $wgUseOldSearchUI ? 'SpecialSearchOld' : 'SpecialSearch';
39 $searchPage = new $class( $wgRequest, $wgUser );
40 if( $wgRequest->getVal( 'fulltext' )
41 || !is_null( $wgRequest->getVal( 'offset' ))
42 || !is_null( $wgRequest->getVal( 'searchx' )) )
43 {
44 $searchPage->showResults( $search );
45 } else {
46 $searchPage->goResult( $search );
47 }
48 }
49
50 /**
51 * implements Special:Search - Run text & title search and display the output
52 * @ingroup SpecialPage
53 */
54 class SpecialSearch {
55
56 /**
57 * Set up basic search parameters from the request and user settings.
58 * Typically you'll pass $wgRequest and $wgUser.
59 *
60 * @param WebRequest $request
61 * @param User $user
62 * @public
63 */
64 function __construct( &$request, &$user ) {
65 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
66 $this->mPrefix = $request->getVal('prefix', '');
67 # Extract requested namespaces
68 $this->namespaces = $this->powerSearch( $request );
69 if( empty( $this->namespaces ) ) {
70 $this->namespaces = SearchEngine::userNamespaces( $user );
71 }
72 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
73 $this->searchAdvanced = $request->getVal( 'advanced' );
74 $this->active = 'advanced';
75 $this->sk = $user->getSkin();
76 $this->didYouMeanHtml = ''; # html of did you mean... link
77 $this->fulltext = $request->getVal('fulltext');
78 }
79
80 /**
81 * If an exact title match can be found, jump straight ahead to it.
82 * @param string $term
83 */
84 public function goResult( $term ) {
85 global $wgOut;
86 $this->setupPage( $term );
87 # Try to go to page as entered.
88 $t = Title::newFromText( $term );
89 # If the string cannot be used to create a title
90 if( is_null( $t ) ) {
91 return $this->showResults( $term );
92 }
93 # If there's an exact or very near match, jump right there.
94 $t = SearchEngine::getNearMatch( $term );
95 if( !is_null( $t ) ) {
96 $wgOut->redirect( $t->getFullURL() );
97 return;
98 }
99 # No match, generate an edit URL
100 $t = Title::newFromText( $term );
101 if( !is_null( $t ) ) {
102 global $wgGoToEdit;
103 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
104 # If the feature is enabled, go straight to the edit page
105 if( $wgGoToEdit ) {
106 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
107 return;
108 }
109 }
110 return $this->showResults( $term );
111 }
112
113 /**
114 * @param string $term
115 */
116 public function showResults( $term ) {
117 global $wgOut, $wgUser, $wgDisableTextSearch, $wgContLang;
118 wfProfileIn( __METHOD__ );
119
120 $sk = $wgUser->getSkin();
121
122 $this->searchEngine = SearchEngine::create();
123 $search =& $this->searchEngine;
124 $search->setLimitOffset( $this->limit, $this->offset );
125 $search->setNamespaces( $this->namespaces );
126 $search->showRedirects = $this->searchRedirects;
127 $search->prefix = $this->mPrefix;
128 $term = $search->transformSearchTerm($term);
129
130 $this->setupPage( $term );
131
132 if( $wgDisableTextSearch ) {
133 global $wgSearchForwardUrl;
134 if( $wgSearchForwardUrl ) {
135 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
136 $wgOut->redirect( $url );
137 wfProfileOut( __METHOD__ );
138 return;
139 }
140 global $wgInputEncoding;
141 $wgOut->addHTML(
142 Xml::openElement( 'fieldset' ) .
143 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
144 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
145 wfMsg( 'googlesearch',
146 htmlspecialchars( $term ),
147 htmlspecialchars( $wgInputEncoding ),
148 htmlspecialchars( wfMsg( 'searchbutton' ) )
149 ) .
150 Xml::closeElement( 'fieldset' )
151 );
152 wfProfileOut( __METHOD__ );
153 return;
154 }
155
156 $t = Title::newFromText( $term );
157
158 // fetch search results
159 $rewritten = $search->replacePrefixes($term);
160
161 $titleMatches = $search->searchTitle( $rewritten );
162 if( !($titleMatches instanceof SearchResultTooMany))
163 $textMatches = $search->searchText( $rewritten );
164
165 // did you mean... suggestions
166 if( $textMatches && $textMatches->hasSuggestion() ) {
167 $st = SpecialPage::getTitleFor( 'Search' );
168 # mirror Go/Search behaviour of original request ..
169 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
170 if($this->fulltext != NULL)
171 $didYouMeanParams['fulltext'] = $this->fulltext;
172 $stParams = wfArrayToCGI(
173 $didYouMeanParams,
174 $this->powerSearchOptions()
175 );
176 $suggestLink = $sk->makeKnownLinkObj( $st,
177 $textMatches->getSuggestionSnippet(),
178 $stParams );
179
180 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
181 }
182
183 // start rendering the page
184 $wgOut->addHtml(
185 Xml::openElement( 'table', array( 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
186 Xml::openElement( 'tr' ) .
187 Xml::openElement( 'td' ) . "\n" .
188 ( $this->searchAdvanced ? $this->powerSearchBox( $term ) : $this->shortDialog( $term ) ) .
189 Xml::closeElement('td') .
190 Xml::closeElement('tr') .
191 Xml::closeElement('table')
192 );
193
194 // Sometimes the search engine knows there are too many hits
195 if( $titleMatches instanceof SearchResultTooMany ) {
196 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
197 wfProfileOut( __METHOD__ );
198 return;
199 }
200
201 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
202 if( '' === trim( $term ) || $filePrefix === trim( $term ) ) {
203 $wgOut->addHTML( $this->searchAdvanced ? $this->powerSearchFocus() : $this->searchFocus() );
204 // Empty query -- straight view of search form
205 wfProfileOut( __METHOD__ );
206 return;
207 }
208
209
210 // Get number of results
211 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
212 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
213 // Total initial query matches (possible false positives)
214 $num = $titleMatchesNum + $textMatchesNum;
215
216 // Get total actual results (after second filtering, if any)
217 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
218 $titleMatches->getTotalHits() : $titleMatchesNum;
219 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
220 $textMatches->getTotalHits() : $textMatchesNum;
221
222 // get total number of results if backend can calculate it
223 $totalRes = 0;
224 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
225 $totalRes += $titleMatches->getTotalHits();
226 if($textMatches && !is_null( $textMatches->getTotalHits() ))
227 $totalRes += $textMatches->getTotalHits();
228
229 // show number of results and current offset
230 $wgOut->addHTML( $this->formHeader($term, $num, $totalRes));
231
232 $wgOut->addHtml( "<div class='searchresults'>" );
233
234 // show direct page/create link
235 if( !is_null($t) ) {
236 if( !$t->exists() ) {
237 $wgOut->addWikiMsg( 'searchmenu-new', wfEscapeWikiText( $t->getPrefixedText() ) );
238 } else {
239 $wgOut->addWikiMsg( 'searchmenu-exists', wfEscapeWikiText( $t->getPrefixedText() ) );
240 }
241 }
242
243 // prev/next links
244 if( $num || $this->offset ) {
245 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
246 SpecialPage::getTitleFor( 'Search' ),
247 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
248 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
249 );
250 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
251 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
252 } else {
253 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
254 }
255
256
257 if( $titleMatches ) {
258 if( $numTitleMatches > 0 ) {
259 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
260 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
261 }
262 $titleMatches->free();
263 }
264 if( $textMatches ) {
265 // output appropriate heading
266 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
267 // if no title matches the heading is redundant
268 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
269 } elseif( $totalRes == 0 ) {
270 # Don't show the 'no text matches' if we received title matches
271 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
272 }
273 // show interwiki results if any
274 if( $textMatches->hasInterwikiResults() ) {
275 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
276 }
277 // show results
278 if( $numTextMatches > 0 ) {
279 $wgOut->addHTML( $this->showMatches( $textMatches ) );
280 }
281
282 $textMatches->free();
283 }
284 if( $num === 0 ) {
285 $wgOut->addWikiMsg( 'search-nonefound' );
286 }
287 $wgOut->addHtml( "</div>" );
288 if( $num === 0 ) {
289 $wgOut->addHTML( $this->searchAdvanced ? $this->powerSearchFocus() : $this->searchFocus() );
290 }
291
292 if( $num || $this->offset ) {
293 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
294 }
295 wfProfileOut( __METHOD__ );
296 }
297
298 /**
299 *
300 */
301 protected function setupPage( $term ) {
302 global $wgOut;
303 // Figure out the active search profile header
304 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
305 if( $this->searchAdvanced )
306 $this->active = 'advanced';
307 else if( $this->namespaces === array(NS_FILE) || $this->startsWithImage( $term ) )
308 $this->active = 'images';
309 elseif( $this->namespaces === $nsAllSet || $this->startsWithAll( $term ) )
310 $this->active = 'all';
311 elseif( $this->namespaces === SearchEngine::defaultNamespaces() )
312 $this->active = 'default';
313 elseif( $this->namespaces === SearchEngine::helpNamespaces() )
314 $this->active = 'help';
315 else
316 $this->active = 'advanced';
317 # Should advanced UI be used?
318 $this->searchAdvanced = ($this->active === 'advanced');
319 if( !empty( $term ) ) {
320 $wgOut->setPageTitle( wfMsg( 'searchresults') );
321 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
322 }
323 $wgOut->setArticleRelated( false );
324 $wgOut->setRobotPolicy( 'noindex,nofollow' );
325 }
326
327 /**
328 * Extract "power search" namespace settings from the request object,
329 * returning a list of index numbers to search.
330 *
331 * @param WebRequest $request
332 * @return array
333 */
334 protected function powerSearch( &$request ) {
335 $arr = array();
336 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
337 if( $request->getCheck( 'ns' . $ns ) ) {
338 $arr[] = $ns;
339 }
340 }
341 return $arr;
342 }
343
344 /**
345 * Reconstruct the 'power search' options for links
346 * @return array
347 */
348 protected function powerSearchOptions() {
349 $opt = array();
350 foreach( $this->namespaces as $n ) {
351 $opt['ns' . $n] = 1;
352 }
353 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
354 if( $this->searchAdvanced ) {
355 $opt['advanced'] = $this->searchAdvanced;
356 }
357 return $opt;
358 }
359
360 /**
361 * Show whole set of results
362 *
363 * @param SearchResultSet $matches
364 */
365 protected function showMatches( &$matches ) {
366 global $wgContLang;
367 wfProfileIn( __METHOD__ );
368
369 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
370
371 $out = "";
372 $infoLine = $matches->getInfo();
373 if( !is_null($infoLine) ) {
374 $out .= "\n<!-- {$infoLine} -->\n";
375 }
376 $off = $this->offset + 1;
377 $out .= "<ul class='mw-search-results'>\n";
378 while( $result = $matches->next() ) {
379 $out .= $this->showHit( $result, $terms );
380 }
381 $out .= "</ul>\n";
382
383 // convert the whole thing to desired language variant
384 $out = $wgContLang->convert( $out );
385 wfProfileOut( __METHOD__ );
386 return $out;
387 }
388
389 /**
390 * Format a single hit result
391 * @param SearchResult $result
392 * @param array $terms terms to highlight
393 */
394 protected function showHit( $result, $terms ) {
395 global $wgContLang, $wgLang, $wgUser;
396 wfProfileIn( __METHOD__ );
397
398 if( $result->isBrokenTitle() ) {
399 wfProfileOut( __METHOD__ );
400 return "<!-- Broken link in search result -->\n";
401 }
402
403 $sk = $wgUser->getSkin();
404 $t = $result->getTitle();
405
406 $link = $this->sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
407
408 //If page content is not readable, just return the title.
409 //This is not quite safe, but better than showing excerpts from non-readable pages
410 //Note that hiding the entry entirely would screw up paging.
411 if( !$t->userCanRead() ) {
412 wfProfileOut( __METHOD__ );
413 return "<li>{$link}</li>\n";
414 }
415
416 // If the page doesn't *exist*... our search index is out of date.
417 // The least confusing at this point is to drop the result.
418 // You may get less results, but... oh well. :P
419 if( $result->isMissingRevision() ) {
420 wfProfileOut( __METHOD__ );
421 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
422 }
423
424 // format redirects / relevant sections
425 $redirectTitle = $result->getRedirectTitle();
426 $redirectText = $result->getRedirectSnippet($terms);
427 $sectionTitle = $result->getSectionTitle();
428 $sectionText = $result->getSectionSnippet($terms);
429 $redirect = '';
430 if( !is_null($redirectTitle) )
431 $redirect = "<span class='searchalttitle'>"
432 .wfMsg('search-redirect',$this->sk->makeKnownLinkObj( $redirectTitle, $redirectText))
433 ."</span>";
434 $section = '';
435 if( !is_null($sectionTitle) )
436 $section = "<span class='searchalttitle'>"
437 .wfMsg('search-section', $this->sk->makeKnownLinkObj( $sectionTitle, $sectionText))
438 ."</span>";
439
440 // format text extract
441 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
442
443 // format score
444 if( is_null( $result->getScore() ) ) {
445 // Search engine doesn't report scoring info
446 $score = '';
447 } else {
448 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
449 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
450 . ' - ';
451 }
452
453 // format description
454 $byteSize = $result->getByteSize();
455 $wordCount = $result->getWordCount();
456 $timestamp = $result->getTimestamp();
457 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
458 $this->sk->formatSize( $byteSize ), $wordCount );
459 $date = $wgLang->timeanddate( $timestamp );
460
461 // link to related articles if supported
462 $related = '';
463 if( $result->hasRelated() ) {
464 $st = SpecialPage::getTitleFor( 'Search' );
465 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
466 array('search' => wfMsgForContent('searchrelated').':'.$t->getPrefixedText(),
467 'fulltext' => wfMsg('search') ));
468
469 $related = ' -- ' . $sk->makeKnownLinkObj( $st,
470 wfMsg('search-relatedarticle'), $stParams );
471 }
472
473 // Include a thumbnail for media files...
474 if( $t->getNamespace() == NS_FILE ) {
475 $img = wfFindFile( $t );
476 if( $img ) {
477 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
478 if( $thumb ) {
479 $desc = $img->getShortDesc();
480 wfProfileOut( __METHOD__ );
481 // Float doesn't seem to interact well with the bullets.
482 // Table messes up vertical alignment of the bullets.
483 // Bullets are therefore disabled (didn't look great anyway).
484 return "<li>" .
485 '<table class="searchResultImage">' .
486 '<tr>' .
487 '<td width="120" align="center" valign="top">' .
488 $thumb->toHtml( array( 'desc-link' => true ) ) .
489 '</td>' .
490 '<td valign="top">' .
491 $link .
492 $extract .
493 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
494 '</td>' .
495 '</tr>' .
496 '</table>' .
497 "</li>\n";
498 }
499 }
500 }
501
502 wfProfileOut( __METHOD__ );
503 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
504 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
505 "</li>\n";
506
507 }
508
509 /**
510 * Show results from other wikis
511 *
512 * @param SearchResultSet $matches
513 */
514 protected function showInterwiki( &$matches, $query ) {
515 global $wgContLang;
516 wfProfileIn( __METHOD__ );
517 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
518
519 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
520 wfMsg('search-interwiki-caption')."</div>\n";
521 $off = $this->offset + 1;
522 $out .= "<ul class='mw-search-iwresults'>\n";
523
524 // work out custom project captions
525 $customCaptions = array();
526 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
527 foreach($customLines as $line) {
528 $parts = explode(":",$line,2);
529 if(count($parts) == 2) // validate line
530 $customCaptions[$parts[0]] = $parts[1];
531 }
532
533 $prev = null;
534 while( $result = $matches->next() ) {
535 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
536 $prev = $result->getInterwikiPrefix();
537 }
538 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
539 $out .= "</ul></div>\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 * Show single interwiki link
549 *
550 * @param SearchResult $result
551 * @param string $lastInterwiki
552 * @param array $terms
553 * @param string $query
554 * @param array $customCaptions iw prefix -> caption
555 */
556 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
557 wfProfileIn( __METHOD__ );
558 global $wgContLang, $wgLang;
559
560 if( $result->isBrokenTitle() ) {
561 wfProfileOut( __METHOD__ );
562 return "<!-- Broken link in search result -->\n";
563 }
564
565 $t = $result->getTitle();
566
567 $link = $this->sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
568
569 // format redirect if any
570 $redirectTitle = $result->getRedirectTitle();
571 $redirectText = $result->getRedirectSnippet($terms);
572 $redirect = '';
573 if( !is_null($redirectTitle) )
574 $redirect = "<span class='searchalttitle'>"
575 .wfMsg('search-redirect',$this->sk->makeKnownLinkObj( $redirectTitle, $redirectText))
576 ."</span>";
577
578 $out = "";
579 // display project name
580 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
581 if( key_exists($t->getInterwiki(),$customCaptions) )
582 // captions from 'search-interwiki-custom'
583 $caption = $customCaptions[$t->getInterwiki()];
584 else{
585 // default is to show the hostname of the other wiki which might suck
586 // if there are many wikis on one hostname
587 $parsed = parse_url($t->getFullURL());
588 $caption = wfMsg('search-interwiki-default', $parsed['host']);
589 }
590 // "more results" link (special page stuff could be localized, but we might not know target lang)
591 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
592 $searchLink = $this->sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
593 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
594 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
595 {$searchLink}</span>{$caption}</div>\n<ul>";
596 }
597
598 $out .= "<li>{$link} {$redirect}</li>\n";
599 wfProfileOut( __METHOD__ );
600 return $out;
601 }
602
603
604 /**
605 * Generates the power search box at bottom of [[Special:Search]]
606 * @param $term string: search term
607 * @return $out string: HTML form
608 */
609 protected function powerSearchBox( $term ) {
610 global $wgScript;
611
612 $namespaces = SearchEngine::searchableNamespaces();
613
614 $tables = $this->namespaceTables( $namespaces );
615
616 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
617 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
618 $searchField = Xml::inputLabel( wfMsg('powersearch-field'), 'search', 'powerSearchText', 50, $term,
619 array( 'type' => 'text') );
620 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ) ) . "\n";
621 $searchTitle = SpecialPage::getTitleFor( 'Search' );
622
623 $redirectText = '';
624 // show redirects check only if backend supports it
625 if( $this->searchEngine->acceptListRedirects() ) {
626 $redirectText = "<p>". $redirect . " " . $redirectLabel ."</p>";
627 }
628
629 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
630 Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n" .
631 "<p>" .
632 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
633 "</p>\n" .
634 '<input type="hidden" name="advanced" value="'.$this->searchAdvanced."\"/>\n".
635 $tables .
636 "<hr style=\"clear: both;\" />\n".
637 $redirectText ."\n".
638 "<div style=\"padding-top:2px;padding-bottom:2px;\">".
639 $searchField .
640 "&nbsp;" .
641 Xml::hidden( 'fulltext', 'Advanced search' ) . "\n" .
642 $searchButton .
643 "</div>".
644 "</form>";
645 $t = Title::newFromText( $term );
646 /* if( $t != null && count($this->namespaces) === 1 ) {
647 $out .= wfMsgExt( 'searchmenu-prefix', array('parseinline'), $term );
648 } */
649 return Xml::openElement( 'fieldset', array('id' => 'mw-searchoptions','style' => 'margin:0em;') ) .
650 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
651 $out . $this->didYouMeanHtml .
652 Xml::closeElement( 'fieldset' );
653 }
654
655 protected function searchFocus() {
656 global $wgJsMimeType;
657 return "<script type=\"$wgJsMimeType\">" .
658 "hookEvent(\"load\", function() {" .
659 "document.getElementById('searchText').focus();" .
660 "});" .
661 "</script>";
662 }
663
664 protected function powerSearchFocus() {
665 global $wgJsMimeType;
666 return "<script type=\"$wgJsMimeType\">" .
667 "hookEvent(\"load\", function() {" .
668 "document.getElementById('powerSearchText').focus();" .
669 "});" .
670 "</script>";
671 }
672
673 protected function formHeader( $term, $resultsShown, $totalNum ) {
674 global $wgContLang, $wgCanonicalNamespaceNames, $wgLang;
675
676 $sep = '&nbsp;&nbsp;&nbsp;';
677 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
678 $out .= Xml::openElement('div');
679
680 $bareterm = $term;
681 if( $this->startsWithImage( $term ) )
682 $bareterm = substr( $term, strpos( $term, ':' ) + 1 ); // delete all/image prefix
683
684 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
685
686 // search profiles headers
687 $m = wfMsg( 'searchprofile-articles' );
688 $tt = wfMsg( 'searchprofile-articles-tooltip',
689 $wgLang->commaList( SearchEngine::namespacesAsText( SearchEngine::defaultNamespaces() ) ) );
690 $tt = Sanitizer::decodeCharReferences( $tt ); // need to allow entities
691 if( $this->active == 'default' ) {
692 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
693 } else {
694 $out .= $this->makeSearchLink( $bareterm, SearchEngine::defaultNamespaces(), $m, $tt );
695 }
696 $out .= $sep;
697
698 $m = wfMsg( 'searchprofile-images' );
699 $tt = wfMsg( 'searchprofile-images-tooltip' );
700 if( $this->active == 'images' ) {
701 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
702 } else {
703 $out .= $this->makeSearchLink( $bareterm, array( NS_FILE ) , $m, $tt );
704 }
705 $out .= $sep;
706
707 $m = wfMsg( 'searchprofile-project' );
708 $tt = wfMsg( 'searchprofile-project-tooltip',
709 $wgLang->commaList( SearchEngine::namespacesAsText( SearchEngine::helpNamespaces() ) ) );
710 $tt = Sanitizer::decodeCharReferences( $tt ); // need to allow entities
711 if( $this->active == 'help' ) {
712 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
713 } else {
714 $out .= $this->makeSearchLink( $bareterm, SearchEngine::helpNamespaces(), $m, $tt );
715 }
716 $out .= $sep;
717
718 $m = wfMsg( 'searchprofile-everything' );
719 $tt = wfMsg( 'searchprofile-everything-tooltip' );
720 if( $this->active == 'all' ) {
721 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
722 } else {
723 $out .= $this->makeSearchLink( $bareterm, $nsAllSet, $m, $tt );
724 }
725 $out .= $sep;
726
727 $m = wfMsg( 'searchprofile-advanced' );
728 $tt = wfMsg( 'searchprofile-advanced-tooltip' );
729 if( $this->active == 'advanced' ) {
730 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
731 } else {
732 $out .= $this->makeSearchLink( $bareterm, $this->namespaces, $m, $tt, array( 'advanced' => '1' ) );
733 }
734 $out .= Xml::closeElement('div') ;
735
736 if ( $resultsShown > 0 ) {
737 if ( $totalNum > 0 ){
738 $top = wfMsgExt('showingresultsheader', array( 'parseinline' ),
739 $this->offset+1, $this->offset+$resultsShown, $totalNum, $term, $resultsShown );
740 } elseif ( $resultsShown >= $this->limit ) {
741 $top = wfShowingResults( $this->offset, $this->limit );
742 } else {
743 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
744 }
745 $out .= "<p>{$top}</p>\n";
746 } else
747 $out .= "<p>&nbsp;</p>\n";
748
749 $out .= Xml::closeElement('div') ;
750
751 return $out;
752 }
753
754 protected function shortDialog( $term ) {
755 global $wgScript;
756 $searchTitle = SpecialPage::getTitleFor( 'Search' );
757 $searchable = SearchEngine::searchableNamespaces();
758 $out = Xml::openElement( 'form', array( 'id' => 'search', 'method' => 'get', 'action' => $wgScript ) );
759 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
760 // show namespaces only for advanced search
761 if( $this->active == 'advanced' ) {
762 $active = array();
763 foreach( $this->namespaces as $ns ) {
764 $active[$ns] = $searchable[$ns];
765 }
766 $out .= wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) . "<br/>\n";
767 $out .= $this->namespaceTables( $active, 1 )."<br/>\n";
768 // Still keep namespace settings otherwise, but don't show them
769 } else {
770 foreach( $this->namespaces as $ns ) {
771 $out .= Xml::hidden( "ns{$ns}", '1' );
772 }
773 }
774 // Keep redirect setting
775 $out .= Xml::hidden( "redirs", (int)$this->searchRedirects );
776 // Term box
777 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . "\n";
778 $out .= Xml::hidden( 'fulltext', 'Search' );
779 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
780 //$out .= ' (' . wfMsgExt('searchmenu-help',array('parseinline') ) . ')';
781 $out .= Xml::closeElement( 'form' );
782 // Add prefix link for single-namespace searches
783 $t = Title::newFromText( $term );
784 /*if( $t != null && count($this->namespaces) === 1 ) {
785 $out .= wfMsgExt( 'searchmenu-prefix', array('parseinline'), $term );
786 }*/
787 return $out . $this->didYouMeanHtml;
788 }
789
790 /** Make a search link with some target namespaces */
791 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
792 $opt = $params;
793 foreach( $namespaces as $n ) {
794 $opt['ns' . $n] = 1;
795 }
796 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
797
798 $st = SpecialPage::getTitleFor( 'Search' );
799 $stParams = wfArrayToCGI( array( 'search' => $term, 'fulltext' => wfMsg( 'search' ) ), $opt );
800
801 return Xml::element( 'a',
802 array( 'href'=> $st->getLocalURL( $stParams ), 'title' => $tooltip ),
803 $label );
804 }
805
806 /** Check if query starts with image: prefix */
807 protected function startsWithImage( $term ) {
808 global $wgContLang;
809
810 $p = explode( ':', $term );
811 if( count( $p ) > 1 ) {
812 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
813 }
814 return false;
815 }
816
817 /** Check if query starts with all: prefix */
818 protected function startsWithAll( $term ) {
819
820 $allkeyword = wfMsgForContent('searchall');
821
822 $p = explode( ':', $term );
823 if( count( $p ) > 1 ) {
824 return $p[0] == $allkeyword;
825 }
826 return false;
827 }
828
829 protected function namespaceTables( $namespaces, $rowsPerTable = 3 ) {
830 global $wgContLang;
831 // Group namespaces into rows according to subject.
832 // Try not to make too many assumptions about namespace numbering.
833 $rows = array();
834 $tables = "";
835 foreach( $namespaces as $ns => $name ) {
836 $subj = MWNamespace::getSubject( $ns );
837 if( !array_key_exists( $subj, $rows ) ) {
838 $rows[$subj] = "";
839 }
840 $name = str_replace( '_', ' ', $name );
841 if( '' == $name ) {
842 $name = wfMsg( 'blanknamespace' );
843 }
844 $rows[$subj] .= Xml::openElement( 'td', array( 'style' => 'white-space: nowrap' ) ) .
845 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
846 Xml::closeElement( 'td' ) . "\n";
847 }
848 $rows = array_values( $rows );
849 $numRows = count( $rows );
850 // Lay out namespaces in multiple floating two-column tables so they'll
851 // be arranged nicely while still accommodating different screen widths
852 // Float to the right on RTL wikis
853 $tableStyle = $wgContLang->isRTL() ?
854 'float: right; margin: 0 0 0em 1em' : 'float: left; margin: 0 1em 0em 0';
855 // Build the final HTML table...
856 for( $i = 0; $i < $numRows; $i += $rowsPerTable ) {
857 $tables .= Xml::openElement( 'table', array( 'style' => $tableStyle ) );
858 for( $j = $i; $j < $i + $rowsPerTable && $j < $numRows; $j++ ) {
859 $tables .= "<tr>\n" . $rows[$j] . "</tr>";
860 }
861 $tables .= Xml::closeElement( 'table' ) . "\n";
862 }
863 return $tables;
864 }
865 }
866
867 /**
868 * implements Special:Search - Run text & title search and display the output
869 * @ingroup SpecialPage
870 */
871 class SpecialSearchOld {
872
873 /**
874 * Set up basic search parameters from the request and user settings.
875 * Typically you'll pass $wgRequest and $wgUser.
876 *
877 * @param WebRequest $request
878 * @param User $user
879 * @public
880 */
881 function __construct( &$request, &$user ) {
882 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
883 $this->mPrefix = $request->getVal('prefix', '');
884 $this->namespaces = $this->powerSearch( $request );
885 if( empty( $this->namespaces ) ) {
886 $this->namespaces = SearchEngine::userNamespaces( $user );
887 }
888
889 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
890 $this->fulltext = $request->getVal('fulltext');
891 }
892
893 /**
894 * If an exact title match can be found, jump straight ahead to it.
895 * @param string $term
896 * @public
897 */
898 function goResult( $term ) {
899 global $wgOut;
900 global $wgGoToEdit;
901
902 $this->setupPage( $term );
903
904 # Try to go to page as entered.
905 $t = Title::newFromText( $term );
906
907 # If the string cannot be used to create a title
908 if( is_null( $t ) ){
909 return $this->showResults( $term );
910 }
911
912 # If there's an exact or very near match, jump right there.
913 $t = SearchEngine::getNearMatch( $term );
914 if( !is_null( $t ) ) {
915 $wgOut->redirect( $t->getFullURL() );
916 return;
917 }
918
919 # No match, generate an edit URL
920 $t = Title::newFromText( $term );
921 if( ! is_null( $t ) ) {
922 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
923 # If the feature is enabled, go straight to the edit page
924 if ( $wgGoToEdit ) {
925 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
926 return;
927 }
928 }
929
930 $extra = $wgOut->parse( '=='.wfMsgNoTrans( 'notitlematches' )."==\n" );
931 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
932 $extra .= wfMsgExt( 'noexactmatch', 'parse', wfEscapeWikiText( $term ) );
933 } else {
934 $extra .= wfMsgExt( 'noexactmatch-nocreate', 'parse', wfEscapeWikiText( $term ) );
935 }
936
937 $this->showResults( $term, $extra );
938 }
939
940 /**
941 * @param string $term
942 * @param string $extra Extra HTML to add after "did you mean"
943 */
944 public function showResults( $term, $extra = '' ) {
945 wfProfileIn( __METHOD__ );
946 global $wgOut, $wgUser;
947 $sk = $wgUser->getSkin();
948
949 $search = SearchEngine::create();
950 $search->setLimitOffset( $this->limit, $this->offset );
951 $search->setNamespaces( $this->namespaces );
952 $search->showRedirects = $this->searchRedirects;
953 $search->prefix = $this->mPrefix;
954 $term = $search->transformSearchTerm($term);
955
956 $this->setupPage( $term );
957
958 $rewritten = $search->replacePrefixes($term);
959 $titleMatches = $search->searchTitle( $rewritten );
960 $textMatches = $search->searchText( $rewritten );
961
962 // did you mean... suggestions
963 if($textMatches && $textMatches->hasSuggestion()){
964 $st = SpecialPage::getTitleFor( 'Search' );
965
966 # mirror Go/Search behaviour of original request
967 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
968 if($this->fulltext != NULL)
969 $didYouMeanParams['fulltext'] = $this->fulltext;
970 $stParams = wfArrayToCGI(
971 $didYouMeanParams,
972 $this->powerSearchOptions()
973 );
974
975 $suggestLink = $sk->makeKnownLinkObj( $st,
976 $textMatches->getSuggestionSnippet(),
977 $stParams );
978
979 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
980 }
981
982 $wgOut->addHTML( $extra );
983
984 $wgOut->wrapWikiMsg( "<div class='mw-searchresult'>\n$1</div>", 'searchresulttext' );
985
986 if( '' === trim( $term ) ) {
987 // Empty query -- straight view of search form
988 $wgOut->setSubtitle( '' );
989 $wgOut->addHTML( $this->powerSearchBox( $term ) );
990 $wgOut->addHTML( $this->powerSearchFocus() );
991 wfProfileOut( __METHOD__ );
992 return;
993 }
994
995 global $wgDisableTextSearch;
996 if ( $wgDisableTextSearch ) {
997 global $wgSearchForwardUrl;
998 if( $wgSearchForwardUrl ) {
999 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
1000 $wgOut->redirect( $url );
1001 wfProfileOut( __METHOD__ );
1002 return;
1003 }
1004 global $wgInputEncoding;
1005 $wgOut->addHTML(
1006 Xml::openElement( 'fieldset' ) .
1007 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
1008 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
1009 wfMsg( 'googlesearch',
1010 htmlspecialchars( $term ),
1011 htmlspecialchars( $wgInputEncoding ),
1012 htmlspecialchars( wfMsg( 'searchbutton' ) )
1013 ) .
1014 Xml::closeElement( 'fieldset' )
1015 );
1016 wfProfileOut( __METHOD__ );
1017 return;
1018 }
1019
1020 $wgOut->addHTML( $this->shortDialog( $term ) );
1021
1022 // Sometimes the search engine knows there are too many hits
1023 if ($titleMatches instanceof SearchResultTooMany) {
1024 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
1025 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1026 $wgOut->addHTML( $this->powerSearchFocus() );
1027 wfProfileOut( __METHOD__ );
1028 return;
1029 }
1030
1031 // show number of results
1032 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
1033 + ( $textMatches ? $textMatches->numRows() : 0);
1034 $totalNum = 0;
1035 if($titleMatches && !is_null($titleMatches->getTotalHits()))
1036 $totalNum += $titleMatches->getTotalHits();
1037 if($textMatches && !is_null($textMatches->getTotalHits()))
1038 $totalNum += $textMatches->getTotalHits();
1039 if ( $num > 0 ) {
1040 if ( $totalNum > 0 ){
1041 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
1042 $this->offset+1, $this->offset+$num, $totalNum, $num );
1043 } elseif ( $num >= $this->limit ) {
1044 $top = wfShowingResults( $this->offset, $this->limit );
1045 } else {
1046 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
1047 }
1048 $wgOut->addHTML( "<p class='mw-search-numberresults'>{$top}</p>\n" );
1049 }
1050
1051 // prev/next links
1052 if( $num || $this->offset ) {
1053 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
1054 SpecialPage::getTitleFor( 'Search' ),
1055 wfArrayToCGI(
1056 $this->powerSearchOptions(),
1057 array( 'search' => $term ) ),
1058 ($num < $this->limit) );
1059 $wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
1060 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
1061 } else {
1062 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
1063 }
1064
1065 if( $titleMatches ) {
1066 if( $titleMatches->numRows() ) {
1067 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
1068 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
1069 }
1070 $titleMatches->free();
1071 }
1072
1073 if( $textMatches ) {
1074 // output appropriate heading
1075 if( $textMatches->numRows() ) {
1076 if($titleMatches)
1077 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
1078 else // if no title matches the heading is redundant
1079 $wgOut->addHTML("<hr/>");
1080 } elseif( $num == 0 ) {
1081 # Don't show the 'no text matches' if we received title matches
1082 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
1083 }
1084 // show interwiki results if any
1085 if( $textMatches->hasInterwikiResults() )
1086 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
1087 // show results
1088 if( $textMatches->numRows() )
1089 $wgOut->addHTML( $this->showMatches( $textMatches ) );
1090
1091 $textMatches->free();
1092 }
1093
1094 if ( $num == 0 ) {
1095 $wgOut->addWikiMsg( 'nonefound' );
1096 }
1097 if( $num || $this->offset ) {
1098 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
1099 }
1100 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1101 wfProfileOut( __METHOD__ );
1102 }
1103
1104 #------------------------------------------------------------------
1105 # Private methods below this line
1106
1107 /**
1108 *
1109 */
1110 function setupPage( $term ) {
1111 global $wgOut;
1112 if( !empty( $term ) ){
1113 $wgOut->setPageTitle( wfMsg( 'searchresults') );
1114 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term) ) );
1115 }
1116 $subtitlemsg = ( Title::newFromText( $term ) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
1117 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
1118 $wgOut->setArticleRelated( false );
1119 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1120 }
1121
1122 /**
1123 * Extract "power search" namespace settings from the request object,
1124 * returning a list of index numbers to search.
1125 *
1126 * @param WebRequest $request
1127 * @return array
1128 * @private
1129 */
1130 function powerSearch( &$request ) {
1131 $arr = array();
1132 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1133 if( $request->getCheck( 'ns' . $ns ) ) {
1134 $arr[] = $ns;
1135 }
1136 }
1137 return $arr;
1138 }
1139
1140 /**
1141 * Reconstruct the 'power search' options for links
1142 * @return array
1143 * @private
1144 */
1145 function powerSearchOptions() {
1146 $opt = array();
1147 foreach( $this->namespaces as $n ) {
1148 $opt['ns' . $n] = 1;
1149 }
1150 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
1151 return $opt;
1152 }
1153
1154 /**
1155 * Show whole set of results
1156 *
1157 * @param SearchResultSet $matches
1158 */
1159 function showMatches( &$matches ) {
1160 wfProfileIn( __METHOD__ );
1161
1162 global $wgContLang;
1163 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1164
1165 $out = "";
1166
1167 $infoLine = $matches->getInfo();
1168 if( !is_null($infoLine) )
1169 $out .= "\n<!-- {$infoLine} -->\n";
1170
1171
1172 $off = $this->offset + 1;
1173 $out .= "<ul class='mw-search-results'>\n";
1174
1175 while( $result = $matches->next() ) {
1176 $out .= $this->showHit( $result, $terms );
1177 }
1178 $out .= "</ul>\n";
1179
1180 // convert the whole thing to desired language variant
1181 global $wgContLang;
1182 $out = $wgContLang->convert( $out );
1183 wfProfileOut( __METHOD__ );
1184 return $out;
1185 }
1186
1187 /**
1188 * Format a single hit result
1189 * @param SearchResult $result
1190 * @param array $terms terms to highlight
1191 */
1192 function showHit( $result, $terms ) {
1193 wfProfileIn( __METHOD__ );
1194 global $wgUser, $wgContLang, $wgLang;
1195
1196 if( $result->isBrokenTitle() ) {
1197 wfProfileOut( __METHOD__ );
1198 return "<!-- Broken link in search result -->\n";
1199 }
1200
1201 $t = $result->getTitle();
1202 $sk = $wgUser->getSkin();
1203
1204 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
1205
1206 //If page content is not readable, just return the title.
1207 //This is not quite safe, but better than showing excerpts from non-readable pages
1208 //Note that hiding the entry entirely would screw up paging.
1209 if (!$t->userCanRead()) {
1210 wfProfileOut( __METHOD__ );
1211 return "<li>{$link}</li>\n";
1212 }
1213
1214 // If the page doesn't *exist*... our search index is out of date.
1215 // The least confusing at this point is to drop the result.
1216 // You may get less results, but... oh well. :P
1217 if( $result->isMissingRevision() ) {
1218 wfProfileOut( __METHOD__ );
1219 return "<!-- missing page " .
1220 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
1221 }
1222
1223 // format redirects / relevant sections
1224 $redirectTitle = $result->getRedirectTitle();
1225 $redirectText = $result->getRedirectSnippet($terms);
1226 $sectionTitle = $result->getSectionTitle();
1227 $sectionText = $result->getSectionSnippet($terms);
1228 $redirect = '';
1229 if( !is_null($redirectTitle) )
1230 $redirect = "<span class='searchalttitle'>"
1231 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
1232 ."</span>";
1233 $section = '';
1234 if( !is_null($sectionTitle) )
1235 $section = "<span class='searchalttitle'>"
1236 .wfMsg('search-section', $sk->makeKnownLinkObj( $sectionTitle, $sectionText))
1237 ."</span>";
1238
1239 // format text extract
1240 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
1241
1242 // format score
1243 if( is_null( $result->getScore() ) ) {
1244 // Search engine doesn't report scoring info
1245 $score = '';
1246 } else {
1247 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
1248 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
1249 . ' - ';
1250 }
1251
1252 // format description
1253 $byteSize = $result->getByteSize();
1254 $wordCount = $result->getWordCount();
1255 $timestamp = $result->getTimestamp();
1256 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
1257 $sk->formatSize( $byteSize ),
1258 $wordCount );
1259 $date = $wgLang->timeanddate( $timestamp );
1260
1261 // link to related articles if supported
1262 $related = '';
1263 if( $result->hasRelated() ){
1264 $st = SpecialPage::getTitleFor( 'Search' );
1265 $stParams = wfArrayToCGI( $this->powerSearchOptions(),
1266 array('search' => wfMsgForContent('searchrelated').':'.$t->getPrefixedText(),
1267 'fulltext' => wfMsg('search') ));
1268
1269 $related = ' -- ' . $sk->makeKnownLinkObj( $st,
1270 wfMsg('search-relatedarticle'), $stParams );
1271 }
1272
1273 // Include a thumbnail for media files...
1274 if( $t->getNamespace() == NS_FILE ) {
1275 $img = wfFindFile( $t );
1276 if( $img ) {
1277 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
1278 if( $thumb ) {
1279 $desc = $img->getShortDesc();
1280 wfProfileOut( __METHOD__ );
1281 // Ugly table. :D
1282 // Float doesn't seem to interact well with the bullets.
1283 // Table messes up vertical alignment of the bullet, but I'm
1284 // not sure what more I can do about that. :(
1285 return "<li>" .
1286 '<table class="searchResultImage">' .
1287 '<tr>' .
1288 '<td width="120" align="center">' .
1289 $thumb->toHtml( array( 'desc-link' => true ) ) .
1290 '</td>' .
1291 '<td valign="top">' .
1292 $link .
1293 $extract .
1294 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
1295 '</td>' .
1296 '</tr>' .
1297 '</table>' .
1298 "</li>\n";
1299 }
1300 }
1301 }
1302
1303 wfProfileOut( __METHOD__ );
1304 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
1305 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
1306 "</li>\n";
1307
1308 }
1309
1310 /**
1311 * Show results from other wikis
1312 *
1313 * @param SearchResultSet $matches
1314 */
1315 function showInterwiki( &$matches, $query ) {
1316 wfProfileIn( __METHOD__ );
1317
1318 global $wgContLang;
1319 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1320
1321 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
1322 $off = $this->offset + 1;
1323 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
1324
1325 // work out custom project captions
1326 $customCaptions = array();
1327 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
1328 foreach($customLines as $line){
1329 $parts = explode(":",$line,2);
1330 if(count($parts) == 2) // validate line
1331 $customCaptions[$parts[0]] = $parts[1];
1332 }
1333
1334
1335 $prev = null;
1336 while( $result = $matches->next() ) {
1337 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
1338 $prev = $result->getInterwikiPrefix();
1339 }
1340 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
1341 $out .= "</ul></div>\n";
1342
1343 // convert the whole thing to desired language variant
1344 global $wgContLang;
1345 $out = $wgContLang->convert( $out );
1346 wfProfileOut( __METHOD__ );
1347 return $out;
1348 }
1349
1350 /**
1351 * Show single interwiki link
1352 *
1353 * @param SearchResult $result
1354 * @param string $lastInterwiki
1355 * @param array $terms
1356 * @param string $query
1357 * @param array $customCaptions iw prefix -> caption
1358 */
1359 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
1360 wfProfileIn( __METHOD__ );
1361 global $wgUser, $wgContLang, $wgLang;
1362
1363 if( $result->isBrokenTitle() ) {
1364 wfProfileOut( __METHOD__ );
1365 return "<!-- Broken link in search result -->\n";
1366 }
1367
1368 $t = $result->getTitle();
1369 $sk = $wgUser->getSkin();
1370
1371 $link = $sk->makeKnownLinkObj( $t, $result->getTitleSnippet($terms));
1372
1373 // format redirect if any
1374 $redirectTitle = $result->getRedirectTitle();
1375 $redirectText = $result->getRedirectSnippet($terms);
1376 $redirect = '';
1377 if( !is_null($redirectTitle) )
1378 $redirect = "<span class='searchalttitle'>"
1379 .wfMsg('search-redirect',$sk->makeKnownLinkObj( $redirectTitle, $redirectText))
1380 ."</span>";
1381
1382 $out = "";
1383 // display project name
1384 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()){
1385 if( key_exists($t->getInterwiki(),$customCaptions) )
1386 // captions from 'search-interwiki-custom'
1387 $caption = $customCaptions[$t->getInterwiki()];
1388 else{
1389 // default is to show the hostname of the other wiki which might suck
1390 // if there are many wikis on one hostname
1391 $parsed = parse_url($t->getFullURL());
1392 $caption = wfMsg('search-interwiki-default', $parsed['host']);
1393 }
1394 // "more results" link (special page stuff could be localized, but we might not know target lang)
1395 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
1396 $searchLink = $sk->makeKnownLinkObj( $searchTitle, wfMsg('search-interwiki-more'),
1397 wfArrayToCGI(array('search' => $query, 'fulltext' => 'Search')));
1398 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
1399 }
1400
1401 $out .= "<li>{$link} {$redirect}</li>\n";
1402 wfProfileOut( __METHOD__ );
1403 return $out;
1404 }
1405
1406
1407 /**
1408 * Generates the power search box at bottom of [[Special:Search]]
1409 * @param $term string: search term
1410 * @return $out string: HTML form
1411 */
1412 function powerSearchBox( $term ) {
1413 global $wgScript, $wgContLang;
1414
1415 $namespaces = SearchEngine::searchableNamespaces();
1416
1417 // group namespaces into rows according to subject; try not to make too
1418 // many assumptions about namespace numbering
1419 $rows = array();
1420 foreach( $namespaces as $ns => $name ) {
1421 $subj = MWNamespace::getSubject( $ns );
1422 if( !array_key_exists( $subj, $rows ) ) {
1423 $rows[$subj] = "";
1424 }
1425 $name = str_replace( '_', ' ', $name );
1426 if( '' == $name ) {
1427 $name = wfMsg( 'blanknamespace' );
1428 }
1429 $rows[$subj] .= Xml::openElement( 'td', array( 'style' => 'white-space: nowrap' ) ) .
1430 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
1431 Xml::closeElement( 'td' ) . "\n";
1432 }
1433 $rows = array_values( $rows );
1434 $numRows = count( $rows );
1435
1436 // lay out namespaces in multiple floating two-column tables so they'll
1437 // be arranged nicely while still accommodating different screen widths
1438 $rowsPerTable = 3; // seems to look nice
1439
1440 // float to the right on RTL wikis
1441 $tableStyle = ( $wgContLang->isRTL() ?
1442 'float: right; margin: 0 0 1em 1em' :
1443 'float: left; margin: 0 1em 1em 0' );
1444
1445 $tables = "";
1446 for( $i = 0; $i < $numRows; $i += $rowsPerTable ) {
1447 $tables .= Xml::openElement( 'table', array( 'style' => $tableStyle ) );
1448 for( $j = $i; $j < $i + $rowsPerTable && $j < $numRows; $j++ ) {
1449 $tables .= "<tr>\n" . $rows[$j] . "</tr>";
1450 }
1451 $tables .= Xml::closeElement( 'table' ) . "\n";
1452 }
1453
1454 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
1455 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
1456 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
1457 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ) ) . "\n";
1458 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1459 $searchHiddens = Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
1460 $searchHiddens .= Xml::hidden( 'fulltext', 'Advanced search' ) . "\n";
1461
1462 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
1463 Xml::fieldset( wfMsg( 'powersearch-legend' ),
1464 "<p>" .
1465 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
1466 "</p>\n" .
1467 $tables .
1468 "<hr style=\"clear: both\" />\n" .
1469 "<p>" .
1470 $redirect . " " . $redirectLabel .
1471 "</p>\n" .
1472 wfMsgExt( 'powersearch-field', array( 'parseinline' ) ) .
1473 "&nbsp;" .
1474 $searchField .
1475 "&nbsp;" .
1476 $searchHiddens .
1477 $searchButton ) .
1478 "</form>";
1479
1480 return $out;
1481 }
1482
1483 function powerSearchFocus() {
1484 global $wgJsMimeType;
1485 return "<script type=\"$wgJsMimeType\">" .
1486 "hookEvent(\"load\", function(){" .
1487 "document.getElementById('powerSearchText').focus();" .
1488 "});" .
1489 "</script>";
1490 }
1491
1492 function shortDialog($term) {
1493 global $wgScript;
1494
1495 $out = Xml::openElement( 'form', array(
1496 'id' => 'search',
1497 'method' => 'get',
1498 'action' => $wgScript
1499 ));
1500 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1501 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
1502 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1503 if( in_array( $ns, $this->namespaces ) ) {
1504 $out .= Xml::hidden( "ns{$ns}", '1' );
1505 }
1506 }
1507 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() );
1508 $out .= Xml::hidden( 'fulltext', 'Search' );
1509 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
1510 $out .= Xml::closeElement( 'form' );
1511
1512 return $out;
1513 }
1514 }