Project

General

Profile

1
<?php
2

    
3
// $Id: search_modext.php 1212 2009-12-12 14:02:06Z MaGnaL $
4

    
5
/*
6

    
7
 Website Baker Project <http://www.websitebaker.org/>
8
 Copyright (C) 2004-2009, Ryan Djurovich
9

    
10
 Website Baker is free software; you can redistribute it and/or modify
11
 it under the terms of the GNU General Public License as published by
12
 the Free Software Foundation; either version 2 of the License, or
13
 (at your option) any later version.
14

    
15
 Website Baker is distributed in the hope that it will be useful,
16
 but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 GNU General Public License for more details.
19

    
20
 You should have received a copy of the GNU General Public License
21
 along with Website Baker; if not, write to the Free Software
22
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23

    
24
*/
25

    
26
// make the url-string for highlighting
27
function make_url_searchstring($search_match, $search_url_array) {
28
	$link = "";
29
	if ($search_match != 'exact') {
30
		$str = implode(" ", $search_url_array);
31
		$link = "?searchresult=1&amp;sstring=".urlencode($str);
32
	} else {
33
		$str = str_replace(' ', '_', $search_url_array[0]);
34
		$link = "?searchresult=2&amp;sstring=".urlencode($str);
35
	}
36
	return $link;
37
}
38

    
39
// make date and time for "last modified by... on ..."-string
40
function get_page_modified($page_modified_when) {
41
	global $TEXT;
42
	if($page_modified_when > 0) {
43
		$date = gmdate(DATE_FORMAT, $page_modified_when+TIMEZONE);
44
		$time = gmdate(TIME_FORMAT, $page_modified_when+TIMEZONE);
45
	} else {
46
		$date = $TEXT['UNKNOWN'].' '.$TEXT['DATE'];
47
		$time = $TEXT['UNKNOWN'].' '.$TEXT['TIME'];
48
	}
49
	return array($date, $time);
50
}
51

    
52
// make username and displayname for "last modified by... on ..."-string
53
function get_page_modified_by($page_modified_by, $users) {
54
	global $TEXT;
55
	// check for existing user-id
56
	if(!isset($users[$page_modified_by]))
57
		$page_modified_by = 0;
58
	
59
	$username = $users[$page_modified_by]['username'];
60
	$displayname = $users[$page_modified_by]['display_name'];
61
	return array($username, $displayname);
62
}
63

    
64
// checks if _all_ searchwords matches
65
function is_all_matched($text, $search_words) {
66
	$all_matched = true;
67
	foreach ($search_words AS $word) {
68
		if(!preg_match('/'.$word.'/ui', $text)) {
69
			$all_matched = false;
70
			break;
71
		}
72
	}
73
	return $all_matched;
74
}
75

    
76
// checks if _any_ of the searchwords matches
77
function is_any_matched($text, $search_words) {
78
	$any_matched = false;
79
	$word = '('.implode('|', $search_words).')';
80
	if(preg_match('/'.$word.'/ui', $text)) {
81
		$any_matched = true;
82
	}
83
	return $any_matched;
84
}
85

    
86
// collects the matches from text in excerpt_array
87
function get_excerpts($text, $search_words, $max_excerpt_num) {
88
	$match_array = array();
89
	$excerpt_array = array();
90
	$word = '('.implode('|', $search_words).')';
91

    
92
	//Filter droplets from the page data
93
	preg_match_all('~\[\[(.*?)\]\]~', $text, $matches);
94
	foreach ($matches[1] as $match) {
95
		$text = str_replace('[['.$match.']]', '', $text);					
96
	}
97

    
98
	// Build the regex-string
99
	if(strpos(strtoupper(PHP_OS), 'WIN')===0) { // windows -> see below
100
		$str1=".!?;";
101
		$str2=".!?;";
102
	} else { // linux & Co.
103
		// start-sign: .!?; + INVERTED EXCLAMATION MARK - INVERTED QUESTION MARK - DOUBLE EXCLAMATION MARK - INTERROBANG - EXCLAMATION QUESTION MARK - QUESTION EXCLAMATION MARK - DOUBLE QUESTION MARK - HALFWIDTH IDEOGRAPHIC FULL STOP - IDEOGRAPHIC FULL STOP - IDEOGRAPHIC COMMA
104
		$str1=".!?;"."\xC2\xA1"."\xC2\xBF"."\xE2\x80\xBC"."\xE2\x80\xBD"."\xE2\x81\x89"."\xE2\x81\x88"."\xE2\x81\x87"."\xEF\xBD\xA1"."\xE3\x80\x82"."\xE3\x80\x81";
105
		// stop-sign: .!?; + DOUBLE EXCLAMATION MARK - INTERROBANG - EXCLAMATION QUESTION MARK - QUESTION EXCLAMATION MARK - DOUBLE QUESTION MARK - HALFWIDTH IDEOGRAPHIC FULL STOP - IDEOGRAPHIC FULL STOP - IDEOGRAPHIC COMMA
106
		$str2=".!?;"."\xE2\x80\xBC"."\xE2\x80\xBD"."\xE2\x81\x89"."\xE2\x81\x88"."\xE2\x81\x87"."\xEF\xBD\xA1"."\xE3\x80\x82"."\xE3\x80\x81";
107
	}
108
	$regex='/(?:^|\b|['.$str1.'])([^'.$str1.']{0,200}?'.$word.'[^'.$str2.']{0,200}(?:['.$str2.']|\b|$))/uis';
109
	if(version_compare(PHP_VERSION, '4.3.3', '>=') &&
110
	   strpos(strtoupper(PHP_OS), 'WIN')!==0
111
	) { // this may crash windows server, so skip if on windows
112
		// jump from match to match, get excerpt, stop if $max_excerpt_num is reached
113
		$last_end = 0; $offset = 0;
114
		while(preg_match('/'.$word.'/uis', $text, $match_array, PREG_OFFSET_CAPTURE, $last_end)) {
115
			$offset = ($match_array[0][1]-206 < $last_end)?$last_end:$match_array[0][1]-206;
116
			if(preg_match($regex, $text, $matches, PREG_OFFSET_CAPTURE, $offset)) {
117
				$last_end = $matches[1][1]+strlen($matches[1][0])-1;
118
				if(!preg_match('/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\./', $matches[1][0])) // skip excerpts with email-addresses
119
					$excerpt_array[] = trim($matches[1][0]);
120
				if(count($excerpt_array)>=$max_excerpt_num) {
121
					$excerpt_array = array_unique($excerpt_array);
122
					if(count($excerpt_array) >= $max_excerpt_num)
123
						break;
124
				}
125
			} else { // problem: preg_match failed - can't find a start- or stop-sign
126
				$last_end += 201; // jump forward and try again
127
			}
128
		}
129
	} else { // compatible, but may be very slow with large pages
130
		if(preg_match_all($regex, $text, $match_array)) {
131
			foreach($match_array[1] AS $string) {
132
				if(!preg_match('/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\./', $string))  // skip excerpts with email-addresses
133
					$excerpt_array[] = trim($string);
134
				
135
			}
136
		}
137
	}
138
	return $excerpt_array;
139
}
140

    
141
// makes excerpt_array a string ready to print out
142
function prepare_excerpts($excerpt_array, $search_words, $max_excerpt_num) {
143
	// excerpts: text before and after a single excerpt, html-tag for markup
144
	$EXCERPT_BEFORE =       '...&nbsp;';
145
	$EXCERPT_AFTER =        '&nbsp;...<br />';
146
	$EXCERPT_MARKUP_START = '<b>';
147
	$EXCERPT_MARKUP_END =   '</b>';
148
	// remove duplicate matches from $excerpt_array, if any.
149
	$excerpt_array = array_unique($excerpt_array);
150
	// use the first $max_excerpt_num excerpts only
151
	if(count($excerpt_array) > $max_excerpt_num) {
152
		$excerpt_array = array_slice($excerpt_array, 0, $max_excerpt_num);
153
	}
154
	// prepare search-string
155
	$string = "(".implode("|", $search_words).")";
156
	// we want markup on search-results page,
157
	// but we need some 'magic' to prevent <br />, <b>... from being highlighted
158
	$excerpt = '';
159
	foreach($excerpt_array as $str) {
160
		$excerpt .= '#,,#'.preg_replace("/($string)/iu","#,,,,#$1#,,,,,#",$str).'#,,,#';
161
	}
162
	$excerpt = str_replace(array('&','<','>','"','\'',"\xC2\xA0"), array('&amp;','&lt;','&gt;','&quot;','&#039;','&nbsp;'), $excerpt);
163
	$excerpt = str_replace(array('#,,,,#','#,,,,,#'), array($EXCERPT_MARKUP_START,$EXCERPT_MARKUP_END), $excerpt);
164
	$excerpt = str_replace(array('#,,#','#,,,#'), array($EXCERPT_BEFORE,$EXCERPT_AFTER), $excerpt);
165
	// prepare to write out
166
	if(DEFAULT_CHARSET != 'utf-8') {
167
		$excerpt = umlauts_to_entities($excerpt, 'UTF-8');
168
	}
169
	return $excerpt;
170
}
171

    
172
// work out what the link-anchor should be
173
function make_url_target($page_link_target, $text, $search_words) {
174
	// 1. e.g. $page_link_target=="&monthno=5&year=2007" - module-dependent target. Do nothing.
175
	// 2. $page_link_target=="#!wb_section_..." - the user wants the section-target, so do nothing.
176
	// 3. $page_link_target=="#wb_section_..." - try to find a better target, use the section-target as fallback.
177
	// 4. $page_link_target=="" - do nothing
178
	if(version_compare(PHP_VERSION, '4.3.3', ">=") && substr($page_link_target,0,12)=='#wb_section_') {
179
		$word = '('.implode('|', $search_words).')';
180
		preg_match('/'.$word.'/ui', $text, $match, PREG_OFFSET_CAPTURE);
181
		if($match && is_array($match[0])) {
182
			$x=$match[0][1]; // position of first match
183
			// is there an anchor nearby?
184
			if(preg_match_all('/<(?:[^>]+id|\s*a[^>]+name)\s*=\s*"(.*)"/iU', substr($text,0,$x), $match, PREG_OFFSET_CAPTURE)) {
185
				$anchor='';
186
				foreach($match[1] AS $array) {
187
					if($array[1] > $x) {
188
						break;
189
					}
190
					$anchor = $array[0];
191
				}
192
				if($anchor != '') {
193
					$page_link_target = '#'.$anchor;
194
				}
195
			}
196
		}
197
	}
198
	elseif(substr($page_link_target,0,13)=='#!wb_section_') {
199
		$page_link_target = '#'.substr($page_link_target, 2);
200
	}
201
	
202
	// since wb 2.7.1 the section-anchor is configurable - SEC_ANCHOR holds the anchor name
203
	if(substr($page_link_target,0,12)=='#wb_section_') {
204
		if(defined('SEC_ANCHOR') && SEC_ANCHOR!='') {
205
			$sec_id = substr($page_link_target, 12);
206
			$page_link_target = '#'.SEC_ANCHOR.$sec_id;
207
		} else { // section-anchors are disabled
208
			$page_link_target = '';
209
		}
210
	}
211
	
212
	return $page_link_target;
213
}
214

    
215
// wrapper for compatibility with old print_excerpt()
216
function print_excerpt($page_link, $page_link_target, $page_title, $page_description, $page_modified_when, $page_modified_by, $text, $max_excerpt_num, $func_vars, $pic_link="") {
217
	$mod_vars = array(
218
		'page_link' => $page_link,
219
		'page_link_target' => $page_link_target,
220
		'page_title' => $page_title,
221
		'page_description' => $page_description,
222
		'page_modified_when' => $page_modified_when,
223
		'page_modified_by' => $page_modified_by,
224
		'text' => $text,
225
		'max_excerpt_num' => $max_excerpt_num,
226
		'pic_link' => $pic_link
227
	);
228
	print_excerpt2($mod_vars, $func_vars);
229
}
230

    
231
/* These functions can be used in module-supplied search_funcs
232
 * -----------------------------------------------------------
233
 * print_excerpt2() - the main-function to use in all search_funcs
234
 * print_excerpt() - wrapper for compatibility-reason. Use print_excerpt2() instead.
235
 * list_files_dirs() - lists all files and dirs below a given directory
236
 * clear_filelist() - keeps only wanted or removes unwanted entries in file-list.
237
 */
