/
formui.php
2384 lines (2188 loc) · 65.6 KB
/
formui.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
/**
* @package Habari
*
*/
/**
* FormUI Library - Create interfaces for plugins
*
* FormUI This is the main class, it generates the form itself;
* FormContainer A form-related class that can contain form elements, derived by FormUI and FormControlFieldset;
* FormValidators Catalog of validation functions, it can be extended if needed;
* FormControl Parent class to controls, it contains basic functionalities overrode in each control's class;
* FormControl* Every control needs a FormControl* class, FormUI literally looks for example, FormControlCheckbox.
*
*/
class FormComponents
{
/**
* Produces a list of HTML parameters from specific values in this object
* @param array $map A list of attributes and the fields on this object of which to map the values to them
* @param array $additional A list of attributes and values to add explicitly to this output
* @return string A list of HTML-style parameters as produced from the input arrays
*/
function parameter_map($map = array(), $additional = array()) {
$output = '';
foreach($map as $tag_param => $tag_fields) {
if(is_numeric($tag_param)) {
$tag_param = $tag_fields;
}
$value_out = $this->get_value_out($tag_fields);
if($value_out) {
if(is_array($value_out)) {
$output .= ' ' . $tag_param . '="' . implode(' ', $value_out) . '"';
}
else {
$output .= ' ' . $tag_param . '="' . $value_out . '"';
}
}
}
foreach($additional as $tag_param => $value_out) {
$output .= ' ' . $tag_param . '="' . $value_out . '"';
}
return $output;
}
/**
* Return the property value that is associated with the first present property from an array list
* @param array $tag_fields A list of potential fields to try
* @return bool|string False if no value found, string of the property value found
*/
public function get_value_out($tag_fields) {
$value_out = false;
foreach(Utils::single_array($tag_fields) as $tag_field) {
if(isset($this->$tag_field)) {
$value_out = $this->$tag_field;
break;
}
}
return $value_out;
}
}
class FormContainer extends FormComponents
{
public $name = '';
public $class = '';
public $caption = '';
public $controls = array();
/** @var Theme $theme_obj */
protected $theme_obj = null;
protected $checksum;
public $template = 'formcontainer';
public $properties = array();
public $prefix = '';
public $postfix = '';
/**
* Constructor for FormContainer prevents construction of this class directly
*/
private function __construct() {}
/**
* Append a control to the end of this container
*
* @param string $name The name of the control
* @param string $type A classname, or the postfix of a class starting 'FormControl' that will be used to create the control
* @return FormControl|FormContainer An instance of the named FormControl descendant.
*/
public function append()
{
$control = null;
$args = func_get_args();
$type = array_shift( $args );
if ( $type instanceof FormControl || $type instanceof FormContainer) {
$control = $type;
$name = $control->name;
}
elseif ( is_string( $type ) && class_exists( 'FormControl' . ucwords( $type ) ) ) {
$name = reset( $args );
$type = 'FormControl' . ucwords( $type );
if ( class_exists( $type ) ) {
// Instanciate a new object from $type
$controlreflect = new ReflectionClass( $type );
$control = $controlreflect->newInstanceArgs( $args );
}
}
if ( $control ) {
$control->container = $this;
$this->controls[$name] = $control;
}
return $control;
}
/**
* Insert a control into the container
*
* @param string The name of the control to insert the new control in front of
* @param string The type of the new control
* @param string The name of the new control
* @return FormControl|FormContainer The new control instance
*/
public function insert()
{
$args = func_get_args();
$before = array_shift( $args );
$control = call_user_func_array( array( $this, 'append' ), $args );
if ( is_string( $before ) ) {
$before = $this->$before;
}
$this->move_before( $control, $before );
return $control;
}
/**
* Generate a hash for this container
*
* @return string An md5 hash built using the controls contained within this container
*/
public function checksum()
{
if ( !isset( $this->checksum ) ) {
$checksum = '';
foreach ( $this->controls as $control ) {
if ( method_exists( $control, 'checksum' ) ) {
$checksum .= get_class( $control ) . ':' . $control->checksum();
}
else {
$checksum .= get_class( $control ) . ':' . $control->name;
}
$checksum .= '::';
}
$this->checksum = md5( $checksum .= $this->name );
}
return $this->checksum;
}
/**
* Returns an associative array of the controls' values
*
* @return array Associative array where key is control's name and value is the control's value
*/
public function get_values()
{
$values = array();
foreach ( $this->controls as $control ) {
if ( $control instanceOf FormContainer ) {
$values = array_merge( $values, $control->get_values() );
}
else {
$values[$control->name] = $control->value;
}
}
return $values;
}
/**
* Returns an associative array of controls
*
* @return array An array of FormControls
*/
public function get_controls()
{
$controls = array();
foreach ( $this->controls as $control ) {
if ( $control instanceOf FormContainer ) {
$controls = array_merge( $controls, $control->get_controls() );
}
else {
$controls[$control->name] = $control;
}
}
return $controls;
}
/**
* Produce HTML output for all this fieldset and all contained controls
*
* @param boolean $forvalidation True if this control should render error information based on validation.
* @return string HTML that will render this control in the form
*/
function get( $forvalidation = true )
{
$theme = $this->get_theme( $forvalidation, $this );
$contents = '';
foreach ( $this->controls as $control ) {
$contents .= $control->get( $forvalidation );
}
$theme->contents = $contents;
// Do not move before $contents
// Else, these variables will contain the last control's values
$theme->class = $this->class;
$theme->id = $this->name;
$theme->caption = $this->caption;
$theme->control = $this;
return $theme->fetch( $this->template, true );
}
/**
* Retreive the Theme used to display the form component
*
* @param boolean $forvalidation If true, perform validation on control and add error messages to output
* @param FormControl $control The control to output using a template
* @return Theme The theme object to display the template for the control
*/
function get_theme( $forvalidation = false, $control = null )
{
if ( !isset( $this->theme_obj ) ) {
$theme_dir = Plugins::filter( 'control_theme_dir', Plugins::filter( 'admin_theme_dir', Site::get_dir( 'admin_theme', true ) ) . 'formcontrols/', $control );
$this->theme_obj = Themes::create( ); // Create the current theme instead of: 'admin', 'RawPHPEngine', $theme_dir
// Add the templates for the form controls tothe current theme,
// and allow any matching templates from the current theme to override
$formcontrol_templates = Utils::glob($theme_dir . '*.php');
foreach($formcontrol_templates as $template) {
$template_name = basename($template, '.php');
$this->theme_obj->add_template($template_name, $template);
}
$list = array();
$list = Plugins::filter('available_templates', $list);
foreach($list as $template_name) {
if($template = Plugins::filter('include_template_file', null, $template_name)) {
$this->theme_obj->add_template($template_name, $template);
}
}
}
$this->theme_obj->start_buffer();
if ( $control instanceof FormControl ) {
// PHP doesn't allow __get() to return pointers, and passing this array to foreach directly generates an error.
$properties = $control->properties;
foreach ( $properties as $name => $value ) {
$this->theme_obj->$name = $value;
}
$this->theme_obj->field = $control->field;
$this->theme_obj->value = $control->value;
$this->theme_obj->caption = $control->caption;
$this->theme_obj->id = (string) $control->id;
$class = (array) $control->class;
$message = '';
if ( $forvalidation ) {
$validate = $control->validate();
if ( count( $validate ) != 0 ) {
$class[] = 'invalid';
$message = implode( '<br>', (array) $validate );
}
}
$this->theme_obj->class = implode( ' ', (array) $class );
$this->theme_obj->message = $message;
}
return $this->theme_obj;
}
/**
* Moves a control to target's position to which we add $int if specified
* That integer is useful to move before or move after the target
*
* @param FormControl $control FormControl object to move
* @param FormControl $target FormControl object acting as destination
* @param int $int Integer added to $target's position (index)
*/
function move( $source, $target, $offset = 0 )
{
// Remove the source control from its container's list of controls
$controls = array();
foreach ( $source->container->controls as $name => $ctrl ) {
if ( $ctrl === $source ) {
$source_name = $name;
continue;
}
$controls[$name] = $ctrl;
}
$source->container->controls = $controls;
// Insert the source control into the destination control's container's list of controls in the correct location
$target_index = array_search( $target, array_values( $target->container->controls ), true );
$left_slice = array_slice( $target->container->controls, 0, ( $target_index + $offset ), true );
$right_slice = array_slice( $target->container->controls, ( $target_index + $offset ), count( $target->container->controls ), true );
$target->container->controls = $left_slice + array( $source_name => $source ) + $right_slice;
}
/**
* Moves a control before the target control
*
* @param FormControl $control FormControl object to move
* @param FormControl $target FormControl object acting as destination
*/
function move_before( $control, $target )
{
$this->move( $control, $target );
}
/**
* Moves a control after the target control
*
* @param FormControl $control FormControl object to move
* @param FormControl $target FormControl object acting as destination
*/
function move_after( $control, $target )
{
$this->move( $control, $target, 1 ); // Increase left slice's size by one.
}
/**
* Move a control into the container
*
* @param FormControl $control FormControl object to move
* @param FormControl $target FormControl object acting as destination
*/
public function move_into( $control, $target )
{
// Remove the source control from its container's list of controls
$controls = array();
foreach ( $control->container->controls as $name => $ctrl ) {
if ( $ctrl === $control ) {
$source_name = $name;
continue;
}
$controls[$name] = $ctrl;
}
$control->container->controls = $controls;
$target->controls[$control->name] = $control;
}
/**
* Replaces a target control by the supplied control
*
* @param FormControl $target FormControl object to replace
* @param FormControl $control FormControl object to replace $target with
*/
function replace( $target, $control )
{
$this->move_after( $control, $target );
$this->remove( $target );
}
/**
* Removes a target control from this group (can be the form or a fieldset)
*
* @param FormControl $target FormControl to remove
*/
function remove( $target )
{
// Strictness will skip recursiveness, else you get an exception (recursive dependency)
unset( $this->controls[array_search( $target, $this->controls, true )] );
}
/**
* Returns true if any of the controls this container contains should be stored in userinfo
*
* @return boolean True if control data should be sotred in userinfo
*/
function has_user_options()
{
$has_user_options = false;
foreach ( $this->controls as $control ) {
$has_user_options |= $control->has_user_options();
}
return $has_user_options;
}
/**
* Magic property getter, returns the specified control
*
* @param string $name The name of the control
* @return FormControl The control object requested
*/
function __get( $name )
{
if ( isset( $this->controls[$name] ) ) {
return $this->controls[$name];
}
foreach ( $this->controls as $control ) {
if ( $control instanceof FormContainer ) {
// Assignment is needed to avoid an indirect modification notice
if ( $ctrl = $control->$name ) {
return $ctrl;
}
}
}
}
/**
* Magic property isset, returns if the specified control exists
*
* @param string $name The name of the control
* @return bool If the control object is set
*/
function __isset( $name )
{
if ( isset( $this->controls[$name] ) ) {
return true;
}
foreach ( $this->controls as $control ) {
if ( $control instanceof FormContainer ) {
// Assignment is needed to avoid an indirect modification notice
if ( $ctrl = $control->$name ) {
return true;
}
}
}
return false;
}
/**
* Return the HTML/script required for all contained controls. Do it only once.
*
* @return string The HTML/javascript required for all contained controls.
*/
function pre_out()
{
$preout = '';
foreach ( $this->controls as $control ) {
$preout .= $control->pre_out();
}
return $preout;
}
/**
* Runs any attached validation functions to check validation of each control contained in this fieldset.
*
* @return array An array of string validation error descriptions or an empty array if no errors were found.
*/
function validate()
{
$results = array();
foreach ( $this->controls as $control ) {
if ( $result = $control->validate() ) {
$results[] = $result;
}
}
return $results;
}
/**
* Store each contained control's value under the control's specified key.
*
* @param string $key (optional) The Options table key to store this option in
*/
function save()
{
foreach ( $this->controls as $control ) {
$control->save();
}
}
/**
* Explicitly assign the theme object to be used with this container
*
* @param Theme $theme The theme object to use to output this container
*/
function set_theme( $theme )
{
$this->theme_obj = $theme;
}
/**
* Output any validation errors on any controls in this container using the supplied format
* $this->validate must be called first!
*
* @params string $format A sprintf()-style format string to format the validation error
* @params string $format A sprintf()-style format string to wrap the returned error, only if at least one error exists
*/
public function errors_out( $format, $wrap = '%s' )
{
echo $this->errors_get( $format, $wrap );
}
/**
* Return any validation errors on any controls in this container using the supplied format
* $this->validate must be called first!
*
* @params string $format A sprintf()-style format string to format the validation error
* @params string $format A sprintf()-style format string to wrap the returned error, only if at least one error exists
* @return string The errors in the supplied format
*/
public function errors_get( $format, $wrap = '%s' )
{
$out = '';
foreach ( $this->get_controls() as $control ) {
foreach ( $control->errors as $error ) {
$out .= sprintf( $format, $error );
}
}
if ( $out != '' ) {
$out = sprintf( $wrap, $out );
}
return $out;
}
/**
* Return the property value that is associated with the first present property from an array list
* This version only searches the list of the class' $properties array, because __get() on this objcet returns named FormControls instances
* @param array $tag_fields A list of potential fields to try
* @return bool|string False if no value found, string of the property value found
*/
public function get_value_out($tag_fields) {
$value_out = false;
foreach(Utils::single_array($tag_fields) as $tag_field) {
if(isset($this->properties[$tag_field])) {
$value_out = $this->properties[$tag_field];
break;
}
}
return $value_out;
}
}
/**
* FormUI Class
* This will generate the <form> structure and call subsequent controls
*
* For a list of options to customize its output or behavior see FormUI::set_option()
*/
class FormUI extends FormContainer implements IsContent
{
private $success_callback;
private $success_callback_params = array();
private $on_save = array();
public $success = false;
public $submitted = false;
private static $outpre = false;
private $options = array(
'save_button' => true,
'ajax' => false,
'form_action' => '',
'template' => 'formcontrol_form',
'theme' => '',
'success_message' => '',
);
public $class = array( 'formui' );
public $id = null;
public $formtype = '';
public $properties = array(
'action' => '',
'onsubmit' => '',
'enctype' => 'application/x-www-form-urlencoded',
'accept_charset' => 'UTF-8',
);
/**
* FormUI's constructor, called on instantiation.
*
* @param string $name The name of the form, used to differentiate multiple forms.
* @param string $formtype The type of the form, used to classify form types for plugin modification
*/
public function __construct( $name, $formtype = null )
{
$this->name = $name;
if ( isset( $formtype ) ) {
$this->formtype = $formtype;
}
else {
$this->formtype = $name;
}
}
/**
* Generate a unique MD5 hash based on the form's name or the control's name.
*
* @return string Unique string composed of 35 hexadecimal digits representing the victim.
*/
public function salted_name()
{
return md5( Options::get( 'secret' ) . 'added salt, for taste' . $this->checksum() );
}
/**
* Produce a form with the contained fields.
*
* @param boolean $process_for_success Set to true to display the form as it would look if the submission succeeded, but do not execute success methods.
* @return string HTML form generated from all controls assigned to this form
*/
public function get( $use_theme = null, $process_for_success = true )
{
$forvalidation = false;
Plugins::act( 'modify_form_' . Utils::slugify( $this->formtype, '_' ), $this );
Plugins::act( 'modify_form', $this );
if ( isset( $use_theme ) ) {
$theme = $use_theme;
}
else {
$theme = $this->get_theme( $forvalidation, $this );
}
$theme->start_buffer();
$theme->success = false;
$this->success = false;
$this->submitted = false;
// Should we be validating?
if ( isset( $_POST['FormUI'] ) && $_POST['FormUI'] == $this->salted_name() ) {
$this->submitted = true;
$validate = $this->validate();
if ( count( $validate ) == 0 ) {
if ( $process_for_success ) {
$result = $this->success();
if ( $result ) {
return $result;
}
}
$theme->success = true;
$this->success = true;
$theme->message = $this->options['success_message'];
}
else {
$forvalidation = true;
if ( !isset( $_SESSION['forms'][$this->salted_name()]['url'] ) ) {
$_SESSION['forms'][$this->salted_name()]['url'] = Site::get_url( 'habari', true ) . Controller::get_stub();
}
}
}
else {
$_SESSION['forms'][$this->salted_name()]['url'] = Site::get_url( 'habari', true ) . Controller::get_stub();
}
if ( isset( $_SESSION['forms'][$this->salted_name()]['error_data'] ) ) {
foreach ( $_SESSION['forms'][$this->salted_name()]['error_data'] as $key => $value ) {
$_POST[$key] = $value;
}
unset( $_SESSION['forms'][$this->salted_name()]['error_data'] );
$forvalidation = true;
}
$out = '';
$theme->controls = $this->output_controls( $forvalidation );
$theme->form = $this;
foreach ( $this->properties as $prop => $value ) {
$theme->$prop = $value;
}
$theme->id = Utils::slugify( $this->name );
$theme->class = implode( " ", (array) $this->class );
$theme->action = $this->options['form_action'];
$theme->onsubmit = ($this->properties['onsubmit'] == '') ? '' : "onsubmit=\"{$this->properties['onsubmit']}\"";
$theme->salted_name = $this->salted_name();
$theme->pre_out = $this->pre_out_controls();
$out = $this->prefix . $theme->display_fallback( $this->options['template'], 'fetch' ) . $this->postfix;
$theme->end_buffer();
return $out;
}
/**
* Output a form with the contained fields.
* Calls $this->get() and echoes.
*/
public function out()
{
$args = func_get_args();
echo call_user_func_array( array( $this, 'get' ), $args );
}
/**
* Return the form control HTML.
*
* @param boolean $forvalidation True if the controls should output additional information based on validation.
* @return string The output of controls' HTML.
*/
public function output_controls( $forvalidation = false )
{
$out = '';
$theme = $this->get_theme( $forvalidation );
foreach ( $this->controls as $control ) {
$out .= $control->get( $forvalidation );
}
$theme->end_buffer();
return $out;
}
/**
* Return pre-output control configuration scripts for any controls that require them.
*
* @return string The output of controls' pre-output HTML.
*/
public function pre_out_controls()
{
$out = '';
if ( !FormUI::$outpre ) {
$out .= '<script type="text/javascript">if(controls==undefined){var controls = {init:function(fn){if(fn!=undefined){controls.inits.push(fn);}else{for(var i in controls.inits){controls.inits[i]();}}},inits:[]};}</script>';
}
foreach ( $this->controls as $control ) {
$out .= $control->pre_out( );
}
if ( !FormUI::$outpre ) {
FormUI::$outpre = true;
$out .= '<script type="text/javascript">window.setTimeout(function(){controls.init();}, 500);</script>';
}
return $out;
}
/**
* Process validation on all controls of this form.
*
* @return array An array of strings describing validation issues, or an empty array if no issues.
*/
public function validate()
{
$validate = array();
foreach ( $this->controls as $control ) {
$validate = array_merge( $validate, $control->validate() );
}
return $validate;
}
/**
* Set a function to call on form submission success
*
* @param mixed $callback A callback function or a plugin filter name.
*/
public function on_success( $callback )
{
$params = func_get_args();
$callback = array_shift( $params );
$this->success_callback = $callback;
$this->success_callback_params = $params;
}
/**
* Set a function to call on form submission success
*
* @param mixed $callback A callback function or a plugin filter name.
*/
public function on_save( $callback )
{
$this->on_save[] = func_get_args();
}
/**
* Calls the success callback for the form, and optionally saves the form values
* to the options table.
*/
public function success()
{
$result = true;
if ( isset( $this->success_callback ) ) {
$params = $this->success_callback_params;
array_unshift( $params, $this );
if ( is_callable( $this->success_callback ) ) {
$result = call_user_func_array( $this->success_callback, $params );
}
else {
array_unshift( $params, $this->success_callback, false );
$result = call_user_func_array( array( 'Plugins', 'filter' ), $params );
}
if ( $result ) {
return $result;
}
}
else {
$this->save();
return false;
}
}
/**
* Save all controls to their storage locations
*/
public function save()
{
foreach ( $this->controls as $control ) {
$control->save();
}
foreach ( $this->on_save as $save ) {
$callback = array_shift( $save );
if ( is_callable( $callback ) ) {
array_unshift( $save, $this );
call_user_func_array( $callback, $save );
}
else {
array_unshift( $save, $callback, $this );
call_user_func_array( array( 'Plugins', 'act' ), $save );
}
}
if ( $this->has_user_options() ) {
User::identify()->info->commit();
}
}
/**
* Set a form option
* Defaults for options are stored in the $this->options array
*
* @param string $option The name of the option to set
* @param mixed $value The value of the option
*/
public function set_option( $option, $value )
{
$this->options[$option] = $value;
}
/**
* Get a form option
*
* @param string $option The name of the option to get
* @return mixed The value of the named option if set, null if not set
*/
public function get_option( $option )
{
return isset( $this->options[$option] ) ? $this->options[$option] : null;
}
/**
* Configure all the options necessary to make this form work inside a media bar panel
* @param string $path Identifies the silo
* @param string $panel The panel in the silo to submit to
* @param string $callback Javascript function to call on form submission
*/
public function media_panel( $path, $panel, $callback )
{
$this->options['ajax'] = true;
$this->options['form_action'] = URL::get( 'admin_ajax', array( 'context' => 'media_panel' ) );
$this->properties['onsubmit'] = "habari.media.submitPanel('$path', '$panel', this, '{$callback}');return false;";
}
/**
* Redirect the user back to the stored URL value in session
*/
public function bounce()
{
$_SESSION['forms'][$this->salted_name()]['error_data'] = $_POST;
Utils::redirect( $_SESSION['forms'][$this->salted_name()]['url'] );
}
/**
* Implementation of IsContent
* @return array An array of content types that this object represents, starting with the most specific
*/
public function content_type()
{
return array('form');
}
/**
* Convert this object instance to a string
* @return string The form as HTML
*/
public function __toString()
{
return $this->get();
}
}
/**
* FormValidators Class
*
* Extend this class to supply your own validators, by default we supply most common
*/
class FormValidators
{
/**
* A validation function that returns an error if the value passed in is not a valid URL.
*
* @param string $text A string to test if it is a valid URL
* @param FormControl $control The control that defines the value
* @param FormContainer $form The container that holds the control
* @param string $warning An optional error message
* @return array An empty array if the string is a valid URL, or an array with strings describing the errors
*/
public static function validate_url( $text, $control, $form, $warning = null, $schemes = array( 'http', 'https' ) )
{
if ( ! empty( $text ) ) {
$parsed = InputFilter::parse_url( $text );
if ( $parsed['is_relative'] ) {
// guess if they meant to use an absolute link
$parsed = InputFilter::parse_url( 'http://' . $text );
if ( $parsed['is_error'] ) {
// disallow relative URLs
$warning = empty( $warning ) ? _t( 'Relative urls are not allowed' ) : $warning;
return array( $warning );
}
}
if ( $parsed['is_pseudo'] || ! in_array( $parsed['scheme'], $schemes ) ) {
// allow only http(s) URLs
$warning = empty( $warning ) ? _t( 'Only %s urls are allowed', array( Format::and_list( $schemes ) ) ) : $warning;
return array( $warning );
}
}
return array();
}
/**
* A validation function that returns an error if the value passed in is not a valid Email Address,
* as per RFC2822 and RFC2821.
*
* @param string $text A string to test if it is a valid Email Address
* @param FormControl $control The control that defines the value
* @param FormContainer $form The container that holds the control
* @param string $warning An optional error message
* @return array An empty array if the string is a valid Email Address, or an array with strings describing the errors
*/
public static function validate_email( $text, $control, $form, $warning = null )
{
if ( ! empty( $text ) ) {
if ( !preg_match( "@^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*\@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$@i", $text ) ) {
$warning = empty( $warning ) ? _t( 'Value must be a valid Email Address.' ) : $warning;
return array( $warning );
}
}
return array();
}
/**
* A validation function that returns an error if the value passed in is not set.
*
* @param string $text A value to test if it is empty
* @param FormControl $control The control that defines the value
* @param FormContainer $form The container that holds the control
* @param string $warning An optional error message
* @return array An empty array if the value exists, or an array with strings describing the errors
*/
public static function validate_required( $value, $control, $form, $warning = null )
{
if ( empty( $value ) || $value == '' ) {
$warning = empty( $warning ) ? _t( 'A value for this field is required.' ) : $warning;
return array( $warning );
}
return array();
}
/**
* A validation function that returns an error if the the passed username is unavailable
*
* @param string $text A value to test as username
* @param FormControl $control The control that defines the value
* @param FormContainer $form The container that holds the control
* @param string $allowed_name An optional name which overrides the check and is always allowed
* @param string $warning An optional error message
* @return array An empty array if the value exists, or an array with strings describing the errors
*/
public static function validate_username( $value, $control, $form, $allowed_name = null, $warning = null )
{
if ( isset( $allowed_name ) && ( $value == $allowed_name ) ) {
return array();
}
if ( User::get_by_name( $value ) ) {
$warning = empty( $warning ) ? _t( 'That username is already in use!' ) : $warning;
return array( $warning );
}
return array();
}
/**
* A validation function that returns an error if the passed control values do not match
*
* @param string $text A value to test for similarity
* @param FormControl $control The control that defines the value
* @param FormContainer $form The container that holds the control
* @param FormControl $matcher The control which should have a matching value
* @param string $warning An optional error message
* @return array An empty array if the value exists, or an array with strings describing the errors
*/
public static function validate_same( $value, $control, $form, $matcher, $warning = null )
{
if ( $value != $matcher->value ) {
$warning = empty( $warning ) ? _t( 'The value of this field must match the value of %s.', array( $matcher->caption ) ) : $warning;
return array( $warning );
}
return array();
}
/**
* A validation function that returns an error if the value passed does not match the regex specified.
*