Removed remaining profile calls
[lhc/web/wiklou.git] / includes / search / SearchHighlighter.php
1 <?php
2 /**
3 * Basic search engine highlighting
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 * @file
21 * @ingroup Search
22 */
23
24 /**
25 * Highlight bits of wikitext
26 *
27 * @ingroup Search
28 */
29 class SearchHighlighter {
30 protected $mCleanWikitext = true;
31
32 function __construct( $cleanupWikitext = true ) {
33 $this->mCleanWikitext = $cleanupWikitext;
34 }
35
36 /**
37 * Default implementation of wikitext highlighting
38 *
39 * @param string $text
40 * @param array $terms Terms to highlight (unescaped)
41 * @param int $contextlines
42 * @param int $contextchars
43 * @return string
44 */
45 public function highlightText( $text, $terms, $contextlines, $contextchars ) {
46 global $wgContLang, $wgSearchHighlightBoundaries;
47
48 $fname = __METHOD__;
49
50 if ( $text == '' ) {
51 return '';
52 }
53
54 // spli text into text + templates/links/tables
55 $spat = "/(\\{\\{)|(\\[\\[[^\\]:]+:)|(\n\\{\\|)";
56 // first capture group is for detecting nested templates/links/tables/references
57 $endPatterns = array(
58 1 => '/(\{\{)|(\}\})/', // template
59 2 => '/(\[\[)|(\]\])/', // image
60 3 => "/(\n\\{\\|)|(\n\\|\\})/" ); // table
61
62 // @todo FIXME: This should prolly be a hook or something
63 if ( function_exists( 'wfCite' ) ) {
64 $spat .= '|(<ref>)'; // references via cite extension
65 $endPatterns[4] = '/(<ref>)|(<\/ref>)/';
66 }
67 $spat .= '/';
68 $textExt = array(); // text extracts
69 $otherExt = array(); // other extracts
70 $start = 0;
71 $textLen = strlen( $text );
72 $count = 0; // sequence number to maintain ordering
73 while ( $start < $textLen ) {
74 // find start of template/image/table
75 if ( preg_match( $spat, $text, $matches, PREG_OFFSET_CAPTURE, $start ) ) {
76 $epat = '';
77 foreach ( $matches as $key => $val ) {
78 if ( $key > 0 && $val[1] != - 1 ) {
79 if ( $key == 2 ) {
80 // see if this is an image link
81 $ns = substr( $val[0], 2, - 1 );
82 if ( $wgContLang->getNsIndex( $ns ) != NS_FILE ) {
83 break;
84 }
85
86 }
87 $epat = $endPatterns[$key];
88 $this->splitAndAdd( $textExt, $count, substr( $text, $start, $val[1] - $start ) );
89 $start = $val[1];
90 break;
91 }
92 }
93 if ( $epat ) {
94 // find end (and detect any nested elements)
95 $level = 0;
96 $offset = $start + 1;
97 $found = false;
98 while ( preg_match( $epat, $text, $endMatches, PREG_OFFSET_CAPTURE, $offset ) ) {
99 if ( array_key_exists( 2, $endMatches ) ) {
100 // found end
101 if ( $level == 0 ) {
102 $len = strlen( $endMatches[2][0] );
103 $off = $endMatches[2][1];
104 $this->splitAndAdd( $otherExt, $count,
105 substr( $text, $start, $off + $len - $start ) );
106 $start = $off + $len;
107 $found = true;
108 break;
109 } else {
110 // end of nested element
111 $level -= 1;
112 }
113 } else {
114 // nested
115 $level += 1;
116 }
117 $offset = $endMatches[0][1] + strlen( $endMatches[0][0] );
118 }
119 if ( !$found ) {
120 // couldn't find appropriate closing tag, skip
121 $this->splitAndAdd( $textExt, $count, substr( $text, $start, strlen( $matches[0][0] ) ) );
122 $start += strlen( $matches[0][0] );
123 }
124 continue;
125 }
126 }
127 // else: add as text extract
128 $this->splitAndAdd( $textExt, $count, substr( $text, $start ) );
129 break;
130 }
131
132 $all = $textExt + $otherExt; // these have disjunct key sets
133
134
135 // prepare regexps
136 foreach ( $terms as $index => $term ) {
137 // manually do upper/lowercase stuff for utf-8 since PHP won't do it
138 if ( preg_match( '/[\x80-\xff]/', $term ) ) {
139 $terms[$index] = preg_replace_callback(
140 '/./us',
141 array( $this, 'caseCallback' ),
142 $terms[$index]
143 );
144 } else {
145 $terms[$index] = $term;
146 }
147 }
148 $anyterm = implode( '|', $terms );
149 $phrase = implode( "$wgSearchHighlightBoundaries+", $terms );
150
151 // @todo FIXME: A hack to scale contextchars, a correct solution
152 // would be to have contextchars actually be char and not byte
153 // length, and do proper utf-8 substrings and lengths everywhere,
154 // but PHP is making that very hard and unclean to implement :(
155 $scale = strlen( $anyterm ) / mb_strlen( $anyterm );
156 $contextchars = intval( $contextchars * $scale );
157
158 $patPre = "(^|$wgSearchHighlightBoundaries)";
159 $patPost = "($wgSearchHighlightBoundaries|$)";
160
161 $pat1 = "/(" . $phrase . ")/ui";
162 $pat2 = "/$patPre(" . $anyterm . ")$patPost/ui";
163
164
165 $left = $contextlines;
166
167 $snippets = array();
168 $offsets = array();
169
170 // show beginning only if it contains all words
171 $first = 0;
172 $firstText = '';
173 foreach ( $textExt as $index => $line ) {
174 if ( strlen( $line ) > 0 && $line[0] != ';' && $line[0] != ':' ) {
175 $firstText = $this->extract( $line, 0, $contextchars * $contextlines );
176 $first = $index;
177 break;
178 }
179 }
180 if ( $firstText ) {
181 $succ = true;
182 // check if first text contains all terms
183 foreach ( $terms as $term ) {
184 if ( !preg_match( "/$patPre" . $term . "$patPost/ui", $firstText ) ) {
185 $succ = false;
186 break;
187 }
188 }
189 if ( $succ ) {
190 $snippets[$first] = $firstText;
191 $offsets[$first] = 0;
192 }
193 }
194 if ( !$snippets ) {
195 // match whole query on text
196 $this->process( $pat1, $textExt, $left, $contextchars, $snippets, $offsets );
197 // match whole query on templates/tables/images
198 $this->process( $pat1, $otherExt, $left, $contextchars, $snippets, $offsets );
199 // match any words on text
200 $this->process( $pat2, $textExt, $left, $contextchars, $snippets, $offsets );
201 // match any words on templates/tables/images
202 $this->process( $pat2, $otherExt, $left, $contextchars, $snippets, $offsets );
203
204 ksort( $snippets );
205 }
206
207 // add extra chars to each snippet to make snippets constant size
208 $extended = array();
209 if ( count( $snippets ) == 0 ) {
210 // couldn't find the target words, just show beginning of article
211 if ( array_key_exists( $first, $all ) ) {
212 $targetchars = $contextchars * $contextlines;
213 $snippets[$first] = '';
214 $offsets[$first] = 0;
215 }
216 } else {
217 // if begin of the article contains the whole phrase, show only that !!
218 if ( array_key_exists( $first, $snippets ) && preg_match( $pat1, $snippets[$first] )
219 && $offsets[$first] < $contextchars * 2 ) {
220 $snippets = array( $first => $snippets[$first] );
221 }
222
223 // calc by how much to extend existing snippets
224 $targetchars = intval( ( $contextchars * $contextlines ) / count ( $snippets ) );
225 }
226
227 foreach ( $snippets as $index => $line ) {
228 $extended[$index] = $line;
229 $len = strlen( $line );
230 if ( $len < $targetchars - 20 ) {
231 // complete this line
232 if ( $len < strlen( $all[$index] ) ) {
233 $extended[$index] = $this->extract(
234 $all[$index],
235 $offsets[$index],
236 $offsets[$index] + $targetchars,
237 $offsets[$index]
238 );
239 $len = strlen( $extended[$index] );
240 }
241
242 // add more lines
243 $add = $index + 1;
244 while ( $len < $targetchars - 20
245 && array_key_exists( $add, $all )
246 && !array_key_exists( $add, $snippets ) ) {
247 $offsets[$add] = 0;
248 $tt = "\n" . $this->extract( $all[$add], 0, $targetchars - $len, $offsets[$add] );
249 $extended[$add] = $tt;
250 $len += strlen( $tt );
251 $add++;
252 }
253 }
254 }
255
256 // $snippets = array_map( 'htmlspecialchars', $extended );
257 $snippets = $extended;
258 $last = - 1;
259 $extract = '';
260 foreach ( $snippets as $index => $line ) {
261 if ( $last == - 1 ) {
262 $extract .= $line; // first line
263 } elseif ( $last + 1 == $index
264 && $offsets[$last] + strlen( $snippets[$last] ) >= strlen( $all[$last] )
265 ) {
266 $extract .= " " . $line; // continous lines
267 } else {
268 $extract .= '<b> ... </b>' . $line;
269 }
270
271 $last = $index;
272 }
273 if ( $extract ) {
274 $extract .= '<b> ... </b>';
275 }
276
277 $processed = array();
278 foreach ( $terms as $term ) {
279 if ( !isset( $processed[$term] ) ) {
280 $pat3 = "/$patPre(" . $term . ")$patPost/ui"; // highlight word
281 $extract = preg_replace( $pat3,
282 "\\1<span class='searchmatch'>\\2</span>\\3", $extract );
283 $processed[$term] = true;
284 }
285 }
286
287
288 return $extract;
289 }
290
291 /**
292 * Split text into lines and add it to extracts array
293 *
294 * @param array $extracts Index -> $line
295 * @param int $count
296 * @param string $text
297 */
298 function splitAndAdd( &$extracts, &$count, $text ) {
299 $split = explode( "\n", $this->mCleanWikitext ? $this->removeWiki( $text ) : $text );
300 foreach ( $split as $line ) {
301 $tt = trim( $line );
302 if ( $tt ) {
303 $extracts[$count++] = $tt;
304 }
305 }
306 }
307
308 /**
309 * Do manual case conversion for non-ascii chars
310 *
311 * @param array $matches
312 * @return string
313 */
314 function caseCallback( $matches ) {
315 global $wgContLang;
316 if ( strlen( $matches[0] ) > 1 ) {
317 return '[' . $wgContLang->lc( $matches[0] ) . $wgContLang->uc( $matches[0] ) . ']';
318 } else {
319 return $matches[0];
320 }
321 }
322
323 /**
324 * Extract part of the text from start to end, but by
325 * not chopping up words
326 * @param string $text
327 * @param int $start
328 * @param int $end
329 * @param int $posStart (out) actual start position
330 * @param int $posEnd (out) actual end position
331 * @return string
332 */
333 function extract( $text, $start, $end, &$posStart = null, &$posEnd = null ) {
334 if ( $start != 0 ) {
335 $start = $this->position( $text, $start, 1 );
336 }
337 if ( $end >= strlen( $text ) ) {
338 $end = strlen( $text );
339 } else {
340 $end = $this->position( $text, $end );
341 }
342
343 if ( !is_null( $posStart ) ) {
344 $posStart = $start;
345 }
346 if ( !is_null( $posEnd ) ) {
347 $posEnd = $end;
348 }
349
350 if ( $end > $start ) {
351 return substr( $text, $start, $end - $start );
352 } else {
353 return '';
354 }
355 }
356
357 /**
358 * Find a nonletter near a point (index) in the text
359 *
360 * @param string $text
361 * @param int $point
362 * @param int $offset Offset to found index
363 * @return int Nearest nonletter index, or beginning of utf8 char if none
364 */
365 function position( $text, $point, $offset = 0 ) {
366 $tolerance = 10;
367 $s = max( 0, $point - $tolerance );
368 $l = min( strlen( $text ), $point + $tolerance ) - $s;
369 $m = array();
370
371 if ( preg_match(
372 '/[ ,.!?~!@#$%^&*\(\)+=\-\\\|\[\]"\'<>]/',
373 substr( $text, $s, $l ),
374 $m,
375 PREG_OFFSET_CAPTURE
376 ) ) {
377 return $m[0][1] + $s + $offset;
378 } else {
379 // check if point is on a valid first UTF8 char
380 $char = ord( $text[$point] );
381 while ( $char >= 0x80 && $char < 0xc0 ) {
382 // skip trailing bytes
383 $point++;
384 if ( $point >= strlen( $text ) ) {
385 return strlen( $text );
386 }
387 $char = ord( $text[$point] );
388 }
389
390 return $point;
391
392 }
393 }
394
395 /**
396 * Search extracts for a pattern, and return snippets
397 *
398 * @param string $pattern Regexp for matching lines
399 * @param array $extracts Extracts to search
400 * @param int $linesleft Number of extracts to make
401 * @param int $contextchars Length of snippet
402 * @param array $out Map for highlighted snippets
403 * @param array $offsets Map of starting points of snippets
404 * @protected
405 */
406 function process( $pattern, $extracts, &$linesleft, &$contextchars, &$out, &$offsets ) {
407 if ( $linesleft == 0 ) {
408 return; // nothing to do
409 }
410 foreach ( $extracts as $index => $line ) {
411 if ( array_key_exists( $index, $out ) ) {
412 continue; // this line already highlighted
413 }
414
415 $m = array();
416 if ( !preg_match( $pattern, $line, $m, PREG_OFFSET_CAPTURE ) ) {
417 continue;
418 }
419
420 $offset = $m[0][1];
421 $len = strlen( $m[0][0] );
422 if ( $offset + $len < $contextchars ) {
423 $begin = 0;
424 } elseif ( $len > $contextchars ) {
425 $begin = $offset;
426 } else {
427 $begin = $offset + intval( ( $len - $contextchars ) / 2 );
428 }
429
430 $end = $begin + $contextchars;
431
432 $posBegin = $begin;
433 // basic snippet from this line
434 $out[$index] = $this->extract( $line, $begin, $end, $posBegin );
435 $offsets[$index] = $posBegin;
436 $linesleft--;
437 if ( $linesleft == 0 ) {
438 return;
439 }
440 }
441 }
442
443 /**
444 * Basic wikitext removal
445 * @protected
446 * @param string $text
447 * @return mixed
448 */
449 function removeWiki( $text ) {
450 $fname = __METHOD__;
451
452 // $text = preg_replace( "/'{2,5}/", "", $text );
453 // $text = preg_replace( "/\[[a-z]+:\/\/[^ ]+ ([^]]+)\]/", "\\2", $text );
454 // $text = preg_replace( "/\[\[([^]|]+)\]\]/", "\\1", $text );
455 // $text = preg_replace( "/\[\[([^]]+\|)?([^|]]+)\]\]/", "\\2", $text );
456 // $text = preg_replace( "/\\{\\|(.*?)\\|\\}/", "", $text );
457 // $text = preg_replace( "/\\[\\[[A-Za-z_-]+:([^|]+?)\\]\\]/", "", $text );
458 $text = preg_replace( "/\\{\\{([^|]+?)\\}\\}/", "", $text );
459 $text = preg_replace( "/\\{\\{([^|]+\\|)(.*?)\\}\\}/", "\\2", $text );
460 $text = preg_replace( "/\\[\\[([^|]+?)\\]\\]/", "\\1", $text );
461 $text = preg_replace_callback(
462 "/\\[\\[([^|]+\\|)(.*?)\\]\\]/",
463 array( $this, 'linkReplace' ),
464 $text
465 );
466 // $text = preg_replace("/\\[\\[([^|]+\\|)(.*?)\\]\\]/", "\\2", $text);
467 $text = preg_replace( "/<\/?[^>]+>/", "", $text );
468 $text = preg_replace( "/'''''/", "", $text );
469 $text = preg_replace( "/('''|<\/?[iIuUbB]>)/", "", $text );
470 $text = preg_replace( "/''/", "", $text );
471
472 return $text;
473 }
474
475 /**
476 * callback to replace [[target|caption]] kind of links, if
477 * the target is category or image, leave it
478 *
479 * @param array $matches
480 * @return string
481 */
482 function linkReplace( $matches ) {
483 $colon = strpos( $matches[1], ':' );
484 if ( $colon === false ) {
485 return $matches[2]; // replace with caption
486 }
487 global $wgContLang;
488 $ns = substr( $matches[1], 0, $colon );
489 $index = $wgContLang->getNsIndex( $ns );
490 if ( $index !== false && ( $index == NS_FILE || $index == NS_CATEGORY ) ) {
491 return $matches[0]; // return the whole thing
492 } else {
493 return $matches[2];
494 }
495 }
496
497 /**
498 * Simple & fast snippet extraction, but gives completely unrelevant
499 * snippets
500 *
501 * @param string $text
502 * @param array $terms
503 * @param int $contextlines
504 * @param int $contextchars
505 * @return string
506 */
507 public function highlightSimple( $text, $terms, $contextlines, $contextchars ) {
508 global $wgContLang;
509 $fname = __METHOD__;
510
511 $lines = explode( "\n", $text );
512
513 $terms = implode( '|', $terms );
514 $max = intval( $contextchars ) + 1;
515 $pat1 = "/(.*)($terms)(.{0,$max})/i";
516
517 $lineno = 0;
518
519 $extract = "";
520 foreach ( $lines as $line ) {
521 if ( 0 == $contextlines ) {
522 break;
523 }
524 ++$lineno;
525 $m = array();
526 if ( !preg_match( $pat1, $line, $m ) ) {
527 continue;
528 }
529 --$contextlines;
530 // truncate function changes ... to relevant i18n message.
531 $pre = $wgContLang->truncate( $m[1], - $contextchars, '...', false );
532
533 if ( count( $m ) < 3 ) {
534 $post = '';
535 } else {
536 $post = $wgContLang->truncate( $m[3], $contextchars, '...', false );
537 }
538
539 $found = $m[2];
540
541 $line = htmlspecialchars( $pre . $found . $post );
542 $pat2 = '/(' . $terms . ")/i";
543 $line = preg_replace( $pat2, "<span class='searchmatch'>\\1</span>", $line );
544
545 $extract .= "${line}\n";
546 }
547
548 return $extract;
549 }
550
551 /**
552 * Returns the first few lines of the text
553 *
554 * @param string $text
555 * @param int $contextlines Max number of returned lines
556 * @param int $contextchars Average number of characters per line
557 * @return string
558 */
559 public function highlightNone( $text, $contextlines, $contextchars ) {
560 $match = array();
561 $text = ltrim( $text ) . "\n"; // make sure the preg_match may find the last line
562 $text = str_replace( "\n\n", "\n", $text ); // remove empty lines
563 preg_match( "/^(.*\n){0,$contextlines}/", $text, $match );
564 $text = htmlspecialchars( substr( trim( $match[0] ), 0, $contextlines * $contextchars ) ); // trim and limit to max number of chars
565 return str_replace( "\n", '<br>', $text );
566 }
567 }