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