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 = array(); /* 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 ---------------
112 * applies this variables to a object
120 $templateFile = $this->template;
121 $args = (array)$this->contents;
122 $content = clone($this->page);
124 foreach($args as $k=>$v) {
128 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
130 $ff = HTML_FlexyFramework::get();
131 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
132 if (isset($ff->Pman['HTTP_HOST']) && $http_host != 'localhost') {
133 $http_host = $ff->Pman['HTTP_HOST'];
136 $content->HTTP_HOST = $http_host;
138 // this should be done by having multiple template sources...!!!
140 require_once 'HTML/Template/Flexy.php';
143 // 'forceCompile' => true,
144 'site_prefix' => false,
145 'multiSource' => true,
148 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
150 //print_R($fopts);exit;
151 if (!empty($fopts['DB_DataObject_translator'])) {
152 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
154 if (!empty($fopts['locale'])) {
155 $tmp_opts['locale'] = $fopts['locale'];
157 if (!empty($fopts['templateDir'])) {
158 $tmp_opts['templateDir'] = $fopts['templateDir'];
161 if (!empty($this->templateDir)) {
162 $tmp_opts['templateDir'] = $this->templateDir;
165 // local opt's overwrite
166 if (!empty($this->locale)) {
167 $tmp_opts['locale'] = $this->locale;
171 $html_tmp_opts = $tmp_opts;
172 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
173 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
174 // then we have a multi-part email...
175 if (!empty($this->html_locale)) {
176 $html_tmp_opts['locale'] = $this->html_locale;
178 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
180 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
181 $htmlbody = $htmltemplate->bufferedOutputObject($content);
183 $this->htmlbody = $htmlbody;
185 // for the html body, we may want to convert the attachments to images.
186 // var_dump($htmlbody);exit;
188 if(!empty($content->body_cls) && strlen($content->body_cls)){
189 $htmlbody = $this->htmlbodySetClass($htmlbody, $content->body_cls);
192 if ($this->replaceImages) {
193 $htmlbody = $this->htmlbodytoCID($htmlbody);
196 if ($this->css_embed) {
197 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
200 if ($this->css_inline && strlen($this->css_inline)) {
201 $htmlbody = $this->htmlbodyInlineCss($htmlbody);
205 $tmp_opts['nonHTML'] = true;
206 //$tmp_opts['debug'] = true;
208 // print_R($tmp_opts);
209 // $tmp_opts['force'] = true;
211 $template = new HTML_Template_Flexy( $tmp_opts );
213 $template->compile('mail/'. $templateFile.'.txt');
215 /* use variables from this object to ouput data. */
216 $mailtext = $template->bufferedOutputObject($content);
217 //print_r($mailtext);exit;
221 //echo "<PRE>";print_R($mailtext);
223 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
224 require_once 'Mail/mimeDecode.php';
225 require_once 'Mail.php';
227 $decoder = new Mail_mimeDecode($mailtext);
228 $parts = $decoder->getSendArray();
229 if (PEAR::isError($parts)) {
231 //echo "PROBLEM: {$parts->message}";
237 require_once 'Mail/mime.php';
238 $mime = new Mail_mime(array(
240 //'html_encoding' => 'base64',
241 'html_charset' => 'utf-8',
242 'text_charset' => 'utf-8',
243 'head_charset' => 'utf-8',
245 // clean up the headers...
248 $parts[1]['Message-Id'] = '<' . $content->msgid .
249 '@' . $content->HTTP_HOST .'>';
252 if ($htmlbody !== false) {
253 // got a html headers...
255 if (isset($parts[1]['Content-Type'])) {
256 unset($parts[1]['Content-Type']);
258 $mime->setTXTBody($parts[2]);
259 $this->textbody = $parts[2];
260 $mime->setHTMLBody($htmlbody);
262 // var_dump($mime);exit;
263 foreach($this->images as $cid=>$cdata) {
268 $cid.'.'.$cdata['ext'],
276 if(!empty($this->attachments)){
277 //if got a attachments
278 $header = $mime->headers($parts[1]);
280 if (isset($parts[1]['Content-Type'])) {
281 unset($parts[1]['Content-Type']);
286 if(preg_match('/text\/html/', $header['Content-Type'])){
287 $mime->setHTMLBody($parts[2]);
288 $mime->setTXTBody('This message is in HTML only');
289 $this->textbody = 'This message is in HTML only';
291 $mime->setTXTBody($parts[2]);
292 $this->textbody = $parts[2];
293 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
296 foreach($this->attachments as $attch){
297 $mime->addAttachment(
300 (!empty($attch['name'])) ? $attch['name'] : '',
309 $parts[2] = $mime->get();
310 $parts[1] = $mime->headers($parts[1]);
315 'recipents' => $parts[0],
316 'headers' => $parts[1],
320 if ($this->rcpts !== false) {
321 $ret['recipents'] = $this->rcpts;
323 // if 'to' is empty, then add the recipents in there... (must be an array?
324 if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
325 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
326 $ret['headers']['To'] = implode(',', $ret['recipents']);
330 // add bcc if necessary..
331 if (!empty($this->bcc)) {
332 $ret['bcc'] = $this->bcc;
336 function send($email = false)
339 $ff = HTML_FlexyFramework::get();
343 $email = is_array($email) ? $email : $this->toData();
345 if (is_a($email, 'PEAR_Error')) {
346 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
352 //$this->log( htmlspecialchars(print_r($email,true)));
354 ///$recipents = array($this->email);
355 // $mailOptions = PEAR::getStaticProperty('Mail','options');
357 $mailOptions = isset($ff->Mail) ? $ff->Mail : array();
358 //print_R($mailOptions);exit;
360 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
361 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
365 $mail = Mail::factory($this->mail_method,$mailOptions);
367 $mail->debug = (bool) $this->debug;
370 $email['headers']['Date'] = date('r');
371 if (PEAR::isError($mail)) {
372 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
377 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
381 // this makes contents untrustable...
382 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
383 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
386 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
393 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
394 error_reporting($oe);
396 $pg->addEvent("COREMAILER-SENT", false,
397 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
398 'Subject: ' . @$email['headers']['Subject']
401 $pg->addEvent("COREMAILER-FAIL", false,
402 "Sending to : " . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
403 " Error: " . $ret->toString());
410 function htmlbodytoCID($html)
412 $dom = new DOMDocument();
413 // this may raise parse errors as some html may be a component..
414 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
415 $imgs= $dom->getElementsByTagName('img');
419 foreach ($imgs as $i=>$img) {
420 $url = $img->getAttribute('src');
421 if (preg_match('#^cid:#', $url)) {
424 $me = $img->getAttribute('mailembed');
429 if(!array_key_exists($url, $urls)){
430 $conv = $this->fetchImage($url);
432 $this->images[$conv['contentid']] = $conv;
436 $img->setAttribute('origsrc', $url);
437 $img->setAttribute('src', 'cid:' . $conv['contentid']);
441 return $dom->saveHTML();
444 function htmlbodyCssEmbed($html)
446 $ff = HTML_FlexyFramework::get();
447 $dom = new DOMDocument();
449 // this may raise parse errors as some html may be a component..
450 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
451 $links = $dom->getElementsByTagName('link');
453 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
456 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
458 foreach ($lc as $i=>$link) {
459 //var_dump($link->getAttribute('href'));
461 if ($link->getAttribute('rel') != 'stylesheet') {
464 $url = $link->getAttribute('href');
465 $file = $ff->rootDir . $url;
467 if (!preg_match('#^(http|https)://#', $url)) {
468 $file = $ff->rootDir . $url;
470 if (!file_exists($file)) {
472 $link->setAttribute('href', 'missing:' . $file);
476 $file = $this->mapurl($url);
479 $par = $link->parentNode;
480 $par->removeChild($link);
481 $s = $dom->createElement('style');
482 $e = $dom->createTextNode(file_get_contents($file));
484 $par->appendChild($s);
487 return $dom->saveHTML();
492 function htmlbodyInlineCss($html)
494 $dom = new DOMDocument();
496 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
498 $html = $dom->getElementsByTagName('html');
499 $head = $dom->getElementsByTagName('head');
500 $body = $dom->getElementsByTagName('body');
503 $head = $dom->createElement('head');
504 $html->item(0)->insertBefore($head, $body->item(0));
505 $head = $dom->getElementsByTagName('head');
508 $s = $dom->createElement('style');
509 $e = $dom->createTextNode($this->css_inline);
511 $head->item(0)->appendChild($s);
513 return $dom->saveHTML();
516 require_once 'HTML/CSS/InlineStyle.php';
518 $doc = new HTML_CSS_InlineStyle($html);
520 $doc->applyStylesheet($this->css_inline);
522 $html = $doc->getHTML();
528 function htmlbodySetClass($html, $cls)
530 $dom = new DOMDocument();
532 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
534 $body = $dom->getElementsByTagName('body');
535 if (!empty($body->length)) {
536 $body->item(0)->setAttribute('class', $cls);
538 $body = $dom->createElement("body");
539 $body->setAttribute('class', $cls);
540 $dom->appendChild($body);
544 return $dom->saveHTML();
547 function fetchImage($url)
551 $this->log( "FETCH : $url\n");
553 if ($url[0] == '/') {
554 $ff = HTML_FlexyFramework::get();
555 $file = $ff->rootDir . $url;
556 require_once 'File/MimeType.php';
557 $m = new File_MimeType();
558 $mt = $m->fromFilename($file);
559 $ext = $m->toExt($mt);
564 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
572 //print_R($url); exit;
575 if (preg_match('#^file:///#', $url)) {
576 $file = preg_replace('#^file://#', '', $url);
577 require_once 'File/MimeType.php';
578 $m = new File_MimeType();
579 $mt = $m->fromFilename($file);
580 $ext = $m->toExt($mt);
585 'contentid' => md5($file),
592 // 2 files --- the info file.. and the actual file...
595 $uinfo = posix_getpwuid( posix_getuid () );
596 $user = $uinfo['name'];
598 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
599 if ($this->cache_images &&
600 file_exists($cache) &&
601 filemtime($cache) > strtotime('NOW - 1 WEEK')
603 $ret = json_decode(file_get_contents($cache), true);
604 $this->log("fetched from cache");
605 $ret['file'] = $cache . '.data';
608 if (!file_exists(dirname($cache))) {
609 mkdir(dirname($cache),0700, true);
612 require_once 'HTTP/Request.php';
614 $real_url = str_replace(' ', '%20', $this->mapurl($url));
615 $a = new HTTP_Request($real_url);
617 $data = $a->getResponseBody();
619 $this->log("got file of size " . strlen($data));
620 $this->log("save contentid " . md5($url));
622 file_put_contents($cache .'.data', $data);
625 $mt = $a->getResponseHeader('Content-Type');
627 require_once 'File/MimeType.php';
628 $m = new File_MimeType();
629 $ext = $m->toExt($mt);
634 'contentid' => md5($url)
638 file_put_contents($cache, json_encode($ret));
639 $ret['file'] = $cache . '.data';
645 foreach($this->urlmap as $o=>$n) {
646 if (strpos($in,$o) === 0) {
647 $ret =$n . substr($in,strlen($o));
648 $this->log("mapURL in $in = $ret");
652 $this->log("mapurl no change - $in");
665 if ($this->debug < 2) {
666 echo '<PRE>' . print_r($val,true). "\n";
669 $fh = fopen('/tmp/core_mailer.log', 'a');
670 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");