-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform.lib.php
executable file
·829 lines (670 loc) · 26.7 KB
/
form.lib.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
<?php
/**
Copyright 2015 JQueryForm.com
License: http://jqueryform.com/license.php
FormID: jqueryform-c96556
Date: 2015-11-02 19:47:59
Generated by http://www.jqueryform.com
IF your form uses mailgun AND the form has file upload field, PHP 5.5+ is required.
*/
namespace JF;
require_once( __DIR__ . '/form.config.php' );
use JF\Config;
// --------------------------------------------------------------
class Form {
public static function setDataDir( $dir ){
self::$dataDir = $dir ;
}
public static function getFormDataFile(){
return self::$dataDir . '/form-data.php' ;
}
public static function getEmailLogFile(){
return self::$dataDir . '/email-log.php' ;
}
public static function validate( $post = array() ){
if( empty($post) ){
$post = $_POST;
};
self::$post = $post;
self::$values = array();
self::$attachments = array();
self::$invalid = array();
self::$columns = array( self::csvfield('RecordID'), self::csvfield('Date'), self::csvfield('IP') );
self::$csvValues = array( self::csvfield(self::getRecordID()), self::csvfield(date("Y-m-d H:i:s")), self::csvfield($_SERVER['REMOTE_ADDR']) );
self::$serverValidationFields = empty(self::$post['serverValidationFields']) ? array(): explode(',', self::$post['serverValidationFields']);
self::$style = 'font-family:Verdana, Arial, Helvetica, sans-serif; font-size : 13px; color:#474747;padding:6px;border:1px solid #cccccc;' ;
self::$rows = array();
$config = self::getConfig();
$ok = self::validateReCaptcha( $post, $config['recaptcha']['secretKey'] );
if( !$ok ){
self::$invalid[] = 'recaptcha';
};
foreach( $config['fields'] as $f ){
switch ($f['field_type']) {
// creditcard field contains extra fields, have to validate them one by one
case 'creditcard':
self::_validateCreditcardFields( $f );
break;
default:
self::_validateField( $f );
};
}; // foreach
self::$values['dataTable'] = empty(self::$rows) ? '' : '<table cellspacing="0" cellpadding="0" border="1" bordercolor="#cccccc" style="border:1px solid #cccccc;"><tbody>' .
join( "\n", self::$rows ).
'</table>';
// save form data to file
if( self::isValid() ){
self::saveRecord();
};
// add preset tags
self::presetTags();
self::$isValidated = true; // validation checked
}
private static function _validateCreditcardFields($field){
foreach ($field['subfields'] as $name => $f ) {
// remove spaces that are created by javascript jquery.payment plugin
self::$post[$name] = str_replace(' ', '', self::$post[$name]);
self::_validateField( $f );
};
}
private static function _validateField($f){
$key = $f['cid'];
$value = "";
switch ($f['field_type']) {
case 'file':
$value = self::handleUploadFile($f);
break;
default:
if( !array_key_exists( $key, self::$post ) ){
self::$values[ $key ] = '';
continue;
};
$value = self::$post[$key];
// checkboxes or select-multiple
if( is_array($value) ){
$tmp = array();
foreach( $value as $v ){
$tmp[] = self::un_quotes($v);
};
$value = join(" | \n", $tmp);
// other input/textarea ...
}else{
$value = self::un_quotes( $value );
};
break;
}; // switch
self::$values[ $key ] = $value;
if( !empty($f['field_options']['sender']) ){
if( 'email' == $f['field_type'] && true == $f['field_options']['sender'] ){
$f['field_options']['sender'] = 'email';
};
self::$values[ 'sender.' . $f['field_options']['sender'] ] = self::$values[ $key ];
};
if( self::isRequired($f) && empty($value) ){
if( empty(self::$serverValidationFields) || (!empty(self::$serverValidationFields) && in_array($key, self::$serverValidationFields)) ){
self::$invalid[] = $key;
};
};
self::$columns[] = self::csvfield( $f['label'] );
self::$csvValues[] = self::csvfield( $value );
self::$rows[] = "<tr> <td valign=top style='" . self::$style."font-weight:bold;width:25%;'>" . $f['label'] . " </td> <td valign=top style='" . self::$style.";'>" . nl2br($value) . " </td></tr>" ;
} // _validateField
private static function validateReCaptcha( $post, $secretKey ){
if( !empty($secretKey) && isset($post['g-recaptcha-response']) ){
$get = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secretKey. '&response=' . $post['g-recaptcha-response'];
$response = file_get_contents( $get );
//echo $get . "\n" . $response;
$success = false;
if( function_exists('json_decode') ){
$json = json_decode( $response, true );
//var_dump($json);
$success = $json['success'] === true;
}else{
$success = preg_match( '/success[\"\']*\\:\\s*(true|1|y)/i', $response );
};
return $success;
};
return true; // recaptcha is not enabled
}
private static function presetTags(){
self::setValue( 'AutoID', self::getRecordID() );
self::setValue( 'HTTP_HOST', $_SERVER['HTTP_HOST'] );
self::setValue( 'IP', $_SERVER['REMOTE_ADDR'] );
self::setValue( 'Date', date("Y-m-d") );
self::setValue( 'Time', date("H:i:s") );
self::setValue( 'HTTP_REFERER', $_SERVER['HTTP_REFERER'] );
//self::setValue( 'FormURL', '' );
//self::setValue( 'AdminURL', '' );
// sender.email
// sender.firstname
// sender.lastname
// sender.fullname
}
private static function un_quotes($str){
return str_replace( array('"', '''), array('"', "'"), $str );
}
private static function handleUploadFile($field){
if( !isset($_FILES[ $field['cid'] ]) ){
return '';
};
$dir = self::getDataDir();
$file = $_FILES[ $field['cid'] ];
$fileName = $file['name'];
if( is_uploaded_file($file['tmp_name']) ){
$safeName = self::renameHarmfulFile($file['name']);
$safeName = preg_replace( "/[^0-9a-zA-Z\.]+/", "-", $safeName );
$filePath = $dir . '/' . self::getRecordID() . '-' . $safeName ;
$ok = @move_uploaded_file( $file['tmp_name'], $filePath );
$link = false;
if( $ok ) {
$link = self::checkFile2Link( $field, $filePath );
if( !empty($link) ){
self::setValue( $field['cid'] . '.name', $fileName );
$fileName = "<a href='{$link}' target='_blank'>{$fileName}</a>";
};
};
// if the file is not a link, then send it as attachment
if( empty($link) ){
self::$attachments[] = array('path' => $ok ? $filePath : $file['tmp_name'], 'name' => $fileName );
};
};
return $fileName;
}
private static function checkFile2Link($field, $filepath){
$kb = $field['field_options']['file']['fileToLinkSize'];
if( empty($kb) ){
return false ;
};
$filesize = filesize($filepath);
if( $filesize >= $kb ){
$link = self::getFileLink( $filepath );
self::setValue( $field['cid'] . '.link', $link );
return $link;
};
return false;
}
private static function getFileLink($filepath){
$realpath = self::dir2unix( realpath($filepath) );
$link = self::getAdminUrl() . '?method=downloadAttachment&id=' . urlencode(basename($filepath));
return $link;
}
public static function dir2unix( $dir ){
return str_replace( array("\\", '//'), '/', $dir );
}
// parse full admin url to view large size uploaded file online
public static function getAdminUrl(){
$url = 'admin.php';
$http = 'http' . ( empty($_SERVER['HTTPS']) ? '' : 's' ) . '://' ;
$http_host = $http . "{$_SERVER['HTTP_HOST']}";
switch( true ){
case (0 === strpos($url, $http )) :
$url = $url;
break;
case ( '/' == substr($url,0,1) ) :
$url = $http_host . $url ;
break;
default:
$uri = self::requestUri();
$pos = strrpos( $uri, '/' );
$vdir = substr( $uri, 0, $pos );
$url = $http_host . $vdir . '/' . $url ;
};
return $url;
}
public static function requestUri(){
$uri = getEnv('REQUEST_URI'); // apache has this
if( false !== $uri && strlen($uri) > 0 ){
return $uri ;
} else {
$uri = ($uri = getEnv('SCRIPT_NAME')) !== false
? $uri
: getEnv('PATH_INFO') ;
$qs = getEnv('QUERY_STRING'); // IIS and Apache has this
return $uri . ( empty($qs) ? '' : '?' . $qs );
};
return "" ;
}
public static function getAttachments(){
return self::$attachments;
}
public static function isValid(){
return empty(self::$invalid);
}
public static function isValidated(){
return self::$isValidated;
}
public static function getInvalidFields(){
return self::$invalid;
}
public static function getValue( $cid ){
return array_key_exists( $cid, self::$values ) ? self::$values[$cid] : '';
}
public static function getAdminUsers(){
$config = self::getConfig();
$default = array();
$admin = empty($config['admin']['users']) ? $default : $config['admin'];
$users = array();
$parts = explode(',', $admin['users']);
foreach( $parts as $part ){
$pos = strpos( $part, ':' );
if( false === $pos ){
continue;
};
$user = trim(substr($part,0,$pos));
$pass = trim(substr($part,$pos+1));
$users[$user] = array('user' => $user, 'password' => $pass);
};
return $users;
}
// avoid email header injection by removing line breaks for email headers
private static function removeLineBreaks( $str ){
return trim(preg_replace('/[\r\n]+/', '', $str));
}
// Email for mail header
public static function getFromEmail( $forAutoResponse = false ){
$email = self::getSenderEmail();
if( $forAutoResponse || empty($email) ){
$email = self::$config['email']['to'];
};
$sendmail_from = self::$config['email']['sendmail_from'];
if( !empty($sendmail_from) ){
ini_set("sendmail_from", $sendmail_from);
$email = $sendmail_from;
};
return self::removeLineBreaks( $email );
}
// Name for mail header
public static function getFromName( $forAutoResponse = false ){
if( $forAutoResponse ){
$fromName = self::$config['email']['fromName'];
return $fromName;
};
$fullname = self::getValue('sender.fullname');
$fromName = '' != $fullname ? $fullname : trim(self::getValue('sender.firstname') . ' ' . self::getValue('sender.lastname')) ;
return self::removeLineBreaks( $fromName );
}
public static function getSenderEmail(){
$email = self::getValue('sender.email');
return self::removeLineBreaks( $email );
}
public static function getToEmail(){
self::getConfig();
return self::removeLineBreaks( self::$config['email']['to'] );
}
public static function getReplyToEmail(){
self::getConfig();
return self::removeLineBreaks( self::$config['autoResponse']['replyTo'] );
}
public static function getReplyToName(){
self::getConfig();
return self::removeLineBreaks( self::$config['autoResponse']['replyToName'] );
}
public static function getId(){
return 'test-form-id';
}
public static function getDataDelivery(){
$config = self::getConfig();
return self::$config['admin']['dataDelivery'];
}
public static function getValues(){
return self::$values;
}
public static function getMailSubject(){
return self::removeLineBreaks( self::renderContent( self::$config['email']['subject'] ) );
}
public static function getMailBody(){
return self::getHtmlHeader() .
self::renderContent( self::mailTemplate() ) .
self::getHtmlFooter();
}
public static function getAutoResponseMailSubject(){
return self::removeLineBreaks( self::renderContent( self::$config['autoResponse']['subject'] ) );
}
public static function getAutoResponseMailBody(){
$body = self::autoResponseTemplate();
return empty($body) ? "" :
self::getHtmlHeader() .
self::renderContent( $body ) .
self::getHtmlFooter();
}
public static function setValue( $key, $value ){
self::$values[$key] = $value ;
}
private static function replaceTags( $content, $tags, $start='{', $end='}' ){
$attrs = array();
foreach ($tags as $tag => $value) {
$attrs[$start.$tag.$end] = $value;
};
$names = array_keys($attrs);
$values = array_values($attrs);
return str_replace( $names, $values, $content );
}
private static function renderContent( $content ){
return self::replaceTags( $content, self::$values );
}
private static function getHtmlHeader(){
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<?php
$output = ob_get_contents();
ob_end_clean();
return $output;
}
private static function getHtmlFooter(){
ob_start();
?>
</body>
</html>
<?php
$output = ob_get_contents();
ob_end_clean();
return $output;
}
private static function mailTemplate(){
$default = "{dataTable}";
$config = self::getConfig();
$template = nl2br( trim(self::$config['email']['template']) );
return empty($template) ? $default : $template;
}
private static function autoResponseTemplate(){
$config = self::getConfig();
$template = nl2br( trim(self::$config['autoResponse']['template']) );
return $template;
}
private static function getDataDir(){
$dir = dirname( self::getFormDataFile() );
if( !is_dir($dir) ){
@mkdir( $dir );
};
return $dir;
}
private static function saveRecord(){
$method = self::getDataDelivery();
if( 'emailOnly' == $method ){
return;
};
// if there are any real data rather then only 3 columns: ID, Date, and IP
if( count(self::$csvValues) <= 3 ){
return;
};
$sep = chr(0x09);
$recordCols = self::data2record( join($sep, self::$columns) ) . PHP_EOL;
$record = self::data2record( join($sep, self::$csvValues) ) . PHP_EOL;
self::getDataDir();
$dataFile = self::getFormDataFile();
if( !file_exists($dataFile) ){
self::secureFile( $dataFile );
file_put_contents($dataFile, $recordCols, FILE_APPEND );
};
file_put_contents($dataFile, $record, FILE_APPEND );
}
public static function secureFile( $file ){
if( !file_exists($file) ){
file_put_contents($file, "<?php exit(); /* For security reason. To avoid public user downloading below data! */?>" . PHP_EOL);
};
}
private static function getRecordID(){
if( !isset($GLOBALS['RecordID']) ){
$GLOBALS['RecordID'] = date("Ymd") . '-'. substr( md5(uniqid(rand(), true)), 0,4 );
};
return $GLOBALS['RecordID'];
}
private static function data2record( $s, $b=true ){
$from = array( "\r", "\n");
$to = array( "\\r", "\\n" );
return $b ? str_replace( $from, $to, $s ) : str_replace( $to, $from, $s ) ;
}
private static function csvfield( $str ){
$str = str_replace( '"', '""', $str );
return '"' . trim($str) . '"';
}
private static function isRequired($field){
return true === $field['field_options']['validators']['required']['enabled'];
}
private static function renameHarmfulFile( $name ){
$ext = strrchr(strtolower($name), '.');
if( $ext !== false ){
$n = strpos( strtolower(self::$harmfulExts), $ext );
if( $n !== false ){
return $name . '.bak' ;
};
};
return $name;
}
private static $config;
private static $post;
private static $values;
private static $invalid;
private static $isValidated = false;
private static $attachments;
private static $dataDir = './data/'; // folder that stores form data file, email traffic log, and upload files
private static $columns;
private static $csvValues;
private static $serverValidationFields;
private static $style;
private static $rows;
private static $harmfulExts = ".php, .html, .css, .js, .exe, .com, .bat, .vb, .vbs, scr, .inf, .reg, .lnk, .pif, .ade, .adp, .app, .bas, .chm, .cmd, .cpl, .crt, .csh, .fxp, .hlp, .hta, .ins, .isp, .jse, .ksh, .Lnk, .mda, .mdb, .mde, .mdt, .mdw, .mdz, .msc, .msi, .msp, .mst, .ops, .pcd, .prf, .prg, .pst, .scf, .scr, .sct, .shb, .shs, .url, .vbe, .wsc, .wsf, .wsh";
public static function getConfig( $decode = true ){
self::$config = Config::getConfig($decode);
self::overwriteConfig( $decode );
return self::$config;
}
private static function overwriteConfig( $decode = true ){
if( !$decode ){
return;
};
$file = __DIR__.'/myconfig.php';
if( !file_exists($file) ){
return;
};
$config = include($file);
if( !is_array($config) ){
return;
};
foreach( $config as $sectionName => $var ){
if( is_array($var) ){
foreach( $var as $key => $val ){
if( !empty($val) ){
self::$config[$sectionName][$key] = $config[$sectionName][$key];
};
};//
}else{
if( !empty($var) ){
self::$config[$sectionName] = $config[$sectionName];
};
}; // if
}; // foreac
} // overwriteConfig
}// end of Form class
// --------------------------------------------------------------
// --------------------------------------------------------------
class Mailer {
private $config;
private $mailer = 'local';
private $logs = array();
public $From;
public $FromName;
public $TO;
public $Subject;
public $Body;
public $CC;
public $BCC;
public $ReplyTo;
public $ReplyToName;
private $isSent = false;
private $sendError = '';
private $sentMIMEMessage = '';
function __construct(){
$this->config = Form::getConfig();
}
public function Send(){
$this->mailer = empty($this->config['mailer']) ? 'local' : $this->config['mailer'];
switch ( $this->mailer ) {
case 'local':
case 'smtp':
$this->SendByPHPMailer();
break;
case 'mailgun':
if ( function_exists('curl_init') ){
$this->SendByMailGun();
} else {
$this->addLog( "CURL module is not avaiable. Can't use mailgun mailer, use normal sendmail mailer.");
$this->SendByPHPMailer();
};
break;
default:
break;
}; // switch
$this->saveLogs();
}
public function mail( $to , $subject , $message, $from = '', $fromName = '' ){
$this->TO = $to;
$this->From = $from;
$this->FromName = $fromName;
$this->Subject = $subject;
$this->Body = $message;
return $this->Send();
}
public function validateForm( $post = array() ){
if( !Form::isValidated() ){
Form::validate($post);
};
$this->From = Form::getFromEmail();
$this->FromName = Form::getFromName();
$this->Subject = Form::getMailSubject();
$this->Body = Form::getMailBody();
$email = $this->config['email'];
$this->TO = Form::getToEmail();
$this->CC = empty($email['cc']) ? '' : $email['cc'];
$this->BCC = empty($email['bcc']) ? '' : $email['bcc'];
}
private function SendByPHPMailer(){
$email = $this->config['email'];
$mailer = new \PHPMailer();
if( !empty($this->ReplyTo) ){
$mailer->AddReplyTo($this->ReplyTo, $this->ReplyToName);
};
$mailer->From = $this->From;
$mailer->FromName = $this->FromName;
$mailer->Subject = $this->Subject;
$mailer->Body = $this->Body;
$mailer->CharSet = 'UTF-8';
$mailer->msgHTML($mailer->Body);
$mailer->IsHtml(true);
$mailer->AddAddress($this->TO);
if( !empty($this->CC) ){
$CCs = explode(',',$this->CC );
foreach($CCs as $c){
$mailer->AddCC( $c );
};
};
if( !empty($this->BCC) ){
$BCCs = explode(',',!empty($this->BCC));
foreach($BCCs as $b){
$mailer->AddBCC( $b );
};
};
$attachments = Form::getAttachments();
//$this->addLog($attachments);
if( is_array($attachments) ){
foreach($attachments as $f){
$mailer->AddAttachment( $f['path'], basename($f['name']) );
};
};
$smtp = $this->config['smtp'];
$isSMTP = $this->mailer == 'smtp' && !empty($smtp);
if( $isSMTP ){
$mailer->IsSMTP();
$mailer->Host = $smtp['host'];
$mailer->Username = $smtp['user'];
$mailer->Password = $smtp['password'];
$mailer->SMTPAuth = !empty($mailer->Password);
$mailer->SMTPSecure = $smtp['security'];
$mailer->Port = empty($smtp['port']) ? 25 : $smtp['port'];
$mailer->SMTPDebug = empty($smtp['debug']) ? 0 : 5;
};
if( $isSMTP && $mailer->SMTPDebug > 0 ){
ob_start();
};
$this->isSent = $mailer->Send();
if( $isSMTP && $mailer->SMTPDebug > 0 ){
$debug = ob_get_contents();
ob_end_clean();
$this->addLog($debug);
};
if( !$sent ){
$this->sendError = $mailer->ErrorInfo;
};
$this->sentMIMEMessage = $mailer->getSentMIMEMessage();
return $this->isSent;
}
private function SendByMailGun(){
$mg = $this->config['mailgun'];
$api_key= $mg['apiKey']; /* Api Key got from https://mailgun.com/cp/my_account */
$domain = $mg['domain']; /* Domain Name you given to Mailgun*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "api:".$api_key);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_URL, "https://api.mailgun.net/v3/".$domain."/messages");
$fields = array(
"from" => $mg['fromName'] . " <" . $mg['fromEmail'] . ">",
"to" => $this->TO,
"subject" => $this->Subject,
"h:Reply-To" => $this->FromName . " <" . $this->From . ">",
"html" => $this->Body
);
// php 5.5+
if( class_exists("\\CURLFile") ){
$attachments = Form::getAttachments();
if( is_array($attachments) ){
$n = count($attachments);
for( $i = 0; $i < $n; $i ++ ) {
$f = $attachments[$i];
$key = "attachment" . ( $i == 0 ? '' : "[{$i}]" );
$fields[$key] = new \CURLFile($f['path'], null, basename($f['name']) );
};
};
};
if( !empty($this->CC) ){
$fields['cc'] = $this->CC;
};
if( !empty($this->BCC) ){
$fields['bcc'] = $this->BCC;
};
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
$this->isSent = $result ? true : false;
$this->sentMIMEMessage = "CURL paramenters:\n" . var_export($fields,true) . "\n" . var_export($result,true);
if( !$this->isSent ){
$this->sendError = curl_error($ch);
}
curl_close($ch);
return $this->isSent;
}
private function saveLogs(){
$line = str_repeat('--------', 8);
$this->addLog( "\n\n" . $line );
$this->addLog( date("Y-m-d H:i:s") );
$this->addLog( "Email Sent: " . ( $this->isSent ? 'OK' : 'Failed (' . $this->sendError . ')' ) );
$this->addLog($this->sentMIMEMessage);
$this->addLog( $line . "\n\n" );
$logFile = Form::getEmailLogFile();
Form::secureFile( $logFile );
file_put_contents($logFile, join("\n", $this->logs), FILE_APPEND);
$this->logs = array(); // clear
}
private function addLog($msg){
$this->logs[] = is_string($msg) ? $msg : var_export($msg,true);
}
} // end of class Mailer
// --------------------------------------------------------------