Project

General

Profile

« Previous | Next » 

Revision 1208

Added by Dietmar over 14 years ago

change searchstring mdcr.js, workout crypt emails in output_filter/filter-routines.php
comment out ob_end_flush line 259 in form/view.php

View differences:

branches/2.8.x/CHANGELOG
11 11
! = Update/Change
12 12

  
13 13
------------------------------------- 2.8.1 -------------------------------------
14
03-Dez-2009 Dietmar Woellbrink (Luisehahne)
15
!	change searchstring mdcr.js, workout crypt emails in output_filter/filter-routines.php
16
!	comment out ob_end_flush line 259 in form/view.php
14 17
02-Dez-2009 Dietmar Woellbrink (Luisehahne)
15 18
!	next step to validate backend themes
16 19
01-Dez-2009 Dietmar Woellbrink (Luisehahne)
branches/2.8.x/wb/modules/form/view.php
1
<?php
2

  
3
// $Id$
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
/*
27
The Website Baker Project would like to thank Rudolph Lartey <www.carbonect.com>
28
for his contributions to this module - adding extra field types
29
*/
30

  
31
// Must include code to stop this file being access directly
32
if(defined('WB_PATH') == false) { exit("Cannot access this file directly"); }
33

  
34
// check if frontend.css file needs to be included into the <body></body> of view.php
35
if((!function_exists('register_frontend_modfiles') || !defined('MOD_FRONTEND_CSS_REGISTERED')) &&  
36
	file_exists(WB_PATH .'/modules/form/frontend.css')) {
37
	echo '<style type="text/css">';
38
	include(WB_PATH .'/modules/form/frontend.css');
39
	echo "\n</style>\n";
40
} 
41

  
42
require_once(WB_PATH.'/include/captcha/captcha.php');
43

  
44
// obtain the settings of the output filter module
45
if(file_exists(WB_PATH.'/modules/output_filter/filter-routines.php')) {
46
	include_once(WB_PATH.'/modules/output_filter/filter-routines.php');
47
	$filter_settings = get_output_filter_settings();
48
} else {
49
	// no output filter used, define default settings
50
	$filter_settings['email_filter'] = 0;
51
}
52

  
53
// Function for generating an optionsfor a select field
54
if (!function_exists('make_option')) {
55
function make_option(&$n, $k, $values) {
56
	// start option group if it exists
57
	if (substr($n,0,2) == '[=') {
58
	 	$n = '<optgroup label="'.substr($n,2,strlen($n)).'">';
59
	} elseif ($n == ']') {
60
		$n = '</optgroup>';
61
	} else {
62
		if(in_array($n, $values)) {
63
			$n = '<option selected="selected" value="'.$n.'">'.$n.'</option>';
64
		} else {
65
			$n = '<option value="'.$n.'">'.$n.'</option>';
66
		}
67
	}
68
}
69
}
70
// Function for generating a checkbox
71
if (!function_exists('make_checkbox')) {
72
function make_checkbox(&$n, $idx, $params) {
73
	$field_id = $params[0][0];
74
	$seperator = $params[0][1];
75
	$label_id = 'wb_'.str_replace(" ", "_", $n);
76
	if(in_array($n, $params[1])) {
77
		$n = '<input class="field_checkbox" type="checkbox" id="'.$label_id.'" name="field'.$field_id.'['.$idx.']" value="'.$n.'" checked="checked" />'.'<label for="'.$label_id.'" class="checkbox_label">'.$n.'</lable>'.$seperator;
78
	} else {
79
		$n = '<input class="field_checkbox" type="checkbox" id="'.$label_id.'" name="field'.$field_id.'['.$idx.']" value="'.$n.'" />'.'<label for="'.$label_id.'" class="checkbox_label">'.$n.'</label>'.$seperator;
80
	}	
81
}
82
}
83
// Function for generating a radio button
84
if (!function_exists('make_radio')) {
85
function make_radio(&$n, $idx, $params) {
86
	$field_id = $params[0];
87
	$group = $params[1];
88
	$seperator = $params[2];
89
	$label_id = 'wb_'.str_replace(" ", "_", $n);
90
	if($n == $params[3]) { 
91
		$n = '<input class="field_radio" type="radio" id="'.$label_id.'" name="field'.$field_id.'" value="'.$n.'" checked="checked" />'.'<label for="'.$label_id.'" class="radio_label">'.$n.'</label>'.$seperator;
92
	} else {
93
		$n = '<input class="field_radio" type="radio" id="'.$label_id.'" name="field'.$field_id.'" value="'.$n.'" />'.'<label for="'.$label_id.'" class="radio_label">'.$n.'</label>'.$seperator;
94
	}
95
}
96
}
97

  
98
if (!function_exists("new_submission_id") ) {
99
	function new_submission_id() {
100
		$submission_id = '';
101
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";
102
		srand((double)microtime()*1000000);
103
		$i = 0;
104
		while ($i <= 7) {
105
			$num = rand() % 33;
106
			$tmp = substr($salt, $num, 1);
107
			$submission_id = $submission_id . $tmp;
108
			$i++;
109
		}
110
		return $submission_id;
111
	}
112
}
113

  
114
// Work-out if the form has been submitted or not
115
if($_POST == array()) {
116

  
117
// Set new submission ID in session
118
$_SESSION['form_submission_id'] = new_submission_id();
119

  
120
// Get settings
121
$query_settings = $database->query("SELECT header,field_loop,footer,use_captcha FROM ".TABLE_PREFIX."mod_form_settings WHERE section_id = '$section_id'");
122
if($query_settings->numRows() > 0) {
123
	$fetch_settings = $query_settings->fetchRow();
124
	$header = str_replace('{WB_URL}',WB_URL,$fetch_settings['header']);
125
	$field_loop = $fetch_settings['field_loop'];
126
	$footer = str_replace('{WB_URL}',WB_URL,$fetch_settings['footer']);
127
	$use_captcha = $fetch_settings['use_captcha'];
128
	$form_name = 'form';
129
	$use_xhtml_strict = false;
130
} else {
131
	$header = '';
132
	$field_loop = '';
133
	$footer = '';
134
	$form_name = 'form';
135
	$use_xhtml_strict = false;
136
}
137

  
138
?>
139
<form <?php echo ( ( (strlen($form_name) > 0) AND (false == $use_xhtml_strict) ) ? "name=\"".$form_name."\"" : ""); ?> action="<?php echo htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])); ?>#wb_<?PHP echo $section_id;?>" method="post">
140
<div>
141
<input type="hidden" name="submission_id" value="<?php echo $_SESSION['form_submission_id']; ?>" />
142
</div>
143
<?php
144
if(ENABLED_ASP) { // first add some honeypot-fields
145
?>
146
<div>
147
<input type="hidden" name="submitted_when" value="<?php $t=time(); echo $t; $_SESSION['submitted_when']=$t; ?>" />
148
</div>
149
<p class="nixhier">
150
email address:
151
<label for="email">Leave this field email-address blank:</label>
152
<input id="email" name="email" size="56" value="" /><br />
153
Homepage:
154
<label for="homepage">Leave this field homepage blank:</label>
155
<input id="homepage" name="homepage" size="55" value="" /><br />
156
URL:
157
<label for="url">Leave this field url blank:</label>
158
<input id="url" name="url" size="61" value="" /><br />
159
Comment:
160
<label for="comment">Leave this field comment blank:</label>
161
<textarea id="comment" name="comment" cols="50" rows="10"></textarea><br />
162
</p>
163

  
164
<?php }
165

  
166
// Print header
167
echo $header;
168

  
169
// Get list of fields
170
$query_fields = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id' ORDER BY position ASC");
171

  
172
if($query_fields->numRows() > 0) {
173
	while($field = $query_fields->fetchRow()) {
174
		// Set field values
175
		$field_id = $field['field_id'];
176
		$value = $field['value'];
177
		// Print field_loop after replacing vars with values
178
		$vars = array('{TITLE}', '{REQUIRED}');
179
		if (($field['type'] == "radio") || ($field['type'] == "checkbox")) {
180
			$field_title = $field['title'];
181
		} else {
182
			$field_title = '<label for="field'.$field_id.'">'.$field['title'].'</label>';
183
		}
184
		$values = array($field_title);
185
		if ($field['required'] == 1) {
186
			$values[] = '<span class="required">*</span>';
187
		} else {
188
			$values[] = '';
189
		}
190
		if($field['type'] == 'textfield') {
191
			$vars[] = '{FIELD}';
192
			$values[] = '<input type="text" name="field'.$field_id.'" id="field'.$field_id.'" maxlength="'.$field['extra'].'" value="'.(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:$value).'" class="textfield" />';
193
		} elseif($field['type'] == 'textarea') {
194
			$vars[] = '{FIELD}';
195
			$values[] = '<textarea name="field'.$field_id.'" id="field'.$field_id.'" class="textarea" cols="25" rows="5">'.(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:$value).'</textarea>';
196
		} elseif($field['type'] == 'select') {
197
			$vars[] = '{FIELD}';
198
			$options = explode(',', $value);
199
			array_walk($options, 'make_option', (isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:array()));
200
			$field['extra'] = explode(',',$field['extra']);
201
			$values[] = '<select name="field'.$field_id.'[]" id="field'.$field_id.'" size="'.$field['extra'][0].'" '.$field['extra'][1].' class="select">'.implode($options).'</select>';		
202
		} elseif($field['type'] == 'heading') {
203
			$vars[] = '{FIELD}';
204
			$str = '<input type="hidden" name="field'.$field_id.'" id="field'.$field_id.'" value="===['.$field['title'].']===" />';
205
			$values[] = ( true == $use_xhtml_strict) ? "<div>".$str."</div>" : $str;
206
			$tmp_field_loop = $field_loop;		// temporarily modify the field loop template
207
			$field_loop = $field['extra'];
208
		} elseif($field['type'] == 'checkbox') {
209
			$vars[] = '{FIELD}';
210
			$options = explode(',', $value);
211
			array_walk($options, 'make_checkbox', array(array($field_id,$field['extra']),(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:array())));
212
			$options[count($options)-1]=substr($options[count($options)-1],0,strlen($options[count($options)-1])-strlen($field['extra']));
213
			$values[] = implode($options);
214
		} elseif($field['type'] == 'radio') {
215
			$vars[] = '{FIELD}';
216
			$options = explode(',', $value);
217
			array_walk($options, 'make_radio', array($field_id,$field['title'],$field['extra'], (isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:'')));
218
			$options[count($options)-1]=substr($options[count($options)-1],0,strlen($options[count($options)-1])-strlen($field['extra']));
219
			$values[] = implode($options);
220
		} elseif($field['type'] == 'email') {
221
			$vars[] = '{FIELD}';
222
			$values[] = '<input type="text" name="field'.$field_id.'" id="field'.$field_id.'" value="'.(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:'').'" maxlength="'.$field['extra'].'" class="email" />';
223
		}
224
		if(isset($_SESSION['field'.$field_id])) unset($_SESSION['field'.$field_id]);
225
		if($field['type'] != '') {
226
			echo str_replace($vars, $values, $field_loop);
227
		}
228
		if (isset($tmp_field_loop)) $field_loop = $tmp_field_loop;
229
	}
230
}
231

  
232
// Captcha
233
if($use_captcha) { ?>
234
	<tr>
235
	<td class="field_title"><?php echo $TEXT['VERIFICATION']; ?>:</td>
236
	<td><?php call_captcha(); ?></td>
237
	</tr>
238
	<?php
239
}
240

  
241
// Print footer
242
echo $footer;
243

  
244
/**
245
	NOTE: comment out the line ob_end_flush() if you indicate problems (e.g. when using ob_start in the index.php of your template)
246
	With ob_end_flush(): output filter will be disabled for this page (and all sections embedded on this page)
247
	Without ob_end_flush(): emails are rewritten (e.g. name@domain.com --> name(at)domain(dot)com) if output filter is enabled
248
	All replacements made by the Output-Filter module will be reverted before the email is send out
249
*/
250
if($filter_settings['email_filter'] && !($filter_settings['at_replacement']=='@' && $filter_settings['dot_replacement']=='.')) { 
251
	ob_end_flush();
252
}
253

  
254
// Add form end code
255
?>
256
</form>
257
<?php
258

  
259
} else {
260
	
261
	// Check that submission ID matches
262
	if(isset($_SESSION['form_submission_id']) AND isset($_POST['submission_id']) AND $_SESSION['form_submission_id'] == $_POST['submission_id']) {
263
		
264
		// Set new submission ID in session
265
		$_SESSION['form_submission_id'] = new_submission_id();
266
		
267
		if(ENABLED_ASP && ( // form faked? Check the honeypot-fields.
268
			(!isset($_POST['submitted_when']) OR !isset($_SESSION['submitted_when'])) OR 
269
			($_POST['submitted_when'] != $_SESSION['submitted_when']) OR
270
			(!isset($_POST['email']) OR $_POST['email']) OR
271
			(!isset($_POST['homepage']) OR $_POST['homepage']) OR
272
			(!isset($_POST['comment']) OR $_POST['comment']) OR
273
			(!isset($_POST['url']) OR $_POST['url'])
274
		)) {
275
			exit(header("Location: ".WB_URL.PAGES_DIRECTORY.""));
276
		}
277

  
278
		// Submit form data
279
		// First start message settings
280
		$query_settings = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_settings WHERE section_id = '$section_id'");
281
		if($query_settings->numRows() > 0) {
282
			$fetch_settings = $query_settings->fetchRow();
283
			$email_to = $fetch_settings['email_to'];
284
			$email_from = $fetch_settings['email_from'];
285
			if(substr($email_from, 0, 5) == 'field') {
286
				// Set the email from field to what the user entered in the specified field
287
				$email_from = htmlspecialchars($wb->add_slashes($_POST[$email_from]));
288
			}
289
			$email_fromname = $fetch_settings['email_fromname'];
290
			$email_subject = $fetch_settings['email_subject'];
291
			$success_page = $fetch_settings['success_page'];
292
			$success_email_to = $fetch_settings['success_email_to'];
293
			if(substr($success_email_to, 0, 5) == 'field') {
294
				// Set the success_email to field to what the user entered in the specified field
295
				$success_email_to = htmlspecialchars($wb->add_slashes($_POST[$success_email_to]));
296
			}
297
			$success_email_from = $fetch_settings['success_email_from'];
298
			$success_email_fromname = $fetch_settings['success_email_fromname'];
299
			$success_email_text = $fetch_settings['success_email_text'];
300
			$success_email_subject = $fetch_settings['success_email_subject'];		
301
			$max_submissions = $fetch_settings['max_submissions'];
302
			$stored_submissions = $fetch_settings['stored_submissions'];
303
			$use_captcha = $fetch_settings['use_captcha'];
304
		} else {
305
			exit($TEXT['UNDER_CONSTRUCTION']);
306
		}
307
		$email_body = '';
308
		
309
		// Create blank "required" array
310
		$required = array();
311
		
312
		// Captcha
313
		if($use_captcha) {
314
			if(isset($_POST['captcha']) AND $_POST['captcha'] != ''){
315
				// Check for a mismatch
316
				if(!isset($_POST['captcha']) OR !isset($_SESSION['captcha']) OR $_POST['captcha'] != $_SESSION['captcha']) {
317
					$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
318
				}
319
			} else {
320
				$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
321
			}
322
		}
323
		if(isset($_SESSION['captcha'])) { unset($_SESSION['captcha']); }
324

  
325
		// Loop through fields and add to message body
326
		// Get list of fields
327
		$query_fields = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id' ORDER BY position ASC");
328
		if($query_fields->numRows() > 0) {
329
			while($field = $query_fields->fetchRow()) {
330
				// Add to message body
331
				if($field['type'] != '') {
332
					if(!empty($_POST['field'.$field['field_id']])) {
333
						if (is_array($_POST['field'.$field['field_id']])) {
334
							$_SESSION['field'.$field['field_id']] = $_POST['field'.$field['field_id']];
335
						} else {
336
							$_SESSION['field'.$field['field_id']] = htmlspecialchars($_POST['field'.$field['field_id']]);
337
						}
338
						// if the output filter is active, we need to revert (dot) to . and (at) to @ (using current filter settings)
339
						// otherwise the entered mail will not be accepted and the recipient would see (dot), (at) etc.
340
						if ($filter_settings['email_filter']) {
341
							$field_value = $_POST['field'.$field['field_id']];
342
							$field_value = str_replace($filter_settings['at_replacement'], '@', $field_value);
343
							$field_value = str_replace($filter_settings['dot_replacement'], '.', $field_value);
344
							$_POST['field'.$field['field_id']] = $field_value;
345
						}
346
						if($field['type'] == 'email' AND $admin->validate_email($_POST['field'.$field['field_id']]) == false) {
347
							$email_error = $MESSAGE['USERS']['INVALID_EMAIL'];
348
						}
349
						if($field['type'] == 'heading') {
350
							$email_body .= $_POST['field'.$field['field_id']]."\n\n";
351
						} elseif (!is_array($_POST['field'.$field['field_id']])) {
352
							$email_body .= $field['title'].': '.$_POST['field'.$field['field_id']]."\n\n";
353
						} else {
354
							$email_body .= $field['title'].": \n";
355
							foreach ($_POST['field'.$field['field_id']] as $k=>$v) {
356
								$email_body .= $v."\n";
357
							}
358
							$email_body .= "\n";
359
						}
360
					} elseif($field['required'] == 1) {
361
						$required[] = $field['title'];
362
					}
363
				}
364
			}
365
		}
366
	
367
		// Check if the user forgot to enter values into all the required fields
368
		if($required != array()) {
369
			if(!isset($MESSAGE['MOD_FORM']['REQUIRED_FIELDS'])) {
370
				echo 'You must enter details for the following fields';
371
			} else {
372
				echo $MESSAGE['MOD_FORM']['REQUIRED_FIELDS'];
373
			}
374
			echo ':<br /><ul>';
375
			foreach($required AS $field_title) {
376
				echo '<li>'.$field_title;
377
			}
378
			if(isset($email_error)) {
379
				echo '<li>'.$email_error.'</li>';
380
			}
381
			if(isset($captcha_error)) {
382
				echo '<li>'.$captcha_error.'</li>';
383
			}
384
			echo '</ul><a href="'.htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])).'">'.$TEXT['BACK'].'</a>';
