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