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)
21 'rcpts' => array(), -- only used by the 'send' code???.
22 'template' => 'your_template.html', // must be in templates/mail direcotry.. -- name without the .html or .txt
24 // 'bcc' => 'xyz@abc.com,abc@xyz.com', // string...
25 // 'contents' => array(), // << keys must be trusted
26 // if bcc is property of contents, then it will be used (BAD DESIGN)
28 // 'html_locale => 'en', // always use the 'english translated verison'
29 // 'cache_images => true, // -- defaults to caching images - set to false to disable.
30 // 'replaceImages => false, // should images be replaced.
31 // 'urlmap => array( // map urls from template to a different location.
32 // 'https://www.mysite.com/' => 'http://localhost/',
34 // 'locale' => 'en', // .... or zh_hk....
36 // 'attachments' => array(
38 // 'file' => '/path/to/file', // file location
39 // name => 'myfile.pdf', // (optional) - uses basename of file
43 // 'mail_method' => 'SMTP', // or SMTPMX
47 * recipents is gathered from the resulting template
55 * $x->toData(); // returns data needed for notify?? - notify should really
56 * // just use this to pass around later..
62 class Pman_Core_Mailer {
64 var $page = false; /* usually a html_flexyframework_page */
65 var $contents = false; /* object or array */
66 var $template = false; /* string */
67 var $replaceImages = false; /* boolean */
69 var $templateDir = false;
70 var $locale = false; // eg. 'en' or 'zh_HK'
71 var $urlmap = array();
74 var $html_locale = false; // eg. 'en' or 'zh_HK'
75 var $images = array(); // generated list of cid images for sending
76 var $attachments = false;
77 var $css_inline = false; // not supported
78 var $css_embed = false; // put the css tags into the body.
80 var $mail_method = 'SMTP';
82 var $cache_images = true;
86 function Pman_Core_Mailer($args) {
87 foreach($args as $k=>$v) {
91 // allow core mailer debug setting.
92 $ff = HTML_FlexyFramework::get();
94 if (!empty($ff->Core_Mailer['debug'])) {
95 $this->debug = $ff->Core_Mailer['debug'];
97 //$this->log("URL MAP");
98 //$this->log($this->urlmap);
103 * ---------------- Global Tools ---------------
109 $templateFile = $this->template;
110 $args = (array)$this->contents;
112 $content = clone($this->page);
114 foreach($args as $k=>$v) {
118 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
120 $ff = HTML_FlexyFramework::get();
121 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
122 if (isset($ff->Pman['HTTP_HOST'])) {
123 $http_host = $ff->Pman['HTTP_HOST'];
127 $content->HTTP_HOST = $http_host;
132 // this should be done by having multiple template sources...!!!
134 require_once 'HTML/Template/Flexy.php';
137 // 'forceCompile' => true,
138 'site_prefix' => false,
140 if (!empty($this->templateDir)) {
141 $tmp_opts['templateDir'] = $this->templateDir;
143 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
144 if (!empty($fopts['DB_DataObject_translator'])) {
145 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
147 if (!empty($fopts['locale'])) {
148 $tmp_opts['locale'] = $fopts['locale'];
151 // local opt's overwrite
152 if (!empty($this->locale)) {
153 $tmp_opts['locale'] = $this->locale;
157 $html_tmp_opts = $tmp_opts;
158 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
159 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
160 // then we have a multi-part email...
162 if (!empty($this->html_locale)) {
163 $html_tmp_opts['locale'] = $this->html_locale;
165 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
167 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
168 $htmlbody = $htmltemplate->bufferedOutputObject($content);
170 $this->htmlbody = $htmlbody;
172 // for the html body, we may want to convert the attachments to images.
173 // var_dump($htmlbody);exit;
174 if ($this->replaceImages) {
175 $htmlbody = $this->htmlbodytoCID($htmlbody);
177 if ($this->css_embed) {
178 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
182 $tmp_opts['nonHTML'] = true;
185 //print_R($tmp_opts);
186 // $tmp_opts['force'] = true;
187 $template = new HTML_Template_Flexy( $tmp_opts );
189 $template->compile('mail/'. $templateFile.'.txt');
191 /* use variables from this object to ouput data. */
192 $mailtext = $template->bufferedOutputObject($content);
193 //print_r($mailtext);exit;
197 //echo "<PRE>";print_R($mailtext);
199 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
200 require_once 'Mail/mimeDecode.php';
201 require_once 'Mail.php';
203 $decoder = new Mail_mimeDecode($mailtext);
204 $parts = $decoder->getSendArray();
205 if (PEAR::isError($parts)) {
207 //echo "PROBLEM: {$parts->message}";
213 require_once 'Mail/mime.php';
214 $mime = new Mail_mime(array(
216 //'html_encoding' => 'base64',
217 'html_charset' => 'utf-8',
218 'text_charset' => 'utf-8',
219 'head_charset' => 'utf-8',
221 // clean up the headers...
224 $parts[1]['Message-Id'] = '<' . $content->msgid .
225 '@' . $content->HTTP_HOST .'>';
228 if ($htmlbody !== false) {
229 // got a html headers...
231 if (isset($parts[1]['Content-Type'])) {
232 unset($parts[1]['Content-Type']);
234 $mime->setTXTBody($parts[2]);
235 $mime->setHTMLBody($htmlbody);
236 // var_dump($mime);exit;
237 foreach($this->images as $cid=>$cdata) {
242 $cid.'.'.$cdata['ext'],
250 if(!empty($this->attachments)){
251 //if got a attachments
252 $header = $mime->headers($parts[1]);
254 if (isset($parts[1]['Content-Type'])) {
255 unset($parts[1]['Content-Type']);
260 if(preg_match('/text\/html/', $header['Content-Type'])){
261 $mime->setHTMLBody($parts[2]);
262 $mime->setTXTBody('This message is in HTML only');
264 $mime->setTXTBody($parts[2]);
265 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
268 foreach($this->attachments as $attch){
269 $mime->addAttachment(
272 (!empty($attch['name'])) ? $attch['name'] : '',
281 $parts[2] = $mime->get();
282 $parts[1] = $mime->headers($parts[1]);
285 'recipents' => $parts[0],
286 'headers' => $parts[1],
290 // add bcc if necessary..
291 if (!empty($this->bcc)) {
292 $ret['bcc'] = $this->bcc;
296 function send($email = false)
299 $pg = HTML_FlexyFramework::get()->page;
302 $email = is_array($email) ? $email : $this->toData();
303 if (is_a($email, 'PEAR_Error')) {
304 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
310 //$this->log( htmlspecialchars(print_r($email,true)));
312 ///$recipents = array($this->email);
313 $mailOptions = PEAR::getStaticProperty('Mail','options');
314 //print_R($mailOptions);exit;
316 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
317 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
321 $mail = Mail::factory($this->mail_method,$mailOptions);
323 $mail->debug = (bool) $this->debug;
326 $email['headers']['Date'] = date('r');
327 if (PEAR::isError($mail)) {
328 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
333 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
337 // this makes contents untrustable...
338 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
339 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
342 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
343 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
344 error_reporting($oe);
346 $pg->addEvent("COREMAILER-SENT", false,
347 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
348 'Subject: ' . @$email['headers']['Subject']
351 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
357 function htmlbodytoCID($html)
359 $dom = new DOMDocument();
360 // this may raise parse errors as some html may be a component..
361 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
362 $imgs= $dom->getElementsByTagName('img');
364 foreach ($imgs as $i=>$img) {
365 $url = $img->getAttribute('src');
366 if (preg_match('#^cid:#', $url)) {
369 $me = $img->getAttribute('mailembed');
374 $conv = $this->fetchImage($url);
375 $this->images[$conv['contentid']] = $conv;
377 $img->setAttribute('src', 'cid:' . $conv['contentid']);
381 return $dom->saveHTML();
386 function htmlbodyCssEmbed($html)
388 $ff = HTML_FlexyFramework::get();
389 $dom = new DOMDocument();
391 // this may raise parse errors as some html may be a component..
392 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
393 $links = $dom->getElementsByTagName('link');
395 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
398 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
400 foreach ($lc as $i=>$link) {
401 //var_dump($link->getAttribute('href'));
403 if ($link->getAttribute('rel') != 'stylesheet') {
406 $url = $link->getAttribute('href');
407 $file = $ff->rootDir . $url;
409 if (!preg_match('#^(http|https)://#', $url)) {
410 $file = $ff->rootDir . $url;
412 if (!file_exists($file)) {
414 $link->setAttribute('href', 'missing:' . $file);
418 $file = $this->mapurl($url);
421 $par = $link->parentNode;
422 $par->removeChild($link);
423 $s = $dom->createElement('style');
424 $e = $dom->createTextNode(file_get_contents($file));
426 $par->appendChild($s);
429 return $dom->saveHTML();
436 function fetchImage($url)
440 $this->log( "FETCH : $url\n");
442 if ($url[0] == '/') {
443 $ff = HTML_FlexyFramework::get();
444 $file = $ff->rootDir . $url;
445 require_once 'File/MimeType.php';
446 $m = new File_MimeType();
447 $mt = $m->fromFilename($file);
448 $ext = $m->toExt($mt);
453 'contentid' => md5($file), // mailer makes md5 cid's' -- cid with attachment-** are done by mailer.
461 //print_R($url); exit;
464 if (preg_match('#^file:///#', $url)) {
465 $file = preg_replace('#^file://#', '', $url);
466 require_once 'File/MimeType.php';
467 $m = new File_MimeType();
468 $mt = $m->fromFilename($file);
469 $ext = $m->toExt($mt);
474 'contentid' => md5($file),
481 // 2 files --- the info file.. and the actual file...
484 $uinfo = posix_getpwuid( posix_getuid () );
485 $user = $uinfo['name'];
487 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
488 if ($this->cache_images &&
489 file_exists($cache) &&
490 filemtime($cache) > strtotime('NOW - 1 WEEK')
492 $ret = json_decode(file_get_contents($cache), true);
493 $this->log("fetched from cache");
494 $ret['file'] = $cache . '.data';
497 if (!file_exists(dirname($cache))) {
498 mkdir(dirname($cache),0700, true);
501 require_once 'HTTP/Request.php';
502 $a = new HTTP_Request($this->mapurl($url));
504 $data = $a->getResponseBody();
506 $this->log("got file of size " . strlen($data));
507 $this->log("save contentid " . md5($url));
509 file_put_contents($cache .'.data', $data);
512 $mt = $a->getResponseHeader('Content-Type');
514 require_once 'File/MimeType.php';
515 $m = new File_MimeType();
516 $ext = $m->toExt($mt);
521 'contentid' => md5($url)
525 file_put_contents($cache, json_encode($ret));
526 $ret['file'] = $cache . '.data';
533 foreach($this->urlmap as $o=>$n) {
534 if (strpos($in,$o) === 0) {
535 $ret =$n . substr($in,strlen($o));
536 $this->log("mapURL in $in = $ret");
540 $this->log("mapurl no change - $in");
553 if ($this->debug < 2) {
554 echo '<PRE>' . print_r($val,true). "\n";
557 $fh = fopen('/tmp/core_mailer.log', 'a');
558 fwrite($fh, date('Y-m-d H:i:s -') . json_encode($val) . "\n");