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