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 cache_images => true -- defaults to caching images - set to false to disable.
25 replaceImages => true|false,
26 locale => 'en' .... or zh_hk....
27 rcpts => array() // override recipients..
31 name : (optional) - uses basename of file
35 mail_method : (SMTP or SMTPMX)
39 * recipents is gathered from the resulting template
47 * $x->toData(); // returns data needed for notify?? - notify should really
48 * // just use this to pass around later..
54 class Pman_Core_Mailer {
56 var $page = false; /* usually a html_flexyframework_page */
57 var $contents = false; /* object or array */
58 var $template = false; /* string */
59 var $replaceImages = false; /* boolean */
61 var $templateDir = false;
62 var $locale = false; // eg. 'en' or 'zh_HK'
65 var $html_locale = false; // eg. 'en' or 'zh_HK'
66 var $images = array(); // generated list of cid images for sending
67 var $attachments = false;
68 var $css_inline = false; // not supported
69 var $css_embed = false; // put the css tags into the body.
71 var $mail_method = 'SMTP';
73 var $cache_images = true;
75 function Pman_Core_Mailer($args) {
76 foreach($args as $k=>$v) {
83 * ---------------- Global Tools ---------------
89 $templateFile = $this->template;
90 $args = $this->contents;
92 $content = clone($this->page);
94 foreach((array)$args as $k=>$v) {
98 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
100 $ff = HTML_FlexyFramework::get();
101 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
102 if (isset($ff->Pman['HTTP_HOST'])) {
103 $http_host = $ff->Pman['HTTP_HOST'];
107 $content->HTTP_HOST = $http_host;
112 // this should be done by having multiple template sources...!!!
114 require_once 'HTML/Template/Flexy.php';
117 // 'forceCompile' => true,
118 'site_prefix' => false,
120 if (!empty($this->templateDir)) {
121 $tmp_opts['templateDir'] = $this->templateDir;
123 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
124 if (!empty($fopts['DB_DataObject_translator'])) {
125 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
127 if (!empty($fopts['locale'])) {
128 $tmp_opts['locale'] = $fopts['locale'];
131 // local opt's overwrite
132 if (!empty($this->locale)) {
133 $tmp_opts['locale'] = $this->locale;
137 $html_tmp_opts = $tmp_opts;
138 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
139 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
140 // then we have a multi-part email...
142 if (!empty($this->html_locale)) {
143 $html_tmp_opts['locale'] = $this->html_locale;
145 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
147 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
148 $htmlbody = $htmltemplate->bufferedOutputObject($content);
150 $this->htmlbody = $htmlbody;
152 // for the html body, we may want to convert the attachments to images.
153 // var_dump($htmlbody);exit;
154 if ($this->replaceImages) {
155 $htmlbody = $this->htmlbodytoCID($htmlbody);
157 if ($this->css_embed) {
158 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
162 $tmp_opts['nonHTML'] = true;
165 //print_R($tmp_opts);
166 // $tmp_opts['force'] = true;
167 $template = new HTML_Template_Flexy( $tmp_opts );
169 $template->compile('mail/'. $templateFile.'.txt');
171 /* use variables from this object to ouput data. */
172 $mailtext = $template->bufferedOutputObject($content);
173 //print_r($mailtext);exit;
177 //echo "<PRE>";print_R($mailtext);
179 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
180 require_once 'Mail/mimeDecode.php';
181 require_once 'Mail.php';
183 $decoder = new Mail_mimeDecode($mailtext);
184 $parts = $decoder->getSendArray();
185 if (PEAR::isError($parts)) {
187 //echo "PROBLEM: {$parts->message}";
193 require_once 'Mail/mime.php';
194 $mime = new Mail_mime(array(
196 //'html_encoding' => 'base64',
197 'html_charset' => 'utf-8',
198 'text_charset' => 'utf-8',
199 'head_charset' => 'utf-8',
201 // clean up the headers...
204 $parts[1]['Message-Id'] = '<' . $content->msgid .
205 '@' . $content->HTTP_HOST .'>';
208 if ($htmlbody !== false) {
209 // got a html headers...
211 if (isset($parts[1]['Content-Type'])) {
212 unset($parts[1]['Content-Type']);
214 $mime->setTXTBody($parts[2]);
215 $mime->setHTMLBody($htmlbody);
216 // var_dump($mime);exit;
217 foreach($this->images as $cid=>$cdata) {
222 $cid.'.'.$cdata['ext'],
230 if(!empty($this->attachments)){
231 //if got a attachments
232 $header = $mime->headers($parts[1]);
234 if (isset($parts[1]['Content-Type'])) {
235 unset($parts[1]['Content-Type']);
240 if(preg_match('/text\/html/', $header['Content-Type'])){
241 $mime->setHTMLBody($parts[2]);
242 $mime->setTXTBody('This message is in HTML only');
244 $mime->setTXTBody($parts[2]);
245 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
248 foreach($this->attachments as $attch){
249 $mime->addAttachment(
252 (!empty($attch['name'])) ? $attch['name'] : '',
261 $parts[2] = $mime->get();
262 $parts[1] = $mime->headers($parts[1]);
266 // print_r($parts[2]);
268 // list($recipents,$headers,$body) = $parts;
270 'recipents' => $parts[0],
271 'headers' => $parts[1],
276 function send($email = false)
279 $pg = HTML_FlexyFramework::get()->page;
282 $email = is_array($email) ? $email : $this->toData();
283 if (is_a($email, 'PEAR_Error')) {
284 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
290 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
292 ///$recipents = array($this->email);
293 $mailOptions = PEAR::getStaticProperty('Mail','options');
294 //print_R($mailOptions);exit;
296 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
297 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
301 $mail = Mail::factory($this->mail_method,$mailOptions);
303 $mail->debug = $this->debug;
306 $email['headers']['Date'] = date('r');
307 if (PEAR::isError($mail)) {
308 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
313 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
315 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
316 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
319 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
320 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
321 error_reporting($oe);
323 $pg->addEvent("COREMAILER-SENT", false,
324 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
325 'Subject: ' . @$email['headers']['Subject']
328 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
334 function htmlbodytoCID($html)
336 $dom = new DOMDocument();
337 // this may raise parse errors as some html may be a component..
338 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
339 $imgs= $dom->getElementsByTagName('img');
341 foreach ($imgs as $i=>$img) {
342 $url = $img->getAttribute('src');
343 if (preg_match('#^cid:#', $url)) {
346 $me = $img->getAttribute('mailembed');
351 $conv = $this->fetchImage($url);
352 $this->images[$conv['contentid']] = $conv;
354 $img->setAttribute('src', 'cid:' . $conv['contentid']);
358 return $dom->saveHTML();
363 function htmlbodyCssEmbed($html)
365 $ff = HTML_FlexyFramework::get();
366 $dom = new DOMDocument();
368 // this may raise parse errors as some html may be a component..
369 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
370 $links = $dom->getElementsByTagName('link');
372 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
375 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
377 foreach ($lc as $i=>$link) {
378 //var_dump($link->getAttribute('href'));
380 if ($link->getAttribute('rel') != 'stylesheet') {
383 $url = $link->getAttribute('href');
384 $file = $ff->rootDir . $url;
386 if (!preg_match('#^http://#', $url)) {
387 $file = $ff->rootDir . $url;
389 if (!file_exists($file)) {
391 $link->setAttribute('href', 'missing:' . $file);
398 $par = $link->parentNode;
399 $par->removeChild($link);
400 $s = $dom->createElement('style');
401 $e = $dom->createTextNode(file_get_contents($file));
403 $par->appendChild($s);
406 return $dom->saveHTML();
413 function fetchImage($url)
416 echo "FETCH : $url\n";
418 if ($url[0] == '/') {
419 $ff = HTML_FlexyFramework::get();
420 $file = $ff->rootDir . $url;
421 require_once 'File/MimeType.php';
422 $m = new File_MimeType();
423 $mt = $m->fromFilename($file);
424 $ext = $m->toExt($mt);
429 'contentid' => md5($file),
437 //print_R($url); exit;
440 if (preg_match('#^file:///#', $url)) {
441 $file = preg_replace('#^file://#', '', $url);
442 require_once 'File/MimeType.php';
443 $m = new File_MimeType();
444 $mt = $m->fromFilename($file);
445 $ext = $m->toExt($mt);
450 'contentid' => md5($file),
457 // 2 files --- the info file.. and the actual file...
460 $uinfo = posix_getpwuid( posix_getuid () );
461 $user = $uinfo['name'];
463 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
464 if ($this->cache_images &&
465 file_exists($cache) &&
466 filemtime($cache) > strtotime('NOW - 1 WEEK')
468 $ret = json_decode(file_get_contents($cache), true);
469 $ret['file'] = $cache . '.data';
472 if (!file_exists(dirname($cache))) {
473 mkdir(dirname($cache),0700, true);
476 require_once 'HTTP/Request.php';
477 $a = new HTTP_Request($url);
479 file_put_contents($cache .'.data', $a->getResponseBody());
481 $mt = $a->getResponseHeader('Content-Type');
483 require_once 'File/MimeType.php';
484 $m = new File_MimeType();
485 $ext = $m->toExt($mt);
490 'contentid' => md5($url)
494 file_put_contents($cache, json_encode($ret));
495 $ret['file'] = $cache . '.data';