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