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