238
 
239
// prints the excerpts for one section
240
function print_excerpt2($mod_vars, $func_vars) {
241
	extract($func_vars, EXTR_PREFIX_ALL, 'func');
242
	extract($mod_vars, EXTR_PREFIX_ALL, 'mod');
243
	global $TEXT;
244
	// check $mod_...vars
245
	if(!isset($mod_page_link))          $mod_page_link = $func_page_link;
246
	if(!isset($mod_page_link_target))   $mod_page_link_target = "";
247
	if(!isset($mod_page_title))         $mod_page_title = $func_page_title;
248
	if(!isset($mod_page_description))   $mod_page_description = $func_page_description;
249
	if(!isset($mod_page_modified_when)) $mod_page_modified_when = $func_page_modified_when;
250
	if(!isset($mod_page_modified_by))   $mod_page_modified_by = $func_page_modified_by;
251
	if(!isset($mod_text))               $mod_text = "";
252
	if(!isset($mod_max_excerpt_num))    $mod_max_excerpt_num = $func_default_max_excerpt;
253
	if(!isset($mod_pic_link))           $mod_pic_link = "";
254
	if(!isset($mod_no_highlight))       $mod_no_highlight = false;
255
	if(!isset($func_enable_flush))      $func_enable_flush = false; // set this in db: wb_search.cfg_enable_flush [READ THE DOC BEFORE]
256
	if(isset($mod_ext_charset)) $mod_ext_charset = strtolower($mod_ext_charset);
257
	else $mod_ext_charset = '';
258

    
259
	if($mod_text == "") // nothing to do
260
		{ return false; }
261

    
262
	if($mod_no_highlight) // no highlighting
263
		{ $mod_page_link_target = "&amp;nohighlight=1".$mod_page_link_target; }
264
	// clean the text:
265
	$mod_text = preg_replace('#<(!--.*--|style.*</style|script.*</script)>#iU', ' ', $mod_text);
266
	$mod_text = preg_replace('#<(br( /)?|dt|/dd|/?(h[1-6]|tr|table|p|li|ul|pre|code|div|hr))[^>]*>#i', '.', $mod_text);
267
	$mod_text = preg_replace('/(\v\s?|\s\s)+/', ' ', $mod_text);
268
	$mod_text = preg_replace('/\s\./', '.', $mod_text);
269
	if($mod_ext_charset!='') { // data from external database may have a different charset
270
		require_once(WB_PATH.'/framework/functions-utf8.php');
271
		switch($mod_ext_charset) {
272
		case 'latin1':
273
		case 'cp1252':
274
			$mod_text = charset_to_utf8($mod_text, 'CP1252');
275
			break;
276
		case 'cp1251':
277
			$mod_text = charset_to_utf8($mod_text, 'CP1251');
278
			break;
279
		case 'latin2':
280
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-2');
281
			break;
282
		case 'hebrew':
283
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-8');
284
			break;
285
		case 'greek':
286
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-7');
287
			break;
288
		case 'latin5':
289
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-9');
290
			break;
291
		case 'latin7':
292
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-13');
293
			break;
294
		case 'utf8':
295
		default:
296
			$mod_text = charset_to_utf8($mod_text, 'UTF-8');
297
		}
298
	} else {
299
	$mod_text = entities_to_umlauts($mod_text, 'UTF-8');
300
	}
301
	$anchor_text = $mod_text; // make an copy containing html-tags
302
	$mod_text = strip_tags($mod_text);
303
	$mod_text = str_replace(array('&gt;','&lt;','&amp;','&quot;','&#039;','&apos;','&nbsp;'), array('>','<','&','"','\'','\'',"\xC2\xA0"), $mod_text);
304
	$mod_text = '.'.trim($mod_text).'.';
305
	// Do a fast scan over $mod_text first. This will speedup things a lot.
306
	if($func_search_match == 'all') {
307
		if(!is_all_matched($mod_text, $func_search_words))
308
			return false;
309
	}
310
	elseif(!is_any_matched($mod_text, $func_search_words)) {
311
		return false;
312
	}
313
	// search for an better anchor - this have to be done before strip_tags() (may fail if search-string contains <, &, amp, gt, lt, ...)
314
	$anchor =  make_url_target($mod_page_link_target, $anchor_text, $func_search_words);
315

    
316
	// make the link from $mod_page_link, add anchor
317
	$link = "";
318
	$link = page_link($mod_page_link);
319
	if(strpos($mod_page_link, 'http:')===FALSE)
320
		$link .= make_url_searchstring($func_search_match, $func_search_url_array);
321
	$link .= $anchor;
322

    
323
	// now get the excerpt
324
	$excerpt = "";
325
	$excerpt_array = array();
326
	if($mod_max_excerpt_num > 0) {
327
		if(!$excerpt_array = get_excerpts($mod_text, $func_search_words, $mod_max_excerpt_num)) {
328
			return false;
329
		}
330
		$excerpt = prepare_excerpts($excerpt_array, $func_search_words, $mod_max_excerpt_num);
331
	}
332

    
333
	// handle thumbs - to deactivate this look in the module's search.php: $show_thumb (or maybe in the module's settings-page)
334
	if($mod_pic_link != "") {
335
		$excerpt = '<table class="excerpt_thumb" width="100%" cellspacing="0" cellpadding="0" border="0"><tbody><tr><td width="110" valign="top"><a href="'.$link.'"><img src="'.WB_URL.'/'.MEDIA_DIRECTORY.$mod_pic_link.'" alt="" /></a></td><td>'.$excerpt.'</td></tr></tbody></table>';
336
	}
337

    
338
	// print-out the excerpt
339
	$vars = array();
340
	$values = array();
341
	list($date, $time) = get_page_modified($mod_page_modified_when);
342
	list($username, $displayname) = get_page_modified_by($mod_page_modified_by, $func_users);
343
	$vars = array('[LINK]', '[TITLE]', '[DESCRIPTION]', '[USERNAME]','[DISPLAY_NAME]','[DATE]','[TIME]','[TEXT_LAST_UPDATED_BY]','[TEXT_ON]','[EXCERPT]');
344
	$values = array(
345
		$link,
346
		$mod_page_title,
347
		$mod_page_description,
348
		$username,
349
		$displayname,
350
		$date,
351
		$time,
352
		$TEXT['LAST_UPDATED_BY'],
353
		$TEXT['ON'],
354
		$excerpt
355
	);
356
	echo str_replace($vars, $values, $func_results_loop_string);
357
	if($func_enable_flush) { // ATTN: this will bypass output-filters and may break template-layout or -filters
358
		ob_flush();flush();
359
	}
360
	return true;
361
}
362

    
363
// list all files and dirs in $dir (recursive), omits '.', '..', and hidden files/dirs
364
// returns an array of two arrays ($files[] and $dirs[]).
365
// usage: list($files,$dirs) = list_files_dirs($directory);
366
//        $depth: get subdirs (true/false)
367
function list_files_dirs($dir, $depth=true, $files=array(), $dirs=array()) {
368
	$dh=opendir($dir);
369
	while(($file = readdir($dh)) !== false) {
370
		if($file{0} == '.' || $file == '..') {
371
			continue;
372
		}
373
		if(is_dir($dir.'/'.$file)) {
374
			if($depth) {
375
				$dirs[] = $dir.'/'.$file;
376
				list($files, $dirs) = list_files_dirs($dir.'/'.$file, $depth, $files, $dirs);
377
			}
378
		} else {
379
			$files[] = $dir.'/'.$file;
380
		}
381
	}
382
	closedir($dh);
383
	natcasesort($files);
384
	natcasesort($dirs);
385
	return(array($files, $dirs));
386
}
387

    
388
// keeps only wanted entries in array $files. $str have to be an eregi()-compatible regex
389
function clear_filelist($files, $str, $keep=true) {
390
	// options: $keep = true  : remove all non-matching entries
391
	//          $keep = false : remove all matching entries
392
	$c_filelist = array();
393
	if($str == '')
394
		return $files;
395
	foreach($files as $file) {
396
		if($keep) {
397
			if(eregi($str, $file)) {
398
				$c_filelist[] = $file;
399
			}
400
		} else {
401
			if(!eregi($str, $file)) {
402
				$c_filelist[] = $file;
403
			}
404
		}
405
	}
406
	return($c_filelist);
407
}
408

    
409
?>
(4-4/4)