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