Project

General

Profile

1 1262 Luisehahne
<?php
2
/*
3
*
4
*                       About WebsiteBaker
5
*
6
* Website Baker is a PHP-based Content Management System (CMS)
7
* designed with one goal in mind: to enable its users to produce websites
8
* with ease.
9
*
10
*                       LICENSE INFORMATION
11
*
12
* WebsiteBaker is free software; you can redistribute it and/or
13
* modify it under the terms of the GNU General Public License
14
* as published by the Free Software Foundation; either version 2
15
* of the License, or (at your option) any later version.
16
*
17
* WebsiteBaker is distributed in the hope that it will be useful,
18
* but WITHOUT ANY WARRANTY; without even the implied warranty of
19
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20
* See the GNU General Public License for more details.
21
*
22
* You should have received a copy of the GNU General Public License
23
* along with this program; if not, write to the Free Software
24
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25
*
26
*                   WebsiteBaker Extra Information
27
*
28
*
29
*/
30
/**
31
 *
32
 * @category        frontend
33
 * @package         search
34 1268 Luisehahne
 * @author          WebsiteBaker Project
35 1262 Luisehahne
 * @copyright       2004-2009, Ryan Djurovich
36
 * @copyright       2009-2010, Website Baker Org. e.V.
37
 * @link			http://www.websitebaker2.org/
38
 * @license         http://www.gnu.org/licenses/gpl.html
39
 * @platform        WebsiteBaker 2.8.x
40
 * @requirements    PHP 4.3.4 and higher
41 1268 Luisehahne
 * @version         $Id$
42
 * @filesource		$HeadURL$
43 1262 Luisehahne
 * @lastmodified    $Date$
44
 *
45
 */