385
		} else {
386
			if(isset($email_error)) {
387
				echo '<br /><ul>';
388
				echo '<li>'.$email_error.'</li>';
389
				echo '</ul><a href="'.htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])).'">'.$TEXT['BACK'].'</a>';
390
			} elseif(isset($captcha_error)) {
391
				echo '<br /><ul>';
392
				echo '<li>'.$captcha_error.'</li>';
393
				echo '</ul><a href="'.htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])).'">'.$TEXT['BACK'].'</a>';
394
			} else {
395
				// Check how many times form has been submitted in last hour
396
				$last_hour = time()-3600;
397
				$query_submissions = $database->query("SELECT submission_id FROM ".TABLE_PREFIX."mod_form_submissions WHERE submitted_when >= '$last_hour'");
398
				if($query_submissions->numRows() > $max_submissions) {
399
					// Too many submissions so far this hour
400
					echo $MESSAGE['MOD_FORM']['EXCESS_SUBMISSIONS'];
401
					$success = false;
402
				} else {
403
					/**	
404
					 *	Adding the IP to the body and try to send the email
405
					 */
406
					$email_body .= "\n\nIP: ".$_SERVER['REMOTE_ADDR'];
407
					
408
					if($email_to != '') {
409
						if($email_from != '') {
410
							if($wb->mail($email_from,$email_to,$email_subject,$email_body,$email_fromname)) {
411
								$success = true;
412
							}
413
						} else {
414
							if($wb->mail('',$email_to,$email_subject,$email_body,$email_fromname)) { 
415
								$success = true; 
416
							}
417
						}
418
					}				
419
					if($success_email_to != '') {
420
						if($success_email_from != '') {
421
							if($wb->mail($success_email_from,$success_email_to,$success_email_subject,$success_email_text,$success_email_fromname)) {
422
								$success = true;
423
							}
424
						} else {
425
							if($wb->mail('',$success_email_to,$success_email_subject,$success_email_text,$success_email_fromname)) {
426
								$success = true;
427
							}
428
						}
429
					}				
430
			
431
					// Write submission to database
432
					if(isset($admin) AND $admin->is_authenticated() AND $admin->get_user_id() > 0) {
433
						$submitted_by = $admin->get_user_id();
434
					} else {
435
						$submitted_by = 0;
436
					}
437
					$email_body = $wb->add_slashes($email_body);
438
					$database->query("INSERT INTO ".TABLE_PREFIX."mod_form_submissions (page_id,section_id,submitted_when,submitted_by,body) VALUES ('".PAGE_ID."','$section_id','".time()."','$submitted_by','$email_body')");
439
					// Make sure submissions table isn't too full
440
					$query_submissions = $database->query("SELECT submission_id FROM ".TABLE_PREFIX."mod_form_submissions ORDER BY submitted_when");
441
					$num_submissions = $query_submissions->numRows();
442
					if($num_submissions > $stored_submissions) {
443
						// Remove excess submission
444
						$num_to_remove = $num_submissions-$stored_submissions;
445
						while($submission = $query_submissions->fetchRow()) {
446
							if($num_to_remove > 0) {
447
								$submission_id = $submission['submission_id'];
448
								$database->query("DELETE FROM ".TABLE_PREFIX."mod_form_submissions WHERE submission_id = '$submission_id'");
449
								$num_to_remove = $num_to_remove-1;
450
							}
451
						}
452
					}
453
					if(!$database->is_error()) {
454
						$success = true;
455
					}
456
				}
457
			}	
