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