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