Project

General

Profile

1
<?php
2

    
3
// $Id: search_modext.php 670 2008-02-08 16:47:43Z thorn $
4

    
5
/*
6

    
7
 Website Baker Project <http://www.websitebaker.org/>
8
 Copyright (C) 2004-2008, 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 = strtr($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
	if($page_modified_by > 0) {
56
			$username = $users[$page_modified_by]['username'];
57
			$displayname = $users[$page_modified_by]['display_name'];
58
		} else {
59
			$username = "";
60
			$displayname = $TEXT['UNKNOWN'];
61
		}
62
	return array($username, $displayname);
63
}
64

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

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

    
87
// collects the matches from text in excerpt_array
88
function get_excerpts($text, $search_words, $max_excerpt_num) {
89
	$match_array = array();
90
	$excerpt_array = array();
91
	$word = "(".implode("|", $search_words).")";
92
	
93
	$text = strtr($text, array('&lt;'=>'<', '&gt;'=>'>', '&amp;'=>'&', '&quot;'=>'"', '&#39;'=>'\'', '&nbsp;'=>"\xC2\xA0"));
94
	$word = strtr($word, array('&lt;'=>'<', '&gt;'=>'>', '&amp;'=>'&', '&quot;'=>'"', '&#39;'=>'\'', '&nbsp;'=>"\xC2\xA0"));
95
	// Build the regex-string
96
	//...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
97
	$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";
98
	// ...DOUBLE EXCLAMATION MARK - INTERROBANG - EXCLAMATION QUESTION MARK - QUESTION EXCLAMATION MARK - DOUBLE QUESTION MARK - HALFWIDTH IDEOGRAPHIC FULL STOP - IDEOGRAPHIC FULL STOP - IDEOGRAPHIC COMMA
99
	$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";
100
	// "{0,200}?'.$word.'" : the '?' (ungreedy) is for performance-tuning; try a step-by-step-trace to see what i mean. 
101
	if(preg_match_all('/(?:^|\b|['.$str1.'])([^'.$str1.']{0,200}?'.$word.'[^'.$str2.']{0,200}(?:['.$str2.']|\b|$))/isu', $text, $match_array)) {
102
		foreach($match_array[1] AS $string) {
103
			$excerpt_array[] = trim($string);
104
		}
105
	}
106
	return $excerpt_array;
107
}
108

    
109
// makes excerpt_array a string ready to print out
110
function prepare_excerpts($excerpt_array, $search_words, $max_excerpt_num) {
111
	// excerpts: text before and after a single excerpt, html-tag for markup
112
	$EXCERPT_BEFORE =       '...&nbsp;';
113
	$EXCERPT_AFTER =        '&nbsp;...<br />';
114
	$EXCERPT_MARKUP_START = '<b>';
115
	$EXCERPT_MARKUP_END =   '</b>';
116
	// remove duplicate matches from $excerpt_array, if any.
117
	$excerpt_array = array_unique($excerpt_array);
118
	// use the first $max_excerpt_num excerpts only
119
	if(count($excerpt_array) > $max_excerpt_num) {
120
		$excerpt_array = array_slice($excerpt_array, 0, $max_excerpt_num);
121
	}
122
	// prepare search-string
123
	$string = "(".implode("|", $search_words).")";
124
	$string = strtr($string, array('&lt;'=>'<', '&gt;'=>'>', '&amp;'=>'&', '&quot;'=>'"', '&#39;'=>'\'', '&nbsp;'=>"\xC2\xA0"));
125
	// we want markup on search-results page,
126
	// but we need some 'magic' to prevent <br />, <b>... from being highlighted
127
	$excerpt = '';
128
	foreach($excerpt_array as $str) {
129
		$excerpt .= '#,,#'.preg_replace("/($string)/iu","#,,,,#$1#,,,,,#",$str).'#,,,#';
130
	}
131
	$excerpt = strtr($excerpt, array('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;', '\''=>'&#39;'));
132
	$excerpt = strtr($excerpt, array('#,,,,#'=>$EXCERPT_MARKUP_START, '#,,,,,#'=>$EXCERPT_MARKUP_END));
133
	$excerpt = strtr($excerpt, array('#,,#'=>$EXCERPT_BEFORE, '#,,,#'=>$EXCERPT_AFTER));
134
	// prepare to write out
135
	if(DEFAULT_CHARSET != 'utf-8') {
136
		$excerpt = umlauts_to_entities($excerpt, 'UTF-8');
137
	}
138
	return $excerpt;
139
}
140

    
141
// work out what the link-target should be
142
function make_url_target($page_link_target, $text, $search_words) {
143
	// 1. e.g. $page_link_target=="&monthno=5&year=2007" - module-dependent target. Do nothing.
144
	// 2. $page_link_target=="#!wb_section_..." - the user wants the section-target, so do nothing.
145
	// 3. $page_link_target=="#wb_section_..." - try to find a better target, use the section-target as fallback.
146
	// 4. $page_link_target=="" - do nothing
147
	if(version_compare(PHP_VERSION, '4.3.0', ">=") && substr($page_link_target,0,12)=='#wb_section_') {
148
		$word = '('.implode('|', $search_words).')';
149
		preg_match('/'.$word.'/iu', $text, $match, PREG_OFFSET_CAPTURE);
150
		if($match && is_array($match[0])) {
151
			$x=$match[0][1];
152
			// is there an anchor nearby?
153
			if (preg_match_all('/<(?:[^>]+id|\s*a[^>]+name)\s*=\s*"(.*)"/iuU', $text, $match, PREG_OFFSET_CAPTURE)) {
154
				$anchor='';
155
				foreach($match[1] AS $array) {
156
					if($array[1] > $x) {
157
						break;
158
					}
159
					$anchor = $array[0];
160
				}
161
				if($anchor != '') {
162
					$page_link_target = '#'.$anchor;
163
				}
164
			}
165
		}
166
	}
167
	elseif(substr($page_link_target,0,13)=='#!wb_section_') {
168
		$page_link_target = '#'.substr($page_link_target, 2);
169
	}
170
	return $page_link_target;
171
}
172

    
173
// wrapper for compatibility with old print_excerpt()
174
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="") {
175
	$mod_vars = array(
176
		'page_link' => $page_link,
177
		'page_link_target' => $page_link_target,
178
		'page_title' => $page_title,
179
		'page_description' => $page_description,
180
		'page_modified_when' => $page_modified_when,
181
		'page_modified_by' => $page_modified_by,
182
		'text' => $text,
183
		'max_excerpt_num' => $max_excerpt_num,
184
		'pic_link' => $pic_link
185
	);
186
	print_excerpt2($mod_vars, $func_vars);
187
}
188

    
189
/* These functions can be used in module-supplied search_funcs
190
 * -----------------------------------------------------------
191
 * print_excerpt2() - the main-function to use in all search_funcs
192
 * print_excerpt() - wrapper for compatibility-reason. Use print_excerpt2() instead.
193
 * list_files_dirs() - lists all files and dirs below a given directory
194
 * clear_filelist() - keeps only wanted or removes unwanted entries in file-list.
195
 */
