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 Pman_Core_Mailer($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 ---------------
112 $templateFile = $this->template;
113 $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'];
130 $content->HTTP_HOST = $http_host;
135 // this should be done by having multiple template sources...!!!
137 require_once 'HTML/Template/Flexy.php';
140 // 'forceCompile' => true,
141 'site_prefix' => false,
143 if (!empty($this->templateDir)) {
144 $tmp_opts['templateDir'] = $this->templateDir;
146 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
147 if (!empty($fopts['DB_DataObject_translator'])) {
148 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
150 if (!empty($fopts['locale'])) {
151 $tmp_opts['locale'] = $fopts['locale'];
154 // local opt's overwrite
155 if (!empty($this->locale)) {
156 $tmp_opts['locale'] = $this->locale;
160 $html_tmp_opts = $tmp_opts;
161 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
162 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
163 // then we have a multi-part email...
165 if (!empty($this->html_locale)) {
166 $html_tmp_opts['locale'] = $this->html_locale;
168 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
170 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
171 $htmlbody = $htmltemplate->bufferedOutputObject($content);
173 $this->htmlbody = $htmlbody;
175 // for the html body, we may want to convert the attachments to images.
176 // var_dump($htmlbody);exit;
177 if ($this->replaceImages) {
178 $htmlbody = $this->htmlbodytoCID($htmlbody);
180 if ($this->css_embed) {
181 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
185 $tmp_opts['nonHTML'] = true;
188 //print_R($tmp_opts);
189 // $tmp_opts['force'] = true;
190 $template = new HTML_Template_Flexy( $tmp_opts );
192 $template->compile('mail/'. $templateFile.'.txt');
194 /* use variables from this object to ouput data. */
195 $mailtext = $template->bufferedOutputObject($content);
196 //print_r($mailtext);exit;
200 //echo "<PRE>";print_R($mailtext);
202 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
203 require_once 'Mail/mimeDecode.php';
204 require_once 'Mail.php';
206 $decoder = new Mail_mimeDecode($mailtext);
207 $parts = $decoder->getSendArray();
208 if (PEAR::isError($parts)) {
210 //echo "PROBLEM: {$parts->message}";
216 require_once 'Mail/mime.php';
217 $mime = new Mail_mime(array(
219 //'html_encoding' => 'base64',
220 'html_charset' => 'utf-8',
221 'text_charset' => 'utf-8',
222 'head_charset' => 'utf-8',
224 // clean up the headers...
227 $parts[1]['Message-Id'] = '<' . $content->msgid .
228 '@' . $content->HTTP_HOST .'>';
231 if ($htmlbody !== false) {
232 // got a html headers...
234 if (isset($parts[1]['Content-Type'])) {
235 unset($parts[1]['Content-Type']);
237 $mime->setTXTBody($parts[2]);
238 $mime->setHTMLBody($htmlbody);
239 // var_dump($mime);exit;
240 foreach($this->images as $cid=>$cdata) {
245 $cid.'.'.$cdata['ext'],
253 if(!empty($this->attachments)){
254 //if got a attachments
255 $header = $mime->headers($parts[1]);
257 if (isset($parts[1]['Content-Type'])) {
258 unset($parts[1]['Content-Type']);
263 if(preg_match('/text\/html/', $header['Content-Type'])){
264 $mime->setHTMLBody($parts[2]);
265 $mime->setTXTBody('This message is in HTML only');
267 $mime->setTXTBody($parts[2]);
268 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
271 foreach($this->attachments as $attch){
272 $mime->addAttachment(
275 (!empty($attch['name'])) ? $attch['name'] : '',
284 $parts[2] = $mime->get();
285 $parts[1] = $mime->headers($parts[1]);
290 'recipents' => $parts[0],
291 'headers' => $parts[1],
295 if ($this->rcpts !== false) {
296 $ret['recipents'] = $this->rcpts;
298 // if 'to' is empty, then add the recipents in there... (must be an array?
299 if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
300 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
301 $ret['headers']['To'] = implode(',', $ret['recipents']);
305 // add bcc if necessary..
306 if (!empty($this->bcc)) {
307 $ret['bcc'] = $this->bcc;
311 function send($email = false)
314 $pg = HTML_FlexyFramework::get()->page;
317 $email = is_array($email) ? $email : $this->toData();
318 if (is_a($email, 'PEAR_Error')) {
319 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
325 //$this->log( htmlspecialchars(print_r($email,true)));
327 ///$recipents = array($this->email);
328 $mailOptions = PEAR::getStaticProperty('Mail','options');
329 //print_R($mailOptions);exit;
331 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
332 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
336 $mail = Mail::factory($this->mail_method,$mailOptions);
338 $mail->debug = (bool) $this->debug;
341 $email['headers']['Date'] = date('r');
342 if (PEAR::isError($mail)) {
343 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
348 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
352 // this makes contents untrustable...
353 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
354 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
357 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
358 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
359 error_reporting($oe);
361 $pg->addEvent("COREMAILER-SENT", false,
362 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
363 'Subject: ' . @$email['headers']['Subject']
366 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
372 function htmlbodytoCID($html)
374 $dom = new DOMDocument();
375 // this may raise parse errors as some html may be a component..
376 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
377 $imgs= $dom->getElementsByTagName('img');
379 foreach ($imgs as $i=>$img) {
380 $url = $img->getAttribute('src');
381 if (preg_match('#^cid:#', $url)) {
384 $me = $img->getAttribute('mailembed');
389 $conv = $this->fetchImage($url);
390 $this->images[$conv['contentid']] = $conv;
392 $img->setAttribute('src', 'cid:' . $conv['contentid']);
396 return $dom->saveHTML();
401 function htmlbodyCssEmbed($html)
403 $ff = HTML_FlexyFramework::get();
404 $dom = new DOMDocument();
406 // this may raise parse errors as some html may be a component..
407 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
408 $links = $dom->getElementsByTagName('link');
410 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
413 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
415 foreach ($lc as $i=>$link) {
416 //var_dump($link->getAttribute('href'));
418 if ($link->getAttribute('rel') != 'stylesheet') {
421 $url = $link->getAttribute('href');
422 $file = $ff->rootDir . $url;
424 if (!preg_match('#^(http|https)://#', $url)) {
425 $file = $ff->rootDir . $url;
427 if (!file_exists($file)) {
429 $link->setAttribute('href', 'missing:' . $file);
433 $file = $this->mapurl($url);
436 $par = $link->parentNode;
437 $par->removeChild($link);
438 $s = $dom->createElement('style');
439 $e = $dom->createTextNode(file_get_contents($file));
441 $par->appendChild($s);
444 return $dom->saveHTML();
451 function fetchImage($url)
455 $this->log( "FETCH : $url\n");
457 if ($url[0] == '/') {
458 $ff = HTML_FlexyFramework::get();
459 $file = $ff->rootDir . $url;
460 require_once 'File/MimeType.php';
461 $m = new File_MimeType();
462 $mt = $m->fromFilename($file);
463 $ext = $m->toExt($mt);
468 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
476 //print_R($url); exit;
479 if (preg_match('#^file:///#', $url)) {
480 $file = preg_replace('#^file://#', '', $url);
481 require_once 'File/MimeType.php';
482 $m = new File_MimeType();
483 $mt = $m->fromFilename($file);
484 $ext = $m->toExt($mt);
489 'contentid' => md5($file),
496 // 2 files --- the info file.. and the actual file...
499 $uinfo = posix_getpwuid( posix_getuid () );
500 $user = $uinfo['name'];
502 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
503 if ($this->cache_images &&
504 file_exists($cache) &&
505 filemtime($cache) > strtotime('NOW - 1 WEEK')
507 $ret = json_decode(file_get_contents($cache), true);
508 $this->log("fetched from cache");
509 $ret['file'] = $cache . '.data';
512 if (!file_exists(dirname($cache))) {
513 mkdir(dirname($cache),0700, true);
516 require_once 'HTTP/Request.php';
517 $a = new HTTP_Request($this->mapurl($url));
519 $data = $a->getResponseBody();
521 $this->log("got file of size " . strlen($data));
522 $this->log("save contentid " . md5($url));
524 file_put_contents($cache .'.data', $data);
527 $mt = $a->getResponseHeader('Content-Type');
529 require_once 'File/MimeType.php';
530 $m = new File_MimeType();
531 $ext = $m->toExt($mt);
536 'contentid' => md5($url)
540 file_put_contents($cache, json_encode($ret));
541 $ret['file'] = $cache . '.data';
548 foreach($this->urlmap as $o=>$n) {
549 if (strpos($in,$o) === 0) {
550 $ret =$n . substr($in,strlen($o));
551 $this->log("mapURL in $in = $ret");
555 $this->log("mapurl no change - $in");
568 if ($this->debug < 2) {
569 echo '<PRE>' . print_r($val,true). "\n";
572 $fh = fopen('/tmp/core_mailer.log', 'a');
573 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");