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(),   -- only used by the 'send' code???.
22        'template' => 'your_template.html',  // must be in templates/mail direcotry.. -- name without the .html or .txt
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         
285         
286         
287         $ret = array(
288             'recipents' => $parts[0],
289             'headers' => $parts[1],
290             'body' => $parts[2],
291             'mailer' => $this
292         );
293         // add bcc if necessary..
294         if (!empty($this->bcc)) {
295            $ret['bcc'] = $this->bcc;
296         }
297         return $ret;
298     }
299     function send($email = false)
300     {
301         
302         $pg = HTML_FlexyFramework::get()->page;
303         
304         
305         $email = is_array($email)  ? $email : $this->toData();
306         if (is_a($email, 'PEAR_Error')) {
307             $pg->addEvent("COREMAILER-FAIL",  false, "email toData failed"); 
308       
309             
310             return $email;
311         }
312         
313         //$this->log( htmlspecialchars(print_r($email,true)));
314         
315         ///$recipents = array($this->email);
316         $mailOptions = PEAR::getStaticProperty('Mail','options');
317         //print_R($mailOptions);exit;
318         
319         if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
320             $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
321             
322         }
323         
324         $mail = Mail::factory($this->mail_method,$mailOptions);
325         if ($this->debug) {
326             $mail->debug = (bool) $this->debug;
327         }
328         
329         $email['headers']['Date'] = date('r'); 
330         if (PEAR::isError($mail)) {
331             $pg->addEvent("COREMAILER-FAIL",  false, "mail factory failed"); 
332       
333             
334             return $mail;
335         } 
336         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
337         
338         
339         
340         // this makes contents untrustable...
341         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
342             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
343         }
344         
345         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
346         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
347         error_reporting($oe);
348         if ($ret === true) { 
349             $pg->addEvent("COREMAILER-SENT",  false,
350                 'To: ' .  ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
351                 'Subject: '  . @$email['headers']['Subject']
352             ); 
353         }  else {
354             $pg->addEvent("COREMAILER-FAIL",  false, $ret->toString());
355         }
356         
357         return $ret;
358     }
359     
360     function htmlbodytoCID($html)
361     {
362         $dom = new DOMDocument();
363         // this may raise parse errors as some html may be a component..
364         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
365         $imgs= $dom->getElementsByTagName('img');
366         
367         foreach ($imgs as $i=>$img) {
368             $url  = $img->getAttribute('src');
369             if (preg_match('#^cid:#', $url)) {
370                 continue;
371             }
372             $me = $img->getAttribute('mailembed');
373             if ($me == 'no') {
374                 continue;
375             }
376             
377             $conv = $this->fetchImage($url);
378             $this->images[$conv['contentid']] = $conv;
379             
380             $img->setAttribute('src', 'cid:' . $conv['contentid']);
381             
382             
383         }
384         return $dom->saveHTML();
385         
386         
387         
388     }
389     function htmlbodyCssEmbed($html)
390     {
391         $ff = HTML_FlexyFramework::get();
392         $dom = new DOMDocument();
393         
394         // this may raise parse errors as some html may be a component..
395         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
396         $links = $dom->getElementsByTagName('link');
397         $lc = array();
398         foreach ($links as $link) {  // duplicate as links is dynamic and we change it..!
399             $lc[] = $link;
400         }
401         //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
402         
403         foreach ($lc as $i=>$link) {
404             //var_dump($link->getAttribute('href'));
405             
406             if ($link->getAttribute('rel') != 'stylesheet') {
407                 continue;
408             }
409             $url  = $link->getAttribute('href');
410             $file = $ff->rootDir . $url;
411             
412             if (!preg_match('#^(http|https)://#', $url)) {
413                 $file = $ff->rootDir . $url;
414
415                 if (!file_exists($file)) {
416 //                    echo $file;
417                     $link->setAttribute('href', 'missing:' . $file);
418                     continue;
419                 }
420             } else {
421                $file = $this->mapurl($url);  
422             }
423             
424             $par = $link->parentNode;
425             $par->removeChild($link);
426             $s = $dom->createElement('style');
427             $e = $dom->createTextNode(file_get_contents($file));
428             $s->appendChild($e);
429             $par->appendChild($s);
430             
431         }
432         return $dom->saveHTML();
433         
434         
435     }
436     
437     
438     
439     function fetchImage($url)
440     {
441         
442         
443         $this->log( "FETCH : $url\n");
444         
445         if ($url[0] == '/') {
446             $ff = HTML_FlexyFramework::get();
447             $file = $ff->rootDir . $url;
448             require_once 'File/MimeType.php';
449             $m  = new File_MimeType();
450             $mt = $m->fromFilename($file);
451             $ext = $m->toExt($mt); 
452             
453             return array(
454                     'mimetype' => $mt,
455                    'ext' => $ext,
456                    'contentid' => md5($file),  // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
457                    'file' => $file
458             );
459             
460             
461             
462         }
463         
464         //print_R($url); exit;
465         
466         
467         if (preg_match('#^file:///#', $url)) {
468             $file = preg_replace('#^file://#', '', $url);
469             require_once 'File/MimeType.php';
470             $m  = new File_MimeType();
471             $mt = $m->fromFilename($file);
472             $ext = $m->toExt($mt); 
473             
474             return array(
475                 'mimetype'  => $mt,
476                 'ext'       =>   $ext,
477                 'contentid' => md5($file),
478                 'file'      => $file
479             );
480             
481         }
482         
483         // CACHE???
484         // 2 files --- the info file.. and the actual file...
485         // add user
486         // unix only...
487         $uinfo = posix_getpwuid( posix_getuid () ); 
488         $user = $uinfo['name']; 
489         
490         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
491         if ($this->cache_images &&
492                 file_exists($cache) &&
493                 filemtime($cache) > strtotime('NOW - 1 WEEK')
494             ) {
495             $ret =  json_decode(file_get_contents($cache), true);
496             $this->log("fetched from cache");
497             $ret['file'] = $cache . '.data';
498             return $ret;
499         }
500         if (!file_exists(dirname($cache))) {
501             mkdir(dirname($cache),0700, true);
502         }
503         
504         require_once 'HTTP/Request.php';
505         $a = new HTTP_Request($this->mapurl($url));
506         $a->sendRequest();
507         $data = $a->getResponseBody();
508         
509         $this->log("got file of size " . strlen($data));
510         $this->log("save contentid " . md5($url));
511         
512         file_put_contents($cache .'.data', $data);
513         
514         
515         $mt = $a->getResponseHeader('Content-Type');
516         
517         require_once 'File/MimeType.php';
518         $m  = new File_MimeType();
519         $ext = $m->toExt($mt);
520         
521         $ret = array(
522             'mimetype' => $mt,
523             'ext' => $ext,
524             'contentid' => md5($url)
525             
526         );
527         
528         file_put_contents($cache, json_encode($ret));
529         $ret['file'] = $cache . '.data';
530         return $ret;
531     }  
532     
533     function mapurl($in)
534     {
535         
536         foreach($this->urlmap as $o=>$n) {
537             if (strpos($in,$o) === 0) {
538                 $ret =$n . substr($in,strlen($o));
539                 $this->log("mapURL in $in = $ret");
540                 return $ret;
541             }
542         }
543         $this->log("mapurl no change - $in");
544         return $in;
545          
546         
547     }
548  
549     
550     
551     function log($val)
552     {
553         if (!$this->debug) {
554             return;
555         }
556         if ($this->debug < 2) {
557             echo '<PRE>' . print_r($val,true). "\n"; 
558             return;
559         }
560         $fh = fopen('/tmp/core_mailer.log', 'a');
561         fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");
562         fclose($fh);
563         
564         
565     }
566     
567 }