/
Form.php
732 lines (657 loc) · 19.6 KB
/
Form.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
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Web;
use LogicException;
use Zend_Config;
use Zend_Form;
use Zend_View_Interface;
use Icinga\Application\Icinga;
use Icinga\Web\Form\Decorator\NoScriptApply;
use Icinga\Web\Form\Element\CsrfCounterMeasure;
/**
* Base class for forms providing CSRF protection, confirmation logic and auto submission
*
* @method $this setDefaults(array $defaults) {
* Use `Form::populate()' for setting default values for elements instead because `Form::setDefaults()' does not
* create the form via `Form::create()'.
*
* Due to a BC introduced with https://github.com/mhujer/zf1/commit/244e3d3f88a363ee0ca49cf63eee31f925f515cd
* we cannot override this function without running into a strict standards violation on Zend version 1.12.7.
*
* @param array $defaults
*
* @return $this
* }
*/
class Form extends Zend_Form
{
/**
* Whether this form has been created
*
* @var bool
*/
protected $created = false;
/**
* The callback to call instead of Form::onSuccess()
*
* @var Callback
*/
protected $onSuccess;
/**
* Label to use for the standard submit button
*
* @var string
*/
protected $submitLabel;
/**
* The url to redirect to upon success
*
* @var string|Url
*/
protected $redirectUrl;
/**
* The view script to use when rendering this form
*
* @var string
*/
protected $viewScript;
/**
* Whether this form should NOT add random generated "challenge" tokens that are associated with the user's current
* session in order to prevent Cross-Site Request Forgery (CSRF). It is the form's responsibility to verify the
* existence and correctness of this token
*
* @var bool
*/
protected $tokenDisabled = false;
/**
* Name of the CSRF token element
*
* @var string
*/
protected $tokenElementName = 'CSRFToken';
/**
* Whether this form should add a UID element being used to distinct different forms posting to the same action
*
* @var bool
*/
protected $uidDisabled = false;
/**
* Name of the form identification element
*
* @var string
*/
protected $uidElementName = 'formUID';
/**
* Default element decorators
*
* @var array
*/
public static $defaultElementDecorators = array(
'ViewHelper',
'Errors',
array('Description', array('tag' => 'span', 'class' => 'description')),
'Label',
array('HtmlTag', array('tag' => 'div'))
);
/**
* Create a new form
*
* Accepts an additional option `onSuccess' which is a callback that is called instead of this
* form's method. It is called using the following signature: (Request $request, Form $form).
*
* @see Zend_Form::__construct()
*
* @throws LogicException In case `onSuccess' is not callable
*/
public function __construct($options = null)
{
if (is_array($options) && isset($options['onSuccess'])) {
$this->onSuccess = $options['onSuccess'];
unset($options['onSuccess']);
} elseif (isset($options->onSuccess)) {
$this->onSuccess = $options->onSuccess;
unset($options->onSuccess);
}
if ($this->onSuccess !== null && false === is_callable($this->onSuccess)) {
throw new LogicException('The option `onSuccess\' is not callable');
}
parent::__construct($options);
}
/**
* Set the label to use for the standard submit button
*
* @param string $label The label to use for the submit button
*
* @return self
*/
public function setSubmitLabel($label)
{
$this->submitLabel = $label;
return $this;
}
/**
* Return the label being used for the standard submit button
*
* @return string
*/
public function getSubmitLabel()
{
return $this->submitLabel;
}
/**
* Set the url to redirect to upon success
*
* @param string|Url $url The url to redirect to
*
* @return self
*/
public function setRedirectUrl($url)
{
$this->redirectUrl = $url;
return $this;
}
/**
* Return the url to redirect to upon success
*
* @return string|Url
*/
public function getRedirectUrl()
{
if ($this->redirectUrl === null) {
$url = Url::fromRequest(array(), $this->getRequest());
// Be sure to remove all form dependent params because we do not want to submit it again
$this->redirectUrl = $url->without(array_keys($this->getElements()));
}
return $this->redirectUrl;
}
/**
* Set the view script to use when rendering this form
*
* @param string $viewScript The view script to use
*
* @return self
*/
public function setViewScript($viewScript)
{
$this->viewScript = $viewScript;
return $this;
}
/**
* Return the view script being used when rendering this form
*
* @return string
*/
public function getViewScript()
{
return $this->viewScript;
}
/**
* Disable CSRF counter measure and remove its field if already added
*
* @param bool $disabled Set true in order to disable CSRF protection for this form, otherwise false
*
* @return self
*/
public function setTokenDisabled($disabled = true)
{
$this->tokenDisabled = (bool) $disabled;
if ($disabled && $this->getElement($this->tokenElementName) !== null) {
$this->removeElement($this->tokenElementName);
}
return $this;
}
/**
* Return whether CSRF counter measures are disabled for this form
*
* @return bool
*/
public function getTokenDisabled()
{
return $this->tokenDisabled;
}
/**
* Set the name to use for the CSRF element
*
* @param string $name The name to set
*
* @return self
*/
public function setTokenElementName($name)
{
$this->tokenElementName = $name;
return $this;
}
/**
* Return the name of the CSRF element
*
* @return string
*/
public function getTokenElementName()
{
return $this->tokenElementName;
}
/**
* Disable form identification and remove its field if already added
*
* @param bool $disabled Set true in order to disable identification for this form, otherwise false
*
* @return self
*/
public function setUidDisabled($disabled = true)
{
$this->uidDisabled = (bool) $disabled;
if ($disabled && $this->getElement($this->uidElementName) !== null) {
$this->removeElement($this->uidElementName);
}
return $this;
}
/**
* Return whether identification is disabled for this form
*
* @return bool
*/
public function getUidDisabled()
{
return $this->uidDisabled;
}
/**
* Set the name to use for the form identification element
*
* @param string $name The name to set
*
* @return self
*/
public function setUidElementName($name)
{
$this->uidElementName = $name;
return $this;
}
/**
* Return the name of the form identification element
*
* @return string
*/
public function getUidElementName()
{
return $this->uidElementName;
}
/**
* Create this form
*
* @param array $formData The data sent by the user
*
* @return self
*/
public function create(array $formData = array())
{
if (false === $this->created) {
$this->createElements($formData);
$this->addFormIdentification()
->addCsrfCounterMeasure()
->addSubmitButton();
if ($this->getAction() === '') {
// We MUST set an action as JS gets confused otherwise, if
// this form is being displayed in an additional column
$this->setAction(Url::fromRequest()->without(array_keys($this->getElements())));
}
$this->created = true;
}
return $this;
}
/**
* Create and add elements to this form
*
* Intended to be implemented by concrete form classes.
*
* @param array $formData The data sent by the user
*/
public function createElements(array $formData)
{
}
/**
* Perform actions after this form was submitted using a valid request
*
* Intended to be implemented by concrete form classes. The base implementation returns always FALSE.
*
* @param Request $request The valid request used to process this form
*
* @return null|bool Return FALSE in case no redirect should take place
*/
public function onSuccess(Request $request)
{
return false;
}
/**
* Perform actions when no form dependent data was sent
*
* Intended to be implemented by concrete form classes.
*
* @param Request $request The current request
*/
public function onRequest(Request $request)
{
}
/**
* Add a submit button to this form
*
* Uses the label previously set with Form::setSubmitLabel(). Overwrite this
* method in order to add multiple submit buttons or one with a custom name.
*
* @return self
*/
public function addSubmitButton()
{
$submitLabel = $this->getSubmitLabel();
if ($submitLabel) {
$this->addElement(
'submit',
'btn_submit',
array(
'ignore' => true,
'label' => $submitLabel,
'decorators' => array(
'ViewHelper',
array('HtmlTag', array('tag' => 'div'))
)
)
);
}
return $this;
}
/**
* Add a subform
*
* @param Zend_Form $form The subform to add
* @param string $name The name of the subform or null to use the name of $form
* @param int $order The location where to insert the form
*
* @return Zend_Form
*/
public function addSubForm(Zend_Form $form, $name = null, $order = null)
{
if ($form instanceof self) {
$form->removeDecorator('Form');
$form->setSubmitLabel('');
$form->setTokenDisabled();
$form->setUidDisabled();
}
if ($name === null) {
$name = $form->getName();
}
return parent::addSubForm($form, $name, $order);
}
/**
* Create a new element
*
* Icinga Web 2 loads its own default element decorators. For loading Zend's default element decorators set the
* `disableLoadDefaultDecorators' option to any other value than `true'. For loading custom element decorators use
* the 'decorators' option.
*
* @param string $type String element type
* @param string $name The name of the element to add
* @param mixed $options The options for the element
*
* @return Zend_Form_Element
*
* @see Form::$defaultElementDecorators For Icinga Web 2's default element decorators.
*/
public function createElement($type, $name, $options = null)
{
if ($options !== null) {
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (! isset($options['decorators'])
&& ! array_key_exists('disabledLoadDefaultDecorators', $options)
) {
$options['decorators'] = static::$defaultElementDecorators;
}
} else {
$options = array('decorators' => static::$defaultElementDecorators);
}
$el = parent::createElement($type, $name, $options);
if ($el && $el->getAttrib('autosubmit')) {
$el->addDecorator(new NoScriptApply()); // Non-JS environments
$class = $el->getAttrib('class');
if (is_array($class)) {
$class[] = 'autosubmit';
} elseif ($class === null) {
$class = 'autosubmit';
} else {
$class .= ' autosubmit';
}
$el->setAttrib('class', $class); // JS environments
unset($el->autosubmit);
}
return $el;
}
/**
* Add a field with a unique and form specific ID
*
* @return self
*/
public function addFormIdentification()
{
if (false === $this->uidDisabled && $this->getElement($this->uidElementName) === null) {
$this->addElement(
'hidden',
$this->uidElementName,
array(
'ignore' => true,
'value' => $this->getName(),
'decorators' => array('ViewHelper')
)
);
}
return $this;
}
/**
* Add CSRF counter measure field to this form
*
* @return self
*/
public function addCsrfCounterMeasure()
{
if (false === $this->tokenDisabled && $this->getElement($this->tokenElementName) === null) {
$this->addElement(new CsrfCounterMeasure($this->tokenElementName));
}
return $this;
}
/**
* Populate the elements with the given values
*
* @param array $defaults The values to populate the elements with
*/
public function populate(array $defaults)
{
$this->create($defaults);
return parent::populate($defaults);
}
/**
* Process the given request using this form
*
* Redirects to the url set with setRedirectUrl() upon success. See onSuccess()
* and onRequest() wherewith you can customize the processing logic.
*
* @param Request $request The request to be processed
*
* @return Request The request supposed to be processed
*/
public function handleRequest(Request $request = null)
{
if ($request === null) {
$request = $this->getRequest();
}
$formData = $this->getRequestData($request);
if ($this->getUidDisabled() || $this->wasSent($formData)) {
$this->populate($formData); // Necessary to get isSubmitted() to work
if (! $this->getSubmitLabel() || $this->isSubmitted()) {
if ($this->isValid($formData)
&& (($this->onSuccess !== null && false !== call_user_func($this->onSuccess, $request, $this))
|| ($this->onSuccess === null && false !== $this->onSuccess($request)))) {
$this->getResponse()->redirectAndExit($this->getRedirectUrl());
}
} else {
// The form can't be processed but we want to show validation errors though
$this->isValidPartial($formData);
}
} else {
$this->onRequest($request);
}
return $request;
}
/**
* Return whether the submit button of this form was pressed
*
* When overwriting Form::addSubmitButton() be sure to overwrite this method as well.
*
* @return bool True in case it was pressed, False otherwise or no submit label was set
*/
public function isSubmitted()
{
if ($this->getSubmitLabel()) {
return $this->getElement('btn_submit')->isChecked();
}
return false;
}
/**
* Return whether the data sent by the user refers to this form
*
* Ensures that the correct form gets processed in case there are multiple forms
* with equal submit button names being posted against the same route.
*
* @param array $formData The data sent by the user
*
* @return bool Whether the given data refers to this form
*/
public function wasSent(array $formData)
{
return isset($formData[$this->uidElementName]) && $formData[$this->uidElementName] === $this->getName();
}
/**
* Return whether the given values (possibly incomplete) are valid
*
* Unlike Zend_Form::isValid() this will not set NULL as value for
* an element that is not present in the given data.
*
* @param array $formData The data to validate
*
* @return bool
*/
public function isValidPartial(array $formData)
{
$this->create($formData);
return parent::isValidPartial($formData);
}
/**
* Return whether the given values are valid
*
* @param array $formData The data to validate
*
* @return bool
*/
public function isValid($formData)
{
$this->create($formData);
return parent::isValid($formData);
}
/**
* Remove all elements of this form
*
* @return self
*/
public function clearElements()
{
$this->created = false;
return parent::clearElements();
}
/**
* Load the default decorators
*
* Overwrites Zend_Form::loadDefaultDecorators to avoid having
* the HtmlTag-Decorator added and to provide viewscript usage
*
* @return self
*/
public function loadDefaultDecorators()
{
if ($this->loadDefaultDecoratorsIsDisabled()) {
return $this;
}
$decorators = $this->getDecorators();
if (empty($decorators)) {
if ($this->viewScript) {
$this->addDecorator('ViewScript', array(
'viewScript' => $this->viewScript,
'form' => $this
));
} else {
$this->addDecorator('FormErrors', array('onlyCustomFormErrors' => true))
->addDecorator('FormElements')
//->addDecorator('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form'))
->addDecorator('Form');
}
}
return $this;
}
/**
* Return the name of this form
*
* @return string
*/
public function getName()
{
$name = parent::getName();
if (! $name) {
$name = get_class($this);
$this->setName($name);
$name = parent::getName();
}
return $name;
}
/**
* Return the request data based on this form's request method
*
* @param Request $request The request to fetch the data from
*
* @return array
*/
public function getRequestData(Request $request)
{
if (strtolower($request->getMethod()) === $this->getMethod()) {
return $request->{'get' . ($request->isPost() ? 'Post' : 'Query')}();
}
return array();
}
/**
* Return the current request
*
* @return Request
*/
public function getRequest()
{
return Icinga::app()->getFrontController()->getRequest();
}
/**
* Return the current Response
*
* @return Response
*/
public function getResponse()
{
return Icinga::app()->getFrontController()->getResponse();
}
/**
* Render this form
*
* @param Zend_View_Interface $view The view context to use
*
* @return string
*/
public function render(Zend_View_Interface $view = null)
{
$this->create();
return parent::render($view);
}
}