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'
68 var $html_locale = false; // eg. 'en' or 'zh_HK'
69 var $images = array(); // generated list of cid images for sending
70 var $attachments = false;
71 var $css_inline = false; // not supported
72 var $css_embed = false; // put the css tags into the body.
74 var $mail_method = 'SMTP';
76 var $cache_images = true;
78 function Pman_Core_Mailer($args) {
79 foreach($args as $k=>$v) {
83 // allow core mailer debug setting.
84 $ff = HTML_FlexyFramework::get();
86 if (!empty($ff->Core_Mailer['debug'])) {
87 $this->debug = $ff->Core_Mailer['debug'];
94 * ---------------- Global Tools ---------------
100 $templateFile = $this->template;
101 $args = $this->contents;
103 $content = clone($this->page);
105 foreach((array)$args as $k=>$v) {
109 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
111 $ff = HTML_FlexyFramework::get();
112 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
113 if (isset($ff->Pman['HTTP_HOST'])) {
114 $http_host = $ff->Pman['HTTP_HOST'];
118 $content->HTTP_HOST = $http_host;
123 // this should be done by having multiple template sources...!!!
125 require_once 'HTML/Template/Flexy.php';
128 // 'forceCompile' => true,
129 'site_prefix' => false,
131 if (!empty($this->templateDir)) {
132 $tmp_opts['templateDir'] = $this->templateDir;
134 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
135 if (!empty($fopts['DB_DataObject_translator'])) {
136 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
138 if (!empty($fopts['locale'])) {
139 $tmp_opts['locale'] = $fopts['locale'];
142 // local opt's overwrite
143 if (!empty($this->locale)) {
144 $tmp_opts['locale'] = $this->locale;
148 $html_tmp_opts = $tmp_opts;
149 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
150 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
151 // then we have a multi-part email...
153 if (!empty($this->html_locale)) {
154 $html_tmp_opts['locale'] = $this->html_locale;
156 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
158 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
159 $htmlbody = $htmltemplate->bufferedOutputObject($content);
161 $this->htmlbody = $htmlbody;
163 // for the html body, we may want to convert the attachments to images.
164 // var_dump($htmlbody);exit;
165 if ($this->replaceImages) {
166 $htmlbody = $this->htmlbodytoCID($htmlbody);
168 if ($this->css_embed) {
169 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
173 $tmp_opts['nonHTML'] = true;
176 //print_R($tmp_opts);
177 // $tmp_opts['force'] = true;
178 $template = new HTML_Template_Flexy( $tmp_opts );
180 $template->compile('mail/'. $templateFile.'.txt');
182 /* use variables from this object to ouput data. */
183 $mailtext = $template->bufferedOutputObject($content);
184 //print_r($mailtext);exit;
188 //echo "<PRE>";print_R($mailtext);
190 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
191 require_once 'Mail/mimeDecode.php';
192 require_once 'Mail.php';
194 $decoder = new Mail_mimeDecode($mailtext);
195 $parts = $decoder->getSendArray();
196 if (PEAR::isError($parts)) {
198 //echo "PROBLEM: {$parts->message}";
204 require_once 'Mail/mime.php';
205 $mime = new Mail_mime(array(
207 //'html_encoding' => 'base64',
208 'html_charset' => 'utf-8',
209 'text_charset' => 'utf-8',
210 'head_charset' => 'utf-8',
212 // clean up the headers...
215 $parts[1]['Message-Id'] = '<' . $content->msgid .
216 '@' . $content->HTTP_HOST .'>';
219 if ($htmlbody !== false) {
220 // got a html headers...
222 if (isset($parts[1]['Content-Type'])) {
223 unset($parts[1]['Content-Type']);
225 $mime->setTXTBody($parts[2]);
226 $mime->setHTMLBody($htmlbody);
227 // var_dump($mime);exit;
228 foreach($this->images as $cid=>$cdata) {
233 $cid.'.'.$cdata['ext'],
241 if(!empty($this->attachments)){
242 //if got a attachments
243 $header = $mime->headers($parts[1]);
245 if (isset($parts[1]['Content-Type'])) {
246 unset($parts[1]['Content-Type']);
251 if(preg_match('/text\/html/', $header['Content-Type'])){
252 $mime->setHTMLBody($parts[2]);
253 $mime->setTXTBody('This message is in HTML only');
255 $mime->setTXTBody($parts[2]);
256 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
259 foreach($this->attachments as $attch){
260 $mime->addAttachment(
263 (!empty($attch['name'])) ? $attch['name'] : '',
272 $parts[2] = $mime->get();
273 $parts[1] = $mime->headers($parts[1]);
277 // print_r($parts[2]);
279 // list($recipents,$headers,$body) = $parts;
281 'recipents' => $parts[0],
282 'headers' => $parts[1],
287 function send($email = false)
290 $pg = HTML_FlexyFramework::get()->page;
293 $email = is_array($email) ? $email : $this->toData();
294 if (is_a($email, 'PEAR_Error')) {
295 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
301 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
303 ///$recipents = array($this->email);
304 $mailOptions = PEAR::getStaticProperty('Mail','options');
305 //print_R($mailOptions);exit;
307 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
308 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
312 $mail = Mail::factory($this->mail_method,$mailOptions);
314 $mail->debug = $this->debug;
317 $email['headers']['Date'] = date('r');
318 if (PEAR::isError($mail)) {
319 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
324 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
326 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
327 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
330 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
331 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
332 error_reporting($oe);
334 $pg->addEvent("COREMAILER-SENT", false,
335 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
336 'Subject: ' . @$email['headers']['Subject']
339 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
345 function htmlbodytoCID($html)
347 $dom = new DOMDocument();
348 // this may raise parse errors as some html may be a component..
349 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
350 $imgs= $dom->getElementsByTagName('img');
352 foreach ($imgs as $i=>$img) {
353 $url = $img->getAttribute('src');
354 if (preg_match('#^cid:#', $url)) {
357 $me = $img->getAttribute('mailembed');
362 $conv = $this->fetchImage($url);
363 $this->images[$conv['contentid']] = $conv;
365 $img->setAttribute('src', 'cid:' . $conv['contentid']);
369 return $dom->saveHTML();
374 function htmlbodyCssEmbed($html)
376 $ff = HTML_FlexyFramework::get();
377 $dom = new DOMDocument();
379 // this may raise parse errors as some html may be a component..
380 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
381 $links = $dom->getElementsByTagName('link');
383 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
386 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
388 foreach ($lc as $i=>$link) {
389 //var_dump($link->getAttribute('href'));
391 if ($link->getAttribute('rel') != 'stylesheet') {
394 $url = $link->getAttribute('href');
395 $file = $ff->rootDir . $url;
397 if (!preg_match('#^(http|https)://#', $url)) {
398 $file = $ff->rootDir . $url;
400 if (!file_exists($file)) {
402 $link->setAttribute('href', 'missing:' . $file);
409 $par = $link->parentNode;
410 $par->removeChild($link);
411 $s = $dom->createElement('style');
412 $e = $dom->createTextNode(file_get_contents($file));
414 $par->appendChild($s);
417 return $dom->saveHTML();
424 function fetchImage($url)
427 echo "FETCH : $url\n";
429 if ($url[0] == '/') {
430 $ff = HTML_FlexyFramework::get();
431 $file = $ff->rootDir . $url;
432 require_once 'File/MimeType.php';
433 $m = new File_MimeType();
434 $mt = $m->fromFilename($file);
435 $ext = $m->toExt($mt);
440 'contentid' => md5($file),
448 //print_R($url); exit;
451 if (preg_match('#^file:///#', $url)) {
452 $file = preg_replace('#^file://#', '', $url);
453 require_once 'File/MimeType.php';
454 $m = new File_MimeType();
455 $mt = $m->fromFilename($file);
456 $ext = $m->toExt($mt);
461 'contentid' => md5($file),
468 // 2 files --- the info file.. and the actual file...
471 $uinfo = posix_getpwuid( posix_getuid () );
472 $user = $uinfo['name'];
474 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
475 if ($this->cache_images &&
476 file_exists($cache) &&
477 filemtime($cache) > strtotime('NOW - 1 WEEK')
479 $ret = json_decode(file_get_contents($cache), true);
480 $ret['file'] = $cache . '.data';
483 if (!file_exists(dirname($cache))) {
484 mkdir(dirname($cache),0700, true);
487 require_once 'HTTP/Request.php';
488 $a = new HTTP_Request($url);
490 file_put_contents($cache .'.data', $a->getResponseBody());
492 $mt = $a->getResponseHeader('Content-Type');
494 require_once 'File/MimeType.php';
495 $m = new File_MimeType();
496 $ext = $m->toExt($mt);
501 'contentid' => md5($url)
505 file_put_contents($cache, json_encode($ret));
506 $ret['file'] = $cache . '.data';
513 foreach($this->urlmap as $o=>$n) {
514 if (strpos($in,$o) === 0) {
515 return $n . substr($in,strlen($o));