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     ]
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         //print_R($tmp_opts);
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         require_once 'Mail/mime.php';
163         $mime = new Mail_mime(array(
164             'eol' => "\n",
165             //'html_encoding' => 'base64',
166             'html_charset' => 'utf-8',
167             'text_charset' => 'utf-8',
168             'head_charset' => 'utf-8',
169         ));
170         // clean up the headers...
171         
172         
173         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
174                                      '@' . $content->HTTP_HOST .'>';
175         
176           
177         if ($htmlbody !== false) {
178             // got a html headers...
179             
180             if (isset($parts[1]['Content-Type'])) {
181                 unset($parts[1]['Content-Type']);
182             }
183             $mime->setTXTBody($parts[2]);
184             $mime->setHTMLBody($htmlbody);
185 //            var_dump($mime);exit;
186             foreach($this->images as $cid=>$cdata) { 
187             
188                 $mime->addHTMLImage(
189                     $cdata['file'],
190                      $cdata['mimetype'],
191                      $cid.'.'.$cdata['ext'],
192                     true,
193                     $cdata['contentid']
194                 );
195             }
196             $parts[2] = $mime->get();
197             $parts[1] = $mime->headers($parts[1]);
198         
199         }
200         
201        // list($recipents,$headers,$body) = $parts;
202         return array(
203             'recipents' => $parts[0],
204             'headers' => $parts[1],
205             'body' => $parts[2]
206         );
207     }
208     function send()
209     {
210         
211         $email = $this->toData();
212         if (is_a($email, 'PEAR_Error')) {
213             return $email;
214         }
215         if ($this->debug) {
216             echo '<PRE>';echo htmlspecialchars(print_r($email,true));
217         }
218         ///$recipents = array($this->email);
219         $mailOptions = PEAR::getStaticProperty('Mail','options');
220         //print_R($mailOptions);exit;
221         $mail = Mail::factory("SMTP",$mailOptions);
222         $headers['Date'] = date('r'); 
223         if (PEAR::isError($mail)) {
224             return $mail;
225         } 
226         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
227         
228         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
229             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
230         }
231         
232         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
233         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
234         error_reporting($oe);
235        
236         return $ret;
237     }
238     
239     function htmlbodytoCID($html)
240     {
241         $dom = new DOMDocument();
242         // this may raise parse errors as some html may be a component..
243         @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
244         $imgs= $dom->getElementsByTagName('img');
245         
246         foreach ($imgs as $i=>$img) {
247             $url  = $img->getAttribute('src');
248             $conv = $this->fetchImage($url);
249             $this->images[$conv['contentid']] = $conv;
250             
251             $img->setAttribute('src', 'cid:' . $conv['contentid']);
252             
253             
254         }
255         return $dom->saveHTML();
256         
257         
258         
259     }
260     function fetchImage($url)
261     {
262         
263         if ($url[0] == '/') {
264             $ff = HTML_FlexyFramework::get();
265             $file = $ff->rootDir . $url;
266             require_once 'File/MimeType.php';
267             $m  = new File_MimeType();
268             $mt = $m->fromFilename($file);
269             $ext = $m->toExt($mt); 
270             
271             return array(
272                     'mimetype' => $mt,
273                    'ext' => $ext,
274                    'contentid' => md5($file),
275                    'file' => $file
276             );
277             
278             
279             
280         }
281         
282         //print_R($url); exit;
283         
284         
285         if (preg_match('#^file:///#', $url)) {
286             $file = preg_replace('#^file://#', '', $url);
287             require_once 'File/MimeType.php';
288             $m  = new File_MimeType();
289             $mt = $m->fromFilename($file);
290             $ext = $m->toExt($mt); 
291             
292             return array(
293                 'mimetype'  => $mt,
294                 'ext'       =>   $ext,
295                 'contentid' => md5($file),
296                 'file'      => $file
297             );
298             
299         }
300         
301         // CACHE???
302         // 2 files --- the info file.. and the actual file...
303         // add user
304         // unix only...
305         $uinfo = posix_getpwuid( posix_getuid () ); 
306         $user = $uinfo['name']; 
307         
308         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
309         if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
310             $ret =  json_decode($cache);
311             $ret['file'] = $cache . '.data';
312             return $ret;
313         }
314         if (!file_exists(dirname($cache))) {
315             mkdir(dirname($cache),0700, true);
316         }
317         
318         require_once 'HTTP/Request.php';
319         $a = new HTTP_Request($url);
320         $a->sendRequest();
321         file_put_contents($cache .'.data', $a->getResponseBody());
322         
323         $mt = $a->getResponseHeader('Content-Type');
324         
325         require_once 'File/MimeType.php';
326         $m  = new File_MimeType();
327         $ext = $m->toExt($mt);
328         
329         $ret = array(
330             'mimetype' => $mt,
331             'ext' => $ext,
332             'contentid' => md5($url)
333             
334         );
335         
336         file_put_contents($cache, json_encode($ret));
337         $ret['file'] = $cache . '.data';
338         return $ret;
339     }  
340     
341     
342     
343 }