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