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