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