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