Allow wikitext for 'powersearchtext'
[lhc/web/wiklou.git] / includes / 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 * @addtogroup SpecialPage
23 */
24
25 /**
26 * Entry point
27 *
28 * @param $par String: (default '')
29 */
30 function wfSpecialSearch( $par = '' ) {
31 global $wgRequest, $wgUser;
32
33 $search = $wgRequest->getText( 'search', $par );
34 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
35 if( $wgRequest->getVal( 'fulltext' ) ||
36 !is_null( $wgRequest->getVal( 'offset' ) ) ||
37 !is_null ($wgRequest->getVal( 'searchx' ) ) ) {
38 $searchPage->showResults( $search );
39 } else {
40 $searchPage->goResult( $search );
41 }
42 }
43
44 /**
45 * implements Special:Search - Run text & title search and display the output
46 * @addtogroup SpecialPage
47 */
48 class SpecialSearch {
49
50 /**
51 * Set up basic search parameters from the request and user settings.
52 * Typically you'll pass $wgRequest and $wgUser.
53 *
54 * @param WebRequest $request
55 * @param User $user
56 * @public
57 */
58 function SpecialSearch( &$request, &$user ) {
59 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
60
61 if( $request->getCheck( 'searchx' ) ) {
62 $this->namespaces = $this->powerSearch( $request );
63 } else {
64 $this->namespaces = $this->userNamespaces( $user );
65 }
66
67 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
68 }
69
70 /**
71 * If an exact title match can be found, jump straight ahead to it.
72 * @param string $term
73 * @public
74 */
75 function goResult( $term ) {
76 global $wgOut;
77 global $wgGoToEdit;
78
79 $this->setupPage( $term );
80
81 # Try to go to page as entered.
82 $t = Title::newFromText( $term );
83
84 # If the string cannot be used to create a title
85 if( is_null( $t ) ){
86 return $this->showResults( $term );
87 }
88
89 # If there's an exact or very near match, jump right there.
90 $t = SearchEngine::getNearMatch( $term );
91 if( !is_null( $t ) ) {
92 $wgOut->redirect( $t->getFullURL() );
93 return;
94 }
95
96 # No match, generate an edit URL
97 $t = Title::newFromText( $term );
98 if( ! is_null( $t ) ) {
99 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
100 # If the feature is enabled, go straight to the edit page
101 if ( $wgGoToEdit ) {
102 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
103 return;
104 }
105 }
106 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
107 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
108 } else {
109 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
110 }
111
112 return $this->showResults( $term );
113 }
114
115 /**
116 * @param string $term
117 * @public
118 */
119 function showResults( $term ) {
120 $fname = 'SpecialSearch::showResults';
121 wfProfileIn( $fname );
122
123 $this->setupPage( $term );
124
125 global $wgOut;
126 $wgOut->addWikiMsg( 'searchresulttext' );
127
128 if( '' === trim( $term ) ) {
129 // Empty query -- straight view of search form
130 $wgOut->setSubtitle( '' );
131 $wgOut->addHTML( $this->powerSearchBox( $term ) );
132 $wgOut->addHTML( $this->powerSearchFocus() );
133 wfProfileOut( $fname );
134 return;
135 }
136
137 global $wgDisableTextSearch;
138 if ( $wgDisableTextSearch ) {
139 global $wgForwardSearchUrl;
140 if( $wgForwardSearchUrl ) {
141 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
142 $wgOut->redirect( $url );
143 return;
144 }
145 global $wgInputEncoding;
146 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
147 $wgOut->addHTML(
148 wfMsg( 'googlesearch',
149 htmlspecialchars( $term ),
150 htmlspecialchars( $wgInputEncoding ),
151 htmlspecialchars( wfMsg( 'searchbutton' ) )
152 )
153 );
154 wfProfileOut( $fname );
155 return;
156 }
157
158 $search = SearchEngine::create();
159 $search->setLimitOffset( $this->limit, $this->offset );
160 $search->setNamespaces( $this->namespaces );
161 $search->showRedirects = $this->searchRedirects;
162 $titleMatches = $search->searchTitle( $term );
163
164 // Sometimes the search engine knows there are too many hits
165 if ($titleMatches instanceof SearchResultTooMany) {
166 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
167 $wgOut->addHTML( $this->powerSearchBox( $term ) );
168 $wgOut->addHTML( $this->powerSearchFocus() );
169 wfProfileOut( $fname );
170 return;
171 }
172 $textMatches = $search->searchText( $term );
173
174 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
175 + ( $textMatches ? $textMatches->numRows() : 0);
176 if ( $num > 0 ) {
177 if ( $num >= $this->limit ) {
178 $top = wfShowingResults( $this->offset, $this->limit );
179 } else {
180 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
181 }
182 $wgOut->addHTML( "<p>{$top}</p>\n" );
183 }
184
185 if( $num || $this->offset ) {
186 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
187 SpecialPage::getTitleFor( 'Search' ),
188 wfArrayToCGI(
189 $this->powerSearchOptions(),
190 array( 'search' => $term ) ),
191 ($num < $this->limit) );
192 $wgOut->addHTML( "<br />{$prevnext}\n" );
193 }
194
195 if( $titleMatches ) {
196 if( $titleMatches->numRows() ) {
197 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
198 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
199 } else {
200 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
201 }
202 $titleMatches->free();
203 }
204
205 if( $textMatches ) {
206 if( $textMatches->numRows() ) {
207 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
208 $wgOut->addHTML( $this->showMatches( $textMatches ) );
209 } elseif( $num == 0 ) {
210 # Don't show the 'no text matches' if we received title matches
211 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
212 }
213 $textMatches->free();
214 }
215
216 if ( $num == 0 ) {
217 $wgOut->addWikiMsg( 'nonefound' );
218 }
219 if( $num || $this->offset ) {
220 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
221 }
222 $wgOut->addHTML( $this->powerSearchBox( $term ) );
223 wfProfileOut( $fname );
224 }
225
226 #------------------------------------------------------------------
227 # Private methods below this line
228
229 /**
230 *
231 */
232 function setupPage( $term ) {
233 global $wgOut;
234 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
235 $subtitlemsg = ( Title::newFromText($term) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
236 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
237 $wgOut->setArticleRelated( false );
238 $wgOut->setRobotpolicy( 'noindex,nofollow' );
239 }
240
241 /**
242 * Extract default namespaces to search from the given user's
243 * settings, returning a list of index numbers.
244 *
245 * @param User $user
246 * @return array
247 * @private
248 */
249 function userNamespaces( &$user ) {
250 $arr = array();
251 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
252 if( $user->getOption( 'searchNs' . $ns ) ) {
253 $arr[] = $ns;
254 }
255 }
256 return $arr;
257 }
258
259 /**
260 * Extract "power search" namespace settings from the request object,
261 * returning a list of index numbers to search.
262 *
263 * @param WebRequest $request
264 * @return array
265 * @private
266 */
267 function powerSearch( &$request ) {
268 $arr = array();
269 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
270 if( $request->getCheck( 'ns' . $ns ) ) {
271 $arr[] = $ns;
272 }
273 }
274 return $arr;
275 }
276
277 /**
278 * Reconstruct the 'power search' options for links
279 * @return array
280 * @private
281 */
282 function powerSearchOptions() {
283 $opt = array();
284 foreach( $this->namespaces as $n ) {
285 $opt['ns' . $n] = 1;
286 }
287 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
288 $opt['searchx'] = 1;
289 return $opt;
290 }
291
292 /**
293 * @param SearchResultSet $matches
294 * @param string $terms partial regexp for highlighting terms
295 */
296 function showMatches( &$matches ) {
297 $fname = 'SpecialSearch::showMatches';
298 wfProfileIn( $fname );
299
300 global $wgContLang;
301 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
302 $terms = implode( '|', $tm );
303
304 $off = $this->offset + 1;
305 $out = "<ol start='{$off}' id='searchResults'>\n";
306
307 while( $result = $matches->next() ) {
308 $out .= $this->showHit( $result, $terms );
309 }
310 $out .= "</ol>\n";
311
312 // convert the whole thing to desired language variant
313 global $wgContLang;
314 $out = $wgContLang->convert( $out );
315 wfProfileOut( $fname );
316 return $out;
317 }
318
319 /**
320 * Format a single hit result
321 * @param SearchResult $result
322 * @param string $terms partial regexp for highlighting terms
323 */
324 function showHit( $result, $terms ) {
325 $fname = 'SpecialSearch::showHit';
326 wfProfileIn( $fname );
327 global $wgUser, $wgContLang, $wgLang;
328
329 $t = $result->getTitle();
330 if( is_null( $t ) ) {
331 wfProfileOut( $fname );
332 return "<!-- Broken link in search result -->\n";
333 }
334 $sk = $wgUser->getSkin();
335
336 $contextlines = $wgUser->getOption( 'contextlines', 5 );
337 $contextchars = $wgUser->getOption( 'contextchars', 50 );
338
339 $link = $sk->makeKnownLinkObj( $t );
340
341 //If page content is not readable, just return the title.
342 //This is not quite safe, but better than showing excerpts from non-readable pages
343 //Note that hiding the entry entirely would screw up paging.
344 if (!$t->userCanRead()) {
345 return "<li>{$link}</li>\n";
346 }
347
348 $extract = $size = '';
349 // Include a thumbnail for media files...
350 if( $t->getNamespace() == NS_IMAGE ) {
351 $img = wfFindFile( $t );
352 if( $img ) {
353 $thumb = $img->getThumbnail( 120, 120 );
354 if( $thumb ) {
355 $extract = '<table class="searchResultImage">' .
356 '<tr>' .
357 '<td width="120" align="center">' .
358 $sk->makeKnownLinkObj( $t, $thumb->toHtml() ) .
359 '</td>' .
360 '<td>' .
361 $link .
362 '<br />' .
363 $img->getLongDesc() .
364 '</td>' .
365 '</tr>' .
366 '</table>';
367 wfProfileOut( $fname );
368 return "<li><div>{$extract}</div></li>\n";
369 }
370 }
371 }
372
373 $extract = $this->extractText( $t, $terms, $contextlines, $contextchars );
374 wfProfileOut( $fname );
375 return "<li>{$link} {$extract}</li>\n";
376
377 }
378
379 private function extractText( $t, $terms, $contextlines, $contextchars ) {
380 global $wgLang, $wgContLang;
381 $fname = __METHOD__;
382
383 $revision = Revision::newFromTitle( $t );
384 if( !$revision ) {
385 return '<!-- missing page -->';
386 }
387
388 $text = $revision->getText();
389 $size = wfMsgExt( 'nbytes', array( 'parsemag', 'escape'),
390 $wgLang->formatNum( strlen( $text ) ) );
391
392 $lines = explode( "\n", $text );
393
394 $max = intval( $contextchars ) + 1;
395 $pat1 = "/(.*)($terms)(.{0,$max})/i";
396
397 $lineno = 0;
398
399 $extract = "($size)";
400 wfProfileIn( "$fname-extract" );
401 foreach ( $lines as $line ) {
402 if ( 0 == $contextlines ) {
403 break;
404 }
405 ++$lineno;
406 $m = array();
407 if ( ! preg_match( $pat1, $line, $m ) ) {
408 continue;
409 }
410 --$contextlines;
411 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
412
413 if ( count( $m ) < 3 ) {
414 $post = '';
415 } else {
416 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
417 }
418
419 $found = $m[2];
420
421 $line = htmlspecialchars( $pre . $found . $post );
422 $pat2 = '/(' . $terms . ")/i";
423 $line = preg_replace( $pat2,
424 "<span class='searchmatch'>\\1</span>", $line );
425
426 $extract .= "<br /><small>{$lineno}: {$line}</small>\n";
427 }
428 wfProfileOut( "$fname-extract" );
429
430 return $extract;
431 }
432
433 function powerSearchBox( $term ) {
434 $namespaces = '';
435 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
436 $checked = in_array( $ns, $this->namespaces )
437 ? ' checked="checked"'
438 : '';
439 $name = str_replace( '_', ' ', $name );
440 if( '' == $name ) {
441 $name = wfMsg( 'blanknamespace' );
442 }
443 $namespaces .= Xml::checkLabel( $name, "ns{$ns}", $name, $checked ) . "\n";
444 }
445
446 $checked = $this->searchRedirects
447 ? ' checked="checked"'
448 : '';
449 $redirect = Xml::check( 'redirs', $checked ) . "\n";
450 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
451 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'searchx' ) );
452
453 $ret = wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
454 $namespaces, $redirect, $searchField,
455 '', '', '', '', '', # Dummy placeholders
456 $searchButton );
457
458 $title = SpecialPage::getTitleFor( 'Search' );
459 $action = $title->escapeLocalURL();
460 return "<br /><br />\n<form id=\"powersearch\" method=\"get\" " .
461 "action=\"$action\">\n{$ret}\n</form>\n";
462 }
463
464 function powerSearchFocus() {
465 return "<script type='text/javascript'>" .
466 "document.getElementById('powerSearchText').focus();" .
467 "</script>";
468 }
469 }
470
471