458
		}
459
	}
460
	
461
	// Now check if the email was sent successfully
462
	if(isset($success) AND $success == true) {
463
	   if ($success_page=='none') {
464
			echo str_replace("\n","<br />",$success_email_text);
465
  		} else {
466
			$query_menu = $database->query("SELECT link,target FROM ".TABLE_PREFIX."pages WHERE `page_id` = '$success_page'");
467
			if($query_menu->numRows() > 0) {
468
  	        	$fetch_settings = $query_menu->fetchRow();
469
			   $link = WB_URL.PAGES_DIRECTORY.$fetch_settings['link'].PAGE_EXTENSION;
470
			   echo "<script type='text/javascript'>location.href='".$link."';</script>";
471
			}    
472
		}
473
		// clearing session on success
474
		$query_fields = $database->query("SELECT field_id FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id'");
475
		while($field = $query_fields->fetchRow()) {
476
			$field_id = $field[0];
477
			if(isset($_SESSION['field'.$field_id])) unset($_SESSION['field'.$field_id]);
478
		}
479
	} else {
480
		if(isset($success) AND $success == false) {
481
			echo $TEXT['ERROR'];
482
		}
483
	}
484
}
485

  
1
<?php
2

  
3
// $Id$
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
 * @category   frontend
25
 * @package    outputfilter
26
 * @author(s)  Dietmar W?llbrink <Luisehahne>, Dietrich Roland Pehlke <Aldus>
27
 * @platform   WB 2.8.0
28
 * @require    PHP 5.2.x
29
 * @license    http://www.gnu.org/licenses/gpl.html
30
 * @link       http://project.websitebaker2.org/browser/branches/2.8.x/wb/modules/form/view.php
31
 * @changeset   2009/12/03 comment out ob_end_flush line 259
