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 * require_once 'Pman/Core/Mailer.php';
18 * $x= new Pman_Core_Mailer(array(
20 // if bcc is property of this, then it will be used (BAD DESIGN)
22 'template' => 'your_template',
23 // must be in templates/mail direcotry..
24 // header and plaintext verison in mail/your_template.txt
25 // if you want a html body - use mail/your_template.body.html
27 // 'bcc' => 'xyz@abc.com,abc@xyz.com', // string...
28 // 'contents' => array(), // << keys must be trusted
29 // if bcc is property of contents, then it will be used (BAD DESIGN)
31 // 'html_locale => 'en', // always use the 'english translated verison'
32 // 'cache_images => true, // -- defaults to caching images - set to false to disable.
33 // 'replaceImages => false, // should images be replaced.
34 // 'urlmap => array( // map urls from template to a different location.
35 // 'https://www.mysite.com/' => 'http://localhost/',
37 // 'locale' => 'en', // .... or zh_hk....
39 // 'attachments' => array(
41 // 'file' => '/path/to/file', // file location
42 // name => 'myfile.pdf', // (optional) - uses basename of file
46 // 'mail_method' => 'SMTP', // or SMTPMX
50 * recipents is gathered from the resulting template
58 * $x->toData(); // returns data needed for notify?? - notify should really
59 * // just use this to pass around later..
65 class Pman_Core_Mailer {
67 var $page = false; /* usually a html_flexyframework_page */
68 var $contents = false; /* object or array */
69 var $template = false; /* string */
70 var $replaceImages = false; /* boolean */
72 var $templateDir = false;
73 var $locale = false; // eg. 'en' or 'zh_HK'
74 var $urlmap = array();
79 var $html_locale = false; // eg. 'en' or 'zh_HK'
80 var $images = array(); // generated list of cid images for sending
81 var $attachments = false;
82 var $css_inline = false; // put the css into the html
83 var $css_embed = false; // put the css tags into the body.
85 var $mail_method = 'SMTP';
87 var $cache_images = true;
91 var $body_cls = false;
93 function __construct($args) {
94 foreach($args as $k=>$v) {
98 // allow core mailer debug setting.
99 $ff = HTML_FlexyFramework::get();
101 if (!empty($ff->Core_Mailer['debug'])) {
102 $this->debug = $ff->Core_Mailer['debug'];
104 //$this->log("URL MAP");
105 //$this->log($this->urlmap);
110 * ---------------- Global Tools ---------------
115 $templateFile = $this->template;
116 $args = (array)$this->contents;
117 $content = clone($this->page);
119 foreach($args as $k=>$v) {
123 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
125 $ff = HTML_FlexyFramework::get();
126 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
127 if (isset($ff->Pman['HTTP_HOST']) && $http_host != 'localhost') {
128 $http_host = $ff->Pman['HTTP_HOST'];
131 $content->HTTP_HOST = $http_host;
133 // this should be done by having multiple template sources...!!!
135 require_once 'HTML/Template/Flexy.php';
138 // 'forceCompile' => true,
139 'site_prefix' => false,
140 'multiSource' => true,
143 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
145 //print_R($fopts);exit;
146 if (!empty($fopts['DB_DataObject_translator'])) {
147 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
149 if (!empty($fopts['locale'])) {
150 $tmp_opts['locale'] = $fopts['locale'];
152 if (!empty($fopts['templateDir'])) {
153 $tmp_opts['templateDir'] = $fopts['templateDir'];
156 if (!empty($this->templateDir)) {
157 $tmp_opts['templateDir'] = $this->templateDir;
160 // local opt's overwrite
161 if (!empty($this->locale)) {
162 $tmp_opts['locale'] = $this->locale;
166 $html_tmp_opts = $tmp_opts;
167 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
168 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
169 // then we have a multi-part email...
170 if (!empty($this->html_locale)) {
171 $html_tmp_opts['locale'] = $this->html_locale;
173 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
175 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
176 $htmlbody = $htmltemplate->bufferedOutputObject($content);
178 $this->htmlbody = $htmlbody;
180 // for the html body, we may want to convert the attachments to images.
181 // var_dump($htmlbody);exit;
183 if(!empty($content->body_cls) && strlen($content->body_cls)){
184 $htmlbody = $this->htmlbodySetClass($htmlbody, $content->body_cls);
187 if ($this->replaceImages) {
188 $htmlbody = $this->htmlbodytoCID($htmlbody);
191 if ($this->css_embed) {
192 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
195 if ($this->css_inline && strlen($this->css_inline)) {
196 $htmlbody = $this->htmlbodyInlineCss($htmlbody);
200 $tmp_opts['nonHTML'] = true;
201 //$tmp_opts['debug'] = true;
203 // print_R($tmp_opts);
204 // $tmp_opts['force'] = true;
206 $template = new HTML_Template_Flexy( $tmp_opts );
208 $template->compile('mail/'. $templateFile.'.txt');
211 /* use variables from this object to ouput data. */
212 $mailtext = $template->bufferedOutputObject($content);
213 //print_r($mailtext);exit;
217 //echo "<PRE>";print_R($mailtext);
219 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
220 require_once 'Mail/mimeDecode.php';
221 require_once 'Mail.php';
223 $decoder = new Mail_mimeDecode($mailtext);
224 $parts = $decoder->getSendArray();
225 if (PEAR::isError($parts)) {
227 //echo "PROBLEM: {$parts->message}";
235 require_once 'Mail/mime.php';
236 $mime = new Mail_mime(array(
238 //'html_encoding' => 'base64',
239 'html_charset' => 'utf-8',
240 'text_charset' => 'utf-8',
241 'head_charset' => 'utf-8',
243 // clean up the headers...
246 $parts[1]['Message-Id'] = '<' . $content->msgid .
247 '@' . $content->HTTP_HOST .'>';
250 if ($htmlbody !== false) {
251 // got a html headers...
253 if (isset($parts[1]['Content-Type'])) {
254 unset($parts[1]['Content-Type']);
256 $mime->setTXTBody($parts[2]);
257 $this->textbody = $parts[2];
258 $mime->setHTMLBody($htmlbody);
260 // var_dump($mime);exit;
261 foreach($this->images as $cid=>$cdata) {
266 $cid.'.'.$cdata['ext'],
274 if(!empty($this->attachments)){
275 //if got a attachments
276 $header = $mime->headers($parts[1]);
278 if (isset($parts[1]['Content-Type'])) {
279 unset($parts[1]['Content-Type']);
284 if(preg_match('/text\/html/', $header['Content-Type'])){
285 $mime->setHTMLBody($parts[2]);
286 $mime->setTXTBody('This message is in HTML only');
287 $this->textbody = 'This message is in HTML only';
289 $mime->setTXTBody($parts[2]);
290 $this->textbody = $parts[2];
291 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
294 foreach($this->attachments as $attch){
295 $mime->addAttachment(
298 (!empty($attch['name'])) ? $attch['name'] : '',
307 $parts[2] = $mime->get();
308 $parts[1] = $mime->headers($parts[1]);
314 'recipents' => $parts[0],
315 'headers' => $parts[1],
319 if ($this->rcpts !== false) {
320 $ret['recipents'] = $this->rcpts;
322 // if 'to' is empty, then add the recipents in there... (must be an array?
323 if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
324 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
325 $ret['headers']['To'] = implode(',', $ret['recipents']);
329 // add bcc if necessary..
330 if (!empty($this->bcc)) {
331 $ret['bcc'] = $this->bcc;
335 function send($email = false)
338 $ff = HTML_FlexyFramework::get();
342 $email = is_array($email) ? $email : $this->toData();
344 if (is_a($email, 'PEAR_Error')) {
345 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
351 //$this->log( htmlspecialchars(print_r($email,true)));
353 ///$recipents = array($this->email);
354 // $mailOptions = PEAR::getStaticProperty('Mail','options');
356 $mailOptions = isset($ff->Mail) ? $ff->Mail : array();
357 //print_R($mailOptions);exit;
359 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
360 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
364 $mail = Mail::factory($this->mail_method,$mailOptions);
366 $mail->debug = (bool) $this->debug;
369 $email['headers']['Date'] = date('r');
370 if (PEAR::isError($mail)) {
371 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
376 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
380 // this makes contents untrustable...
381 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
382 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
385 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
392 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
393 error_reporting($oe);
395 $pg->addEvent("COREMAILER-SENT", false,
396 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
397 'Subject: ' . @$email['headers']['Subject']
400 $pg->addEvent("COREMAILER-FAIL", false,
401 "Sending to : " . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
402 " Error: " . $ret->toString());
409 function htmlbodytoCID($html)
411 $dom = new DOMDocument();
412 // this may raise parse errors as some html may be a component..
413 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
414 $imgs= $dom->getElementsByTagName('img');
418 foreach ($imgs as $i=>$img) {
419 $url = $img->getAttribute('src');
420 if (preg_match('#^cid:#', $url)) {
423 $me = $img->getAttribute('mailembed');
428 if(!array_key_exists($url, $urls)){
429 $conv = $this->fetchImage($url);
431 $this->images[$conv['contentid']] = $conv;
435 $img->setAttribute('origsrc', $url);
436 $img->setAttribute('src', 'cid:' . $conv['contentid']);
440 return $dom->saveHTML();
443 function htmlbodyCssEmbed($html)
445 $ff = HTML_FlexyFramework::get();
446 $dom = new DOMDocument();
448 // this may raise parse errors as some html may be a component..
449 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
450 $links = $dom->getElementsByTagName('link');
452 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
455 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
457 foreach ($lc as $i=>$link) {
458 //var_dump($link->getAttribute('href'));
460 if ($link->getAttribute('rel') != 'stylesheet') {
463 $url = $link->getAttribute('href');
464 $file = $ff->rootDir . $url;
466 if (!preg_match('#^(http|https)://#', $url)) {
467 $file = $ff->rootDir . $url;
469 if (!file_exists($file)) {
471 $link->setAttribute('href', 'missing:' . $file);
475 $file = $this->mapurl($url);
478 $par = $link->parentNode;
479 $par->removeChild($link);
480 $s = $dom->createElement('style');
481 $e = $dom->createTextNode(file_get_contents($file));
483 $par->appendChild($s);
486 return $dom->saveHTML();
491 function htmlbodyInlineCss($html)
493 $dom = new DOMDocument();
495 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
497 $html = $dom->getElementsByTagName('html');
498 $head = $dom->getElementsByTagName('head');
499 $body = $dom->getElementsByTagName('body');
502 $head = $dom->createElement('head');
503 $html->item(0)->insertBefore($head, $body->item(0));
504 $head = $dom->getElementsByTagName('head');
507 $s = $dom->createElement('style');
508 $e = $dom->createTextNode($this->css_inline);
510 $head->item(0)->appendChild($s);
512 return $dom->saveHTML();
515 require_once 'HTML/CSS/InlineStyle.php';
517 $doc = new HTML_CSS_InlineStyle($html);
519 $doc->applyStylesheet($this->css_inline);
521 $html = $doc->getHTML();
527 function htmlbodySetClass($html, $cls)
529 $dom = new DOMDocument();
531 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
533 $body = $dom->getElementsByTagName('body');
534 if (!empty($body->length)) {
535 $body->item(0)->setAttribute('class', $cls);
537 $body = $dom->createElement("body");
538 $body->setAttribute('class', $cls);
539 $dom->appendChild($body);
543 return $dom->saveHTML();
546 function fetchImage($url)
550 $this->log( "FETCH : $url\n");
552 if ($url[0] == '/') {
553 $ff = HTML_FlexyFramework::get();
554 $file = $ff->rootDir . $url;
555 require_once 'File/MimeType.php';
556 $m = new File_MimeType();
557 $mt = $m->fromFilename($file);
558 $ext = $m->toExt($mt);
563 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
571 //print_R($url); exit;
574 if (preg_match('#^file:///#', $url)) {
575 $file = preg_replace('#^file://#', '', $url);
576 require_once 'File/MimeType.php';
577 $m = new File_MimeType();
578 $mt = $m->fromFilename($file);
579 $ext = $m->toExt($mt);
584 'contentid' => md5($file),
591 // 2 files --- the info file.. and the actual file...
594 $uinfo = posix_getpwuid( posix_getuid () );
595 $user = $uinfo['name'];
597 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
598 if ($this->cache_images &&
599 file_exists($cache) &&
600 filemtime($cache) > strtotime('NOW - 1 WEEK')
602 $ret = json_decode(file_get_contents($cache), true);
603 $this->log("fetched from cache");
604 $ret['file'] = $cache . '.data';
607 if (!file_exists(dirname($cache))) {
608 mkdir(dirname($cache),0700, true);
611 require_once 'HTTP/Request.php';
613 $real_url = str_replace(' ', '%20', $this->mapurl($url));
614 $a = new HTTP_Request($real_url);
616 $data = $a->getResponseBody();
618 $this->log("got file of size " . strlen($data));
619 $this->log("save contentid " . md5($url));
621 file_put_contents($cache .'.data', $data);
624 $mt = $a->getResponseHeader('Content-Type');
626 require_once 'File/MimeType.php';
627 $m = new File_MimeType();
628 $ext = $m->toExt($mt);
633 'contentid' => md5($url)
637 file_put_contents($cache, json_encode($ret));
638 $ret['file'] = $cache . '.data';
644 foreach($this->urlmap as $o=>$n) {
645 if (strpos($in,$o) === 0) {
646 $ret =$n . substr($in,strlen($o));
647 $this->log("mapURL in $in = $ret");
651 $this->log("mapurl no change - $in");
664 if ($this->debug < 2) {
665 echo '<PRE>' . print_r($val,true). "\n";
668 $fh = fopen('/tmp/core_mailer.log', 'a');
669 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");