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