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