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