32
*/
33

  
34
/*
35
The Website Baker Project would like to thank Rudolph Lartey <www.carbonect.com>
36
for his contributions to this module - adding extra field types
37
*/
38

  
39
// Must include code to stop this file being access directly
40
if(defined('WB_PATH') == false) { exit("Cannot access this file directly"); }
41

  
42
// check if frontend.css file needs to be included into the <body></body> of view.php
43
if((!function_exists('register_frontend_modfiles') || !defined('MOD_FRONTEND_CSS_REGISTERED')) &&
44
	file_exists(WB_PATH .'/modules/form/frontend.css')) {
45
	echo '<style type="text/css">';
46
	include(WB_PATH .'/modules/form/frontend.css');
47
	echo "\n</style>\n";
48
} 
49

  
50
require_once(WB_PATH.'/include/captcha/captcha.php');
51

  
52
// obtain the settings of the output filter module
53
if(file_exists(WB_PATH.'/modules/output_filter/filter-routines.php')) {
54
	include_once(WB_PATH.'/modules/output_filter/filter-routines.php');
55
	$filter_settings = get_output_filter_settings();
56
} else {
57
	// no output filter used, define default settings
58
	$filter_settings['email_filter'] = 0;
59
}
60

  
61
// Function for generating an optionsfor a select field
62
if (!function_exists('make_option')) {
63
function make_option(&$n, $k, $values) {
64
	// start option group if it exists
65
	if (substr($n,0,2) == '[=') {
66
	 	$n = '<optgroup label="'.substr($n,2,strlen($n)).'">';
67
	} elseif ($n == ']') {
68
		$n = '</optgroup>';
69
	} else {
70
		if(in_array($n, $values)) {
71
			$n = '<option selected="selected" value="'.$n.'">'.$n.'</option>';
72
		} else {
73
			$n = '<option value="'.$n.'">'.$n.'</option>';
74
		}
75
	}
76
}
77
}
78
// Function for generating a checkbox
79
if (!function_exists('make_checkbox')) {
80
function make_checkbox(&$n, $idx, $params) {
81
	$field_id = $params[0][0];
82
	$seperator = $params[0][1];
83
	$label_id = 'wb_'.str_replace(" ", "_", $n);
84
	if(in_array($n, $params[1])) {
85
		$n = '<input class="field_checkbox" type="checkbox" id="'.$label_id.'" name="field'.$field_id.'['.$idx.']" value="'.$n.'" checked="checked" />'.'<label for="'.$label_id.'" class="checkbox_label">'.$n.'</lable>'.$seperator;
86
	} else {
87
		$n = '<input class="field_checkbox" type="checkbox" id="'.$label_id.'" name="field'.$field_id.'['.$idx.']" value="'.$n.'" />'.'<label for="'.$label_id.'" class="checkbox_label">'.$n.'</label>'.$seperator;
88
	}	
89
}
90
}
91
// Function for generating a radio button
92
if (!function_exists('make_radio')) {
93
function make_radio(&$n, $idx, $params) {
94
	$field_id = $params[0];
95
	$group = $params[1];
96
	$seperator = $params[2];
97
	$label_id = 'wb_'.str_replace(" ", "_", $n);
98
	if($n == $params[3]) { 
99
		$n = '<input class="field_radio" type="radio" id="'.$label_id.'" name="field'.$field_id.'" value="'.$n.'" checked="checked" />'.'<label for="'.$label_id.'" class="radio_label">'.$n.'</label>'.$seperator;
100
	} else {
101
		$n = '<input class="field_radio" type="radio" id="'.$label_id.'" name="field'.$field_id.'" value="'.$n.'" />'.'<label for="'.$label_id.'" class="radio_label">'.$n.'</label>'.$seperator;
102
	}
103
}
104
}
105

  
106
if (!function_exists("new_submission_id") ) {
107
	function new_submission_id() {
108
		$submission_id = '';
109
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";
110
		srand((double)microtime()*1000000);
111
		$i = 0;
112
		while ($i <= 7) {
113
			$num = rand() % 33;
114
			$tmp = substr($salt, $num, 1);
115
			$submission_id = $submission_id . $tmp;
116
			$i++;
117
		}
118
		return $submission_id;
119
	}
120
}
121

  
122
// Work-out if the form has been submitted or not
123
if($_POST == array()) {
124

  
125
// Set new submission ID in session
126
$_SESSION['form_submission_id'] = new_submission_id();
127

  
128
// Get settings
129
$query_settings = $database->query("SELECT header,field_loop,footer,use_captcha FROM ".TABLE_PREFIX."mod_form_settings WHERE section_id = '$section_id'");
130
if($query_settings->numRows() > 0) {
131
	$fetch_settings = $query_settings->fetchRow();
132
	$header = str_replace('{WB_URL}',WB_URL,$fetch_settings['header']);
133
	$field_loop = $fetch_settings['field_loop'];
134
	$footer = str_replace('{WB_URL}',WB_URL,$fetch_settings['footer']);
135
	$use_captcha = $fetch_settings['use_captcha'];
136
	$form_name = 'form';
137
	$use_xhtml_strict = false;
138
} else {
139
	$header = '';
140
	$field_loop = '';
141
	$footer = '';
142
	$form_name = 'form';
143
	$use_xhtml_strict = false;
144
}
145

  
146
?>
147
<form <?php echo ( ( (strlen($form_name) > 0) AND (false == $use_xhtml_strict) ) ? "name=\"".$form_name."\"" : ""); ?> action="<?php echo htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])); ?>#wb_<?PHP echo $section_id;?>" method="post">
148
<div>
149
<input type="hidden" name="submission_id" value="<?php echo $_SESSION['form_submission_id']; ?>" />
150
</div>
151
<?php
152
if(ENABLED_ASP) { // first add some honeypot-fields
153
?>
154
<div>
155
<input type="hidden" name="submitted_when" value="<?php $t=time(); echo $t; $_SESSION['submitted_when']=$t; ?>" />
156
</div>
157
<p class="nixhier">
158
email address:
159
<label for="email">Leave this field email-address blank:</label>
160
<input id="email" name="email" size="56" value="" /><br />
161
Homepage:
162
<label for="homepage">Leave this field homepage blank:</label>
163
<input id="homepage" name="homepage" size="55" value="" /><br />
164
URL:
165
<label for="url">Leave this field url blank:</label>
166
<input id="url" name="url" size="61" value="" /><br />
167
Comment:
168
<label for="comment">Leave this field comment blank:</label>
169
<textarea id="comment" name="comment" cols="50" rows="10"></textarea><br />
170
</p>
171

  
172
<?php }
173

  
174
// Print header
175
echo $header;
176

  
177
// Get list of fields
178
$query_fields = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id' ORDER BY position ASC");
179

  
180
if($query_fields->numRows() > 0) {
181
	while($field = $query_fields->fetchRow()) {
182
		// Set field values
183
		$field_id = $field['field_id'];
184
		$value = $field['value'];
185
		// Print field_loop after replacing vars with values
186
		$vars = array('{TITLE}', '{REQUIRED}');
187
		if (($field['type'] == "radio") || ($field['type'] == "checkbox")) {
188
			$field_title = $field['title'];
189
		} else {
190
			$field_title = '<label for="field'.$field_id.'">'.$field['title'].'</label>';
191
		}
192
		$values = array($field_title);
193
		if ($field['required'] == 1) {
194
			$values[] = '<span class="required">*</span>';
195
		} else {
196
			$values[] = '';
197
		}
198
		if($field['type'] == 'textfield') {
199
			$vars[] = '{FIELD}';
200
			$values[] = '<input type="text" name="field'.$field_id.'" id="field'.$field_id.'" maxlength="'.$field['extra'].'" value="'.(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:$value).'" class="textfield" />';
201
		} elseif($field['type'] == 'textarea') {
202
			$vars[] = '{FIELD}';
203
			$values[] = '<textarea name="field'.$field_id.'" id="field'.$field_id.'" class="textarea" cols="25" rows="5">'.(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:$value).'</textarea>';
204
		} elseif($field['type'] == 'select') {
205
			$vars[] = '{FIELD}';
206
			$options = explode(',', $value);
207
			array_walk($options, 'make_option', (isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:array()));
208
			$field['extra'] = explode(',',$field['extra']);
209
			$values[] = '<select name="field'.$field_id.'[]" id="field'.$field_id.'" size="'.$field['extra'][0].'" '.$field['extra'][1].' class="select">'.implode($options).'</select>';		
210
		} elseif($field['type'] == 'heading') {
211
			$vars[] = '{FIELD}';
212
			$str = '<input type="hidden" name="field'.$field_id.'" id="field'.$field_id.'" value="===['.$field['title'].']===" />';
213
			$values[] = ( true == $use_xhtml_strict) ? "<div>".$str."</div>" : $str;
214
			$tmp_field_loop = $field_loop;		// temporarily modify the field loop template
215
			$field_loop = $field['extra'];
216
		} elseif($field['type'] == 'checkbox') {
217
			$vars[] = '{FIELD}';
218
			$options = explode(',', $value);
219
			array_walk($options, 'make_checkbox', array(array($field_id,$field['extra']),(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:array())));
220
			$options[count($options)-1]=substr($options[count($options)-1],0,strlen($options[count($options)-1])-strlen($field['extra']));
221
			$values[] = implode($options);
222
		} elseif($field['type'] == 'radio') {
223
			$vars[] = '{FIELD}';
224
			$options = explode(',', $value);
225
			array_walk($options, 'make_radio', array($field_id,$field['title'],$field['extra'], (isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:'')));
226
			$options[count($options)-1]=substr($options[count($options)-1],0,strlen($options[count($options)-1])-strlen($field['extra']));
227
			$values[] = implode($options);
228
		} elseif($field['type'] == 'email') {
229
			$vars[] = '{FIELD}';
230
			$values[] = '<input type="text" name="field'.$field_id.'" id="field'.$field_id.'" value="'.(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:'').'" maxlength="'.$field['extra'].'" class="email" />';
231
		}
232
		if(isset($_SESSION['field'.$field_id])) unset($_SESSION['field'.$field_id]);
233
		if($field['type'] != '') {
234
			echo str_replace($vars, $values, $field_loop);
235
		}
236
		if (isset($tmp_field_loop)) $field_loop = $tmp_field_loop;
237
	}
238
}
239

  
240
// Captcha
241
if($use_captcha) { ?>
242
	<tr>
243
	<td class="field_title"><?php echo $TEXT['VERIFICATION']; ?>:</td>
244
	<td><?php call_captcha(); ?></td>
245
	</tr>
246
	<?php
247
}
248

  
249
// Print footer
250
echo $footer;
251

  
252
/**
253
	NOTE: comment out the line ob_end_flush() if you indicate problems (e.g. when using ob_start in the index.php of your template)
254
	With ob_end_flush(): output filter will be disabled for this page (and all sections embedded on this page)
255
	Without ob_end_flush(): emails are rewritten (e.g. name@domain.com --> name(at)domain(dot)com) if output filter is enabled
256
	All replacements made by the Output-Filter module will be reverted before the email is send out
257
*/
258
if($filter_settings['email_filter'] && !($filter_settings['at_replacement']=='@' && $filter_settings['dot_replacement']=='.')) {
259
  /* 	ob_end_flush(); */
260
}
261

  
262
// Add form end code
263
?>
264
</form>
265
<?php
266

  
267
} else {
268

  
269
	// Check that submission ID matches
270
	if(isset($_SESSION['form_submission_id']) AND isset($_POST['submission_id']) AND $_SESSION['form_submission_id'] == $_POST['submission_id']) {
271
		
272
		// Set new submission ID in session
273
		$_SESSION['form_submission_id'] = new_submission_id();
274
		
275
		if(ENABLED_ASP && ( // form faked? Check the honeypot-fields.
276
			(!isset($_POST['submitted_when']) OR !isset($_SESSION['submitted_when'])) OR 
277
			($_POST['submitted_when'] != $_SESSION['submitted_when']) OR
278
			(!isset($_POST['email']) OR $_POST['email']) OR
279
			(!isset($_POST['homepage']) OR $_POST['homepage']) OR
280
			(!isset($_POST['comment']) OR $_POST['comment']) OR
281
			(!isset($_POST['url']) OR $_POST['url'])
282
		)) {
283
			exit(header("Location: ".WB_URL.PAGES_DIRECTORY.""));
284
		}
285

  
286
		// Submit form data
287
		// First start message settings
288
		$query_settings = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_settings WHERE section_id = '$section_id'");
289
		if($query_settings->numRows() > 0) {
290
			$fetch_settings = $query_settings->fetchRow();
291
			$email_to = $fetch_settings['email_to'];
292
			$email_from = $fetch_settings['email_from'];
293
			if(substr($email_from, 0, 5) == 'field') {
294
				// Set the email from field to what the user entered in the specified field
295
				$email_from = htmlspecialchars($wb->add_slashes($_POST[$email_from]));
296
			}
297
			$email_fromname = $fetch_settings['email_fromname'];
298
			$email_subject = $fetch_settings['email_subject'];
299
			$success_page = $fetch_settings['success_page'];
300
			$success_email_to = $fetch_settings['success_email_to'];
301
			if(substr($success_email_to, 0, 5) == 'field') {
302
				// Set the success_email to field to what the user entered in the specified field
303
				$success_email_to = htmlspecialchars($wb->add_slashes($_POST[$success_email_to]));
304
			}
305
			$success_email_from = $fetch_settings['success_email_from'];
306
			$success_email_fromname = $fetch_settings['success_email_fromname'];
307
			$success_email_text = $fetch_settings['success_email_text'];
308
			$success_email_subject = $fetch_settings['success_email_subject'];		
309
			$max_submissions = $fetch_settings['max_submissions'];
310
			$stored_submissions = $fetch_settings['stored_submissions'];
311
			$use_captcha = $fetch_settings['use_captcha'];
312
		} else {
313
			exit($TEXT['UNDER_CONSTRUCTION']);
314
		}
315
		$email_body = '';
316
		
317
		// Create blank "required" array
318
		$required = array();
319
		
320
		// Captcha
321
		if($use_captcha) {
322
			if(isset($_POST['captcha']) AND $_POST['captcha'] != ''){
323
				// Check for a mismatch
324
				if(!isset($_POST['captcha']) OR !isset($_SESSION['captcha']) OR $_POST['captcha'] != $_SESSION['captcha']) {
325
					$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
326
				}
327
			} else {
328
				$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
329
			}
330
		}
331
		if(isset($_SESSION['captcha'])) { unset($_SESSION['captcha']); }
332

  
333
		// Loop through fields and add to message body
334
		// Get list of fields
335
		$query_fields = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id' ORDER BY position ASC");
336
		if($query_fields->numRows() > 0) {
337
			while($field = $query_fields->fetchRow()) {
338
				// Add to message body
339
				if($field['type'] != '') {
340
					if(!empty($_POST['field'.$field['field_id']])) {
341
						if (is_array($_POST['field'.$field['field_id']])) {
342
							$_SESSION['field'.$field['field_id']] = $_POST['field'.$field['field_id']];
343
						} else {
344
							$_SESSION['field'.$field['field_id']] = htmlspecialchars($_POST['field'.$field['field_id']]);
345
						}
346
						// if the output filter is active, we need to revert (dot) to . and (at) to @ (using current filter settings)
347
						// otherwise the entered mail will not be accepted and the recipient would see (dot), (at) etc.
348
						if ($filter_settings['email_filter']) {
349
							$field_value = $_POST['field'.$field['field_id']];
350
							$field_value = str_replace($filter_settings['at_replacement'], '@', $field_value);
351
							$field_value = str_replace($filter_settings['dot_replacement'], '.', $field_value);
352
							$_POST['field'.$field['field_id']] = $field_value;
353
						}
354
						if($field['type'] == 'email' AND $admin->validate_email($_POST['field'.$field['field_id']]) == false) {
355
							$email_error = $MESSAGE['USERS']['INVALID_EMAIL'];
356
						}
357
						if($field['type'] == 'heading') {
358
							$email_body .= $_POST['field'.$field['field_id']]."\n\n";
359
						} elseif (!is_array($_POST['field'.$field['field_id']])) {
360
							$email_body .= $field['title'].': '.$_POST['field'.$field['field_id']]."\n\n";
361
						} else {
362
							$email_body .= $field['title'].": \n";
363
							foreach ($_POST['field'.$field['field_id']] as $k=>$v) {
364
								$email_body .= $v."\n";
365
							}
366
							$email_body .= "\n";
367
						}
368
					} elseif($field['required'] == 1) {
369
						$required[] = $field['title'];
370
					}
371
				}
372
			}
373
		}
374
	
375
		// Check if the user forgot to enter values into all the required fields
376
		if($required != array()) {
377
			if(!isset($MESSAGE['MOD_FORM']['REQUIRED_FIELDS'])) {
378
				echo 'You must enter details for the following fields';
379
			} else {
380
				echo $MESSAGE['MOD_FORM']['REQUIRED_FIELDS'];
381
			}
382
			echo ':<br /><ul>';
383
			foreach($required AS $field_title) {
384
				echo '<li>'.$field_title;
385
			}
386
			if(isset($email_error)) {
387
				echo '<li>'.$email_error.'</li>';
388
			}
389
			if(isset($captcha_error)) {
390
				echo '<li>'.$captcha_error.'</li>';
391
			}
392
			echo '</ul><a href="'.htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])).'">'.$TEXT['BACK'].'</a>';
