DataObjects/Core_watch.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     
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         $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
199         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
200         $ret = $mail->send($rcpts,$email['headers'],$email['body']);
201         error_reporting($oe);
202        
203         return $ret;
204     }
205     
206     function htmlbodytoCID($html)
207     {
208         $dom = new DOMDocument;
209         $dom->loadHTML($html);
210         $imgs= $dom->getElementsByTagName('img');
211         
212         foreach ($imgs as $i=>$img) {
213             $url  = $img->getAttribute('src');
214             $conv = $this->fetchImage($url);
215             $this->images[$conv['contentid']] = $conv;
216             
217             $img->setAttribute('src', 'cid:' . $conv['contentid']);
218             
219             
220         }
221         return $dom->saveHTML();
222         
223         
224         
225     }
226     function fetchImage($url)
227     {
228         
229         if ($url[0] == '/') {
230             $file = $this->page->rootDir . $url;
231             require_once 'File/MimeType.php';
232             $m  = new File_MimeType();
233             $mt = $m->fromFilename($file);
234             $ext = $m->toExt($mt); 
235             
236             return array(
237                     'mimetype' => $mt,
238                    'ext' => $ext,
239                    'contentid' => md5($file),
240                    'file' => $file
241             );
242             
243             
244             
245         }
246         
247         //print_R($url); exit;
248         
249         
250         if (preg_match('#^file:///#', $url)) {
251             $file = preg_replace('#^file://#', '', $url);
252             require_once 'File/MimeType.php';
253             $m  = new File_MimeType();
254             $mt = $m->fromFilename($file);
255             $ext = $m->toExt($mt); 
256             
257             return array(
258                     'mimetype' => $mt,
259                    'ext' => $ext,
260                    'contentid' => md5($file),
261                    'file' => $file
262             );
263             
264         }
265         
266         // CACHE???
267         // 2 files --- the info file.. and the actual file...
268         $cache = ini_get('session.save_path').'/Pman_Core_Mailer/' . md5($url);
269         if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
270             $ret =  json_decode($cache);
271             $ret['file'] = $cache . '.data';
272             return $ret;
273         }
274         if (!file_exists(dirname($cache))) {
275             mkdir(dirname($cache),0666, true);
276         }
277         
278         require_once 'HTTP/Request.php';
279         $a = new HTTP_Request($url);
280         $a->sendRequest();
281         file_put_contents($cache .'.data', $a->getResponseBody());
282         
283         $mt = $a->getResponseHeader('Content-Type');
284         
285         require_once 'File/MimeType.php';
286         $m  = new File_MimeType();
287         $ext = $m->toExt($mt);
288         
289         $ret = array(
290             'mimetype' => $mt,
291             'ext' => $ext,
292             'contentid' => md5($url)
293             
294         );
295         
296         file_put_contents($cache, json_encode($ret));
297         $ret['file'] = $cache . '.data';
298         return $ret;
299     }  
300     
301     
302     
303 }