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'];
95 * ---------------- Global Tools ---------------
101 $templateFile = $this->template;
102 $args = $this->contents;
104 $content = clone($this->page);
106 foreach((array)$args as $k=>$v) {
110 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
112 $ff = HTML_FlexyFramework::get();
113 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
114 if (isset($ff->Pman['HTTP_HOST'])) {
115 $http_host = $ff->Pman['HTTP_HOST'];
119 $content->HTTP_HOST = $http_host;
124 // this should be done by having multiple template sources...!!!
126 require_once 'HTML/Template/Flexy.php';
129 // 'forceCompile' => true,
130 'site_prefix' => false,
132 if (!empty($this->templateDir)) {
133 $tmp_opts['templateDir'] = $this->templateDir;
135 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
136 if (!empty($fopts['DB_DataObject_translator'])) {
137 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
139 if (!empty($fopts['locale'])) {
140 $tmp_opts['locale'] = $fopts['locale'];
143 // local opt's overwrite
144 if (!empty($this->locale)) {
145 $tmp_opts['locale'] = $this->locale;
149 $html_tmp_opts = $tmp_opts;
150 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
151 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
152 // then we have a multi-part email...
154 if (!empty($this->html_locale)) {
155 $html_tmp_opts['locale'] = $this->html_locale;
157 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
159 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
160 $htmlbody = $htmltemplate->bufferedOutputObject($content);
162 $this->htmlbody = $htmlbody;
164 // for the html body, we may want to convert the attachments to images.
165 // var_dump($htmlbody);exit;
166 if ($this->replaceImages) {
167 $htmlbody = $this->htmlbodytoCID($htmlbody);
169 if ($this->css_embed) {
170 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
174 $tmp_opts['nonHTML'] = true;
177 //print_R($tmp_opts);
178 // $tmp_opts['force'] = true;
179 $template = new HTML_Template_Flexy( $tmp_opts );
181 $template->compile('mail/'. $templateFile.'.txt');
183 /* use variables from this object to ouput data. */
184 $mailtext = $template->bufferedOutputObject($content);
185 //print_r($mailtext);exit;
189 //echo "<PRE>";print_R($mailtext);
191 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
192 require_once 'Mail/mimeDecode.php';
193 require_once 'Mail.php';
195 $decoder = new Mail_mimeDecode($mailtext);
196 $parts = $decoder->getSendArray();
197 if (PEAR::isError($parts)) {
199 //echo "PROBLEM: {$parts->message}";
205 require_once 'Mail/mime.php';
206 $mime = new Mail_mime(array(
208 //'html_encoding' => 'base64',
209 'html_charset' => 'utf-8',
210 'text_charset' => 'utf-8',
211 'head_charset' => 'utf-8',
213 // clean up the headers...
216 $parts[1]['Message-Id'] = '<' . $content->msgid .
217 '@' . $content->HTTP_HOST .'>';
220 if ($htmlbody !== false) {
221 // got a html headers...
223 if (isset($parts[1]['Content-Type'])) {
224 unset($parts[1]['Content-Type']);
226 $mime->setTXTBody($parts[2]);
227 $mime->setHTMLBody($htmlbody);
228 // var_dump($mime);exit;
229 foreach($this->images as $cid=>$cdata) {
234 $cid.'.'.$cdata['ext'],
242 if(!empty($this->attachments)){
243 //if got a attachments
244 $header = $mime->headers($parts[1]);
246 if (isset($parts[1]['Content-Type'])) {
247 unset($parts[1]['Content-Type']);
252 if(preg_match('/text\/html/', $header['Content-Type'])){
253 $mime->setHTMLBody($parts[2]);
254 $mime->setTXTBody('This message is in HTML only');
256 $mime->setTXTBody($parts[2]);
257 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
260 foreach($this->attachments as $attch){
261 $mime->addAttachment(
264 (!empty($attch['name'])) ? $attch['name'] : '',
273 $parts[2] = $mime->get();
274 $parts[1] = $mime->headers($parts[1]);
278 // print_r($parts[2]);
280 // list($recipents,$headers,$body) = $parts;
282 'recipents' => $parts[0],
283 'headers' => $parts[1],
288 function send($email = false)
291 $pg = HTML_FlexyFramework::get()->page;
294 $email = is_array($email) ? $email : $this->toData();
295 if (is_a($email, 'PEAR_Error')) {
296 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
302 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
304 ///$recipents = array($this->email);
305 $mailOptions = PEAR::getStaticProperty('Mail','options');
306 //print_R($mailOptions);exit;
308 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
309 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
313 $mail = Mail::factory($this->mail_method,$mailOptions);
315 $mail->debug = $this->debug;
318 $email['headers']['Date'] = date('r');
319 if (PEAR::isError($mail)) {
320 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
325 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
327 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
328 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
331 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
332 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
333 error_reporting($oe);
335 $pg->addEvent("COREMAILER-SENT", false,
336 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
337 'Subject: ' . @$email['headers']['Subject']
340 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
346 function htmlbodytoCID($html)
348 $dom = new DOMDocument();
349 // this may raise parse errors as some html may be a component..
350 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
351 $imgs= $dom->getElementsByTagName('img');
353 foreach ($imgs as $i=>$img) {
354 $url = $img->getAttribute('src');
355 if (preg_match('#^cid:#', $url)) {
358 $me = $img->getAttribute('mailembed');
363 $conv = $this->fetchImage($url);
364 $this->images[$conv['contentid']] = $conv;
366 $img->setAttribute('src', 'cid:' . $conv['contentid']);
370 return $dom->saveHTML();
375 function htmlbodyCssEmbed($html)
377 $ff = HTML_FlexyFramework::get();
378 $dom = new DOMDocument();
380 // this may raise parse errors as some html may be a component..
381 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
382 $links = $dom->getElementsByTagName('link');
384 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
387 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
389 foreach ($lc as $i=>$link) {
390 //var_dump($link->getAttribute('href'));
392 if ($link->getAttribute('rel') != 'stylesheet') {
395 $url = $link->getAttribute('href');
396 $file = $ff->rootDir . $url;
398 if (!preg_match('#^(http|https)://#', $url)) {
399 $file = $ff->rootDir . $url;
401 if (!file_exists($file)) {
403 $link->setAttribute('href', 'missing:' . $file);
410 $par = $link->parentNode;
411 $par->removeChild($link);
412 $s = $dom->createElement('style');
413 $e = $dom->createTextNode(file_get_contents($file));
415 $par->appendChild($s);
418 return $dom->saveHTML();
425 function fetchImage($url)
427 $url = $this->mapurl($url);
430 echo "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 $ret['file'] = $cache . '.data';
486 if (!file_exists(dirname($cache))) {
487 mkdir(dirname($cache),0700, true);
490 require_once 'HTTP/Request.php';
491 $a = new HTTP_Request($url);
493 file_put_contents($cache .'.data', $a->getResponseBody());
495 $mt = $a->getResponseHeader('Content-Type');
497 require_once 'File/MimeType.php';
498 $m = new File_MimeType();
499 $ext = $m->toExt($mt);
504 'contentid' => md5($url)
508 file_put_contents($cache, json_encode($ret));
509 $ret['file'] = $cache . '.data';
516 foreach($this->urlmap as $o=>$n) {
517 if (strpos($in,$o) === 0) {
518 return $n . substr($in,strlen($o));