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 * $x= new Pman_Core_Mailer($opts)
19 * $x= Pman_Core_Mailer(array(
21 contents << keys must be trusted
24 html_locale => 'en' == always use the 'english translated verison'
25 cache_images => true -- defaults to caching images - set to false to disable.
26 replaceImages => true|false,
28 'https://www.mysite.com/', 'http://localhost/'
30 locale => 'en' .... or zh_hk....
31 rcpts => array() // override recipients..
35 name : (optional) - uses basename of file
39 mail_method : (SMTP or SMTPMX)
43 * recipents is gathered from the resulting template
51 * $x->toData(); // returns data needed for notify?? - notify should really
52 * // just use this to pass around later..
58 class Pman_Core_Mailer {
60 var $page = false; /* usually a html_flexyframework_page */
61 var $contents = false; /* object or array */
62 var $template = false; /* string */
63 var $replaceImages = false; /* boolean */
65 var $templateDir = false;
66 var $locale = false; // eg. 'en' or 'zh_HK'
67 var $urlmap = array();
70 var $html_locale = false; // eg. 'en' or 'zh_HK'
71 var $images = array(); // generated list of cid images for sending
72 var $attachments = false;
73 var $css_inline = false; // not supported
74 var $css_embed = false; // put the css tags into the body.
76 var $mail_method = 'SMTP';
78 var $cache_images = true;
82 function Pman_Core_Mailer($args) {
83 foreach($args as $k=>$v) {
87 // allow core mailer debug setting.
88 $ff = HTML_FlexyFramework::get();
90 if (!empty($ff->Core_Mailer['debug'])) {
91 $this->debug = $ff->Core_Mailer['debug'];
93 //$this->log("URL MAP");
94 //$this->log($this->urlmap);
99 * ---------------- Global Tools ---------------
105 $templateFile = $this->template;
106 $args = (array)$this->contents;
108 $content = clone($this->page);
110 foreach($args as $k=>$v) {
114 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
116 $ff = HTML_FlexyFramework::get();
117 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
118 if (isset($ff->Pman['HTTP_HOST'])) {
119 $http_host = $ff->Pman['HTTP_HOST'];
123 $content->HTTP_HOST = $http_host;
128 // this should be done by having multiple template sources...!!!
130 require_once 'HTML/Template/Flexy.php';
133 // 'forceCompile' => true,
134 'site_prefix' => false,
136 if (!empty($this->templateDir)) {
137 $tmp_opts['templateDir'] = $this->templateDir;
139 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
140 if (!empty($fopts['DB_DataObject_translator'])) {
141 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
143 if (!empty($fopts['locale'])) {
144 $tmp_opts['locale'] = $fopts['locale'];
147 // local opt's overwrite
148 if (!empty($this->locale)) {
149 $tmp_opts['locale'] = $this->locale;
153 $html_tmp_opts = $tmp_opts;
154 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
155 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
156 // then we have a multi-part email...
158 if (!empty($this->html_locale)) {
159 $html_tmp_opts['locale'] = $this->html_locale;
161 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
163 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
164 $htmlbody = $htmltemplate->bufferedOutputObject($content);
166 $this->htmlbody = $htmlbody;
168 // for the html body, we may want to convert the attachments to images.
169 // var_dump($htmlbody);exit;
170 if ($this->replaceImages) {
171 $htmlbody = $this->htmlbodytoCID($htmlbody);
173 if ($this->css_embed) {
174 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
178 $tmp_opts['nonHTML'] = true;
181 //print_R($tmp_opts);
182 // $tmp_opts['force'] = true;
183 $template = new HTML_Template_Flexy( $tmp_opts );
185 $template->compile('mail/'. $templateFile.'.txt');
187 /* use variables from this object to ouput data. */
188 $mailtext = $template->bufferedOutputObject($content);
189 //print_r($mailtext);exit;
193 //echo "<PRE>";print_R($mailtext);
195 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
196 require_once 'Mail/mimeDecode.php';
197 require_once 'Mail.php';
199 $decoder = new Mail_mimeDecode($mailtext);
200 $parts = $decoder->getSendArray();
201 if (PEAR::isError($parts)) {
203 //echo "PROBLEM: {$parts->message}";
209 require_once 'Mail/mime.php';
210 $mime = new Mail_mime(array(
212 //'html_encoding' => 'base64',
213 'html_charset' => 'utf-8',
214 'text_charset' => 'utf-8',
215 'head_charset' => 'utf-8',
217 // clean up the headers...
220 $parts[1]['Message-Id'] = '<' . $content->msgid .
221 '@' . $content->HTTP_HOST .'>';
224 if ($htmlbody !== false) {
225 // got a html headers...
227 if (isset($parts[1]['Content-Type'])) {
228 unset($parts[1]['Content-Type']);
230 $mime->setTXTBody($parts[2]);
231 $mime->setHTMLBody($htmlbody);
232 // var_dump($mime);exit;
233 foreach($this->images as $cid=>$cdata) {
238 $cid.'.'.$cdata['ext'],
246 if(!empty($this->attachments)){
247 //if got a attachments
248 $header = $mime->headers($parts[1]);
250 if (isset($parts[1]['Content-Type'])) {
251 unset($parts[1]['Content-Type']);
256 if(preg_match('/text\/html/', $header['Content-Type'])){
257 $mime->setHTMLBody($parts[2]);
258 $mime->setTXTBody('This message is in HTML only');
260 $mime->setTXTBody($parts[2]);
261 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
264 foreach($this->attachments as $attch){
265 $mime->addAttachment(
268 (!empty($attch['name'])) ? $attch['name'] : '',
277 $parts[2] = $mime->get();
278 $parts[1] = $mime->headers($parts[1]);
281 'recipents' => $parts[0],
282 'headers' => $parts[1],
286 // add bcc if necessary..
287 if (!empty($this->bcc)) {
288 $ret['bcc'] = $this->bcc;
292 function send($email = false)
295 $pg = HTML_FlexyFramework::get()->page;
298 $email = is_array($email) ? $email : $this->toData();
299 if (is_a($email, 'PEAR_Error')) {
300 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
306 //$this->log( htmlspecialchars(print_r($email,true)));
308 ///$recipents = array($this->email);
309 $mailOptions = PEAR::getStaticProperty('Mail','options');
310 //print_R($mailOptions);exit;
312 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
313 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
317 $mail = Mail::factory($this->mail_method,$mailOptions);
319 $mail->debug = (bool) $this->debug;
322 $email['headers']['Date'] = date('r');
323 if (PEAR::isError($mail)) {
324 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
329 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
333 // this makes contents untrustable...
334 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
335 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
338 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
339 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
340 error_reporting($oe);
342 $pg->addEvent("COREMAILER-SENT", false,
343 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
344 'Subject: ' . @$email['headers']['Subject']
347 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
353 function htmlbodytoCID($html)
355 $dom = new DOMDocument();
356 // this may raise parse errors as some html may be a component..
357 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
358 $imgs= $dom->getElementsByTagName('img');
360 foreach ($imgs as $i=>$img) {
361 $url = $img->getAttribute('src');
362 if (preg_match('#^cid:#', $url)) {
365 $me = $img->getAttribute('mailembed');
370 $conv = $this->fetchImage($url);
371 $this->images[$conv['contentid']] = $conv;
373 $img->setAttribute('src', 'cid:' . $conv['contentid']);
377 return $dom->saveHTML();
382 function htmlbodyCssEmbed($html)
384 $ff = HTML_FlexyFramework::get();
385 $dom = new DOMDocument();
387 // this may raise parse errors as some html may be a component..
388 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
389 $links = $dom->getElementsByTagName('link');
391 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
394 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
396 foreach ($lc as $i=>$link) {
397 //var_dump($link->getAttribute('href'));
399 if ($link->getAttribute('rel') != 'stylesheet') {
402 $url = $link->getAttribute('href');
403 $file = $ff->rootDir . $url;
405 if (!preg_match('#^(http|https)://#', $url)) {
406 $file = $ff->rootDir . $url;
408 if (!file_exists($file)) {
410 $link->setAttribute('href', 'missing:' . $file);
414 $file = $this->mapurl($url);
417 $par = $link->parentNode;
418 $par->removeChild($link);
419 $s = $dom->createElement('style');
420 $e = $dom->createTextNode(file_get_contents($file));
422 $par->appendChild($s);
425 return $dom->saveHTML();
432 function fetchImage($url)
436 $this->log( "FETCH : $url\n");
438 if ($url[0] == '/') {
439 $ff = HTML_FlexyFramework::get();
440 $file = $ff->rootDir . $url;
441 require_once 'File/MimeType.php';
442 $m = new File_MimeType();
443 $mt = $m->fromFilename($file);
444 $ext = $m->toExt($mt);
449 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
457 //print_R($url); exit;
460 if (preg_match('#^file:///#', $url)) {
461 $file = preg_replace('#^file://#', '', $url);
462 require_once 'File/MimeType.php';
463 $m = new File_MimeType();
464 $mt = $m->fromFilename($file);
465 $ext = $m->toExt($mt);
470 'contentid' => md5($file),
477 // 2 files --- the info file.. and the actual file...
480 $uinfo = posix_getpwuid( posix_getuid () );
481 $user = $uinfo['name'];
483 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
484 if ($this->cache_images &&
485 file_exists($cache) &&
486 filemtime($cache) > strtotime('NOW - 1 WEEK')
488 $ret = json_decode(file_get_contents($cache), true);
489 $this->log("fetched from cache");
490 $ret['file'] = $cache . '.data';
493 if (!file_exists(dirname($cache))) {
494 mkdir(dirname($cache),0700, true);
497 require_once 'HTTP/Request.php';
498 $a = new HTTP_Request($this->mapurl($url));
500 $data = $a->getResponseBody();
502 $this->log("got file of size " . strlen($data));
503 $this->log("save contentid " . md5($url));
505 file_put_contents($cache .'.data', $data);
508 $mt = $a->getResponseHeader('Content-Type');
510 require_once 'File/MimeType.php';
511 $m = new File_MimeType();
512 $ext = $m->toExt($mt);
517 'contentid' => md5($url)
521 file_put_contents($cache, json_encode($ret));
522 $ret['file'] = $cache . '.data';
529 foreach($this->urlmap as $o=>$n) {
530 if (strpos($in,$o) === 0) {
531 $ret =$n . substr($in,strlen($o));
532 $this->log("mapURL in $in = $ret");
536 $this->log("mapurl no change - $in");
549 if ($this->debug < 2) {
550 echo '<PRE>' . print_r($val,true). "\n";
553 $fh = fopen('/tmp/core_mailer.log', 'a');
554 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");