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        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             
155               
156         }
157         $tmp_opts['nonHTML'] = true;
158         
159         
160         //print_R($tmp_opts);
161         // $tmp_opts['force'] = true;
162         $template = new HTML_Template_Flexy(  $tmp_opts );
163         
164         $template->compile('mail/'. $templateFile.'.txt');
165         
166         /* use variables from this object to ouput data. */
167         $mailtext = $template->bufferedOutputObject($content);
168         //print_r($mailtext);exit;
169        
170         
171         
172         //echo "<PRE>";print_R($mailtext);
173         
174         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
175         require_once 'Mail/mimeDecode.php';
176         require_once 'Mail.php';
177         
178         $decoder = new Mail_mimeDecode($mailtext);
179         $parts = $decoder->getSendArray();
180         if (PEAR::isError($parts)) {
181             return $parts;
182             //echo "PROBLEM: {$parts->message}";
183             //exit;
184         } 
185         
186         $isMime = false;
187         
188         require_once 'Mail/mime.php';
189         $mime = new Mail_mime(array(
190             'eol' => "\n",
191             //'html_encoding' => 'base64',
192             'html_charset' => 'utf-8',
193             'text_charset' => 'utf-8',
194             'head_charset' => 'utf-8',
195         ));
196         // clean up the headers...
197         
198         
199         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
200                                      '@' . $content->HTTP_HOST .'>';
201         
202           
203         if ($htmlbody !== false) {
204             // got a html headers...
205             
206             if (isset($parts[1]['Content-Type'])) {
207                 unset($parts[1]['Content-Type']);
208             }
209             $mime->setTXTBody($parts[2]);
210             $mime->setHTMLBody($htmlbody);
211 //            var_dump($mime);exit;
212             foreach($this->images as $cid=>$cdata) { 
213             
214                 $mime->addHTMLImage(
215                     $cdata['file'],
216                      $cdata['mimetype'],
217                      $cid.'.'.$cdata['ext'],
218                     true,
219                     $cdata['contentid']
220                 );
221             }
222             $isMime = true;
223         }
224         
225         if(!empty($this->attachments)){
226             //if got a attachments
227             $header = $mime->headers($parts[1]);
228             
229             if (isset($parts[1]['Content-Type'])) {
230                 unset($parts[1]['Content-Type']);
231             }
232             
233             if (!$isMime) {
234             
235                 if(preg_match('/text\/html/', $header['Content-Type'])){
236                     $mime->setHTMLBody($parts[2]);
237                     $mime->setTXTBody('This message is in HTML only');
238                 }else{
239                     $mime->setTXTBody($parts[2]);
240                     $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
241                 }
242             }
243             foreach($this->attachments as $attch){
244                 $mime->addAttachment(
245                         $attch['file'],
246                         $attch['mimetype'],
247                         (!empty($attch['name'])) ? $attch['name'] : '',
248                         true
249                 );
250             }
251             
252             $isMime = true;
253         }
254         
255         if($isMime){
256             $parts[2] = $mime->get();
257             $parts[1] = $mime->headers($parts[1]);
258         }
259 //        echo '<PRE>';
260 //        print_r('parts');
261 //        print_r($parts[2]);
262 //        exit;
263        // list($recipents,$headers,$body) = $parts;
264         return array(
265             'recipents' => $parts[0],
266             'headers' => $parts[1],
267             'body' => $parts[2],
268             'mailer' => $this
269         );
270     }
271     function send($email = false)
272     {
273         
274         $pg = HTML_FlexyFramework::get()->page;
275         
276         
277         $email = is_array($email)  ? $email : $this->toData();
278         if (is_a($email, 'PEAR_Error')) {
279             $pg->addEvent("COREMAILER-FAIL",  false, "email toData failed"); 
280       
281             
282             return $email;
283         }
284         if ($this->debug) {
285             echo '<PRE>';echo htmlspecialchars(print_r($email,true));
286         }
287         ///$recipents = array($this->email);
288         $mailOptions = PEAR::getStaticProperty('Mail','options');
289         //print_R($mailOptions);exit;
290         
291         if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
292             $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
293             
294         }
295         
296         $mail = Mail::factory($this->mail_method,$mailOptions);
297         if ($this->debug) {
298             $mail->debug = $this->debug;
299         }
300         
301         $email['headers']['Date'] = date('r'); 
302         if (PEAR::isError($mail)) {
303             $pg->addEvent("COREMAILER-FAIL",  false, "mail factory failed"); 
304       
305             
306             return $mail;
307         } 
308         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
309         
310         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
311             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
312         }
313         
314         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
315         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
316         error_reporting($oe);
317         if ($ret === true) { 
318             $pg->addEvent("COREMAILER-SENT",  false,
319                 'To: ' .  ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
320                 'Subject: '  . @$email['headers']['Subject']
321             ); 
322         }  else {
323             $pg->addEvent("COREMAILER-FAIL",  false, $ret->toString());
324         }
325         
326         return $ret;
327     }
328     
329     function htmlbodytoCID($html)
330     {
331         $dom = new DOMDocument();
332         // this may raise parse errors as some html may be a component..
333         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
334         $imgs= $dom->getElementsByTagName('img');
335         
336         foreach ($imgs as $i=>$img) {
337             $url  = $img->getAttribute('src');
338             if (preg_match('#^cid:#', $url)) {
339                 continue;
340             }
341             $conv = $this->fetchImage($url);
342             $this->images[$conv['contentid']] = $conv;
343             
344             $img->setAttribute('src', 'cid:' . $conv['contentid']);
345             
346             
347         }
348         return $dom->saveHTML();
349         
350         
351         
352     }
353     function fetchImage($url)
354     {
355         
356         if ($url[0] == '/') {
357             $ff = HTML_FlexyFramework::get();
358             $file = $ff->rootDir . $url;
359             require_once 'File/MimeType.php';
360             $m  = new File_MimeType();
361             $mt = $m->fromFilename($file);
362             $ext = $m->toExt($mt); 
363             
364             return array(
365                     'mimetype' => $mt,
366                    'ext' => $ext,
367                    'contentid' => md5($file),
368                    'file' => $file
369             );
370             
371             
372             
373         }
374         
375         //print_R($url); exit;
376         
377         
378         if (preg_match('#^file:///#', $url)) {
379             $file = preg_replace('#^file://#', '', $url);
380             require_once 'File/MimeType.php';
381             $m  = new File_MimeType();
382             $mt = $m->fromFilename($file);
383             $ext = $m->toExt($mt); 
384             
385             return array(
386                 'mimetype'  => $mt,
387                 'ext'       =>   $ext,
388                 'contentid' => md5($file),
389                 'file'      => $file
390             );
391             
392         }
393         
394         // CACHE???
395         // 2 files --- the info file.. and the actual file...
396         // add user
397         // unix only...
398         $uinfo = posix_getpwuid( posix_getuid () ); 
399         $user = $uinfo['name']; 
400         
401         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
402         if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
403             $ret =  json_decode(file_get_contents($cache), true);
404             $ret['file'] = $cache . '.data';
405             return $ret;
406         }
407         if (!file_exists(dirname($cache))) {
408             mkdir(dirname($cache),0700, true);
409         }
410         
411         require_once 'HTTP/Request.php';
412         $a = new HTTP_Request($url);
413         $a->sendRequest();
414         file_put_contents($cache .'.data', $a->getResponseBody());
415         
416         $mt = $a->getResponseHeader('Content-Type');
417         
418         require_once 'File/MimeType.php';
419         $m  = new File_MimeType();
420         $ext = $m->toExt($mt);
421         
422         $ret = array(
423             'mimetype' => $mt,
424             'ext' => $ext,
425             'contentid' => md5($url)
426             
427         );
428         
429         file_put_contents($cache, json_encode($ret));
430         $ret['file'] = $cache . '.data';
431         return $ret;
432     }  
433     
434     
435     
436 }