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