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         
107         $htmlbody = false;
108         $htmltemplate = new HTML_Template_Flexy( $tmp_opts );
109
110         if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
111             // then we have a multi-part email...
112             
113             
114             $htmltemplate->compile('mail/'. $templateFile.'.body.html');
115             $htmlbody =  $htmltemplate->bufferedOutputObject($content);
116             
117             // for the html body, we may want to convert the attachments to images.
118 //            var_dump($htmlbody);exit;
119             $htmlbody = $this->htmlbodytoCID($htmlbody);
120             
121               
122         }
123         $tmp_opts['nonHTML'] = true;
124         // $tmp_opts['force'] = true;
125         $template = new HTML_Template_Flexy(  $tmp_opts );
126         
127         $template->compile('mail/'. $templateFile.'.txt');
128         
129         /* use variables from this object to ouput data. */
130         $mailtext = $template->bufferedOutputObject($content);
131         //print_r($mailtext);exit;
132        
133         
134         
135         //echo "<PRE>";print_R($mailtext);
136         
137         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
138         require_once 'Mail/mimeDecode.php';
139         require_once 'Mail.php';
140         
141         $decoder = new Mail_mimeDecode($mailtext);
142         $parts = $decoder->getSendArray();
143         if (PEAR::isError($parts)) {
144             return $parts;
145             //echo "PROBLEM: {$parts->message}";
146             //exit;
147         } 
148         
149         
150         
151         
152         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
153                                      '@' . $content->HTTP_HOST .'>';
154         
155         
156         
157         
158         if ($htmlbody !== false) {
159             require_once 'Mail/mime.php';
160             $mime = new Mail_mime(array('eol' => "\n",
161 //                                    'html_encoding' => 'base64',
162                                     'html_charset' => 'utf-8',
163                                     'text_charset' => 'utf-8',
164                                     'head_charset' => 'utf-8'
165                 ));
166             
167             $mime->setTXTBody($parts[2]);
168             $mime->setHTMLBody($htmlbody);
169 //            var_dump($mime);exit;
170             foreach($this->images as $cid=>$cdata) { 
171             
172                 $mime->addHTMLImage(
173                     $cdata['file'],
174                      $cdata['mimetype'],
175                      $cid.'.'.$cdata['ext'],
176                     true,
177                     $cdata['contentid']
178                 );
179             }
180             $parts[2] = $mime->get();
181             $parts[1] = $mime->headers($parts[1]);
182         
183         }
184         
185        // list($recipents,$headers,$body) = $parts;
186         return array(
187             'recipents' => $parts[0],
188             'headers' => $parts[1],
189             'body' => $parts[2]
190         );
191     }
192     function send()
193     {
194         
195         $email = $this->toData();
196         if (is_a($email, 'PEAR_Error')) {
197             return $email;
198         }
199         if ($this->debug) {
200             echo '<PRE>';echo htmlspecialchars(print_r($email,true));
201         }
202         ///$recipents = array($this->email);
203         $mailOptions = PEAR::getStaticProperty('Mail','options');
204         //print_R($mailOptions);exit;
205         $mail = Mail::factory("SMTP",$mailOptions);
206         $headers['Date'] = date('r'); 
207         if (PEAR::isError($mail)) {
208             return $mail;
209         } 
210         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
211         
212         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
213             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
214         }
215         
216         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
217         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
218         error_reporting($oe);
219        
220         return $ret;
221     }
222     
223     function htmlbodytoCID($html)
224     {
225         $dom = new DOMDocument;
226         $dom->loadHTML('<?xml encoding="UTF-8">' .$html);
227         $imgs= $dom->getElementsByTagName('img');
228         
229         foreach ($imgs as $i=>$img) {
230             $url  = $img->getAttribute('src');
231             $conv = $this->fetchImage($url);
232             $this->images[$conv['contentid']] = $conv;
233             
234             $img->setAttribute('src', 'cid:' . $conv['contentid']);
235             
236             
237         }
238         return $dom->saveHTML();
239         
240         
241         
242     }
243     function fetchImage($url)
244     {
245         
246         if ($url[0] == '/') {
247             $ff = HTML_FlexyFramework::get();
248             $file = $ff->rootDir . $url;
249             require_once 'File/MimeType.php';
250             $m  = new File_MimeType();
251             $mt = $m->fromFilename($file);
252             $ext = $m->toExt($mt); 
253             
254             return array(
255                     'mimetype' => $mt,
256                    'ext' => $ext,
257                    'contentid' => md5($file),
258                    'file' => $file
259             );
260             
261             
262             
263         }
264         
265         //print_R($url); exit;
266         
267         
268         if (preg_match('#^file:///#', $url)) {
269             $file = preg_replace('#^file://#', '', $url);
270             require_once 'File/MimeType.php';
271             $m  = new File_MimeType();
272             $mt = $m->fromFilename($file);
273             $ext = $m->toExt($mt); 
274             
275             return array(
276                     'mimetype' => $mt,
277                    'ext' => $ext,
278                    'contentid' => md5($file),
279                    'file' => $file
280             );
281             
282         }
283         
284         // CACHE???
285         // 2 files --- the info file.. and the actual file...
286         // add user
287         // unix only...
288         $uinfo = posix_getpwuid( posix_getuid () ); 
289         $user = $uinfo['name']; 
290         
291         $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
292         if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
293             $ret =  json_decode($cache);
294             $ret['file'] = $cache . '.data';
295             return $ret;
296         }
297         if (!file_exists(dirname($cache))) {
298             mkdir(dirname($cache),0700, true);
299         }
300         
301         require_once 'HTTP/Request.php';
302         $a = new HTTP_Request($url);
303         $a->sendRequest();
304         file_put_contents($cache .'.data', $a->getResponseBody());
305         
306         $mt = $a->getResponseHeader('Content-Type');
307         
308         require_once 'File/MimeType.php';
309         $m  = new File_MimeType();
310         $ext = $m->toExt($mt);
311         
312         $ret = array(
313             'mimetype' => $mt,
314             'ext' => $ext,
315             'contentid' => md5($url)
316             
317         );
318         
319         file_put_contents($cache, json_encode($ret));
320         $ret['file'] = $cache . '.data';
321         return $ret;
322     }  
323     
324     
325     
326 }