Mailer.php
[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     
77     var $html_locale = false; // eg. 'en' or 'zh_HK'
78     var $images         = array(); // generated list of cid images for sending
79     var $attachments = false;
80     var $css_inline = false; // put the css into the html
81     var $css_embed = false; // put the css tags into the body.
82     
83     var $mail_method = 'SMTP';
84     
85     var $cache_images = true;
86       
87     var $bcc = false;
88     
89     var $body_cls = false;
90     
91     function __construct($args) {
92         foreach($args as $k=>$v) {
93             // a bit trusting..
94             $this->$k =  $v;
95         }
96         // allow core mailer debug setting.
97         $ff = HTML_FlexyFramework::get();
98         
99         if (!empty($ff->Core_Mailer['debug'])) {
100             $this->debug = $ff->Core_Mailer['debug'];
101         }
102         //$this->log("URL MAP");
103         //$this->log($this->urlmap);
104         
105     }
106      
107     /**
108      * ---------------- Global Tools ---------------   
109      */
110     
111     function toData()
112     {
113         $ts = microtime(true);
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'])) {
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         if (!empty($this->templateDir)) {
143             $tmp_opts['templateDir'] = $this->templateDir;
144         }
145         $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
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         
153         // local opt's overwrite
154         if (!empty($this->locale)) {
155             $tmp_opts['locale'] = $this->locale;
156         }
157         
158         $htmlbody = false;
159         $html_tmp_opts = $tmp_opts;
160         $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
161         if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) { 
162             // then we have a multi-part email...
163             if (!empty($this->html_locale)) {
164                 $html_tmp_opts['locale'] = $this->html_locale;
165             }
166             $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
167             
168             $htmltemplate->compile('mail/'. $templateFile.'.body.html');
169             $htmlbody =  $htmltemplate->bufferedOutputObject($content);
170             
171             $this->htmlbody = $htmlbody;
172             
173             // for the html body, we may want to convert the attachments to images.
174 //            var_dump($htmlbody);exit;
175             
176             if(!empty($content->body_cls) && strlen($content->body_cls)){
177                 $htmlbody = $this->htmlbodySetClass($htmlbody, $content->body_cls);
178             }
179             
180             if ($this->replaceImages) {
181                 $htmlbody = $this->htmlbodytoCID($htmlbody);    
182             }
183             
184             if ($this->css_embed) {
185                 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
186             }
187             
188             if ($this->css_inline && strlen($this->css_inline)) {
189                 $htmlbody = $this->htmlbodyInlineCss($htmlbody);
190             }
191             
192         }
193         $tmp_opts['nonHTML'] = true;
194         
195         
196         //print_R($tmp_opts);
197         // $tmp_opts['force'] = true;
198         
199         $template = new HTML_Template_Flexy(  $tmp_opts );
200         $template->compile('mail/'. $templateFile.'.txt');
201         
202         /* use variables from this object to ouput data. */
203         $mailtext = $template->bufferedOutputObject($content);
204         //print_r($mailtext);exit;
205        
206         
207         
208         //echo "<PRE>";print_R($mailtext);
209         
210         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
211         require_once 'Mail/mimeDecode.php';
212         require_once 'Mail.php';
213         
214         $decoder = new Mail_mimeDecode($mailtext);
215         $parts = $decoder->getSendArray();
216         if (PEAR::isError($parts)) {
217             return $parts;
218             //echo "PROBLEM: {$parts->message}";
219             //exit;
220         } 
221         
222         $isMime = false;
223         
224         require_once 'Mail/mime.php';
225         $mime = new Mail_mime(array(
226             'eol' => "\n",
227             //'html_encoding' => 'base64',
228             'html_charset' => 'utf-8',
229             'text_charset' => 'utf-8',
230             'head_charset' => 'utf-8',
231         ));
232         // clean up the headers...
233         
234         
235         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
236                                      '@' . $content->HTTP_HOST .'>';
237         
238           
239         if ($htmlbody !== false) {
240             // got a html headers...
241             
242             if (isset($parts[1]['Content-Type'])) {
243                 unset($parts[1]['Content-Type']);
244             }
245             $mime->setTXTBody($parts[2]);
246             $mime->setHTMLBody($htmlbody);
247 //            var_dump($mime);exit;
248             foreach($this->images as $cid=>$cdata) { 
249             
250                 $mime->addHTMLImage(
251                     $cdata['file'],
252                      $cdata['mimetype'],
253                      $cid.'.'.$cdata['ext'],
254                     true,
255                     $cdata['contentid']
256                 );
257             }
258             $isMime = true;
259         }
260         
261         if(!empty($this->attachments)){
262             //if got a attachments
263             $header = $mime->headers($parts[1]);
264             
265             if (isset($parts[1]['Content-Type'])) {
266                 unset($parts[1]['Content-Type']);
267             }
268             
269             if (!$isMime) {
270             
271                 if(preg_match('/text\/html/', $header['Content-Type'])){
272                     $mime->setHTMLBody($parts[2]);
273                     $mime->setTXTBody('This message is in HTML only');
274                 }else{
275                     $mime->setTXTBody($parts[2]);
276                     $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
277                 }
278             }
279             foreach($this->attachments as $attch){
280                 $mime->addAttachment(
281                         $attch['file'],
282                         $attch['mimetype'],
283                         (!empty($attch['name'])) ? $attch['name'] : '',
284                         true
285                 );
286             }
287             
288             $isMime = true;
289         }
290         
291         if($isMime){
292             $parts[2] = $mime->get();
293             $parts[1] = $mime->headers($parts[1]);
294         }
295          
296         
297         $ret = array(
298             'recipents' => $parts[0],
299             'headers' => $parts[1],
300             'body' => $parts[2],
301             'mailer' => $this
302         );
303         if ($this->rcpts !== false) {
304             $ret['recipents'] =  $this->rcpts;
305         }
306         // if 'to' is empty, then add the recipents in there... (must be an array?
307         if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
308                 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
309             $ret['headers']['To'] = implode(',', $ret['recipents']);
310         }
311        
312         
313         // add bcc if necessary..
314         if (!empty($this->bcc)) {
315            $ret['bcc'] = $this->bcc;
316         }
317         return $ret;
318     }
319     function send($email = false)
320     {
321                         
322         $ff = HTML_FlexyFramework::get();
323         
324         $pg = $ff->page;
325         
326         $email = is_array($email)  ? $email : $this->toData();
327         
328         if (is_a($email, 'PEAR_Error')) {
329             $pg->addEvent("COREMAILER-FAIL",  false, "email toData failed"); 
330       
331             
332             return $email;
333         }
334         
335         //$this->log( htmlspecialchars(print_r($email,true)));
336         
337         ///$recipents = array($this->email);
338 //        $mailOptions = PEAR::getStaticProperty('Mail','options');
339         
340         $mailOptions = isset($ff->Mail) ? $ff->Mail : array();
341         //print_R($mailOptions);exit;
342         
343         if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
344             $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
345             
346         }
347         
348         $mail = Mail::factory($this->mail_method,$mailOptions);
349         if ($this->debug) {
350             $mail->debug = (bool) $this->debug;
351         }
352         
353         $email['headers']['Date'] = date('r'); 
354         if (PEAR::isError($mail)) {
355             $pg->addEvent("COREMAILER-FAIL",  false, "mail factory failed"); 
356       
357             
358             return $mail;
359         } 
360         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
361         
362         
363         
364         // this makes contents untrustable...
365         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
366             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
367         }
368         
369         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
370         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
371         error_reporting($oe);
372         if ($ret === true) { 
373             $pg->addEvent("COREMAILER-SENT",  false,
374                 'To: ' .  ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
375                 'Subject: '  . @$email['headers']['Subject']
376             ); 
377         }  else {
378             $pg->addEvent("COREMAILER-FAIL",  false, $ret->toString());
379         }
380         
381         return $ret;
382     }
383     
384     function htmlbodytoCID($html)
385     {
386         $dom = new DOMDocument();
387         // this may raise parse errors as some html may be a component..
388         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
389         $imgs= $dom->getElementsByTagName('img');
390         
391         foreach ($imgs as $i=>$img) {
392             $url  = $img->getAttribute('src');
393             if (preg_match('#^cid:#', $url)) {
394                 continue;
395             }
396             $me = $img->getAttribute('mailembed');
397             if ($me == 'no') {
398                 continue;
399             }
400             
401             $conv = $this->fetchImage($url);
402             $this->images[$conv['contentid']] = $conv;
403             
404             $img->setAttribute('src', 'cid:' . $conv['contentid']);
405             
406             
407         }
408         return $dom->saveHTML();
409         
410         
411         
412     }
413     function htmlbodyCssEmbed($html)
414     {
415         $ff = HTML_FlexyFramework::get();
416         $dom = new DOMDocument();
417         
418         // this may raise parse errors as some html may be a component..
419         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
420         $links = $dom->getElementsByTagName('link');
421         $lc = array();
422         foreach ($links as $link) {  // duplicate as links is dynamic and we change it..!
423             $lc[] = $link;
424         }
425         //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
426         
427         foreach ($lc as $i=>$link) {
428             //var_dump($link->getAttribute('href'));
429             
430             if ($link->getAttribute('rel') != 'stylesheet') {
431                 continue;
432             }
433             $url  = $link->getAttribute('href');
434             $file = $ff->rootDir . $url;
435             
436             if (!preg_match('#^(http|https)://#', $url)) {
437                 $file = $ff->rootDir . $url;
438
439                 if (!file_exists($file)) {
440 //                    echo $file;
441                     $link->setAttribute('href', 'missing:' . $file);
442                     continue;
443                 }
444             } else {
445                $file = $this->mapurl($url);  
446             }
447             
448             $par = $link->parentNode;
449             $par->removeChild($link);
450             $s = $dom->createElement('style');
451             $e = $dom->createTextNode(file_get_contents($file));
452             $s->appendChild($e);
453             $par->appendChild($s);
454             
455         }
456         return $dom->saveHTML();
457         
458         
459     }
460     
461     function htmlbodyInlineCss($html)
462     {   
463         $dom = new DOMDocument();
464         
465         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
466         
467         $html = $dom->getElementsByTagName('html');
468         $head = $dom->getElementsByTagName('head');
469         $body = $dom->getElementsByTagName('body');
470         
471         if(!$head->length){
472             $head = $dom->createElement('head');
473             $html->item(0)->insertBefore($head, $body->item(0));
474             $head = $dom->getElementsByTagName('head');
475         }
476         
477         $s = $dom->createElement('style');
478         $e = $dom->createTextNode($this->css_inline);
479         $s->appendChild($e);
480         $head->item(0)->appendChild($s);
481         
482         return $dom->saveHTML();
483         
484         /* Inline
485         require_once 'HTML/CSS/InlineStyle.php';
486         
487         $doc = new HTML_CSS_InlineStyle($html);
488         
489         $doc->applyStylesheet($this->css_inline);
490         
491         $html = $doc->getHTML();
492         
493         return $html;
494         */
495     }
496     
497     function htmlbodySetClass($html, $cls)
498     {
499         $dom = new DOMDocument();
500         
501         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
502         
503         $body = $dom->getElementsByTagName('body');
504         
505         $class = $dom->createAttribute('class');
506         $class->value = $cls;
507         $body->item(0)->appendChild($class);
508         
509         return $dom->saveHTML();
510     }
511     
512     function fetchImage($url)
513     {
514         
515         
516         $this->log( "FETCH : $url\n");
517         
518         if ($url[0] == '/') {
519             $ff = HTML_FlexyFramework::get();
520             $file = $ff->rootDir . $url;
521             require_once 'File/MimeType.php';
522             $m  = new File_MimeType();
523             $mt = $m->fromFilename($file);
524             $ext = $m->toExt($mt); 
525             
526             return array(
527                     'mimetype' => $mt,
528                    'ext' => $ext,
529                    'contentid' => md5($file),  // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
530                    'file' => $file
531             );
532             
533             
534             
535         }
536         
537         //print_R($url); exit;
538         
539         
540         if (preg_match('#^file:///#', $url)) {
541             $file = preg_replace('#^file://#', '', $url);
542             require_once 'File/MimeType.php';
543             $m  = new File_MimeType();
544             $mt = $m->fromFilename($file);
545             $ext = $m->toExt($mt); 
546             
547             return array(
548                 'mimetype'  => $mt,
549                 'ext'       =>   $ext,
550                 'contentid' => md5($file),
551                 'file'      => $file
552             );
553             
554         }
555         
556         // CACHE???
557         // 2 files --- the info file.. and the actual file...
558         // add user
559         // unix only...
560         $uinfo = posix_getpwuid( posix_getuid () ); 
561         $user = $uinfo['name']; 
562         
563         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
564         if ($this->cache_images &&
565                 file_exists($cache) &&
566                 filemtime($cache) > strtotime('NOW - 1 WEEK')
567             ) {
568             $ret =  json_decode(file_get_contents($cache), true);
569             $this->log("fetched from cache");
570             $ret['file'] = $cache . '.data';
571             return $ret;
572         }
573         if (!file_exists(dirname($cache))) {
574             mkdir(dirname($cache),0700, true);
575         }
576         
577         require_once 'HTTP/Request.php';
578         
579         $real_url = str_replace(' ', '%20', $this->mapurl($url));
580         $a = new HTTP_Request($real_url);
581         $a->sendRequest();
582         $data = $a->getResponseBody();
583         
584         $this->log("got file of size " . strlen($data));
585         $this->log("save contentid " . md5($url));
586         
587         file_put_contents($cache .'.data', $data);
588         
589         
590         $mt = $a->getResponseHeader('Content-Type');
591         
592         require_once 'File/MimeType.php';
593         $m  = new File_MimeType();
594         $ext = $m->toExt($mt);
595         
596         $ret = array(
597             'mimetype' => $mt,
598             'ext' => $ext,
599             'contentid' => md5($url)
600             
601         );
602         
603         file_put_contents($cache, json_encode($ret));
604         $ret['file'] = $cache . '.data';
605         return $ret;
606     }  
607     
608     function mapurl($in)
609     {
610         
611         foreach($this->urlmap as $o=>$n) {
612             if (strpos($in,$o) === 0) {
613                 $ret =$n . substr($in,strlen($o));
614                 $this->log("mapURL in $in = $ret");
615                 return $ret;
616             }
617         }
618         $this->log("mapurl no change - $in");
619         return $in;
620          
621         
622     }
623  
624     
625     
626     function log($val)
627     {
628         if (!$this->debug) {
629             return;
630         }
631         if ($this->debug < 2) {
632             echo '<PRE>' . print_r($val,true). "\n"; 
633             return;
634         }
635         $fh = fopen('/tmp/core_mailer.log', 'a');
636         fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");
637         fclose($fh);
638         
639         
640     }
641     
642 }