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