5 * code that used to be in Pman (sendTemplate / emailTemplate)
7 * template is in template directory subfolder 'mail'
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
17 * $x= new Pman_Core_Mailer($opts)
19 * $x= Pman_Core_Mailer(array(
23 html_locale => 'en' == always use the 'english translated verison'
24 replaceImages => true|false,
25 locale => 'en' .... or zh_hk....
26 rcpts => array() // override recipients..
30 name : (optional) - uses basename of file
34 mail_method : (SMTP or SMTPMX)
38 * recipents is gathered from the resulting template
46 * $x->toData(); // returns data needed for notify?? - notify should really
47 * // just use this to pass around later..
53 class Pman_Core_Mailer {
55 var $page = false; /* usually a html_flexyframework_page */
56 var $contents = false; /* object or array */
57 var $template = false; /* string */
58 var $replaceImages = false; /* boolean */
60 var $templateDir = false;
61 var $locale = false; // eg. 'en' or 'zh_HK'
64 var $html_locale = false; // eg. 'en' or 'zh_HK'
65 var $images = array(); // generated list of cid images for sending
66 var $attachments = false;
68 var $mail_method = 'SMTP';
70 function Pman_Core_Mailer($args) {
71 foreach($args as $k=>$v) {
78 * ---------------- Global Tools ---------------
84 $templateFile = $this->template;
85 $args = $this->contents;
87 $content = clone($this->page);
89 foreach((array)$args as $k=>$v) {
93 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
95 $ff = HTML_FlexyFramework::get();
96 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
97 if (isset($ff->Pman['HTTP_HOST'])) {
98 $http_host = $ff->Pman['HTTP_HOST'];
102 $content->HTTP_HOST = $http_host;
107 // this should be done by having multiple template sources...!!!
109 require_once 'HTML/Template/Flexy.php';
112 // 'forceCompile' => true,
113 'site_prefix' => false,
115 if (!empty($this->templateDir)) {
116 $tmp_opts['templateDir'] = $this->templateDir;
118 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
119 if (!empty($fopts['DB_DataObject_translator'])) {
120 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
122 if (!empty($fopts['locale'])) {
123 $tmp_opts['locale'] = $fopts['locale'];
126 // local opt's overwrite
127 if (!empty($this->locale)) {
128 $tmp_opts['locale'] = $this->locale;
132 $html_tmp_opts = $tmp_opts;
133 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
134 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
135 // then we have a multi-part email...
137 if (!empty($this->html_locale)) {
138 $html_tmp_opts['locale'] = $this->html_locale;
140 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
142 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
143 $htmlbody = $htmltemplate->bufferedOutputObject($content);
145 $this->htmlbody = $htmlbody;
147 // for the html body, we may want to convert the attachments to images.
148 // var_dump($htmlbody);exit;
149 if ($this->replaceImages) {
150 $htmlbody = $this->htmlbodytoCID($htmlbody);
155 $tmp_opts['nonHTML'] = true;
158 //print_R($tmp_opts);
159 // $tmp_opts['force'] = true;
160 $template = new HTML_Template_Flexy( $tmp_opts );
162 $template->compile('mail/'. $templateFile.'.txt');
164 /* use variables from this object to ouput data. */
165 $mailtext = $template->bufferedOutputObject($content);
166 //print_r($mailtext);exit;
170 //echo "<PRE>";print_R($mailtext);
172 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
173 require_once 'Mail/mimeDecode.php';
174 require_once 'Mail.php';
176 $decoder = new Mail_mimeDecode($mailtext);
177 $parts = $decoder->getSendArray();
178 if (PEAR::isError($parts)) {
180 //echo "PROBLEM: {$parts->message}";
186 require_once 'Mail/mime.php';
187 $mime = new Mail_mime(array(
189 //'html_encoding' => 'base64',
190 'html_charset' => 'utf-8',
191 'text_charset' => 'utf-8',
192 'head_charset' => 'utf-8',
194 // clean up the headers...
197 $parts[1]['Message-Id'] = '<' . $content->msgid .
198 '@' . $content->HTTP_HOST .'>';
201 if ($htmlbody !== false) {
202 // got a html headers...
204 if (isset($parts[1]['Content-Type'])) {
205 unset($parts[1]['Content-Type']);
207 $mime->setTXTBody($parts[2]);
208 $mime->setHTMLBody($htmlbody);
209 // var_dump($mime);exit;
210 foreach($this->images as $cid=>$cdata) {
215 $cid.'.'.$cdata['ext'],
223 if(!empty($this->attachments)){
224 //if got a attachments
225 $header = $mime->headers($parts[1]);
227 if (isset($parts[1]['Content-Type'])) {
228 unset($parts[1]['Content-Type']);
233 if(preg_match('/text\/html/', $header['Content-Type'])){
234 $mime->setHTMLBody($parts[2]);
235 $mime->setTXTBody('This message is in HTML only');
237 $mime->setTXTBody($parts[2]);
238 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
241 foreach($this->attachments as $attch){
242 $mime->addAttachment(
245 (!empty($attch['name'])) ? $attch['name'] : '',
254 $parts[2] = $mime->get();
255 $parts[1] = $mime->headers($parts[1]);
259 // print_r($parts[2]);
261 // list($recipents,$headers,$body) = $parts;
263 'recipents' => $parts[0],
264 'headers' => $parts[1],
269 function send($email = false)
272 $pg = HTML_FlexyFramework::get()->page;
275 $email = is_array($email) ? $email : $this->toData();
276 if (is_a($email, 'PEAR_Error')) {
277 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
283 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
285 ///$recipents = array($this->email);
286 $mailOptions = PEAR::getStaticProperty('Mail','options');
287 //print_R($mailOptions);exit;
289 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
290 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
294 $mail = Mail::factory($this->mail_method,$mailOptions);
296 $mail->debug = $this->debug;
299 $email['headers']['Date'] = date('r');
300 if (PEAR::isError($mail)) {
301 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
306 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
308 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
309 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
312 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
313 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
314 error_reporting($oe);
316 $pg->addEvent("COREMAILER-SENT", false,
317 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
318 'Subject: ' . @$email['headers']['Subject']
321 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
327 function htmlbodytoCID($html)
329 $dom = new DOMDocument();
330 // this may raise parse errors as some html may be a component..
331 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
332 $imgs= $dom->getElementsByTagName('img');
334 foreach ($imgs as $i=>$img) {
335 $url = $img->getAttribute('src');
336 if (preg_match('#^cid:#', $url)) {
339 $conv = $this->fetchImage($url);
340 $this->images[$conv['contentid']] = $conv;
342 $img->setAttribute('src', 'cid:' . $conv['contentid']);
346 return $dom->saveHTML();
351 function fetchImage($url)
354 if ($url[0] == '/') {
355 $ff = HTML_FlexyFramework::get();
356 $file = $ff->rootDir . $url;
357 require_once 'File/MimeType.php';
358 $m = new File_MimeType();
359 $mt = $m->fromFilename($file);
360 $ext = $m->toExt($mt);
365 'contentid' => md5($file),
373 //print_R($url); exit;
376 if (preg_match('#^file:///#', $url)) {
377 $file = preg_replace('#^file://#', '', $url);
378 require_once 'File/MimeType.php';
379 $m = new File_MimeType();
380 $mt = $m->fromFilename($file);
381 $ext = $m->toExt($mt);
386 'contentid' => md5($file),
393 // 2 files --- the info file.. and the actual file...
396 $uinfo = posix_getpwuid( posix_getuid () );
397 $user = $uinfo['name'];
399 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
400 if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
401 $ret = json_decode(file_get_contents($cache), true);
402 $ret['file'] = $cache . '.data';
405 if (!file_exists(dirname($cache))) {
406 mkdir(dirname($cache),0700, true);
409 require_once 'HTTP/Request.php';
410 $a = new HTTP_Request($url);
412 file_put_contents($cache .'.data', $a->getResponseBody());
414 $mt = $a->getResponseHeader('Content-Type');
416 require_once 'File/MimeType.php';
417 $m = new File_MimeType();
418 $ext = $m->toExt($mt);
423 'contentid' => md5($url)
427 file_put_contents($cache, json_encode($ret));
428 $ret['file'] = $cache . '.data';