Project

General

Profile

1
<?php
2

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

    
88
// Work-out if the form has been submitted or not
89
if($_POST == array()) {
90

    
91
// Set new submission ID in session
92
$_SESSION['form_submission_id'] = new_submission_id();
93

    
94
// Get settings
95
$query_settings = $database->query("SELECT header,field_loop,footer,use_captcha FROM ".TABLE_PREFIX."mod_form_settings WHERE section_id = '$section_id'");
96
if($query_settings->numRows() > 0) {
97
	$fetch_settings = $query_settings->fetchRow();
98
	$header = str_replace('{WB_URL}',WB_URL,$fetch_settings['header']);
99
	$field_loop = $fetch_settings['field_loop'];
100
	$footer = str_replace('{WB_URL}',WB_URL,$fetch_settings['footer']);
101
	$use_captcha = $fetch_settings['use_captcha'];
102
} else {
103
	$header = '';
104
	$field_loop = '';
105
	$footer = '';
106
}
107

    
108
$java_fields = '';
109
$java_titles = '';
110
$java_tween = ''; // I know kinda stupid, anyone better idea?
111
$java_mailcheck = '';
112

    
113
// Add form starter code
114
?>
115
<form name="form" onsubmit="return formCheck(this);" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
116
<input type="hidden" name="submission_id" value="<?php echo $_SESSION['form_submission_id']; ?>" />
117
<?php
118

    
119
// Print header
120
echo $header;
121

    
122
// Get list of fields
123
$query_fields = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id' ORDER BY position ASC");
124
if($query_fields->numRows() > 0) {
125
	while($field = $query_fields->fetchRow()) {
126
		// Set field values
127
		$field_id = $field['field_id'];
128
		$value = $field['value'];
129
		// Print field_loop after replacing vars with values
130
		$vars = array('{TITLE}', '{REQUIRED}');
131
		$values = array($field['title']);
132
		if($field['required'] == 1) {
133
			$values[] = '<font class="required">*</font>';
134
			$java_fields .= $java_tween.'"field'.$field_id.'"';
135
			$java_titles .= $java_tween.'"'.$field['title'].'"';
136
			$java_tween = ', ';
137
		} else {
138
			$values[] = '';
139
		}
140
		if($field['type'] == 'textfield') {
141
			$vars[] = '{FIELD}';
142
			$values[] = '<input type="text" name="field'.$field_id.'" id="field'.$field_id.'" maxlength="'.$field['extra'].'" value="'.$value.'" class="textfield" />';
143
		} elseif($field['type'] == 'textarea') {
144
			$vars[] = '{FIELD}';
145
			$values[] = '<textarea name="field'.$field_id.'" id="field'.$field_id.'" class="textarea">'.$value.'</textarea>';
146
		} elseif($field['type'] == 'select') {
147
			$vars[] = '{FIELD}';
148
			$options = explode(',', $value);
149
			array_walk($options, 'make_option');
150
			$field['extra'] = explode(',',$field['extra']); 
151
			$values[] = '<select name="field'.$field_id.'[]" id="field'.$field_id.'" size="'.$field['extra'][0].'" '.$field['extra'][1].' class="select">'.implode($options).'</select>';
152
		} elseif($field['type'] == 'heading') {
153
			$vars[] = '{FIELD}';
154
			$values[] = '<input type="hidden" name="field'.$field_id.'" id="field'.$field_id.'" value="===['.$field['title'].']===" />';
155
			$tmp_field_loop = $field_loop;		// temporarily modify the field loop template
156
			$field_loop = $field['extra'];
157
		} elseif($field['type'] == 'checkbox') {
158
			$vars[] = '{FIELD}';
159
			$options = explode(',', $value);
160
			array_walk($options, 'make_checkbox',array($field_id,$field['extra']));
161
			$options[count($options)-1]=substr($options[count($options)-1],0,strlen($options[count($options)-1])-strlen($field['extra']));
162
			$values[] = implode($options);
163
		} elseif($field['type'] == 'radio') {
164
			$vars[] = '{FIELD}';
165
			$options = explode(',', $value);
166
			array_walk($options, 'make_radio',array($field_id,$field['title'],$field['extra']));
167
			$options[count($options)-1]=substr($options[count($options)-1],0,strlen($options[count($options)-1])-strlen($field['extra']));
168
			$values[] = implode($options);
169
		} elseif($field['type'] == 'email') {
170
			$vars[] = '{FIELD}';
171
			$values[] = '<input type="text" name="field'.$field_id.'" onChange="return checkmail(this.form.field'.$field_id.')"  id="field'.$field_id.'" maxlength="'.$field['extra'].'" class="email" />';
172
			$java_mailcheck .= 'onChange="return checkmail(this.form'.$field_id.'" ';
173
		}
174
		if($field['type'] != '') {
175
			echo str_replace($vars, $values, $field_loop);
176
		}
177
		if (isset($tmp_field_loop)) $field_loop = $tmp_field_loop;
178
	}
179
}
180

    
181
// Captcha
182
if($use_captcha) {
183
	$_SESSION['captcha'] = '';
184
	for($i = 0; $i < 5; $i++) {
185
		$_SESSION['captcha'] .= rand(0,9);
186
	}
187
	?><tr><td class="field_title"><?php echo $TEXT['VERIFICATION']; ?>:</td><td>
188
	<table cellpadding="2" cellspacing="0" border="0">
189
	<tr><td><img src="<?php echo WB_URL; ?>/include/captcha.php?t=<?php echo time(); ?>" alt="Captcha" /></td>
190
	<td><input type="text" name="captcha" maxlength="5" /></td>
191
	</tr></table>
192
	</td></tr>
193
	<?php
194
}
195
echo '
196
<script language="JavaScript">
197
<!--
198

    
199
/***********************************************
200
* Required field(s) validation v1.10- By NavSurf
201
* Visit Nav Surf at http://navsurf.com
202
* Visit http://www.dynamicdrive.com/ for full source code
203
***********************************************/
204

    
205
function formCheck(formobj){
206
	// Enter name of mandatory fields
207
	var fieldRequired = Array('.$java_fields.');
208
	// Enter field description to appear in the dialog box
209
	var fieldDescription = Array('.$java_titles.');
210
	// dialog message
211
	var alertMsg = "'.$MESSAGE['MOD_FORM']['REQUIRED_FIELDS'].':\n";
212
	
213
	var l_Msg = alertMsg.length;
214
	
215
	for (var i = 0; i < fieldRequired.length; i++){
216
		var obj = formobj.elements[fieldRequired[i]];
217
		if (obj){
218
			switch(obj.type){
219
			case "select-one":
220
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
221
					alertMsg += " - " + fieldDescription[i] + "\n";
222
				}
223
				break;
224
			case "select-multiple":
225
				if (obj.selectedIndex == -1){
226
					alertMsg += " - " + fieldDescription[i] + "\n";
227
				}
228
				break;
229
			case "text":
230
			case "textarea":
231
				if (obj.value == "" || obj.value == null){
232
					alertMsg += " - " + fieldDescription[i] + "\n";
233
				}
234
				break;
235
			default:
236
			}
237
			if (obj.type == undefined){
238
				var blnchecked = false;
239
				for (var j = 0; j < obj.length; j++){
240
					if (obj[j].checked){
241
						blnchecked = true;
242
					}
243
				}
244
				if (!blnchecked){
245
					alertMsg += " - " + fieldDescription[i] + "\n";
246
				}
247
			}
248
		}
249
	}
250

    
251
	if (alertMsg.length == l_Msg){
252
		return true;
253
	}else{
254
		alert(alertMsg);
255
		return false;
256
	}
257
}
258
/***********************************************
259
* Email Validation script- ? Dynamic Drive (www.dynamicdrive.com)
260
* This notice must stay intact for legal use.
261
* Visit http://www.dynamicdrive.com/ for full source code
262
***********************************************/
263

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

    
266
function checkmail(e){
267
var returnval=emailfilter.test(e.value);
268
if (returnval==false){
269
alert("Please enter a valid email address.");
270
e.select();
271
}
272
return returnval;
273
}
274
-->
275

    
276
</script>';
277

    
278

    
279
// Print footer
280
echo $footer;
281

    
282
// Add form end code
283
?>
284
</form>
285
<?php
286

    
287
} else {
288
	
289
	// Check that submission ID matches
290
	if(isset($_SESSION['form_submission_id']) AND isset($_POST['submission_id']) AND $_SESSION['form_submission_id'] == $_POST['submission_id']) {
291
		
292
		// Set new submission ID in session
293
		$_SESSION['form_submission_id'] = new_submission_id();
294
		
295
		// Submit form data
296
		// First start message settings
297
		$query_settings = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_settings WHERE section_id = '$section_id'");
298
		if($query_settings->numRows() > 0) {
299
			$fetch_settings = $query_settings->fetchRow();
300
			$email_to = $fetch_settings['email_to'];
301
			$email_from = $fetch_settings['email_from'];
302
			if(substr($email_from, 0, 5) == 'field') {
303
				// Set the email from field to what the user entered in the specified field
304
				$email_from = $wb->add_slashes($_POST[$email_from]);
305
			}
306
			$email_subject = $fetch_settings['email_subject'];
307
			$success_page = $fetch_settings['success_page'];
308
			$success_email_to = $fetch_settings['success_email_to'];
309
			if(substr($success_email_to, 0, 5) == 'field') {
310
				// Set the success_email to field to what the user entered in the specified field
311
				$success_email_to = $wb->add_slashes($_POST[$success_email_to]);
312
			}
313
			$success_email_from = $fetch_settings['success_email_from'];
314
			$success_email_text = $fetch_settings['success_email_text'];
315
			$success_email_subject = $fetch_settings['success_email_subject'];		
316
			$max_submissions = $fetch_settings['max_submissions'];
317
			$stored_submissions = $fetch_settings['stored_submissions'];
318
			$use_captcha = $fetch_settings['use_captcha'];
319
		} else {
320
			exit($TEXT['UNDER_CONSTRUCTION']);
321
		}
322
		$email_body = '';
323
		
324
		// Create blank "required" array
325
		$required = array();
326
		
327
		// Loop through fields and add to message body
328
		// Get list of fields
329
		$query_fields = $database->query("SELECT * FROM ".TABLE_PREFIX."mod_form_fields WHERE section_id = '$section_id' ORDER BY position ASC");
330
		if($query_fields->numRows() > 0) {
331
			while($field = $query_fields->fetchRow()) {
332
				// Add to message body
333
				if($field['type'] != '') {
334
					if(!empty($_POST['field'.$field['field_id']])) {
335
						if($field['type'] == 'email' AND $admin->validate_email($_POST['field'.$field['field_id']]) == false) {
336
							$email_error = $MESSAGE['USERS']['INVALID_EMAIL'];
337
						}
338
						if($field['type'] == 'heading') {
339
							$email_body .= $_POST['field'.$field['field_id']]."\n\n";
340
						} elseif (!is_array($_POST['field'.$field['field_id']])) {
341
							$email_body .= $field['title'].': '.$_POST['field'.$field['field_id']]."\n\n";
342
						} else {
343
							$email_body .= $field['title'].": \n";
344
							foreach ($_POST['field'.$field['field_id']] as $k=>$v) {
345
								$email_body .= $v."\n";
346
							}
347
							$email_body .= "\n";
348
						}
349
					} elseif($field['required'] == 1) {
350
						$required[] = $field['title'];
351
					}
352
				}
353
			}
354
		}
355
		
356
		// Captcha
357
		if(extension_loaded('gd') AND function_exists('imageCreateFromJpeg')) { /* Make's sure GD library is installed */
358
			if($use_captcha) {
359
				if(isset($_POST['captcha']) AND $_POST['captcha'] != ''){
360
					// Check for a mismatch
361
					if(!isset($_POST['captcha']) OR !isset($_SESSION['captcha']) OR $_POST['captcha'] != $_SESSION['captcha']) {
362
						$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
363
					}
364
				} else {
365
					$captcha_error = $MESSAGE['MOD_FORM']['INCORRECT_CAPTCHA'];
366
				}
367
			}
368
		}
369
		if(isset($_SESSION['captcha'])) { unset($_SESSION['captcha']); }
370
		
371
		// Addslashes to email body - proposed by Icheb in topic=1170.0
372
		// $email_body = $wb->add_slashes($email_body);
373
		
374
		// Check if the user forgot to enter values into all the required fields
375
		if($required != array()) {
376
			if(!isset($MESSAGE['MOD_FORM']['REQUIRED_FIELDS'])) {
377
				echo 'You must enter details for the following fields';
378
			} else {
379
				echo $MESSAGE['MOD_FORM']['REQUIRED_FIELDS'];
380
			}
381
			echo ':<br /><ul>';
382
			foreach($required AS $field_title) {
383
				echo '<li>'.$field_title;
384
			}
385
			if(isset($email_error)) { echo '<li>'.$email_error.'</li>'; }
386
			if(isset($captcha_error)) { echo '<li>'.$captcha_error.'</li>'; }
387
			echo '</ul><a href="javascript: history.go(-1);">'.$TEXT['BACK'].'</a>';
388
			
389
		} else {
390
			
391
			if(isset($email_error)) {
392
				echo '<br /><ul>';
393
				echo '<li>'.$email_error.'</li>';
394
				echo '</ul><a href="javascript: history.go(-1);">'.$TEXT['BACK'].'</a>';
395
			} elseif(isset($captcha_error)) {
396
				echo '<br /><ul>';
397
				echo '<li>'.$captcha_error.'</li>';
398
				echo '</ul><a href="javascript: history.go(-1);">'.$TEXT['BACK'].'</a>';
399
			} else {
400
				
401
				// Check how many times form has been submitted in last hour
402
				$last_hour = time()-3600;
403
				$query_submissions = $database->query("SELECT submission_id FROM ".TABLE_PREFIX."mod_form_submissions WHERE submitted_when >= '$last_hour'");
404
				if($query_submissions->numRows() > $max_submissions) {
405
					// Too many submissions so far this hour
406
					echo $MESSAGE['MOD_FORM']['EXCESS_SUBMISSIONS'];
407
					$success = false;
408
				} else {
409
					// Now send the email
410
					if($email_to != '') {
411
						if($email_from != '') {
412
							if($wb->mail($email_from,$email_to,$email_subject,$email_body)) {
413
								$success = true;
414
							}
415
						} else {
416
							if($wb->mail('',$email_to,$email_subject,$email_body)) { 
417
								$success = true; 
418
							}
419
						}
420
					}				
421
					if($success_email_to != '') {
422
						if($success_email_from != '') {
423
							if($wb->mail($success_email_from,$success_email_to,$success_email_subject,$success_email_text)) {
424
								$success = true;
425
							}
426
						} else {
427
							if($wb->mail('',$success_email_to,$success_email_subject,$success_email_text)) {
428
								$success = true;
429
							}
430
						}
431
					}				
432
			
433
					// Write submission to database
434
					if(isset($admin) AND $admin->get_user_id() > 0) {
435
						$admin->get_user_id();
436
					} else {
437
						$submitted_by = 0;
438
					}
439
					$email_body = $wb->add_slashes($email_body);
440
					$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')");
441
					// Make sure submissions table isn't too full
442
					$query_submissions = $database->query("SELECT submission_id FROM ".TABLE_PREFIX."mod_form_submissions ORDER BY submitted_when");
443
					$num_submissions = $query_submissions->numRows();
444
					if($num_submissions > $stored_submissions) {
445
						// Remove excess submission
446
						$num_to_remove = $num_submissions-$stored_submissions;
447
						while($submission = $query_submissions->fetchRow()) {
448
							if($num_to_remove > 0) {
449
								$submission_id = $submission['submission_id'];
450
								$database->query("DELETE FROM ".TABLE_PREFIX."mod_form_submissions WHERE submission_id = '$submission_id'");
451
								$num_to_remove = $num_to_remove-1;
452
							}
453
						}
454
					}
455
					if(!$database->is_error()) {
456
						$success = true;
457
					}
458
				}
459
			}	
460
		}
461
	}
462
	
463
	// Now check if the email was sent successfully
464
	if(isset($success) AND $success == true) {
465
	    if ($success_page=='none') {
466
			echo str_replace("\n","<br />",$success_email_text);
467
  		} else {
468
			$query_menu = $database->query("SELECT link,target FROM ".TABLE_PREFIX."pages WHERE `page_id` = '$success_page'");
469
			if($query_menu->numRows() > 0) {
470
  	         	$fetch_settings = $query_menu->fetchRow();
471
			    $link = WB_URL.PAGES_DIRECTORY.$fetch_settings['link'].PAGE_EXTENSION;
472
			    echo "<script type='text/javascript'>location.href='".$link."';</script>";
473
			}    
474
		}
475
	} else {
476
		echo $TEXT['ERROR'];
477
	}
478
	
479
}
480

    
481
?>
(22-22/23)