PHP8 fixes
[Pman.Core] / Mailer.php
1 <?php
2
3 /**
4  *
5  *  code that used to be in Pman (sendTemplate / emailTemplate)
6  * 
7  *  template is in template directory subfolder 'mail'
8  *   
9  *  eg. use 'welcome' as template -> this will use templates/mail/welcome.txt
10  *  if you also have templates/mail/welcome.body.html - then that will be used as 
11  *     the html body
12  * 
13  *
14  *  usage:
15  *
16  * 
17  *  require_once 'Pman/Core/Mailer.php';
18  *  $x= new  Pman_Core_Mailer(array(
19        'page' => $this,
20                 // if bcc is property of this, then it will be used (BAD DESIGN)
21        'rcpts' => array(),    
22        'template' => 'your_template',
23                 // must be in templates/mail direcotry..
24                 // header and plaintext verison in mail/your_template.txt
25                 // if you want a html body - use  mail/your_template.body.html
26        
27         // 'bcc' => 'xyz@abc.com,abc@xyz.com',  // string...
28         // 'contents'  => array(),              //  << keys must be trusted
29                                             // if bcc is property of contents, then it will be used (BAD DESIGN)
30            
31         // 'html_locale => 'en',                // always use the 'english translated verison'
32         // 'cache_images => true,               // -- defaults to caching images - set to false to disable.
33         // 'replaceImages => false,             // should images be replaced.
34         // 'urlmap => array(                    // map urls from template to a different location.
35         //      'https://www.mysite.com/' => 'http://localhost/',
36         // ),
37         // 'locale' => 'en',                    // .... or zh_hk....
38            
39         // 'attachments' => array(
40         //       array(
41         //        'file' => '/path/to/file',    // file location
42         //        name => 'myfile.pdf',         // (optional) - uses basename of file
43         //        mimetype : 
44         //      ), 
45         //  
46         // 'mail_method' =>  'SMTP',            // or SMTPMX
47   
48     )
49  *
50  *  recipents is gathered from the resulting template
51  *   -- eg.
52  *    To: <a>,<b>,<c>
53  * 
54  * 
55  *  if the file     '
56  * 
57  * 
58  *  $x->toData(); // returns data needed for notify?? - notify should really
59  *                  // just use this to pass around later..
60  *
61  *  $x->send();
62  *
63  */
64
65 class Pman_Core_Mailer {
66     var $debug          = 0;
67     var $page           = false; /* usually a html_flexyframework_page */
68     var $contents       = false; /* object or array */
69     var $template       = false; /* string */
70     var $replaceImages  = false; /* boolean */
71     var $rcpts   = false;
72     var $templateDir = false;
73     var $locale = false; // eg. 'en' or 'zh_HK'
74     var $urlmap = array();
75     
76     var $htmlbody;
77     var $textbody;
78     
79     var $html_locale = false; // eg. 'en' or 'zh_HK'
80     var $images         = array(); // generated list of cid images for sending
81     var $attachments = false;
82     var $css_inline = false; // put the css into the html
83     var $css_embed = false; // put the css tags into the body.
84     
85     var $mail_method = 'SMTP';
86     
87     var $cache_images = true;
88       
89     var $bcc = false;
90     
91     var $body_cls = false;
92     
93     function __construct($args) {
94         foreach($args as $k=>$v) {
95             // a bit trusting..
96             $this->$k =  $v;
97         }
98         // allow core mailer debug setting.
99         $ff = HTML_FlexyFramework::get();
100         
101         if (!empty($ff->Core_Mailer['debug'])) {
102             $this->debug = $ff->Core_Mailer['debug'];
103         }
104         //$this->log("URL MAP");
105         //$this->log($this->urlmap);
106         
107     }
108      
109     /**
110      * ---------------- Global Tools ---------------   
111      */
112     
113     function toData()
114     {
115         $templateFile = $this->template;
116         $args = (array)$this->contents;
117         $content  = clone($this->page);
118         
119         foreach($args as $k=>$v) {
120             $content->$k = $v;
121         }
122         
123         $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
124         
125         $ff = HTML_FlexyFramework::get();
126         $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
127         if (isset($ff->Pman['HTTP_HOST']) && $http_host != 'localhost') {
128             $http_host  = $ff->Pman['HTTP_HOST'];
129         }
130         
131         $content->HTTP_HOST = $http_host;
132         
133         // this should be done by having multiple template sources...!!!
134         
135         require_once 'HTML/Template/Flexy.php';
136         
137         $tmp_opts = array(
138            // 'forceCompile' => true,
139             'site_prefix' => false,
140             'multiSource' => true,
141         );
142         
143         $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
144         
145         //print_R($fopts);exit;
146         if (!empty($fopts['DB_DataObject_translator'])) {
147             $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
148         }
149         if (!empty($fopts['locale'])) {
150             $tmp_opts['locale'] = $fopts['locale'];
151         }
152         if (!empty($fopts['templateDir'])) {
153             $tmp_opts['templateDir'] = $fopts['templateDir'];
154         }
155         // override.
156         if (!empty($this->templateDir)) {
157             $tmp_opts['templateDir'] = $this->templateDir;
158         }
159         
160         // local opt's overwrite
161         if (!empty($this->locale)) {
162             $tmp_opts['locale'] = $this->locale;
163         }
164         
165         $htmlbody = false;
166         $html_tmp_opts = $tmp_opts;
167         $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
168         if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) { 
169             // then we have a multi-part email...
170             if (!empty($this->html_locale)) {
171                 $html_tmp_opts['locale'] = $this->html_locale;
172             }
173             $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
174             
175             $htmltemplate->compile('mail/'. $templateFile.'.body.html');
176             $htmlbody =  $htmltemplate->bufferedOutputObject($content);
177             
178             $this->htmlbody = $htmlbody;
179             
180             // for the html body, we may want to convert the attachments to images.
181 //            var_dump($htmlbody);exit;
182             
183             if(!empty($content->body_cls) && strlen($content->body_cls)){
184                 $htmlbody = $this->htmlbodySetClass($htmlbody, $content->body_cls);
185             }
186             
187             if ($this->replaceImages) {
188                 $htmlbody = $this->htmlbodytoCID($htmlbody);    
189             }
190             
191             if ($this->css_embed) {
192                 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
193             }
194             
195             if ($this->css_inline && strlen($this->css_inline)) {
196                 $htmlbody = $this->htmlbodyInlineCss($htmlbody);
197             }
198             
199         }
200         $tmp_opts['nonHTML'] = true;
201         //$tmp_opts['debug'] = true;
202         
203         // print_R($tmp_opts);
204         // $tmp_opts['force'] = true;
205         
206         $template = new HTML_Template_Flexy(  $tmp_opts );
207         
208         $template->compile('mail/'. $templateFile.'.txt');
209         
210         /* use variables from this object to ouput data. */
211         $mailtext = $template->bufferedOutputObject($content);
212         //print_r($mailtext);exit;
213        
214         
215         
216         //echo "<PRE>";print_R($mailtext);
217         
218         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
219         require_once 'Mail/mimeDecode.php';
220         require_once 'Mail.php';
221         
222         $decoder = new Mail_mimeDecode($mailtext);
223         $parts = $decoder->getSendArray();
224         if (PEAR::isError($parts)) {
225             return $parts;
226             //echo "PROBLEM: {$parts->message}";
227             //exit;
228         } 
229         
230         $isMime = false;
231         
232         require_once 'Mail/mime.php';
233         $mime = new Mail_mime(array(
234             'eol' => "\n",
235             //'html_encoding' => 'base64',
236             'html_charset' => 'utf-8',
237             'text_charset' => 'utf-8',
238             'head_charset' => 'utf-8',
239         ));
240         // clean up the headers...
241         
242         
243         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
244                                      '@' . $content->HTTP_HOST .'>';
245         
246           
247         if ($htmlbody !== false) {
248             // got a html headers...
249             
250             if (isset($parts[1]['Content-Type'])) {
251                 unset($parts[1]['Content-Type']);
252             }
253             $mime->setTXTBody($parts[2]);
254             $this->textbody = $parts[2];
255             $mime->setHTMLBody($htmlbody);
256             
257 //            var_dump($mime);exit;
258             foreach($this->images as $cid=>$cdata) { 
259             
260                 $mime->addHTMLImage(
261                     $cdata['file'],
262                      $cdata['mimetype'],
263                      $cid.'.'.$cdata['ext'],
264                     true,
265                     $cdata['contentid']
266                 );
267             }
268             $isMime = true;
269         }
270         
271         if(!empty($this->attachments)){
272             //if got a attachments
273             $header = $mime->headers($parts[1]);
274             
275             if (isset($parts[1]['Content-Type'])) {
276                 unset($parts[1]['Content-Type']);
277             }
278             
279             if (!$isMime) {
280             
281                 if(preg_match('/text\/html/', $header['Content-Type'])){
282                     $mime->setHTMLBody($parts[2]);
283                     $mime->setTXTBody('This message is in HTML only');
284                     $this->textbody = 'This message is in HTML only';
285                 }else{
286                     $mime->setTXTBody($parts[2]);
287                     $this->textbody = $parts[2];
288                     $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
289                 }
290             }
291             foreach($this->attachments as $attch){
292                 $mime->addAttachment(
293                         $attch['file'],
294                         $attch['mimetype'],
295                         (!empty($attch['name'])) ? $attch['name'] : '',
296                         true
297                 );
298             }
299             
300             $isMime = true;
301         }
302         
303         if($isMime){
304             $parts[2] = $mime->get();
305             $parts[1] = $mime->headers($parts[1]);
306         }
307          
308         
309         $ret = array(
310             'recipents' => $parts[0],
311             'headers' => $parts[1],
312             'body' => $parts[2],
313             'mailer' => $this
314         );
315         if ($this->rcpts !== false) {
316             $ret['recipents'] =  $this->rcpts;
317         }
318         // if 'to' is empty, then add the recipents in there... (must be an array?
319         if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
320                 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
321             $ret['headers']['To'] = implode(',', $ret['recipents']);
322         }
323        
324         
325         // add bcc if necessary..
326         if (!empty($this->bcc)) {
327            $ret['bcc'] = $this->bcc;
328         }
329         return $ret;
330     }
331     function send($email = false)
332     {
333                         
334         $ff = HTML_FlexyFramework::get();
335         
336         $pg = $ff->page;
337         
338         $email = is_array($email)  ? $email : $this->toData();
339         
340         if (is_a($email, 'PEAR_Error')) {
341             $pg->addEvent("COREMAILER-FAIL",  false, "email toData failed"); 
342       
343             
344             return $email;
345         }
346         
347         //$this->log( htmlspecialchars(print_r($email,true)));
348         
349         ///$recipents = array($this->email);
350 //        $mailOptions = PEAR::getStaticProperty('Mail','options');
351         
352         $mailOptions = isset($ff->Mail) ? $ff->Mail : array();
353         //print_R($mailOptions);exit;
354         
355         if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
356             $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
357             
358         }
359         
360         $mail = Mail::factory($this->mail_method,$mailOptions);
361         if ($this->debug) {
362             $mail->debug = (bool) $this->debug;
363         }
364         
365         $email['headers']['Date'] = date('r'); 
366         if (PEAR::isError($mail)) {
367             $pg->addEvent("COREMAILER-FAIL",  false, "mail factory failed"); 
368       
369             
370             return $mail;
371         } 
372         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
373         
374         
375         
376         // this makes contents untrustable...
377         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
378             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
379         }
380         
381         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
382         if ($this->debug) {
383             print_r(array(
384                 'rcpts' => $rcpts,
385                 'email' => $email
386             ));
387         }
388         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
389         error_reporting($oe);
390         if ($ret === true) { 
391             $pg->addEvent("COREMAILER-SENT",  false,
392                 'To: ' .  ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
393                 'Subject: '  . @$email['headers']['Subject']
394             ); 
395         }  else {
396             $pg->addEvent("COREMAILER-FAIL",  false,
397                 "Sending to : " . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
398                 " Error: " . $ret->toString());
399
400         }
401         
402         return $ret;
403     }
404     
405     function htmlbodytoCID($html)
406     {
407         $dom = new DOMDocument();
408         // this may raise parse errors as some html may be a component..
409         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
410         $imgs= $dom->getElementsByTagName('img');
411         
412         $urls = array();
413         
414         foreach ($imgs as $i=>$img) {
415             $url  = $img->getAttribute('src');
416             if (preg_match('#^cid:#', $url)) {
417                 continue;
418             }
419             $me = $img->getAttribute('mailembed');
420             if ($me == 'no') {
421                 continue;
422             }
423             
424             if(!array_key_exists($url, $urls)){
425                 $conv = $this->fetchImage($url);
426                 $urls[$url] = $conv;
427                 $this->images[$conv['contentid']] = $conv;
428             } else {
429                 $conv = $urls[$url];
430             }
431             $img->setAttribute('origsrc', $url);
432             $img->setAttribute('src', 'cid:' . $conv['contentid']);
433         }
434         
435         
436         return $dom->saveHTML();
437         
438     }
439     function htmlbodyCssEmbed($html)
440     {
441         $ff = HTML_FlexyFramework::get();
442         $dom = new DOMDocument();
443         
444         // this may raise parse errors as some html may be a component..
445         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
446         $links = $dom->getElementsByTagName('link');
447         $lc = array();
448         foreach ($links as $link) {  // duplicate as links is dynamic and we change it..!
449             $lc[] = $link;
450         }
451         //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
452         
453         foreach ($lc as $i=>$link) {
454             //var_dump($link->getAttribute('href'));
455             
456             if ($link->getAttribute('rel') != 'stylesheet') {
457                 continue;
458             }
459             $url  = $link->getAttribute('href');
460             $file = $ff->rootDir . $url;
461             
462             if (!preg_match('#^(http|https)://#', $url)) {
463                 $file = $ff->rootDir . $url;
464
465                 if (!file_exists($file)) {
466 //                    echo $file;
467                     $link->setAttribute('href', 'missing:' . $file);
468                     continue;
469                 }
470             } else {
471                $file = $this->mapurl($url);  
472             }
473             
474             $par = $link->parentNode;
475             $par->removeChild($link);
476             $s = $dom->createElement('style');
477             $e = $dom->createTextNode(file_get_contents($file));
478             $s->appendChild($e);
479             $par->appendChild($s);
480             
481         }
482         return $dom->saveHTML();
483         
484         
485     }
486     
487     function htmlbodyInlineCss($html)
488     {   
489         $dom = new DOMDocument();
490         
491         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
492         
493         $html = $dom->getElementsByTagName('html');
494         $head = $dom->getElementsByTagName('head');
495         $body = $dom->getElementsByTagName('body');
496         
497         if(!$head->length){
498             $head = $dom->createElement('head');
499             $html->item(0)->insertBefore($head, $body->item(0));
500             $head = $dom->getElementsByTagName('head');
501         }
502         
503         $s = $dom->createElement('style');
504         $e = $dom->createTextNode($this->css_inline);
505         $s->appendChild($e);
506         $head->item(0)->appendChild($s);
507         
508         return $dom->saveHTML();
509         
510         /* Inline
511         require_once 'HTML/CSS/InlineStyle.php';
512         
513         $doc = new HTML_CSS_InlineStyle($html);
514         
515         $doc->applyStylesheet($this->css_inline);
516         
517         $html = $doc->getHTML();
518         
519         return $html;
520         */
521     }
522     
523     function htmlbodySetClass($html, $cls)
524     {
525         $dom = new DOMDocument();
526         
527         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
528         
529         $body = $dom->getElementsByTagName('body');
530         if (!empty($body->length)) {
531             $body->item(0)->setAttribute('class', $cls);
532         } else {
533             $body = $dom->createElement("body");
534             $body->setAttribute('class', $cls);
535             $dom->appendChild($body);
536         }
537         
538         
539         return $dom->saveHTML();
540     }
541     
542     function fetchImage($url)
543     {
544         
545         
546         $this->log( "FETCH : $url\n");
547         
548         if ($url[0] == '/') {
549             $ff = HTML_FlexyFramework::get();
550             $file = $ff->rootDir . $url;
551             require_once 'File/MimeType.php';
552             $m  = new File_MimeType();
553             $mt = $m->fromFilename($file);
554             $ext = $m->toExt($mt); 
555             
556             return array(
557                     'mimetype' => $mt,
558                    'ext' => $ext,
559                    'contentid' => md5($file),  // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
560                    'file' => $file
561             );
562             
563             
564             
565         }
566         
567         //print_R($url); exit;
568         
569         
570         if (preg_match('#^file:///#', $url)) {
571             $file = preg_replace('#^file://#', '', $url);
572             require_once 'File/MimeType.php';
573             $m  = new File_MimeType();
574             $mt = $m->fromFilename($file);
575             $ext = $m->toExt($mt); 
576             
577             return array(
578                 'mimetype'  => $mt,
579                 'ext'       =>   $ext,
580                 'contentid' => md5($file),
581                 'file'      => $file
582             );
583             
584         }
585         
586         // CACHE???
587         // 2 files --- the info file.. and the actual file...
588         // add user
589         // unix only...
590         $uinfo = posix_getpwuid( posix_getuid () ); 
591         $user = $uinfo['name']; 
592         
593         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
594         if ($this->cache_images &&
595                 file_exists($cache) &&
596                 filemtime($cache) > strtotime('NOW - 1 WEEK')
597             ) {
598             $ret =  json_decode(file_get_contents($cache), true);
599             $this->log("fetched from cache");
600             $ret['file'] = $cache . '.data';
601             return $ret;
602         }
603         if (!file_exists(dirname($cache))) {
604             mkdir(dirname($cache),0700, true);
605         }
606         
607         require_once 'HTTP/Request.php';
608         
609         $real_url = str_replace(' ', '%20', $this->mapurl($url));
610         $a = new HTTP_Request($real_url);
611         $a->sendRequest();
612         $data = $a->getResponseBody();
613         
614         $this->log("got file of size " . strlen($data));
615         $this->log("save contentid " . md5($url));
616         
617         file_put_contents($cache .'.data', $data);
618         
619         
620         $mt = $a->getResponseHeader('Content-Type');
621         
622         require_once 'File/MimeType.php';
623         $m  = new File_MimeType();
624         $ext = $m->toExt($mt);
625         
626         $ret = array(
627             'mimetype' => $mt,
628             'ext' => $ext,
629             'contentid' => md5($url)
630             
631         );
632         
633         file_put_contents($cache, json_encode($ret));
634         $ret['file'] = $cache . '.data';
635         return $ret;
636     }  
637     
638     function mapurl($in)
639     {
640          foreach($this->urlmap as $o=>$n) {
641             if (strpos($in,$o) === 0) {
642                 $ret =$n . substr($in,strlen($o));
643                 $this->log("mapURL in $in = $ret");
644                 return $ret;
645             }
646         }
647         $this->log("mapurl no change - $in");
648         return $in;
649          
650         
651     }
652  
653     
654     
655     function log($val)
656     {
657         if (!$this->debug) {
658             return;
659         }
660         if ($this->debug < 2) {
661             echo '<PRE>' . print_r($val,true). "\n"; 
662             return;
663         }
664         $fh = fopen('/tmp/core_mailer.log', 'a');
665         fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");
666         fclose($fh);
667         
668         
669     }
670     
671 }