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; // not supported
81 var $css_embed = false; // put the css tags into the body.
83 var $mail_method = 'SMTP';
85 var $cache_images = true;
89 function __construct($args) {
90 foreach($args as $k=>$v) {
94 // allow core mailer debug setting.
95 $ff = HTML_FlexyFramework::get();
97 if (!empty($ff->Core_Mailer['debug'])) {
98 $this->debug = $ff->Core_Mailer['debug'];
100 //$this->log("URL MAP");
101 //$this->log($this->urlmap);
106 * ---------------- Global Tools ---------------
111 $templateFile = $this->template;
112 $args = (array)$this->contents;
113 $content = clone($this->page);
115 foreach($args as $k=>$v) {
119 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
121 $ff = HTML_FlexyFramework::get();
122 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
123 if (isset($ff->Pman['HTTP_HOST'])) {
124 $http_host = $ff->Pman['HTTP_HOST'];
128 $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,
141 if (!empty($this->templateDir)) {
142 $tmp_opts['templateDir'] = $this->templateDir;
144 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
145 if (!empty($fopts['DB_DataObject_translator'])) {
146 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
148 if (!empty($fopts['locale'])) {
149 $tmp_opts['locale'] = $fopts['locale'];
152 // local opt's overwrite
153 if (!empty($this->locale)) {
154 $tmp_opts['locale'] = $this->locale;
158 $html_tmp_opts = $tmp_opts;
159 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
160 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
161 // then we have a multi-part email...
162 if (!empty($this->html_locale)) {
163 $html_tmp_opts['locale'] = $this->html_locale;
165 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
167 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
168 $htmlbody = $htmltemplate->bufferedOutputObject($content);
170 $this->htmlbody = $htmlbody;
172 // for the html body, we may want to convert the attachments to images.
173 // var_dump($htmlbody);exit;
174 if ($this->replaceImages) {
175 $htmlbody = $this->htmlbodytoCID($htmlbody);
177 if ($this->css_embed) {
178 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
182 $tmp_opts['nonHTML'] = true;
185 //print_R($tmp_opts);
186 // $tmp_opts['force'] = true;
187 $template = new HTML_Template_Flexy( $tmp_opts );
188 $template->compile('mail/'. $templateFile.'.txt');
190 /* use variables from this object to ouput data. */
191 $mailtext = $template->bufferedOutputObject($content);
192 //print_r($mailtext);exit;
196 //echo "<PRE>";print_R($mailtext);
198 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
199 require_once 'Mail/mimeDecode.php';
200 require_once 'Mail.php';
202 $decoder = new Mail_mimeDecode($mailtext);
203 $parts = $decoder->getSendArray();
204 if (PEAR::isError($parts)) {
206 //echo "PROBLEM: {$parts->message}";
212 require_once 'Mail/mime.php';
213 $mime = new Mail_mime(array(
215 //'html_encoding' => 'base64',
216 'html_charset' => 'utf-8',
217 'text_charset' => 'utf-8',
218 'head_charset' => 'utf-8',
220 // clean up the headers...
223 $parts[1]['Message-Id'] = '<' . $content->msgid .
224 '@' . $content->HTTP_HOST .'>';
227 if ($htmlbody !== false) {
228 // got a html headers...
230 if (isset($parts[1]['Content-Type'])) {
231 unset($parts[1]['Content-Type']);
233 $mime->setTXTBody($parts[2]);
234 $mime->setHTMLBody($htmlbody);
235 // var_dump($mime);exit;
236 foreach($this->images as $cid=>$cdata) {
241 $cid.'.'.$cdata['ext'],
249 if(!empty($this->attachments)){
250 //if got a attachments
251 $header = $mime->headers($parts[1]);
253 if (isset($parts[1]['Content-Type'])) {
254 unset($parts[1]['Content-Type']);
259 if(preg_match('/text\/html/', $header['Content-Type'])){
260 $mime->setHTMLBody($parts[2]);
261 $mime->setTXTBody('This message is in HTML only');
263 $mime->setTXTBody($parts[2]);
264 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
267 foreach($this->attachments as $attch){
268 $mime->addAttachment(
271 (!empty($attch['name'])) ? $attch['name'] : '',
280 $parts[2] = $mime->get();
281 $parts[1] = $mime->headers($parts[1]);
286 'recipents' => $parts[0],
287 'headers' => $parts[1],
291 if ($this->rcpts !== false) {
292 $ret['recipents'] = $this->rcpts;
294 // if 'to' is empty, then add the recipents in there... (must be an array?
295 if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
296 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
297 $ret['headers']['To'] = implode(',', $ret['recipents']);
301 // add bcc if necessary..
302 if (!empty($this->bcc)) {
303 $ret['bcc'] = $this->bcc;
307 function send($email = false)
309 $ff = HTML_FlexyFramework::get();
313 $email = is_array($email) ? $email : $this->toData();
315 if (is_a($email, 'PEAR_Error')) {
316 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
322 //$this->log( htmlspecialchars(print_r($email,true)));
324 ///$recipents = array($this->email);
325 // $mailOptions = PEAR::getStaticProperty('Mail','options');
327 $mailOptions = isset($ff->Mail) ? $ff->Mail : array();
328 //print_R($mailOptions);exit;
330 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
331 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
335 $mail = Mail::factory($this->mail_method,$mailOptions);
337 $mail->debug = (bool) $this->debug;
340 $email['headers']['Date'] = date('r');
341 if (PEAR::isError($mail)) {
342 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
347 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
351 // this makes contents untrustable...
352 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
353 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
356 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
357 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
358 error_reporting($oe);
360 $pg->addEvent("COREMAILER-SENT", false,
361 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
362 'Subject: ' . @$email['headers']['Subject']
365 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
371 function htmlbodytoCID($html)
373 $dom = new DOMDocument();
374 // this may raise parse errors as some html may be a component..
375 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
376 $imgs= $dom->getElementsByTagName('img');
378 foreach ($imgs as $i=>$img) {
379 $url = $img->getAttribute('src');
380 if (preg_match('#^cid:#', $url)) {
383 $me = $img->getAttribute('mailembed');
388 $conv = $this->fetchImage($url);
389 $this->images[$conv['contentid']] = $conv;
391 $img->setAttribute('src', 'cid:' . $conv['contentid']);
395 return $dom->saveHTML();
400 function htmlbodyCssEmbed($html)
402 $ff = HTML_FlexyFramework::get();
403 $dom = new DOMDocument();
405 // this may raise parse errors as some html may be a component..
406 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
407 $links = $dom->getElementsByTagName('link');
409 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
412 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
414 foreach ($lc as $i=>$link) {
415 //var_dump($link->getAttribute('href'));
417 if ($link->getAttribute('rel') != 'stylesheet') {
420 $url = $link->getAttribute('href');
421 $file = $ff->rootDir . $url;
423 if (!preg_match('#^(http|https)://#', $url)) {
424 $file = $ff->rootDir . $url;
426 if (!file_exists($file)) {
428 $link->setAttribute('href', 'missing:' . $file);
432 $file = $this->mapurl($url);
435 $par = $link->parentNode;
436 $par->removeChild($link);
437 $s = $dom->createElement('style');
438 $e = $dom->createTextNode(file_get_contents($file));
440 $par->appendChild($s);
443 return $dom->saveHTML();
450 function fetchImage($url)
454 $this->log( "FETCH : $url\n");
456 if ($url[0] == '/') {
457 $ff = HTML_FlexyFramework::get();
458 $file = $ff->rootDir . $url;
459 require_once 'File/MimeType.php';
460 $m = new File_MimeType();
461 $mt = $m->fromFilename($file);
462 $ext = $m->toExt($mt);
467 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
475 //print_R($url); exit;
478 if (preg_match('#^file:///#', $url)) {
479 $file = preg_replace('#^file://#', '', $url);
480 require_once 'File/MimeType.php';
481 $m = new File_MimeType();
482 $mt = $m->fromFilename($file);
483 $ext = $m->toExt($mt);
488 'contentid' => md5($file),
495 // 2 files --- the info file.. and the actual file...
498 $uinfo = posix_getpwuid( posix_getuid () );
499 $user = $uinfo['name'];
501 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
502 if ($this->cache_images &&
503 file_exists($cache) &&
504 filemtime($cache) > strtotime('NOW - 1 WEEK')
506 $ret = json_decode(file_get_contents($cache), true);
507 $this->log("fetched from cache");
508 $ret['file'] = $cache . '.data';
511 if (!file_exists(dirname($cache))) {
512 mkdir(dirname($cache),0700, true);
515 require_once 'HTTP/Request.php';
516 $a = new HTTP_Request($this->mapurl($url));
518 $data = $a->getResponseBody();
520 $this->log("got file of size " . strlen($data));
521 $this->log("save contentid " . md5($url));
523 file_put_contents($cache .'.data', $data);
526 $mt = $a->getResponseHeader('Content-Type');
528 require_once 'File/MimeType.php';
529 $m = new File_MimeType();
530 $ext = $m->toExt($mt);
535 'contentid' => md5($url)
539 file_put_contents($cache, json_encode($ret));
540 $ret['file'] = $cache . '.data';
547 foreach($this->urlmap as $o=>$n) {
548 if (strpos($in,$o) === 0) {
549 $ret =$n . substr($in,strlen($o));
550 $this->log("mapURL in $in = $ret");
554 $this->log("mapurl no change - $in");
567 if ($this->debug < 2) {
568 echo '<PRE>' . print_r($val,true). "\n";
571 $fh = fopen('/tmp/core_mailer.log', 'a');
572 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");