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(
23 html_locale => 'en' == always use the 'english translated verison'
24 cache_images => true -- defaults to caching images - set to false to disable.
25 replaceImages => true|false,
27 'https://www.mysite.com/', 'http://localhost/'
29 locale => 'en' .... or zh_hk....
30 rcpts => array() // override recipients..
34 name : (optional) - uses basename of file
38 mail_method : (SMTP or SMTPMX)
42 * recipents is gathered from the resulting template
50 * $x->toData(); // returns data needed for notify?? - notify should really
51 * // just use this to pass around later..
57 class Pman_Core_Mailer {
59 var $page = false; /* usually a html_flexyframework_page */
60 var $contents = false; /* object or array */
61 var $template = false; /* string */
62 var $replaceImages = false; /* boolean */
64 var $templateDir = false;
65 var $locale = false; // eg. 'en' or 'zh_HK'
66 var $urlmap = array();
69 var $html_locale = false; // eg. 'en' or 'zh_HK'
70 var $images = array(); // generated list of cid images for sending
71 var $attachments = false;
72 var $css_inline = false; // not supported
73 var $css_embed = false; // put the css tags into the body.
75 var $mail_method = 'SMTP';
77 var $cache_images = true;
81 function Pman_Core_Mailer($args) {
82 foreach($args as $k=>$v) {
86 // allow core mailer debug setting.
87 $ff = HTML_FlexyFramework::get();
89 if (!empty($ff->Core_Mailer['debug'])) {
90 $this->debug = $ff->Core_Mailer['debug'];
92 //$this->log("URL MAP");
93 //$this->log($this->urlmap);
98 * ---------------- Global Tools ---------------
104 $templateFile = $this->template;
105 $args = (array)$this->contents;
107 $content = clone($this->page);
109 foreach($args as $k=>$v) {
113 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
115 $ff = HTML_FlexyFramework::get();
116 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
117 if (isset($ff->Pman['HTTP_HOST'])) {
118 $http_host = $ff->Pman['HTTP_HOST'];
122 $content->HTTP_HOST = $http_host;
127 // this should be done by having multiple template sources...!!!
129 require_once 'HTML/Template/Flexy.php';
132 // 'forceCompile' => true,
133 'site_prefix' => false,
135 if (!empty($this->templateDir)) {
136 $tmp_opts['templateDir'] = $this->templateDir;
138 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
139 if (!empty($fopts['DB_DataObject_translator'])) {
140 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
142 if (!empty($fopts['locale'])) {
143 $tmp_opts['locale'] = $fopts['locale'];
146 // local opt's overwrite
147 if (!empty($this->locale)) {
148 $tmp_opts['locale'] = $this->locale;
152 $html_tmp_opts = $tmp_opts;
153 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
154 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
155 // then we have a multi-part email...
157 if (!empty($this->html_locale)) {
158 $html_tmp_opts['locale'] = $this->html_locale;
160 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
162 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
163 $htmlbody = $htmltemplate->bufferedOutputObject($content);
165 $this->htmlbody = $htmlbody;
167 // for the html body, we may want to convert the attachments to images.
168 // var_dump($htmlbody);exit;
169 if ($this->replaceImages) {
170 $htmlbody = $this->htmlbodytoCID($htmlbody);
172 if ($this->css_embed) {
173 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
177 $tmp_opts['nonHTML'] = true;
180 //print_R($tmp_opts);
181 // $tmp_opts['force'] = true;
182 $template = new HTML_Template_Flexy( $tmp_opts );
184 $template->compile('mail/'. $templateFile.'.txt');
186 /* use variables from this object to ouput data. */
187 $mailtext = $template->bufferedOutputObject($content);
188 //print_r($mailtext);exit;
192 //echo "<PRE>";print_R($mailtext);
194 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
195 require_once 'Mail/mimeDecode.php';
196 require_once 'Mail.php';
198 $decoder = new Mail_mimeDecode($mailtext);
199 $parts = $decoder->getSendArray();
200 if (PEAR::isError($parts)) {
202 //echo "PROBLEM: {$parts->message}";
208 require_once 'Mail/mime.php';
209 $mime = new Mail_mime(array(
211 //'html_encoding' => 'base64',
212 'html_charset' => 'utf-8',
213 'text_charset' => 'utf-8',
214 'head_charset' => 'utf-8',
216 // clean up the headers...
219 $parts[1]['Message-Id'] = '<' . $content->msgid .
220 '@' . $content->HTTP_HOST .'>';
223 if ($htmlbody !== false) {
224 // got a html headers...
226 if (isset($parts[1]['Content-Type'])) {
227 unset($parts[1]['Content-Type']);
229 $mime->setTXTBody($parts[2]);
230 $mime->setHTMLBody($htmlbody);
231 // var_dump($mime);exit;
232 foreach($this->images as $cid=>$cdata) {
237 $cid.'.'.$cdata['ext'],
245 if(!empty($this->attachments)){
246 //if got a attachments
247 $header = $mime->headers($parts[1]);
249 if (isset($parts[1]['Content-Type'])) {
250 unset($parts[1]['Content-Type']);
255 if(preg_match('/text\/html/', $header['Content-Type'])){
256 $mime->setHTMLBody($parts[2]);
257 $mime->setTXTBody('This message is in HTML only');
259 $mime->setTXTBody($parts[2]);
260 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
263 foreach($this->attachments as $attch){
264 $mime->addAttachment(
267 (!empty($attch['name'])) ? $attch['name'] : '',
276 $parts[2] = $mime->get();
277 $parts[1] = $mime->headers($parts[1]);
280 'recipents' => $parts[0],
281 'headers' => $parts[1],
285 // add bcc if necessary..
286 if (!empty($this->bcc)) {
287 $ret['bcc'] = $this->bcc;
291 function send($email = false)
294 $pg = HTML_FlexyFramework::get()->page;
297 $email = is_array($email) ? $email : $this->toData();
298 if (is_a($email, 'PEAR_Error')) {
299 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
305 //$this->log( htmlspecialchars(print_r($email,true)));
307 ///$recipents = array($this->email);
308 $mailOptions = PEAR::getStaticProperty('Mail','options');
309 //print_R($mailOptions);exit;
311 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
312 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
316 $mail = Mail::factory($this->mail_method,$mailOptions);
318 $mail->debug = (bool) $this->debug;
321 $email['headers']['Date'] = date('r');
322 if (PEAR::isError($mail)) {
323 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
328 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
330 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
331 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
334 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
335 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
336 error_reporting($oe);
338 $pg->addEvent("COREMAILER-SENT", false,
339 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
340 'Subject: ' . @$email['headers']['Subject']
343 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
349 function htmlbodytoCID($html)
351 $dom = new DOMDocument();
352 // this may raise parse errors as some html may be a component..
353 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
354 $imgs= $dom->getElementsByTagName('img');
356 foreach ($imgs as $i=>$img) {
357 $url = $img->getAttribute('src');
358 if (preg_match('#^cid:#', $url)) {
361 $me = $img->getAttribute('mailembed');
366 $conv = $this->fetchImage($url);
367 $this->images[$conv['contentid']] = $conv;
369 $img->setAttribute('src', 'cid:' . $conv['contentid']);
373 return $dom->saveHTML();
378 function htmlbodyCssEmbed($html)
380 $ff = HTML_FlexyFramework::get();
381 $dom = new DOMDocument();
383 // this may raise parse errors as some html may be a component..
384 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
385 $links = $dom->getElementsByTagName('link');
387 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
390 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
392 foreach ($lc as $i=>$link) {
393 //var_dump($link->getAttribute('href'));
395 if ($link->getAttribute('rel') != 'stylesheet') {
398 $url = $link->getAttribute('href');
399 $file = $ff->rootDir . $url;
401 if (!preg_match('#^(http|https)://#', $url)) {
402 $file = $ff->rootDir . $url;
404 if (!file_exists($file)) {
406 $link->setAttribute('href', 'missing:' . $file);
410 $file = $this->mapurl($url);
413 $par = $link->parentNode;
414 $par->removeChild($link);
415 $s = $dom->createElement('style');
416 $e = $dom->createTextNode(file_get_contents($file));
418 $par->appendChild($s);
421 return $dom->saveHTML();
428 function fetchImage($url)
432 $this->log( "FETCH : $url\n");
434 if ($url[0] == '/') {
435 $ff = HTML_FlexyFramework::get();
436 $file = $ff->rootDir . $url;
437 require_once 'File/MimeType.php';
438 $m = new File_MimeType();
439 $mt = $m->fromFilename($file);
440 $ext = $m->toExt($mt);
445 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
453 //print_R($url); exit;
456 if (preg_match('#^file:///#', $url)) {
457 $file = preg_replace('#^file://#', '', $url);
458 require_once 'File/MimeType.php';
459 $m = new File_MimeType();
460 $mt = $m->fromFilename($file);
461 $ext = $m->toExt($mt);
466 'contentid' => md5($file),
473 // 2 files --- the info file.. and the actual file...
476 $uinfo = posix_getpwuid( posix_getuid () );
477 $user = $uinfo['name'];
479 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
480 if ($this->cache_images &&
481 file_exists($cache) &&
482 filemtime($cache) > strtotime('NOW - 1 WEEK')
484 $ret = json_decode(file_get_contents($cache), true);
485 $this->log("fetched from cache");
486 $ret['file'] = $cache . '.data';
489 if (!file_exists(dirname($cache))) {
490 mkdir(dirname($cache),0700, true);
493 require_once 'HTTP/Request.php';
494 $a = new HTTP_Request($this->mapurl($url));
496 $data = $a->getResponseBody();
498 $this->log("got file of size " . strlen($data));
499 $this->log("save contentid " . md5($url));
501 file_put_contents($cache .'.data', $data);
504 $mt = $a->getResponseHeader('Content-Type');
506 require_once 'File/MimeType.php';
507 $m = new File_MimeType();
508 $ext = $m->toExt($mt);
513 'contentid' => md5($url)
517 file_put_contents($cache, json_encode($ret));
518 $ret['file'] = $cache . '.data';
525 foreach($this->urlmap as $o=>$n) {
526 if (strpos($in,$o) === 0) {
527 $ret =$n . substr($in,strlen($o));
528 $this->log("mapURL in $in = $ret");
532 $this->log("mapurl no change - $in");
545 if ($this->debug < 2) {
546 echo '<PRE>' . print_r($val,true). "\n";
549 $fh = fopen('/tmp/core_mailer.log', 'a');
550 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");