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