This repository has been archived by the owner on Mar 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 207
/
eform.inc.php
1242 lines (1101 loc) · 48 KB
/
eform.inc.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
# eForm 1.4.6 - Electronic Form Snippet
# Original created by: Raymond Irving 15-Dec-2004.
# Extended by: Jelle Jager (TobyL) September 2006
# -----------------------------------------------------
#
#
# Captcha image support - thanks to Djamoer
# Multi checkbox, radio, select support - thanks to Djamoer
# Form Parser and extended validation - by Jelle Jager
#
# see docs/eform.htm for installation and usage information
#
# VERSION HISTORY
# Work around for setting required class on check & radio labels
# fixed bug: If eform attibute is set on multiple check boxes only the last
# value is set in values list
# For a full version history see the eform_history.htm file in the docs directory
#
# Some more fixes and problems:
# FIXED: reg expression failed for select and textarea boxes which have regex special
# characters in their name attribute. eg name="multipleSelection[]"
# FIXED: validation of multiple values with #LIST & #SELECT stopped after 1st value
# Caused by repeating $v variable naming (overwriting $v array)
# e.g.
# <select name="multipleSelection[]" multiple="multiple" eform="::1::"/>
# <option value="1">1</option>
# <option value="2">2</option>
# <option value="3">3</option>
# </select>
# would only have the first selected value validated!
#
# bugfix: &jScript parameter doesn't accept chunks, only a link to a JS file if more than one chunk is declared (eg &jScript=`chunk1,chunk2)
# bugfix: &protectSubmit creates hash for all fields instead of fields declared in &protectSubmit
# bugfix: Auto respond email didn't honour the &sendAsText parameter
# bugfix: The #FUNCTION validation rule for select boxes never calls the function
# bugfix: Validation css class isn't being added to labels.
#
# SECURITY FIX: add additional sanitization to fields after stripping slashes to avoid remote tag execution
##
$GLOBALS['optionsName'] = "eform"; //name of pseudo attribute used for format settings
$GLOBALS['efPostBack'] = false;
function eForm($modx,$params) {
global $_lang;
global $debugText;
global $formats,$fields,$efPostBack;
$fields = array(); //reset fields array - needed in case of multiple forms
// define some variables used as array index
$_dfnMaxlength = 6;
extract($params,EXTR_SKIP); // extract params into variables
$fileVersion = '1.4.6';
$version = isset($version)?$version:'prior to 1.4.2';
#include default language file
include_once($snipPath."lang/english.inc.php");
#include other language file if set.
$form_language = isset($language)?$language:$modx->config['manager_language'];
if($form_language!="english" && $form_language!='') {
if(file_exists($snipPath ."lang/".$form_language.".inc.php"))
include_once $snipPath ."lang/".$form_language.".inc.php";
else
if( $isDebug ) $debugText .= "<strong>Language file '$form_language.inc.php' not found!</strong><br />"; //always in english!
}
# add debug warning - moved again...
if( $isDebug ) $debugText .= $_lang['ef_debug_warning'];
//check version differences
if( $version != $fileVersion )
return formMerge($_lang['ef_version_error'], array('version' => $version, 'fileVersion' => $fileVersion));
# check for valid form key - moved to below fetching form template to allow id coming from form template
$nomail = $noemail; //adjust variable name confusion
# activate nomail if missing $to
if (!$to) $nomail = 1;
# load templates
if($tpl==$modx->documentIdentifier) return $_lang['ef_is_own_id']."'$tpl'";
//required
if( $tmp=efLoadTemplate($tpl) ) $tpl=$tmp; else return $_lang['ef_no_doc'] . " '$tpl'";
# check for valid form key
if ($formid=="") return $_lang['ef_error_formid'];
// try to get formid from <form> tag id
preg_match('/<form[^>]*?id=[\'"]([^\'"]*?)[\'"]/i',$tpl,$matches);
$form_id = isset($matches[1])?$matches[1]:'';
//check for <input type='hidden name='formid'...>
if( !preg_match('/<input[^>]*?name=[\'"]formid[\'"]/i',$tpl) ){
//insert hidden formid field
$tpl = str_replace('</form>',"<input type=\"hidden\" name=\"formid\" value=\"$form_id\" /></form>",$tpl);
}
$validFormId = ($formid==$_POST['formid'])?1:0;
# check if postback mode
$efPostBack = ($validFormId && count($_POST)>0)? true:false; //retain old variable?
if($efPostBack){
$report = (($tmp=efLoadTemplate($report))!==false)?$tmp:$_lang['ef_no_doc'] . " '$report'";
if($thankyou) $thankyou = (($tmp=efLoadTemplate($thankyou))!==false )?$tmp:$_lang['ef_no_doc'] . " '$thankyou'";
if($autotext) $autotext = (($tmp=efLoadTemplate($autotext))!==false )?$tmp:$_lang['ef_no_doc'] . " '$autotext'";
}
//these will be added to the HEAD section of the document when the form is displayed!
if($cssStyle){
$cssStyle = ( strpos($cssStyle,',') && strpos($cssStyle,'<style')===false ) ? explode(',',$cssStyle) : array($cssStyle);
foreach( $cssStyle as $tmp ) $startupSource[]= array($tmp,'css');
}
if($jScript){
$jScript = ( strpos($jScript,',') && strpos($jScript,'<script')===false ) ? explode(',',$jScript) : array($jScript);
foreach( $jScript as $tmp )
$startupSource[]= array($tmp,'javascript');
}
#New in 1.4.4 - run snippet to include 'event' functions
if( strlen($runSnippet)>0 ){
$modx->runSnippet($runSnippet, array('formid'=>$formid));
//Sadly we cannot know if the snippet fails or if it exists as modx->runsnippet's return value
//is ambiguous
}
# invoke onBeforeFormParse event set by another script
// Changed in 1.4.4.8 - Multiple event functions separated by comma.
if ($eFormOnBeforeFormParse) {
$eFormOnBeforeFormParse = array_filter(array_map('trim', explode(',', $eFormOnBeforeFormParse)));
foreach ($eFormOnBeforeFormParse as $beforeFormParse) {
if ($isDebug && !function_exists($beforeFormParse)) {
$fields['debug'] .= 'eFormOnBeforeFormParse event: Could not find the function ' . $beforeFormParse;
} else {
$templates = array('tpl' => $tpl, 'report' => $report, 'thankyou' => $thankyou, 'autotext' => $autotext);
if ($beforeFormParse($fields, $templates) === false) {
return '';
} elseif (is_array($templates)) {
extract($templates); // extract back into original variables
}
}
}
}
# parse form for formats and generate placeholders
$tpl = eFormParseTemplate($tpl,$isDebug);
if ($efPostBack) {
foreach($formats as $k => $discard)
if(!isset($fields[$k])) $fields[$k] = ""; // store dummy value inside $fields
$disclaimer = (($tmp=efLoadTemplate($disclaimer))!==false )? $tmp:'';
//error message containers
$vMsg = $rMsg = $rClass = array();
# get user post back data
foreach($_POST as $name => $value){
if(is_array($value)){
//remove empty values
$fields[$name] = array_filter($value,create_function('$v','return (!empty($v));'));
} else {
if ($allowhtml && $formats[$name][2]=='html') {
$fields[$name] = stripslashes($value);
} else {
$fields[$name] = strip_tags(stripslashes($value));
}
}
}
# get uploaded files
foreach($_FILES as $name => $value){
$fields[$name] = $value;
}
# check vericode
if($vericode) {
//add support for captcha code - thanks to Djamoer
$code = $_SESSION['veriword'] ? $_SESSION['veriword'] : $_SESSION['eForm.VeriCode'];
if($fields['vericode']!=$code) {
$vMsg[count($vMsg)]=$_lang['ef_failed_vericode'];
$rClass['vericode']=$invalidClass; //added in 1.4.4
}
}
# sanitize the values with slashes stripped to avoid remote execution of Snippets
$version = $modx->getVersionData();
if (version_compare($version['version'], '1.0.9', '<=')) {
modx_sanitize_gpc($fields, array(
'@<script[^>]*?>.*?</script>@si',
'@&#(\d+);@e',
'@\[\~(.*?)\~\]@si',
'@\[\((.*?)\)\]@si',
'@{{(.*?)}}@si',
'@\[\+(.*?)\+\]@si',
'@\[\*(.*?)\*\]@si',
'@\[\[(.*?)\]\]@si',
'@\[!(.*?)!\]@si'
));
}
# validate fields
foreach($fields as $name => $value) {
$fld = $formats[$name];
if ($fld) {
$desc = $fld[1];
$datatype = $fld[2];
$isRequired = $fld[3];
if ($isRequired==1 && $value=="" && $datatype!="file"){
$rMsg[count($rMsg)]="$desc";
$rClass[$name]=$requiredClass;
}elseif( !empty($fld[5]) && $value!="" && $datatype!="file" ) {
$value = validateField($value,$fld,$vMsg,$isDebug);
if($value===false) $rClass[$name]=$invalidClass;
//if returned value is not of type boolean replace value...
elseif($value!==true) $fields[$name]=$value; //replace value.
}else{ //value check
switch ($datatype){
case "integer":
case "float":
if (strlen($value)>0 && !is_numeric($value)){
$vMsg[count($vMsg)]=$desc . $_lang["ef_invalid_number"];
$rClass[$name]=$invalidClass;
}
break;
case "date":
if(strlen($value)==0) break;
//corrected by xwisdom for php version differences
$rt = strtotime($value); //php 5.1.0+ returns false while < 5.1.0 returns -1
if ($rt===false||$rt===-1){
$vMsg[count($vMsg)]=$desc . $_lang["ef_invalid_date"];
$rClass[$name]=$invalidClass;
}
break;
case "email":
//stricter email validation - udated to allow + in local name part
if (strlen($value)>0 && !preg_match(
'/^(?:[a-z0-9+_-]+?\.)*?[a-z0-9_+-]+?@(?:[a-z0-9_-]+?\.)*?[a-z0-9_-]+?\.[a-z0-9]{2,5}$/i', $value) ){
$vMsg[count($vMsg)] = isset($formats[$name][4]) ? $formats[$name][4] : $desc . $_lang["ef_invalid_email"];
$rClass[$name]=$invalidClass;
}
break;
case "phone":
if (strlen($value)>0 && !preg_match(
'/^((8|\+7)[\- ]?)?(\(?\d{3}\)?[\- ]?)?[\d\- ]{7,10}$/', $value) ){
$vMsg[count($vMsg)]=$desc . $_lang["ef_invalid_phone"];
$rClass[$name]=$invalidClass;
}
break;
case "file":
if ($_FILES[$name]['error']==1 || $_FILES[$name]['error']==2){
$vMsg[count($vMsg)]=$desc . $_lang['ef_upload_exceeded'];
$rClass[$name]=$invalidClass;
}elseif ($isRequired==1 && ($_FILES[$name] && $_FILES[$name]['type']=='')){
$rMsg[count($rMsg)]=$desc;
$rClass[$name]=$requiredClass;
}elseif ($_FILES[$name]['tmp_name']){
if( substr($fld[5],0,5)!="#LIST" || validateField($_FILES[$name]['name'],$fld,$vMsg,$isDebug) )
$attachments[count($attachments)] = $_FILES[$name]['tmp_name'];
else $rClass[$name]=$invalidClass;
}
break;
case "html":
case "checkbox":
case "string":
default:
break;
}
}//end required test
}
}
// Changed in 1.4.4.5 - now expects 4 parameters
// Changed in 1.4.4.8 - Multiple event functions separated by comma.
if ($eFormOnValidate) {
$eFormOnValidate = array_filter(array_map('trim', explode(',', $eFormOnValidate)));
foreach ($eFormOnValidate as $onValidate) {
if ($isDebug && !function_exists($onValidate)) {
$fields['debug'] .= 'eformOnValidate event: Could not find the function ' . $onValidate;
} else {
if ($onValidate($fields, $vMsg, $rMsg, $rClass) === false) {
return;
}
}
}
}
if(count($vMsg)>0 || count($rMsg)>0){
//New in 1.4.2 - classes are set in labels and form elements for invalid fields
foreach($rClass as $n => $class){
$fields[$n . '_class'] = $fields[$n . '_class'] ? ' ' . $fields[$n . '_class'] . ' ' . $class : ' ' . $class;
$fields[$n.'_vClass'] = $fields[$n.'_vClass']?$fields[$n.'_vClass'].' '. $class:$class;
//work around for checkboxes
if( isset($formats[$n][6] )){ //have separate id's for check and option tags - set classes as well
foreach( explode(',',$formats[$n][6]) as $id)
$fields[$id.'_vClass'] = $fields[$id.'_vClass'] ? $fields[$id.'_vClass'].' '. $class : $class;
}
}
//add debugging info to fields array
if($isDebug){
ksort($fields);
if($isDebug>1){
$debugText .= "<br /><strong>Formats array:</strong><pre>". var_export($formats,true).'</pre>';
$debugText .= "<br /><strong>Fields array:</strong><pre>". var_export($fields,true).'</pre>';
$debugText .= "<br /><strong>Classes parsed :</strong><pre>" . var_export($rClass,true) ."</pre>";
}
$debugText .= "<br /><strong>eForm configuration:</strong><pre>\n". var_export($params,true).'</pre>';
$fields['debug']=$debugText;
}
// set validation message
$params['errorTpl'] = ($modx->getChunk($params['errorTpl'])) ? $modx->getChunk($params['errorTpl']) : $params['errorTpl'];
$params['errorRequiredTpl'] = ($modx->getChunk($params['errorRequiredTpl'])) ? $modx->getChunk($params['errorRequiredTpl']) : $params['errorRequiredTpl'];
$params['errorRequiredSeparator'] = ($modx->getChunk($params['errorRequiredSeparator'])) ? $modx->getChunk($params['errorRequiredSeparator']) : $params['errorRequiredSeparator'];
if (count($rMsg) > 0) {
$rMsg = str_replace('[+ef_required_list+]', implode($params['errorRequiredSeparator'], $rMsg), $params['errorRequiredTpl']);
array_unshift($vMsg, str_replace("[+fields+]", $rMsg, $_lang['ef_required_message']));
}
$validationMessage = str_replace('[+ef_message_text+]', $_lang['ef_validation_message'], $params['errorTpl']);
if (!strstr($tpl, '[+validationmessage+]')) {
$modx->setPlaceholder('validationmessage', str_replace('[+ef_wrapper+]', implode('<br/>', $vMsg), $validationMessage));
} else {
$fields['validationmessage'] .= str_replace('[+ef_wrapper+]', implode('<br/>', $vMsg), $validationMessage);
}
} else {
# format report fields
foreach($fields as $name => $value) {
$fld = $formats[$name];
if ($fld) {
$datatype = $fld[2];
switch ($datatype) {
case "integer":
$value = number_format( (float) $value); //EM~
break;
case "float":
$localeInfo = localeconv();
$th_sep = empty($_lang['ef_thousands_separator'])?$localeInfo['thousands_sep']:$_lang['ef_thousands_separator'];
$dec_point= $localeInfo['decimal_point'];
$debugText .= 'Locale<pre>'.var_export($localeInfo,true).'</pre>';
$value = number_format((float) $value, 2, $dec_point, $th_sep); //EM~
break;
case "date":
$format_string = isset($_lang['ef_date_format']) ? $_lang['ef_date_format'] : '%d-%b-%Y %H:%M:%S';
$value = ($value)? strftime($format_string,strtotime($value)):"";
$value=str_replace("00:00:00","",$value);// remove trailing zero time values
break;
case "html":
// convert \n to <br />
if(!$sendAsText ) $value = preg_replace('#(\n<br[ /]*?>|<br[ /]*?>\n|\n)#i','<br />',$value);
break;
case "file":
// set file name
if($value['type']!="" && $value['error']==0){
$value = $value["name"];
$patharray = explode(((strpos($value,"/")===false)? "\\":"/"), $value);
$value = $patharray[count($patharray)-1];
}
else {
$value = "";
}
break;
}
$fields[$name] = $value;
}
}
# set postdate
$fields['postdate'] = strftime("%d-%b-%Y %H:%M:%S",time());
//check against email injection and replace suspect content
if( hasMailHeaders($fields) ){
//send email to webmaster??
if ($reportAbuse){ //set in snippet configuration tab
$body = $_lang['ef_mail_abuse_message'];
$body .="<table>";
foreach($fields as $key => $value)
$body .= "<tr><td>$key</td><td><pre>$value</pre></td></tr>";
$body .="</table>";
$modx->loadExtension('MODxMailer');
# send abuse alert
$modx->mail->IsHTML($isHtml);
$modx->mail->From = $modx->config['emailsender'];
$modx->mail->FromName = $modx->config['site_name'];
$modx->mail->Subject = $_lang['ef_mail_abuse_subject'];
$modx->mail->Body = $body;
AddAddressToMailer($modx->mail,"to",$modx->config['emailsender']);
$modx->mail->send(); //ignore mail errors in this case
$modx->mail->ClearAllRecipients();
}
//return empty form with error message
//register css and/or javascript
if( isset($startupSource) ) efRegisterStartupBlock($startupSource);
return formMerge($tpl,array('validationmessage'=> $_lang['ef_mail_abuse_error']));
}
# added in 1.4.2 - Limit the time between form submissions
if($submitLimit>0){
if( time()<$submitLimit+$_SESSION[$formid.'_limit'] ){
return formMerge($_lang['ef_submit_time_limit'], array('submitLimitMinutes' => $submitLimit / 60));
}
else unset($_SESSION[$formid.'_limit'], $_SESSION[$formid.'_hash']); //time expired
}
# invoke OnBeforeMailSent event set by another script
// Changed in 1.4.4.8 - Multiple event functions separated by comma.
if ($eFormOnBeforeMailSent) {
$eFormOnBeforeMailSent = array_filter(array_map('trim', explode(',', $eFormOnBeforeMailSent)));
foreach ($eFormOnBeforeMailSent as $beforeMailSent) {
if ($isDebug && !function_exists($beforeMailSent)) {
$fields['debug'] .= 'eFormOnBeforeMailSent event: Could not find the function ' . $beforeMailSent;
} elseif ($beforeMailSent($fields) === false) {
if (isset($fields['validationmessage']) && !empty($fields['validationmessage'])) {
//register css and/or javascript
if (isset($startupSource)) {
efRegisterStartupBlock($startupSource);
}
return formMerge($tpl, $fields);
} else {
return;
}
}
}
}
if( $protectSubmit ){
$hash = '';
# create a hash of key data
if(!is_numeric($protectSubmit)){ //supplied field names
$protectSubmit = (strpos($protectSubmit,','))? explode(',',$protectSubmit):array($protectSubmit);
foreach($protectSubmit as $fld) $hash .= isset($fields[$fld]) ? $fields[$fld] : '';
}else //all required fields
foreach($formats as $fld) $hash .= ($fld[3]==1) ? $fields[$fld[0]] : '';
if($hash) $hash = md5($hash);
if( $isDebug ) $debugText .= "<strong>SESSION HASH</strong>:".$_SESSION[$formid.'_hash']."<br />"."<b>FORM HASH</b>:".$hash."<br />";
# check if already succesfully submitted with same data
if( isset($_SESSION[$formid.'_hash']) && $_SESSION[$formid.'_hash'] == $hash && $hash!='' )
return formMerge($_lang['ef_multiple_submit'],$fields);
}
$fields['disclaimer'] = ($disclaimer)? formMerge($disclaimer,$fields):"";
$subject = isset($fields['subject'])?$fields['subject']:(($subject)? formMerge($subject,$fields):$category);
$fields['subject'] = $subject; //make subject available in report & thank you page
$report = ($report)? formMerge($report,$fields):"";
$keywords = ($keywords)? formMerge($keywords,$fields):"";
$from = ($from)? formMerge($from,$fields):"";
$fromname = ($from)? formMerge($fromname,$fields):"";
# added in 1.4.5 - Use a field for attachments
if ($attachmentField != '' && isset($fields[$attachmentField]) && !empty($fields[$attachmentField])) {
$attachmentPath = realpath(MODX_BASE_PATH . $attachmentPath) . '/';
$filenames = explode(',', $fields[$attachmentField]);
foreach ($filenames as $filename) {
if (file_exists($attachmentPath . $filename)) {
$attachments[count($attachments)] = $attachmentPath . $filename;
}
}
}
$to = formMerge($to,$fields);
if(empty($to) || !strpos($to,'@')) $nomail=1;
if(!$nomail){
# check for mail selector field - select an email from to list
if ($mselector && $fields[$mselector]) {
$i = (int)$fields[$mselector];
$ar = explode(",",$to);
if ($i>0) $i--;
if ($ar[$i]) $to = $ar[$i];
else $to = $ar[0];
}
//set reply-to address
//$replyto snippet parameter must contain email or fieldname
if(!strstr($replyto,'@'))
$replyto = ( $fields[$replyto] && strstr($fields[$replyto],'@') )?$fields[$replyto]:$from;
# include PHP Mailer
$modx->loadExtension('MODxMailer');
# send form
//defaults to html so only test sendasText
$isHtml = ($sendAsText==1 || strstr($sendAsText,'report'))?false:true;
# added in 1.4.4.8 - Send sendirect, ccsender and autotext mails only to the first mail address of the comma separated list.
if ($fields['email']) {
$firstEmail = explode(',', $fields['email']);
$firstEmail = array_shift($firstEmail);
} else {
$firstEmail = '';
}
if(!$noemail) {
if($sendirect) $to = $firstEmail;
$modx->mail->IsHTML($isHtml);
$modx->mail->From = $from;
$modx->mail->FromName = $fromname;
$modx->mail->Subject = $subject;
$modx->mail->Body = (!$isHtml) ? $report : htmlspecialchars_decode($report, ENT_QUOTES);
AddAddressToMailer($modx->mail,"replyto",$replyto);
AddAddressToMailer($modx->mail,"to",$to);
AddAddressToMailer($modx->mail,"cc",$cc);
AddAddressToMailer($modx->mail,"bcc",$bcc);
AttachFilesToMailer($modx->mail,$attachments);
if(!$modx->mail->send()) return 'Main mail: ' . $_lang['ef_mail_error'] . $modx->mail->ErrorInfo;
$modx->mail->ClearAllRecipients();
$modx->mail->ClearAttachments();
}
# send user a copy of the report
if($ccsender && $firstEmail != '') {
$modx->mail->IsHTML($isHtml);
$modx->mail->From = $from;
$modx->mail->FromName = $fromname;
$modx->mail->Subject = $subject;
$modx->mail->Body = (!$isHtml) ? $report : htmlspecialchars_decode($report, ENT_QUOTES);
AddAddressToMailer($modx->mail,"to",$firstEmail);
AttachFilesToMailer($modx->mail,$attachments);
if(!$modx->mail->send()) return 'CCSender: ' . $_lang['ef_mail_error'] . $modx->mail->ErrorInfo;
$modx->mail->ClearAllRecipients();
$modx->mail->ClearAttachments();
}
# send auto-respond email
//defaults to html so only test sendasText
$isHtml = ($sendAsText==1 || strstr($sendAsText,'autotext'))?false:true;
if ($autotext && $firstEmail != '') {
$autotext = formMerge($autotext,$fields);
$modx->mail->IsHTML($isHtml);
$modx->mail->From = ($autosender)? $autosender:$from;
$modx->mail->FromName = ($autoSenderName)?$autoSenderName:$fromname;
$modx->mail->Subject = $subject;
$modx->mail->Body = (!$isHtml) ? $autotext : htmlspecialchars_decode($autotext, ENT_QUOTES);
AddAddressToMailer($modx->mail,"to",$firstEmail);
if(!$modx->mail->send()) return 'AutoText: ' . $_lang['ef_mail_error'] . $modx->mail->ErrorInfo;
$modx->mail->ClearAllRecipients();
}
//defaults to text - test for sendAsHtml
$isHTML = ($sendAsHTML==1 || strstr($sendAsHtml,'mobile'))?true:false;
# send mobile email
if ($mobile && $mobiletext) {
$mobiletext = formMerge($mobiletext,$fields);
$modx->mail->IsHTML($isHtml);
$modx->mail->From = $from;
$modx->mail->FromName = $fromname;
$modx->mail->Subject = $subject;
$modx->mail->Body = (!$isHtml) ? $mobiletext : htmlspecialchars_decode($mobiletext, ENT_QUOTES);
AddAddressToMailer($modx->mail,"to",$mobile);
$modx->mail->send();
$modx->mail->ClearAllRecipients();
}
}//end test nomail
# added in 1.4.2 - Protection against multiple submit with same form data
if($protectSubmit) $_SESSION[$formid.'_hash'] = $hash; //hash is set earlier
# added in 1.4.2 - Limit the time between form submissions
if($submitLimit>0) $_SESSION[$formid.'_limit'] = time();
# invoke OnMailSent event set by another script
// Changed in 1.4.4.8 - Multiple event functions separated by comma.
if ($eFormOnMailSent) {
$eFormOnMailSent = array_filter(array_map('trim', explode(',', $eFormOnMailSent)));
foreach ($eFormOnMailSent as $mailSent) {
if ($isDebug && !function_exists($mailSent)) {
$fields['debug'] .= 'eFormOnMailSent event: Could not find the function' . $mailSent;
} else {
if ($mailSent($fields) === false) {
return;
}
}
}
}
if($isDebug){
$debugText .="<strong>Mail Headers:</strong><br />From: $from ($fromname)<br />Reply-to:$replyto<br />To: $to<br />Subject: $subject<br />CC: $cc<br /> BCC:$bcc<br />";
if($isDebug>1){
$debugText .= "<br /><strong>Formats array:</strong><pre>". var_export($formats,true).'</pre>';
$debugText .= "<br /><strong>Fields array:</strong><pre>". var_export($fields,true).'</pre>';
}
$fields['debug'] = $debugText;
}
# show or redirect to thank you page
if ($gid==$modx->documentIdentifier){
if(!empty($thankyou) ){
if($isDebug && !strstr($thankyou,'[+debug+]')) $thankyou .= '[+debug+]';
if( isset($startupSource) ) efRegisterStartupBlock($startupSource,true); //skip scripts
if( $sendAsText ){
foreach($formats as $key => $fmt)
if($fmt[2]=='html') $fields[$key] = str_replace("\n",'<br />',$fields[$key]);
}
$thankyou = formMerge($thankyou,$fields);
return $thankyou;
}else{
return $_lang['ef_thankyou_message'];
}
}
else {
$url = $modx->makeURL($gid);
$modx->sendRedirect($url);
}
return; // stop here
}
}else{ //not postback
//add debugging info to fields array
if($isDebug){
$debugText .= "<br /><strong>eForm configuration:</strong><pre>". var_export($params,true).'</pre>';
$fields['debug']=$debugText;
}
//strip the eform attribute
$regExpr = "#eform=([\"'])[^\\1]*?\\1#si";
$tpl = preg_replace($regExpr,'',$tpl);
}
// set vericode
if($vericode) {
$_SESSION['eForm.VeriCode'] = $fields['vericode'] = substr(uniqid(''),-5);
$fields['verimageurl'] = MODX_MANAGER_URL.'includes/veriword.php?rand='.rand();
}
# get SESSION data - thanks to sottwell
if($sessionVars){
$sessionVars = (strpos($sessionVars,',',0))?array_filter(array_map('trim', explode(',', $sessionVars))):array($sessionVars);
foreach( $sessionVars as $varName ){
if( isset($_SESSION[$varName]) && !empty($_SESSION[$varName]) )
$fields[$varName] = ( isset($fields[$varName]) && $postOverides )?$fields[$varName]:$_SESSION[$varName];
}
}
# invoke OnBeforeFormMerge event set by another script
// Changed in 1.4.4.8 - Multiple event functions separated by comma.
if ($eFormOnBeforeFormMerge) {
$eFormOnBeforeFormMerge = array_filter(array_map('trim', explode(',', $eFormOnBeforeFormMerge)));
foreach ($eFormOnBeforeFormMerge as $beforeFormMerge) {
if ($isDebug && !function_exists($beforeFormMerge)) {
$fields['debug'] .= 'eFormOnBeforeFormMerge event: Could not find the function ' . $beforeFormMerge;
} else {
if ($beforeFormMerge($fields) === false) {
return;
}
}
}
}
# build form
if($isDebug && !$fields['debug']) $fields['debug'] = $debugText;
if($isDebug && !strstr($tpl,'[+debug+]')) $tpl .= '[+debug+]';
//register css and/or javascript
if( isset($startupSource) ) efRegisterStartupBlock($startupSource);
return formMerge($tpl,$fields);
}
# Form Merge
function formMerge($docText, $docFields) {
global $modx, $formats, $lastitems;
if(!$docText) return '';
preg_match_all('~\[\+(.*?)\+\]~', $docText, $matches);
for($i=0;$i<count($matches[1]);$i++) {
$name = $matches[1][$i];
list($listName,$listValue) = explode(":",$name);
$value = isset($docFields[$listName])? $docFields[$listName]:'';
// support for multi checkbox, radio and select - Djamoer
if(is_array($value)) $value=implode(', ', $value);
$fld = $formats[$name];
if (!isset($fld)){
// listbox, checkbox, radio select
$colonPost = strpos($name, ':');
$listName = substr($name, 0, $colonPost);
$listValue = substr($name, $colonPost+1);
$datatype = $formats[$listName][2];
if(is_array($docFields[$listName])) {
if($datatype=="listbox" && in_array($listValue, $docFields[$listName])) $docText = str_replace("[+$listName:$listValue+]","selected='selected'",$docText);
if(($datatype=="checkbox"||$datatype=="radio") && in_array($listValue, $docFields[$listName])) $docText = str_replace("[+$listName:$listValue+]","checked='checked'",$docText);
}
else {
if($datatype=="listbox" && $listValue==$docFields[$listName]) $docText = str_replace("[+$listName:$listValue+]","selected='selected'",$docText);
if(($datatype=="checkbox"||$datatype=="radio") && $listValue==$docFields[$listName]) $docText = str_replace("[+$listName:$listValue+]","checked='checked'",$docText);
}
}
// prevent XSS for formfields
if (isset($fld)) {
$value = htmlspecialchars($value, ENT_QUOTES, $modx->config['modx_charset']);
}
if(strpos($name,":")===false) $docText = str_replace("[+$name+]",$value,$docText);
else {
// this might be a listbox item.
// we'll remove this field later
$lastitems[count($lastitems)]="[+$name+]";
}
}
$docText = $modx->mergeDocumentContent($docText);
$docText = $modx->mergeSettingsContent($docText);
$docText = $modx->mergeChunkContent($docText);
if(strpos($docText,'[!')!==false) $docText = str_replace(array('[!','!]'),array('[[',']]'),$docText);
$docText = $modx->evalSnippets($docText);
$lastitems[count($lastitems)] = "class=\"\""; //removal off empty class attributes
$docText = str_replace($lastitems,"",$docText);
return $docText;
}
# Adds Addresses to Mailer
function AddAddressToMailer(&$mail,$type,$addr){
if(empty($addr)) return;
$a = array_filter(array_map('trim', explode(',', $addr)));
for($i=0;$i<count($a);$i++){
if ($type=="to") $mail->AddAddress($a[$i]);
elseif ($type=="cc") $mail->AddCC($a[$i]);
elseif ($type=="bcc") $mail->AddBCC($a[$i]);
elseif ($type=="replyto") $mail->AddReplyTo($a[$i]);
}
}
# Attach Files to Mailer
function AttachFilesToMailer(&$mail,&$attachFiles) {
if(count($attachFiles)>0){
foreach($attachFiles as $attachFile){
if(!file_exists($attachFile)) continue;
$FileName = $attachFile;
$contentType = "application/octetstream";
if (is_uploaded_file($attachFile)){
foreach($_FILES as $n => $v){
if($_FILES[$n]['tmp_name']==$attachFile) {
$FileName = $_FILES[$n]['name'];
$contentType = $_FILES[$n]['type'];
}
}
}
$patharray = explode(((strpos($FileName,"/")===false)? "\\":"/"), $FileName);
$FileName = $patharray[count($patharray)-1];
$mail->AddAttachment($attachFile,$FileName,"base64",$contentType);
}
}
}
/*--- Form Parser stuff----------------------*/
function eFormParseTemplate($tpl, $isDebug=false ){
global $modx,$formats,$optionsName,$_lang,$debugText,$fields,$validFormId;
global $efPostBack;
$formats = array(); //clear formats so values don't persist through multiple snippet calls
$labels = array();
$regExpr = "#(<label[^>]*?>)(.*?)</label>#si";;
preg_match_all($regExpr,$tpl,$matches);
foreach($matches[1] as $key => $fld){
$attr = attr2array($fld);
if(isset($attr['for'])){
$name = substr($attr['for'],1,-1);
//add class to fields array
$fields[$name."_vClass"] = isset($attr['class'])?substr($attr['class'],1,-1):'';
$labels[$name] = strip_tags($matches[2][$key]);
//create placeholder for class
$attr['class'] = '"[+'.$name.'_vClass+]"';
$newTag = buildTagPlaceholder('label',$attr,$name);
$tpl = str_replace($fld,$newTag,$tpl);
}
}
//retrieve all the form fields
$regExpr = "#(<(input|select|textarea)[^>]*?>)#si";
preg_match_all($regExpr,$tpl,$matches);
$fieldTypes = $matches[2];
$fieldTags = $matches[1];
for($i=0;$i<count($fieldTypes);$i++){
$type = $fieldTypes[$i];
//get array of html attributes
$tagAttributes = attr2array($fieldTags[$i]);
//attribute values are stored including quotes
//strip quotes as well as any brackets to get the raw name
$name = str_replace(array("'",'"','[',']'),'',$tagAttributes['name']);
//skip all fields without name attribute (these could even not be worked by eform)
if ($name) {
#skip vericode field - updated in 1.4.4
#special case. We need to set the class placeholder but forget about the rest
if ($name == "vericode") {
if (isset($tagAttributes['class'])) {
$tagAttributes['class'] = '"' . substr($tagAttributes['class'], 1, -1) . '[+' . $name . '_class+]"';
} else {
$tagAttributes['class'] = '"[+' . $name . '_class+]"';
}
$tagAttributes['value'] = '';
$newTag = buildTagPlaceholder('input', $tagAttributes, $name);
$tpl = str_replace($fieldTags[$i], $newTag, $tpl);
continue;
}
//store the field options
if (isset($tagAttributes[$optionsName])) {
//split to max of 5 so validation rule can contain ':'
$formats[$name] = explode(":", stripTagQuotes($tagAttributes[$optionsName]), 5);
array_unshift($formats[$name], $name);
} else {
if (!isset($formats[$name])) $formats[$name] = array($name, '', '', 0);
}
//added for 1.4 - use label if it is defined
if (empty($formats[$name][1])) {
$formats[$name][1] = (isset($labels[$name])) ? $labels[$name] : $name;
}
//added in 1.4.4.1
if (isset($id)) {
$formats[6] = $id;
}
unset($tagAttributes[$optionsName]);
//added in 1.4.2 - add placeholder to class attribute
if (isset($tagAttributes['class'])) {
$tagAttributes['class'] = '"' . substr($tagAttributes['class'], 1, -1) . '[+' . $name . '_class+]"';
} else {
$tagAttributes['class'] = '"[+' . $name . '_class+]"';
}
switch ($type) {
case "select":
//replace with 'cleaned' tag and added placeholder
$newTag = buildTagPlaceholder('select', $tagAttributes, $name);
$tpl = str_replace($fieldTags[$i], $newTag, $tpl);
if ($formats[$name]) {
$formats[$name][2] = 'listbox';
}
//Get the whole select block with option tags
//escape any regex characters!
$regExp = "#<select [^><]*?name=" . preg_quote($tagAttributes['name'], '#') . "[^>]*?" . ">(.*?)</select>#si";
preg_match($regExp, $tpl, $matches);
$optionTags = $matches[1];
$select = $newSelect = $matches[0];
//get separate option tags and split them up
preg_match_all("#(<option [^>]*?>)#si", $optionTags, $matches);
$validValues = array();
foreach ($matches[1] as $option) {
$attr = attr2array($option);
//* debug */ print __LINE__.': <pre>'.print_r($attr,true) .'</pre><br />';
$value = substr($attr['value'], 1, -1); //strip outer quotes
if (trim($value) != '') {
$validValues[] = $value;
}
$newTag = buildTagPlaceholder('option', $attr, $name);
$newSelect = str_replace($option, $newTag, $newSelect);
//if no postback, retain any checked values
if (!$efPostBack && !empty($attr['selected'])) {
$fields[$name][] = $value;
}
}
//replace complete select block
$tpl = str_replace($select, $newSelect, $tpl);
//add valid values to formats... (extension to $formats)
if ($formats[$name] && !$formats[$name][5]) {
$formats[$name][4] = $_lang['ef_failed_default'];
//convert commas in values to something else !
$formats[$name][5] = "#LIST " . implode(",", str_replace(',', ',', $validValues));
}
break;
case "textarea":
// add support for maxlength attribute for textarea
// attribute get's stripped form form //
if ($tagAttributes['maxlength']) {
$formats[$name][$_dfnMaxlength] == $tagAttributes['maxlength'];
unset($tagAttributes['maxlength']);
}
$newTag = buildTagPlaceholder($type, $tagAttributes, $name);
$regExp = "#<textarea [^>]*?name=" . $tagAttributes["name"] . "[^>]*?" . ">(.*?)</textarea>#si";
preg_match($regExp, $tpl, $matches);
//if nothing Posted retain the content between start/end tags
$placeholderValue = ($efPostBack) ? "[+$name+]" : $matches[1];
$tpl = str_replace($matches[0], $newTag . $placeholderValue . "</textarea>", $tpl);
break;
default:
//all the rest, ie. "input"
$newTag = buildTagPlaceholder($type, $tagAttributes, $name);
$fieldType = stripTagQuotes($tagAttributes['type']);
//validate on maxlength...
if ($fieldType == 'text' && $tagAttributes['maxlength']) {
$formats[$name][$_dfnMaxlength] == $tagAttributes['maxlength'];
}
if ($formats[$name] && !$formats[$name][2]) {
$formats[$name][2] = ($fieldType == 'text') ? "string" : $fieldType;
}
//populate automatic validation values for hidden, checkbox and radio fields
if ($fieldType == 'hidden') {
if (!$isDebug) $formats[$name][1] = "[undefined]"; //do not want to disclose hidden field names
if (!isset($formats[$name][4])) $formats[$name][4] = $_lang['ef_tamper_attempt'];
if (!isset($formats[$name][5])) $formats[$name][5] = "#VALUE " . stripTagQuotes($tagAttributes['value']);
} elseif ($fieldType == 'checkbox' || $fieldType == 'radio') {
$formats[$name][4] = $_lang['ef_failed_default'];
$formats[$name][5] .= isset($formats[$name][5]) ? "," : "#LIST ";
//convert embedded comma's in values!
$formats[$name][5] .= str_replace(',', ',', stripTagQuotes($tagAttributes['value']));
//store the id as well
//if no postback, retain any checked values
if (!$efPostBack && !empty($tagAttributes['checked'])) {
$fields[$name][] = stripTagQuotes($tagAttributes['value']);
}
$formats[$name][6] .= (isset($formats[$name][6]) ? "," : "") . stripTagQuotes($tagAttributes['id']);
} elseif (empty($fields[$name])) {
//plain old text input field
//retain default value set in form template if not already set in code
$fields[$name] = stripTagQuotes($tagAttributes['value']);
}
$tpl = str_replace($fieldTags[$i], $newTag, $tpl);
break;
}
}
}
if($isDebug>2) $debugText .= "<strong>Parsed template</strong><p style=\"border:1px solid black;padding:2px;\">" . str_replace("\n",'<br />',str_replace('+','+',htmlspecialchars($tpl)))."</p><hr>";
return $tpl;
}
function stripTagQuotes($value){
return substr($value,1,-1);
}
function buildTagPlaceholder($tag,$attributes,$name){
$type = stripTagQuotes($attributes["type"]);
$quotedValue = $attributes['value'];
$val = stripTagQuotes($quotedValue);
foreach ($attributes as $k => $v)
$t .= ($k!='value' && $k!='checked' && $k!='selected')?" $k=$v":"";
switch($tag){
case "select":
return "<$tag$t>"; //only the start tag mind you
case "option":
return "<$tag$t value=".$quotedValue." [+$name:$val+]>";
case "input":
switch($type){
case 'file':
case 'image':
return "<input$t/>";
case 'radio':
case 'checkbox':
return "<input$t value=".$quotedValue." [+$name:$val+] />";
case 'text':
if($name=='vericode') return "<input$t value=\"\" />";
//else pass on to next
case 'email':
case 'tel':
case 'url':
case 'number':
case 'range':
case 'date':
case 'month':
case 'week':
case 'time':
case 'datetime':
case 'datetime-local':
case 'color':
case 'password':
return "<input$t value=\"[+$name+]\" />";
default: //leave as is - no placeholder
return "<input$t value=".$quotedValue." />";
}
case "file": //no placeholder!
case "textarea": //placeholder needs to be added in calling code
return "<$tag$t>";
case "label":
return "<$tag$t>";
default:
return "<input$t value=\"[+$name+]\" />";
} // switch
return ""; //if we've arrived here we're in trouble