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;
79 function Pman_Core_Mailer($args) {
80 foreach($args as $k=>$v) {
84 // allow core mailer debug setting.
85 $ff = HTML_FlexyFramework::get();
87 if (!empty($ff->Core_Mailer['debug'])) {
88 $this->debug = $ff->Core_Mailer['debug'];
90 $this->log("URL MAP");
91 $this->log($this->urlmap);
96 * ---------------- Global Tools ---------------
102 $templateFile = $this->template;
103 $args = $this->contents;
105 $content = clone($this->page);
107 foreach((array)$args as $k=>$v) {
111 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
113 $ff = HTML_FlexyFramework::get();
114 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
115 if (isset($ff->Pman['HTTP_HOST'])) {
116 $http_host = $ff->Pman['HTTP_HOST'];
120 $content->HTTP_HOST = $http_host;
125 // this should be done by having multiple template sources...!!!
127 require_once 'HTML/Template/Flexy.php';
130 // 'forceCompile' => true,
131 'site_prefix' => false,
133 if (!empty($this->templateDir)) {
134 $tmp_opts['templateDir'] = $this->templateDir;
136 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
137 if (!empty($fopts['DB_DataObject_translator'])) {
138 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
140 if (!empty($fopts['locale'])) {
141 $tmp_opts['locale'] = $fopts['locale'];
144 // local opt's overwrite
145 if (!empty($this->locale)) {
146 $tmp_opts['locale'] = $this->locale;
150 $html_tmp_opts = $tmp_opts;
151 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
152 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
153 // then we have a multi-part email...
155 if (!empty($this->html_locale)) {
156 $html_tmp_opts['locale'] = $this->html_locale;
158 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
160 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
161 $htmlbody = $htmltemplate->bufferedOutputObject($content);
163 $this->htmlbody = $htmlbody;
165 // for the html body, we may want to convert the attachments to images.
166 // var_dump($htmlbody);exit;
167 if ($this->replaceImages) {
168 $htmlbody = $this->htmlbodytoCID($htmlbody);
170 if ($this->css_embed) {
171 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
175 $tmp_opts['nonHTML'] = true;
178 //print_R($tmp_opts);
179 // $tmp_opts['force'] = true;
180 $template = new HTML_Template_Flexy( $tmp_opts );
182 $template->compile('mail/'. $templateFile.'.txt');
184 /* use variables from this object to ouput data. */
185 $mailtext = $template->bufferedOutputObject($content);
186 //print_r($mailtext);exit;
190 //echo "<PRE>";print_R($mailtext);
192 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
193 require_once 'Mail/mimeDecode.php';
194 require_once 'Mail.php';
196 $decoder = new Mail_mimeDecode($mailtext);
197 $parts = $decoder->getSendArray();
198 if (PEAR::isError($parts)) {
200 //echo "PROBLEM: {$parts->message}";
206 require_once 'Mail/mime.php';
207 $mime = new Mail_mime(array(
209 //'html_encoding' => 'base64',
210 'html_charset' => 'utf-8',
211 'text_charset' => 'utf-8',
212 'head_charset' => 'utf-8',
214 // clean up the headers...
217 $parts[1]['Message-Id'] = '<' . $content->msgid .
218 '@' . $content->HTTP_HOST .'>';
221 if ($htmlbody !== false) {
222 // got a html headers...
224 if (isset($parts[1]['Content-Type'])) {
225 unset($parts[1]['Content-Type']);
227 $mime->setTXTBody($parts[2]);
228 $mime->setHTMLBody($htmlbody);
229 // var_dump($mime);exit;
230 foreach($this->images as $cid=>$cdata) {
235 $cid.'.'.$cdata['ext'],
243 if(!empty($this->attachments)){
244 //if got a attachments
245 $header = $mime->headers($parts[1]);
247 if (isset($parts[1]['Content-Type'])) {
248 unset($parts[1]['Content-Type']);
253 if(preg_match('/text\/html/', $header['Content-Type'])){
254 $mime->setHTMLBody($parts[2]);
255 $mime->setTXTBody('This message is in HTML only');
257 $mime->setTXTBody($parts[2]);
258 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
261 foreach($this->attachments as $attch){
262 $mime->addAttachment(
265 (!empty($attch['name'])) ? $attch['name'] : '',
274 $parts[2] = $mime->get();
275 $parts[1] = $mime->headers($parts[1]);
279 // print_r($parts[2]);
281 // list($recipents,$headers,$body) = $parts;
283 'recipents' => $parts[0],
284 'headers' => $parts[1],
289 function send($email = false)
292 $pg = HTML_FlexyFramework::get()->page;
295 $email = is_array($email) ? $email : $this->toData();
296 if (is_a($email, 'PEAR_Error')) {
297 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
303 //$this->log( htmlspecialchars(print_r($email,true)));
305 ///$recipents = array($this->email);
306 $mailOptions = PEAR::getStaticProperty('Mail','options');
307 //print_R($mailOptions);exit;
309 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
310 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
314 $mail = Mail::factory($this->mail_method,$mailOptions);
316 $mail->debug = (bool) $this->debug;
319 $email['headers']['Date'] = date('r');
320 if (PEAR::isError($mail)) {
321 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
326 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
328 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
329 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
332 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
333 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
334 error_reporting($oe);
336 $pg->addEvent("COREMAILER-SENT", false,
337 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
338 'Subject: ' . @$email['headers']['Subject']
341 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
347 function htmlbodytoCID($html)
349 $dom = new DOMDocument();
350 // this may raise parse errors as some html may be a component..
351 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
352 $imgs= $dom->getElementsByTagName('img');
354 foreach ($imgs as $i=>$img) {
355 $url = $img->getAttribute('src');
356 if (preg_match('#^cid:#', $url)) {
359 $me = $img->getAttribute('mailembed');
364 $conv = $this->fetchImage($url);
365 $this->images[$conv['contentid']] = $conv;
367 $img->setAttribute('src', 'cid:' . $conv['contentid']);
371 return $dom->saveHTML();
376 function htmlbodyCssEmbed($html)
378 $ff = HTML_FlexyFramework::get();
379 $dom = new DOMDocument();
381 // this may raise parse errors as some html may be a component..
382 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
383 $links = $dom->getElementsByTagName('link');
385 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
388 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
390 foreach ($lc as $i=>$link) {
391 //var_dump($link->getAttribute('href'));
393 if ($link->getAttribute('rel') != 'stylesheet') {
396 $url = $link->getAttribute('href');
397 $file = $ff->rootDir . $url;
399 if (!preg_match('#^(http|https)://#', $url)) {
400 $file = $ff->rootDir . $url;
402 if (!file_exists($file)) {
404 $link->setAttribute('href', 'missing:' . $file);
408 $file = $this->mapurl($url);
411 $par = $link->parentNode;
412 $par->removeChild($link);
413 $s = $dom->createElement('style');
414 $e = $dom->createTextNode(file_get_contents($file));
416 $par->appendChild($s);
419 return $dom->saveHTML();
426 function fetchImage($url)
430 $this->log( "FETCH : $url\n");
432 if ($url[0] == '/') {
433 $ff = HTML_FlexyFramework::get();
434 $file = $ff->rootDir . $url;
435 require_once 'File/MimeType.php';
436 $m = new File_MimeType();
437 $mt = $m->fromFilename($file);
438 $ext = $m->toExt($mt);
443 'contentid' => md5($file),
451 //print_R($url); exit;
454 if (preg_match('#^file:///#', $url)) {
455 $file = preg_replace('#^file://#', '', $url);
456 require_once 'File/MimeType.php';
457 $m = new File_MimeType();
458 $mt = $m->fromFilename($file);
459 $ext = $m->toExt($mt);
464 'contentid' => md5($file),
471 // 2 files --- the info file.. and the actual file...
474 $uinfo = posix_getpwuid( posix_getuid () );
475 $user = $uinfo['name'];
477 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
478 if ($this->cache_images &&
479 file_exists($cache) &&
480 filemtime($cache) > strtotime('NOW - 1 WEEK')
482 $ret = json_decode(file_get_contents($cache), true);
483 $this->log("fetched from cache");
484 $ret['file'] = $cache . '.data';
487 if (!file_exists(dirname($cache))) {
488 mkdir(dirname($cache),0700, true);
491 require_once 'HTTP/Request.php';
492 $a = new HTTP_Request($this->mapurl($url));
494 $data = $a->getResponseBody();
496 $this->log("got file of size " . strlen($data));
497 $this->log("save contentid " . md5($url));
499 file_put_contents($cache .'.data', $data);
502 $mt = $a->getResponseHeader('Content-Type');
504 require_once 'File/MimeType.php';
505 $m = new File_MimeType();
506 $ext = $m->toExt($mt);
511 'contentid' => md5($url)
515 file_put_contents($cache, json_encode($ret));
516 $ret['file'] = $cache . '.data';
523 foreach($this->urlmap as $o=>$n) {
524 if (strpos($in,$o) === 0) {
525 $ret =$n . substr($in,strlen($o));
526 $this->log("mapURL in $in = $ret");
530 $this->log("mapurl no change - $in");
541 if ($this->debug < 2) {
542 echo '<PRE>' . $val. "\n";
545 $fh = fopen('/tmp/core_mailer.log', 'a');
546 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");