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