forked from skydiver/wn-forms-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMagicForm.php
332 lines (270 loc) · 11.1 KB
/
MagicForm.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
<?php
namespace Martin\Forms\Classes;
use Cms\Classes\ComponentBase;
use Martin\Forms\Models\Record;
use Martin\Forms\Models\Settings;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Martin\Forms\Classes\BackendHelpers;
use Winter\Storm\Support\Facades\Config;
use Winter\Storm\Exception\AjaxException;
use Martin\Forms\Classes\FilePond\FilePond;
use Winter\Storm\Support\Facades\Validator;
use Martin\Forms\Classes\Mails\AutoResponse;
use Martin\Forms\Classes\Mails\Notification;
use Winter\Storm\Exception\ValidationException;
abstract class MagicForm extends ComponentBase
{
use \Martin\Forms\Classes\ReCaptcha;
use \Martin\Forms\Classes\SharedProperties;
public function onRun()
{
$this->page['recaptcha_enabled'] = $this->isReCaptchaEnabled();
$this->page['recaptcha_misconfigured'] = $this->isReCaptchaMisconfigured();
if ($this->property('uploader_enable')) {
$this->page['allowed_filesize'] = Settings::get('global_allowed_filesize');
}
if ($this->isReCaptchaEnabled()) {
$this->loadReCaptcha();
}
if ($this->isReCaptchaMisconfigured()) {
$this->page['recaptcha_warn'] = Lang::get('martin.forms::lang.components.shared.recaptcha_warn');
}
if ($this->property('inline_errors') == 'display') {
$this->addJs('assets/js/inline-errors.js');
}
}
public function settings()
{
return [
'recaptcha_site_key' => Settings::get('recaptcha_site_key'),
'recaptcha_secret_key' => Settings::get('recaptcha_secret_key'),
];
}
public function onFormSubmit()
{
// FLASH PARTIAL
$flash_partial = $this->property('messages_partial', '@flash.htm');
// CSRF CHECK
if (Config::get('cms.enableCsrfProtection') && (Session::token() != post('_token'))) {
throw new AjaxException(['#' . $this->alias . '_forms_flash' => $this->renderPartial($flash_partial, [
'status' => 'error',
'type' => 'danger',
'content' => Lang::get('martin.forms::lang.components.shared.csrf_error'),
])]);
}
// LOAD TRANSLATOR PLUGIN
if (BackendHelpers::isTranslatePlugin()) {
$translator = \RainLab\Translate\Classes\Translator::instance();
$translator->loadLocaleFromSession();
$locale = $translator->getLocale();
\RainLab\Translate\Models\Message::setContext($locale);
}
// FILTER ALLOWED FIELDS
$allow = $this->property('allowed_fields');
if (is_array($allow) && !empty($allow)) {
foreach ($allow as $field) {
$post[$field] = post($field);
}
if ($this->isReCaptchaEnabled()) {
$post['g-recaptcha-response'] = post('g-recaptcha-response');
}
} else {
$post = post();
}
// SANITIZE FORM DATA
if ($this->property('sanitize_data') == 'htmlspecialchars') {
$post = $this->array_map_recursive(function ($value) {
return htmlspecialchars($value, ENT_QUOTES);
}, $post);
}
// VALIDATION PARAMETERS
$rules = (array)$this->property('rules');
$msgs = (array)$this->property('rules_messages');
$custom_attributes = (array)$this->property('custom_attributes');
// TRANSLATE CUSTOM ERROR MESSAGES
if (BackendHelpers::isTranslatePlugin()) {
foreach ($msgs as $rule => $msg) {
$msgs[$rule] = \RainLab\Translate\Models\Message::trans($msg);
}
}
// ADD reCAPTCHA VALIDATION
if ($this->isReCaptchaEnabled() && $this->property('recaptcha_size') != 'invisible') {
$rules['g-recaptcha-response'] = 'required';
}
// DO FORM VALIDATION
$validator = Validator::make($post, $rules, $msgs, $custom_attributes);
// NICE reCAPTCHA FIELD NAME
if ($this->isReCaptchaEnabled()) {
$fields_names = ['g-recaptcha-response' => 'reCAPTCHA'];
$validator->setAttributeNames(array_merge($fields_names, $custom_attributes));
}
// VALIDATE ALL + CAPTCHA EXISTS
if ($validator->fails()) {
// GET DEFAULT ERROR MESSAGE
$message = $this->property('messages_errors');
// LOOK FOR TRANSLATION
if (BackendHelpers::isTranslatePlugin()) {
$message = \RainLab\Translate\Models\Message::trans($message);
}
// THROW ERRORS
if ($this->property('inline_errors') == 'display') {
throw new ValidationException($validator);
} else {
throw new AjaxException($this->exceptionResponse($validator, [
'status' => 'error',
'type' => 'danger',
'title' => $message,
'list' => $validator->messages()->all(),
'errors' => json_encode($validator->messages()->messages()),
'jscript' => $this->property('js_on_error'),
]));
}
}
// IF FIRST VALIDATION IS OK, VALIDATE CAPTCHA vs GOOGLE
// (this prevents to resolve captcha after every form error)
if ($this->isReCaptchaEnabled()) {
// PREPARE RECAPTCHA VALIDATION
$rules = ['g-recaptcha-response' => 'recaptcha'];
$err_msg = ['g-recaptcha-response.recaptcha' => Lang::get('martin.forms::lang.validation.recaptcha_error')];
// DO SECOND VALIDATION
$validator = Validator::make($post, $rules, $err_msg);
// VALIDATE ALL + CAPTCHA EXISTS
if ($validator->fails()) {
// THROW ERRORS
if ($this->property('inline_errors') == 'display') {
throw new ValidationException($validator);
} else {
throw new AjaxException($this->exceptionResponse($validator, [
'status' => 'error',
'type' => 'danger',
'content' => Lang::get('martin.forms::lang.validation.recaptcha_error'),
'errors' => json_encode($validator->messages()->messages()),
'jscript' => $this->property('js_on_error'),
]));
}
}
}
// REMOVE EXTRA FIELDS FROM STORED DATA
unset($post['_token'], $post['g-recaptcha-response'], $post['_session_key'], $post['files']);
// FIRE BEFORE SAVE EVENT
Event::fire('martin.forms.beforeSaveRecord', [&$post, $this]);
if (count($custom_attributes)) {
$post = collect($post)->mapWithKeys(function ($val, $key) use ($custom_attributes) {
return [array_get($custom_attributes, $key, $key) => $val];
})->all();
}
$record = new Record;
$record->ip = $this->getIP();
$record->created_at = date('Y-m-d H:i:s');
// SAVE RECORD TO DATABASE
if (!$this->property('skip_database')) {
$record->form_data = json_encode($post, JSON_UNESCAPED_UNICODE);
if ($this->property('group') != '') {
$record->group = $this->property('group');
}
// attach files
$this->attachFiles($record);
$record->save(null, post('_session_key'));
}
// SEND NOTIFICATION EMAIL
if ($this->property('mail_enabled')) {
$notification = App::makeWith(Notification::class, [
$this->getProperties(), $post, $record, $record->files
]);
$notification->send();
}
// SEND AUTORESPONSE EMAIL
if ($this->property('mail_resp_enabled')) {
$autoresponse = App::makeWith(AutoResponse::class, [
$this->getProperties(), $post, $record
]);
$autoresponse->send();
}
// FIRE AFTER SAVE EVENT
Event::fire('martin.forms.afterSaveRecord', [&$post, $this, $record]);
// CHECK FOR REDIRECT
if ($this->property('redirect')) {
return Redirect::to($this->property('redirect'));
}
// GET DEFAULT SUCCESS MESSAGE
$message = $this->property('messages_success');
// LOOK FOR TRANSLATION
if (BackendHelpers::isTranslatePlugin()) {
$message = \RainLab\Translate\Models\Message::trans($message);
}
// DISPLAY SUCCESS MESSAGE
return ['#' . $this->alias . '_forms_flash' => $this->renderPartial($flash_partial, [
'status' => 'success',
'type' => 'success',
'content' => $message,
'jscript' => $this->prepareJavaScript(),
])];
}
private function exceptionResponse($validator, $params)
{
// FLASH PARTIAL
$flash_partial = $this->property('messages_partial', '@flash.htm');
// EXCEPTION RESPONSE
$response = ['#' . $this->alias . '_forms_flash' => $this->renderPartial($flash_partial, $params)];
// INCLUDE ERROR FIELDS IF REQUIRED
if ($this->property('inline_errors') != 'disabled') {
$response['error_fields'] = $validator->messages();
}
return $response;
}
private function prepareJavaScript()
{
$code = false;
/* SUCCESS JS */
if ($this->property('js_on_success') != '') {
$code .= $this->property('js_on_success');
}
/* RECAPTCHA JS */
if ($this->isReCaptchaEnabled()) {
$code .= $this->renderPartial('@js/recaptcha.htm');
}
/* RESET FORM JS */
if ($this->property('reset_form')) {
$params = ['id' => '#' . $this->alias . '_forms_flash'];
$code .= $this->renderPartial('@js/reset-form.htm', $params);
}
return $code;
}
private function getIP()
{
if ($this->property('anonymize_ip') == 'full') {
return '(Not stored)';
}
$ip = Request::getClientIp();
if ($this->property('anonymize_ip') == 'partial') {
return BackendHelpers::anonymizeIPv4($ip);
}
return $ip;
}
private function array_map_recursive($callback, $array)
{
$func = function ($item) use (&$func, &$callback) {
return is_array($item) ? array_map($func, $item) : call_user_func($callback, $item);
};
return array_map($func, $array);
}
private function attachFiles(Record $record)
{
$files = post('files', null);
if (!$files) {
return;
}
foreach ($files as $file) {
$filepond = App::make(FilePond::class);
$filePath = $filepond->getPathFromServerId($file);
$record->files()->create([
'data' => $filePath
], post('_session_key'));
}
}
}