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