393
		} else {
394
			if(isset($email_error)) {
395
				echo '<br /><ul>';
396
				echo '<li>'.$email_error.'</li>';
397
				echo '</ul><a href="'.htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])).'">'.$TEXT['BACK'].'</a>';
398
			} elseif(isset($captcha_error)) {
399
				echo '<br /><ul>';
400
				echo '<li>'.$captcha_error.'</li>';
401
				echo '</ul><a href="'.htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])).'">'.$TEXT['BACK'].'</a>';
402
			} else {
403
				// Check how many times form has been submitted in last hour
404
				$last_hour = time()-3600;
405
				$query_submissions = $database->query("SELECT submission_id FROM ".TABLE_PREFIX."mod_form_submissions WHERE submitted_when >= '$last_hour'");
406
				if($query_submissions->numRows() > $max_submissions) {
407
					// Too many submissions so far this hour
408
					echo $MESSAGE['MOD_FORM']['EXCESS_SUBMISSIONS'];
409
					$success = false;
410
				} else {
411
					/**	
412
					 *	Adding the IP to the body and try to send the email
413
					 */
414
					$email_body .= "\n\nIP: ".$_SERVER['REMOTE_ADDR'];
415
					
416
					if($email_to != '') {
417
						if($email_from != '') {
418
							if($wb->mail($email_from,$email_to,$email_subject,$email_body,$email_fromname)) {
419
								$success = true;
420
							}
421
						} else {
422
							if($wb->mail('',$email_to,$email_subject,$email_body,$email_fromname)) { 
423
								$success = true; 
424
							}
425
						}
426
					}				
427
					if($success_email_to != '') {
428
						if($success_email_from != '') {
429
							if($wb->mail($success_email_from,$success_email_to,$success_email_subject,$success_email_text,$success_email_fromname)) {
430
								$success = true;
431
							}
432
						} else {
433
							if($wb->mail('',$success_email_to,$success_email_subject,$success_email_text,$success_email_fromname)) {
434
								$success = true;
435
							}
436
						}
437
					}				
438
			
439
					// Write submission to database
440
					if(isset($admin) AND $admin->is_authenticated() AND $admin->get_user_id() > 0) {
441
						$submitted_by = $admin->get_user_id();
442
					} else {
443
						$submitted_by = 0;
444
					}
445
					$email_body = $wb->add_slashes($email_body);
446
					$database->query("INSERT INTO ".TABLE_PREFIX."mod_form_submissions (page_id,section_id,submitted_when,submitted_by,body) VALUES ('".PAGE_ID."','$section_id','".time()."','$submitted_by','$email_body')");
447
					// Make sure submissions table isn't too full
448
					$query_submissions = $database->query("SELECT submission_id FROM ".TABLE_PREFIX."mod_form_submissions ORDER BY submitted_when");
449
					$num_submissions = $query_submissions->numRows();
450
					if($num_submissions > $stored_submissions) {
451
						// Remove excess submission
452
						$num_to_remove = $num_submissions-$stored_submissions;
453
						while($submission = $query_submissions->fetchRow()) {
454
							if($num_to_remove > 0) {
455
								$submission_id = $submission['submission_id'];
456
								$database->query("DELETE FROM ".TABLE_PREFIX."mod_form_submissions WHERE submission_id = '$submission_id'");
457
								$num_to_remove = $num_to_remove-1;
458
							}
459
						}
460
					}
461
					if(!$database->is_error()) {
462
						$success = true;
463
					}
464
				}
465
			}	
