c405598a89504e2ff91c521415539e84547b106e
[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         var_dump($content);
211         /* use variables from this object to ouput data. */
212         $mailtext = $template->bufferedOutputObject($content);
213         //print_r($mailtext);exit;
214        
215         
216         
217         //echo "<PRE>";print_R($mailtext);
218         
219         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
220         require_once 'Mail/mimeDecode.php';
221         require_once 'Mail.php';
222         var_dump($mailtext);
223         $decoder = new Mail_mimeDecode($mailtext);
224         $parts = $decoder->getSendArray();
225         if (PEAR::isError($parts)) {
226             return $parts;
227             //echo "PROBLEM: {$parts->message}";
228             //exit;
229         } 
230
231         var_dump($parts);
232         
233         $isMime = false;
234         
235         require_once 'Mail/mime.php';
236         $mime = new Mail_mime(array(
237             'eol' => "\n",
238             //'html_encoding' => 'base64',
239             'html_charset' => 'utf-8',
240             'text_charset' => 'utf-8',
241             'head_charset' => 'utf-8',
242         ));
243         // clean up the headers...
244         
245         
246         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
247                                      '@' . $content->HTTP_HOST .'>';
248         
249           
250         if ($htmlbody !== false) {
251             // got a html headers...
252             
253             if (isset($parts[1]['Content-Type'])) {
254                 unset($parts[1]['Content-Type']);
255             }
256             $mime->setTXTBody($parts[2]);
257             $this->textbody = $parts[2];
258             $mime->setHTMLBody($htmlbody);
259             
260 //            var_dump($mime);exit;
261             foreach($this->images as $cid=>$cdata) { 
262             
263                 $mime->addHTMLImage(
264                     $cdata['file'],
265                      $cdata['mimetype'],
266                      $cid.'.'.$cdata['ext'],
267                     true,
268                     $cdata['contentid']
269                 );
270             }
271             $isMime = true;
272         }
273         
274         if(!empty($this->attachments)){
275             //if got a attachments
276             $header = $mime->headers($parts[1]);
277             
278             if (isset($parts[1]['Content-Type'])) {
279                 unset($parts[1]['Content-Type']);
280             }
281             
282             if (!$isMime) {
283             
284                 if(preg_match('/text\/html/', $header['Content-Type'])){
285                     $mime->setHTMLBody($parts[2]);
286                     $mime->setTXTBody('This message is in HTML only');
287                     $this->textbody = 'This message is in HTML only';
288                 }else{
289                     $mime->setTXTBody($parts[2]);
290                     $this->textbody = $parts[2];
291                     $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
292                 }
293             }
294             foreach($this->attachments as $attch){
295                 $mime->addAttachment(
296                         $attch['file'],
297                         $attch['mimetype'],
298                         (!empty($attch['name'])) ? $attch['name'] : '',
299                         true
300                 );
301             }
302             
303             $isMime = true;
304         }
305         
306         if($isMime){
307             $parts[2] = $mime->get();
308             $parts[1] = $mime->headers($parts[1]);
309         }
310         
311         var_dump($parts);
312         
313         $ret = array(
314             'recipents' => $parts[0],
315             'headers' => $parts[1],
316             'body' => $parts[2],
317             'mailer' => $this
318         );
319         if ($this->rcpts !== false) {
320             $ret['recipents'] =  $this->rcpts;
321         }
322         // if 'to' is empty, then add the recipents in there... (must be an array?
323         if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
324                 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
325             $ret['headers']['To'] = implode(',', $ret['recipents']);
326         }
327        
328         
329         // add bcc if necessary..
330         if (!empty($this->bcc)) {
331            $ret['bcc'] = $this->bcc;
332         }
333         return $ret;
334     }
335     function send($email = false)
336     {
337                         
338         $ff = HTML_FlexyFramework::get();
339         
340         $pg = $ff->page;
341         
342         $email = is_array($email)  ? $email : $this->toData();
343         
344         if (is_a($email, 'PEAR_Error')) {
345             $pg->addEvent("COREMAILER-FAIL",  false, "email toData failed"); 
346       
347             
348             return $email;
349         }
350         
351         //$this->log( htmlspecialchars(print_r($email,true)));
352         
353         ///$recipents = array($this->email);
354 //        $mailOptions = PEAR::getStaticProperty('Mail','options');
355         
356         $mailOptions = isset($ff->Mail) ? $ff->Mail : array();
357         //print_R($mailOptions);exit;
358         
359         if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
360             $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
361             
362         }
363         
364         $mail = Mail::factory($this->mail_method,$mailOptions);
365         if ($this->debug) {
366             $mail->debug = (bool) $this->debug;
367         }
368         
369         $email['headers']['Date'] = date('r'); 
370         if (PEAR::isError($mail)) {
371             $pg->addEvent("COREMAILER-FAIL",  false, "mail factory failed"); 
372       
373             
374             return $mail;
375         } 
376         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
377         
378         
379         
380         // this makes contents untrustable...
381         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
382             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
383         }
384         
385         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
386         if ($this->debug) {
387             print_r(array(
388                 'rcpts' => $rcpts,
389                 'email' => $email
390             ));
391         }
392         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
393         error_reporting($oe);
394         if ($ret === true) { 
395             $pg->addEvent("COREMAILER-SENT",  false,
396                 'To: ' .  ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
397                 'Subject: '  . @$email['headers']['Subject']
398             ); 
399         }  else {
400             $pg->addEvent("COREMAILER-FAIL",  false,
401                 "Sending to : " . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
402                 " Error: " . $ret->toString());
403
404         }
405         
406         return $ret;
407     }
408     
409     function htmlbodytoCID($html)
410     {
411         $dom = new DOMDocument();
412         // this may raise parse errors as some html may be a component..
413         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
414         $imgs= $dom->getElementsByTagName('img');
415         
416         $urls = array();
417         
418         foreach ($imgs as $i=>$img) {
419             $url  = $img->getAttribute('src');
420             if (preg_match('#^cid:#', $url)) {
421                 continue;
422             }
423             $me = $img->getAttribute('mailembed');
424             if ($me == 'no') {
425                 continue;
426             }
427             
428             if(!array_key_exists($url, $urls)){
429                 $conv = $this->fetchImage($url);
430                 $urls[$url] = $conv;
431                 $this->images[$conv['contentid']] = $conv;
432             } else {
433                 $conv = $urls[$url];
434             }
435             $img->setAttribute('origsrc', $url);
436             $img->setAttribute('src', 'cid:' . $conv['contentid']);
437         }
438         
439         
440         return $dom->saveHTML();
441         
442     }
443     function htmlbodyCssEmbed($html)
444     {
445         $ff = HTML_FlexyFramework::get();
446         $dom = new DOMDocument();
447         
448         // this may raise parse errors as some html may be a component..
449         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
450         $links = $dom->getElementsByTagName('link');
451         $lc = array();
452         foreach ($links as $link) {  // duplicate as links is dynamic and we change it..!
453             $lc[] = $link;
454         }
455         //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
456         
457         foreach ($lc as $i=>$link) {
458             //var_dump($link->getAttribute('href'));
459             
460             if ($link->getAttribute('rel') != 'stylesheet') {
461                 continue;
462             }
463             $url  = $link->getAttribute('href');
464             $file = $ff->rootDir . $url;
465             
466             if (!preg_match('#^(http|https)://#', $url)) {
467                 $file = $ff->rootDir . $url;
468
469                 if (!file_exists($file)) {
470 //                    echo $file;
471                     $link->setAttribute('href', 'missing:' . $file);
472                     continue;
473                 }
474             } else {
475                $file = $this->mapurl($url);  
476             }
477             
478             $par = $link->parentNode;
479             $par->removeChild($link);
480             $s = $dom->createElement('style');
481             $e = $dom->createTextNode(file_get_contents($file));
482             $s->appendChild($e);
483             $par->appendChild($s);
484             
485         }
486         return $dom->saveHTML();
487         
488         
489     }
490     
491     function htmlbodyInlineCss($html)
492     {   
493         $dom = new DOMDocument();
494         
495         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
496         
497         $html = $dom->getElementsByTagName('html');
498         $head = $dom->getElementsByTagName('head');
499         $body = $dom->getElementsByTagName('body');
500         
501         if(!$head->length){
502             $head = $dom->createElement('head');
503             $html->item(0)->insertBefore($head, $body->item(0));
504             $head = $dom->getElementsByTagName('head');
505         }
506         
507         $s = $dom->createElement('style');
508         $e = $dom->createTextNode($this->css_inline);
509         $s->appendChild($e);
510         $head->item(0)->appendChild($s);
511         
512         return $dom->saveHTML();
513         
514         /* Inline
515         require_once 'HTML/CSS/InlineStyle.php';
516         
517         $doc = new HTML_CSS_InlineStyle($html);
518         
519         $doc->applyStylesheet($this->css_inline);
520         
521         $html = $doc->getHTML();
522         
523         return $html;
524         */
525     }
526     
527     function htmlbodySetClass($html, $cls)
528     {
529         $dom = new DOMDocument();
530         
531         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
532         
533         $body = $dom->getElementsByTagName('body');
534         if (!empty($body->length)) {
535             $body->item(0)->setAttribute('class', $cls);
536         } else {
537             $body = $dom->createElement("body");
538             $body->setAttribute('class', $cls);
539             $dom->appendChild($body);
540         }
541         
542         
543         return $dom->saveHTML();
544     }
545     
546     function fetchImage($url)
547     {
548         
549         
550         $this->log( "FETCH : $url\n");
551         
552         if ($url[0] == '/') {
553             $ff = HTML_FlexyFramework::get();
554             $file = $ff->rootDir . $url;
555             require_once 'File/MimeType.php';
556             $m  = new File_MimeType();
557             $mt = $m->fromFilename($file);
558             $ext = $m->toExt($mt); 
559             
560             return array(
561                     'mimetype' => $mt,
562                    'ext' => $ext,
563                    'contentid' => md5($file),  // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
564                    'file' => $file
565             );
566             
567             
568             
569         }
570         
571         //print_R($url); exit;
572         
573         
574         if (preg_match('#^file:///#', $url)) {
575             $file = preg_replace('#^file://#', '', $url);
576             require_once 'File/MimeType.php';
577             $m  = new File_MimeType();
578             $mt = $m->fromFilename($file);
579             $ext = $m->toExt($mt); 
580             
581             return array(
582                 'mimetype'  => $mt,
583                 'ext'       =>   $ext,
584                 'contentid' => md5($file),
585                 'file'      => $file
586             );
587             
588         }
589         
590         // CACHE???
591         // 2 files --- the info file.. and the actual file...
592         // add user
593         // unix only...
594         $uinfo = posix_getpwuid( posix_getuid () ); 
595         $user = $uinfo['name']; 
596         
597         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
598         if ($this->cache_images &&
599                 file_exists($cache) &&
600                 filemtime($cache) > strtotime('NOW - 1 WEEK')
601             ) {
602             $ret =  json_decode(file_get_contents($cache), true);
603             $this->log("fetched from cache");
604             $ret['file'] = $cache . '.data';
605             return $ret;
606         }
607         if (!file_exists(dirname($cache))) {
608             mkdir(dirname($cache),0700, true);
609         }
610         
611         require_once 'HTTP/Request.php';
612         
613         $real_url = str_replace(' ', '%20', $this->mapurl($url));
614         $a = new HTTP_Request($real_url);
615         $a->sendRequest();
616         $data = $a->getResponseBody();
617         
618         $this->log("got file of size " . strlen($data));
619         $this->log("save contentid " . md5($url));
620         
621         file_put_contents($cache .'.data', $data);
622         
623         
624         $mt = $a->getResponseHeader('Content-Type');
625         
626         require_once 'File/MimeType.php';
627         $m  = new File_MimeType();
628         $ext = $m->toExt($mt);
629         
630         $ret = array(
631             'mimetype' => $mt,
632             'ext' => $ext,
633             'contentid' => md5($url)
634             
635         );
636         
637         file_put_contents($cache, json_encode($ret));
638         $ret['file'] = $cache . '.data';
639         return $ret;
640     }  
641     
642     function mapurl($in)
643     {
644          foreach($this->urlmap as $o=>$n) {
645             if (strpos($in,$o) === 0) {
646                 $ret =$n . substr($in,strlen($o));
647                 $this->log("mapURL in $in = $ret");
648                 return $ret;
649             }
650         }
651         $this->log("mapurl no change - $in");
652         return $in;
653          
654         
655     }
656  
657     
658     
659     function log($val)
660     {
661         if (!$this->debug) {
662             return;
663         }
664         if ($this->debug < 2) {
665             echo '<PRE>' . print_r($val,true). "\n"; 
666             return;
667         }
668         $fh = fopen('/tmp/core_mailer.log', 'a');
669         fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");
670         fclose($fh);
671         
672         
673     }
674     
675 }