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