Mailer.php
[Pman.Core] / Mailer.php
1 <?php
2
3 /**
4  *
5  *  code that used to be in Pman (sendTemplate / emailTemplate)
6  *
7  *  usage:
8  *
9  *
10  *  $x= new Pman_Core_Mailer($opts)
11  *
12  *  $opts[
13        page => 
14        contents
15        template
16        replaceImages => true|false
17     ]
18  *
19  *  $x->asData(); // returns data needed for notify?? - notify should really
20  *                  // just use this to pass around later..
21  *
22  *  $x->send();
23  *
24  */
25
26 class Pman_Core_Mailer {
27     
28     var $page           = false; /* usually a html_flexyframework_page */
29     var $contents       = false; /* object or array */
30     var $template       = false; /* string */
31     var $replaceImages  = false; /* boolean */
32     
33     
34     var $images         = array(); // generated list of cid images for sending
35     
36     
37     function Pman_Core_Mailer($args) {
38         foreach($args as $k=>$v) {
39             // a bit trusting..
40             $this->$k =  $v;
41         }
42     }
43      
44     /**
45      * ---------------- Global Tools ---------------   
46      */
47     
48     function toData()
49     {
50     
51         $templateFile = $this->template;
52         $args = $this->contents;
53         
54         $content  = clone($page);
55         
56         foreach((array)$args as $k=>$v) {
57             $content->$k = $v;
58         }
59         
60         $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
61         
62         $ff = HTML_FlexyFramework::get();
63         $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
64         if (isset($ff->Pman['HTTP_HOST'])) {
65             $http_host  = $ff->Pman['HTTP_HOST'];
66         }
67         
68         
69         $content->HTTP_HOST = $http_host;
70         
71         
72         
73         // this should be done by having multiple template sources...!!!
74         
75         require_once 'HTML/Template/Flexy.php';
76         
77         $htmlbody = false;
78         
79         if (is_string($template->resolvePath('mail/'.$template.'.body.html')) ) {
80             // then we have a multi-part email...
81             
82             
83             $htmltemplate = new HTML_Template_Flexy(  );
84             $htmltemplate->compile('mail/'. $templateFile.'.body.html');
85             $htmlbody =  $template->bufferedOutputObject($content);
86             
87             // for the html body, we may want to convert the attachments to images.
88             
89             $this->htmlbodytoCID($htmlbody);
90             
91              
92         }
93         
94         
95         
96         $template = new HTML_Template_Flexy( array(
97                 'nonHTML' => true,
98         ));
99         
100         $template->compile('mail/'. $templateFile.'.txt');
101         
102         /* use variables from this object to ouput data. */
103         $mailtext = $template->bufferedOutputObject($content);
104         
105         
106         
107         
108         
109         
110         
111         
112         
113         
114         //echo "<PRE>";print_R($mailtext);
115         
116         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
117         require_once 'Mail/mimeDecode.php';
118         require_once 'Mail.php';
119         
120         $decoder = new Mail_mimeDecode($mailtext);
121         $parts = $decoder->getSendArray();
122         if (PEAR::isError($parts)) {
123             return $parts;
124             //echo "PROBLEM: {$parts->message}";
125             //exit;
126         } 
127         
128         
129         
130         
131         $parts[1]['Message-Id'] = '<' .   $content->msgid   .
132                                      '@' . $content->HTTP_HOST .'>';
133         
134         
135         
136         
137         if ($htmlbody !== false) {
138             require_once 'Mail/mime.php';
139             $mime = new Mail_mime(array('eol' => "\n"));
140             
141             $mime->setTXTBody($parts[2]);
142             $mime->setHTMLBody($htmlbody);
143             
144             foreach($this->images as $cid=>$cdata) { 
145             
146                 $mime->addAttachment(
147                     $cdata['file'],
148                     $cdata['mimetype'],
149                     $name        = $cid.'.'.$cdata['ext'],
150                     $isfile      = true,
151                     $encoding    = 'base64',
152                     $disposition = 'attachment',
153                     $charset     = '',
154                     $language    = '',
155                     $location    = '',
156                     $n_encoding  = null,
157                     $f_encoding  = null,
158                     $description = '',
159                     $h_charset   = null
160             }
161             $parts[2] = $mime->get();
162             $parts[1] = $mime->headers($parts[1]);
163         
164
165         
166         
167         
168         
169         
170         
171        // list($recipents,$headers,$body) = $parts;
172         return array(
173             'recipents' => $parts[0],
174             'headers' => $parts[1],
175             'body' => $parts[2]
176         );
177     }
178     function send()
179     {
180         
181         $email = $this->toData();
182         if (is_a($email, 'PEAR_Error')) {
183             return $email;
184         }
185         ///$recipents = array($this->email);
186         $mailOptions = PEAR::getStaticProperty('Mail','options');
187         $mail = Mail::factory("SMTP",$mailOptions);
188         $headers['Date'] = date('r');
189         if (PEAR::isError($mail)) {
190             return $mail;
191         } 
192         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
193         $ret = $mail->send($email['recipents'],$email['headers'],$email['body']);
194         error_reporting($oe);
195        
196         return $ret;
197     }
198     
199     function htmlbodytoCID($html)
200     {
201         $dom = new DOMDocument;
202         $dom->loadHTML($html);
203         $imgs= $dom->getElementsByTagName('img');
204         
205         foreach ($imgs as $i=>$img) {
206             $url  = $dom->getAttribute('src');
207             $conv = $this->fetchImage($url);
208             $this->images[$conv['contentid']] = $conv;
209             
210             $url->setAttribute('src', 'cid:' . $conv['contentid']);
211             
212             
213         }
214         return $dom->saveHTML();
215         
216         
217         
218     }
219     function fetchImage($url)
220     {
221         // CACHE???
222         // 2 files --- the info file.. and the actual file...
223         $cache = ini_get('session.save_path').'/Pman_Core_Mailer/' . md5($url);
224         if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
225             $ret =  json_decode($cache);
226             $ret['file'] = $cache . '.data';
227             return $ret;
228         }
229         if (!file_exists(dirname($cache))) {
230             mkdir(dirname($cache),0666, true);
231         }
232         
233         
234         $a = &new HTTP_Request($url);
235         $a->sendRequest();
236         file_put_contents($cache .'.data', base64_encode( $a->getResponseBody()));
237         
238         $mt = $a->getResponseHeader('Content-Type');
239         
240         require_once 'File/MimeType.php';
241         $m  = new File_MimeType();
242         $ext = $m->toExt($mt);
243         
244         $ret = array(
245             'mimetype' => $mt,
246             'ext' => $ext,
247             'contentid' => md5($url)
248             
249         );
250         
251         file_put_contents($cache, json_encode($ret));
252          $ret['file'] = $cache . '.data';
253         return $ret;
254         
255     
256     
257     
258 }