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  *  $x= new Pman_Core_Mailer($opts)
18  *
19  *  $x= Pman_Core_Mailer(array(
20        page => 
21        contents
22        template
23        html_locale => 'en' == always use the 'english translated verison'
24        cache_images => true -- defaults to caching images - set to false to disable.
25        replaceImages => true|false,
26        urlmap => array(
27             'https://www.mysite.com/', 'http://localhost/'
28        )
29        locale => 'en' .... or zh_hk....
30        rcpts => array()   // override recipients..
31        attachments => array(
32         array(
33           file: 
34           name : (optional) - uses basename of file
35           mimetype : 
36         ), 
37         ......
38         mail_method : (SMTP or SMTPMX)
39   
40     )
41  *
42  *  recipents is gathered from the resulting template
43  *   -- eg.
44  *    To: <a>,<b>,<c>
45  * 
46  * 
47  *  if the file     '
48  * 
49  * 
50  *  $x->toData(); // returns data needed for notify?? - notify should really
51  *                  // just use this to pass around later..
52  *
53  *  $x->send();
54  *
55  */
56
57 class Pman_Core_Mailer {
58     var $debug          = 0;
59     var $page           = false; /* usually a html_flexyframework_page */
60     var $contents       = false; /* object or array */
61     var $template       = false; /* string */
62     var $replaceImages  = false; /* boolean */
63     var $rcpts   = false;
64     var $templateDir = false;
65     var $locale = false; // eg. 'en' or 'zh_HK'
66     var $urlmap = array();
67     
68     
69     var $html_locale = false; // eg. 'en' or 'zh_HK'
70     var $images         = array(); // generated list of cid images for sending
71     var $attachments = false;
72     var $css_inline = false; // not supported
73     var $css_embed = false; // put the css tags into the body.
74     
75     var $mail_method = 'SMTP';
76     
77     var $cache_images = true;
78     
79     function Pman_Core_Mailer($args) {
80         foreach($args as $k=>$v) {
81             // a bit trusting..
82             $this->$k =  $v;
83         }
84         // allow core mailer debug setting.
85         $ff = HTML_FlexyFramework::get();
86         
87         if (!empty($ff->Core_Mailer['debug'])) {
88             $this->debug = $ff->Core_Mailer['debug'];
89         }
90         $this->log("URL MAP");
91         $this->log($this->urlmap);
92         
93     }
94      
95     /**
96      * ---------------- Global Tools ---------------   
97      */
98     
99     function toData()
100     {
101     
102         $templateFile = $this->template;
103         $args = (array)$this->contents;
104         
105         $content  = clone($this->page);
106         
107         foreach($args as $k=>$v) {
108             $content->$k = $v;
109         }
110         
111         $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
112         
113         $ff = HTML_FlexyFramework::get();
114         $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
115         if (isset($ff->Pman['HTTP_HOST'])) {
116             $http_host  = $ff->Pman['HTTP_HOST'];
117         }
118         
119         
120         $content->HTTP_HOST = $http_host;
121         
122         
123         
124         
125         // this should be done by having multiple template sources...!!!
126         
127         require_once 'HTML/Template/Flexy.php';
128         
129         $tmp_opts = array(
130            // 'forceCompile' => true,
131             'site_prefix' => false,
132         );
133         if (!empty($this->templateDir)) {
134             $tmp_opts['templateDir'] = $this->templateDir;
135         }
136         $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
137         if (!empty($fopts['DB_DataObject_translator'])) {
138             $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
139         }
140         if (!empty($fopts['locale'])) {
141             $tmp_opts['locale'] = $fopts['locale'];
142         }
143         
144         // local opt's overwrite
145         if (!empty($this->locale)) {
146             $tmp_opts['locale'] = $this->locale;
147         }
148         
149         $htmlbody = false;
150         $html_tmp_opts = $tmp_opts;
151         $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
152         if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
153             // then we have a multi-part email...
154             
155             if (!empty($this->html_locale)) {
156                 $html_tmp_opts['locale'] = $this->html_locale;
157             }
158             $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
159             
160             $htmltemplate->compile('mail/'. $templateFile.'.body.html');
161             $htmlbody =  $htmltemplate->bufferedOutputObject($content);
162             
163             $this->htmlbody = $htmlbody;
164             
165             // for the html body, we may want to convert the attachments to images.
166 //            var_dump($htmlbody);exit;
167             if ($this->replaceImages) {
168                 $htmlbody = $this->htmlbodytoCID($htmlbody);    
169             }
170             if ($this->css_embed) {
171                 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);    
172               
173             }
174         }
175         $tmp_opts['nonHTML'] = true;
176         
177         
178         //print_R($tmp_opts);
179         // $tmp_opts['force'] = true;
180         $template = new HTML_Template_Flexy(  $tmp_opts );
181         
182         $template->compile('mail/'. $templateFile.'.txt');
183         
184         /* use variables from this object to ouput data. */
185         $mailtext = $template->bufferedOutputObject($content);
186         //print_r($mailtext);exit;
187        
188         
189         
190         //echo "<PRE>";print_R($mailtext);
191         
192         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
193         require_once 'Mail/mimeDecode.php';
194         require_once 'Mail.php';
195         
196         $decoder = new Mail_mimeDecode($mailtext);
197         $parts = $decoder->getSendArray();
198         if (PEAR::isError($parts)) {
199             return $parts;
200             //echo "PROBLEM: {$parts->message}";
201             //exit;
202         } 
203         
204         $isMime = false;
205         
206         require_once 'Mail/mime.php';
207         $mime = new Mail_mime(array(
208             'eol' => "\n",
209             //'html_encoding' => 'base64',
210             'html_charset' => 'utf-8',
211             'text_charset' => 'utf-8',
212             'head_charset' => 'utf-8',
213         ));
214         // clean up the headers...
215         
216         
217         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
218                                      '@' . $content->HTTP_HOST .'>';
219         
220           
221         if ($htmlbody !== false) {
222             // got a html headers...
223             
224             if (isset($parts[1]['Content-Type'])) {
225                 unset($parts[1]['Content-Type']);
226             }
227             $mime->setTXTBody($parts[2]);
228             $mime->setHTMLBody($htmlbody);
229 //            var_dump($mime);exit;
230             foreach($this->images as $cid=>$cdata) { 
231             
232                 $mime->addHTMLImage(
233                     $cdata['file'],
234                      $cdata['mimetype'],
235                      $cid.'.'.$cdata['ext'],
236                     true,
237                     $cdata['contentid']
238                 );
239             }
240             $isMime = true;
241         }
242         
243         if(!empty($this->attachments)){
244             //if got a attachments
245             $header = $mime->headers($parts[1]);
246             
247             if (isset($parts[1]['Content-Type'])) {
248                 unset($parts[1]['Content-Type']);
249             }
250             
251             if (!$isMime) {
252             
253                 if(preg_match('/text\/html/', $header['Content-Type'])){
254                     $mime->setHTMLBody($parts[2]);
255                     $mime->setTXTBody('This message is in HTML only');
256                 }else{
257                     $mime->setTXTBody($parts[2]);
258                     $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
259                 }
260             }
261             foreach($this->attachments as $attch){
262                 $mime->addAttachment(
263                         $attch['file'],
264                         $attch['mimetype'],
265                         (!empty($attch['name'])) ? $attch['name'] : '',
266                         true
267                 );
268             }
269             
270             $isMime = true;
271         }
272         
273         if($isMime){
274             $parts[2] = $mime->get();
275             $parts[1] = $mime->headers($parts[1]);
276         }
277         $ret = array(
278             'recipents' => $parts[0],
279             'headers' => $parts[1],
280             'body' => $parts[2],
281             'mailer' => $this
282         );
283         if (isset($))
284         return $ret;;
285     }
286     function send($email = false)
287     {
288         
289         $pg = HTML_FlexyFramework::get()->page;
290         
291         
292         $email = is_array($email)  ? $email : $this->toData();
293         if (is_a($email, 'PEAR_Error')) {
294             $pg->addEvent("COREMAILER-FAIL",  false, "email toData failed"); 
295       
296             
297             return $email;
298         }
299         
300         //$this->log( htmlspecialchars(print_r($email,true)));
301         
302         ///$recipents = array($this->email);
303         $mailOptions = PEAR::getStaticProperty('Mail','options');
304         //print_R($mailOptions);exit;
305         
306         if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
307             $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
308             
309         }
310         
311         $mail = Mail::factory($this->mail_method,$mailOptions);
312         if ($this->debug) {
313             $mail->debug = (bool) $this->debug;
314         }
315         
316         $email['headers']['Date'] = date('r'); 
317         if (PEAR::isError($mail)) {
318             $pg->addEvent("COREMAILER-FAIL",  false, "mail factory failed"); 
319       
320             
321             return $mail;
322         } 
323         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
324         
325         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
326             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
327         }
328         
329         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
330         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
331         error_reporting($oe);
332         if ($ret === true) { 
333             $pg->addEvent("COREMAILER-SENT",  false,
334                 'To: ' .  ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
335                 'Subject: '  . @$email['headers']['Subject']
336             ); 
337         }  else {
338             $pg->addEvent("COREMAILER-FAIL",  false, $ret->toString());
339         }
340         
341         return $ret;
342     }
343     
344     function htmlbodytoCID($html)
345     {
346         $dom = new DOMDocument();
347         // this may raise parse errors as some html may be a component..
348         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
349         $imgs= $dom->getElementsByTagName('img');
350         
351         foreach ($imgs as $i=>$img) {
352             $url  = $img->getAttribute('src');
353             if (preg_match('#^cid:#', $url)) {
354                 continue;
355             }
356             $me = $img->getAttribute('mailembed');
357             if ($me == 'no') {
358                 continue;
359             }
360             
361             $conv = $this->fetchImage($url);
362             $this->images[$conv['contentid']] = $conv;
363             
364             $img->setAttribute('src', 'cid:' . $conv['contentid']);
365             
366             
367         }
368         return $dom->saveHTML();
369         
370         
371         
372     }
373     function htmlbodyCssEmbed($html)
374     {
375         $ff = HTML_FlexyFramework::get();
376         $dom = new DOMDocument();
377         
378         // this may raise parse errors as some html may be a component..
379         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
380         $links = $dom->getElementsByTagName('link');
381         $lc = array();
382         foreach ($links as $link) {  // duplicate as links is dynamic and we change it..!
383             $lc[] = $link;
384         }
385         //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
386         
387         foreach ($lc as $i=>$link) {
388             //var_dump($link->getAttribute('href'));
389             
390             if ($link->getAttribute('rel') != 'stylesheet') {
391                 continue;
392             }
393             $url  = $link->getAttribute('href');
394             $file = $ff->rootDir . $url;
395             
396             if (!preg_match('#^(http|https)://#', $url)) {
397                 $file = $ff->rootDir . $url;
398
399                 if (!file_exists($file)) {
400                     echo $file;
401                     $link->setAttribute('href', 'missing:' . $file);
402                     continue;
403                 }
404             } else {
405                $file = $this->mapurl($url);  
406             }
407             
408             $par = $link->parentNode;
409             $par->removeChild($link);
410             $s = $dom->createElement('style');
411             $e = $dom->createTextNode(file_get_contents($file));
412             $s->appendChild($e);
413             $par->appendChild($s);
414             
415         }
416         return $dom->saveHTML();
417         
418         
419     }
420     
421     
422     
423     function fetchImage($url)
424     {
425         
426         
427         $this->log( "FETCH : $url\n");
428         
429         if ($url[0] == '/') {
430             $ff = HTML_FlexyFramework::get();
431             $file = $ff->rootDir . $url;
432             require_once 'File/MimeType.php';
433             $m  = new File_MimeType();
434             $mt = $m->fromFilename($file);
435             $ext = $m->toExt($mt); 
436             
437             return array(
438                     'mimetype' => $mt,
439                    'ext' => $ext,
440                    'contentid' => md5($file),
441                    'file' => $file
442             );
443             
444             
445             
446         }
447         
448         //print_R($url); exit;
449         
450         
451         if (preg_match('#^file:///#', $url)) {
452             $file = preg_replace('#^file://#', '', $url);
453             require_once 'File/MimeType.php';
454             $m  = new File_MimeType();
455             $mt = $m->fromFilename($file);
456             $ext = $m->toExt($mt); 
457             
458             return array(
459                 'mimetype'  => $mt,
460                 'ext'       =>   $ext,
461                 'contentid' => md5($file),
462                 'file'      => $file
463             );
464             
465         }
466         
467         // CACHE???
468         // 2 files --- the info file.. and the actual file...
469         // add user
470         // unix only...
471         $uinfo = posix_getpwuid( posix_getuid () ); 
472         $user = $uinfo['name']; 
473         
474         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
475         if ($this->cache_images &&
476                 file_exists($cache) &&
477                 filemtime($cache) > strtotime('NOW - 1 WEEK')
478             ) {
479             $ret =  json_decode(file_get_contents($cache), true);
480             $this->log("fetched from cache");
481             $ret['file'] = $cache . '.data';
482             return $ret;
483         }
484         if (!file_exists(dirname($cache))) {
485             mkdir(dirname($cache),0700, true);
486         }
487         
488         require_once 'HTTP/Request.php';
489         $a = new HTTP_Request($this->mapurl($url));
490         $a->sendRequest();
491         $data = $a->getResponseBody();
492         
493         $this->log("got file of size " . strlen($data));
494         $this->log("save contentid " . md5($url));
495         
496         file_put_contents($cache .'.data', $data);
497         
498         
499         $mt = $a->getResponseHeader('Content-Type');
500         
501         require_once 'File/MimeType.php';
502         $m  = new File_MimeType();
503         $ext = $m->toExt($mt);
504         
505         $ret = array(
506             'mimetype' => $mt,
507             'ext' => $ext,
508             'contentid' => md5($url)
509             
510         );
511         
512         file_put_contents($cache, json_encode($ret));
513         $ret['file'] = $cache . '.data';
514         return $ret;
515     }  
516     
517     function mapurl($in)
518     {
519         
520         foreach($this->urlmap as $o=>$n) {
521             if (strpos($in,$o) === 0) {
522                 $ret =$n . substr($in,strlen($o));
523                 $this->log("mapURL in $in = $ret");
524                 return $ret;
525             }
526         }
527         $this->log("mapurl no change - $in");
528         return $in;
529          
530         
531     }
532     
533     function log($val)
534     {
535         if (!$this->debug) {
536             return;
537         }
538         if ($this->debug < 2) {
539             echo '<PRE>' . $val. "\n";
540             return;
541         }
542         $fh = fopen('/tmp/core_mailer.log', 'a');
543         fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");
544         fclose($fh);
545         
546         
547     }
548     
549 }