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