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