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