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