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     
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         if (!empty($this->templateDir)) {
96             $tmp_opts['templateDir'] = $this->templateDir;
97         }
98         
99         
100         $htmlbody = false;
101         $htmltemplate = new HTML_Template_Flexy( $tmp_opts );
102
103         if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
104             // then we have a multi-part email...
105             
106             
107             $htmltemplate->compile('mail/'. $templateFile.'.body.html');
108             $htmlbody =  $htmltemplate->bufferedOutputObject($content);
109             
110             // for the html body, we may want to convert the attachments to images.
111             
112             $htmlbody = $this->htmlbodytoCID($htmlbody);
113             
114               
115         }
116         
117         $tmp_opts['nonHTML'] = true;
118         
119         $template = new HTML_Template_Flexy(  $tmp_opts );
120         
121         $template->compile('mail/'. $templateFile.'.txt');
122         
123         /* use variables from this object to ouput data. */
124         $mailtext = $template->bufferedOutputObject($content);
125         
126         
127         
128         
129         
130         
131         
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             
162             $mime->setTXTBody($parts[2]);
163             $mime->setHTMLBody($htmlbody);
164             
165             foreach($this->images as $cid=>$cdata) { 
166             
167                 $mime->addHTMLImage(
168                     $cdata['file'],
169                      $cdata['mimetype'],
170                      $cid.'.'.$cdata['ext'],
171                     true,
172                     $cdata['contentid']
173                 );
174             }
175             print_r($parts);exit;
176             $parts[2] = $mime->get();
177             $parts[1] = $mime->headers($parts[1]);
178         
179         }
180         
181         //print_r($parts);exit;
182         
183        // list($recipents,$headers,$body) = $parts;
184         return array(
185             'recipents' => $parts[0],
186             'headers' => $parts[1],
187             'body' => $parts[2]
188         );
189     }
190     function send()
191     {
192         
193         $email = $this->toData();
194         if (is_a($email, 'PEAR_Error')) {
195             return $email;
196         }
197         ///$recipents = array($this->email);
198         $mailOptions = PEAR::getStaticProperty('Mail','options');
199         //print_R($mailOptions);exit;
200         $mail = Mail::factory("SMTP",$mailOptions);
201         $headers['Date'] = date('r'); 
202         if (PEAR::isError($mail)) {
203             return $mail;
204         } 
205         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
206         
207         if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
208             $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
209         }
210         
211         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
212         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
213         error_reporting($oe);
214        
215         return $ret;
216     }
217     
218     function htmlbodytoCID($html)
219     {
220         $dom = new DOMDocument;
221         $dom->loadHTML($html);
222         $imgs= $dom->getElementsByTagName('img');
223         
224         foreach ($imgs as $i=>$img) {
225             $url  = $img->getAttribute('src');
226             $conv = $this->fetchImage($url);
227             $this->images[$conv['contentid']] = $conv;
228             
229             $img->setAttribute('src', 'cid:' . $conv['contentid']);
230             
231             
232         }
233         return $dom->saveHTML();
234         
235         
236         
237     }
238     function fetchImage($url)
239     {
240         
241         if ($url[0] == '/') {
242             $file = $this->page->rootDir . $url;
243             require_once 'File/MimeType.php';
244             $m  = new File_MimeType();
245             $mt = $m->fromFilename($file);
246             $ext = $m->toExt($mt); 
247             
248             return array(
249                     'mimetype' => $mt,
250                    'ext' => $ext,
251                    'contentid' => md5($file),
252                    'file' => $file
253             );
254             
255             
256             
257         }
258         
259         //print_R($url); exit;
260         
261         
262         if (preg_match('#^file:///#', $url)) {
263             $file = preg_replace('#^file://#', '', $url);
264             require_once 'File/MimeType.php';
265             $m  = new File_MimeType();
266             $mt = $m->fromFilename($file);
267             $ext = $m->toExt($mt); 
268             
269             return array(
270                     'mimetype' => $mt,
271                    'ext' => $ext,
272                    'contentid' => md5($file),
273                    'file' => $file
274             );
275             
276         }
277         
278         // CACHE???
279         // 2 files --- the info file.. and the actual file...
280         $cache = ini_get('session.save_path').'/Pman_Core_Mailer/' . md5($url);
281         if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
282             $ret =  json_decode($cache);
283             $ret['file'] = $cache . '.data';
284             return $ret;
285         }
286         if (!file_exists(dirname($cache))) {
287             mkdir(dirname($cache),0666, true);
288         }
289         
290         require_once 'HTTP/Request.php';
291         $a = new HTTP_Request($url);
292         $a->sendRequest();
293         file_put_contents($cache .'.data', $a->getResponseBody());
294         
295         $mt = $a->getResponseHeader('Content-Type');
296         
297         require_once 'File/MimeType.php';
298         $m  = new File_MimeType();
299         $ext = $m->toExt($mt);
300         
301         $ret = array(
302             'mimetype' => $mt,
303             'ext' => $ext,
304             'contentid' => md5($url)
305             
306         );
307         
308         file_put_contents($cache, json_encode($ret));
309         $ret['file'] = $cache . '.data';
310         return $ret;
311     }  
312     
313     
314     
315 }