-
Notifications
You must be signed in to change notification settings - Fork 0
/
FormPlugin.pm
1643 lines (1286 loc) · 45.3 KB
/
FormPlugin.pm
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
# Plugin for Foswiki - The Free and Open Source Wiki, http://foswiki.org/
#
# Copyright (c) 2007, 2008, 2009 Arthur Clemens, Sven Dowideit
# All Rights Reserved. TWiki Contributors
# are listed in the AUTHORS file in the root of this distribution.
# NOTE: Please extend that file, not this notice.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. For
# more details read LICENSE in the root of this distribution.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# For licensing info read LICENSE file in the installation root.
package Foswiki::Plugins::FormPlugin;
# Always use strict to enforce variable scoping
use strict;
use Foswiki::Func;
use CGI qw( :all );
# $VERSION is referred to by Foswiki, and is the only global variable that
# *must* exist in this package
use vars qw( $VERSION $RELEASE $debug $pluginName $installWeb);
use vars
qw( $currentTopic $currentWeb $defaultFormat $defaultHiddenFieldFormat $defaultTitleFormat %expandedForms %substitutedForms %uncheckedForms %validatedForms %errorForms %noErrorForms %errorFields $headerDone
%currentForm $elementcssclass $SEP);
# This should always be $Rev$ so that Foswiki can determine the checked-in
# status of the plugin. It is used by the build automation tools, so
# you should leave it alone.
$VERSION = '$Rev$';
$RELEASE = '1.4.1';
# Name of this Plugin, only used in this module
$pluginName = 'FormPlugin';
$SEP = "\n";
$headerDone = 0;
$defaultTitleFormat = ' $t <br />';
$defaultFormat = '<p>$titleformat $e $m $h </p>';
$defaultHiddenFieldFormat = '$e';
%expandedForms = ();
%validatedForms = ();
%errorForms = ();
%noErrorForms = ();
%uncheckedForms = ();
%substitutedForms = ()
; # hash of forms names that have their field tokens substituted by the corresponding field values
%errorFields = (); # for each field entry: ...
# constants
my $STATUS_NO_ERROR = 'noerror';
my $STATUS_ERROR = 'error';
my $STATUS_UNCHECKED = 'unchecked';
my $DEFAULT_METHOD = 'GET';
my $FORM_SUBMIT_TAG = 'FP_submit';
my $ACTION_URL_TAG = 'FP_actionurl';
my $VALIDATE_TAG = 'FP_validate';
my $CONDITION_TAG = 'FP_condition';
my $FIELDTITLE_TAG = 'FP_title';
my $MULTIPLE_TAG_ID = '=m';
my %MULTIPLE_TYPES = (
'radio' => 1,
'select' => 1,
'checkbox' => 1
);
my %ERROR_STRINGS = (
'invalid' => '- enter a different value',
'invalidtype' => '- enter a different value',
'blank' => '- please enter a value',
'missing' => '- please enter a value',
);
my %ERROR_TYPE_HINTS = (
'integer' => '(a rounded number)',
'float' => '(a floating number)',
'email' => '(an e-mail address)',
);
# translate from user-friendly names to Validate.pm input
my %REQUIRED_TYPE_TABLE = (
'int' => 'i',
'float' => 'f',
'email' => 'e',
'nonempty' => 's',
'string' => 's',
);
my %CONDITION_TYPE_TABLE = (
'int' => 'i',
'float' => 'f',
'email' => 'e',
'nonempty' => 's',
'string' => 's',
);
my $NOTIFICATION_ANCHOR_NAME = 'FormPluginNotification';
my $ELEMENT_ANCHOR_NAME = 'FormElement';
my $NOTIFICATION_CSS_CLASS = 'formPluginNotification';
my $ELEMENT_GROUP_CSS_CLASS = 'formPluginGroup';
my $ELEMENT_GROUP_HINT_CSS_CLASS = 'formPluginGroupWithHint';
my $ERROR_CSS_CLASS = 'formPluginError';
my $TITLE_CSS_CLASS = 'formPluginTitle';
my $HINT_CSS_CLASS = 'formPluginHint';
my $MANDATORY_CSS_CLASS = 'formPluginMandatory';
my $MANDATORY_STRING = '*';
my $BEFORE_CLICK_CSS_CLASS = 'foswikiInputFieldBeforeClick';
=pod
=cut
sub initPlugin {
my ( $topic, $web, $user, $installWeb ) = @_;
# check for Plugins.pm versions
if ( $Foswiki::Plugins::VERSION < 1.026 ) {
Foswiki::Func::writeWarning(
"Version mismatch between $pluginName and Plugins.pm");
return 0;
}
$currentTopic = $topic if !$currentTopic;
$currentWeb = $web if !$currentWeb;
$debug = Foswiki::Func::getPluginPreferencesFlag("DEBUG")
|| Foswiki::Func::getPreferencesFlag("DEBUG");
Foswiki::Func::registerTagHandler( 'STARTFORM', \&_startForm );
Foswiki::Func::registerTagHandler( 'ENDFORM', \&_endForm );
Foswiki::Func::registerTagHandler( 'FORMELEMENT', \&_formElement );
Foswiki::Func::registerTagHandler( 'FORMSTATUS', \&_formStatus );
Foswiki::Func::registerTagHandler( 'FORMERROR', \&_formError );
# Plugin correctly initialized
return 1;
}
=pod
Process form before any %STARTFORM{}% is expanded:
- substitute tokens
- validate form
Because beforeCommonTagsHandler is called multiple times while rendering, the processed forms are stored and checked each time.
=cut
sub beforeCommonTagsHandler {
# do not uncomment, use $_[0], $_[1]... instead
### my ( $text, $topic, $web ) = @_;
my $query = Foswiki::Func::getCgiQuery();
my $submittedFormName =
$query->param($FORM_SUBMIT_TAG); # form name is stored in submit
if ($submittedFormName) {
return
if $substitutedForms{$submittedFormName}
&& $validatedForms{$submittedFormName};
}
# substitute dynamic values
if ( $submittedFormName && !$substitutedForms{$submittedFormName} ) {
_substituteFieldTokens();
$substitutedForms{$submittedFormName} = $submittedFormName;
}
# validate form
if ( $submittedFormName && !$validatedForms{$submittedFormName} ) {
my $error = !_validateForm();
if ($error) {
$errorForms{$submittedFormName} = 1;
$noErrorForms{$submittedFormName} = 0;
}
else {
$errorForms{$submittedFormName} = 0;
$noErrorForms{$submittedFormName} = 1;
}
$validatedForms{$submittedFormName} = 1;
}
}
sub _initValues {
$elementcssclass = '';
# form attributes we want to retrieve while parsing FORMELEMENT tags:
undef %currentForm;
%currentForm = (
'name' => 'untitled',
'elementformat' => $defaultFormat,
'noFormHtml' => '',
);
}
=pod
Read form field tokens and replace them by the field values.
For instance: if a field contains the value '$about', this string is substituted
by the value of the field with name 'about'.
=cut
sub _substituteFieldTokens {
my $query = Foswiki::Func::getCgiQuery();
# create quick lookup hash
my @names = $query->param;
my %keyValues;
my %conditionFields = ();
foreach (@names) {
my $name = $_;
next if !$name;
$keyValues{$name} = $query->param($name);
}
foreach ( keys %keyValues ) {
my $name = $_;
next if $conditionFields{$name}; # value already set with a condition
my $value = $keyValues{$_};
my ( $referencedField, $meetsCondition ) =
_meetsCondition( $name, $value );
if ($meetsCondition) {
$value =~ s/(\$(\w+))/$keyValues{$2}/go;
$query->param( -name => $_, -value => $value );
}
else {
$value = '';
$query->param( -name => $referencedField, -value => $value );
$conditionFields{$referencedField} = 1;
}
}
}
=pod
Checks if a field value meets the condition of a referenced field.
For instance:
User input is:
%FORMELEMENT{
name="comment_from_date"
condition="$comment_from_date_input=nonempty"
}%
This has been parsed to:
(hidden) field name: FP_condition_comment_from_date
(hidden) field value: =comment_from_date=s
=cut
sub _meetsCondition {
my ( $fieldName, $nameAndValidationType ) = @_;
if ( !( $fieldName =~ m/^$CONDITION_TAG\_(.+?)$/go ) ) {
return ( $fieldName, 1 ); # no condition, so pass
}
my $referencedField = $1;
my %validateFields = ();
_createValidationFieldEntry( $referencedField, $nameAndValidationType, 0,
\%validateFields );
_validateFormFields(%validateFields);
if (@Foswiki::Plugins::FormPlugin::Validate::ErrorFields) {
return ( $referencedField, 0 );
}
return ( $referencedField, 1 );
}
=pod
Retrieves the status of the form. Usage:
%FORMSTATUS{"form_name"}%
or
%FORMSTATUS{"form_name" status="noerror"}%
%FORMSTATUS{"form_name" status="error"}%
%FORMSTATUS{"form_name" status="unchecked"}%
=cut
sub _formStatus {
my ( $session, $params, $topic, $web ) = @_;
my $name = $params->{'_DEFAULT'};
return '' if !$name;
my $statusFormat = $params->{'status'};
my %status = _status($name);
return $status{$statusFormat} || "0" if $statusFormat;
return $STATUS_NO_ERROR if ( $noErrorForms{$name} );
return $STATUS_ERROR if ( $errorForms{$name} );
# else
return $STATUS_UNCHECKED;
}
=pod
Retrieves the error message of the form. Usage:
%FORMERROR{"form_name"}%
=cut
sub _formError {
my ( $session, $params, $topic, $web ) = @_;
my $name = $params->{'_DEFAULT'};
return '' if !$name;
return _displayErrors(@_);
}
=pod
=cut
sub _status {
my ($formName) = @_;
return (
$STATUS_NO_ERROR => $noErrorForms{$formName},
$STATUS_ERROR => $errorForms{$formName},
$STATUS_UNCHECKED => !$noErrorForms{$formName}
&& !$errorForms{$formName},
);
}
=pod
=cut
sub _addHeader {
return if $headerDone;
my $header = <<'END';
<style type="text/css" media="all">
@import url("%PUBURL%/%SYSTEMWEB%/FormPlugin/formplugin.css");
</style>
<script type="text/javascript" src="%PUBURL%/%SYSTEMWEB%/JavascriptFiles/foswikilib.js"></script>
<script type="text/javascript" src="%PUBURL%/%SYSTEMWEB%/JavascriptFiles/foswikiCSS.js"></script>
<script type="text/javascript" src="%PUBURL%/%SYSTEMWEB%/JavascriptFiles/foswikiForm.js"></script>
<script type="text/javascript" src="%PUBURL%/%SYSTEMWEB%/JavascriptFiles/foswikiString.js"></script>
END
Foswiki::Func::addToHEAD( 'FORMPLUGIN', $header );
$headerDone = 1;
}
=pod
Order of actions:
- Check if this is the form that has been submitted
- Returns if the form did not validate (has been validated before this call)
- Redirects if an action url has been passed in the form
=cut
sub _startForm {
my ( $session, $params, $topic, $web ) = @_;
_initValues();
_addHeader();
my $name = $params->{'name'} || '';
return '' if $expandedForms{$name};
#alow us to replace \n with somethign else.
$SEP = $params->{'sep'} if (defined($params->{'sep'}));
my $showErrors = lc($params->{'showerrors'} || 'above');
# else
$expandedForms{$name} = 1;
# check if the submitted form is the form at hand
my $query = Foswiki::Func::getCgiQuery();
my $submittedFormName = $query->param($FORM_SUBMIT_TAG);
if ( $submittedFormName && $name eq $submittedFormName ) {
if ( $errorForms{$submittedFormName} ) {
my $formOutput = _displayForm(@_);
if (($showErrors eq 'no') or ($showErrors eq 'off')) {
return $formOutput
}
my $errorOutput = _displayErrors(@_);
if ($showErrors eq 'below') {
return $formOutput.$errorOutput;
}
# default to show validation error feedback above form
return $errorOutput . $formOutput;
}
# redirectto if an action url has been passed in the form
my $actionUrl = $query->param($ACTION_URL_TAG);
if ($actionUrl) {
# delete temporary parameters
$query->delete($ACTION_URL_TAG);
# do not delete param $FORM_SUBMIT_TAG as we might want to know if this form is validated
my $method = _method( $params->{'method'} );
if ( $method eq 'POST' && $Foswiki::Plugins::VERSION < 1.2 ) {
# on previous versions redirecting a POST does not work
# because the request is changed to a GET
# to not loose the parameters we will convert all key-values
# to a parameter string
$actionUrl .= '?' . _postDataToUrlParamString();
# we now have a url param
# delete original POST data
$query->delete_all();
Foswiki::Func::writeDebug(
"FormPlugin - POST and Plugins::VERSION < 1.2 -- converting all key-values to a parameter string: actionUrl="
. $actionUrl )
if $debug;
Foswiki::Func::redirectCgiQuery( undef, $actionUrl );
return;
}
# else
Foswiki::Func::redirectCgiQuery( undef, $actionUrl, 1 );
return '';
}
}
# else
return _displayForm(@_);
}
=pod
Returns 1 when validation is ok; 0 if an error has been found.
=cut
sub _validateForm {
eval 'use Foswiki::Plugins::FormPlugin::Validate';
# Some fields might need to be validated
# this is set with parameter =validate="s"= in %FORMELEMENT%
# during parsing of %FORMELEMENT% this has been converted to
# a new hidden field $VALIDATE_TAG_fieldname
my $query = Foswiki::Func::getCgiQuery();
my @names = $query->param;
my %validateFields = ();
my $order = 0;
foreach (@names) {
my $name = $_;
next if !$name;
# the (hidden) field that has set the validation type
# can be recognized by $VALIDATE_TAG_fieldname
my $isSettingField = $name =~ m/^$VALIDATE_TAG\_(.+?)$/go;
if ($isSettingField) {
my $referencedField = $1;
my $nameAndValidationType = $query->param($name);
_createValidationFieldEntry( $referencedField,
$nameAndValidationType, $order++, \%validateFields );
}
}
# return all fine if nothing to be done
return 1 if !keys %validateFields;
_validateFormFields(%validateFields);
if (@Foswiki::Plugins::FormPlugin::Validate::ErrorFields) {
# store field name refs
for my $href (@Foswiki::Plugins::FormPlugin::Validate::ErrorFields) {
my $fieldNameForRef = $href->{'field'};
$errorFields{$fieldNameForRef} = 1;
}
return 0;
}
return 1;
}
sub _createValidationFieldEntry {
my ( $fieldName, $nameAndValidationType, $order, $validateFields ) = @_;
# create hash entry:
# string_fieldname+validation_type => reference_field
$nameAndValidationType =~ s/^(.*?)(\=m)*$/$1/go;
# append order argument
$nameAndValidationType .= '=' . $order;
my $isMultiple = $2 if $2;
if ($isMultiple) {
my @fieldNameRef;
$validateFields->{$nameAndValidationType} = \@fieldNameRef
if $nameAndValidationType;
}
else {
my $fieldNameRef;
$validateFields->{$nameAndValidationType} = \$fieldNameRef
if $nameAndValidationType;
}
}
=pod
Use Validator to check fields.
Returns 1 when validation is ok; 0 if an error has been found.
=cut
sub _validateFormFields {
my (%fields) = @_;
eval 'use Foswiki::Plugins::FormPlugin::Validate';
# allow some fields not to be validated
# otherwise we get errors on hidden fields we have inserted ourselves
$Foswiki::Plugins::FormPlugin::Validate::IgnoreNonMatchingFields = 1;
# not need to check for all form elements
$Foswiki::Plugins::FormPlugin::Validate::Complete = 1;
# test fields
my $query = Foswiki::Func::getCgiQuery();
Foswiki::Plugins::FormPlugin::Validate::GetFormData($query, %fields);
if ($Foswiki::Plugins::FormPlugin::Validate::Error) {
return 0;
}
return 1;
}
=pod
=cut
sub _displayErrors {
my ( $session, $params, $topic, $web ) = @_;
if (@Foswiki::Plugins::FormPlugin::Validate::ErrorFields) {
my $note = " *Some fields are not filled in correctly:* ";
my @sortedErrorFields =
sort { $a->{order} cmp $b->{order} }
@Foswiki::Plugins::FormPlugin::Validate::ErrorFields;
for my $href (@sortedErrorFields) {
my $errorType = $href->{'type'};
my $fieldName = $href->{'field'};
my $errorString = $ERROR_STRINGS{$errorType} || '';
my $expected = $href->{'expected'};
my $expectedString =
$expected ? ' ' . $ERROR_TYPE_HINTS{$expected} : '';
$errorString .= $expectedString;
my $anchor = '#' . _anchorLink($fieldName);
# preserve state information
my $currentUrl = _currentUrl(@_);
$note .=
"\n * <a href=\"$currentUrl$anchor\">$fieldName</a> $errorString";
}
return _wrapHtmlError($note) if scalar @sortedErrorFields;
}
return '';
}
=pod
With GET, retrieves the url parameters if any.
With POST, ignores url parameters.
=cut
sub _currentUrl {
my ( $session, $params, $topic, $web ) = @_;
my $query = Foswiki::Func::getCgiQuery();
my $currentUrl = $query->url() . $query->path_info();
return $currentUrl;
}
=pod
=cut
sub _method {
my ($method) = @_;
$method ||= $DEFAULT_METHOD;
return $method;
}
=pod
=cut
sub _displayForm {
my ( $session, $params, $topic, $web ) = @_;
my $name = $params->{'name'} || '';
my $actionParam = $params->{'action'} || '';
my $method = _method( $params->{'method'} || '' );
my $redirectto = $params->{'redirectto'} || '';
$elementcssclass = $params->{'elementcssclass'} || '';
my $formcssclass = $params->{'formcssclass'} || '';
my $webParam = $params->{'web'} || '';
my $topicParam = $params->{'topic'} || '';
# store for element rendering
$currentForm{'name'} = $name;
$currentForm{'elementformat'} = $params->{'elementformat'} || '';
my $noFormHtml = Foswiki::Func::isTrue( $params->{'noformhtml'} || '' );
if ($noFormHtml) {
$currentForm{'noFormHtml'} = 1;
return '';
}
if ($topicParam) {
( $web, $topic ) =
Foswiki::Func::normalizeWebTopicName( $webParam, $topicParam );
}
else {
$web = $currentWeb;
$topic = $currentTopic;
}
my $anchor = $params->{'anchor'} || $NOTIFICATION_ANCHOR_NAME;
my $actionUrl = '';
if ( $actionParam eq 'save' ) {
$actionUrl = "%SCRIPTURL{save}%/$web/$topic";
}
elsif ( $actionParam eq 'edit' ) {
$actionUrl = "%SCRIPTURL{edit}%/$web/$topic";
}
elsif ( $actionParam eq 'upload' ) {
$actionUrl = "%SCRIPTURL{upload}%/$web/$topic";
}
elsif ( $actionParam eq 'view' ) {
$actionUrl = "%SCRIPTURL{view}%/$web/$topic";
}
elsif ( $actionParam eq 'viewauth' ) {
$actionUrl = "%SCRIPTURL{viewauth}%/$web/$topic";
}
else {
$actionUrl = $actionParam;
}
my $currentUrl = _currentUrl(@_);
$currentUrl .= '#' . $anchor if ( defined $anchor );
my $onSubmit = $params->{'onSubmit'} || undef;
my %startFormParameters = ();
$startFormParameters{'-name'} = $name;
$startFormParameters{'-method'} = $method;
$startFormParameters{'-onSubmit'} = $onSubmit if $onSubmit;
my $disableValidation = $params->{'validate'} eq 'off'
if ( defined $params->{'validate'} );
$startFormParameters{'-action'} =
$disableValidation ? $actionUrl : $currentUrl;
# multi-part is needed for upload. Why not always use it?
#my $formStart = CGI::start_form(%startFormParameters);
my $formStart = CGI::start_multipart_form(%startFormParameters);
$formStart =~ s/\n/$SEP/eg; #unhappily, CGI::start_multipart_form adds a \n, which will stuff up tables.
my $formClassAttr = $formcssclass ? " class=\"$formcssclass\"" : '';
$formStart .= "<div$formClassAttr>$SEP<!--FormPlugin form start-->";
$formStart .= "$SEP"
. CGI::hidden(
-name => $ACTION_URL_TAG,
-default => $actionUrl
) if $actionUrl;
# store name reference in form so it can be retrieved after submitting
$formStart .= "$SEP"
. CGI::hidden(
-name => $FORM_SUBMIT_TAG,
-default => $name
);
$formStart .= "$SEP"
. CGI::hidden(
-name => 'redirectto',
-default => $redirectto
) if $redirectto;
$formStart =~ s/\n/$SEP/ge if ($SEP ne "\n"); #again, breaks table generation
return $formStart;
}
=pod
=cut
sub _endForm {
my ( $session, $params, $topic, $web ) = @_;
my $endForm = '</div><!--/FormPlugin form end-->' . CGI::end_form();
$endForm = '' if ( $currentForm{'noFormHtml'} );
_initValues();
$endForm =~ s/\n/$SEP/ge if ($SEP ne "\n"); #breaks table generation
return $endForm;
}
=pod
Lifted out:
# needs to be tested more
my $formcondition = $params->{'formcondition'};
if ($formcondition) {
$formcondition =~ m/^(.*?)\.(.*?)$/;
my ( $formName, $conditionStatus ) = ( $1, $2 );
my %status = _status($formName);
return '' unless isTrue( $status{$conditionStatus} );
my $query = Foswiki::Func::getCgiQuery();
my $default = $params->{'default'};
$query->param( -name => $name, -value => $default );
}
| =formcondition= | Display only if the form condition is true. Condition syntax: =form_name.contition_status=, where =contition_status= is one of =unchecked=, =error= or =noerror= |- |- | =formcondition="Mailform.noerror"= |
=cut
sub _formElement {
my ( $session, $params, $topic, $web ) = @_;
_addHeader();
my $element = _getFormElementHtml(@_);
$element =
'<noautolink>'
. $element
. '</noautolink>'; # prevent wiki words inside form fields
my $type = $params->{'type'};
my $name = $params->{'name'};
my $format =
$params->{'format'}
|| $currentForm{'elementformat'}
|| $defaultFormat;
$format = $defaultHiddenFieldFormat if ( $type eq 'hidden' );
my $javascriptCalls = '';
my $focus = $params->{'focus'};
if ($focus) {
my $focusCall =
'<script type="text/javascript">foswiki.Form.setFocus("'
. $currentForm{'name'} . '", "'
. $name
. '");</script>';
$javascriptCalls .= $focusCall;
}
my $beforeclick = $params->{'beforeclick'};
if ($beforeclick) {
my $formName = $currentForm{'name'};
my $beforeclickCall = '';
$beforeclickCall .= '<script type="text/javascript">';
if ( $formName eq '' ) {
$beforeclickCall .=
'var field=document.getElementsByName("'
. $name
. '")[0]; var formName=field.form.name;';
}
else {
$beforeclickCall .= 'var formName="' . $formName . '";';
}
$beforeclickCall .=
'var el=foswiki.Form.getFormElement(formName, "'
. $name
. '"); foswiki.Form.initBeforeFocusText(el,"'
. $beforeclick . '");';
$beforeclickCall .= '</script>';
$javascriptCalls .= $beforeclickCall;
}
$format =~ s/(\$e\b)/$1$javascriptCalls/go;
my $mandatoryParam = $params->{'mandatory'};
my $isMandatory = Foswiki::Func::isTrue( $mandatoryParam, 0 );
my $mandatory =
$isMandatory ? _wrapHtmlMandatoryContainer($MANDATORY_STRING) : '';
my $validationTypeParam = $params->{'validate'};
my $validationType =
$validationTypeParam ? $REQUIRED_TYPE_TABLE{$validationTypeParam} : '';
if ( !$validationTypeParam && $mandatoryParam ) {
$validationType = 's'; # non-empty
}
if ($validationType) {
my $validate = '=' . $validationType;
my $multiple = $MULTIPLE_TYPES{$type} ? $MULTIPLE_TAG_ID : '';
$format .= "$SEP"
. CGI::hidden(
-name => $VALIDATE_TAG . '_' . $name,
-default => "$name$validate$multiple"
);
}
my $conditionParam = $params->{'condition'};
if ($conditionParam) {
$conditionParam =~ m/^\$(.*)?\=(.*)$/go;
my $conditionReferencedField = $1;
my $conditionValue = $2;
my $conditionType =
$conditionValue ? $CONDITION_TYPE_TABLE{$conditionValue} : '';
if ($conditionType) {
my $condition = '=' . $conditionType;
$format .= "$SEP"
. CGI::hidden(
-name => $CONDITION_TAG . '_' . $name,
-default => "$conditionReferencedField$condition"
);
}
}
my $title = $params->{'title'} || '';
my $hint = $params->{'hint'} || '';
$title = _wrapHtmlTitleContainer($title) if $title;
my $titleformat = $params->{'titleformat'} || $defaultTitleFormat;
$format =~ s/\$titleformat/$titleformat/go if $title;
$format =~ s/\$e\b/$element/go;
$format =~ s/\$t\b/$title/go;
$format =~ s/\$m\b/$mandatory/go;
return $format if ( $type eq 'hidden' ); # do not draw any more html
$hint = _wrapHtmlHintContainer($hint) if $hint;
$format =~ s/\$h\b/$hint/go;
my $hintCssClass = $hint ? ' ' . $ELEMENT_GROUP_HINT_CSS_CLASS : '';
$format =~ s/\$_h/$hintCssClass/go;
# clean up tokens if no title
$format =~ s/\$titleformat//go;
$format = _renderFormattingTokens($format);
if ($elementcssclass) {
# not for hidden classes, but these are returned earlier in sub
my $classAttr = ' class="' . $elementcssclass . '"';
$format = '<div class="' . $elementcssclass . '">' . $format . '</div>';
}
# error?
my %formStatus = _status( $currentForm{'name'} );
if ( $formStatus{$STATUS_ERROR} && $name && $errorFields{$name} ) {
$format = _wrapHtmlErrorContainer($format);
}
# add anchor so individual fields can be targeted from any
# error feedback
$format = '<a name="' . _anchorLink($name) . '"></a>' . "$SEP" . $format;
$format =~ s/\n/$SEP/ge if ($SEP ne "\n"); #again, breaks table generation
return $format;
}
=pod
=cut
sub _getFormElementHtml {
my ( $session, $params, $topic, $web ) = @_;
my $name = $params->{'name'} || '';
my $type = $params->{'type'};
my $hasMultiSelect = $type =~ m/^(.*?)multi$/;
$type =~ s/^(.*?)multi$/$1/;
my $value =
$params->{'default'}
|| $params->{'value'}
|| $params->{'buttonlabel'};
my $size = $params->{'size'} || ( $type eq 'date' ? '15' : '40' );
my $maxlength = $params->{'maxlength'};
$size = $maxlength if defined $maxlength && $maxlength < $size;
my ( $options, $labels ) =
_parseOptions( $params->{'options'}, $params->{'labels'} );
my $itemformat = $params->{'fieldformat'};
my $cssClass = $params->{'cssclass'} || '';
$cssClass = _normalizeCssClassName($cssClass);
my $selectedoptions = $params->{'default'} || undef;
my $isMultiple = $MULTIPLE_TYPES{$type};
if ($isMultiple) {
my @values = param($name);
$selectedoptions ||= join( ",", @values );
}
else {
$selectedoptions ||= param($name);
}
my $disabled = $params->{'disabled'} ? 'disabled' : undef;
my $readonly = $params->{'readonly'} ? 'readonly' : undef;
my ( $onFocus, $onBlur, $onClick, $onChange, $onSelect, $onMouseOver,
$onMouseOut, $onKeyUp );
my $beforeclick = $params->{'beforeclick'};
if ($beforeclick) {
$onFocus = 'foswiki.Form.clearBeforeFocusText(this)';
$onBlur = 'foswiki.Form.restoreBeforeFocusText(this)';
# additional init function in _formElement
}
$onFocus ||= $params->{'onFocus'};
$onBlur ||= $params->{'onBlur'};
$onClick ||= $params->{'onClick'};
$onChange ||= $params->{'onChange'};
$onSelect ||= $params->{'onSelect'};
$onMouseOver ||= $params->{'onMouseOver'};
$onMouseOut ||= $params->{'onMouseOut'};
$onKeyUp ||= $params->{'onKeyUp'};
my %extraAttributes = ();
$extraAttributes{'class'} = $cssClass if $cssClass;
$extraAttributes{'disabled'} = $disabled if $disabled;
$extraAttributes{'readonly'} = $readonly if $readonly;
# javascript parameters
$extraAttributes{'-onFocus'} = $onFocus if $onFocus;
$extraAttributes{'-onBlur'} = $onBlur if $onBlur;
$extraAttributes{'-onClick'} = $onClick if $onClick;
$extraAttributes{'-onChange'} = $onChange if $onChange;
$extraAttributes{'-onSelect'} = $onSelect if $onSelect;
$extraAttributes{'-onMouseOver'} = $onMouseOver if $onMouseOver;
$extraAttributes{'-onMouseOut'} = $onMouseOut if $onMouseOut;
$extraAttributes{'onkeyup'} = $onKeyUp if $onKeyUp;
my $element = '';
if ( $type eq 'text' ) {
$element =
_getTextFieldHtml( $session, $name, $value, $size, $maxlength,
%extraAttributes );
}
elsif ( $type eq 'password' ) {
$element =
_getPasswordFieldHtml( $session, $name, $value, $size, $maxlength,
%extraAttributes );
}
elsif ( $type eq 'upload' ) {
$element = _getUploadHtml( $session, $name, 'starting value',
$size, $maxlength, %extraAttributes );
}
elsif ( $type eq 'submit' ) {
$element =
_getSubmitButtonHtml( $session, $name, $value, %extraAttributes );
}
elsif ( $type eq 'radio' ) {
$element = _getRadioButtonGroupHtml( $session, $name, $options, $labels,
$selectedoptions, $itemformat, %extraAttributes );
}
elsif ( $type eq 'checkbox' ) {
$element =
_getCheckboxButtonGroupHtml( $session, $name, $options, $labels,
$selectedoptions, $itemformat, %extraAttributes );
}
elsif ( $type eq 'select' ) {
$element =
_getSelectHtml( $session, $name, $options, $labels, $selectedoptions,
$size, $hasMultiSelect, %extraAttributes );
}
elsif ( $type eq 'dropdown' ) {
# just a select box with size of 1 and no multiple
$element =
_getSelectHtml( $session, $name, $options, $labels, $selectedoptions,
'1', undef, %extraAttributes );
}