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