7, it's 7! (follow up to r68824)
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 /**
3 * Copyright (C) 2004 Brion Vibber <brion@pobox.com>
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 /**
22 * Run text & title search and display the output
23 * @file
24 * @ingroup SpecialPage
25 */
26
27 /**
28 * Entry point
29 *
30 * @param $par String: (default '')
31 */
32 function wfSpecialSearch( $par = '' ) {
33 global $wgRequest, $wgUser;
34 // Strip underscores from title parameter; most of the time we'll want
35 // text form here. But don't strip underscores from actual text params!
36 $titleParam = str_replace( '_', ' ', $par );
37 // Fetch the search term
38 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
39 $searchPage = new SpecialSearch( $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 $request WebRequest
61 * @param $user User
62 */
63 public function __construct( &$request, &$user ) {
64 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
65 $this->mPrefix = $request->getVal('prefix', '');
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 $this->didYouMeanHtml = ''; # html of did you mean... link
76 $this->fulltext = $request->getVal('fulltext');
77 }
78
79 /**
80 * If an exact title match can be found, jump straight ahead to it.
81 *
82 * @param $term String
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 wfRunHooks( 'SpecialSearchGomatch', array( &$t ) );
97 $wgOut->redirect( $t->getFullURL() );
98 return;
99 }
100 # No match, generate an edit URL
101 $t = Title::newFromText( $term );
102 if( !is_null( $t ) ) {
103 global $wgGoToEdit;
104 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
105 # If the feature is enabled, go straight to the edit page
106 if( $wgGoToEdit ) {
107 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
108 return;
109 }
110 }
111 return $this->showResults( $term );
112 }
113
114 /**
115 * @param $term String
116 */
117 public function showResults( $term ) {
118 global $wgOut, $wgUser, $wgDisableTextSearch, $wgContLang, $wgScript;
119 wfProfileIn( __METHOD__ );
120
121 $sk = $wgUser->getSkin();
122
123 $this->searchEngine = SearchEngine::create();
124 $search =& $this->searchEngine;
125 $search->setLimitOffset( $this->limit, $this->offset );
126 $search->setNamespaces( $this->namespaces );
127 $search->showRedirects = $this->searchRedirects;
128 $search->prefix = $this->mPrefix;
129 $term = $search->transformSearchTerm($term);
130
131 $this->setupPage( $term );
132
133 if( $wgDisableTextSearch ) {
134 global $wgSearchForwardUrl;
135 if( $wgSearchForwardUrl ) {
136 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
137 $wgOut->redirect( $url );
138 wfProfileOut( __METHOD__ );
139 return;
140 }
141 global $wgInputEncoding;
142 $wgOut->addHTML(
143 Xml::openElement( 'fieldset' ) .
144 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
145 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
146 wfMsg( 'googlesearch',
147 htmlspecialchars( $term ),
148 htmlspecialchars( $wgInputEncoding ),
149 htmlspecialchars( wfMsg( 'searchbutton' ) )
150 ) .
151 Xml::closeElement( 'fieldset' )
152 );
153 wfProfileOut( __METHOD__ );
154 return;
155 }
156
157 $t = Title::newFromText( $term );
158
159 // fetch search results
160 $rewritten = $search->replacePrefixes($term);
161
162 $titleMatches = $search->searchTitle( $rewritten );
163 if( !($titleMatches instanceof SearchResultTooMany))
164 $textMatches = $search->searchText( $rewritten );
165
166 // did you mean... suggestions
167 if( $textMatches && $textMatches->hasSuggestion() ) {
168 $st = SpecialPage::getTitleFor( 'Search' );
169
170 # mirror Go/Search behaviour of original request ..
171 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
172
173 if($this->fulltext != null)
174 $didYouMeanParams['fulltext'] = $this->fulltext;
175
176 $stParams = array_merge(
177 $didYouMeanParams,
178 $this->powerSearchOptions()
179 );
180
181 $suggestionSnippet = $textMatches->getSuggestionSnippet();
182
183 if( $suggestionSnippet == '' )
184 $suggestionSnippet = null;
185
186 $suggestLink = $sk->linkKnown(
187 $st,
188 $suggestionSnippet,
189 array(),
190 $stParams
191 );
192
193 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
194 }
195 // start rendering the page
196 $wgOut->addHtml(
197 Xml::openElement(
198 'form',
199 array(
200 'id' => ( $this->searchAdvanced ? 'powersearch' : 'search' ),
201 'method' => 'get',
202 'action' => $wgScript
203 )
204 )
205 );
206 $wgOut->addHtml(
207 Xml::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
208 Xml::openElement( 'tr' ) .
209 Xml::openElement( 'td' ) . "\n" .
210 $this->shortDialog( $term ) .
211 Xml::closeElement('td') .
212 Xml::closeElement('tr') .
213 Xml::closeElement('table')
214 );
215
216 // Sometimes the search engine knows there are too many hits
217 if( $titleMatches instanceof SearchResultTooMany ) {
218 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
219 wfProfileOut( __METHOD__ );
220 return;
221 }
222
223 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
224 if( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
225 $wgOut->addHTML( $this->searchFocus() );
226 $wgOut->addHTML( $this->formHeader($term, 0, 0));
227 if( $this->searchAdvanced ) {
228 $wgOut->addHTML( $this->powerSearchBox( $term ) );
229 }
230 $wgOut->addHTML( '</form>' );
231 // Empty query -- straight view of search form
232 wfProfileOut( __METHOD__ );
233 return;
234 }
235
236 // Get number of results
237 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
238 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
239 // Total initial query matches (possible false positives)
240 $num = $titleMatchesNum + $textMatchesNum;
241
242 // Get total actual results (after second filtering, if any)
243 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
244 $titleMatches->getTotalHits() : $titleMatchesNum;
245 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
246 $textMatches->getTotalHits() : $textMatchesNum;
247
248 // get total number of results if backend can calculate it
249 $totalRes = 0;
250 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
251 $totalRes += $titleMatches->getTotalHits();
252 if($textMatches && !is_null( $textMatches->getTotalHits() ))
253 $totalRes += $textMatches->getTotalHits();
254
255 // show number of results and current offset
256 $wgOut->addHTML( $this->formHeader($term, $num, $totalRes));
257 if( $this->searchAdvanced ) {
258 $wgOut->addHTML( $this->powerSearchBox( $term ) );
259 }
260
261 $wgOut->addHtml( Xml::closeElement( 'form' ) );
262 $wgOut->addHtml( "<div class='searchresults'>" );
263
264 // prev/next links
265 if( $num || $this->offset ) {
266 // Show the create link ahead
267 $this->showCreateLink( $t );
268 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
269 SpecialPage::getTitleFor( 'Search' ),
270 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
271 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
272 );
273 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
274 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
275 } else {
276 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
277 }
278
279 if( $titleMatches ) {
280 if( $numTitleMatches > 0 ) {
281 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
282 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
283 }
284 $titleMatches->free();
285 }
286 if( $textMatches ) {
287 // output appropriate heading
288 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
289 // if no title matches the heading is redundant
290 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
291 } elseif( $totalRes == 0 ) {
292 # Don't show the 'no text matches' if we received title matches
293 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
294 }
295 // show interwiki results if any
296 if( $textMatches->hasInterwikiResults() ) {
297 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
298 }
299 // show results
300 if( $numTextMatches > 0 ) {
301 $wgOut->addHTML( $this->showMatches( $textMatches ) );
302 }
303
304 $textMatches->free();
305 }
306 if( $num === 0 ) {
307 $wgOut->addWikiMsg( 'search-nonefound', wfEscapeWikiText( $term ) );
308 $this->showCreateLink( $t );
309 }
310 $wgOut->addHtml( "</div>" );
311 if( $num === 0 ) {
312 $wgOut->addHTML( $this->searchFocus() );
313 }
314
315 if( $num || $this->offset ) {
316 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
317 }
318 wfProfileOut( __METHOD__ );
319 }
320
321 protected function showCreateLink( $t ) {
322 global $wgOut;
323
324 // show direct page/create link if applicable
325 $messageName = null;
326 if( !is_null($t) ) {
327 if( $t->isKnown() ) {
328 $messageName = 'searchmenu-exists';
329 } elseif( $t->userCan( 'create' ) ) {
330 $messageName = 'searchmenu-new';
331 } else {
332 $messageName = 'searchmenu-new-nocreate';
333 }
334 }
335 if( $messageName ) {
336 $wgOut->addWikiMsg( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
337 } else {
338 // preserve the paragraph for margins etc...
339 $wgOut->addHtml( '<p></p>' );
340 }
341 }
342
343 /**
344 *
345 */
346 protected function setupPage( $term ) {
347 global $wgOut;
348 // Figure out the active search profile header
349 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
350 if( $this->searchAdvanced )
351 $this->active = 'advanced';
352 else {
353 $profiles = $this->getSearchProfiles();
354
355 foreach( $profiles as $key => $data ) {
356 if ( $this->namespaces == $data['namespaces'] && $key != 'advanced')
357 $this->active = $key;
358 }
359
360 }
361 # Should advanced UI be used?
362 $this->searchAdvanced = ($this->active === 'advanced');
363 if( !empty( $term ) ) {
364 $wgOut->setPageTitle( wfMsg( 'searchresults') );
365 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
366 }
367 $wgOut->setArticleRelated( false );
368 $wgOut->setRobotPolicy( 'noindex,nofollow' );
369 // add javascript specific to special:search
370 $wgOut->addScriptFile( 'search.js' );
371
372 // Bug #16886: Sister projects box moves down the first extract on IE7
373 $wgOut->addStyle( 'common/IE70Fixes.css', 'screen', 'IE 7' );
374 }
375
376 /**
377 * Extract "power search" namespace settings from the request object,
378 * returning a list of index numbers to search.
379 *
380 * @param $request WebRequest
381 * @return Array
382 */
383 protected function powerSearch( &$request ) {
384 $arr = array();
385 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
386 if( $request->getCheck( 'ns' . $ns ) ) {
387 $arr[] = $ns;
388 }
389 }
390 return $arr;
391 }
392
393 /**
394 * Reconstruct the 'power search' options for links
395 *
396 * @return Array
397 */
398 protected function powerSearchOptions() {
399 $opt = array();
400 foreach( $this->namespaces as $n ) {
401 $opt['ns' . $n] = 1;
402 }
403 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
404 if( $this->searchAdvanced ) {
405 $opt['advanced'] = $this->searchAdvanced;
406 }
407 return $opt;
408 }
409
410 /**
411 * Show whole set of results
412 *
413 * @param $matches SearchResultSet
414 */
415 protected function showMatches( &$matches ) {
416 global $wgContLang;
417 wfProfileIn( __METHOD__ );
418
419 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
420
421 $out = "";
422 $infoLine = $matches->getInfo();
423 if( !is_null($infoLine) ) {
424 $out .= "\n<!-- {$infoLine} -->\n";
425 }
426 $off = $this->offset + 1;
427 $out .= "<ul class='mw-search-results'>\n";
428 while( $result = $matches->next() ) {
429 $out .= $this->showHit( $result, $terms );
430 }
431 $out .= "</ul>\n";
432
433 // convert the whole thing to desired language variant
434 $out = $wgContLang->convert( $out );
435 wfProfileOut( __METHOD__ );
436 return $out;
437 }
438
439 /**
440 * Format a single hit result
441 *
442 * @param $result SearchResult
443 * @param $terms Array: terms to highlight
444 */
445 protected function showHit( $result, $terms ) {
446 global $wgContLang, $wgLang, $wgUser;
447 wfProfileIn( __METHOD__ );
448
449 if( $result->isBrokenTitle() ) {
450 wfProfileOut( __METHOD__ );
451 return "<!-- Broken link in search result -->\n";
452 }
453
454 $sk = $wgUser->getSkin();
455 $t = $result->getTitle();
456
457 $titleSnippet = $result->getTitleSnippet($terms);
458
459 if( $titleSnippet == '' )
460 $titleSnippet = null;
461
462 $link_t = clone $t;
463
464 wfRunHooks( 'ShowSearchHitTitle',
465 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
466
467 $link = $this->sk->linkKnown(
468 $link_t,
469 $titleSnippet
470 );
471
472 //If page content is not readable, just return the title.
473 //This is not quite safe, but better than showing excerpts from non-readable pages
474 //Note that hiding the entry entirely would screw up paging.
475 if( !$t->userCanRead() ) {
476 wfProfileOut( __METHOD__ );
477 return "<li>{$link}</li>\n";
478 }
479
480 // If the page doesn't *exist*... our search index is out of date.
481 // The least confusing at this point is to drop the result.
482 // You may get less results, but... oh well. :P
483 if( $result->isMissingRevision() ) {
484 wfProfileOut( __METHOD__ );
485 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
486 }
487
488 // format redirects / relevant sections
489 $redirectTitle = $result->getRedirectTitle();
490 $redirectText = $result->getRedirectSnippet($terms);
491 $sectionTitle = $result->getSectionTitle();
492 $sectionText = $result->getSectionSnippet($terms);
493 $redirect = '';
494
495 if( !is_null($redirectTitle) ) {
496 if( $redirectText == '' )
497 $redirectText = null;
498
499 $redirect = "<span class='searchalttitle'>" .
500 wfMsg(
501 'search-redirect',
502 $this->sk->linkKnown(
503 $redirectTitle,
504 $redirectText
505 )
506 ) .
507 "</span>";
508 }
509
510 $section = '';
511
512
513 if( !is_null($sectionTitle) ) {
514 if( $sectionText == '' )
515 $sectionText = null;
516
517 $section = "<span class='searchalttitle'>" .
518 wfMsg(
519 'search-section', $this->sk->linkKnown(
520 $sectionTitle,
521 $sectionText
522 )
523 ) .
524 "</span>";
525 }
526
527 // format text extract
528 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
529
530 // format score
531 if( is_null( $result->getScore() ) ) {
532 // Search engine doesn't report scoring info
533 $score = '';
534 } else {
535 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
536 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
537 . ' - ';
538 }
539
540 // format description
541 $byteSize = $result->getByteSize();
542 $wordCount = $result->getWordCount();
543 $timestamp = $result->getTimestamp();
544 $size = wfMsgExt(
545 'search-result-size',
546 array( 'parsemag', 'escape' ),
547 $this->sk->formatSize( $byteSize ),
548 $wgLang->formatNum( $wordCount )
549 );
550
551 if( $t->getNamespace() == NS_CATEGORY ) {
552 $cat = Category::newFromTitle( $t );
553 $size = wfMsgExt(
554 'search-result-category-size',
555 array( 'parsemag', 'escape' ),
556 $wgLang->formatNum( $cat->getPageCount() ),
557 $wgLang->formatNum( $cat->getSubcatCount() ),
558 $wgLang->formatNum( $cat->getFileCount() )
559 );
560 }
561
562 $date = $wgLang->timeanddate( $timestamp );
563
564 // link to related articles if supported
565 $related = '';
566 if( $result->hasRelated() ) {
567 $st = SpecialPage::getTitleFor( 'Search' );
568 $stParams = array_merge(
569 $this->powerSearchOptions(),
570 array(
571 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
572 'fulltext' => wfMsg( 'search' )
573 )
574 );
575
576 $related = ' -- ' . $sk->linkKnown(
577 $st,
578 wfMsg('search-relatedarticle'),
579 array(),
580 $stParams
581 );
582 }
583
584 // Include a thumbnail for media files...
585 if( $t->getNamespace() == NS_FILE ) {
586 $img = wfFindFile( $t );
587 if( $img ) {
588 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
589 if( $thumb ) {
590 $desc = $img->getShortDesc();
591 wfProfileOut( __METHOD__ );
592 // Float doesn't seem to interact well with the bullets.
593 // Table messes up vertical alignment of the bullets.
594 // Bullets are therefore disabled (didn't look great anyway).
595 return "<li>" .
596 '<table class="searchResultImage">' .
597 '<tr>' .
598 '<td width="120" align="center" valign="top">' .
599 $thumb->toHtml( array( 'desc-link' => true ) ) .
600 '</td>' .
601 '<td valign="top">' .
602 $link .
603 $extract .
604 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
605 '</td>' .
606 '</tr>' .
607 '</table>' .
608 "</li>\n";
609 }
610 }
611 }
612
613 wfProfileOut( __METHOD__ );
614 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
615 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
616 "</li>\n";
617
618 }
619
620 /**
621 * Show results from other wikis
622 *
623 * @param $matches SearchResultSet
624 * @param $query String
625 */
626 protected function showInterwiki( &$matches, $query ) {
627 global $wgContLang;
628 wfProfileIn( __METHOD__ );
629 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
630
631 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
632 wfMsg('search-interwiki-caption')."</div>\n";
633 $off = $this->offset + 1;
634 $out .= "<ul class='mw-search-iwresults'>\n";
635
636 // work out custom project captions
637 $customCaptions = array();
638 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
639 foreach($customLines as $line) {
640 $parts = explode(":",$line,2);
641 if(count($parts) == 2) // validate line
642 $customCaptions[$parts[0]] = $parts[1];
643 }
644
645 $prev = null;
646 while( $result = $matches->next() ) {
647 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
648 $prev = $result->getInterwikiPrefix();
649 }
650 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
651 $out .= "</ul></div>\n";
652
653 // convert the whole thing to desired language variant
654 $out = $wgContLang->convert( $out );
655 wfProfileOut( __METHOD__ );
656 return $out;
657 }
658
659 /**
660 * Show single interwiki link
661 *
662 * @param $result SearchResult
663 * @param $lastInterwiki String
664 * @param $terms Array
665 * @param $query String
666 * @param $customCaptions Array: iw prefix -> caption
667 */
668 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
669 wfProfileIn( __METHOD__ );
670 global $wgContLang, $wgLang;
671
672 if( $result->isBrokenTitle() ) {
673 wfProfileOut( __METHOD__ );
674 return "<!-- Broken link in search result -->\n";
675 }
676
677 $t = $result->getTitle();
678
679 $titleSnippet = $result->getTitleSnippet($terms);
680
681 if( $titleSnippet == '' )
682 $titleSnippet = null;
683
684 $link = $this->sk->linkKnown(
685 $t,
686 $titleSnippet
687 );
688
689 // format redirect if any
690 $redirectTitle = $result->getRedirectTitle();
691 $redirectText = $result->getRedirectSnippet($terms);
692 $redirect = '';
693 if( !is_null($redirectTitle) ) {
694 if( $redirectText == '' )
695 $redirectText = null;
696
697 $redirect = "<span class='searchalttitle'>" .
698 wfMsg(
699 'search-redirect',
700 $this->sk->linkKnown(
701 $redirectTitle,
702 $redirectText
703 )
704 ) .
705 "</span>";
706 }
707
708 $out = "";
709 // display project name
710 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
711 if( key_exists($t->getInterwiki(),$customCaptions) )
712 // captions from 'search-interwiki-custom'
713 $caption = $customCaptions[$t->getInterwiki()];
714 else{
715 // default is to show the hostname of the other wiki which might suck
716 // if there are many wikis on one hostname
717 $parsed = parse_url($t->getFullURL());
718 $caption = wfMsg('search-interwiki-default', $parsed['host']);
719 }
720 // "more results" link (special page stuff could be localized, but we might not know target lang)
721 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
722 $searchLink = $this->sk->linkKnown(
723 $searchTitle,
724 wfMsg('search-interwiki-more'),
725 array(),
726 array(
727 'search' => $query,
728 'fulltext' => 'Search'
729 )
730 );
731 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
732 {$searchLink}</span>{$caption}</div>\n<ul>";
733 }
734
735 $out .= "<li>{$link} {$redirect}</li>\n";
736 wfProfileOut( __METHOD__ );
737 return $out;
738 }
739
740
741 /**
742 * Generates the power search box at bottom of [[Special:Search]]
743 *
744 * @param $term String: search term
745 * @return String: HTML form
746 */
747 protected function powerSearchBox( $term ) {
748 global $wgScript, $wgContLang;
749
750 // Groups namespaces into rows according to subject
751 $rows = array();
752 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
753 $subject = MWNamespace::getSubject( $namespace );
754 if( !array_key_exists( $subject, $rows ) ) {
755 $rows[$subject] = "";
756 }
757 $name = str_replace( '_', ' ', $name );
758 if( $name == '' ) {
759 $name = wfMsg( 'blanknamespace' );
760 }
761 $rows[$subject] .=
762 Xml::openElement(
763 'td', array( 'style' => 'white-space: nowrap' )
764 ) .
765 Xml::checkLabel(
766 $name,
767 "ns{$namespace}",
768 "mw-search-ns{$namespace}",
769 in_array( $namespace, $this->namespaces )
770 ) .
771 Xml::closeElement( 'td' );
772 }
773 $rows = array_values( $rows );
774 $numRows = count( $rows );
775
776 // Lays out namespaces in multiple floating two-column tables so they'll
777 // be arranged nicely while still accommodating different screen widths
778 $namespaceTables = '';
779 for( $i = 0; $i < $numRows; $i += 4 ) {
780 $namespaceTables .= Xml::openElement(
781 'table',
782 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
783 );
784 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
785 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
786 }
787 $namespaceTables .= Xml::closeElement( 'table' );
788 }
789 // Show redirects check only if backend supports it
790 $redirects = '';
791 if( $this->searchEngine->acceptListRedirects() ) {
792 $redirects =
793 Xml::check(
794 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' )
795 ) .
796 ' ' .
797 Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
798 }
799 // Return final output
800 return
801 Xml::openElement(
802 'fieldset',
803 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
804 ) .
805 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
806 Xml::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
807 Xml::tags(
808 'div',
809 array( 'id' => 'mw-search-togglebox' ),
810 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
811 Xml::element(
812 'input',
813 array(
814 'type'=>'button',
815 'id' => 'mw-search-toggleall',
816 'onclick' => 'mwToggleSearchCheckboxes("all");',
817 'value' => wfMsg( 'powersearch-toggleall' )
818 )
819 ) .
820 Xml::element(
821 'input',
822 array(
823 'type'=>'button',
824 'id' => 'mw-search-togglenone',
825 'onclick' => 'mwToggleSearchCheckboxes("none");',
826 'value' => wfMsg( 'powersearch-togglenone' )
827 )
828 )
829 ) .
830 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
831 $namespaceTables .
832 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
833 $redirects .
834 Xml::hidden( 'title', SpecialPage::getTitleFor( 'Search' )->getPrefixedText() ) .
835 Xml::hidden( 'advanced', $this->searchAdvanced ) .
836 Xml::hidden( 'fulltext', 'Advanced search' ) .
837 Xml::closeElement( 'fieldset' );
838 }
839
840 protected function searchFocus() {
841 $id = $this->searchAdvanced ? 'powerSearchText' : 'searchText';
842 return Html::inlineScript(
843 "hookEvent(\"load\", function() {" .
844 "document.getElementById('$id').focus();" .
845 "});" );
846 }
847
848 protected function getSearchProfiles() {
849 // Builds list of Search Types (profiles)
850 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
851
852 $profiles = array(
853 'default' => array(
854 'message' => 'searchprofile-articles',
855 'tooltip' => 'searchprofile-articles-tooltip',
856 'namespaces' => SearchEngine::defaultNamespaces(),
857 'namespace-messages' => SearchEngine::namespacesAsText(
858 SearchEngine::defaultNamespaces()
859 ),
860 ),
861 'images' => array(
862 'message' => 'searchprofile-images',
863 'tooltip' => 'searchprofile-images-tooltip',
864 'namespaces' => array( NS_FILE ),
865 ),
866 'help' => array(
867 'message' => 'searchprofile-project',
868 'tooltip' => 'searchprofile-project-tooltip',
869 'namespaces' => SearchEngine::helpNamespaces(),
870 'namespace-messages' => SearchEngine::namespacesAsText(
871 SearchEngine::helpNamespaces()
872 ),
873 ),
874 'all' => array(
875 'message' => 'searchprofile-everything',
876 'tooltip' => 'searchprofile-everything-tooltip',
877 'namespaces' => $nsAllSet,
878 ),
879 'advanced' => array(
880 'message' => 'searchprofile-advanced',
881 'tooltip' => 'searchprofile-advanced-tooltip',
882 'namespaces' => $this->namespaces,
883 'parameters' => array( 'advanced' => 1 ),
884 )
885 );
886
887 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
888
889 foreach( $profiles as $key => &$data ) {
890 sort($data['namespaces']);
891 }
892
893 return $profiles;
894 }
895
896 protected function formHeader( $term, $resultsShown, $totalNum ) {
897 global $wgContLang, $wgLang;
898
899 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
900
901 $bareterm = $term;
902 if( $this->startsWithImage( $term ) ) {
903 // Deletes prefixes
904 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
905 }
906
907 $profiles = $this->getSearchProfiles();
908
909 // Outputs XML for Search Types
910 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
911 $out .= Xml::openElement( 'ul' );
912 foreach ( $profiles as $id => $profile ) {
913 $tooltipParam = isset( $profile['namespace-messages'] ) ?
914 $wgLang->commaList( $profile['namespace-messages'] ) : null;
915 $out .= Xml::tags(
916 'li',
917 array(
918 'class' => $this->active == $id ? 'current' : 'normal'
919 ),
920 $this->makeSearchLink(
921 $bareterm,
922 $profile['namespaces'],
923 wfMsg( $profile['message'] ),
924 wfMsg( $profile['tooltip'], $tooltipParam ),
925 isset( $profile['parameters'] ) ? $profile['parameters'] : array()
926 )
927 );
928 }
929 $out .= Xml::closeElement( 'ul' );
930 $out .= Xml::closeElement('div') ;
931
932 // Results-info
933 if ( $resultsShown > 0 ) {
934 if ( $totalNum > 0 ){
935 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
936 $wgLang->formatNum( $this->offset + 1 ),
937 $wgLang->formatNum( $this->offset + $resultsShown ),
938 $wgLang->formatNum( $totalNum ),
939 wfEscapeWikiText( $term ),
940 $wgLang->formatNum( $resultsShown )
941 );
942 } elseif ( $resultsShown >= $this->limit ) {
943 $top = wfShowingResults( $this->offset, $this->limit );
944 } else {
945 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
946 }
947 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
948 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
949 );
950 }
951
952 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
953 $out .= Xml::closeElement('div');
954
955 // Adds hidden namespace fields
956 if ( !$this->searchAdvanced ) {
957 foreach( $this->namespaces as $ns ) {
958 $out .= Xml::hidden( "ns{$ns}", '1' );
959 }
960 }
961
962 return $out;
963 }
964
965 protected function shortDialog( $term ) {
966 $searchTitle = SpecialPage::getTitleFor( 'Search' );
967 $searchable = SearchEngine::searchableNamespaces();
968 $out = Html::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
969 // Keep redirect setting
970 $out .= Html::hidden( "redirs", (int)$this->searchRedirects ) . "\n";
971 // Term box
972 $out .= Html::input( 'search', $term, 'search', array(
973 'id' => $this->searchAdvanced ? 'powerSearchText' : 'searchText',
974 'size' => '50',
975 'autofocus'
976 ) ) . "\n";
977 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
978 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
979 return $out . $this->didYouMeanHtml;
980 }
981
982 /**
983 * Make a search link with some target namespaces
984 *
985 * @param $term String
986 * @param $namespaces Array
987 * @param $label String: link's text
988 * @param $tooltip String: link's tooltip
989 * @param $params Array: query string parameters
990 * @return String: HTML fragment
991 */
992 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
993 $opt = $params;
994 foreach( $namespaces as $n ) {
995 $opt['ns' . $n] = 1;
996 }
997 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
998
999 $st = SpecialPage::getTitleFor( 'Search' );
1000 $stParams = array_merge(
1001 array(
1002 'search' => $term,
1003 'fulltext' => wfMsg( 'search' )
1004 ),
1005 $opt
1006 );
1007
1008 return Xml::element(
1009 'a',
1010 array(
1011 'href' => $st->getLocalURL( $stParams ),
1012 'title' => $tooltip,
1013 'onmousedown' => 'mwSearchHeaderClick(this);',
1014 'onkeydown' => 'mwSearchHeaderClick(this);'),
1015 $label
1016 );
1017 }
1018
1019 /**
1020 * Check if query starts with image: prefix
1021 *
1022 * @param $term String: the string to check
1023 * @return Boolean
1024 */
1025 protected function startsWithImage( $term ) {
1026 global $wgContLang;
1027
1028 $p = explode( ':', $term );
1029 if( count( $p ) > 1 ) {
1030 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1031 }
1032 return false;
1033 }
1034
1035 /**
1036 * Check if query starts with all: prefix
1037 *
1038 * @param $term String: the string to check
1039 * @return Boolean
1040 */
1041 protected function startsWithAll( $term ) {
1042
1043 $allkeyword = wfMsgForContent('searchall');
1044
1045 $p = explode( ':', $term );
1046 if( count( $p ) > 1 ) {
1047 return $p[0] == $allkeyword;
1048 }
1049 return false;
1050 }
1051 }
1052