466
		}
467
	}
468
	
469
	// Now check if the email was sent successfully
470
	if(isset($success) AND $success == true) {
471
	   if ($success_page=='none') {
472
			echo str_replace("\n","<br />",$success_email_text);
473
  		} else {
474
			$query_menu = $database->query("SELECT link,target FROM ".TABLE_PREFIX."pages WHERE `page_id` = '$success_page'");
475
			if($query_menu->numRows() > 0) {
476
  	        	$fetch_settings = $query_menu->fetchRow();
477
			   $link = WB_URL.PAGES_DIRECTORY.$fetch_settings['link'].PAGE_EXTENSION;
478
			   echo "<script type='text/javascript'>location.href='".$link."';</script>";
479
			}    
480
		}
481
		// clearing session on success
482
		$query_fields = $database->query("SELECT field_id FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id'");
483
		while($field = $query_fields->fetchRow()) {
484
			$field_id = $field[0];
485
			if(isset($_SESSION['field'.$field_id])) unset($_SESSION['field'.$field_id]);
486
		}
487
	} else {
488
		if(isset($success) AND $success == false) {
489
			echo $TEXT['ERROR'];
490
		}
491
	}
492
}
493

  
486 494
?>
branches/2.8.x/wb/modules/output_filter/filter-routines.php
1
<?php
2

  
3
// $Id$
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
// prevent this file from being accessed directly
27
if(!defined('WB_PATH')) die(header('Location: ../index.php'));
28

  
29
// function to read the current filter settings
30
if (!function_exists('get_output_filter_settings')) {
31
	function get_output_filter_settings() {
32
		global $database, $admin;
33
		// connect to database and read out filter settings
34
		$result = $database->query("SELECT * FROM " .TABLE_PREFIX ."mod_output_filter");
35
		if($result && $result->numRows() > 0) {
36
			// get all data
37
			$data = $result->fetchRow();
38
			$filter_settings['email_filter'] = $admin->strip_slashes($data['email_filter']);
39
			$filter_settings['mailto_filter'] = $admin->strip_slashes($data['mailto_filter']);
40
			$filter_settings['at_replacement'] = $admin->strip_slashes($data['at_replacement']);
41
			$filter_settings['dot_replacement'] = $admin->strip_slashes($data['dot_replacement']);
42
		} else {
43
			// something went wrong, use default values
44
			$filter_settings['email_filter'] = '0';
45
			$filter_settings['mailto_filter'] = '0';
46
			$filter_settings['at_replacement'] = '(at)';
47
			$filter_settings['dot_replacement'] = '(dot)';
48
		}
49
		
50
		// return array with filter settings
51
		return $filter_settings;
52
	}
53
}
54

  
55
// function to filter the output before displaying it on the frontend
56
if (!function_exists('filter_frontend_output')) {
57
	function filter_frontend_output($content) {
58
		// get output filter settings from database
59
		$filter_settings = get_output_filter_settings();
60
		
61
		// work out the defined output filter mode: possible output filter modes: [0], 1, 2, 3, 6, 7
62
		// 2^0 * (0.. disable, 1.. enable) filtering of mail addresses in text
63
		// 2^1 * (0.. disable, 1.. enable) filtering of mail addresses in mailto links
64
		// 2^2 * (0.. disable, 1.. enable) Javascript mailto encryption (only if mailto filtering enabled)
65

  
66
		// only filter output if we are supposed to
67
		if($filter_settings['email_filter'] != '1' && $filter_settings['mailto_filter'] != '1'){
68
			// nothing to do ...
69
			return $content;
70
		}
71

  
72
		// check if non mailto mail addresses needs to be filtered
73
		$output_filter_mode = ($filter_settings['email_filter'] == '1') ? 1 : 0;		// 0|1
74
		
75
		// check if mailto mail addresses needs to be filtered
76
		if($filter_settings['mailto_filter'] == '1') {
77
			$output_filter_mode = $output_filter_mode + 2;								// 0|2
78
						
79
			// check if Javascript mailto encryption is enabled (call register_frontend_functions in the template)
80
			$search = '<script type="text/javascript" src="' .WB_URL .'/modules/output_filter/js/mdcr.js"></script>';
81
			$search_droplet = '<script type="text/javascript" src="' .WB_URL .'/modules/droplets/js/mdcr.js"></script>';
82
			if(strpos($content, $search) !== false || strpos($content, $search_droplet) !== false) { 
83
				$output_filter_mode = $output_filter_mode + 4;							// 0|4
84
			}
85
		}
86
		
87
		// define some constants so we do not call the database in the callback function again
88
		define('OUTPUT_FILTER_MODE', (int) $output_filter_mode);
89
		define('OUTPUT_FILTER_AT_REPLACEMENT', $filter_settings['at_replacement']);
90
		define('OUTPUT_FILTER_DOT_REPLACEMENT', $filter_settings['dot_replacement']);
91
		
92
		// first search part to find all mailto email addresses
93
		$pattern = '#(<a[^<]*href\s*?=\s*?"\s*?mailto\s*?:\s*?)([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})([^"]*?)"([^>]*>)(.*?)</a>';
94
		// second part to find all non mailto email addresses
95
		$pattern .= '|(value\s*=\s*"|\')??\b([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})\b#i';
96
		/*
97
		Sub 1:\b(<a.[^<]*href\s*?=\s*?"\s*?mailto\s*?:\s*?)			-->	"<a id="yyy" class="xxx" href = " mailto :" ignoring white spaces
98
		Sub 2:([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})			-->	the email address in the mailto: part of the mail link
99
		Sub 3:([^"]*?)"												--> possible ?Subject&cc... stuff attached to the mail address
100
		Sub 4:([^>]*>)												--> all class or id statements after the mailto but before closing ..>
101
		Sub 5:(.*?)</a>\b											--> the mailto text; all characters between >xxxxx</a>
102
		Sub 6:|\b([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})\b		--> email addresses which may appear in the text (require word boundaries)
103
		*/
104
			
105
		// find all email addresses embedded in the content and filter them using a callback function
106
		$content = preg_replace_callback($pattern, 'filter_mail_addresses', $content);
107
		return $content;
108
	}
109
}		
110

  
111

  
112
// function to filter mail addresses embedded in text or mailto links before outputing them on the frontend
113
if (!function_exists('filter_mail_addresses')) {
114
	function filter_mail_addresses($match) { 
115
		
116
		// check if required output filter mode is defined
117
		if(!(defined('OUTPUT_FILTER_MODE') && defined('OUTPUT_FILTER_MODE') && defined('OUTPUT_FILTER_MODE'))) {
118
			return $match[0];
119
		}
120
		
121
		$search = array('@', '.');
122
		$replace = array(OUTPUT_FILTER_AT_REPLACEMENT ,OUTPUT_FILTER_DOT_REPLACEMENT);
123
		
124
		// check if the match contains the expected number of subpatterns (6|8)
125
		if(count($match) == 8) {
126
			/**
127
				OUTPUT FILTER FOR EMAIL ADDRESSES EMBEDDED IN TEXT
128
			**/
129
			
130
			// 1.. text mails only, 3.. text mails + mailto (no JS), 7 text mails + mailto (JS)
131
			if(!in_array(OUTPUT_FILTER_MODE, array(1,3,7))) return $match[0];
132

  
133
			// do not filter mail addresses included in input tags (<input ... value = "test@mail)
134
			if (strpos($match[6], 'value') !== false) return $match[0];
135
			
136
			// filtering of non mailto email addresses enabled
137
			return str_replace($search, $replace, $match[0]);
138
				
139
		} elseif(count($match) == 6) {
140
			/**
141
				OUTPUT FILTER FOR EMAIL ADDRESSES EMBEDDED IN MAILTO LINKS
142
			**/
143

  
144
			// 2.. mailto only (no JS), 3.. text mails + mailto (no JS), 6.. mailto only (JS), 7.. all filters active
145
			if(!in_array(OUTPUT_FILTER_MODE, array(2,3,6,7))) return $match[0];
146
			
147
			// check if last part of the a href link: >xxxx</a> contains a email address we need to filter
148
			$pattern = '#[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}#i';
149
			if(preg_match_all($pattern, $match[5], $matches)) {
150
				foreach($matches as $submatch) {
151
					foreach($submatch as $value) {
152
						// replace all . and all @ in email address parts by (dot) and (at) strings
153
						$match[5] = str_replace($value, str_replace($search, $replace, $value), $match[5]);
154
					}
155
				}
156
			}
157

  
158
			// check if Javascript encryption routine is enabled
159
			if(in_array(OUTPUT_FILTER_MODE, array(6,7))) {
160
				/** USE JAVASCRIPT ENCRYPTION FOR MAILTO LINKS **/
161
				
162
				// extract possible class and id attribute from ahref link
163
				preg_match('/class\s*?=\s*?("|\')(.*?)\1/ix', $match[0], $class_attr);
164
				$class_attr = empty($class_attr) ? '' : 'class="' . $class_attr[2] . '" ';
165
				preg_match('/id\s*?=\s*?("|\')(.*?)\1/ix', $match[0], $id_attr);
166
				$id_attr = empty($id_attr) ? '' : 'id="' . $id_attr[2] . '" ';
167
				
168
				// preprocess mailto link parts for further usage
169
				$search = array('@', '.', '_', '-'); $replace = array('F', 'Z', 'X', 'K');
170
				$email_address = str_replace($search, $replace, strtolower($match[2]));
171
				$email_subject = rawurlencode(html_entity_decode($match[3]));
172
				
173
				// create a random encryption key for the Caesar cipher
174
				mt_srand((double)microtime()*1000000);	// (PHP < 4.2.0)
175
				$shift = mt_rand(1, 25);
176
				
177
				// encrypt the email using an adapted Caesar cipher
178
		  		$encrypted_email = "";
179
				for($i = strlen($email_address) -1; $i > -1; $i--) {
180
					if(preg_match('#[FZXK0-9]#', $email_address[$i], $characters)) {
181
						$encrypted_email .= $email_address[$i];
182
					} else {	
183
						$encrypted_email .= chr((ord($email_address[$i]) -97 + $shift) % 26 + 97);
184
					}
185
				}
186
				$encrypted_email .= chr($shift + 97);
187

  
188
				// build the encrypted Javascript mailto link
189
				$mailto_link  = "<a {$class_attr}{$id_attr}href=\"javascript:mdcr('$encrypted_email','$email_subject')\">" .$match[5] ."</a>";
190
				
191
				return $mailto_link;	
192

  
193
			} else {
194
				/** DO NOT USE JAVASCRIPT ENCRYPTION FOR MAILTO LINKS **/
195

  
196
				// as minimum protection, replace replace @ in the mailto part by (at)
197
				// dots are not transformed as this would transform my.name@domain.com into: my(dot)name(at)domain(dot)com
198
				
199
				// rebuild the mailto link from the subpatterns (at the missing characters " and </a>")
200
				return $match[1] .str_replace('@', OUTPUT_FILTER_AT_REPLACEMENT, $match[2]) .$match[3] .'"' .$match[4] .$match[5] .'</a>';
201
				// if you want to protect both, @ and dots, comment out the line above and remove the comment from the line below
202
				// return $match[1] .str_replace($search, $replace, $match[2]) .$match[3] .'"' .$match[4] .$match[5] .'</a>';
203
			}
204
		
205
		}
206
		
207
		// number of subpatterns do not match the requirements ... do nothing
208
		return $match[0];
209
	}		
210
}
211

  
212
?>
1
<?php
2

  
3
// $Id$
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
 * @category   frontend
