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