46
47
// make the url-string for highlighting
48
function make_url_searchstring($search_match, $search_url_array) {
49
	$link = "";
50
	if ($search_match != 'exact') {
51
		$str = implode(" ", $search_url_array);
52
		$link = "?searchresult=1&amp;sstring=".urlencode($str);
53
	} else {
54
		$str = str_replace(' ', '_', $search_url_array[0]);
55
		$link = "?searchresult=2&amp;sstring=".urlencode($str);
56
	}
57
	return $link;
58
}
59
60
// make date and time for "last modified by... on ..."-string
61
function get_page_modified($page_modified_when) {
62
	global $TEXT;
63
	if($page_modified_when > 0) {
64
		$date = gmdate(DATE_FORMAT, $page_modified_when+TIMEZONE);
65
		$time = gmdate(TIME_FORMAT, $page_modified_when+TIMEZONE);
66
	} else {
67
		$date = $TEXT['UNKNOWN'].' '.$TEXT['DATE'];
68
		$time = $TEXT['UNKNOWN'].' '.$TEXT['TIME'];
69
	}
70
	return array($date, $time);
71
}
72
73
// make username and displayname for "last modified by... on ..."-string
74
function get_page_modified_by($page_modified_by, $users) {
75
	global $TEXT;
76
	// check for existing user-id
77
	if(!isset($users[$page_modified_by]))
78
		$page_modified_by = 0;
79
80
	$username = $users[$page_modified_by]['username'];
81
	$displayname = $users[$page_modified_by]['display_name'];
82
	return array($username, $displayname);
83
}
84
85
// checks if _all_ searchwords matches
86
function is_all_matched($text, $search_words) {
87
	$all_matched = true;
88
	foreach ($search_words AS $word) {
89
		if(!preg_match('/'.$word.'/ui', $text)) {
90
			$all_matched = false;
91
			break;
92
		}
93
	}
94
	return $all_matched;
95
}
96
97
// checks if _any_ of the searchwords matches
98
function is_any_matched($text, $search_words) {
99
	$any_matched = false;
100
	$word = '('.implode('|', $search_words).')';
101
	if(preg_match('/'.$word.'/ui', $text)) {
102
		$any_matched = true;
103
	}
104
	return $any_matched;
105
}
106
107
// collects the matches from text in excerpt_array
108
function get_excerpts($text, $search_words, $max_excerpt_num) {
109
	$match_array = array();
110
	$excerpt_array = array();
111
	$word = '('.implode('|', $search_words).')';
112
113
	//Filter droplets from the page data
114
	preg_match_all('~\[\[(.*?)\]\]~', $text, $matches);
115
	foreach ($matches[1] as $match) {
116
		$text = str_replace('[['.$match.']]', '', $text);
117
	}
118
119
	// Build the regex-string
120
	if(strpos(strtoupper(PHP_OS), 'WIN')===0) { // windows -> see below
121
		$str1=".!?;";
122
		$str2=".!?;";
123
	} else { // linux & Co.
124
		// 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
125
		$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";
126
		// stop-sign: .!?; + DOUBLE EXCLAMATION MARK - INTERROBANG - EXCLAMATION QUESTION MARK - QUESTION EXCLAMATION MARK - DOUBLE QUESTION MARK - HALFWIDTH IDEOGRAPHIC FULL STOP - IDEOGRAPHIC FULL STOP - IDEOGRAPHIC COMMA
127
		$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";
128
	}
129
	$regex='/(?:^|\b|['.$str1.'])([^'.$str1.']{0,200}?'.$word.'[^'.$str2.']{0,200}(?:['.$str2.']|\b|$))/uis';
130
	if(version_compare(PHP_VERSION, '4.3.3', '>=') &&
131
	   strpos(strtoupper(PHP_OS), 'WIN')!==0
132
	) { // this may crash windows server, so skip if on windows
133
		// jump from match to match, get excerpt, stop if $max_excerpt_num is reached
134
		$last_end = 0; $offset = 0;
135
		while(preg_match('/'.$word.'/uis', $text, $match_array, PREG_OFFSET_CAPTURE, $last_end)) {
136
			$offset = ($match_array[0][1]-206 < $last_end)?$last_end:$match_array[0][1]-206;
137
			if(preg_match($regex, $text, $matches, PREG_OFFSET_CAPTURE, $offset)) {
138
				$last_end = $matches[1][1]+strlen($matches[1][0])-1;
139
				if(!preg_match('/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\./', $matches[1][0])) // skip excerpts with email-addresses
140
					$excerpt_array[] = trim($matches[1][0]);
141
				if(count($excerpt_array)>=$max_excerpt_num) {
142
					$excerpt_array = array_unique($excerpt_array);
143
					if(count($excerpt_array) >= $max_excerpt_num)
144
						break;
145
				}
146
			} else { // problem: preg_match failed - can't find a start- or stop-sign
147
				$last_end += 201; // jump forward and try again
148
			}
149
		}
150
	} else { // compatible, but may be very slow with large pages
151
		if(preg_match_all($regex, $text, $match_array)) {
152
			foreach($match_array[1] AS $string) {
153
				if(!preg_match('/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\./', $string))  // skip excerpts with email-addresses
154
					$excerpt_array[] = trim($string);
155
156
			}
157
		}
158
	}
159
	return $excerpt_array;
160
}
161
162
// makes excerpt_array a string ready to print out
163
function prepare_excerpts($excerpt_array, $search_words, $max_excerpt_num) {
164
	// excerpts: text before and after a single excerpt, html-tag for markup
165
	$EXCERPT_BEFORE =       '...&nbsp;';
166
	$EXCERPT_AFTER =        '&nbsp;...<br />';
167
	$EXCERPT_MARKUP_START = '<b>';
168
	$EXCERPT_MARKUP_END =   '</b>';
169
	// remove duplicate matches from $excerpt_array, if any.
170
	$excerpt_array = array_unique($excerpt_array);
171
	// use the first $max_excerpt_num excerpts only
172
	if(count($excerpt_array) > $max_excerpt_num) {
173
		$excerpt_array = array_slice($excerpt_array, 0, $max_excerpt_num);
174
	}
175
	// prepare search-string
176
	$string = "(".implode("|", $search_words).")";
177
	// we want markup on search-results page,
178
	// but we need some 'magic' to prevent <br />, <b>... from being highlighted
179
	$excerpt = '';
180
	foreach($excerpt_array as $str) {
181
		$excerpt .= '#,,#'.preg_replace("/($string)/iu","#,,,,#$1#,,,,,#",$str).'#,,,#';
182
	}
183
	$excerpt = str_replace(array('&','<','>','"','\'',"\xC2\xA0"), array('&amp;','&lt;','&gt;','&quot;','&#039;','&nbsp;'), $excerpt);
184
	$excerpt = str_replace(array('#,,,,#','#,,,,,#'), array($EXCERPT_MARKUP_START,$EXCERPT_MARKUP_END), $excerpt);
185
	$excerpt = str_replace(array('#,,#','#,,,#'), array($EXCERPT_BEFORE,$EXCERPT_AFTER), $excerpt);
186
	// prepare to write out
187
	if(DEFAULT_CHARSET != 'utf-8') {
188
		$excerpt = umlauts_to_entities($excerpt, 'UTF-8');
189
	}
190
	return $excerpt;
191
}
192
193
// work out what the link-anchor should be
194
function make_url_target($page_link_target, $text, $search_words) {
195
	// 1. e.g. $page_link_target=="&monthno=5&year=2007" - module-dependent target. Do nothing.
196
	// 2. $page_link_target=="#!wb_section_..." - the user wants the section-target, so do nothing.
197
	// 3. $page_link_target=="#wb_section_..." - try to find a better target, use the section-target as fallback.
198
	// 4. $page_link_target=="" - do nothing
199
	if(version_compare(PHP_VERSION, '4.3.3', ">=") && substr($page_link_target,0,12)=='#wb_section_') {
200
		$word = '('.implode('|', $search_words).')';
201
		preg_match('/'.$word.'/ui', $text, $match, PREG_OFFSET_CAPTURE);
202
		if($match && is_array($match[0])) {
203
			$x=$match[0][1]; // position of first match
204
			// is there an anchor nearby?
205
			if(preg_match_all('/<(?:[^>]+id|\s*a[^>]+name)\s*=\s*"(.*)"/iU', substr($text,0,$x), $match, PREG_OFFSET_CAPTURE)) {
206
				$anchor='';
207
				foreach($match[1] AS $array) {
208
					if($array[1] > $x) {
209
						break;
210
					}
211
					$anchor = $array[0];
212
				}
213
				if($anchor != '') {
214
					$page_link_target = '#'.$anchor;
215
				}
216
			}
217
		}
218
	}
219
	elseif(substr($page_link_target,0,13)=='#!wb_section_') {
220
		$page_link_target = '#'.substr($page_link_target, 2);
221
	}
222
223
	// since wb 2.7.1 the section-anchor is configurable - SEC_ANCHOR holds the anchor name
224
	if(substr($page_link_target,0,12)=='#wb_section_') {
225
		if(defined('SEC_ANCHOR') && SEC_ANCHOR!='') {
226
			$sec_id = substr($page_link_target, 12);
227
			$page_link_target = '#'.SEC_ANCHOR.$sec_id;
228
		} else { // section-anchors are disabled
229
			$page_link_target = '';
230
		}
231
	}
232
233
	return $page_link_target;
234
}
235
236
// wrapper for compatibility with old print_excerpt()
237
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="") {
238
	$mod_vars = array(
239
		'page_link' => $page_link,
240
		'page_link_target' => $page_link_target,
241
		'page_title' => $page_title,
242
		'page_description' => $page_description,
243
		'page_modified_when' => $page_modified_when,
244
		'page_modified_by' => $page_modified_by,
245
		'text' => $text,
246
		'max_excerpt_num' => $max_excerpt_num,
247
		'pic_link' => $pic_link
248
	);
249
	print_excerpt2($mod_vars, $func_vars);
250
}
251
252
/* These functions can be used in module-supplied search_funcs
253
 * -----------------------------------------------------------
254
 * print_excerpt2() - the main-function to use in all search_funcs
255
 * print_excerpt() - wrapper for compatibility-reason. Use print_excerpt2() instead.
256
 * list_files_dirs() - lists all files and dirs below a given directory
257
 * clear_filelist() - keeps only wanted or removes unwanted entries in file-list.
258
 */
