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