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