259
260
// prints the excerpts for one section
261
function print_excerpt2($mod_vars, $func_vars) {
262
	extract($func_vars, EXTR_PREFIX_ALL, 'func');
263
	extract($mod_vars, EXTR_PREFIX_ALL, 'mod');
264
	global $TEXT;
265
	// check $mod_...vars
266
	if(!isset($mod_page_link))          $mod_page_link = $func_page_link;
267
	if(!isset($mod_page_link_target))   $mod_page_link_target = "";
268
	if(!isset($mod_page_title))         $mod_page_title = $func_page_title;
269
	if(!isset($mod_page_description))   $mod_page_description = $func_page_description;
270
	if(!isset($mod_page_modified_when)) $mod_page_modified_when = $func_page_modified_when;
271
	if(!isset($mod_page_modified_by))   $mod_page_modified_by = $func_page_modified_by;
272
	if(!isset($mod_text))               $mod_text = "";
273
	if(!isset($mod_max_excerpt_num))    $mod_max_excerpt_num = $func_default_max_excerpt;
274
	if(!isset($mod_pic_link))           $mod_pic_link = "";
275
	if(!isset($mod_no_highlight))       $mod_no_highlight = false;
276
	if(!isset($func_enable_flush))      $func_enable_flush = false; // set this in db: wb_search.cfg_enable_flush [READ THE DOC BEFORE]
277
	if(isset($mod_ext_charset)) $mod_ext_charset = strtolower($mod_ext_charset);
278
	else $mod_ext_charset = '';
279
280
	if($mod_text == "") // nothing to do
281
		{ return false; }
282
283
	if($mod_no_highlight) // no highlighting
284
		{ $mod_page_link_target = "&amp;nohighlight=1".$mod_page_link_target; }
285
	// clean the text:
286
	$mod_text = preg_replace('#<(!--.*--|style.*</style|script.*</script)>#iU', ' ', $mod_text);
287
	$mod_text = preg_replace('#<(br( /)?|dt|/dd|/?(h[1-6]|tr|table|p|li|ul|pre|code|div|hr))[^>]*>#i', '.', $mod_text);
288
	$mod_text = preg_replace('/(\v\s?|\s\s)+/', ' ', $mod_text);
289
	$mod_text = preg_replace('/\s\./', '.', $mod_text);
290
	if($mod_ext_charset!='') { // data from external database may have a different charset
291
		require_once(WB_PATH.'/framework/functions-utf8.php');
292
		switch($mod_ext_charset) {
293
		case 'latin1':
294
		case 'cp1252':
295
			$mod_text = charset_to_utf8($mod_text, 'CP1252');
296
			break;
297
		case 'cp1251':
298
			$mod_text = charset_to_utf8($mod_text, 'CP1251');
299
			break;
300
		case 'latin2':
301
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-2');
302
			break;
303
		case 'hebrew':
304
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-8');
305
			break;
306
		case 'greek':
307
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-7');
308
			break;
309
		case 'latin5':
310
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-9');
311
			break;
312
		case 'latin7':
313
			$mod_text = charset_to_utf8($mod_text, 'ISO-8859-13');
314
			break;
315
		case 'utf8':
316
		default:
317
			$mod_text = charset_to_utf8($mod_text, 'UTF-8');
318
		}
319
	} else {
320
	$mod_text = entities_to_umlauts($mod_text, 'UTF-8');
321
	}
322
	$anchor_text = $mod_text; // make an copy containing html-tags
323
	$mod_text = strip_tags($mod_text);
324
	$mod_text = str_replace(array('&gt;','&lt;','&amp;','&quot;','&#039;','&apos;','&nbsp;'), array('>','<','&','"','\'','\'',"\xC2\xA0"), $mod_text);
325
	$mod_text = '.'.trim($mod_text).'.';
326
	// Do a fast scan over $mod_text first. This will speedup things a lot.
327
	if($func_search_match == 'all') {
328
		if(!is_all_matched($mod_text, $func_search_words))
329
			return false;
330
	}
331
	elseif(!is_any_matched($mod_text, $func_search_words)) {
332
		return false;
333
	}
334
	// search for an better anchor - this have to be done before strip_tags() (may fail if search-string contains <, &, amp, gt, lt, ...)
335
	$anchor =  make_url_target($mod_page_link_target, $anchor_text, $func_search_words);
336
337
	// make the link from $mod_page_link, add anchor
338
	$link = "";
339
	$link = page_link($mod_page_link);
340
	if(strpos($mod_page_link, 'http:')===FALSE)
341
		$link .= make_url_searchstring($func_search_match, $func_search_url_array);
342
	$link .= $anchor;
343
344
	// now get the excerpt
345
	$excerpt = "";
346
	$excerpt_array = array();
347
	if($mod_max_excerpt_num > 0) {
348
		if(!$excerpt_array = get_excerpts($mod_text, $func_search_words, $mod_max_excerpt_num)) {
349
			return false;
350
		}
351
		$excerpt = prepare_excerpts($excerpt_array, $func_search_words, $mod_max_excerpt_num);
352
	}
353
354
	// handle thumbs - to deactivate this look in the module's search.php: $show_thumb (or maybe in the module's settings-page)
355
	if($mod_pic_link != "") {
356
		$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>';
357
	}
358
359
	// print-out the excerpt
360
	$vars = array();
361
	$values = array();
362
	list($date, $time) = get_page_modified($mod_page_modified_when);
363
	list($username, $displayname) = get_page_modified_by($mod_page_modified_by, $func_users);
364
	$vars = array('[LINK]', '[TITLE]', '[DESCRIPTION]', '[USERNAME]','[DISPLAY_NAME]','[DATE]','[TIME]','[TEXT_LAST_UPDATED_BY]','[TEXT_ON]','[EXCERPT]');
365
	$values = array(
366
		$link,
367
		$mod_page_title,
368
		$mod_page_description,
369
		$username,
370
		$displayname,
371
		$date,
372
		$time,
373
		$TEXT['LAST_UPDATED_BY'],
374
		$TEXT['ON'],
375
		$excerpt
376
	);
377
	echo str_replace($vars, $values, $func_results_loop_string);
378
	if($func_enable_flush) { // ATTN: this will bypass output-filters and may break template-layout or -filters
379
		ob_flush();flush();
380
	}
381
	return true;
382
}
383
384
// list all files and dirs in $dir (recursive), omits '.', '..', and hidden files/dirs
385
// returns an array of two arrays ($files[] and $dirs[]).
386
// usage: list($files,$dirs) = list_files_dirs($directory);
387
//        $depth: get subdirs (true/false)
388
function list_files_dirs($dir, $depth=true, $files=array(), $dirs=array()) {
389
	$dh=opendir($dir);
390
	while(($file = readdir($dh)) !== false) {
391
		if($file{0} == '.' || $file == '..') {
392
			continue;
393
		}
394
		if(is_dir($dir.'/'.$file)) {
395
			if($depth) {
396
				$dirs[] = $dir.'/'.$file;
397
				list($files, $dirs) = list_files_dirs($dir.'/'.$file, $depth, $files, $dirs);
398
			}
399
		} else {
400
			$files[] = $dir.'/'.$file;
401
		}
402
	}
403
	closedir($dh);
404
	natcasesort($files);
405
	natcasesort($dirs);
406
	return(array($files, $dirs));
407
}
408
409
// keeps only wanted entries in array $files. $str have to be an eregi()-compatible regex
410
function clear_filelist($files, $str, $keep=true) {
411
	// options: $keep = true  : remove all non-matching entries
412
	//          $keep = false : remove all matching entries
413
	$c_filelist = array();
414
	if($str == '')
415
		return $files;
416
	foreach($files as $file) {
417
		if($keep) {
418
			if(eregi($str, $file)) {
419
				$c_filelist[] = $file;
420
			}
421
		} else {
422
			if(!eregi($str, $file)) {
423
				$c_filelist[] = $file;
424
			}
425
		}
426
	}
427
	return($c_filelist);
428
}
429
430
?>