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