aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/forms/Form.php
blob: 36a2e7d0fb2c4be9ca468dc17ecf057d6fcae364 (plain)
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
<?php

namespace Studip\Forms;

class Form extends Part
{

    //models:
    protected $store_callbacks = [];

    //internals
    protected $inputs = [];
    protected $parts = [];
    protected $buttons = [];

    //appearance in html-form
    protected $url = null;
    protected $save_button_text = '';
    protected $save_button_name = 'STUDIPFORM_STORE_BUTTON';

    protected $cancel_button_text = '';
    protected $cancel_button_name = '';
    protected $autoStore = false;
    protected $debugmode = false;
    protected $success_message = '';

    protected $collapsable = false;
    protected $data_secure = true;

    //to identify a form element
    protected $id = null;

    /**
     * Creates a new Form object from a SORM object so that each field of the db-table becomes
     * an input-field of the form. You can modify the form by the params.
     * @param \SimpleORMap $object
     * @param array $params
     * @param string|null $url
     * @return Form
     */
    public static function fromSORM(\SimpleORMap $object, $params = [], $url = null)
    {
        $form = static::create();
        $form->addSORM($object, $params);
        if ($url) {
            $form->setURL($url);
        }
        return $form;
    }


    /**
     * A static constructor for an empty Form object.
     * @return Form
     */
    public static function create() : Form
    {
        $form = new static();
        return $form;
    }

    /**
     * Finalized constructor.
     *
     * @param mixed[] ...$parts
     */
    final public function __construct(...$parts)
    {
        parent::__construct(...$parts);
        //Set a default for the success message:
        $this->success_message = _('Daten wurden gespeichert.');
        \NotificationCenter::addObserver($this, 'validationStep', 'ActionDidPerform');
    }

    /**
     * Adds a new Fieldset to the Form object with the SORM object's fields as
     * input fields. These fields can be modified or specified by the $params array.
     * @param \SimpleORMap $object
     * @param array $params
     * @return Form $this
     */
    public function addSORM(\SimpleORMap $object, array $params = [])
    {
        $metadata = $object->getTableMetadata();

        // Normalize parameters
        $params = array_merge([
            'types'   => [],
            'fields'  => [],
            'without' => [],
        ], $params);

        if ($params['fields']) {
            //Setting the label
            foreach ($params['fields'] as $fieldname => $fielddata) {
                if (is_string($fielddata)) {
                    $params['fields'][$fieldname] = [
                        'label' => $fielddata
                    ];
                }
            }
            //Setting the type and name
            foreach ($params['fields'] as $fieldname => $fielddata) {
                if (is_array($fielddata)) {
                    $meta = $metadata['fields'][$fieldname] ?? null;
                    if (!isset($fielddata['type'])) {
                        if ($meta) {
                            $fielddata = array_merge(Input::getFielddataFromMeta($meta, $object), $fielddata);
                        } else {
                            $fielddata['type'] = 'text';
                        }

                        $params['fields'][$fieldname] = $fielddata;
                    }
                    $params['fields'][$fieldname]['name'] = $fieldname;
                }
            }
        } else {
            foreach ($metadata['fields'] as $attribute => $meta) {
                if (!in_array($attribute, (array) $params['without'])) {
                    $fielddata = [
                        'label' => $attribute
                    ];
                    $fielddata = array_merge(Input::getFielddataFromMeta($meta, $object), $fielddata);

                    $params['fields'][$attribute] = $fielddata;
                }
            }
        }
        foreach ($params['fields'] as $fieldname => $fielddata) {
            if (is_array($fielddata) && !array_key_exists('value', $fielddata)) {
                if (
                    $object->isField($fieldname)
                    || $object->isAdditionalField($fieldname)
                    || $object->isAliasField($fieldname)
                ) {
                    $params['fields'][$fieldname]['value'] = $object[$fieldname];
                }
            }
        }
        foreach ((array) $params['types'] as $fieldname => $type) {
            $params['fields'][$fieldname]['type'] = $type;
        }
        //respect the without param:
        foreach ((array) $params['without'] as $fieldname) {
            unset($params['fields'][$fieldname]);
        }
        $fields = $params['fields'];

        //Now initializing the fieldset:
        $fieldset = new Fieldset($params['legend'] ?: _("Daten"));
        $fieldset->setContextObject($object);
        $this->addPart($fieldset);

        foreach ($fields as $fieldname => $fielddata) {
            if (is_array($fielddata)) {
                $fieldset->addInput($fieldset->getInputFromArray($fielddata));
            } elseif(is_subclass_of($fielddata, Part::class)) {
                $fieldset->addPart($fielddata);
            } elseif(is_subclass_of($fielddata, Input::class)) {
                $fieldset->addInput($fielddata);
            }
        }
        return $this;
    }

