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