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= Pman_Core_Mailer(array(
19        'page' => $this,
20                 // if bcc is property of this, then it will be used (BAD DESIGN)
21        'rcpts' => array(),   // override recipients..
22        'template' => 'your_template.html',
23        
24         // 'bcc' => 'xyz@abc.com,abc@xyz.com',  // string...
25         // 'contents'  => array(),              //  << keys must be trusted
26                                             // if bcc is property of contents, then it will be used (BAD DESIGN)
27            
28         // 'html_locale => 'en',                // always use the 'english translated verison'
29         // 'cache_images => true,               // -- defaults to caching images - set to false to disable.
30         // 'replaceImages => false,             // should images be replaced.
31         // 'urlmap => array(                    // map urls from template to a different location.
32         //      'https://www.mysite.com/' => 'http://localhost/',
33         // ),
34         // 'locale' => 'en',                    // .... or zh_hk....
35            
36         // 'attachments' => array(
37         //       array(
38         //        'file' => '/path/to/file',    // file location
39         //        name => 'myfile.pdf',         // (optional) - uses basename of file
40         //        mimetype : 
41         //      ), 
42         //  
43         // 'mail_method' =>  'SMTP',            // or SMTPMX
44   
45     )
46  *
47  *  recipents is gathered from the resulting template
48  *   -- eg.
49  *    To: <a>,<b>,<c>
50  * 
51  * 
52  *  if the file     '
53  * 
54  * 
55  *  $x->toData(); // returns data needed for notify?? - notify should really
56  *                  // just use this to pass around later..
57  *
58  *  $x->send();
59  *
60  */
61
62 class Pman_Core_Mailer {
63     var $debug          = 0;
64     var $page           = false; /* usually a html_flexyframework_page */
65     var $contents       = false; /* object or array */
66     var $template       = false; /* string */
67     var $replaceImages  = false; /* boolean */
68     var $rcpts   = false;
69     var $templateDir = false;
70     var $locale = false; // eg. 'en' or 'zh_HK'
71     var $urlmap = array();
72     
73     
74     var $html_locale = false; // eg. 'en' or 'zh_HK'
75     var $images         = array(); // generated list of cid images for sending
76     var $attachments = false;
77     var $css_inline = false; // not supported
78     var $css_embed = false; // put the css tags into the body.
79     
80     var $mail_method = 'SMTP';
81     
82     var $cache_images = true;
83       
84     var $bcc = false;
85     
86     function Pman_Core_Mailer($args) {
87         foreach($args as $k=>$v) {
88             // a bit trusting..
89             $this->$k =  $v;
90         }
91         // allow core mailer debug setting.
92         $ff = HTML_FlexyFramework::get();
93         
94         if (!empty($ff->Core_Mailer['debug'])) {
95             $this->debug = $ff->Core_Mailer['debug'];
96         }
97         //$this->log("URL MAP");
98         //$this->log($this->urlmap);
99         
100     }
101      
102     /**
103      * ---------------- Global Tools ---------------   
104      */
105     
106     function toData()
107     {
108     
109         $templateFile = $this->template;
110         $args = (array)$this->contents;
111         
112         $content  = clone($this->page);
113         
114         foreach($args as $k=>$v) {
115             $content->$k = $v;
116         }
117         
118         $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
119         
120         $ff = HTML_FlexyFramework::get();
121         $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
122         if (isset($ff->Pman['HTTP_HOST'])) {
123             $http_host  = $ff->Pman['HTTP_HOST'];
124         }
125         
126         
127         $content->HTTP_HOST = $http_host;
128         
129         
130         
131         
132         // this should be done by having multiple template sources...!!!
133         
134         require_once 'HTML/Template/Flexy.php';
135         
136         $tmp_opts = array(
137            // 'forceCompile' => true,
138             'site_prefix' => false,
139         );
140         if (!empty($this->templateDir)) {
141             $tmp_opts['templateDir'] = $this->templateDir;
142         }
143         $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
144         if (!empty($fopts['DB_DataObject_translator'])) {
145             $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
146         }
147         if (!empty($fopts['locale'])) {
148             $tmp_opts['locale'] = $fopts['locale'];
149         }
150         
151         // local opt's overwrite
152         if (!empty($this->locale)) {
153             $tmp_opts['locale'] = $this->locale;
154         }
155         
156         $htmlbody = false;
157         $html_tmp_opts = $tmp_opts;
158         $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
159         if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
160             // then we have a multi-part email...
161             
162             if (!empty($this->html_locale)) {
163                 $html_tmp_opts['locale'] = $this->html_locale;
164             }
165             $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
166             
167             $htmltemplate->compile('mail/'. $templateFile.'.body.html');
168             $htmlbody =  $htmltemplate->bufferedOutputObject($content);
169             
170             $this->htmlbody = $htmlbody;
171             
172             // for the html body, we may want to convert the attachments to images.
173 //            var_dump($htmlbody);exit;
174             if ($this->replaceImages) {
175                 $htmlbody = $this->htmlbodytoCID($htmlbody);    
176             }
177             if ($this->css_embed) {
178                 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);    
179               
180             }
181         }
182         $tmp_opts['nonHTML'] = true;
183         
184         
185         //print_R($tmp_opts);
186         // $tmp_opts['force'] = true;
187         $template = new HTML_Template_Flexy(  $tmp_opts );
188         
189         $template->compile('mail/'. $templateFile.'.txt');
190         
191         /* use variables from this object to ouput data. */
192         $mailtext = $template->bufferedOutputObject($content);
193         //print_r($mailtext);exit;
194        
195         
196         
197         //echo "<PRE>";print_R($mailtext);
198         
199         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
200         require_once 'Mail/mimeDecode.php';
201         require_once 'Mail.php';
202         
203         $decoder = new Mail_mimeDecode($mailtext);
204         $parts = $decoder->getSendArray();
205         if (PEAR::isError($parts)) {
206             return $parts;
207             //echo "PROBLEM: {$parts->message}";
208             //exit;
209         } 
210         
211         $isMime = false;
212         
213         require_once 'Mail/mime.php';
214         $mime = new Mail_mime(array(
215             'eol' => "\n",
216             //'html_encoding' => 'base64',
217             'html_charset' => 'utf-8',
218             'text_charset' => 'utf-8',
219             'head_charset' => 'utf-8',
220         ));
221         // clean up the headers...
222         
223         
224         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
225                                      '@' . $content->HTTP_HOST .'>';
226         
227           
228         if ($htmlbody !== false) {
229             // got a html headers...
230             
231             if (isset($parts[1]['Content-Type'])) {
232                 unset($parts[1]['Content-Type']);
233             }
234             $mime->setTXTBody($parts[2]);
235             $mime->setHTMLBody($htmlbody);
236 //            var_dump($mime);exit;
237             foreach($this->images as $cid=>$cdata) { 
238             
239                 $mime->addHTMLImage(
240                     $cdata['file'],
241                      $cdata['mimetype'],
242                      $cid.'.'.$cdata['ext'],
243                     true,
244                     $cdata['contentid']
245                 );
246             }
247             $isMime = true;
248         }
249         
250         if(!empty($this->attachments)){
251             //if got a attachments
252             $header = $mime->headers($parts[1]);
253             
254             if (isset($parts[1]['Content-Type'])) {
255                 unset($parts[1]['Content-Type']);
256             }
257             
258             if (!$isMime) {
259             
260                 if(preg_match('/text\/html/', $header['Content-Type'])){
261                     $mime->setHTMLBody($parts[2]);
262                     $mime->setTXTBody('This message is in HTML only');
263                 }else{
264                     $mime->setTXTBody($parts[2]);
265                     $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
266                 }
267             }
268             foreach($this->attachments as $attch){
269                 $mime->addAttachment(
270                         $attch['file'],
271                         $attch['mimetype'],
272                         (!empty($attch['name'])) ? $attch['name'] : '',
273                         true
274                 );
275             }
276             
277             $isMime = true;
278         }
279         
280         if($isMime){
281             $parts[2] = $mime->get();
282             $parts[1] = $mime->headers($parts[1]);
283         }
284         $ret = array(
285             'recipents' => $parts[0],
286             'headers' => $parts[1],
287             'body' => $parts[2],
288             'mailer' => $this
289         );
290         // add bcc if necessary..
291         if (!empty($this->bcc)) {
292            $ret['bcc'] = $this->bcc;
293         }
294         return $ret;
295     }
296     function send($email = false)
297     {
298         
299         $pg = HTML_FlexyFramework::get()->page;
300         
301         
302         $email = is_array($email)  ? $email : $this->toData();
303         if (is_a($email, 'PEAR_Error')) {
304             $pg->addEvent("COREMAILER-FAIL",  false, "email toData failed"); 
305       
306             
307             return $email;
308         }
309         
310         //$this->log( htmlspecialchars(print_r($email,true)));
311         
312         ///$recipents = array($this->email);
313         $mailOptions = PEAR::getStaticProperty('Mail','options');
314         //print_R($mailOptions);exit;
315         
316         if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
317             $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
318             
319         }
320         
321         $mail = Mail::factory($this->mail_method,$mailOptions);
322         if ($this->debug) {
323             $mail->debug = (bool) $this->debug;
324         }
325         
326         $email['headers']['Date'] = date('r'); 
327         if (PEAR::isError($mail)) {
328             $pg->addEvent("COREMAILER-FAIL",  false, "mail factory failed"); 
329       
330             
331             return $mail;
332         } 
333         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
334         
335         
336         
337         // this makes contents untrustable...
338         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
339             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
340         }
341         
342         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
343         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
344         error_reporting($oe);
345         if ($ret === true) { 
346             $pg->addEvent("COREMAILER-SENT",  false,
347                 'To: ' .  ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
348                 'Subject: '  . @$email['headers']['Subject']
349             ); 
350         }  else {
351             $pg->addEvent("COREMAILER-FAIL",  false, $ret->toString());
352         }
353         
354         return $ret;
355     }
356     
357     function htmlbodytoCID($html)
358     {
359         $dom = new DOMDocument();
360         // this may raise parse errors as some html may be a component..
361         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
362         $imgs= $dom->getElementsByTagName('img');
363         
364         foreach ($imgs as $i=>$img) {
365             $url  = $img->getAttribute('src');
366             if (preg_match('#^cid:#', $url)) {
367                 continue;
368             }
369             $me = $img->getAttribute('mailembed');
370             if ($me == 'no') {
371                 continue;
372             }
373             
374             $conv = $this->fetchImage($url);
375             $this->images[$conv['contentid']] = $conv;
376             
377             $img->setAttribute('src', 'cid:' . $conv['contentid']);
378             
379             
380         }
381         return $dom->saveHTML();
382         
383         
384         
385     }
386     function htmlbodyCssEmbed($html)
387     {
388         $ff = HTML_FlexyFramework::get();
389         $dom = new DOMDocument();
390         
391         // this may raise parse errors as some html may be a component..
392         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
393         $links = $dom->getElementsByTagName('link');
394         $lc = array();
395         foreach ($links as $link) {  // duplicate as links is dynamic and we change it..!
396             $lc[] = $link;
397         }
398         //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
399         
400         foreach ($lc as $i=>$link) {
401             //var_dump($link->getAttribute('href'));
402             
403             if ($link->getAttribute('rel') != 'stylesheet') {
404                 continue;
405             }
406             $url  = $link->getAttribute('href');
407             $file = $ff->rootDir . $url;
408             
409             if (!preg_match('#^(http|https)://#', $url)) {
410                 $file = $ff->rootDir . $url;
411
412                 if (!file_exists($file)) {
413 //                    echo $file;
414                     $link->setAttribute('href', 'missing:' . $file);
415                     continue;
416                 }
417             } else {
418                $file = $this->mapurl($url);  
419             }
420             
421             $par = $link->parentNode;
422             $par->removeChild($link);
423             $s = $dom->createElement('style');
424             $e = $dom->createTextNode(file_get_contents($file));
425             $s->appendChild($e);
426             $par->appendChild($s);
427             
428         }
429         return $dom->saveHTML();
430         
431         
432     }
433     
434     
435     
436     function fetchImage($url)
437     {
438         
439         
440         $this->log( "FETCH : $url\n");
441         
442         if ($url[0] == '/') {
443             $ff = HTML_FlexyFramework::get();
444             $file = $ff->rootDir . $url;
445             require_once 'File/MimeType.php';
446             $m  = new File_MimeType();
447             $mt = $m->fromFilename($file);
448             $ext = $m->toExt($mt); 
449             
450             return array(
451                     'mimetype' => $mt,
452                    'ext' => $ext,
453                    'contentid' => md5($file),  // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
454                    'file' => $file
455             );
456             
457             
458             
459         }
460         
461         //print_R($url); exit;
462         
463         
464         if (preg_match('#^file:///#', $url)) {
465             $file = preg_replace('#^file://#', '', $url);
466             require_once 'File/MimeType.php';
467             $m  = new File_MimeType();
468             $mt = $m->fromFilename($file);
469             $ext = $m->toExt($mt); 
470             
471             return array(
472                 'mimetype'  => $mt,
473                 'ext'       =>   $ext,
474                 'contentid' => md5($file),
475                 'file'      => $file
476             );
477             
478         }
479         
480         // CACHE???
481         // 2 files --- the info file.. and the actual file...
482         // add user
483         // unix only...
484         $uinfo = posix_getpwuid( posix_getuid () ); 
485         $user = $uinfo['name']; 
486         
487         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
488         if ($this->cache_images &&
489                 file_exists($cache) &&
490                 filemtime($cache) > strtotime('NOW - 1 WEEK')
491             ) {
492             $ret =  json_decode(file_get_contents($cache), true);
493             $this->log("fetched from cache");
494             $ret['file'] = $cache . '.data';
495             return $ret;
496         }
497         if (!file_exists(dirname($cache))) {
498             mkdir(dirname($cache),0700, true);
499         }
500         
501         require_once 'HTTP/Request.php';
502         $a = new HTTP_Request($this->mapurl($url));
503         $a->sendRequest();
504         $data = $a->getResponseBody();
505         
506         $this->log("got file of size " . strlen($data));
507         $this->log("save contentid " . md5($url));
508         
509         file_put_contents($cache .'.data', $data);
510         
511         
512         $mt = $a->getResponseHeader('Content-Type');
513         
514         require_once 'File/MimeType.php';
515         $m  = new File_MimeType();
516         $ext = $m->toExt($mt);
517         
518         $ret = array(
519             'mimetype' => $mt,
520             'ext' => $ext,
521             'contentid' => md5($url)
522             
523         );
524         
525         file_put_contents($cache, json_encode($ret));
526         $ret['file'] = $cache . '.data';
527         return $ret;
528     }  
529     
530     function mapurl($in)
531     {
532         
533         foreach($this->urlmap as $o=>$n) {
534             if (strpos($in,$o) === 0) {
535                 $ret =$n . substr($in,strlen($o));
536                 $this->log("mapURL in $in = $ret");
537                 return $ret;
538             }
539         }
540         $this->log("mapurl no change - $in");
541         return $in;
542          
543         
544     }
545  
546     
547     
548     function log($val)
549     {
550         if (!$this->debug) {
551             return;
552         }
553         if ($this->debug < 2) {
554             echo '<PRE>' . print_r($val,true). "\n"; 
555             return;
556         }
557         $fh = fopen('/tmp/core_mailer.log', 'a');
558         fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");
559         fclose($fh);
560         
561         
562     }
563     
564 }