-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormHandler.php
269 lines (232 loc) · 5.87 KB
/
FormHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<?php
namespace FormGuide\Handlx;
use FormGuide\PHPFormValidator\FormValidator;
use PHPMailer;
use FormGuide\Handlx\Microtemplate;
use Gregwar\Captcha\CaptchaBuilder;
/**
* FormHandler
* A wrapper class that handles common form handling tasks
* - handles Form validations using PHPFormValidator class
* - sends email using PHPMailer
* - can handle captcha validation
* - can handle file uploads and attaching the upload to email
*
* ==== Sample usage ====
* $fh = FormHandler::create()->validate(function($validator)
* {
* $validator->fields(['name','email'])
* ->areRequired()->maxLength(50);
* $validator->field('email')->isEmail();
*
* })->useMailTemplate(__DIR__.'/templ/email.php')
* ->sendEmailTo('[email protected]');
*
* $fh->process($_POST);
*/
class FormHandler
{
private $emails;
public $validator;
private $mailer;
private $mail_template;
private $captcha;
private $attachments;
private $recaptcha;
public function __construct()
{
$this->emails = array();
$this->validator = FormValidator::create();
$this->mailer = new PHPMailer;
$this->mail_template='';
$this->mailer->Subject = "Contact Form Submission ";
$host = isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:'localhost';
$from_email ='forms@'.$host;
$this->mailer->setFrom($from_email,'Contact Form',false);
$this->captcha = false;
$this->attachments = [];
$this->recaptcha =null;
}
/**
* sendEmailTo: add a recipient email address
* @param string/array $email_s one or more emails. If more than one emails, pass the emails as array
* @return The form handler object itself so that the methods can be chained
*/
public function sendEmailTo($email_s)
{
if(is_array($email_s))
{
$this->emails =array_merge($this->emails, $email_s);
}
else
{
$this->emails[] = $email_s;
}
return $this;
}
public function useMailTemplate($templ_path)
{
$this->mail_template = $templ_path;
return $this;
}
/**
* [attachFiles find the file uplods and attach to the email]
* @param array $fields The array of field names
*/
public function attachFiles($fields)
{
$this->attachments = array_merge($this->attachments, $fields);
return $this;
}
public function getRecipients()
{
return $this->emails;
}
/**
* [validate add Validations. This function takes a call back function which receives the PHPFormValidator object]
* @param function $validator_fn The funtion gets a validator parameter using which, you can add validations
*/
public function validate($validator_fn)
{
$validator_fn($this->validator);
return $this;
}
public function requireReCaptcha($config_fn=null)
{
$this->recaptcha = new ReCaptchaValidator();
$this->recaptcha->enable(true);
if($config_fn)
{
$config_fn($this->recaptcha);
}
return $this;
}
public function getReCaptcha()
{
return $this->recaptcha;
}
public function requireCaptcha($enable=true)
{
$this->captcha = $enable;
return $this;
}
public function getValidator()
{
return $this->validator;
}
public function configMailer($mailconfig_fn)
{
$mailconfig_fn($this->mailer);
return $this;
}
public function getMailer()
{
return $this->mailer;
}
public static function create()
{
return new FormHandler();
}
public function process($post_data)
{
if($this->captcha === true)
{
$res = $this->validate_captcha($post_data);
if($res !== true)
{
return $res;
}
}
if($this->recaptcha !== null &&
$this->recaptcha->isEnabled())
{
if($this->recaptcha->validate() !== true)
{
return json_encode([
'result'=>'recaptcha_validation_failed',
'errors'=>['captcha'=>'ReCaptcha Validation Failed.']
]);
}
}
$this->validator->test($post_data);
//if(false == $this->validator->test($post_data))
if($this->validator->hasErrors())
{
return json_encode([
'result'=>'validation_failed',
'errors'=>$this->validator->getErrors(/*associative*/ true)
]);
}
if(!empty($this->emails))
{
foreach($this->emails as $email)
{
$this->mailer->addAddress($email);
}
$this->compose_mail($post_data);
if(!empty($this->attachments))
{
$this->attach_files();
}
if(!$this->mailer->send())
{
return json_encode([
'result'=>'error_sending_email',
'errors'=> ['mail'=> $this->mailer->ErrorInfo]
]);
}
}
return json_encode(['result'=>'success']);
}
private function validate_captcha($post)
{
@session_start();
if(empty($post['captcha']))
{
return json_encode([
'result'=>'captcha_error',
'errors'=>['captcha'=>'Captcha code not entered']
]);
}
else
{
$usercaptcha = trim($post['captcha']);
if($_SESSION['user_phrase'] !== $usercaptcha)
{
return json_encode([
'result'=>'captcha_error',
'errors'=>['captcha'=>'Captcha code does not match']
]);
}
}
return true;
}
private function attach_files()
{
foreach($this->attachments as $file_field)
{
if (!array_key_exists($file_field, $_FILES))
{
continue;
}
$filename = $_FILES[$file_field]['name'];
$uploadfile = tempnam(sys_get_temp_dir(), sha1($filename));
if (!move_uploaded_file($_FILES[$file_field]['tmp_name'],
$uploadfile))
{
continue;
}
$this->mailer->addAttachment($uploadfile, $filename);
}
}
private function compose_mail($post)
{
$content = "Form submission: \n\n";
foreach($post as $name=>$value)
{
$content .= ucwords($name).":\n";
$content .= "$value\n\n";
}
$this->mailer->Body = $content;
}
}