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