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