Project

General

Profile

1
<?php
2

    
3
// $Id: view.php 618 2008-01-27 20:14:38Z 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
require_once(WB_PATH.'/include/captcha/asp.php');
44

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

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

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

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

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

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

    
131
// Print header
132
echo $header;
133

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

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

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

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

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

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

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

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

    
302
</script>';
303

    
304

    
305
// Print footer
306
echo $footer;
307

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

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

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

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

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

    
517
?>
(22-22/23)