24
 * @package    outputfilter
25
 * @author(s)  Dietmar W?llbrink <Luisehahne>, Dietrich Roland Pehlke <Aldus>
26
 * @platform   WB 2.8.0
27
 * @require    PHP 5.2.x
28
 * @license    http://www.gnu.org/licenses/gpl.html
29
 * @link       http://project.websitebaker2.org/browser/branches/2.8.x/wb/modules/output_filter/filter-routines.php
30
 * @changeset   2009/12/03 change searchstring mdcr.js, workout crypt emails
31

  
32
*/
33

  
34
// prevent this file from being accessed directly
35
if(!defined('WB_PATH')) die(header('Location: ../index.php'));
36

  
37
// function to read the current filter settings
38
if (!function_exists('get_output_filter_settings')) {
39
	function get_output_filter_settings() {
40
		global $database, $admin;
41
		// connect to database and read out filter settings
42
		$result = $database->query("SELECT * FROM " .TABLE_PREFIX ."mod_output_filter");
43
		if($result && $result->numRows() > 0) {
44
			// get all data
45
			$data = $result->fetchRow();
46
			$filter_settings['email_filter'] = $admin->strip_slashes($data['email_filter']);
47
			$filter_settings['mailto_filter'] = $admin->strip_slashes($data['mailto_filter']);
48
			$filter_settings['at_replacement'] = $admin->strip_slashes($data['at_replacement']);
49
			$filter_settings['dot_replacement'] = $admin->strip_slashes($data['dot_replacement']);
50
		} else {
51
			// something went wrong, use default values
52
			$filter_settings['email_filter'] = '0';
53
			$filter_settings['mailto_filter'] = '0';
54
			$filter_settings['at_replacement'] = '(at)';
55
			$filter_settings['dot_replacement'] = '(dot)';
56
		}
57
		
58
		// return array with filter settings
59
		return $filter_settings;
60
	}
61
}
62

  
63
// function to filter the output before displaying it on the frontend
64
if (!function_exists('filter_frontend_output')) {
65
	function filter_frontend_output($content) {
66
		// get output filter settings from database
67
		$filter_settings = get_output_filter_settings();
68
		
69
		// work out the defined output filter mode: possible output filter modes: [0], 1, 2, 3, 6, 7
70
		// 2^0 * (0.. disable, 1.. enable) filtering of mail addresses in text
71
		// 2^1 * (0.. disable, 1.. enable) filtering of mail addresses in mailto links
72
		// 2^2 * (0.. disable, 1.. enable) Javascript mailto encryption (only if mailto filtering enabled)
73

  
74
		// only filter output if we are supposed to
75
		if($filter_settings['email_filter'] != '1' && $filter_settings['mailto_filter'] != '1'){
76
			// nothing to do ...
77
			return $content;
78
		}
79

  
80
		// check if non mailto mail addresses needs to be filtered
81
		$output_filter_mode = ($filter_settings['email_filter'] == '1') ? 1 : 0;		// 0|1
82

  
83
		// check if mailto mail addresses needs to be filtered
84
		if($filter_settings['mailto_filter'] == '1') {
85
			$output_filter_mode = $output_filter_mode + 2;								// 0|2
86
						
87
			// check if Javascript mailto encryption is enabled (call register_frontend_functions in the template)
88
			$search = '<script src="' .WB_URL .'/modules/output_filter/js/mdcr.js" type="text/javascript"></script>';
89
			$search_droplet = '<script src="' .WB_URL .'/modules/droplets/js/mdcr.js" type="text/javascript"></script>';
90
			if(strpos($content, $search) !== false || strpos($content, $search_droplet) !== false) { 
91
				$output_filter_mode = $output_filter_mode + 4;							// 0|4
92
			}
93
		}
94
		
95
		// define some constants so we do not call the database in the callback function again
96
		define('OUTPUT_FILTER_MODE', (int) $output_filter_mode);
97
		define('OUTPUT_FILTER_AT_REPLACEMENT', $filter_settings['at_replacement']);
98
		define('OUTPUT_FILTER_DOT_REPLACEMENT', $filter_settings['dot_replacement']);
99
		
100
		// first search part to find all mailto email addresses
101
		$pattern = '#(<a[^<]*href\s*?=\s*?"\s*?mailto\s*?:\s*?)([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})([^"]*?)"([^>]*>)(.*?)</a>';
102
		// second part to find all non mailto email addresses
103
		$pattern .= '|(value\s*=\s*"|\')??\b([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})\b#i';
104
		/*
105
		Sub 1:\b(<a.[^<]*href\s*?=\s*?"\s*?mailto\s*?:\s*?)			-->	"<a id="yyy" class="xxx" href = " mailto :" ignoring white spaces
106
		Sub 2:([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})			-->	the email address in the mailto: part of the mail link
107
		Sub 3:([^"]*?)"												--> possible ?Subject&cc... stuff attached to the mail address
108
		Sub 4:([^>]*>)												--> all class or id statements after the mailto but before closing ..>
109
		Sub 5:(.*?)</a>\b											--> the mailto text; all characters between >xxxxx</a>
110
		Sub 6:|\b([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})\b		--> email addresses which may appear in the text (require word boundaries)
111
		*/
112
			
113
		// find all email addresses embedded in the content and filter them using a callback function
114
		$content = preg_replace_callback($pattern, 'filter_mail_addresses', $content);
115
		return $content;
116
	}
117
}		
118

  
119

  
120
// function to filter mail addresses embedded in text or mailto links before outputing them on the frontend
121
if (!function_exists('filter_mail_addresses')) {
122
	function filter_mail_addresses($match) { 
123
		
124
		// check if required output filter mode is defined
125
		if(!(defined('OUTPUT_FILTER_MODE') && defined('OUTPUT_FILTER_MODE') && defined('OUTPUT_FILTER_MODE'))) {
126
			return $match[0];
127
		}
128
		
129
		$search = array('@', '.');
130
		$replace = array(OUTPUT_FILTER_AT_REPLACEMENT ,OUTPUT_FILTER_DOT_REPLACEMENT);
131
		
132
		// check if the match contains the expected number of subpatterns (6|8)
133
		if(count($match) == 8) {
134
			/**
135
				OUTPUT FILTER FOR EMAIL ADDRESSES EMBEDDED IN TEXT
136
			**/
137
			
138
			// 1.. text mails only, 3.. text mails + mailto (no JS), 7 text mails + mailto (JS)
139
			if(!in_array(OUTPUT_FILTER_MODE, array(1,3,7))) return $match[0];
140

  
141
			// do not filter mail addresses included in input tags (<input ... value = "test@mail)
142
			if (strpos($match[6], 'value') !== false) return $match[0];
143
			
144
			// filtering of non mailto email addresses enabled
145
			return str_replace($search, $replace, $match[0]);
146
				
147
		} elseif(count($match) == 6) {
148
			/**
149
				OUTPUT FILTER FOR EMAIL ADDRESSES EMBEDDED IN MAILTO LINKS
150
			**/
151

  
152
			// 2.. mailto only (no JS), 3.. text mails + mailto (no JS), 6.. mailto only (JS), 7.. all filters active
153
			if(!in_array(OUTPUT_FILTER_MODE, array(2,3,6,7))) return $match[0];
154
			
155
			// check if last part of the a href link: >xxxx</a> contains a email address we need to filter
156
			$pattern = '#[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}#i';
157
			if(preg_match_all($pattern, $match[5], $matches)) {
158
				foreach($matches as $submatch) {
159
					foreach($submatch as $value) {
160
						// replace all . and all @ in email address parts by (dot) and (at) strings
161
						$match[5] = str_replace($value, str_replace($search, $replace, $value), $match[5]);
162
					}
163
				}
164
			}
165

  
166
			// check if Javascript encryption routine is enabled
167
			if(in_array(OUTPUT_FILTER_MODE, array(6,7))) {
168
				/** USE JAVASCRIPT ENCRYPTION FOR MAILTO LINKS **/
169
				
170
				// extract possible class and id attribute from ahref link
171
				preg_match('/class\s*?=\s*?("|\')(.*?)\1/ix', $match[0], $class_attr);
172
				$class_attr = empty($class_attr) ? '' : 'class="' . $class_attr[2] . '" ';
173
				preg_match('/id\s*?=\s*?("|\')(.*?)\1/ix', $match[0], $id_attr);
174
				$id_attr = empty($id_attr) ? '' : 'id="' . $id_attr[2] . '" ';
175
				
176
				// preprocess mailto link parts for further usage
177
				$search = array('@', '.', '_', '-'); $replace = array('F', 'Z', 'X', 'K');
178
				$email_address = str_replace($search, $replace, strtolower($match[2]));
179
				$email_subject = rawurlencode(html_entity_decode($match[3]));
180
				
181
				// create a random encryption key for the Caesar cipher
182
				mt_srand((double)microtime()*1000000);	// (PHP < 4.2.0)
183
				$shift = mt_rand(1, 25);
184
				
185
				// encrypt the email using an adapted Caesar cipher
186
		  		$encrypted_email = "";
187
				for($i = strlen($email_address) -1; $i > -1; $i--) {
188
					if(preg_match('#[FZXK0-9]#', $email_address[$i], $characters)) {
189
						$encrypted_email .= $email_address[$i];
190
					} else {	
191
						$encrypted_email .= chr((ord($email_address[$i]) -97 + $shift) % 26 + 97);
192
					}
193
				}
194
				$encrypted_email .= chr($shift + 97);
195

  
196
				// build the encrypted Javascript mailto link
197
				$mailto_link  = "<a {$class_attr}{$id_attr}href=\"javascript:mdcr('$encrypted_email','$email_subject')\">" .$match[5] ."</a>";
198
				
199
				return $mailto_link;	
200

  
201
			} else {
202
				/** DO NOT USE JAVASCRIPT ENCRYPTION FOR MAILTO LINKS **/
203

  
204
				// as minimum protection, replace replace @ in the mailto part by (at)
205
				// dots are not transformed as this would transform my.name@domain.com into: my(dot)name(at)domain(dot)com
206
				
207
				// rebuild the mailto link from the subpatterns (at the missing characters " and </a>")
208
				return $match[1] .str_replace('@', OUTPUT_FILTER_AT_REPLACEMENT, $match[2]) .$match[3] .'"' .$match[4] .$match[5] .'</a>';
209
				// if you want to protect both, @ and dots, comment out the line above and remove the comment from the line below
210
				// return $match[1] .str_replace($search, $replace, $match[2]) .$match[3] .'"' .$match[4] .$match[5] .'</a>';
211
			}
212
		
213
		}
214
		
215
		// number of subpatterns do not match the requirements ... do nothing
216
		return $match[0];
217
	}		
218
}
219

  
220
?>

Also available in: Unified diff