196
 
197
// prints the excerpts for one section
198
function print_excerpt2($mod_vars, $func_vars) {
199
	extract($func_vars, EXTR_PREFIX_ALL, 'func');
200
	extract($mod_vars, EXTR_PREFIX_ALL, 'mod');
201
	global $TEXT;
202
	// check $mod_...vars
203
	if(!isset($mod_page_link))          $mod_page_link = $func_page_link;
204
	if(!isset($mod_page_link_target))   $mod_page_link_target = "";
205
	if(!isset($mod_page_title))         $mod_page_title = $func_page_title;
206
	if(!isset($mod_page_description))   $mod_page_description = $func_page_description;
207
	if(!isset($mod_page_modified_when)) $mod_page_modified_when = $func_page_modified_when;
208
	if(!isset($mod_page_modified_by))   $mod_page_modified_by = $func_page_modified_by;
209
	if(!isset($mod_text))               $mod_text = "";
210
	if(!isset($mod_max_excerpt_num))    $mod_max_excerpt_num = $func_default_max_excerpt;
211
	if(!isset($mod_pic_link))           $mod_pic_link = "";
212
	if(!isset($mod_no_highlight))       $mod_no_highlight = false;
213
	if($mod_text == "") // nothing to do
214
		{ return false; }
215
	if($mod_no_highlight) // no highlighting
216
		{ $mod_page_link_target = "&nohighlight".$mod_page_link_target; }
217

    
218
	// prepare the text (part 1): remove lf and cr, convert \" to ", remove comments, style, scripting and unnecessary whitespace, convert to utf8
219
	$mod_text = strtr($mod_text, array("\x0D\x0A" => ' ', "\x0D" => ' ', "\x0A" => ' ', '\"' => '"'));
220
	$mod_text = preg_replace('/(<!--.*?-->|<style.*?<\/style>|<script.*?<\/script>|\s+)/i', ' ', $mod_text);
221
	// remove email-addresses
222
	$mod_text = preg_replace('/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\b/', ' ', $mod_text);
223
	$mod_text = entities_to_umlauts($mod_text, 'UTF-8');
224

    
225
	// make the link from $mod_page_link, add target
226
	$link = "";
227
	$link = page_link($mod_page_link);
228
	$link .= make_url_searchstring($func_search_match, $func_search_url_array);
229
	$link .= make_url_target($mod_page_link_target, $mod_text, $func_search_words);
230

    
231
	// prepare the text (part 2): convert some special tags to '.', strip tags
232
	$mod_text = preg_replace('/<(br( \/)?|dt|\/dd|\/?(h[1-6]|tr|table|p|li|ul|pre|code|div|hr))[^>]*>/i', '.', $mod_text);
233
	$mod_text = strip_tags($mod_text);
234

    
235
// unhtmlspecialchars
236
//	$mod_text = strtr($mod_text, array('&lt;'=>'<', '&gt;'=>'>', '&amp;'=>'&', '&quot;'=>'"', '&#39;'=>'\'', '&nbsp;'=>"\xC2\xA0"));
237
//	$tmp_words = array();
238
//	foreach($func_search_words as $w) {
239
//		$tmp_words[] = strtr($w, array('&lt;'=>'<', '&gt;'=>'>', '&amp;'=>'&', '&quot;'=>'"', '&#39;'=>'\'', '&nbsp;'=>"\xC2\xA0"));
240
//	}
241
//	$func_search_words = $tmp_words;
242

    
243
	// Do a fast scan over $mod_text first. This will speedup things a lot.
244
	if($func_search_match == 'all') {
245
		if(!is_all_matched($mod_text, $func_search_words)) {
246
			return false;
247
		}
248
	}
249
	elseif(!is_any_matched($mod_text, $func_search_words)) {
250
		return false;
251
	}
252

    
253
	// now get the excerpt
254
	$excerpt = "";
255
	$excerpt_array = array();
256
	if($mod_max_excerpt_num > 0) {
257
		if(!$excerpt_array = get_excerpts($mod_text, $func_search_words, $mod_max_excerpt_num)) {
258
			return false;
259
		}
260
		$excerpt = prepare_excerpts($excerpt_array, $func_search_words, $mod_max_excerpt_num);
261
	}
262

    
263
	// handle image
264
	if($mod_pic_link != "") {
265
		$excerpt = '<table 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>';
266
	}
267

    
268
	// print-out the excerpt
269
	$vars = array();
270
	$values = array();
271
	list($date, $time) = get_page_modified($mod_page_modified_when);
272
	list($username, $displayname) = get_page_modified_by($mod_page_modified_by, $func_users);
273
	$vars = array('[LINK]', '[TITLE]', '[DESCRIPTION]', '[USERNAME]','[DISPLAY_NAME]','[DATE]','[TIME]','[TEXT_LAST_UPDATED_BY]','[TEXT_ON]','[EXCERPT]');
274
	$values = array(
275
		$link,
276
		$mod_page_title,
277
		$mod_page_description,
278
		$username,
279
		$displayname,
280
		$date,
281
		$time,
282
		$TEXT['LAST_UPDATED_BY'],
283
		$TEXT['ON'],
284
		$excerpt
285
	);
286
	echo str_replace($vars, $values, $func_results_loop_string);
287
	return true;
288
}
289

    
290
// list all files and dirs in $dir (recursive), omits '.' and '..'
291
// returns an array of two arrays ($files[] and $dirs[]).
292
// usage: list($files,$dirs) = list_files_dirs($directory);
293
//        $depth: get subdirs (true/false)
294
function list_files_dirs($dir, $depth=true, $files=array(), $dirs=array()) {
295
	$dh=opendir($dir);
296
	while(($file = readdir($dh)) !== false) {
297
		if($file == '.' || $file == '..') {
298
			continue;
299
		}
300
		if(is_dir($dir.'/'.$file)) {
301
			if($depth) {
302
				$dirs[] = $dir.'/'.$file;
303
				list($files, $dirs) = list_files_dirs($dir.'/'.$file, $depth, $files, $dirs);
304
			}
305
		} else {
306
			$files[] = $dir.'/'.$file;
307
		}
308
	}
309
	closedir($dh);
310
	natcasesort($files);
311
	natcasesort($dirs);
312
	return(array($files, $dirs));
313
}
314

    
315
// keeps only wanted entries in array $files. $str have to be an eregi()-compatible regex
316
function clear_filelist($files, $str, $keep=true) {
317
	// $keep = true  : remove all non-matching entries
318
	// $keep = false : remove all matching entries
319
	$c_filelist = array();
320
	if($str == '')
321
		return $files;
322
	foreach($files as $file) {
323
		if($keep) {
324
			if(eregi($str, $file)) {
325
				$c_filelist[] = $file;
326
			}
327
		} else {
328
			if(!eregi($str, $file)) {
329
				$c_filelist[] = $file;
330
			}
331
		}
332
	}
333
	return($c_filelist);
334
}
335

    
336
?>
(4-4/4)