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,
26 locale => 'en' .... or zh_hk....
27 rcpts => array() // override recipients..
31 name : (optional) - uses basename of file
35 mail_method : (SMTP or SMTPMX)
39 * recipents is gathered from the resulting template
47 * $x->toData(); // returns data needed for notify?? - notify should really
48 * // just use this to pass around later..
54 class Pman_Core_Mailer {
56 var $page = false; /* usually a html_flexyframework_page */
57 var $contents = false; /* object or array */
58 var $template = false; /* string */
59 var $replaceImages = false; /* boolean */
61 var $templateDir = false;
62 var $locale = false; // eg. 'en' or 'zh_HK'
65 var $html_locale = false; // eg. 'en' or 'zh_HK'
66 var $images = array(); // generated list of cid images for sending
67 var $attachments = false;
68 var $css_inline = false; // not supported
69 var $css_embed = false; // put the css tags into the body.
71 var $mail_method = 'SMTP';
73 var $cache_images = true;
75 function Pman_Core_Mailer($args) {
76 foreach($args as $k=>$v) {
80 // allow core mailer debug setting.
81 $ff = HTML_FlexyFramework::get();
82 if (!empty($ff->Core_Mailer['debug'])) {
83 $this->debug = $ff->Core_Mailer['debug'];
90 * ---------------- Global Tools ---------------
96 $templateFile = $this->template;
97 $args = $this->contents;
99 $content = clone($this->page);
101 foreach((array)$args as $k=>$v) {
105 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
107 $ff = HTML_FlexyFramework::get();
108 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
109 if (isset($ff->Pman['HTTP_HOST'])) {
110 $http_host = $ff->Pman['HTTP_HOST'];
114 $content->HTTP_HOST = $http_host;
119 // this should be done by having multiple template sources...!!!
121 require_once 'HTML/Template/Flexy.php';
124 // 'forceCompile' => true,
125 'site_prefix' => false,
127 if (!empty($this->templateDir)) {
128 $tmp_opts['templateDir'] = $this->templateDir;
130 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
131 if (!empty($fopts['DB_DataObject_translator'])) {
132 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
134 if (!empty($fopts['locale'])) {
135 $tmp_opts['locale'] = $fopts['locale'];
138 // local opt's overwrite
139 if (!empty($this->locale)) {
140 $tmp_opts['locale'] = $this->locale;
144 $html_tmp_opts = $tmp_opts;
145 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
146 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
147 // then we have a multi-part email...
149 if (!empty($this->html_locale)) {
150 $html_tmp_opts['locale'] = $this->html_locale;
152 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
154 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
155 $htmlbody = $htmltemplate->bufferedOutputObject($content);
157 $this->htmlbody = $htmlbody;
159 // for the html body, we may want to convert the attachments to images.
160 // var_dump($htmlbody);exit;
161 if ($this->replaceImages) {
162 $htmlbody = $this->htmlbodytoCID($htmlbody);
164 if ($this->css_embed) {
165 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
169 $tmp_opts['nonHTML'] = true;
172 //print_R($tmp_opts);
173 // $tmp_opts['force'] = true;
174 $template = new HTML_Template_Flexy( $tmp_opts );
176 $template->compile('mail/'. $templateFile.'.txt');
178 /* use variables from this object to ouput data. */
179 $mailtext = $template->bufferedOutputObject($content);
180 //print_r($mailtext);exit;
184 //echo "<PRE>";print_R($mailtext);
186 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
187 require_once 'Mail/mimeDecode.php';
188 require_once 'Mail.php';
190 $decoder = new Mail_mimeDecode($mailtext);
191 $parts = $decoder->getSendArray();
192 if (PEAR::isError($parts)) {
194 //echo "PROBLEM: {$parts->message}";
200 require_once 'Mail/mime.php';
201 $mime = new Mail_mime(array(
203 //'html_encoding' => 'base64',
204 'html_charset' => 'utf-8',
205 'text_charset' => 'utf-8',
206 'head_charset' => 'utf-8',
208 // clean up the headers...
211 $parts[1]['Message-Id'] = '<' . $content->msgid .
212 '@' . $content->HTTP_HOST .'>';
215 if ($htmlbody !== false) {
216 // got a html headers...
218 if (isset($parts[1]['Content-Type'])) {
219 unset($parts[1]['Content-Type']);
221 $mime->setTXTBody($parts[2]);
222 $mime->setHTMLBody($htmlbody);
223 // var_dump($mime);exit;
224 foreach($this->images as $cid=>$cdata) {
229 $cid.'.'.$cdata['ext'],
237 if(!empty($this->attachments)){
238 //if got a attachments
239 $header = $mime->headers($parts[1]);
241 if (isset($parts[1]['Content-Type'])) {
242 unset($parts[1]['Content-Type']);
247 if(preg_match('/text\/html/', $header['Content-Type'])){
248 $mime->setHTMLBody($parts[2]);
249 $mime->setTXTBody('This message is in HTML only');
251 $mime->setTXTBody($parts[2]);
252 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
255 foreach($this->attachments as $attch){
256 $mime->addAttachment(
259 (!empty($attch['name'])) ? $attch['name'] : '',
268 $parts[2] = $mime->get();
269 $parts[1] = $mime->headers($parts[1]);
273 // print_r($parts[2]);
275 // list($recipents,$headers,$body) = $parts;
277 'recipents' => $parts[0],
278 'headers' => $parts[1],
283 function send($email = false)
286 $pg = HTML_FlexyFramework::get()->page;
289 $email = is_array($email) ? $email : $this->toData();
290 if (is_a($email, 'PEAR_Error')) {
291 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
297 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
299 ///$recipents = array($this->email);
300 $mailOptions = PEAR::getStaticProperty('Mail','options');
301 //print_R($mailOptions);exit;
303 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
304 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
308 $mail = Mail::factory($this->mail_method,$mailOptions);
310 $mail->debug = $this->debug;
313 $email['headers']['Date'] = date('r');
314 if (PEAR::isError($mail)) {
315 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
320 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
322 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
323 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
326 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
327 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
328 error_reporting($oe);
330 $pg->addEvent("COREMAILER-SENT", false,
331 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
332 'Subject: ' . @$email['headers']['Subject']
335 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
341 function htmlbodytoCID($html)
343 $dom = new DOMDocument();
344 // this may raise parse errors as some html may be a component..
345 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
346 $imgs= $dom->getElementsByTagName('img');
348 foreach ($imgs as $i=>$img) {
349 $url = $img->getAttribute('src');
350 if (preg_match('#^cid:#', $url)) {
353 $me = $img->getAttribute('mailembed');
358 $conv = $this->fetchImage($url);
359 $this->images[$conv['contentid']] = $conv;
361 $img->setAttribute('src', 'cid:' . $conv['contentid']);
365 return $dom->saveHTML();
370 function htmlbodyCssEmbed($html)
372 $ff = HTML_FlexyFramework::get();
373 $dom = new DOMDocument();
375 // this may raise parse errors as some html may be a component..
376 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
377 $links = $dom->getElementsByTagName('link');
379 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
382 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
384 foreach ($lc as $i=>$link) {
385 //var_dump($link->getAttribute('href'));
387 if ($link->getAttribute('rel') != 'stylesheet') {
390 $url = $link->getAttribute('href');
391 $file = $ff->rootDir . $url;
393 if (!preg_match('#^http://#', $url)) {
394 $file = $ff->rootDir . $url;
396 if (!file_exists($file)) {
398 $link->setAttribute('href', 'missing:' . $file);
405 $par = $link->parentNode;
406 $par->removeChild($link);
407 $s = $dom->createElement('style');
408 $e = $dom->createTextNode(file_get_contents($file));
410 $par->appendChild($s);
413 return $dom->saveHTML();
420 function fetchImage($url)
423 echo "FETCH : $url\n";
425 if ($url[0] == '/') {
426 $ff = HTML_FlexyFramework::get();
427 $file = $ff->rootDir . $url;
428 require_once 'File/MimeType.php';
429 $m = new File_MimeType();
430 $mt = $m->fromFilename($file);
431 $ext = $m->toExt($mt);
436 'contentid' => md5($file),
444 //print_R($url); exit;
447 if (preg_match('#^file:///#', $url)) {
448 $file = preg_replace('#^file://#', '', $url);
449 require_once 'File/MimeType.php';
450 $m = new File_MimeType();
451 $mt = $m->fromFilename($file);
452 $ext = $m->toExt($mt);
457 'contentid' => md5($file),
464 // 2 files --- the info file.. and the actual file...
467 $uinfo = posix_getpwuid( posix_getuid () );
468 $user = $uinfo['name'];
470 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
471 if ($this->cache_images &&
472 file_exists($cache) &&
473 filemtime($cache) > strtotime('NOW - 1 WEEK')
475 $ret = json_decode(file_get_contents($cache), true);
476 $ret['file'] = $cache . '.data';
479 if (!file_exists(dirname($cache))) {
480 mkdir(dirname($cache),0700, true);
483 require_once 'HTTP/Request.php';
484 $a = new HTTP_Request($url);
486 file_put_contents($cache .'.data', $a->getResponseBody());
488 $mt = $a->getResponseHeader('Content-Type');
490 require_once 'File/MimeType.php';
491 $m = new File_MimeType();
492 $ext = $m->toExt($mt);
497 'contentid' => md5($url)
501 file_put_contents($cache, json_encode($ret));
502 $ret['file'] = $cache . '.data';