Edit   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 353
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 203
dl 0
loc 353
ccs 0
cts 264
cp 0
rs 9.92
c 0
b 0
f 0
wmc 31

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getData() 0 4 1
A execute() 0 16 3
B loadForm() 0 157 2
A parse() 0 26 4
A parseFields() 0 33 3
A parseErrorMessages() 0 7 1
F validateForm() 0 72 16
A loadDeleteForm() 0 8 1
1
<?php
2
3
namespace Backend\Modules\FormBuilder\Actions;
4
5
use Backend\Core\Engine\Base\ActionEdit as BackendBaseActionEdit;
6
use Backend\Core\Engine\Model as BackendModel;
7
use Backend\Core\Engine\Form as BackendForm;
8
use Backend\Core\Language\Language as BL;
9
use Backend\Form\Type\DeleteType;
10
use Backend\Modules\FormBuilder\Engine\Autocomplete;
11
use Frontend\Core\Language\Language as FL;
12
use Backend\Modules\FormBuilder\Engine\Model as BackendFormBuilderModel;
13
use Backend\Modules\FormBuilder\Engine\Helper as FormBuilderHelper;
14
15
/**
16
 * This is the edit-action, it will display a form to edit an existing item
17
 */
18
class Edit extends BackendBaseActionEdit
19
{
20
    /**
21
     * The available templates
22
     *
23
     * @var array
24
     */
25
    private $templates = [];
26
27
    public function execute(): void
28
    {
29
        $this->id = $this->getRequest()->query->getInt('id');
30
31
        // does the item exist
32
        if ($this->id !== 0 && BackendFormBuilderModel::exists($this->id)) {
33
            parent::execute();
34
            $this->getData();
35
            $this->loadForm();
36
            $this->validateForm();
37
            $this->loadDeleteForm();
38
            $this->parse();
39
            $this->display();
40
        } else {
41
            // no item found, throw an exceptions, because somebody is fucking with our url
42
            $this->redirect(BackendModel::createUrlForAction('Index') . '&error=non-existing');
43
        }
44
    }
45
46
    private function getData(): void
47
    {
48
        $this->record = BackendFormBuilderModel::get($this->id);
49
        $this->templates = BackendFormBuilderModel::getTemplates();
50
    }
51
52
    private function loadForm(): void
53
    {
54
        $this->form = new BackendForm('edit');
55
        $this->form->addText('name', $this->record['name'])->makeRequired();
56
        $this->form->addDropdown(
57
            'method',
58
            [
59
                'database' => BL::getLabel('MethodDatabase'),
60
                'database_email' => BL::getLabel('MethodDatabaseEmail'),
61
                'email' => BL::getLabel('MethodEmail'),
62
            ],
63
            $this->record['method']
64
        )->makeRequired();
65
        $this->form->addText('email', implode(',', (array) $this->record['email']));
66
        $this->form->addText('email_subject', $this->record['email_subject']);
67
68
        // if we have multiple templates, add a dropdown to select them
69
        if (count($this->templates) > 1) {
70
            $this->form->addDropdown(
71
                'template',
72
                array_combine($this->templates, $this->templates),
73
                $this->record['email_template']
74
            );
75
        }
76
        $this->form->addText('identifier', $this->record['identifier']);
77
        $this->form->addEditor('success_message', $this->record['success_message'])->makeRequired();
78
79
        // textfield dialog
80
        $this->form->addText('textbox_label');
81
        $this->form->addText('textbox_value');
82
        $this->form->addText('textbox_placeholder');
83
        $this->form->addText('textbox_classname');
84
        $this->form->addCheckbox('textbox_required');
85
        $this->form->addCheckbox('textbox_reply_to');
86
        $this->form->addCheckbox('textbox_mailmotor');
87
        $this->form->addText('textbox_required_error_message');
88
        $this->form->addDropdown(
89
            'textbox_validation',
90
            [
91
                '' => '',
92
                'email' => BL::getLabel('Email'),
93
                'number' => BL::getLabel('Numeric'),
94
            ]
95
        );
96
        $this->form->addCheckbox('textbox_send_confirmation_mail_to');
97
        $this->form->addText('textbox_confirmation_mail_subject');
98
        $this->form->addEditor('textbox_confirmation_mail_message');
99
        $this->form->addText('textbox_validation_parameter');
100
        $this->form->addText('textbox_error_message');
101
102
        $this->form->addDropdown('textbox_autocomplete', Autocomplete::getValuesForDropdown());
103
104
        // textarea dialog
105
        $this->form->addText('textarea_label');
106
        $this->form->addTextarea('textarea_value');
107
        $this->form->getField('textarea_value')->setAttribute('cols', 30);
108
        $this->form->addText('textarea_placeholder');
109
        $this->form->addText('textarea_classname');
110
        $this->form->addCheckbox('textarea_required');
111
        $this->form->addText('textarea_required_error_message');
112
        $this->form->addDropdown('textarea_validation', ['' => '']);
113
        $this->form->addText('textarea_validation_parameter');
114
        $this->form->addText('textarea_error_message');
115
116
        // datetime dialog
117
        $this->form->addText('datetime_label');
118
        $this->form->addDropdown(
119
            'datetime_value_amount',
120
            [
121
                '' => '',
122
                '1' => '+1',
123
                '2' => '+2',
124
                '3' => '+3',
125
                '4' => '+4',
126
                '5' => '+5',
127
            ]
128
        );
129
        $this->form->addDropdown(
130
            'datetime_value_type',
131
            [
132
                '' => '',
133
                'today' => BL::getLabel('Today'),
134
                'day' => BL::getLabel('Day'),
135
                'week' => BL::getLabel('Week'),
136
                'month' => BL::getLabel('Month'),
137
                'year' => BL::getLabel('Year'),
138
            ]
139
        );
140
        $this->form->addDropdown(
141
            'datetime_type',
142
            [
143
                'date' => BL::getLabel('Date'),
144
                'time' => BL::getLabel('Time'),
145
            ]
146
        );
147
        $this->form->addCheckbox('datetime_required');
148
        $this->form->addText('datetime_required_error_message');
149
        $this->form->addDropdown(
150
            'datetime_type',
151
            [
152
                'date' => BL::getLabel('Date'),
153
                'time' => BL::getLabel('Time'),
154
            ]
155
        );
156
        $this->form->addDropdown(
157
            'datetime_validation',
158
            [
159
                '' => '',
160
                'time' => BL::getLabel('Time'),
161
            ]
162
        );
163
        $this->form->addText('datetime_classname');
164
        $this->form->addText('datetime_error_message');
165
166
        $this->form->addDropdown('datetime_autocomplete', Autocomplete::getValuesForDropdown());
167
168
        // dropdown dialog
169
        $this->form->addText('dropdown_label');
170
        $this->form->addText('dropdown_values');
171
        $this->form->addDropdown('dropdown_default_value', ['' => ''])->setAttribute('rel', 'dropDownValues');
172
        $this->form->addCheckbox('dropdown_required');
173
        $this->form->addText('dropdown_required_error_message');
174
        $this->form->addText('dropdown_classname');
175
176
        // radiobutton dialog
177
        $this->form->addText('radiobutton_label');
178
        $this->form->addText('radiobutton_values');
179
        $this->form->addDropdown('radiobutton_default_value', ['' => ''])->setAttribute('rel', 'radioButtonValues');
180
        $this->form->addCheckbox('radiobutton_required');
181
        $this->form->addText('radiobutton_required_error_message');
182
        $this->form->addText('radiobutton_classname');
183
184
        // checkbox dialog
185
        $this->form->addText('checkbox_label');
186
        $this->form->addText('checkbox_values');
187
        $this->form->addDropdown('checkbox_default_value', ['' => ''])->setAttribute('rel', 'checkBoxValues');
188
        $this->form->addCheckbox('checkbox_required');
189
        $this->form->addText('checkbox_required_error_message');
190
        $this->form->addText('checkbox_classname');
191
192
        // heading dialog
193
        $this->form->addText('heading');
194
195
        // mailmotor dialog
196
        $settings = BackendModel::get('fork.settings');
197
        $this->form->addText(
198
            'mailmotor_list_id',
199
            $settings->get('Mailmotor', 'list_id_' . BL::getWorkingLanguage()) ?? $settings->get('Mailmotor', 'list_id')
200
        );
201
        $this->form->addText('mailmotor_label', BL::lbl('MailmotorSubscribeToNewsletter'));
202
203
        // paragraph dialog
204
        $this->form->addEditor('paragraph');
205
        $this->form->getField('paragraph')->setAttribute('cols', 30);
206
207
        // submit dialog
208
        $this->form->addText('submit');
209
    }
210
211
    protected function parse(): void
212
    {
213
        $this->parseFields();
214
215
        parent::parse();
216
217
        $this->template->assign('id', $this->record['id']);
218
        $this->template->assign('name', $this->record['name']);
219
        $settings = BackendModel::get('fork.settings');
220
        $recaptchaSiteKey = $settings->get('Core', 'google_recaptcha_site_key');
221
        $recaptchaSecretKey = $settings->get('Core', 'google_recaptcha_secret_key');
222
        $mailmotorListId = $settings->get('Mailmotor', 'list_id');
223
224
        if (!($recaptchaSiteKey || $recaptchaSecretKey)) {
225
            $this->template->assign('recaptchaMissing', true);
226
        }
227
228
        if (BackendModel::isModuleInstalled('Mailmotor')) {
229
            $this->template->assign('showMailmotorOption', !empty($mailmotorListId));
230
            $this->template->assign('mailmotorMailEngine', $settings->get('Mailmotor', 'mail_engine'));
231
        }
232
233
        // parse error messages
234
        $this->parseErrorMessages();
235
236
        $this->header->appendDetailToBreadcrumbs($this->record['name']);
237
    }
238
239
    /**
240
     * Parse the default error messages
241
     */
242
    private function parseErrorMessages(): void
243
    {
244
        // set frontend locale
245
        FL::setLocale(BL::getWorkingLanguage(), true);
246
247
        // assign error messages
248
        $this->template->assign('errors', BackendFormBuilderModel::getErrors());
249
    }
250
251
    private function parseFields(): void
252
    {
253
        $fieldsHTML = [];
254
255
        // get fields
256
        $fields = BackendFormBuilderModel::getFields($this->id);
257
258
        // loop fields
259
        foreach ($fields as $field) {
260
            // submit button
261
            if ($field['type'] == 'submit') {
262
                // assign
263
                $this->template->assign('submitId', $field['id']);
264
265
                // add field
266
                $btn = $this->form->addButton(
267
                    'submit_field',
268
                    \SpoonFilter::htmlspecialcharsDecode($field['settings']['values']),
269
                    'button',
270
                    'btn btn-default'
271
                );
272
                $btn->setAttribute('disabled', 'disabled');
273
274
                // skip
275
                continue;
276
            }
277
278
            // parse field to html
279
            $fieldsHTML[]['field'] = FormBuilderHelper::parseField($field);
280
        }
281
282
        // assign iteration
283
        $this->template->assign('fields', $fieldsHTML);
284
    }
285
286
    private function validateForm(): void
287
    {
288
        if ($this->form->isSubmitted()) {
289
            $this->form->cleanupFields();
290
291
            // shorten the fields
292
            $txtName = $this->form->getField('name');
293
            $txtEmail = $this->form->getField('email');
294
            $txtEmailSubject = $this->form->getField('email_subject');
295
            $ddmMethod = $this->form->getField('method');
296
            $txtSuccessMessage = $this->form->getField('success_message');
297
            $txtIdentifier = $this->form->getField('identifier');
298
299
            $emailAddresses = (array) explode(',', $txtEmail->getValue());
300
301
            // validate fields
302
            $txtName->isFilled(BL::getError('NameIsRequired'));
303
            $txtSuccessMessage->isFilled(BL::getError('SuccessMessageIsRequired'));
304
            if ($ddmMethod->isFilled(BL::getError('NameIsRequired')) && $ddmMethod->getValue() == 'database_email') {
305
                $error = false;
306
307
                // check the addresses
308
                foreach ($emailAddresses as $address) {
309
                    $address = trim($address);
310
311
                    if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
312
                        $error = true;
313
                        break;
314
                    }
315
                }
316
317
                // add error
318
                if ($error) {
319
                    $txtEmail->addError(BL::getError('EmailIsInvalid'));
320
                }
321
            }
322
323
            // identifier
324
            if ($txtIdentifier->isFilled()) {
325
                // invalid characters
326
                if (!\SpoonFilter::isValidAgainstRegexp('/^[a-zA-Z0-9\.\_\-]+$/', $txtIdentifier->getValue())) {
327
                    $txtIdentifier->setError(BL::getError('InvalidIdentifier'));
328
                } elseif (BackendFormBuilderModel::existsIdentifier($txtIdentifier->getValue(), $this->id)) {
329
                    $txtIdentifier->setError(BL::getError('UniqueIdentifier'));
330
                }
331
            }
332
333
            if ($this->form->isCorrect()) {
334
                // build array
335
                $values = [];
336
                $values['name'] = $txtName->getValue();
337
                $values['method'] = $ddmMethod->getValue();
338
                $values['email'] = ($ddmMethod->getValue() == 'database_email' || $ddmMethod->getValue() === 'email')
339
                    ? serialize($emailAddresses) : null;
340
                $values['email_template'] = count($this->templates) > 1
341
                    ? $this->form->getField('template')->getValue() : $this->templates[0];
342
                $values['email_subject'] = empty($txtEmailSubject->getValue()) ? null : $txtEmailSubject->getValue();
343
                $values['success_message'] = $txtSuccessMessage->getValue(true);
344
                $values['identifier'] = (
345
                    $txtIdentifier->isFilled() ?
346
                    $txtIdentifier->getValue() :
347
                    BackendFormBuilderModel::createIdentifier()
348
                );
349
                $values['edited_on'] = BackendModel::getUTCDate();
350
351
                // insert the item
352
                $id = (int) BackendFormBuilderModel::update($this->id, $values);
353
354
                // everything is saved, so redirect to the overview
355
                $this->redirect(
356
                    BackendModel::createUrlForAction('Index') . '&report=edited&var=' .
357
                    rawurlencode($values['name']) . '&highlight=row-' . $id
358
                );
359
            }
360
        }
361
    }
362
363
    private function loadDeleteForm(): void
364
    {
365
        $deleteForm = $this->createForm(
366
            DeleteType::class,
367
            ['id' => $this->record['id']],
368
            ['module' => $this->getModule()]
369
        );
370
        $this->template->assign('deleteForm', $deleteForm->createView());
371
    }
372
}
373