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