    /**
     * Sets the URL where the Form should be leading after submitting.
     * @param $url
     * @return Form $this
     */
    public function setURL($url)
    {
        $this->url = $url;
        return $this;
    }

    /**
     * Returns the URL where the Form is leading to after the submit.
     * @return string|null
     */
    public function getURL()
    {
        return $this->url;
    }

    /**
     * Sets the text for the "save" button in the form.
     *
     * @param string $text The text for the button to save the form.
     * @return $this
     */
    public function setSaveButtonText(string $text): Form
    {
        $this->save_button_text = $text;
        return $this;
    }

    /**
     * @return string The text for the "save" button in the form.
     */
    public function getSaveButtonText() : string
    {
        return $this->save_button_text ?: _('Speichern');
    }

    public function setSaveButtonName(string $name): Form
    {
        $this->save_button_name = $name;
        return $this;
    }

    public function getSaveButtonName() : string
    {
        return $this->save_button_name ?: $this->getSaveButtonText();
    }

    public function setCancelButtonText(string $text): Form
    {
        $this->cancel_button_text = $text;
        return $this;
    }

    /**
     * @return string The text for the "save" button in the form.
     */
    public function getCancelButtonText() : string
    {
        return $this->cancel_button_text ?: _('Abbrechen');
    }

    public function setCancelButtonName(string $name): Form
    {
        $this->cancel_button_name = $name;
        return $this;
    }

    public function getCancelButtonName() : string
    {
        return $this->cancel_button_name ?: $this->getCancelButtonText();
    }

    public function setSuccessMessage(string $success_message): Form
    {
        $this->success_message = $success_message;
        return $this;
    }

    public function setDebugMode(bool $debug = true): Form
    {
        $this->debugmode = $debug;
        return $this;
    }

    public function getDebugMode(): bool
    {
        return $this->debugmode;
    }

    public function getSuccessMessage() : string
    {
        return $this->success_message;
    }

    public function setCollapsable($collapsing = true)
    {
        $this->collapsable = $collapsing;
        return $this;
    }

    public function isCollapsable()
    {
        return $this->collapsable;
    }

    /**
     * Stores the Form object if this is a POST-request. This also erases the URL so that the auto-save URL
     * will be set automatically to the current $_SERVER['REQUEST_URI'].
     * @return $this
     * @throws \AccessDeniedException
     */
    public function autoStore()
    {
        $this->autoStore = true;
        if (
             \Request::isPost()
             && \Request::isAjax()
             && !\Request::isDialog()
             && \Request::submitted('STUDIPFORM_AUTOSTORE')
        ) {
            if (\Request::submitted('STUDIPFORM_SERVERVALIDATION')) {
                $this->validate();
            } else {
                //storing the input
                $this->store();
                if ($this->success_message) {
                    \PageLayout::postSuccess($this->success_message);
                }
                page_close();
                die();
            }
        }
        return $this;
    }

    public function validate()
    {
        if (\Request::isPost() && \Request::submitted('STUDIPFORM_SERVERVALIDATION')) {
            //verify the user input:
            $output = [];
            foreach ($this->getAllInputs() as $input) {
                if ($input->hasValidation()) {
                    $callback = $input->getValidationCallback();
                    $value = $this->getStorableValueFromRequest($input);
                    $valid = $callback($value, $input);
                    if ($valid !== true) {
                        $output[$input->getName()] = [
                            'name' => $input->getName(),
                            'label' => $input->getTitle(),
                            'error' => $valid,
                        ];
                    }
                }
            }
            header('Content-Type: application/json');
            echo json_encode($output);
            page_close();
            die();
        }
        return $this;
    }

    public function isAutoStoring()
    {
        return $this->autoStore;
    }

    /**
     * Adds a callback function that is executed right after the store-method. That callback receives this
     * Form object as the only parameter.
     * @param callable $c
     * @return Form $this
     */
    public function addStoreCallback(Callable $c): Form
    {
        $this->store_callbacks[] = $c;
        return $this;
    }

    /**
     * Sets if the form should be secured against accidental leaving of the page. Standard is on.
     * @param $data_secure
     * @return $this
     */
    public function setDataSecure($data_secure)
    {
        $this->data_secure = $data_secure;
        return $this;
    }

    public function getDataSecure() {
        return $this->data_secure;
    }

