forked from splittingred/FormIt
/
Request.php
491 lines (421 loc) · 14.6 KB
/
Request.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
<?php
namespace Sterc\FormIt;
use Sterc\FormIt\Service\Recaptcha;
use Sterc\FormIt\Service\RecaptchaService;
/**
* Class Request
*
* @package Sterc\FormIt
*/
class Request
{
/**
* A reference to the FormIt instance
* @var \Sterc\FormIt $formit
*/
public $formit = null;
/**
* A reference to the modX instance
* @var \modX $modx
*/
public $modx = null;
/**
* An array of configuration properties
* @var array $config
*/
public $config = [];
/**
* Set to true if wanting to prevent the clearing of fields at the end
* @var boolean $clearFieldsAtEnd
*/
public $clearFieldsAtEnd = false;
/**
* @var Validator $validator
*/
public $validator = null;
/**
* @var Dictionary $fiDictionary
*/
public $dictionary = null;
/**
* @var Recaptcha $reCaptcha
*/
public $reCaptcha = null;
/**
* @param \Sterc\FormIt $formit A reference to the FormIt class instance.
* @param array $config Optional. An array of configuration parameters.
*/
function __construct($formit, $config = [])
{
$this->formit = $formit;
$this->modx = $formit->modx;
$this->config = array_merge([
'clearFieldsOnSuccess' => true,
'hooks' => '',
'placeholderPrefix' => 'fi.',
'preHooks' => '',
'store' => false,
'submitVar' => '',
'validate' => '',
'validateSeparator' => ',',
'renderHooks' => ''
], $config);
}
/**
* Handle all pre-request data, including loading of preHooks, reCaptcha preparation, and the math hook.
*
* @return array An array of pre-fetched fields and their data, possibly set by preHooks
*/
public function prepare()
{
/* if using recaptcha, load recaptcha html */
if ($this->formit->hasHook('recaptcha')) {
$this->loadReCaptcha($this->config);
if (!empty($this->reCaptcha) && $this->reCaptcha instanceof Recaptcha) {
$this->reCaptcha->render($this->config);
} else {
$this->modx->log(\modX::LOG_LEVEL_ERROR,'[FormIt] '.$this->modx->lexicon('formit.recaptcha_err_load'));
}
}
/* if using math hook, load default placeholders */
if ($this->formit->hasHook('math')) {
if (!$this->hasSubmission()) {
$mathMaxRange = $this->modx->getOption('mathMaxRange', $this->config, 100);
$mathMinRange = $this->modx->getOption('mathMinRange', $this->config, 10);
$op1 = rand($mathMinRange, $mathMaxRange);
$op2 = rand($mathMinRange, $mathMaxRange);
/* prevent numbers from being equal */
while ($op2 == $op1) {
$op2 = rand($mathMinRange, $mathMaxRange);
}
if ($op2 > $op1) {
$t = $op2;
$op2 = $op1;
$op1 = $t;
}
/* swap so we always get positive #s */
$operators = array('+', '-');
$operator = rand(0, 1);
/* Store in session so math fields are not required for math hook */
$_SESSION['formitMath'] = array(
'op1' => $op1,
'op2' => $op2,
'operator' => $operators[$operator]
);
} else {
$op1 = $_SESSION['formitMath']['op1'];
$op2 = $_SESSION['formitMath']['op2'];
$operators[$operator] = $_SESSION['formitMath']['operator'];
}
$this->modx->setPlaceholders(array(
$this->modx->getOption('mathOp1Field', $this->config, 'op1') => $op1,
$this->modx->getOption('mathOp2Field', $this->config, 'op2') => $op2,
$this->modx->getOption('mathOperatorField', $this->config, 'operator') => $operators[$operator],
), $this->config['placeholderPrefix']);
}
if ($this->modx->getOption('storeAttachments', $this->config, false) &&
($this->formit->hasHook('FormItSaveForm') || $this->formit->hasHook('saveform'))
) {
$newForm = $this->modx->newObject('FormItForm');
$newForm->validateStoreAttachment($this->config);
}
return $this->runPreHooks();
}
/**
* Load and run preHooks, setting any fields passed.
*
* @return array
*/
public function runPreHooks()
{
$fields = array();
$this->formit->loadHooks('pre', $this->config);
$this->formit->preHooks->loadMultiple($this->config['preHooks'], array(), array(
'submitVar' => $this->config['submitVar'],
'hooks' => $this->config['preHooks']
));
/* if a prehook sets a field, do so here, but only if POST isnt submitted */
if (!$this->hasSubmission()) {
$fields = $this->formit->preHooks->gatherFields();
}
/* if any errors in preHooks */
if ($this->formit->preHooks->hasErrors()) {
$this->formit->preHooks->processErrors();
}
return $fields;
}
/**
* Load and run renderHooks.
*/
public function runRenderHooks()
{
$this->formit->loadHooks('render', $this->config);
$fields = array();
$errors = array();
if ($this->dictionary) {
$fields = $this->dictionary->toArray();
}
if ($this->validator) {
$errors = $this->validator->getErrors();
}
$this->formit->renderHooks->loadMultiple($this->config['renderHooks'], $fields, array(), $errors);
}
/**
* Checks to see if a POST submission for this form has occurred
*
* @return boolean
*/
public function hasSubmission()
{
$inPost = false;
if (!empty($_POST)) {
$inPost = true;
if (!empty($this->config['submitVar']) && empty($_POST[$this->config['submitVar']])) {
$inPost = false;
}
}
return $inPost;
}
/**
* Load the reCaptcha service class
*
* @param array $config An array of configuration parameters for the reCaptcha class
*
* @return Recaptcha An instance of the reCaptcha class
*/
public function loadReCaptcha(array $config = array())
{
if (empty($this->reCaptcha)) {
if ($this->modx->loadClass('recaptcha.FormItReCaptcha', $this->config['model_path'], true, true)) {
$this->reCaptcha = new RecaptchaService($this->formit, $config);
} else {
$this->modx->log(\modX::LOG_LEVEL_ERROR, '[FormIt] '.$this->modx->lexicon('formit.recaptcha_err_load'));
return null;
}
}
return $this->reCaptcha;
}
/**
* Handle the POST request
*
* @param array $fields
*
* @return string
*/
public function handle(array $fields = array())
{
if ($this->hasSubmission()) {
$this->loadDictionary();
$this->dictionary->gather($fields);
/* validate fields */
$this->loadValidator();
$this->validator->reset();
$validated = $this->validate($this->config['validate'], $this->config['validateSeparator']);
if ($validated) {
$this->postProcess();
}
if (!$this->clearFieldsAtEnd) {
$this->setFieldsAsPlaceholders();
}
}
$this->runRenderHooks();
return '';
}
/**
* Removes files if allowFiles is set to 0
*
* @return void
*/
public function checkForFiles()
{
if (!$this->modx->getOption('allowFiles',$this->config,true)) {
$fields = $this->dictionary->toArray();
foreach ($fields as $key => $value) {
if (is_array($value) && !empty($value['tmp_name'])) {
$this->dictionary->remove($key);
}
}
}
}
/**
* Loads the Validator class.
*
* @return Validator An instance of the fiValidator class.
*/
public function loadValidator()
{
if ($this->modx->loadClass('formit.fiValidator',$this->formit->config['model_path'],true,true)) {
$this->validator = new Validator($this->formit, $this->config);
} else {
$this->modx->log(\modX::LOG_LEVEL_ERROR,'[FormIt] Could not load Validator class.');
}
return $this->validator;
}
/**
* Load the dictionary storage mechanism
*
* @return null|Dictionary
*/
public function loadDictionary()
{
if ($this->modx->loadClass('formit.fiDictionary',$this->formit->config['model_path'],true,true)) {
$this->dictionary = new Dictionary($this->formit,$this->config);
} else {
$this->modx->log(\modX::LOG_LEVEL_ERROR,'[FormIt] Could not load Dictionary class.');
}
return $this->dictionary;
}
/**
* Validate all fields prior to post processing
*
* @param string $validationString
* @param string $validationSeparator
*
* @return bool
*/
public function validate($validationString, $validationSeparator)
{
$success = true;
$this->validator->validateFields($this->dictionary,$validationString,$validationSeparator);
if ($this->validator->hasErrors()) {
$success = false;
$this->validator->processErrors();
}
return $success;
}
/**
* Handle post-processing through postHooks
*
* @return bool
*/
public function postProcess()
{
$success = $this->runPostHooks();
if ($success) {
/* if store is set for FormItRetriever, store fields here */
$store = $this->modx->getOption('store', $this->config, false);
if (!empty($store)) {
$this->dictionary->store();
}
/* Remove files older than 1 day uploaded by fiDictionary->gather() */
$tmpFileLifetime = 86400;
if (isset($_SESSION['formit']['tmp_files']) &&
is_array($_SESSION['formit']['tmp_files']) &&
count($_SESSION['formit']['tmp_files'])
) {
foreach ($_SESSION['formit']['tmp_files'] as $key => $file) {
if (file_exists($file) && (time() - filemtime($file) >= $tmpFileLifetime)) {
unlink($file);
unset($_SESSION['formit']['tmp_files'][$key]);
}
}
}
/* Also do a glob for removing files that are left behind by not-completed form submissions */
if (function_exists('glob')) {
$tmpPath = $this->formit->config['assets_path'].'tmp/';
foreach (glob($tmpPath.'*') as $file) {
if (file_exists($file) && (time() - filemtime($file) >= $tmpFileLifetime)) {
unlink($file);
}
}
}
/* if the redirect URL was set, redirect */
$this->checkForRedirect();
/* set success placeholder */
$this->setSuccessMessage();
/* if clearing fields on success, just end here */
if ($this->modx->getOption('clearFieldsOnSuccess', $this->config, true)) {
$this->clearFieldsAtEnd = true;
}
}
return $success;
}
/**
* Run any postHooks that were specified.
*
* @return boolean True if all hooks executed successfully.
*/
public function runPostHooks()
{
$success = true;
/* load posthooks */
$this->formit->loadHooks('post',$this->config);
$this->formit->postHooks->loadMultiple($this->config['hooks'],$this->dictionary->toArray());
/* process form */
if ($this->formit->preHooks->hasErrors() && $this->modx->getOption('preventPostHooksIfPreHooksErrors',$this->config,true)) {
/* prevent scripts from running with prehook errors */
$success = false;
$this->formit->preHooks->processErrors();
} elseif ($this->formit->postHooks->hasErrors()) {
$success = false;
$this->formit->postHooks->processErrors();
} else {
/* assign new values from postHooks */
$this->dictionary->fromArray($this->formit->postHooks->fields);
}
return $success;
}
/**
* Check to see if the redirect URL was set; if so, redirect
* Does not redirect when inTestMode is true, or when returnOutput is true.
*
* @return void
*/
public function checkForRedirect()
{
$url = $this->formit->postHooks->getRedirectUrl();
if (!empty($url) && !$this->formit->inTestMode && !$this->formit->returnOutput) {
$this->modx->sendRedirect($url);
}
}
/**
* Sets the success message placeholders
*
* @param string $message
*
* @return void
*/
public function setSuccessMessage($message = '')
{
$successMsg = $this->modx->getOption('successMessage',$this->config,$message);
$this->modx->setPlaceholder($this->config['placeholderPrefix'].'success',true);
if (!empty($successMsg)) {
$smPlaceholder = $this->modx->getOption('successMessagePlaceholder',$this->config,$this->config['placeholderPrefix'].'successMessage');
$this->modx->setPlaceholder($smPlaceholder,$successMsg);
}
}
/**
* Sets the fields to MODX placeholders
*
* @return void
*/
public function setFieldsAsPlaceholders()
{
$fields = $this->dictionary->toArray();
/* better handling of checkbox values when input name is an array[] */
$fs = array();
/** @var mixed $v */
foreach ($fields as $k => $v) {
if (is_array($v)) {
foreach ($v as $sk => $sv) {
$fs[$k.'.'.$sk] = $this->convertMODXTags($sv);
}
$v = $this->modx->toJSON($v);
}
/* str_replace to prevent showing of placeholders */
$fs[$k] = $this->convertMODXTags($v);
}
$this->modx->setPlaceholders($fs, $this->config['placeholderPrefix']);
}
/**
* Convert MODX tags.
*
* @param string $value
*
* @return string
*/
public function convertMODXTags($value)
{
return str_replace(['[[', ']]'], ['[[', ']]'], $value);
}
}