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