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; // put the css into the html
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,
140 'multiSource' => true,
142 if (!empty($this->templateDir)) {
143 $tmp_opts['templateDir'] = $this->templateDir;
145 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
146 if (!empty($fopts['DB_DataObject_translator'])) {
147 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
149 if (!empty($fopts['locale'])) {
150 $tmp_opts['locale'] = $fopts['locale'];
153 // local opt's overwrite
154 if (!empty($this->locale)) {
155 $tmp_opts['locale'] = $this->locale;
159 $html_tmp_opts = $tmp_opts;
160 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
161 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
162 // then we have a multi-part email...
163 if (!empty($this->html_locale)) {
164 $html_tmp_opts['locale'] = $this->html_locale;
166 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
168 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
169 $htmlbody = $htmltemplate->bufferedOutputObject($content);
171 $this->htmlbody = $htmlbody;
173 // for the html body, we may want to convert the attachments to images.
174 // var_dump($htmlbody);exit;
175 if ($this->replaceImages) {
176 $htmlbody = $this->htmlbodytoCID($htmlbody);
179 if ($this->css_embed) {
180 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
183 if ($this->css_inline && strlen($this->css_inline)) {
184 $htmlbody = $this->htmlbodyInlineCss($htmlbody);
188 $tmp_opts['nonHTML'] = true;
191 //print_R($tmp_opts);
192 // $tmp_opts['force'] = true;
194 $template = new HTML_Template_Flexy( $tmp_opts );
195 $template->compile('mail/'. $templateFile.'.txt');
197 /* use variables from this object to ouput data. */
198 $mailtext = $template->bufferedOutputObject($content);
199 //print_r($mailtext);exit;
203 //echo "<PRE>";print_R($mailtext);
205 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
206 require_once 'Mail/mimeDecode.php';
207 require_once 'Mail.php';
209 $decoder = new Mail_mimeDecode($mailtext);
210 $parts = $decoder->getSendArray();
211 if (PEAR::isError($parts)) {
213 //echo "PROBLEM: {$parts->message}";
219 require_once 'Mail/mime.php';
220 $mime = new Mail_mime(array(
222 //'html_encoding' => 'base64',
223 'html_charset' => 'utf-8',
224 'text_charset' => 'utf-8',
225 'head_charset' => 'utf-8',
227 // clean up the headers...
230 $parts[1]['Message-Id'] = '<' . $content->msgid .
231 '@' . $content->HTTP_HOST .'>';
234 if ($htmlbody !== false) {
235 // got a html headers...
237 if (isset($parts[1]['Content-Type'])) {
238 unset($parts[1]['Content-Type']);
240 $mime->setTXTBody($parts[2]);
241 $mime->setHTMLBody($htmlbody);
242 // var_dump($mime);exit;
243 foreach($this->images as $cid=>$cdata) {
248 $cid.'.'.$cdata['ext'],
256 if(!empty($this->attachments)){
257 //if got a attachments
258 $header = $mime->headers($parts[1]);
260 if (isset($parts[1]['Content-Type'])) {
261 unset($parts[1]['Content-Type']);
266 if(preg_match('/text\/html/', $header['Content-Type'])){
267 $mime->setHTMLBody($parts[2]);
268 $mime->setTXTBody('This message is in HTML only');
270 $mime->setTXTBody($parts[2]);
271 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
274 foreach($this->attachments as $attch){
275 $mime->addAttachment(
278 (!empty($attch['name'])) ? $attch['name'] : '',
287 $parts[2] = $mime->get();
288 $parts[1] = $mime->headers($parts[1]);
293 'recipents' => $parts[0],
294 'headers' => $parts[1],
298 if ($this->rcpts !== false) {
299 $ret['recipents'] = $this->rcpts;
301 // if 'to' is empty, then add the recipents in there... (must be an array?
302 if (!empty($ret['recipents']) && is_array($ret['recipents']) &&
303 (empty($ret['headers']['To']) || !strlen(trim($ret['headers']['To'])))) {
304 $ret['headers']['To'] = implode(',', $ret['recipents']);
308 // add bcc if necessary..
309 if (!empty($this->bcc)) {
310 $ret['bcc'] = $this->bcc;
314 function send($email = false)
317 $ff = HTML_FlexyFramework::get();
321 $email = is_array($email) ? $email : $this->toData();
323 if (is_a($email, 'PEAR_Error')) {
324 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
330 //$this->log( htmlspecialchars(print_r($email,true)));
332 ///$recipents = array($this->email);
333 // $mailOptions = PEAR::getStaticProperty('Mail','options');
335 $mailOptions = isset($ff->Mail) ? $ff->Mail : array();
336 //print_R($mailOptions);exit;
338 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
339 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
343 $mail = Mail::factory($this->mail_method,$mailOptions);
345 $mail->debug = (bool) $this->debug;
348 $email['headers']['Date'] = date('r');
349 if (PEAR::isError($mail)) {
350 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
355 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
359 // this makes contents untrustable...
360 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
361 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
364 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
365 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
366 error_reporting($oe);
368 $pg->addEvent("COREMAILER-SENT", false,
369 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
370 'Subject: ' . @$email['headers']['Subject']
373 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
379 function htmlbodytoCID($html)
381 $dom = new DOMDocument();
382 // this may raise parse errors as some html may be a component..
383 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
384 $imgs= $dom->getElementsByTagName('img');
386 foreach ($imgs as $i=>$img) {
387 $url = $img->getAttribute('src');
388 if (preg_match('#^cid:#', $url)) {
391 $me = $img->getAttribute('mailembed');
396 $conv = $this->fetchImage($url);
397 $this->images[$conv['contentid']] = $conv;
399 $img->setAttribute('src', 'cid:' . $conv['contentid']);
403 return $dom->saveHTML();
408 function htmlbodyCssEmbed($html)
410 $ff = HTML_FlexyFramework::get();
411 $dom = new DOMDocument();
413 // this may raise parse errors as some html may be a component..
414 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
415 $links = $dom->getElementsByTagName('link');
417 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
420 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
422 foreach ($lc as $i=>$link) {
423 //var_dump($link->getAttribute('href'));
425 if ($link->getAttribute('rel') != 'stylesheet') {
428 $url = $link->getAttribute('href');
429 $file = $ff->rootDir . $url;
431 if (!preg_match('#^(http|https)://#', $url)) {
432 $file = $ff->rootDir . $url;
434 if (!file_exists($file)) {
436 $link->setAttribute('href', 'missing:' . $file);
440 $file = $this->mapurl($url);
443 $par = $link->parentNode;
444 $par->removeChild($link);
445 $s = $dom->createElement('style');
446 $e = $dom->createTextNode(file_get_contents($file));
448 $par->appendChild($s);
451 return $dom->saveHTML();
456 function htmlbodyInlineCss($html)
458 require_once 'HTML/CSS/InlineStyle.php';
460 $doc = new HTML_CSS_InlineStyle($html);
462 $htmldoc->applyStylesheet($this->css_inline);
464 $html = $htmldoc->getHTML();
466 // libxml_use_internal_errors (false);
468 // if (!function_exists('tidy_repair_string')) {
469 // return "INSTALL TIDY ON SERVER " . $html;
472 // $html = tidy_repair_string(
476 // 'output-xhtml' => TRUE,
484 // $dom = new DOMDocument();
486 // @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
488 // $html = $dom->getElementsByTagName('html');
489 // $head = $dom->getElementsByTagName('head');
490 // $body = $dom->getElementsByTagName('body');
492 // if(!$head->length){
493 // $head = $dom->createElement('head');
494 // $html->item(0)->insertBefore($head, $body->item(0));
495 // $head = $dom->getElementsByTagName('head');
498 // $s = $dom->createElement('style');
499 // $e = $dom->createTextNode($this->css_inline);
500 // $s->appendChild($e);
501 // $head->item(0)->appendChild($s);
503 // return $dom->saveHTML();
506 function fetchImage($url)
510 $this->log( "FETCH : $url\n");
512 if ($url[0] == '/') {
513 $ff = HTML_FlexyFramework::get();
514 $file = $ff->rootDir . $url;
515 require_once 'File/MimeType.php';
516 $m = new File_MimeType();
517 $mt = $m->fromFilename($file);
518 $ext = $m->toExt($mt);
523 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
531 //print_R($url); exit;
534 if (preg_match('#^file:///#', $url)) {
535 $file = preg_replace('#^file://#', '', $url);
536 require_once 'File/MimeType.php';
537 $m = new File_MimeType();
538 $mt = $m->fromFilename($file);
539 $ext = $m->toExt($mt);
544 'contentid' => md5($file),
551 // 2 files --- the info file.. and the actual file...
554 $uinfo = posix_getpwuid( posix_getuid () );
555 $user = $uinfo['name'];
557 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
558 if ($this->cache_images &&
559 file_exists($cache) &&
560 filemtime($cache) > strtotime('NOW - 1 WEEK')
562 $ret = json_decode(file_get_contents($cache), true);
563 $this->log("fetched from cache");
564 $ret['file'] = $cache . '.data';
567 if (!file_exists(dirname($cache))) {
568 mkdir(dirname($cache),0700, true);
571 require_once 'HTTP/Request.php';
573 $real_url = str_replace(' ', '%20', $this->mapurl($url));
574 $a = new HTTP_Request($real_url);
576 $data = $a->getResponseBody();
578 $this->log("got file of size " . strlen($data));
579 $this->log("save contentid " . md5($url));
581 file_put_contents($cache .'.data', $data);
584 $mt = $a->getResponseHeader('Content-Type');
586 require_once 'File/MimeType.php';
587 $m = new File_MimeType();
588 $ext = $m->toExt($mt);
593 'contentid' => md5($url)
597 file_put_contents($cache, json_encode($ret));
598 $ret['file'] = $cache . '.data';
605 foreach($this->urlmap as $o=>$n) {
606 if (strpos($in,$o) === 0) {
607 $ret =$n . substr($in,strlen($o));
608 $this->log("mapURL in $in = $ret");
612 $this->log("mapurl no change - $in");
625 if ($this->debug < 2) {
626 echo '<PRE>' . print_r($val,true). "\n";
629 $fh = fopen('/tmp/core_mailer.log', 'a');
630 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");