Project

General

Profile

1
<?php
2

    
3
// $Id: view.php 734 2008-03-02 12:53:33Z 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
/*
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
// Function for generating an optionsfor a select field
45
if (!function_exists('make_option')) {
46
function make_option(&$n, $k, $values) {
47
	// start option group if it exists
48
	if (substr($n,0,2) == '[=') {
49
	 	$n = '<optgroup label="'.substr($n,2,strlen($n)).'">';
50
	} elseif ($n == ']') {
51
		$n = '</optgroup>';
52
	} else {
53
		if(in_array($n, $values))
54
			$n = '<option selected="selected" value="'.$n.'">'.$n.'</option>';
55
		else
56
			$n = '<option value="'.$n.'">'.$n.'</option>';
57
	}
58
}
59
}
60
// Function for generating a checkbox
61
if (!function_exists('make_checkbox')) {
62
function make_checkbox(&$n, $idx, $params) {
63
	$field_id = $params[0][0];
64
	$seperator = $params[0][1];
65
	//$n = '<input class="field_checkbox" type="checkbox" id="'.$n.'" name="field'.$field_id.'" value="'.$n.'">'.'<font class="checkbox_label" onclick="javascript: document.getElementById(\''.$n.'\').checked = !document.getElementById(\''.$n.'\').checked;">'.$n.'</font>'.$seperator;
66
	if(in_array($n, $params[1]))
67
		$n = '<input class="field_checkbox" type="checkbox" id="'.$n.'" name="field'.$field_id.'['.$idx.']" value="'.$n.'" checked="checked">'.'<font class="checkbox_label" onclick="javascript: document.getElementById(\''.$n.'\').checked = !document.getElementById(\''.$n.'\').checked;">'.$n.'</font>'.$seperator;
68
	else
69
		$n = '<input class="field_checkbox" type="checkbox" id="'.$n.'" name="field'.$field_id.'['.$idx.']" value="'.$n.'">'.'<font class="checkbox_label" onclick="javascript: document.getElementById(\''.$n.'\').checked = !document.getElementById(\''.$n.'\').checked;">'.$n.'</font>'.$seperator;
70
}
71
}
72
// Function for generating a radio button
73
if (!function_exists('make_radio')) {
74
function make_radio(&$n, $idx, $params) {
75
	$field_id = $params[0];
76
	$group = $params[1];
77
	$seperator = $params[2];
78
	if($n == $params[3])
79
		$n = '<input class="field_radio" type="radio" id="'.$n.'" name="field'.$field_id.'" value="'.$n.'" checked="checked">'.'<font class="radio_label" onclick="javascript: document.getElementById(\''.$n.'\').checked = true;">'.$n.'</font>'.$seperator;
80
	else
81
		$n = '<input class="field_radio" type="radio" id="'.$n.'" name="field'.$field_id.'" value="'.$n.'">'.'<font class="radio_label" onclick="javascript: document.getElementById(\''.$n.'\').checked = true;">'.$n.'</font>'.$seperator;
82
}
83
}
84
// Generate temp submission id
85
function new_submission_id() {
86
	$submission_id = '';
87
	$salt = "abchefghjkmnpqrstuvwxyz0123456789";
88
	srand((double)microtime()*1000000);
89
	$i = 0;
90
	while ($i <= 7) {
91
		$num = rand() % 33;
92
		$tmp = substr($salt, $num, 1);
93
		$submission_id = $submission_id . $tmp;
94
		$i++;
95
	}
96
	return $submission_id;
97
}
98

    
99
// Work-out if the form has been submitted or not
100
if($_POST == array()) {
101

    
102
// Set new submission ID in session
103
$_SESSION['form_submission_id'] = new_submission_id();
104

    
105
// Get settings
106
$query_settings = $database->query("SELECT header,field_loop,footer,use_captcha FROM ".TABLE_PREFIX."mod_form_settings WHERE section_id = '$section_id'");
107
if($query_settings->numRows() > 0) {
108
	$fetch_settings = $query_settings->fetchRow();
109
	$header = str_replace('{WB_URL}',WB_URL,$fetch_settings['header']);
110
	$field_loop = $fetch_settings['field_loop'];
111
	$footer = str_replace('{WB_URL}',WB_URL,$fetch_settings['footer']);
112
	$use_captcha = $fetch_settings['use_captcha'];
113
} else {
114
	$header = '';
115
	$field_loop = '';
116
	$footer = '';
117
}
118

    
119
$java_fields = '';
120
$java_titles = '';
121
$java_tween = ''; // I know kinda stupid, anyone better idea?
122
$java_mailcheck = '';
123

    
124
// Add form starter code
125
?>
126
<form name="form" onsubmit="return formCheck(this);" action="<?php echo htmlspecialchars(strip_tags($_SERVER['PHP_SELF'])); ?>" method="post">
127
<input type="hidden" name="submission_id" value="<?php echo $_SESSION['form_submission_id']; ?>" />
128
<?php
129

    
130
// Print header
131
echo $header;
132

    
133
if(ENABLED_ASP) { // first add some honeypot-fields
134
?>
135
<input type="hidden" name="submitted_when" value="<?php $t=time(); echo $t; $_SESSION['submitted_when']=$t; ?>" />
136
<p style="display:none;">
137
email address:
138
<label for="email">Your e-mail address is not relevant Leave this field blank:</label>
139
<input id="email" name="email" size="56" value="" /><br />
140
Homepage:
141
<label for="homepage">Do not enter a homepage-url www.whatever.com here:</label>
142
<input id="homepage" name="homepage" size="55" value="" /><br />
143
URL:
144
<label for="url">Don't write anything in this field:</label>
145
<input id="url" name="url" size="61" value="" /><br />
146
Comment:
147
<label for="comment">Enter not your comment here:</label>
148
<textarea name="comment" cols="50" rows="10"></textarea><br />
149
</p>
150
<?php }
151

    
152
// Get list of fields
153
$query_fields = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id' ORDER BY position ASC");
154
if($query_fields->numRows() > 0) {
155
	while($field = $query_fields->fetchRow()) {
156
		// Set field values
157
		$field_id = $field['field_id'];
158
		$value = $field['value'];
159
		// Print field_loop after replacing vars with values
160
		$vars = array('{TITLE}', '{REQUIRED}');
161
		$values = array($field['title']);
162
		if($field['required'] == 1) {
163
			$values[] = '<font class="required">*</font>';
164
			$java_fields .= $java_tween.'"field'.$field_id.'"';
165
			$java_titles .= $java_tween.'"'.$field['title'].'"';
166
			$java_tween = ', ';
167
		} else {
168
			$values[] = '';
169
		}
170
		if($field['type'] == 'textfield') {
171
			$vars[] = '{FIELD}';
172
			$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" />';
173
		} elseif($field['type'] == 'textarea') {
174
			$vars[] = '{FIELD}';
175
			$values[] = '<textarea name="field'.$field_id.'" id="field'.$field_id.'" class="textarea">'.(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:$value).'</textarea>';
176
		} elseif($field['type'] == 'select') {
177
			$vars[] = '{FIELD}';
178
			$options = explode(',', $value);
179
			array_walk($options, 'make_option', (isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:array()));
180
			$field['extra'] = explode(',',$field['extra']); 
181
			$values[] = '<select name="field'.$field_id.'[]" id="field'.$field_id.'" size="'.$field['extra'][0].'" '.$field['extra'][1].' class="select">'.implode($options).'</select>';
182
		} elseif($field['type'] == 'heading') {
183
			$vars[] = '{FIELD}';
184
			$values[] = '<input type="hidden" name="field'.$field_id.'" id="field'.$field_id.'" value="===['.$field['title'].']===" />';
185
			$tmp_field_loop = $field_loop;		// temporarily modify the field loop template
186
			$field_loop = $field['extra'];
187
		} elseif($field['type'] == 'checkbox') {
188
			$vars[] = '{FIELD}';
189
			$options = explode(',', $value);
190
			array_walk($options, 'make_checkbox', array(array($field_id,$field['extra']),(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:array())));
191
			$options[count($options)-1]=substr($options[count($options)-1],0,strlen($options[count($options)-1])-strlen($field['extra']));
192
			$values[] = implode($options);
193
		} elseif($field['type'] == 'radio') {
194
			$vars[] = '{FIELD}';
195
			$options = explode(',', $value);
196
			array_walk($options, 'make_radio', array($field_id,$field['title'],$field['extra'], (isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:'')));
197
			$options[count($options)-1]=substr($options[count($options)-1],0,strlen($options[count($options)-1])-strlen($field['extra']));
198
			$values[] = implode($options);
199
		} elseif($field['type'] == 'email') {
200
			$vars[] = '{FIELD}';
201
			$values[] = '<input type="text" name="field'.$field_id.'" onChange="return checkmail(this.form.field'.$field_id.')"  id="field'.$field_id.'" value="'.(isset($_SESSION['field'.$field_id])?$_SESSION['field'.$field_id]:'').'" maxlength="'.$field['extra'].'" class="email" />';
202
			$java_mailcheck .= 'onChange="return checkmail(this.form'.$field_id.'" ';
203
		}
204
		if(isset($_SESSION['field'.$field_id])) unset($_SESSION['field'.$field_id]);
205
		if($field['type'] != '') {
206
			echo str_replace($vars, $values, $field_loop);
207
		}
208
		if (isset($tmp_field_loop)) $field_loop = $tmp_field_loop;
209
	}
210
}
211

    
212
// Captcha
213
if($use_captcha) { ?>
214
	<tr>
215
	<td class="field_title"><?php echo $TEXT['VERIFICATION']; ?>:</td>
216
	<td><?php call_captcha(); ?></td>
217
	</tr>
218
	<?php
219
}
220
echo '
221
<script language="JavaScript">
222
<!--
223

    
224
/***********************************************
225
* Required field(s) validation v1.10- By NavSurf
226
* Visit Nav Surf at http://navsurf.com
227
* Visit http://www.dynamicdrive.com/ for full source code
228
***********************************************/
229

    
230
function formCheck(formobj){
231
	// Enter name of mandatory fields
232
	var fieldRequired = Array('.$java_fields.');
233
	// Enter field description to appear in the dialog box
234
	var fieldDescription = Array('.$java_titles.');
235
	// dialog message
236
	var alertMsg = "'.$MESSAGE['MOD_FORM']['REQUIRED_FIELDS'].':\n";
237
	
238
	var l_Msg = alertMsg.length;
239
	
240
	for (var i = 0; i < fieldRequired.length; i++){
241
		var obj = formobj.elements[fieldRequired[i]];
242
		if (obj){
243
			switch(obj.type){
244
			case "select-one":
245
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
246
					alertMsg += " - " + fieldDescription[i] + "\n";
247
				}
248
				break;
249
			case "select-multiple":
250
				if (obj.selectedIndex == -1){
251
					alertMsg += " - " + fieldDescription[i] + "\n";
252
				}
253
				break;
254
			case "text":
255
			case "textarea":
256
				if (obj.value == "" || obj.value == null){
257
					alertMsg += " - " + fieldDescription[i] + "\n";
258
				}
259
				break;
260
			default:
261
			}
262
			if (obj.type == undefined){
263
				var blnchecked = false;
264
				for (var j = 0; j < obj.length; j++){
265
					if (obj[j].checked){
266
						blnchecked = true;
267
					}
268
				}
269
				if (!blnchecked){
270
					alertMsg += " - " + fieldDescription[i] + "\n";
271
				}
272
			}
273
		}
274
	}
