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 $ff = HTML_FlexyFramework::get();
81 if (!empty($ff->Core_Mailer['debug'])) {
82 $this->debug = $ff->Core_Mailer['debug'];
89 * ---------------- Global Tools ---------------
95 $templateFile = $this->template;
96 $args = $this->contents;
98 $content = clone($this->page);
100 foreach((array)$args as $k=>$v) {
104 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
106 $ff = HTML_FlexyFramework::get();
107 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
108 if (isset($ff->Pman['HTTP_HOST'])) {
109 $http_host = $ff->Pman['HTTP_HOST'];
113 $content->HTTP_HOST = $http_host;
118 // this should be done by having multiple template sources...!!!
120 require_once 'HTML/Template/Flexy.php';
123 // 'forceCompile' => true,
124 'site_prefix' => false,
126 if (!empty($this->templateDir)) {
127 $tmp_opts['templateDir'] = $this->templateDir;
129 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
130 if (!empty($fopts['DB_DataObject_translator'])) {
131 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
133 if (!empty($fopts['locale'])) {
134 $tmp_opts['locale'] = $fopts['locale'];
137 // local opt's overwrite
138 if (!empty($this->locale)) {
139 $tmp_opts['locale'] = $this->locale;
143 $html_tmp_opts = $tmp_opts;
144 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
145 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
146 // then we have a multi-part email...
148 if (!empty($this->html_locale)) {
149 $html_tmp_opts['locale'] = $this->html_locale;
151 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
153 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
154 $htmlbody = $htmltemplate->bufferedOutputObject($content);
156 $this->htmlbody = $htmlbody;
158 // for the html body, we may want to convert the attachments to images.
159 // var_dump($htmlbody);exit;
160 if ($this->replaceImages) {
161 $htmlbody = $this->htmlbodytoCID($htmlbody);
163 if ($this->css_embed) {
164 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
168 $tmp_opts['nonHTML'] = true;
171 //print_R($tmp_opts);
172 // $tmp_opts['force'] = true;
173 $template = new HTML_Template_Flexy( $tmp_opts );
175 $template->compile('mail/'. $templateFile.'.txt');
177 /* use variables from this object to ouput data. */
178 $mailtext = $template->bufferedOutputObject($content);
179 //print_r($mailtext);exit;
183 //echo "<PRE>";print_R($mailtext);
185 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
186 require_once 'Mail/mimeDecode.php';
187 require_once 'Mail.php';
189 $decoder = new Mail_mimeDecode($mailtext);
190 $parts = $decoder->getSendArray();
191 if (PEAR::isError($parts)) {
193 //echo "PROBLEM: {$parts->message}";
199 require_once 'Mail/mime.php';
200 $mime = new Mail_mime(array(
202 //'html_encoding' => 'base64',
203 'html_charset' => 'utf-8',
204 'text_charset' => 'utf-8',
205 'head_charset' => 'utf-8',
207 // clean up the headers...
210 $parts[1]['Message-Id'] = '<' . $content->msgid .
211 '@' . $content->HTTP_HOST .'>';
214 if ($htmlbody !== false) {
215 // got a html headers...
217 if (isset($parts[1]['Content-Type'])) {
218 unset($parts[1]['Content-Type']);
220 $mime->setTXTBody($parts[2]);
221 $mime->setHTMLBody($htmlbody);
222 // var_dump($mime);exit;
223 foreach($this->images as $cid=>$cdata) {
228 $cid.'.'.$cdata['ext'],
236 if(!empty($this->attachments)){
237 //if got a attachments
238 $header = $mime->headers($parts[1]);
240 if (isset($parts[1]['Content-Type'])) {
241 unset($parts[1]['Content-Type']);
246 if(preg_match('/text\/html/', $header['Content-Type'])){
247 $mime->setHTMLBody($parts[2]);
248 $mime->setTXTBody('This message is in HTML only');
250 $mime->setTXTBody($parts[2]);
251 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
254 foreach($this->attachments as $attch){
255 $mime->addAttachment(
258 (!empty($attch['name'])) ? $attch['name'] : '',
267 $parts[2] = $mime->get();
268 $parts[1] = $mime->headers($parts[1]);
272 // print_r($parts[2]);
274 // list($recipents,$headers,$body) = $parts;
276 'recipents' => $parts[0],
277 'headers' => $parts[1],
282 function send($email = false)
285 $pg = HTML_FlexyFramework::get()->page;
288 $email = is_array($email) ? $email : $this->toData();
289 if (is_a($email, 'PEAR_Error')) {
290 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
296 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
298 ///$recipents = array($this->email);
299 $mailOptions = PEAR::getStaticProperty('Mail','options');
300 //print_R($mailOptions);exit;
302 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
303 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
307 $mail = Mail::factory($this->mail_method,$mailOptions);
309 $mail->debug = $this->debug;
312 $email['headers']['Date'] = date('r');
313 if (PEAR::isError($mail)) {
314 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
319 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
321 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
322 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
325 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
326 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
327 error_reporting($oe);
329 $pg->addEvent("COREMAILER-SENT", false,
330 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
331 'Subject: ' . @$email['headers']['Subject']
334 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
340 function htmlbodytoCID($html)
342 $dom = new DOMDocument();
343 // this may raise parse errors as some html may be a component..
344 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
345 $imgs= $dom->getElementsByTagName('img');
347 foreach ($imgs as $i=>$img) {
348 $url = $img->getAttribute('src');
349 if (preg_match('#^cid:#', $url)) {
352 $me = $img->getAttribute('mailembed');
357 $conv = $this->fetchImage($url);
358 $this->images[$conv['contentid']] = $conv;
360 $img->setAttribute('src', 'cid:' . $conv['contentid']);
364 return $dom->saveHTML();
369 function htmlbodyCssEmbed($html)
371 $ff = HTML_FlexyFramework::get();
372 $dom = new DOMDocument();
374 // this may raise parse errors as some html may be a component..
375 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
376 $links = $dom->getElementsByTagName('link');
378 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
381 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
383 foreach ($lc as $i=>$link) {
384 //var_dump($link->getAttribute('href'));
386 if ($link->getAttribute('rel') != 'stylesheet') {
389 $url = $link->getAttribute('href');
390 $file = $ff->rootDir . $url;
392 if (!preg_match('#^http://#', $url)) {
393 $file = $ff->rootDir . $url;
395 if (!file_exists($file)) {
397 $link->setAttribute('href', 'missing:' . $file);
404 $par = $link->parentNode;
405 $par->removeChild($link);
406 $s = $dom->createElement('style');
407 $e = $dom->createTextNode(file_get_contents($file));
409 $par->appendChild($s);
412 return $dom->saveHTML();
419 function fetchImage($url)
422 echo "FETCH : $url\n";
424 if ($url[0] == '/') {
425 $ff = HTML_FlexyFramework::get();
426 $file = $ff->rootDir . $url;
427 require_once 'File/MimeType.php';
428 $m = new File_MimeType();
429 $mt = $m->fromFilename($file);
430 $ext = $m->toExt($mt);
435 'contentid' => md5($file),
443 //print_R($url); exit;
446 if (preg_match('#^file:///#', $url)) {
447 $file = preg_replace('#^file://#', '', $url);
448 require_once 'File/MimeType.php';
449 $m = new File_MimeType();
450 $mt = $m->fromFilename($file);
451 $ext = $m->toExt($mt);
456 'contentid' => md5($file),
463 // 2 files --- the info file.. and the actual file...
466 $uinfo = posix_getpwuid( posix_getuid () );
467 $user = $uinfo['name'];
469 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
470 if ($this->cache_images &&
471 file_exists($cache) &&
472 filemtime($cache) > strtotime('NOW - 1 WEEK')
474 $ret = json_decode(file_get_contents($cache), true);
475 $ret['file'] = $cache . '.data';
478 if (!file_exists(dirname($cache))) {
479 mkdir(dirname($cache),0700, true);
482 require_once 'HTTP/Request.php';
483 $a = new HTTP_Request($url);
485 file_put_contents($cache .'.data', $a->getResponseBody());
487 $mt = $a->getResponseHeader('Content-Type');
489 require_once 'File/MimeType.php';
490 $m = new File_MimeType();
491 $ext = $m->toExt($mt);
496 'contentid' => md5($url)
500 file_put_contents($cache, json_encode($ret));
501 $ret['file'] = $cache . '.data';