-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathHtmlForm.php
1266 lines (1147 loc) · 37.9 KB
/
HtmlForm.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
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file htmlform.php
* @brief htmlform class and autoloader
*
* @author Frank Hellenkamp <[email protected]>
* @author Sebastian Reinhold <[email protected]>
*
* @copyright this is the copyright
* @license http://www.gnu.org/licenses/gpl-2.0.html GPL2
* @license http://www.spdx.org/licenses/MIT MIT License
**/
// {{{ namespace
/**
* @namespace depage
* @brief depage cms
*
* @namespace Depage::HtmlForm
* @brief htmlform class and autoloader
*
* @namespace Depage::HtmlForm::Abstracts
* @brief Abstract element classes
*
* @namespace Depage::HtmlForm::Elements
* @brief Classes for HTML input-elements
*
* All Classes in this namespace are HTML input-elements that can be added to
* instances of the @link Depage::HtmlForm::HtmlForm HtmlForm-class@endlink,
* but also to also to @link Depage::HtmlForm::Elements::Fieldset fieldsets@endlink
* and @link Depage::HtmlForm::Elements::Step steps@endlink:
*
* These are the most used elements that are added to the form with the add-method:
*
* @code
<?php
$form = new Depage\HtmlForm\HtmlForm('simpleForm');
// input[type=text]
$input = $form->addText('input', array('label' => 'Normal Input'));
// input[type=email]
$form->addEmail('email', array('label' => 'Email Input'));
// input[type=url]
$form->addEmail('url', array('label' => 'URL Input'));
// input[type=password]
$form->addPassword('password', array('label' => 'Password Input'));
// input[type=date]
$form->addDate('date', array('label' => 'Date Input'));
// input[type=number]
$form->addNumber('number', array('label' => 'Number Input'));
@endcode
*
* @namespace Depage::HtmlForm::Exceptions
* @brief HtmlForm exceptions
*
* @namespace Depage::HtmlForm::Validators
* @brief Validators for HTML input-elements
**/
namespace Depage\HtmlForm;
// }}}
// {{{ autoloader
/**
* @brief PHP autoloader
*
* Autoloads classes by namespace. (requires PHP >= 5.3)
**/
function autoload($class)
{
$class = str_replace('\\', '/', str_replace(__NAMESPACE__ . '\\', '', $class));
$file = __DIR__ . '/' . $class . '.php';
if (file_exists($file)) {
require_once($file);
}
}
spl_autoload_register(__NAMESPACE__ . '\autoload');
// }}}
/**
* @brief main interface to users
*
* The class HtmlForm is the main tool of the htmlform library. It generates
* input elements and container elements. It also contains the PHP session
* handlers.
*
* When you use <em>depage-forms</em> this is probably the only class you will
* instantiate directly.
*
* In general:
*
* @code
<?php
$form = new Depage\HtmlForm\HtmlForm('simpleForm');
// add form fields
$form->addText('username', array('label' => 'User name', 'required' => true));
$form->addEmail('email', array('label' => 'Email address'));
// process form
$form->process();
if ($form->validate()) {
// do something with your valid data
var_dump($form->getValues());
} else {
// Form was empty or data was not valid:
// Display the form.
echo ($form);
}
@endcode
*
* You can find a list of available input-class in @link Depage::HtmlForm::Elements
* elements@endlink.
**/
class HtmlForm extends Abstracts\Container
{
// {{{ constants
public const priorityCountries = [
'en' => ['us','gb','ie','au','nz'],
'de' => ['de','at','ch'],
'fr' => ['fr','ch','be','lu','ca'],
'it' => ['it','ch'],
];
// }}}
// {{{ variables
/**
* @brief HTML form method attribute
**/
protected $method;
/**
* @brief url of the current page
**/
protected $url;
/**
* @brief HTML form action attribute
**/
protected $submitURL;
/**
* @brief Specifies where the user is redirected to, once the form-data is valid
**/
protected $successURL;
/**
* @brief Specifies where the user is redirected to, once the form-data is cancelled
**/
protected $cancelURL;
/**
* @brief Contains the submit button label of the form
**/
protected $label;
/**
* @brief Contains the back button label of the form
**/
protected $backLabel;
/**
* @brief Contains the cancel button label of the form
**/
protected $cancelLabel;
/**
* @brief Contains the additional class value of the form
**/
protected $class;
/**
* @brief Contains the validator function of the form
**/
protected $validator;
/**
* @brief Contains the javascript validation type of the form
**/
protected $jsValidation;
/**
* @brief Contains the javascript autosave type of the form
**/
protected $jsAutosave;
/**
* @brief Contains the name of the array in the PHP session, holding the form-data
**/
protected $sessionSlotName;
/**
* @brief PHP session handle
**/
protected $sessionSlot;
/**
* @brief Contains current step number
**/
private $currentStepId;
/**
* @brief Contains array of step object references
**/
private $steps = [];
/**
* @brief Time until session expiry (seconds)
**/
protected $ttl;
/**
* @brief Form validation result/status
**/
public $valid;
/**
* @brief true if form request is from autosave call
**/
public $isAutoSaveRequest = false;
/**
* @brief List of internal fieldnames that are not part of the results
**/
protected $internalFields = [
'formIsValid',
'formIsAutosaved',
'formName',
'formTimestamp',
'formStep',
'formFinalPost',
'formCsrfToken',
'formCaptcha',
];
/**
* @brief Namespace strings for addible element classes
**/
protected $namespaces = ['\\Depage\\HtmlForm\\Elements'];
// }}}
// {{{ __construct()
/**
* @brief HtmlForm class constructor
*
* @param string $name form name
* @param array $parameters form parameters, HTML attributes
* @param object $form parent form object reference (not used in this case)
* @return void
**/
public function __construct(string $name, array $parameters = [], HtmlForm|null $form = null)
{
$this->isAutoSaveRequest = isset($_POST['formAutosave']) && $_POST['formAutosave'] === "true";
$this->url = parse_url($_SERVER['REQUEST_URI']);
parent::__construct($name, $parameters, $this);
$this->url = parse_url($this->submitURL);
if (empty($this->successURL)) {
$this->successURL = $this->submitURL;
}
if (empty($this->cancelURL)) {
$this->cancelURL = $this->submitURL;
}
$this->currentStepId = isset($_GET['step']) ? $_GET['step'] : 0;
$this->startSession();
$this->valid = (isset($this->sessionSlot['formIsValid'])) ? $this->sessionSlot['formIsValid'] : null;
// set CSRF Token
if (!isset($this->sessionSlot['formCsrfToken'])) {
$this->sessionSlot['formCsrfToken'] = $this->getNewCsrfToken();
}
if (!isset($this->sessionSlot['formFinalPost'])) {
$this->sessionSlot['formFinalPost'] = false;
}
// create a hidden input to tell forms apart
$this->addHidden('formName')->setValue($this->name);
// create hidden input for submitted step
$this->addHidden('formStep')->setValue($this->currentStepId);
// create hidden input for CSRF token
$this->addHidden('formCsrfToken')->setValue($this->sessionSlot['formCsrfToken']);
$this->addChildElements();
}
// }}}
// {{{ setDefaults()
/**
* @brief Collects initial values across subclasses.
*
* The constructor loops through these and creates settable class
* attributes at runtime. It's a compact mechanism for initialising
* a lot of variables.
*
* @return void
**/
protected function setDefaults(): void
{
parent::setDefaults();
$this->defaults['label'] = 'submit';
$this->defaults['cancelLabel'] = '';
$this->defaults['backLabel'] = '';
$this->defaults['class'] = '';
$this->defaults['method'] = 'post';
// @todo adjust submit url for steps when used
$this->defaults['submitURL'] = $_SERVER['REQUEST_URI'];
$this->defaults['successURL'] = null;
$this->defaults['cancelURL'] = null;
$this->defaults['validator'] = null;
$this->defaults['ttl'] = 60 * 60; // 60 minutes
$this->defaults['jsValidation'] = 'blur';
$this->defaults['jsAutosave'] = 'false';
}
// }}}
// {{{ startSession()
/**
* @brief Start session when there is no current session yet
*
* Starts a new session if there is no session, sets the session slot
* and also calls the session expiry handler.
*
* @return void
**/
private function startSession()
{
// check if there's an open session
if (!session_id()) {
$params = session_get_cookie_params();
$sessionName = session_name();
session_set_cookie_params(
$this->ttl,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly'],
);
session_start();
// Extend the expiration time upon page load
if (isset($_COOKIE[$sessionName])) {
setcookie(
$sessionName,
$_COOKIE[$sessionName],
time() + $this->ttl,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly'],
);
}
}
$this->sessionSlotName = 'htmlform-' . $this->name . '-data';
$this->sessionSlot = & $_SESSION[$this->sessionSlotName];
$this->sessionExpiry();
}
// }}}
// {{{ sessionExpiry()
/**
* @brief Deletes session when it expires.
*
* checks if session lifetime exceeds ttl value and deletes it. Updates
* timestamp.
*
* @return void
**/
private function sessionExpiry()
{
if (isset($this->ttl) && is_numeric($this->ttl)) {
$timestamp = time();
if (
isset($this->sessionSlot['formTimestamp'])
&& ($timestamp - $this->sessionSlot['formTimestamp'] > $this->ttl)
) {
$this->clearSession();
$this->sessionSlot = & $_SESSION[$this->sessionSlotName];
}
$this->sessionSlot['formTimestamp'] = $timestamp;
}
}
// }}}
// {{{ isEmpty()
/**
* @brief Returns wether form has been submitted before or not.
*
* @return bool session status
**/
public function isEmpty()
{
return !isset($this->sessionSlot['formName']);
}
// }}}
// {{{ getNewCsrfToken()
/**
* @brief Returns new XSRF token
*
* @return array element objects
**/
protected function getNewCsrfToken()
{
return base64_encode(openssl_random_pseudo_bytes(16));
}
// }}}
// {{{ addElement()
/**
* @brief Adds input or fieldset elements to htmlform.
*
* Calls parent class to generate an input element or a fieldset and add
* it to its list of elements.
*
* @param string $type input type or fieldset
* @param string $name name of the element
* @param array $parameters element attributes: HTML attributes, validation parameters etc.
* @return object $newElement element object
**/
protected function addElement(string $type, string $name, array $parameters): Abstracts\Element
{
$this->checkElementName($name);
$newElement = parent::addElement($type, $name, $parameters);
if ($newElement instanceof Elements\Step) {
$this->steps[] = $newElement;
}
if ($newElement instanceof Abstracts\Input) {
$this->updateInputValue($name);
}
return $newElement;
}
// }}}
// {{{ checkElementName()
/**
* @brief Checks for duplicate subelement names.
*
* Checks within the form if an input element or fieldset name is already
* taken. If so, it throws an exception.
*
* @param string $name name to check
* @return void
**/
public function checkElementName(string $name): void
{
foreach ($this->getElements(true) as $element) {
if ($element->getName() === $name) {
throw new Exceptions\DuplicateElementNameException("Element name \"{$name}\" already in use.");
}
}
}
// }}}
// {{{ getCurrenElements()
/**
* @brief Returns an array of input elements contained in the current step.
*
* @return array element objects
**/
private function getCurrentElements(): array
{
$currentElements = [];
foreach ($this->elements as $element) {
if ($element instanceof Abstracts\Container) {
if (
!($element instanceof Elements\Step)
|| (isset($this->steps[$this->currentStepId]) && ($element == $this->steps[$this->currentStepId]))
) {
$currentElements = array_merge($currentElements, $element->getElements());
}
} else {
$currentElements[] = $element;
}
}
return $currentElements;
}
// }}}
// {{{ registerNamespace
/**
* @brief Stores element namespaces for adding
*
* @param string $nameSpace namespace name
* @return void
**/
public function registerNamespace(string $namespace): void
{
$this->namespaces[] = $namespace;
}
// }}}
// {{{ getNamespaces
/**
* @brief Returns list of registered namespaces
*
* @return array
**/
public function getNamespaces(): array
{
return $this->namespaces;
}
// }}}
// {{{ inCurrentStep()
/**
* @brief Checks if the element named $name is in the current step.
*
* @param string $name name of element
* @return bool says wether it's in the current step
**/
private function inCurrentStep(string $name): bool
{
return in_array($this->getElement($name), $this->getCurrentElements());
}
// }}}
// {{{ setCurrentStep()
/**
* @brief Validates step number of GET request.
*
* Validates step number of the GET request. If it's out of range it's
* reset to the number of the first invalid step. (only to be used after
* the form is completely created, because the step elements have to be
* counted)
*
* @return void
**/
public function setCurrentStep(int|null $step = null): void
{
if (!is_null($step)) {
$this->currentStepId = $step;
}
if (!is_numeric($this->currentStepId)
|| ($this->currentStepId > count($this->steps) - 1)
|| ($this->currentStepId < 0)
) {
$this->currentStepId = $this->getFirstInvalidStep();
}
}
// }}}
// {{{ getUrl()
public function getUrl(): array
{
return $this->url;
}
// }}}
// {{{ getSteps()
/**
* @brief Returns an array of steps
*
* @return array step objects
**/
public function getSteps(): array
{
return $this->steps;
}
// }}}
// {{{ getCurrentStepId()
/**
* @brief Returns the current step id
*
* @return int current step
**/
public function getCurrentStepId(): int
{
return $this->currentStepId;
}
// }}}
// {{{ getFirstInvalidStep()
/**
* @brief Returns first step that didn't pass validation.
*
* Checks steps consecutively and returns the number of the first one that
* isn't valid (steps need to be submitted at least once to count as valid).
* Form must have been validated before calling this method.
*
* @return int $stepNumber number of first invalid step
**/
public function getFirstInvalidStep(): int
{
if (count($this->steps) > 0) {
foreach ($this->steps as $stepNumber => $step) {
if (!$step->validate()) {
return $stepNumber;
}
}
/**
* If there aren't any invalid steps there must be a fieldset
* directly attached to the form that's invalid. In this case we
* don't want to jump back to the first step. Hence, this little
* hack.
**/
return count($this->steps) - 1;
} else {
return 0;
}
}
// }}}
// {{{ buildUrl()
/**
* @brief Builds URL from parts
*
* @return new URL
**/
public function buildUrl(array $args = []): string
{
$url = isset($this->url['scheme']) ? $this->url['scheme'] . '://' : '';
$url .= $this->url['host'] ?? '';
$url .= isset($this->url['port']) ? ':' . $this->url['port'] : '';
$url .= $this->url['path'] ?? '';
$url .= $this->buildUrlQuery($args);
return $url;
}
// }}}
// {{{ buildUrlQuery()
/**
* @brief Adding step parameter to already existing query
*
* @return new query
**/
public function buildUrlQuery(array $args = []): string
{
$query = '';
$queryParts = [];
if (isset($this->url['query']) && $this->url['query'] != "") {
//decoding query string
$query = html_entity_decode($this->url['query']);
//parsing the query into an array
parse_str($query, $queryParts);
}
foreach ($args as $name => $value) {
if ($value != "") {
$queryParts[$name] = $value;
} elseif (isset($queryParts[$name])) {
unset($queryParts[$name]);
}
}
// build the query again
$query = http_build_query($queryParts);
if ($query == "") {
return "";
}
return "?" . $query;
}
// }}}
// {{{ updateInputValue()
/**
* @brief Updates the value of an associated input element
*
* Sets the input elements' value. If there is post-data - we'll use that
* to update the value of the input element and the session. If not - we
* take the value that's already in the session. If the value is neither in
* the session nor in the post-data - nothing happens.
*
* @param string $name name of the input element
* @return void
**/
public function updateInputValue(string $name): void
{
$element = $this->getElement($name);
// handle captcha phrase
if ($this->getElement($name) instanceof Elements\Captcha) {
$element->setSessionSlot($this->sessionSlot);
}
// if it's a post, take the value from there and save it to the session
if (
isset($_POST['formName']) && ($_POST['formName'] === $this->name)
&& $this->inCurrentStep($name)
&& isset($_POST['formCsrfToken']) && $_POST['formCsrfToken'] === $this->sessionSlot['formCsrfToken']
) {
if ($this->getElement($name) instanceof Elements\File) {
// handle uploaded file
$oldValue = isset($this->sessionSlot[$name]) ? $this->sessionSlot[$name] : null;
$this->sessionSlot[$name] = $element->handleUploadedFiles($oldValue);
} elseif (!$element->getDisabled()) {
// save value
$value = isset($_POST[$name]) ? $_POST[$name] : null;
$this->sessionSlot[$name] = $element->setValue($value);
} elseif (!isset($this->sessionSlot[$name])) {
// set default value for disabled elements
$this->sessionSlot[$name] = $element->setValue($element->getDefaultValue());
}
}
// if it's not a post, try to get the value from the session
elseif (isset($this->sessionSlot[$name])) {
$element->setValue($this->sessionSlot[$name]);
}
}
// }}}
// {{{ clearInputValue()
/**
* @brief clearInputValue
*
* @param mixed $name
* @return void
**/
public function clearInputValue(string $name): void
{
$element = $this->getElement($name);
$this->sessionSlot[$name] = $element->clearValue();
}
// }}}
// {{{ populate()
/**
* @brief Fills subelement values.
*
* Allows to manually populate the forms' input elements with values by
* parsing an array of name-value pairs.
*
* @param array $data input element names (key) and values (value)
* @return void
**/
public function populate(array|object $data = []): void
{
foreach ($this->getElements() as $element) {
$name = $element->name;
if (!in_array($name, $this->internalFields)) {
if (is_array($data) && isset($data[$name])) {
$value = $data[$name];
} elseif (is_object($data) && isset($data->$name)) {
$value = $data->$name;
}
if (isset($value)) {
$element->setDefaultValue($value);
if ($element->getDisabled() && !isset($this->sessionSlot[$name])) {
$this->sessionSlot[$name] = $value;
}
}
unset($value);
}
}
}
// }}}
// {{{ process()
/**
* @brief Calls form validation and handles redirects.
*
* Implememts the Post/Redirect/Get strategy. Redirects to success Address
* on succesful validation otherwise redirects to first invalid step or
* back to form.
*
* @return void
*
* @see validate()
**/
public function process(): void
{
$this->setCurrentStep();
// if there's post-data from this form
if (isset($_POST['formName']) && ($_POST['formName'] === $this->name)) {
// save in session if submission was from last step
$this->sessionSlot['formFinalPost'] = count($this->steps) == 0 || $_POST['formStep'] + 1 == count($this->steps)
&& !$this->isAutoSaveRequest;
if (!empty($this->cancelLabel) && isset($_POST['formSubmit']) && $_POST['formSubmit'] === $this->cancelLabel) {
// cancel button was pressed
$this->clearSession();
$this->redirect($this->cancelURL);
} elseif ($this->isAutoSaveRequest) {
// do not redirect -> is autosave
$this->onPost();
} elseif (!empty($this->backLabel) && isset($_POST['formSubmit']) && $_POST['formSubmit'] === $this->backLabel) {
// back button was pressed
$this->onPost();
$this->sessionSlot['formFinalPost'] = false;
$prevStep = $this->currentStepId - 1;
if ($prevStep < 0) {
$prevStep = 0;
}
$this->redirect($this->buildUrl(['step' => ($prevStep <= 0) ? '' : $prevStep]));
} elseif ($this->validate()) {
// form was successfully submitted
$this->onPost();
$this->redirect($this->successURL);
} else {
// goto to next step or display first invalid step
$this->onPost();
$nextStep = $this->currentStepId + 1;
$firstInvalidStep = $this->getFirstInvalidStep();
if ($nextStep > $firstInvalidStep) {
$nextStep = $firstInvalidStep;
}
if ($nextStep > count($this->steps)) {
$nextStep = count($this->steps) - 1;
}
$this->redirect($this->buildUrl(['step' => ($nextStep == 0) ? '' : $nextStep]));
}
}
}
// }}}
// {{{ validate()
/**
* @brief Validates the forms subelements.
*
* Form validation - validates form elements returns validation result and
* writes it to session. Also calls custom validator if available.
*
* @return bool validation result
*
* @see process()
**/
public function validate(): bool
{
// onValidate hook for custom required/validation rules
$this->valid = $this->onValidate();
$this->valid = $this->valid && $this->validateAutosave();
if ($this->valid && !is_null($this->validator)) {
if (is_callable($this->validator)) {
$this->valid = call_user_func($this->validator, $this, $this->getValues());
} else {
throw new exceptions\validatorNotCallable("The validator paramater must be callable");
}
}
$this->valid = $this->valid && $this->sessionSlot['formFinalPost'];
// save validation-state in session
$this->sessionSlot['formIsValid'] = $this->valid;
return $this->valid;
}
// }}}
// {{{ onPost()
/**
* @brief onPost hook
*
* Can be overridden to run a custom method when form is posted
*
* @return targetUrl
*
* @see process()
**/
protected function onPost(): bool
{
return true;
}
// }}}
// {{{ onValidate()
/**
* @brief Validation hook
*
* Can be overridden with custom validation rules, field-required rules etc.
*
* @return void
*
* @see validate()
**/
protected function onValidate(): bool
{
return true;
}
// }}}
// validateAutosave() {{{
/**
* If the form is autosaving the validation property is defaulted to false.
*
* This function returns the actual state of input validation.
* It can therefore be used to test autosave fields are correct without forcing
* the form save.
*
* @return bool $partValid - whether the autosave postback data is valid
*/
public function validateAutosave(): bool
{
parent::validate();
if (isset($_POST['formCsrfToken'])) {
$hasCorrectToken = $_POST['formCsrfToken'] === $this->sessionSlot['formCsrfToken'];
$this->valid = $this->valid && $hasCorrectToken;
if (!$hasCorrectToken) {
http_response_code(400);
$this->log("HtmlForm: Requst invalid because of incorrect CsrfToken");
}
}
$partValid = $this->valid;
// save data in session when autosaving but don't validate successfully
if ($this->isAutoSaveRequest
|| (isset($this->sessionSlot['formIsAutosaved'])
&& $this->sessionSlot['formIsAutosaved'] === true)
) {
$this->valid = false;
}
// save whether form was autosaved the last time
$this->sessionSlot['formIsAutosaved'] = $this->isAutoSaveRequest;
return $partValid;
}
// }}}
// {{{ getValues()
/**
* @brief Gets form-data from current PHP session.
*
* @return array form-data
**/
public function getValues(): ?array
{
if (isset($this->sessionSlot)) {
// remove internal attributes from values
return array_diff_key($this->sessionSlot, array_fill_keys($this->internalFields, ''));
} else {
return null;
}
}
// }}}
// {{{ getValuesWithLabel()
/**
* @brief Gets form-data from current PHP session but also contain elemnt labels.
*
* @return array form-data with labels
**/
public function getValuesWithLabel(): ?array
{
//get values first
$values = $this->getValues();
$valuesWithLabel = [];
if (isset($values)) {
foreach ($values as $element => $value) {
$elem = $this->getElement($element);
if ($elem) {
$valuesWithLabel[$element] = [
"value" => $value,
"label" => $elem->getLabel(),
];
}
}
return $valuesWithLabel;
} else {
return null;
}
}
// }}}
// {{{ redirect()
/**
* @brief Redirects Browser to a different URL.
*
* @param string $url url to redirect to
*/
public function redirect(string $url): void
{
header('Location: ' . $url);
die("Tried to redirect you to <a href=\"$url\">$url</a>");
}
// }}}
// {{{ clearSession()
/**
* @brief Deletes the current forms' PHP session data.
*
* @param bool $clearCsrfToken whether to clear complete form or just the data values and to keep csrf-token.
*
* @return void
**/
public function clearSession(bool $clearCsrfToken = true): void
{
if ($clearCsrfToken) {
// clear everything
$this->clearValue();