-
Notifications
You must be signed in to change notification settings - Fork 12
/
CmsFormHandler.java
2178 lines (1920 loc) · 90.4 KB
/
CmsFormHandler.java
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
/*
* This program is part of the OpenCms Mercury Template.
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package alkacon.mercury.webform;
import alkacon.mercury.template.captcha.CmsCaptchaPluginLoader;
import alkacon.mercury.template.captcha.I_CmsCaptchaProvider;
import alkacon.mercury.webform.captcha.CmsCaptchaServiceCache;
import alkacon.mercury.webform.fields.CmsCaptchaField;
import alkacon.mercury.webform.fields.CmsCheckboxField;
import alkacon.mercury.webform.fields.CmsEmptyField;
import alkacon.mercury.webform.fields.CmsFieldItem;
import alkacon.mercury.webform.fields.CmsFileUploadField;
import alkacon.mercury.webform.fields.CmsHiddenField;
import alkacon.mercury.webform.fields.CmsPagingField;
import alkacon.mercury.webform.fields.CmsParameterField;
import alkacon.mercury.webform.fields.CmsPasswordField;
import alkacon.mercury.webform.fields.CmsPrivacyField;
import alkacon.mercury.webform.fields.CmsTextField;
import alkacon.mercury.webform.fields.I_CmsField;
import alkacon.mercury.webform.fields.I_CmsHasHiddenFieldHtml;
import alkacon.mercury.webform.mail.A_CmsFormMail;
import alkacon.mercury.webform.mail.CmsFormMailICalInfo;
import alkacon.mercury.webform.mail.CmsFormMailRegisterAdmin;
import alkacon.mercury.webform.mail.CmsFormMailRegisterUser;
import alkacon.mercury.webform.stringtemplates.I_CmsTemplateCheckPage;
import alkacon.mercury.webform.stringtemplates.I_CmsTemplateConfirmationPage;
import alkacon.mercury.webform.stringtemplates.I_CmsTemplateError;
import alkacon.mercury.webform.stringtemplates.I_CmsTemplateForm;
import alkacon.mercury.webform.stringtemplates.I_CmsTemplateFormJs;
import alkacon.mercury.webform.stringtemplates.I_CmsTemplateFullyBooked;
import alkacon.mercury.webform.stringtemplates.I_CmsTemplateInitError;
import alkacon.mercury.webform.stringtemplates.I_CmsTemplateSubmissionError;
import org.opencms.cache.CmsVfsMemoryObjectCache;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsResource;
import org.opencms.flex.CmsFlexController;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsMessages;
import org.opencms.i18n.CmsMultiMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.jsp.util.CmsJspStandardContextBean;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.module.CmsModule;
import org.opencms.util.CmsDateUtil;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import java.io.IOException;
import java.io.StringReader;
import java.io.Writer;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.mail.internet.AddressException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.logging.Log;
import org.apache.commons.mail.EmailException;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateErrorListener;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.antlr.stringtemplate.language.DefaultTemplateLexer;
import com.octo.captcha.service.text.TextCaptchaService;
/**
* The form handler controls the HTML or mail output of a configured email form.<p>
*
* Provides methods to determine the action that takes place and methods to create different
* output formats of a submitted form.<p>
*
*/
public class CmsFormHandler extends CmsJspActionElement {
/** Request parameter value for the form action parameter: correct the input. */
public static final String ACTION_CONFIRMED = "confirmed";
/** Request parameter value for the form action parameter: correct the input. */
public static final String ACTION_CORRECT_INPUT = "correct";
/** Request parameter value for the form action parameter: form submitted. */
public static final String ACTION_SUBMIT = "submit";
/** Name of the file item session attribute. */
public static final String ATTRIBUTE_FILEITEMS = "fileitems";
/** Configuration key name for the 'end time' of an event. */
public static final String CONFIG_END_TIME = "EndTime";
/** Form error: mandatory field not filled out. */
public static final String ERROR_MANDATORY = "mandatory";
/** Error: failed to save form data in the XML-content. */
public static final String ERROR_STORE_FORMDATA = "storedata";
/** Form error: unique error of input. */
public static final String ERROR_UNIQUE = "unique";
/** Form error: validation error of input. */
public static final String ERROR_VALIDATION = "validation";
/** HTTP webform response header. */
public static final String HEADER_OC_WEBFORM = "X-Oc-Webform";
/** HTTP webform response header value. */
public static final String HEADER_VALUE_OC_WEBFORM = "YES";
/** Form info: mandatory upload field filled out already. */
public static final String INFO_UPLOAD_FIELD_MANDATORY_FILLED_OUT = "uploadfield_mandatory_filled_out";
/** Macro name for the waitlist information macro that can be used in registration mail text fields. */
public static final String MACRO_EVENT_WAITLIST_INFO = "event.waitlist.info";
/** Macro name for the date macro that can be used in mail text fields. */
public static final String MACRO_DATE = "date";
/** Macro name for the form data macro that can be used in mail text fields. */
public static final String MACRO_FORMDATA = "formdata";
/** Macro name for the locale macro that can be used in mail text fields. */
public static final String MACRO_LOCALE = "locale";
/** Macro prefix for field values. */
public static final String MACRO_PREFIX_VALUE = "value_";
/** Macro name for the url macro that can be used in mail text fields. */
public static final String MACRO_URL = "url";
/** Request parameter name for the back parameter. */
public static final String PARAM_BACK = "back";
/** Request parameter name for the final page parameter. */
public static final String PARAM_FINALPAGE = "finalpage";
/** Request parameter name for the hidden form action parameter to determine the action. */
public static final String PARAM_FORMACTION = "formaction";
/** Request parameter name for the page parameter. */
public static final String PARAM_PAGE = "page";
/** Request parameter uri for the page parameter. */
public static final String PARAM_URI = "uri";
/** Prefix for encrypted String values. */
public static final String PREFIX_ENCRYPTED = "encrypted:";
/** The module path of the webform module. */
static final String MODULE_PATH = CmsWorkplace.VFS_PATH_MODULES + CmsForm.MODULE_NAME + "/";
/** Path to the captcha.jsp. */
static final String PATH_CAPTCHA_JSP = MODULE_PATH + "elements/captcha.jsp";
/** Path to the keepsession.js. */
static final String PATH_KEEP_SESSION_JS = MODULE_PATH + "resources/js/keepsession.js";
/** Path to the keepsession.jsp. */
static final String PATH_KEEP_SESSION_JSP = MODULE_PATH + "elements/keepsession.jsp";
/** Path to the subfields.js. */
static final String PATH_SUBFIELDS_JS = MODULE_PATH + "resources/js/subfields.js";
/** Prefix for dynamic config values that should be used as macros. */
private static final String DYNAMIC_CONFIG_PREFIX_MACRO = "macro:";
/** Error that happened when the confirmation mail was tried to send. */
private static final String ERROR_CONFIRMATION_SENT = "confirmationsent";
/** Error that happened when the confirmation mail was tried to send. */
private static final String ERROR_REGISTRATION_SENT = "registrationsent";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsFormHandler.class);
/** Contains eventual validation errors. */
protected Map<String, String> m_errors;
/** The form configuration object. */
protected CmsForm m_formConfiguration;
/** Temporarily stores the fields as hidden fields in the String. */
protected String m_hiddenFields;
/** Contains eventual validation infos. */
protected Map<String, String> m_infos;
/** Flag indicating if the form is displayed for the first time. */
protected boolean m_initial;
/** Flag indicating if the form handler configuration has been initialized successfully. */
protected boolean m_initSuccess;
/** Boolean indicating if the form is validated correctly. */
protected Boolean m_isValidatedCorrect;
/** Needed to implant form fields into the mail text. */
protected transient CmsMacroResolver m_macroResolver;
/** The localized messages for the form handler. */
protected CmsMultiMessages m_messages;
/** The multipart file items. */
protected List<FileItem> m_multipartFileItems;
/** The templates for the web form output. */
protected StringTemplateGroup m_outputTemplates;
/** The map of request parameters. */
protected Map<String, String[]> m_parameterMap;
/** The submission status of the form. Initialized lazily. */
protected CmsSubmissionStatus m_submissionStatus;
/** For the case of bookable events, this is the end time of the event, otherwise null. */
private Long m_endTime;
/** The iCalendar information. */
private CmsFormMailICalInfo m_iCalInfo;
/** The resource path of the event configuration. */
private String m_eventConfiguration;
/**
* Empty constructor, be sure to call one of the available initialization methods afterwards.<p>
*
* Possible initialization methods are:<p>
* <ul>
* <li>{@link #init(PageContext, HttpServletRequest, HttpServletResponse)}</li>
* <li>{@link #init(PageContext, HttpServletRequest, HttpServletResponse, String)}</li>
* </ul>
*/
public CmsFormHandler() {
super();
m_errors = new HashMap<>();
m_infos = new HashMap<>();
}
/**
* Gets the truncated file item name. Some clients, such as the Opera browser, do include path information.
* This method only returns the the base file name.<p>
*
* @param name the file item name
*
* @return the truncated file item name
*/
public static String getTruncatedFileItemName(String name) {
// here is not used the File.separator, because there are problems is the
// OpenCms OS and the explores OS are different
// for example if you have an OpenCms on Unix and you use the
// formgenerator in a browser in Windows
if (name.contains("/")) {
int lastIndex = name.lastIndexOf("/");
if (name.length() > lastIndex) {
name = name.substring(lastIndex + 1);
return name;
}
} else if (name.contains("\\")) {
int lastIndex = name.lastIndexOf("\\");
if (name.length() > lastIndex) {
name = name.substring(lastIndex + 1);
return name;
}
}
return name;
}
/**
* Adds on the first position the given messages.<p>
*
* @param messages the localized messages
*/
public void addMessages(CmsMessages messages) {
CmsMultiMessages tmpOld = m_messages;
m_messages = new CmsMultiMessages(messages.getLocale());
m_messages.addMessages(messages);
if (tmpOld != null) {
m_messages.addMessages(tmpOld.getMessages());
}
tmpOld = null;
}
/**
* Replaces line breaks with html <br>.<p>
*
* @param value the value to substitute
* @return the substituted value
*/
public String convertToHtmlValue(String value) {
return convertValue(value, "html");
}
/**
* Replaces html <br> with line breaks.<p>
*
* @param value the value to substitute
* @return the substituted value
*/
public String convertToPlainValue(String value) {
return convertValue(value, "");
}
/**
* Converts a given String value to the desired output format.<p>
*
* The following output formats are possible:
* <ul>
* <li>"HTML" meaning that <br> tags are added</li>
* <li>"plain" or any other String value meaning that <br> tags are removed</li>
* </ul>
*
* @param value the String value to convert
* @param outputType the type of the resulting output
* @return the converted String in the desired output format
*/
public String convertValue(String value, String outputType) {
if ("html".equalsIgnoreCase(outputType)) {
// output should be HTML, add line break tags and characters
value = CmsStringUtil.escapeHtml(value);
} else {
// output should be plain, remove HTML line break tags and characters
value = CmsStringUtil.substitute(value, "<br>", "\n");
}
return value;
}
/**
* Creates the main web form output for usage on a JSP.<p>
*
* @throws IOException if an I/O error occurs
* @throws ServletException if forwarding goes wrong
*/
public void createForm() throws IOException, ServletException {
// the output writer
Writer out = getJspContext().getOut();
// include eventual JavaScript
out.write(buildNecessaryJavaScript());
// check the template group syntax and show eventual errors
out.write(buildTemplateGroupCheckHtml());
if (!isInitSuccess()) {
// form was not configured correctly, show error message
out.write(buildInitError());
} else if (showRelease()) {
// form is still to be released, show release text
out.write(getFormConfiguration().getReleaseText());
} else if (showExpired()) {
// form is expired, show expiration text
out.write(getFormConfiguration().getExpirationText());
} else if (!showForm() && isValidFormaction()) {
// form has been submitted with correct values, decide further actions
if (showCheck()) {
// show optional check page
out.write(buildCheckHtml());
} else {
// try to send a notification email with the submitted form field values
String errorLinkTarget = executeBeforeWebformAction();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(errorLinkTarget)) {
getResponse().sendRedirect(link(errorLinkTarget));
return;
}
if (sendData()) {
// successfully stored data and/or sent email, decide further actions
// prepare the web form action class if configured
executeAfterWebformAction();
if (getFormConfiguration().hasTargetUri() && !getFormConfiguration().isInstantRedirect()) {
onSuccessRedirect();
} else {
// show confirmation end page
out.write(buildConfirmHtml());
}
} else {
out.write(buildFailureHtml());
}
}
} else {
if (getSubmissionStatus().isFullyBooked()) {
out.write(buildFullyBookedHtml());
} else {
// create the main input form
out.write(buildFormHtml());
}
}
}
/**
* Returns the configured form field values as hidden input fields.<p>
*
* @return the configured form field values as hidden input fields
*/
public String createHiddenFields() {
if (CmsStringUtil.isEmpty(m_hiddenFields)) {
List<I_CmsField> fields = getFormConfiguration().getAllFields(true, false, false);
StringBuffer result = new StringBuffer(fields.size() * 8);
// iterate the form fields
for (int i = 0, n = fields.size(); i < n; i++) {
I_CmsField currentField = fields.get(i);
if (currentField == null) {
continue;
} else if (CmsCheckboxField.class.isAssignableFrom(currentField.getClass())) {
// special case: checkbox, can have more than one value
Iterator<CmsFieldItem> k = currentField.getItems().iterator();
while (k.hasNext()) {
CmsFieldItem item = k.next();
if (item.isSelected()) {
result.append("<input type=\"hidden\" name=\"");
result.append(currentField.getName());
result.append("\" value=\"");
result.append(CmsEncoder.escapeXml(item.getValue()));
result.append("\" />\n");
}
}
} else if (CmsParameterField.class.equals(currentField.getClass())) {
// special case: table, can have more than one value
//Iterator<CmsFieldItem> k = currentField.getItems().iterator();
result.append("<input type=\"hidden\" name=\"");
result.append(currentField.getName());
result.append("\" value=\"");
result.append(CmsEncoder.escapeXml(currentField.getValue()));
result.append("\" />\n");
result.append(
CmsParameterField.createHiddenFields(getParameterMap(), currentField.getParameters()));
} else if (currentField instanceof I_CmsHasHiddenFieldHtml) {
String hiddenFieldHtml = ((I_CmsHasHiddenFieldHtml)currentField).getHiddenFieldHtml();
result.append(hiddenFieldHtml);
} else if (CmsStringUtil.isNotEmpty(currentField.getValue())) {
// all other fields are converted to a simple hidden field
result.append("<input type=\"hidden\" name=\"");
result.append(currentField.getName());
result.append("\" value=\"");
result.append(CmsEncoder.escapeXml(currentField.getValue()));
result.append("\" />\n");
}
}
// store the generated input fields for further usage to avoid unnecessary rebuilding
m_hiddenFields = result.toString();
}
// return generated result list
return m_hiddenFields;
}
/**
* Creates the form submission mail for the submitted fields.<p>
* @param isConfirmationMail whether to create a confirmation mail
* @return the form submission mail
*/
public A_CmsFormMail createRegistrationMail(boolean isConfirmationMail) {
boolean isHtmlMail = getFormConfiguration().getMailType().equals(CmsForm.MAILTYPE_HTML);
List<I_CmsField> fieldValues = getFormConfiguration().getAllFields(true, false, true);
List<CmsFormDataField> formDataFields = new ArrayList<>(fieldValues.size());
StringBuffer formDataString = new StringBuffer(fieldValues.size() * 16);
Iterator<I_CmsField> i = fieldValues.iterator();
while (i.hasNext()) {
I_CmsField current = i.next();
if (current instanceof CmsPagingField) {
continue;
}
if (!useInFormDataMacro(current)) {
continue;
}
// only show the empty field in the confirmation mail, if it is marked as mandatory
if ((current instanceof CmsEmptyField) && !current.isMandatory()) {
continue;
}
String value = current.toString();
if (current instanceof CmsFileUploadField) {
value = current.getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) {
// try to read upload item from session attribute
FileItem fileItem = getUploadFile(current);
if (fileItem != null) {
value = fileItem.getName();
}
}
value = CmsFormHandler.getTruncatedFileItemName(value);
}
if (isHtmlMail) {
// format field label as HTML
String label = current.getLabel();
// special case for table and empty fields
if (current instanceof CmsEmptyField) {
label = "";
}
// format field value as HTML
String fieldValue = convertToHtmlValue(value);
// special case for table and empty fields
if (current instanceof CmsEmptyField) {
fieldValue = value;
}
// if label and value is not set, skip it
if (CmsStringUtil.isEmpty(label) && CmsStringUtil.isEmpty(fieldValue)) {
continue;
}
CmsFormDataField mailField = new CmsFormDataField(label, fieldValue);
formDataFields.add(mailField);
} else {
// format output as plain text
String label;
try {
label = CmsHtmlToTextConverter.htmlToText(
current.getLabel(),
getCmsObject().getRequestContext().getEncoding(),
true).trim();
} catch (Exception e) {
// error parsing the String, provide it as is
label = current.getLabel();
}
// if label and value is not set, skip it
if (CmsStringUtil.isEmpty(label) && CmsStringUtil.isEmpty(value)) {
continue;
} else if (current instanceof CmsEmptyField) {
label = "";
}
formDataString.append(label);
formDataString.append("\t\t");
formDataString.append(value);
formDataString.append("\n");
}
}
return isConfirmationMail
? new CmsFormMailRegisterUser(this, formDataFields, formDataString)
: new CmsFormMailRegisterAdmin(this, formDataFields, formDataString);
}
/**
* Executes the after web form action.<p>
*/
public void executeAfterWebformAction() {
String actionClass = getFormConfiguration().getActionClass();
if (CmsStringUtil.isNotEmpty(actionClass)) {
try {
I_CmsWebformActionHandler handler = getObject(actionClass);
handler.afterWebformAction(getCmsObject(), this);
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Invalid webform action handler class: " + actionClass, e);
}
}
}
}
/**
* Executes the before web form action.<p>
*
* @return <code>null</code> if successful, otherwise a redirect link for the failure case.
*/
public String executeBeforeWebformAction() {
String actionClass = getFormConfiguration().getActionClass();
if (CmsStringUtil.isNotEmpty(actionClass)) {
try {
I_CmsWebformActionHandler handler = getObject(actionClass);
return handler.beforeWebformAction(getCmsObject(), this);
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Invalid webform action handler class: " + actionClass, e);
}
}
}
return null;
}
/**
* Returns the errors found when validating the form.<p>
*
* @return the errors found when validating the form
*/
public Map<String, String> getErrors() {
return m_errors;
}
/**
* Returns the check page text, after resolving macros.<p>
*
* @return the check page text
*/
public String getFormCheckText() {
CmsMacroResolver macroResolver = CmsMacroResolver.newInstance();
macroResolver.setKeepEmptyMacros(true);
List<I_CmsField> fields = getFormConfiguration().getFields();
addFieldMacros(macroResolver, fields, false);
return macroResolver.resolveMacros(getFormConfiguration().getFormCheckText());
}
/**
* Returns the form configuration.<p>
*
* @return the form configuration
*/
public CmsForm getFormConfiguration() {
return m_formConfiguration;
}
/**
* Returns the confirmation text, after resolving macros.<p>
*
* @return the confirmation text
*/
public String getFormConfirmationText() {
return m_macroResolver.resolveMacros(getFormConfiguration().getFormConfirmationText());
}
/**
* Returns the iCalendar information.
* @return the iCalendar information
*/
public CmsFormMailICalInfo getICalInfo() {
return m_iCalInfo;
}
/**
* Returns the infos found when validating the form.<p>
*
* @return the infos found when validating the form
*/
public Map<String, String> getInfos() {
return m_infos;
}
/**
* Returns the macro resolver.<p>
*
* @return the resolver
*/
public CmsMacroResolver getMacroResolver() {
return m_macroResolver;
}
/**
* Returns the localized messages.<p>
*
* @return the localized messages
*/
public CmsMessages getMessages() {
return m_messages;
}
/**
* Returns the template for the web form HTML output.<p>
*
* @param templateName the name of the template to return
*
* @return the template for the web form HTML output
*/
public StringTemplate getOutputTemplate(String templateName) {
StringTemplate result = getOutputTemplateGroup().getInstanceOf(templateName);
if (!getRequestContext().getCurrentProject().isOnlineProject() && (result == null)) {
// no template with the specified name found, return initialized error template
try {
CmsFile stFile = getCmsObject().readFile(CmsForm.VFS_PATH_ERROR_TEMPLATEFILE);
String stContent = new String(stFile.getContents(), getCmsObject().getRequestContext().getEncoding());
result = new StringTemplate(stContent, DefaultTemplateLexer.class);
// set the error attributes of the template
result.setAttribute(I_CmsTemplateError.ATTR_ERROR_HEADLINE, "Error getting output template");
result.setAttribute(
I_CmsTemplateError.ATTR_ERROR_TEXT,
"The desired template \"" + templateName + "\" was not found.");
result.setAttribute(
I_CmsTemplateError.ATTR_ERROR_TEMPLATE_NAMES,
getOutputTemplateGroup().getTemplateNames());
} catch (Exception e) {
// something went wrong, log error
LOG.error(
"Error while getting error output template from file \""
+ CmsForm.VFS_PATH_ERROR_TEMPLATEFILE
+ "\".");
}
}
return result;
}
/**
* Returns the output template group that generates the web form HTML output.<p>
*
* @return the output template group that generates the web form HTML output
*/
public StringTemplateGroup getOutputTemplateGroup() {
if (m_outputTemplates == null) {
String vfsPath = null;
if (getFormConfiguration() != null) {
// check if an individual output template path is set
vfsPath = getFormConfiguration().getTemplateFile();
if (!getCmsObject().existsResource(vfsPath)) {
// configured output template path does not exist, log error and use default output templates
LOG.error("Configured web form HTML output template file \"" + vfsPath + "\" does not exist.");
vfsPath = null;
}
}
if (vfsPath == null) {
// no valid template path configured, use default output templates
vfsPath = OpenCms.getModuleManager().getModule(CmsForm.MODULE_NAME).getParameter(
CmsForm.MODULE_PARAM_TEMPLATE_FILE,
CmsForm.VFS_PATH_DEFAULT_TEMPLATEFILE);
}
try {
// first try to get the initialized template group from VFS cache
String rootPath = getRequestContext().addSiteRoot(vfsPath);
StringTemplateGroup stGroup = (StringTemplateGroup)CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().getCachedObject(
getCmsObject(),
rootPath);
if (stGroup == null) {
// template group is not in cache, read the file and generate template group
CmsFile stFile = getCmsObject().readFile(vfsPath);
String stContent = new String(
stFile.getContents(),
getCmsObject().getRequestContext().getEncoding());
StringTemplateErrorListener errors = new CmsStringTemplateErrorListener();
stGroup = new StringTemplateGroup(new StringReader(stContent), DefaultTemplateLexer.class, errors);
// store the template group in cache
CmsVfsMemoryObjectCache.getVfsMemoryObjectCache().putCachedObject(
getCmsObject(),
rootPath,
stGroup);
}
m_outputTemplates = stGroup;
} catch (Exception e) {
// something went wrong, log error
LOG.error("Error while creating web form HTML output templates from file \"" + vfsPath + "\".");
}
}
return m_outputTemplates;
}
/**
* Returns the request parameter with the specified name.<p>
*
* @param parameter the parameter to return
*
* @return the parameter value
*/
public String getParameter(String parameter) {
if (PARAM_FORMACTION.equals(parameter) || CmsForm.PARAM_SENDCONFIRMATION.equals(parameter)) {
parameter += getFormConfiguration().getConfigId();
}
try {
return (m_parameterMap.get(parameter))[0];
} catch (NullPointerException e) {
return "";
}
}
/**
* Returns the map of request parameters.<p>
*
* @return the map of request parameters
*/
public Map<String, String[]> getParameterMap() {
return m_parameterMap;
}
/**
* Returns the lazily initialized submission status.
* @return the lazily initialized submission status.
*/
public CmsSubmissionStatus getSubmissionStatus() {
if (null == m_submissionStatus) {
try {
m_submissionStatus = new CmsSubmissionStatus(
CmsWebformModuleAction.getAdminCms(getCmsObject()),
getFormConfiguration().getUgcConfiguration());
} catch (CmsException e) {
LOG.error("Failed to initialize submission status of the form. Using default submission status.", e);
m_submissionStatus = new CmsSubmissionStatus();
}
}
return m_submissionStatus;
}
/**
* Return <code>null</code> or the file item for the given field in
* case it is of type <code>{@link CmsFileUploadField}</code>.<p>
*
* @param isFileUploadField the field to the the file item of
*
* @return <code>null</code> or the file item for the given field in
* case it is of type <code>{@link CmsFileUploadField}</code>
*/
public FileItem getUploadFile(I_CmsField isFileUploadField) {
FileItem result = null;
FileItem current;
String fieldName = isFileUploadField.getName();
String uploadFileFieldName;
Map<String, FileItem> fileUploads = getFileUploads();
if (fileUploads != null) {
Iterator<FileItem> i = fileUploads.values().iterator();
while (i.hasNext()) {
current = i.next();
uploadFileFieldName = current.getFieldName();
if (fieldName.equals(uploadFileFieldName)) {
result = current;
}
}
}
return result;
}
/**
* Returns if the submitted values contain validation errors.<p>
*
* @return <code>true</code> if the submitted values contain validation errors, otherwise <code>false</code>
*/
public boolean hasValidationErrors() {
return (!isInitial() && (getErrors().size() > 0));
}
/**
* Initializes the form handler and creates the necessary configuration objects.<p>
*
* @see org.opencms.jsp.CmsJspBean#init(javax.servlet.jsp.PageContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public void init(PageContext context, HttpServletRequest req, HttpServletResponse res) {
try {
init(context, req, res, null);
} catch (CmsException e) {
// log initialization error
LOG.error(e);
}
}
/**
* Initializes the form handler and creates the necessary configuration objects.<p>
*
* @param context the JSP page context object
* @param req the JSP request
* @param res the JSP response
* @param formConfigUri URI of the form configuration file, if not provided, current URI is used for configuration
*
* @throws CmsException if initializing the form message objects fails
*/
public void init(PageContext context, HttpServletRequest req, HttpServletResponse res, String formConfigUri)
throws CmsException {
init(context, req, res, formConfigUri, null);
}
/**
* Initializes the form handler and creates the necessary configuration objects.<p>
*
* @param context the JSP page context object
* @param req the JSP request
* @param res the JSP response
* @param formConfigUri URI of the form configuration file, if not provided, current URI is used for configuration
* @param dynamicConfig map of configurations that can overwrite the configuration from the configuration file
*
* @throws CmsException if initializing the form message objects fails
*/
public void init(
PageContext context,
HttpServletRequest req,
HttpServletResponse res,
String formConfigUri,
Map<String, String> dynamicConfig)
throws CmsException {
init(context, req, res, formConfigUri, dynamicConfig, null);
}
/**
* Initializes the form handler and creates the necessary configuration objects.<p>
*
* @param context the JSP page context object
* @param req the JSP request
* @param res the JSP response
* @param formConfigUri URI of the form configuration file, if not provided, current URI is used for configuration
* @param dynamicConfig map of configurations that can overwrite the configuration from the configuration file
* @param extraConfig a map of additional configuration values to be accessed in the string template.
*
* @throws CmsException if initializing the form message objects fails
*/
public void init(
PageContext context,
HttpServletRequest req,
HttpServletResponse res,
String formConfigUri,
Map<String, String> dynamicConfig,
Map<String, String> extraConfig)
throws CmsException {
super.init(context, req, res);
try {
// set the webform HTTP header
HttpServletResponse topResponse = CmsFlexController.getController(req).getTopResponse();
topResponse.setHeader(HEADER_OC_WEBFORM, HEADER_VALUE_OC_WEBFORM);
// initialize the form configuration
configureForm(req, formConfigUri, dynamicConfig, extraConfig);
m_initSuccess = true;
} catch (Exception e) {
LOG.error(e);
// error in form initialization, initialize at least the localized messages
initMessages(formConfigUri);
}
}
/**
* Returns if the form is displayed for the first time.<p>
*
* @return <code>true</code> if the form is displayed for the first time, otherwise <code>false</code>
*/
public boolean isInitial() {
return m_initial;
}
/**
* Returns if the form handler configuration has been initialized successfully.<p>
*
* @return <code>true</code> if the form handler configuration has been initialized successfully, otherwise <code>false</code>
*/
public boolean isInitSuccess() {
return m_initSuccess;
}
/**
* Returns if the formaction is of predefined value.<p>
*
* @return <code>true</code> if the formaction is valid, otherwise <code>false</code>
*/
public boolean isValidFormaction() {
String formAction = getParameter(PARAM_FORMACTION);