275

    
276
	if (alertMsg.length == l_Msg){
277
		return true;
278
	}else{
279
		alert(alertMsg);
280
		return false;
281
	}
282
}
283
/***********************************************
284
* Email Validation script- ? Dynamic Drive (www.dynamicdrive.com)
285
* This notice must stay intact for legal use.
286
* Visit http://www.dynamicdrive.com/ for full source code
287
***********************************************/
288

    
289
var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
290

    
291
function checkmail(e){
292
var returnval=emailfilter.test(e.value);
293
if (returnval==false){
294
alert("Please enter a valid email address.");
295
e.select();
296
}
297
return returnval;
298
}
299
-->
300

    
301
</script>';
302

    
303

    
304
// Print footer
305
echo $footer;
306

    
307
// Add form end code
308
?>
309
</form>
310
<?php
311

    
312
} else {
313
	
314
	// Check that submission ID matches
315
	if(isset($_SESSION['form_submission_id']) AND isset($_POST['submission_id']) AND $_SESSION['form_submission_id'] == $_POST['submission_id']) {
316
		
317
		// Set new submission ID in session
318
		$_SESSION['form_submission_id'] = new_submission_id();
319
		
320
		if(ENABLED_ASP && ( // form faked? Check the honeypot-fields.
321
			(!isset($_POST['submitted_when']) OR !isset($_SESSION['submitted_when'])) OR 
322
			($_POST['submitted_when'] != $_SESSION['submitted_when']) OR
323
			(!isset($_POST['email']) OR $_POST['email']) OR
324
			(!isset($_POST['homepage']) OR $_POST['homepage']) OR
325
			(!isset($_POST['comment']) OR $_POST['comment']) OR
326
			(!isset($_POST['url']) OR $_POST['url'])
327
		)) {
328
			exit(header("Location: ".WB_URL.PAGES_DIRECTORY.""));
329
		}
330

    
331
		// Submit form data
332
		// First start message settings
333
		$query_settings = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_settings WHERE section_id = '$section_id'");
334
		if($query_settings->numRows() > 0) {
335
			$fetch_settings = $query_settings->fetchRow();
336
			$email_to = $fetch_settings['email_to'];
337
			$email_from = $fetch_settings['email_from'];
338
			if(substr($email_from, 0, 5) == 'field') {
339
				// Set the email from field to what the user entered in the specified field
340
				$email_from = htmlspecialchars($wb->add_slashes($_POST[$email_from]));
341
			}
342
			$email_fromname = $fetch_settings['email_fromname'];
343
			$email_subject = $fetch_settings['email_subject'];
344
			$success_page = $fetch_settings['success_page'];
345
			$success_email_to = $fetch_settings['success_email_to'];
346
			if(substr($success_email_to, 0, 5) == 'field') {
347
				// Set the success_email to field to what the user entered in the specified field
348
				$success_email_to = htmlspecialchars($wb->add_slashes($_POST[$success_email_to]));
349
			}
350
			$success_email_from = $fetch_settings['success_email_from'];
351
			$success_email_fromname = $fetch_settings['success_email_fromname'];
352
			$success_email_text = $fetch_settings['success_email_text'];
353
			$success_email_subject = $fetch_settings['success_email_subject'];		
354
			$max_submissions = $fetch_settings['max_submissions'];
355
			$stored_submissions = $fetch_settings['stored_submissions'];
356
			$use_captcha = $fetch_settings['use_captcha'];
357
		} else {
358
			exit($TEXT['UNDER_CONSTRUCTION']);
359
		}
360
		$email_body = '';
361
		
362
		// Create blank "required" array
363
		$required = array();
364
		
365
		// Captcha
366
		if($use_captcha) {
367
			if(isset($_POST['captcha']) AND $_POST['captcha'] != ''){
368
				// Check for a mismatch
369
				if(!isset($_POST['captcha']) OR !isset($_SESSION['captcha']) OR $_POST['captcha'] != $_SESSION['captcha']) {
370
					$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
371
				}
372
			} else {
373
				$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
374
			}
375
		}
376
		if(isset($_SESSION['captcha'])) { unset($_SESSION['captcha']); }
377

    
378
		// Loop through fields and add to message body
379
		// Get list of fields
380
		$query_fields = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id' ORDER BY position ASC");
381
		if($query_fields->numRows() > 0) {
382
			while($field = $query_fields->fetchRow()) {
383
				// Add to message body
384
				if($field['type'] != '') {
385
					if(!empty($_POST['field'.$field['field_id']])) {
386
						if(isset($captcha_error)) $_SESSION['field'.$field['field_id']] = htmlspecialchars($_POST['field'.$field['field_id']]);
387
						if($field['type'] == 'email' AND $admin->validate_email($_POST['field'.$field['field_id']]) == false) {
388
							$email_error = $MESSAGE['USERS']['INVALID_EMAIL'];
389
						}
390
						if($field['type'] == 'heading') {
391
							$email_body .= $_POST['field'.$field['field_id']]."\n\n";
392
						} elseif (!is_array($_POST['field'.$field['field_id']])) {
393
							$email_body .= $field['title'].': '.$_POST['field'.$field['field_id']]."\n\n";
394
						} else {
395
							$email_body .= $field['title'].": \n";
396
							foreach ($_POST['field'.$field['field_id']] as $k=>$v) {
397
								$email_body .= $v."\n";
398
							}
399
							$email_body .= "\n";
400
						}
401
					} elseif($field['required'] == 1) {
402
						$required[] = $field['title'];
403
					}
404
				}
405
			}
406
		}
407

    
408
		// Addslashes to email body - proposed by Icheb in topic=1170.0
409
		// $email_body = $wb->add_slashes($email_body);
410
		
411
		// Check if the user forgot to enter values into all the required fields
412
		if($required != array()) {
413
			if(!isset($MESSAGE['MOD_FORM']['REQUIRED_FIELDS'])) {
414
				echo 'You must enter details for the following fields';
415
			} else {
416
				echo $MESSAGE['MOD_FORM']['REQUIRED_FIELDS'];
417
			}
418
			echo ':<br /><ul>';
419
			foreach($required AS $field_title) {
420
				echo '<li>'.$field_title;
421
			}
422
			if(isset($email_error)) { echo '<li>'.$email_error.'</li>'; }
423
			if(isset($captcha_error)) { echo '<li>'.$captcha_error.'</li>'; }
424
			echo '</ul><a href="javascript: history.go(-1);">'.$TEXT['BACK'].'</a>';
425
			
426
		} else {
427
			
428
			if(isset($email_error)) {
429
				echo '<br /><ul>';
430
				echo '<li>'.$email_error.'</li>';
431
				echo '</ul><a href="javascript: history.go(-1);">'.$TEXT['BACK'].'</a>';
432
			} elseif(isset($captcha_error)) {
433
				echo '<br /><ul>';
434
				echo '<li>'.$captcha_error.'</li>';
435
				echo '</ul><a href="javascript: history.go(-1);">'.$TEXT['BACK'].'</a>';
436
			} else {
437
				
438
				// Check how many times form has been submitted in last hour
439
				$last_hour = time()-3600;
440
				$query_submissions = $database->query("SELECT submission_id FROM ".TABLE_PREFIX."mod_form_submissions WHERE submitted_when >= '$last_hour'");
441
				if($query_submissions->numRows() > $max_submissions) {
442
					// Too many submissions so far this hour
443
					echo $MESSAGE['MOD_FORM']['EXCESS_SUBMISSIONS'];
444
					$success = false;
445
				} else {
446
					// Now send the email
447
					if($email_to != '') {
448
						if($email_from != '') {
449
							if($wb->mail($email_from,$email_to,$email_subject,$email_body,$email_fromname)) {
450
								$success = true;
451
							}
452
						} else {
453
							if($wb->mail('',$email_to,$email_subject,$email_body,$email_fromname)) { 
454
								$success = true; 
455
							}
456
						}
457
					}				
458
					if($success_email_to != '') {
459
						if($success_email_from != '') {
460
							if($wb->mail($success_email_from,$success_email_to,$success_email_subject,$success_email_text,$success_email_fromname)) {
461
								$success = true;
462
							}
463
						} else {
464
							if($wb->mail('',$success_email_to,$success_email_subject,$success_email_text,$success_email_fromname)) {
465
								$success = true;
466
							}
467
						}
468
					}				
469
			
470
					// Write submission to database
471
					if(isset($admin) AND $admin->is_authenticated() AND $admin->get_user_id() > 0) {
472
						$submitted_by = $admin->get_user_id();
473
					} else {
474
						$submitted_by = 0;
475
					}
476
					$email_body = $wb->add_slashes($email_body);
477
					$database->query("INSERT INTO ".TABLE_PREFIX."mod_form_submissions (page_id,section_id,submitted_when,submitted_by,body) VALUES ('".PAGE_ID."','$section_id','".mktime()."','$submitted_by','$email_body')");
478
					// Make sure submissions table isn't too full
479
					$query_submissions = $database->query("SELECT submission_id FROM ".TABLE_PREFIX."mod_form_submissions ORDER BY submitted_when");
480
					$num_submissions = $query_submissions->numRows();
481
					if($num_submissions > $stored_submissions) {
482
						// Remove excess submission
483
						$num_to_remove = $num_submissions-$stored_submissions;
484
						while($submission = $query_submissions->fetchRow()) {
485
							if($num_to_remove > 0) {
486
								$submission_id = $submission['submission_id'];
487
								$database->query("DELETE FROM ".TABLE_PREFIX."mod_form_submissions WHERE submission_id = '$submission_id'");
488
								$num_to_remove = $num_to_remove-1;
489
							}
490
						}
491
					}
492
					if(!$database->is_error()) {
493
						$success = true;
494
					}
495
				}
496
			}	
497
		}
498
	}
499
	
500
	// Now check if the email was sent successfully
501
	if(isset($success) AND $success == true) {
502
	    if ($success_page=='none') {
503
			echo str_replace("\n","<br />",$success_email_text);
504
  		} else {
505
			$query_menu = $database->query("SELECT link,target FROM ".TABLE_PREFIX."pages WHERE `page_id` = '$success_page'");
506
			if($query_menu->numRows() > 0) {
507
  	         	$fetch_settings = $query_menu->fetchRow();
508
			    $link = WB_URL.PAGES_DIRECTORY.$fetch_settings['link'].PAGE_EXTENSION;
509
			    echo "<script type='text/javascript'>location.href='".$link."';</script>";
510
			}    
511
		}
512
	} else {
513
		echo $TEXT['ERROR'];
514
	}
515
	
516
}
517

    
518
?>
(22-22/23)