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();
77 var $html_locale = false; // eg. 'en' or 'zh_HK'
78 var $images = array(); // generated list of cid images for sending
79 var $attachments = false;
80 var $css_inline = false; // put the css into the html
81 var $css_embed = false; // put the css tags into the body.
83 var $mail_method = 'SMTP';
85 var $cache_images = true;
89 var $body_cls = false;
91 function __construct($args) {
92 foreach($args as $k=>$v) {
96 // allow core mailer debug setting.
97 $ff = HTML_FlexyFramework::get();
99 if (!empty($ff->Core_Mailer['debug'])) {
100 $this->debug = $ff->Core_Mailer['debug'];
102 //$this->log("URL MAP");
103 //$this->log($this->urlmap);
108 * ---------------- Global Tools ---------------
113 $templateFile = $this->template;
114 $args = (array)$this->contents;
115 $content = clone($this->page);
117 foreach($args as $k=>$v) {
121 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
123 $ff = HTML_FlexyFramework::get();
124 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
125 if (isset($ff->Pman['HTTP_HOST'])) {
126 $http_host = $ff->Pman['HTTP_HOST'];
129 $content->HTTP_HOST = $http_host;
131 // this should be done by having multiple template sources...!!!
133 require_once 'HTML/Template/Flexy.php';
136 // 'forceCompile' => true,
137 'site_prefix' => false,
138 'multiSource' => true,
140 if (!empty($this->templateDir)) {
141 $tmp_opts['templateDir'] = $this->templateDir;
143 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
144 if (!empty($fopts['DB_DataObject_translator'])) {
145 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
147 if (!empty($fopts['locale'])) {
148 $tmp_opts['locale'] = $fopts['locale'];
151 // local opt's overwrite
152 if (!empty($this->locale)) {
153 $tmp_opts['locale'] = $this->locale;
157 $html_tmp_opts = $tmp_opts;
158 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
159 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
160 // then we have a multi-part email...
161 if (!empty($this->html_locale)) {
162 $html_tmp_opts['locale'] = $this->html_locale;
164 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
166 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
167 $htmlbody = $htmltemplate->bufferedOutputObject($content);
169 $this->htmlbody = $htmlbody;
171 // for the html body, we may want to convert the attachments to images.
172 // var_dump($htmlbody);exit;
174 if(!empty($content->body_cls) && strlen($content->body_cls)){
175 $htmlbody = $this->htmlbodySetClass($htmlbody, $content->body_cls);
178 if ($this->replaceImages) {
179 $htmlbody = $this->htmlbodytoCID($htmlbody);
182 if ($this->css_embed) {
183 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
186 if ($this->css_inline && strlen($this->css_inline)) {
187 $htmlbody = $this->htmlbodyInlineCss($htmlbody);
191 $tmp_opts['nonHTML'] = true;
194 //print_R($tmp_opts);
195 // $tmp_opts['force'] = true;
197 $template = new HTML_Template_Flexy( $tmp_opts );
198 $template->compile('mail/'. $templateFile.'.txt');
200 /* use variables from this object to ouput data. */
201 $mailtext = $template->bufferedOutputObject($content);
202 //print_r($mailtext);exit;
206 //echo "<PRE>";print_R($mailtext);
208 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
209 require_once 'Mail/mimeDecode.php';
210 require_once 'Mail.php';
212 $decoder = new Mail_mimeDecode($mailtext);
213 $parts = $decoder->getSendArray();
214 if (PEAR::isError($parts)) {
216 //echo "PROBLEM: {$parts->message}";
222 require_once 'Mail/mime.php';
223 $mime = new Mail_mime(array(
225 //'html_encoding' => 'base64',
226 'html_charset' => 'utf-8',
227 'text_charset' => 'utf-8',
228 'head_charset' => 'utf-8',
230 // clean up the headers...
233 $parts[1]['Message-Id'] = '<' . $content->msgid .
234 '@' . $content->HTTP_HOST .'>';
237 if ($htmlbody !== false) {
238 // got a html headers...
240 if (isset($parts[1]['Content-Type'])) {
241 unset($parts[1]['Content-Type']);
243 $mime->setTXTBody($parts[2]);
244 $mime->setHTMLBody($htmlbody);
245 // var_dump($mime);exit;
246 foreach($this->images as $cid=>$cdata) {
251 $cid.'.'.$cdata['ext'],
259 if(!empty($this->attachments)){
260 //if got a attachments
261 $header = $mime->headers($parts[1]);
263 if (isset($parts[1]['Content-Type'])) {
264 unset($parts[1]['Content-Type']);
269 if(preg_match('/text\/html/', $header['Content-Type'])){
270 $mime->setHTMLBody($parts[2]);
271 $mime->setTXTBody('This message is in HTML only');
273 $mime->setTXTBody($parts[2]);
274 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
277 foreach($this->attachments as $attch){
278 $mime->addAttachment(
281 (!empty($attch['name'])) ? $attch['name'] : '',
290 $parts[2] = $mime->get();
291 $parts[1] = $mime->headers($parts[1]);
296 'recipents' => $parts[0],
297 'headers' => $parts[1],
301 if ($this->rcpts !== false) {
302 $ret['recipents'] = $this->rcpts;
304 // if 'to' is empty, then add the recipents in there... (must be an array?
305 if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
306 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
307 $ret['headers']['To'] = implode(',', $ret['recipents']);
311 // add bcc if necessary..
312 if (!empty($this->bcc)) {
313 $ret['bcc'] = $this->bcc;
317 function send($email = false)
320 $ff = HTML_FlexyFramework::get();
324 $email = is_array($email) ? $email : $this->toData();
326 if (is_a($email, 'PEAR_Error')) {
327 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
333 //$this->log( htmlspecialchars(print_r($email,true)));
335 ///$recipents = array($this->email);
336 // $mailOptions = PEAR::getStaticProperty('Mail','options');
338 $mailOptions = isset($ff->Mail) ? $ff->Mail : array();
339 //print_R($mailOptions);exit;
341 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
342 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
346 $mail = Mail::factory($this->mail_method,$mailOptions);
348 $mail->debug = (bool) $this->debug;
351 $email['headers']['Date'] = date('r');
352 if (PEAR::isError($mail)) {
353 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
358 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
362 // this makes contents untrustable...
363 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
364 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
367 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
368 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
369 error_reporting($oe);
371 $pg->addEvent("COREMAILER-SENT", false,
372 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
373 'Subject: ' . @$email['headers']['Subject']
376 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
382 function htmlbodytoCID($html)
384 $dom = new DOMDocument();
385 // this may raise parse errors as some html may be a component..
386 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
387 $imgs= $dom->getElementsByTagName('img');
391 foreach ($imgs as $i=>$img) {
392 $url = $img->getAttribute('src');
393 if (preg_match('#^cid:#', $url)) {
396 $me = $img->getAttribute('mailembed');
401 if(!array_key_exists($url, $urls)){
402 $conv = $this->fetchImage($url);
404 $this->images[$conv['contentid']] = $conv;
409 $img->setAttribute('src', 'cid:' . $conv['contentid']);
413 foreach ($imgs as $i=>$img) {
414 $url = $img->getAttribute('src');
415 if (preg_match('#^cid:#', $url)) {
418 $me = $img->getAttribute('mailembed');
423 $conv = $this->fetchImage($url);
424 $this->images[$conv['contentid']] = $conv;
426 $img->setAttribute('src', 'cid:' . $conv['contentid']);
431 return $dom->saveHTML();
436 function htmlbodyCssEmbed($html)
438 $ff = HTML_FlexyFramework::get();
439 $dom = new DOMDocument();
441 // this may raise parse errors as some html may be a component..
442 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
443 $links = $dom->getElementsByTagName('link');
445 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
448 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
450 foreach ($lc as $i=>$link) {
451 //var_dump($link->getAttribute('href'));
453 if ($link->getAttribute('rel') != 'stylesheet') {
456 $url = $link->getAttribute('href');
457 $file = $ff->rootDir . $url;
459 if (!preg_match('#^(http|https)://#', $url)) {
460 $file = $ff->rootDir . $url;
462 if (!file_exists($file)) {
464 $link->setAttribute('href', 'missing:' . $file);
468 $file = $this->mapurl($url);
471 $par = $link->parentNode;
472 $par->removeChild($link);
473 $s = $dom->createElement('style');
474 $e = $dom->createTextNode(file_get_contents($file));
476 $par->appendChild($s);
479 return $dom->saveHTML();
484 function htmlbodyInlineCss($html)
486 $dom = new DOMDocument();
488 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
490 $html = $dom->getElementsByTagName('html');
491 $head = $dom->getElementsByTagName('head');
492 $body = $dom->getElementsByTagName('body');
495 $head = $dom->createElement('head');
496 $html->item(0)->insertBefore($head, $body->item(0));
497 $head = $dom->getElementsByTagName('head');
500 $s = $dom->createElement('style');
501 $e = $dom->createTextNode($this->css_inline);
503 $head->item(0)->appendChild($s);
505 return $dom->saveHTML();
508 require_once 'HTML/CSS/InlineStyle.php';
510 $doc = new HTML_CSS_InlineStyle($html);
512 $doc->applyStylesheet($this->css_inline);
514 $html = $doc->getHTML();
520 function htmlbodySetClass($html, $cls)
522 $dom = new DOMDocument();
524 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
526 $body = $dom->getElementsByTagName('body');
528 $class = $dom->createAttribute('class');
529 $class->value = $cls;
530 $body->item(0)->appendChild($class);
532 return $dom->saveHTML();
535 function fetchImage($url)
539 $this->log( "FETCH : $url\n");
541 if ($url[0] == '/') {
542 $ff = HTML_FlexyFramework::get();
543 $file = $ff->rootDir . $url;
544 require_once 'File/MimeType.php';
545 $m = new File_MimeType();
546 $mt = $m->fromFilename($file);
547 $ext = $m->toExt($mt);
552 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
560 //print_R($url); exit;
563 if (preg_match('#^file:///#', $url)) {
564 $file = preg_replace('#^file://#', '', $url);
565 require_once 'File/MimeType.php';
566 $m = new File_MimeType();
567 $mt = $m->fromFilename($file);
568 $ext = $m->toExt($mt);
573 'contentid' => md5($file),
580 // 2 files --- the info file.. and the actual file...
583 $uinfo = posix_getpwuid( posix_getuid () );
584 $user = $uinfo['name'];
586 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
587 if ($this->cache_images &&
588 file_exists($cache) &&
589 filemtime($cache) > strtotime('NOW - 1 WEEK')
591 $ret = json_decode(file_get_contents($cache), true);
592 $this->log("fetched from cache");
593 $ret['file'] = $cache . '.data';
596 if (!file_exists(dirname($cache))) {
597 mkdir(dirname($cache),0700, true);
600 require_once 'HTTP/Request.php';
602 $real_url = str_replace(' ', '%20', $this->mapurl($url));
603 $a = new HTTP_Request($real_url);
605 $data = $a->getResponseBody();
607 $this->log("got file of size " . strlen($data));
608 $this->log("save contentid " . md5($url));
610 file_put_contents($cache .'.data', $data);
613 $mt = $a->getResponseHeader('Content-Type');
615 require_once 'File/MimeType.php';
616 $m = new File_MimeType();
617 $ext = $m->toExt($mt);
622 'contentid' => md5($url)
626 file_put_contents($cache, json_encode($ret));
627 $ret['file'] = $cache . '.data';
634 foreach($this->urlmap as $o=>$n) {
635 if (strpos($in,$o) === 0) {
636 $ret =$n . substr($in,strlen($o));
637 $this->log("mapURL in $in = $ret");
641 $this->log("mapurl no change - $in");
654 if ($this->debug < 2) {
655 echo '<PRE>' . print_r($val,true). "\n";
658 $fh = fopen('/tmp/core_mailer.log', 'a');
659 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");