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