Project

General

Profile

1
<?php
2

    
3
// $Id: view.php 739 2008-03-02 21:10:00Z 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 htmlspecialchars(strip_tags($_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 = htmlspecialchars($wb->add_slashes($_POST[$email_from]));
342
			}
343
			$email_fromname = $fetch_settings['email_fromname'];
344
			$email_subject = $fetch_settings['email_subject'];
345
			$success_page = $fetch_settings['success_page'];
346
			$success_email_to = $fetch_settings['success_email_to'];
347
			if(substr($success_email_to, 0, 5) == 'field') {
348
				// Set the success_email to field to what the user entered in the specified field
349
				$success_email_to = htmlspecialchars($wb->add_slashes($_POST[$success_email_to]));
350
			}
351
			$success_email_from = $fetch_settings['success_email_from'];
352
			$success_email_fromname = $fetch_settings['success_email_fromname'];
353
			$success_email_text = $fetch_settings['success_email_text'];
354
			$success_email_subject = $fetch_settings['success_email_subject'];		
355
			$max_submissions = $fetch_settings['max_submissions'];
356
			$stored_submissions = $fetch_settings['stored_submissions'];
357
			$use_captcha = $fetch_settings['use_captcha'];
358
		} else {
359
			exit($TEXT['UNDER_CONSTRUCTION']);
360
		}
361
		$email_body = '';
362
		
363
		// Create blank "required" array
364
		$required = array();
365
		
366
		// Captcha
367
		if($use_captcha) {
368
			if(isset($_POST['captcha']) AND $_POST['captcha'] != ''){
369
				// Check for a mismatch
370
				if(!isset($_POST['captcha']) OR !isset($_SESSION['captcha']) OR $_POST['captcha'] != $_SESSION['captcha']) {
371
					$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
372
				}
373
			} else {
374
				$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
375
			}
376
		}
377
		if(isset($_SESSION['captcha'])) { unset($_SESSION['captcha']); }
378

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

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

    
519
?>
(22-22/23)