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