    /**
     * Sets the ID if this form. This ID is only relevant for plugins to identify this Form object.
     * @param string|null $id
     * @return Form $this
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * Returns the ID if this form. This ID is only relevant for plugins to identify this Form object.
     * @return string|null
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns the number of storing processes
     * @return: a number of storing processes. 0 if nothing was stored.
     */
    public function store()
    {
        if (!\CSRFProtection::verifyRequest()) {
            throw new \AccessDeniedException();
        }
        \NotificationCenter::postNotification('FormWillStore', $this);

        $stored = 0;

        foreach ($this->getAllInputs() as $input) {
            if ($input->hasValidation()) {
                $callback = $input->getValidationCallback();
                $value = $this->getStorableValueFromRequest($input);
                $valid = $callback($value, $input);
                if ($valid !== true) {
                    return $stored;
                }
            }
        }

        //store by each input
        $all_values = [];
        foreach ($this->getAllInputs() as $input) {
            $value = $this->getStorableValueFromRequest($input);
            $callback = $this->getStoringCallback($input);
            if (is_callable($callback)) {
                $stored += $callback($value, $input);
            }
            $all_values[$input->getName()] = $value;
        }
        foreach ($this->parts as $part) {
            $context = $part->getContextObject();
            if ($context && method_exists($context, 'store')) {
                $stored += $context->store();
            }
        }

        foreach ($this->store_callbacks as $callback) {
            if (is_callable($callback)) {
                $stored += call_user_func($callback, $this, $all_values);
            } else {
                //throw warning if callback is not available:
                if ($callback === null) {
                    $callback = 'NULL';
                }
                trigger_error(sprintf('Could not execute callback %s in Form object.', $callback), E_USER_WARNING);
            }
        }
        return $stored;
    }

    /**
     * Adds a Part object to this form like a fieldset
     * @param Part $part
     * @return Form|void
     */
    public function addPart(Part $part)
    {
        $part->setParent($this);
        $this->parts[] = $part;
    }

    /**
     * Returns all the Part objects like Fieldsets as an array.
     * @return Part[]
     */
    public function getParts() : array
    {
        return $this->parts;
    }

    /**
     * Returns the last part of the form. If there is none yet, it will create a fieldset and return that.
     * @return Part
     */
    public function getLastPart() : Part
    {
        if (count($this->parts) === 0) {
            $this->parts[] = new Fieldset();
        }
        return $this->parts[count($this->parts) - 1];
    }

    /**
     * Adds a Studip-Button object to the footer of the dialog.
     * @param \Studip\Button $button
     * @return Form
     */
    public function addButton(\Studip\Button $button) : Form
    {
        $this->buttons[] = $button;
        return $this;
    }

    /**
     * Returns the additional buttons (except the save-button) as an array of \Studip\Button objects
     * @return array
     */
    public function getButtons() : array
    {
        return $this->buttons;
    }

    /**
     * Renders the whole form as a string.
     * @return string
     * @throws \Flexi\TemplateNotFoundException
     */
    public function render()
    {
        \NotificationCenter::postNotification('FormWillRender', $this);
        $template = $GLOBALS['template_factory']->open('forms/form');
        $template->form = $this;
        return $template->render();
    }

    /**
     * Returns the function to be used to store the value into the input. If the given Input has no storing
     * function it will generate a Closuer to set the value to the SimpleORMap context object.
     * @param $input
     * @return \Closure|void
     */
    protected function getStoringCallback(Input $input)
    {
        if ($input->store) {
            return $input->store;
        }
        $context = $input->getParent()->getContextObject();
        if (
            $context
            && is_subclass_of($context, \SimpleORMap::class)
            && (
                $context->isField($input->getName())
                || $context->isAdditionalField($input->getName())
                || $context->isAliasField($input->getName())
                || $context->isRelation($input->getName())
            )
        ) {
            return function ($value) use ($context, $input) {
                if ($context && !$value && $value !== null) {
                    $metadata = $context->getTableMetadata();
                    if (
                        isset($metadata['fields'][$input->getName()]['null'])
                        && $metadata['fields'][$input->getName()]['null'] === 'YES'
                    ) {
                        //sets the value to null if this is a feasible db value for this field:
                        $value = null;
                    }
                }
                $context[$input->getName()] = $value;
            };
        }
    }

    /**
     * Returns the value for the Input object from the $_REQUEST. This value will also be mapped by
     * the Input's dataMapper function and after that by a special mapper-callback the Input
     * probably has.
     * @param Input $input
     * @return mixed
     */
    protected function getStorableValueFromRequest(Input $input)
    {
        $requestparam = $input->getName();
        $bracket_pos = strpos($requestparam, "[");
        if ($bracket_pos !== false) {
            $requestparam = substr($requestparam, 0, $bracket_pos);
            $value = \Request::getArray($requestparam);
            foreach ($value as $i => $v) {
                $value[$i] = $input->dataMapper($v);
            }
        } else {
            $value = $input->getRequestValue();
            $value = $input->dataMapper($value);
        }
        if ($input->mapper && is_callable($input->mapper)) {
            $mapper = $input->mapper;
            $value = $mapper($value, $input->getContextObject());
        }
        return $value;
    }
}