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