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