PluginProbe
Smart Forms – when you need more than just a contact form / trunk
Smart Forms – when you need more than just a contact form vtrunk
trunk 0.5 0.5.5 0.6 0.7 0.8 0.8.5 0.9.1
smart-forms / php_classes / save / php_entry_saver_base.php

php_entry_saver_base.php in Smart Forms – when you need more than just a contact form trunk, at php_classes/save/php_entry_saver_base.php

695 lines 21.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 include_once(SMART_FORMS_DIR.'string_renderer/rednao_string_builder.php');
3 include_once(SMART_FORMS_DIR.'smart-forms-ajax.php');
4
5
6 class php_entry_saver_base {
7 private $FormId=null;
8 public $FormEntryData=null;
9 public $FormOptions=null;
10 public $ElementOptions=null;
11 private $Captcha=null;
12 private $ReferenceId=null;
13 private $EntryId="";
14 private $FormString="";
15 private $StringBuilder;
16 private $InsertedValuesString=null;
17
18
19 function __construct($formId,$formString,$captcha,$referenceId="",$formOptions=null,$elementOptions=null)
20 {
21 $this->FormId = $formId;
22 $this->FormString=$formString;
23 $this->FormEntryData = json_decode($this->FormString,true);
24 $this->Captcha=$captcha;
25 $this->ReferenceId=$referenceId;
26 $this->FormOptions=$formOptions;
27 $this->ElementOptions=$elementOptions;
28 if($this->ElementOptions!=null)
29 $this->StringBuilder=new rednao_string_builder();
30 }
31
32 public function ProcessEntry($validateCaptcha=true,$additionalData=array())
33 {
34 if($this->FormOptions==null||$this->ElementOptions==null){
35 $this->GetFormOptions();
36 $this->StringBuilder=new rednao_string_builder();
37 }
38
39
40 if($this->FormEntryData==null)
41 {
42 echo '{"message":"'.__("An error occurred, please try again later.").'","refreshCaptcha":"n","success":"n"}';
43 return;
44 }
45
46 if($this->FormOptions["UsesCaptcha"]=="y"&&$validateCaptcha==true)
47 {
48 if($this->FormOptions["CaptchaVersion"]=="1")
49 if(!$this->CaptchaIsValid())
50 {
51 echo '{"message":"'.__("Invalid captcha.").'","refreshCaptcha":"y","success":"n"}';
52 return;
53 }
54
55 $errorMessage="";
56 if($this->FormOptions["CaptchaVersion"]=="2")
57 if(!$this->CaptchaIsValid2($errorMessage))
58 {
59 echo json_encode(array(
60 'message'=>$errorMessage,
61 'refreshCaptcha'=>'y',
62 'success'=>'n'
63 ));
64
65 return;
66 }
67 }
68
69
70 if(isset($_FILES)&&count($_FILES)>0)
71 {
72 $errorMessage='';
73 if(!$this->SaveFiles($errorMessage))
74 {
75 echo json_encode(array(
76 'message'=> __("An error occurred, please try again later."),
77 'success'=>'n',
78 'cause'=>$errorMessage
79 ));
80 return;
81 }
82 }
83
84 require_once SMART_FORMS_DIR.'php_classes/save/insert_entry_base.php';
85 require_once SMART_FORMS_DIR.'php_classes/save/pre_insert_entry.php';
86 $preInsertedEntry=new PreInsertEntry($this->FormId,$this->FormEntryData,$this->FormOptions,$this->ElementOptions,$additionalData);
87 do_action('sf_before_saving_form',$preInsertedEntry);
88
89
90
91 if(has_action('sf_before_saving_form'))
92 {
93 $this->FormEntryData = $preInsertedEntry->FormEntryData;
94 $this->FormString = json_encode($this->FormEntryData);
95 }
96
97 if($preInsertedEntry->ContinueInsertion==false)
98 {
99 echo json_encode(
100 array(
101 "success"=>"n",
102 "AdditionalActions"=>$preInsertedEntry->GetSerializedActions()
103 )
104 );
105
106 return false;
107 }
108
109 $this->InsertedValuesString=array();
110 $result=$this->ExecuteInsertions();
111 if($this->FormOptions["SendNotificationEmail"]=="y")
112 {
113 foreach($this->FormOptions["Emails"] as $email)
114 $this->SendFormEmail($email,$this->FormEntryData,$this->ElementOptions,$preInsertedEntry, false);
115 }
116
117
118 if($result==true)
119 {
120 $postInsertEntry=new PreInsertEntry($this->FormId,$this->FormEntryData,$this->FormOptions,$this->ElementOptions,$additionalData);
121 do_action('sf_after_saving_form',$postInsertEntry);
122
123
124 echo json_encode(
125 array(
126 "message"=>__("Information submitted successfully."),
127 "success"=>"y",
128 "AdditionalActions"=>$postInsertEntry->GetSerializedActions(),
129 "insertedValues"=>array('_formid'=>$this->InsertedValuesString['_formid'])
130 )
131 );
132 return true;
133 }
134 else
135 {
136 echo '{"message":"'.__("An error occurred, please try again later.").'","success":"n"}';
137 return false;
138 }
139
140
141 }
142
143 private function ExecuteInsertions()
144 {
145 return $this->InsertEntryData();
146 }
147
148 public function GetFormElementsDictionary()
149 {
150 $formElementsDictionary =array();
151 foreach($this->ElementOptions as $element)
152 $formElementsDictionary[$element["Id"]]=$element;
153
154 return $formElementsDictionary;
155 }
156
157 private function InsertEntryData(){
158 if(isset($this->FormOptions['DisableDBStorage'])&&$this->FormOptions['DisableDBStorage']=='y')
159 {
160 $this->FormEntryData["_formid"]='';
161 $this->InsertedValuesString["_formid"]='';
162 return true;
163 }
164 $currentuser=wp_get_current_user();
165 $this->FormEntryData['user_id']=$currentuser->ID;
166
167 $ip=$_SERVER['REMOTE_ADDR'];
168 if(isset($this->FormOptions['DisableIPStorage'])&&$this->FormOptions['DisableIPStorage']=='y')
169 {
170 $ip='';
171 }
172
173 $formStringToSave=$this->FormString;
174 if(get_option('SmartFormsEnableGDPR','n')=='y')
175 {
176 $formStringToSave=$this->RemoveDataProtectedFields(json_decode($this->FormString,true),$this->GetFormElementsDictionary());
177 $formStringToSave=json_encode($formStringToSave);
178 }
179
180
181 global $wpdb;
182
183 $sequentialId=get_option($this->FormId.'_'.'sequential',0);
184 $sequentialId++;
185 $data=array(
186 'form_id'=>$this->FormId,
187 'user_id'=>$currentuser->ID,
188 'date'=>date('c'),
189 'data'=>$formStringToSave,
190 'ip'=>$ip,
191 'reference_id'=>$this->ReferenceId,
192 'sequential_id'=>$sequentialId
193 );
194 $this->FormEntryData['_sequentialId']=$sequentialId;
195
196 $data=apply_filters('smart_forms_before_inserting',$data);
197
198 $result= $wpdb->insert(SMART_FORMS_ENTRY,$data);
199
200 update_option($this->FormId.'_'.'sequential',$sequentialId);
201
202
203 if($result==false)
204 return false;
205 $this->EntryId=$wpdb->insert_id;
206 $this->FormEntryData["_formid"]=$this->EntryId;
207 $this->InsertedValuesString["_formid"]=$this->EntryId;
208
209 $formEntryDataToSave=$this->FormEntryData;
210 $formEntryDataToSave=$this->RemoveDataProtectedFields($formEntryDataToSave,$this->GetFormElementsDictionary());
211 $result=$this->ParseAndInsertDetail($this->EntryId,$formEntryDataToSave,$this->GetFormElementsDictionary());
212 return $result;
213
214
215 }
216
217 public function SendFormEmail($formOptions,$entryData,$elementOptions,$preInsertEntry,$useTestData)
218 {
219 if(isset($formOptions['Condition']))
220 {
221 $condition=$formOptions['Condition'];
222 if(isset($condition['Use'])&&$condition['Use']=='condition')
223 {
224 require_once SMART_FORMS_DIR.'php_classes/condition_parser/condition_parser.php';
225 $conditionParser=new SFConditionParser($preInsertEntry);
226 $conditionSettings=$condition['ConditionSettings'];
227 if(!$conditionParser->IsTrue($conditionSettings['Conditions']))
228 return true;
229 }
230
231 }
232 $EmailText=$formOptions["EmailText"];
233 $FromName=$formOptions["FromName"];
234 $FromEmail=$formOptions["FromEmail"];
235 $ToEmail=$formOptions["ToEmail"];
236 $EmailSubject=$formOptions["EmailSubject"];
237 $Bcc='';
238
239 if(isset($formOptions["Bcc"]))
240 $Bcc=$formOptions["Bcc"];
241
242 if(isset($formOptions['ReplyTo']))
243 $ReplyTo=$formOptions['ReplyTo'];
244 else
245 $ReplyTo=$FromEmail;
246
247
248 if($FromName=="")
249 $FromName="Wordpress";
250
251 if($EmailSubject=="")
252 $EmailSubject="Form Submitted";
253
254 if($ToEmail=="")
255 $ToEmail=get_option("admin_email");
256
257
258 $fieldPattern='/\\[field ([^\\]]+)/';
259 preg_match_all($fieldPattern,$EmailText, $matches, PREG_PATTERN_ORDER);
260
261 require_once(SMART_FORMS_DIR.'php_classes/save/smarty_custom_code/smarty_email_generator.php');
262 $smarty=new smarty_email_generator();
263 try{
264 $EmailText=$smarty->AttemptToProcessEmailString($elementOptions,$EmailText,$matches,$entryData,$useTestData);
265 }catch (Exception $e)
266 {
267 foreach($matches[1] as $match)
268 {
269 $value=GetValueByField($this->StringBuilder,$match,$entryData,$elementOptions,$useTestData);
270 $EmailText=str_replace("[field $match]",$value,$EmailText);
271 }
272 }
273
274
275
276
277 if(strpos($FromName,"[field")!==false)
278 {
279 preg_match_all($fieldPattern,$FromName, $matches, PREG_PATTERN_ORDER);
280 foreach($matches[1] as $match)
281 {
282 $value=GetValueByField($this->StringBuilder,$match,$entryData,$elementOptions,$useTestData);
283 $FromName=str_replace("[field $match]",$value,$FromName);
284 }
285 }
286
287 if(strpos($EmailSubject,"[field")!==false)
288 {
289 preg_match_all($fieldPattern,$EmailSubject, $matches, PREG_PATTERN_ORDER);
290 foreach($matches[1] as $match)
291 {
292 $value=GetValueByField($this->StringBuilder,$match,$entryData,$elementOptions,$useTestData);
293 $EmailSubject=str_replace("[field $match]",$value,$EmailSubject);
294 }
295 }
296
297
298 if(strpos($FromEmail,"[field")===0)
299 {
300 preg_match_all($fieldPattern,$FromEmail, $matches, PREG_PATTERN_ORDER);
301 if(count($matches[1])>0)
302 {
303 $field=$matches[1][0];
304 $value=GetValueByField($this->StringBuilder,$field,$entryData,$elementOptions,$useTestData);
305 $FromEmail=$value;
306 }else{
307 $FromEmail="";
308 error_log('the to email field was not found');
309 }
310
311 }
312
313 if(strpos($ReplyTo,"[field")===0)
314 {
315 preg_match_all($fieldPattern,$ReplyTo, $matches, PREG_PATTERN_ORDER);
316 if(count($matches[1])>0)
317 {
318 $field=$matches[1][0];
319 $value=GetValueByField($this->StringBuilder,$field,$entryData,$elementOptions,$useTestData);
320 $ReplyTo=$value;
321 }else{
322 $ReplyTo="";
323 error_log('the to email field was not found');
324 }
325
326 }
327
328 if(strpos($Bcc,"[field")===0)
329 {
330 preg_match_all($fieldPattern,$Bcc, $matches, PREG_PATTERN_ORDER);
331 if(count($matches[1])>0)
332 {
333 $field=$matches[1][0];
334 $value=GetValueByField($this->StringBuilder,$field,$entryData,$elementOptions,$useTestData);
335 $Bcc=$value;
336 }else{
337 $Bcc="";
338 error_log('the to email field was not found');
339 }
340
341 }
342
343 if($FromEmail=='')
344 {
345 $FromEmail = apply_filters('wp_mail_from',get_option('admin_email'));
346 }
347
348
349 $headers = 'MIME-Version: 1.0' . "\r\n";
350 $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
351 $headers.= "From: ".$this->SanitizeName($FromName)." <$FromEmail>". "\r\n";
352 if($Bcc!='')
353 $headers.= "Bcc: $Bcc\r\n";
354 if($ReplyTo!='')
355 $headers.= "Reply-To: $FromName <$ReplyTo>";
356 if(trim($ToEmail)!="")
357 {
358
359 $toEmailArray=explode(",",$ToEmail);
360 $finalToEmails=array();
361 for($i=0;$i<count($toEmailArray);$i++)
362 {
363 if($toEmailArray[$i]=='[loggeduseremail]'&&isset($entryData['user_id']))
364 {
365 $userId=intval($entryData['user_id']);
366 if($userId==0)
367 continue;
368
369 $user=get_user_by('ID',$userId);
370 if($user==false)
371 continue;
372
373 $finalToEmails[]=$user->get('user_email');
374 }else
375 if(strpos($toEmailArray[$i],"[field")===0)
376 {
377 preg_match_all($fieldPattern,$toEmailArray[$i], $matches, PREG_PATTERN_ORDER);
378 if(count($matches[1])>0)
379 {
380 $field=$matches[1][0];
381
382 //$value=GetValueByField($this->StringBuilder,$field,$entryData,$elementOptions,$useTestData);
383 $value=$this->GetEmailsFromField($formOptions, $field,$preInsertEntry);
384 $toEmailArray=array_merge($toEmailArray,$value);
385 }
386
387
388 }else
389 {
390 if(trim($toEmailArray[$i])!="")
391 array_push($finalToEmails,$toEmailArray[$i]);
392 }
393
394 }
395 $toEmailArray=array_filter($toEmailArray);
396
397 $emailParams=array(
398 "EmailContent"=>array(
399 "ToEmail"=>$finalToEmails,
400 "Subject"=>$EmailSubject,
401 "EmailText"=>"<html><body>".$EmailText."</body></html>",
402 "Headers"=>$headers,
403 "Attachments"=>Array()
404 ),
405 "FormOptions"=>$formOptions,
406 "InsertEntry"=>$preInsertEntry
407 );
408
409
410 $emailParams=apply_filters('smart_forms_before_sending_email',$emailParams);
411 $emailContent=$emailParams["EmailContent"];
412 apply_filters('smart_forms_before_sending_email',$emailContent);
413 $result= wp_mail($emailContent["ToEmail"],$emailContent["Subject"],$emailContent["EmailText"],$emailContent["Headers"],$emailContent["Attachments"]);
414 do_action('smart_forms_after_sending_email',$emailContent);
415 return $result;
416 }
417
418 return false;
419 }
420
421 private function SanitizeName($name)
422 {
423 $rule = array("\r" => '',
424 "\n" => '',
425 "\t" => '',
426 '"' => "'",
427 '<' => '[',
428 '>' => ']',
429 );
430
431 return trim(strtr($name, $rule));
432 }
433
434 private function GetEmailsFromField($emailOptions,$fieldId,$preInsertEntry)
435 {
436 $fieldData=$preInsertEntry->GetField($fieldId);
437 if($fieldData["ClassName"]=="rednaomultipleradios"||$fieldData["ClassName"]=="rednaomultiplecheckboxes"
438 ||$fieldData["ClassName"]=="rednaoselectbasic"||$fieldData["ClassName"]=="rednaosearchablelist")
439 {
440 $selectedValues= $preInsertEntry->GetFieldValue($fieldId, SFSerializationType::ARRAYLIST);
441 if(!isset($emailOptions["MultipleOptionsToEmails"][$fieldId]))
442 return array();
443 $emailsToReturn=array();
444 $optionsToEmail=$emailOptions["MultipleOptionsToEmails"][$fieldId];
445 foreach($selectedValues as $selectedValue)
446 foreach($optionsToEmail as $optionToEmail)
447 {
448 if ($selectedValue["label"] == $optionToEmail["Label"])
449 {
450 $emails = $optionToEmail["EmailTo"];
451 if (trim($emails) == "")
452 continue;
453 $emailsToReturn = array_merge($emailsToReturn, explode(",", $emails));
454 }
455 }
456
457 return $emailsToReturn;
458
459
460 }
461 else
462 {
463 $text=$preInsertEntry->GetFieldValue($fieldId, SFSerializationType::TEXT);
464 if(trim($text)=="")
465 return array();
466 else
467 return array($text);
468
469 }
470
471
472 }
473
474
475 private function CaptchaIsValid()
476 {
477 $Message="";
478 if($this->Captcha==""||$this->Captcha==null||$this->Captcha["response"]=="")
479 return false;
480
481 $captchaPost=$this->Captcha;
482 $captcha=ARRAY();
483 $captcha["challenge"]=stripslashes($captchaPost["challenge"]);
484 $captcha["response"]=stripslashes($captchaPost["response"]);
485 $captcha["remoteip"]=$_SERVER['REMOTE_ADDR'];
486 $captcha["privatekey"]="6Lf2J-wSAAAAAOH6uSmSdx75ZLRpDIfvSeAdx9ST";
487
488 $args=Array();
489
490 $args['headers']=Array
491 (
492 'Content-Type'=>'application/x-www-form-urlencoded;',
493 'Method'=>'Post'
494 );
495 $args['body']=$captcha;
496 $res=wp_remote_post('http://www.google.com/recaptcha/api/verify',$args);
497 if(strpos($res["body"],"true")!==0)
498 return false;
499
500 return true;
501 }
502
503 private function CaptchaIsValid2(&$errorMessage)
504 {
505 $errorMessage="Invalid captcha";
506 $Message="";
507 if($this->Captcha==""||$this->Captcha==null||$this->Captcha["response"]=="")
508 return false;
509
510 $captchaPost=$this->Captcha;
511 $captcha=ARRAY();
512 $captcha["response"]=stripslashes($captchaPost["response"]);
513 $captcha["remoteip"]=$_SERVER['REMOTE_ADDR'];
514 $captcha["secret"]=$this->FormOptions['FieldServerOptions']['captcha2']['SecretKey'];
515 $args=Array();
516 $args['headers']=Array
517 (
518 'Content-Type'=>'application/x-www-form-urlencoded;',
519 'Method'=>'Post'
520 );
521 $args['body']=$captcha;
522 $res=wp_remote_post('https://www.google.com/recaptcha/api/siteverify',$args);
523 $response=json_decode($res["body"],true);
524 if($response["success"]===true)
525 return true;
526 if($response["error-codes"][0]=="invalid-input-secret")
527 $errorMessage="Invalid secret key";
528
529 return false;
530 }
531
532 private function GetFormOptions()
533 {
534 global $wpdb;
535 $result=$wpdb->get_results($wpdb->prepare("select form_options,element_options from ".SMART_FORMS_TABLE_NAME." where form_id=%d",$this->FormId));
536
537 if(count($result)>0){
538 $this->FormOptions=json_decode($result[0]->form_options,true);
539 $this->ElementOptions=json_decode($result[0]->element_options,true);
540 }
541 }
542
543 private function SaveFiles(&$errorMessage)
544 {
545 require_once(SMART_FORMS_DIR . "php_classes/file_upload/physical_file_uploader.php");
546 $fileUploader=new physical_file_uploader();
547 $result= $fileUploader->UploadFiles($this->FormEntryData);
548 if($result["success"]==true)
549 {
550 $this->FormEntryData=$result["entryData"];
551 $this->FormString=json_encode($result["entryData"]);
552 return true;
553 }
554 else
555 $errorMessage=$result['cause'];
556 return false;
557 }
558
559 private function DeleteInsertedEntry()
560 {
561 global $wpdb;
562 $wpdb->query($wpdb->prepare("delete from ".SMART_FORMS_ENTRY." WHERE entry_id=%d",$this->EntryId));
563 }
564
565 public function ParseAndInsertDetail($entryId,$entryData,$formElementsDictionary)
566 {
567 if($this->StringBuilder==null)
568 $this->StringBuilder=new rednao_string_builder();
569 foreach($entryData as $key=>$unprocessedValue)
570 {
571 if(!isset($formElementsDictionary[$key]))
572 continue;
573
574 $fieldConfiguration=$formElementsDictionary[$key];
575 $value=$this->StringBuilder->GetStringFromColumn($fieldConfiguration,$unprocessedValue,$entryId);
576 if($fieldConfiguration["ClassName"]!="sfFileUpload")
577 $this->InsertedValuesString[$key]=$value;
578 $exValue=$this->StringBuilder->GetExValue($fieldConfiguration,$unprocessedValue);
579 $dateValue=$this->StringBuilder->GetDateValue($fieldConfiguration,$unprocessedValue);
580 if($dateValue!=null)
581 $dateValue=date('Y-m-d',$dateValue);
582 $jsonValue=json_encode($unprocessedValue);
583 if(!$this->InsertDetailRecord($entryId,$key,$value,$jsonValue,$exValue,$dateValue))
584 return true;
585 }
586
587 return true;
588 }
589
590 private function InsertDetailRecord($entry_id, $fieldId, $value, $jsonValue,$exValue,$dateValue)
591 {
592 global $wpdb;
593 $arrayToInsert=array_merge(array(
594 "entry_id"=>$entry_id,
595 "field_id"=>$fieldId,
596 "json_value"=>$jsonValue,
597 "value"=>$value
598 ),$exValue);
599
600 if($dateValue!=null)
601 $arrayToInsert["datevalue"]=$dateValue;
602 return $wpdb->insert(SMART_FORMS_ENTRY_DETAIL,$arrayToInsert);
603 }
604
605 private function RemoveDataProtectedFields($FormData, $formDictionary)
606 {
607 foreach($FormData as $key=>&$value)
608 {
609 if(!isset($formDictionary[$key]))
610 continue;
611
612 $field=$formDictionary[$key];
613 if(isset($field['DoNotSave'])&&$field['DoNotSave']=='y')
614 {
615 unset($FormData[$key]);
616 continue;
617 }
618
619 if($field['ClassName']=='rednaorepeater'&&isset($value['value']))
620 {
621 foreach($field['FieldOptions'] as $subFieldOptions)
622 {
623 if(isset($subFieldOptions['DoNotSave'])&&$subFieldOptions['DoNotSave']=='y')
624 {
625 foreach($value['value'] as &$subValueRow)
626 {
627 foreach($subValueRow as $subValueFieldId=>$subValueFieldValue)
628 {
629 if(preg_match('/^'.$subFieldOptions['Id'].'_/',$subValueFieldId))
630 {
631 unset($subValueRow[$subValueFieldId]);
632 }
633 }
634
635 }
636 }
637
638 }
639
640 }
641 }
642
643 return $FormData;
644
645 }
646
647
648 }
649
650 function SmartFormsOverwriteHandleUpload($upload)
651 {
652
653 }
654
655 function GetPHPFormula($formula)
656 {
657 $fieldPattern='/\\[field ([^\\]]+)/';
658 preg_match_all($fieldPattern,$formula, $matches, PREG_PATTERN_ORDER);
659
660 foreach($matches[1] as $match)
661 {
662 $formula=str_replace("[field $match]","formData[$match]['amount']",$formula);
663 }
664
665 return $formula;
666 }
667
668 function SmartFormsGetFormattedFormValues($formValues,$elementOptions)
669 {
670 include_once(SMART_FORMS_DIR.'string_renderer/rednao_string_builder.php');
671 include_once(SMART_FORMS_DIR.'smart-forms-ajax.php');
672 $stringBuilder=new rednao_string_builder();
673 $processedData=array();
674 foreach($formValues as $key=>$value)
675 {
676 $element=null;
677 foreach($elementOptions as $item)
678 {
679 if($item["Id"]==$key)
680 {
681 $element=$item;
682 break;
683 }
684 }
685
686 if($element!=null)
687 {
688 $processedData[]=array("name"=>$element["Label"],
689 "value"=>$stringBuilder->GetStringFromColumn($element,$value));
690 }
691 }
692
693 return $processedData;
694
695 }