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