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 replaceImages => true|false,
25 locale => 'en' .... or zh_hk....
26 rcpts => array() // override recipients..
30 name : (optional) - uses basename of file
34 mail_method : (SMTP or SMTPMX)
38 * recipents is gathered from the resulting template
46 * $x->toData(); // returns data needed for notify?? - notify should really
47 * // just use this to pass around later..
53 class Pman_Core_Mailer {
55 var $page = false; /* usually a html_flexyframework_page */
56 var $contents = false; /* object or array */
57 var $template = false; /* string */
58 var $replaceImages = false; /* boolean */
60 var $templateDir = false;
61 var $locale = false; // eg. 'en' or 'zh_HK'
64 var $html_locale = false; // eg. 'en' or 'zh_HK'
65 var $images = array(); // generated list of cid images for sending
66 var $attachments = false;
67 var $css_inline = false; // not supported
68 var $css_embed = false; // put the css tags into the body.
70 var $mail_method = 'SMTP';
72 function Pman_Core_Mailer($args) {
73 foreach($args as $k=>$v) {
80 * ---------------- Global Tools ---------------
86 $templateFile = $this->template;
87 $args = $this->contents;
89 $content = clone($this->page);
91 foreach((array)$args as $k=>$v) {
95 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
97 $ff = HTML_FlexyFramework::get();
98 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
99 if (isset($ff->Pman['HTTP_HOST'])) {
100 $http_host = $ff->Pman['HTTP_HOST'];
104 $content->HTTP_HOST = $http_host;
109 // this should be done by having multiple template sources...!!!
111 require_once 'HTML/Template/Flexy.php';
114 // 'forceCompile' => true,
115 'site_prefix' => false,
117 if (!empty($this->templateDir)) {
118 $tmp_opts['templateDir'] = $this->templateDir;
120 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
121 if (!empty($fopts['DB_DataObject_translator'])) {
122 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
124 if (!empty($fopts['locale'])) {
125 $tmp_opts['locale'] = $fopts['locale'];
128 // local opt's overwrite
129 if (!empty($this->locale)) {
130 $tmp_opts['locale'] = $this->locale;
134 $html_tmp_opts = $tmp_opts;
135 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
136 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
137 // then we have a multi-part email...
139 if (!empty($this->html_locale)) {
140 $html_tmp_opts['locale'] = $this->html_locale;
142 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
144 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
145 $htmlbody = $htmltemplate->bufferedOutputObject($content);
147 $this->htmlbody = $htmlbody;
149 // for the html body, we may want to convert the attachments to images.
150 // var_dump($htmlbody);exit;
151 if ($this->replaceImages) {
152 $htmlbody = $this->htmlbodytoCID($htmlbody);
154 if ($this->css_embed) {
155 $htmlbody = $this->htmlbodyCssEmbed($htmlbody);
159 $tmp_opts['nonHTML'] = true;
162 //print_R($tmp_opts);
163 // $tmp_opts['force'] = true;
164 $template = new HTML_Template_Flexy( $tmp_opts );
166 $template->compile('mail/'. $templateFile.'.txt');
168 /* use variables from this object to ouput data. */
169 $mailtext = $template->bufferedOutputObject($content);
170 //print_r($mailtext);exit;
174 //echo "<PRE>";print_R($mailtext);
176 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
177 require_once 'Mail/mimeDecode.php';
178 require_once 'Mail.php';
180 $decoder = new Mail_mimeDecode($mailtext);
181 $parts = $decoder->getSendArray();
182 if (PEAR::isError($parts)) {
184 //echo "PROBLEM: {$parts->message}";
190 require_once 'Mail/mime.php';
191 $mime = new Mail_mime(array(
193 //'html_encoding' => 'base64',
194 'html_charset' => 'utf-8',
195 'text_charset' => 'utf-8',
196 'head_charset' => 'utf-8',
198 // clean up the headers...
201 $parts[1]['Message-Id'] = '<' . $content->msgid .
202 '@' . $content->HTTP_HOST .'>';
205 if ($htmlbody !== false) {
206 // got a html headers...
208 if (isset($parts[1]['Content-Type'])) {
209 unset($parts[1]['Content-Type']);
211 $mime->setTXTBody($parts[2]);
212 $mime->setHTMLBody($htmlbody);
213 // var_dump($mime);exit;
214 foreach($this->images as $cid=>$cdata) {
219 $cid.'.'.$cdata['ext'],
227 if(!empty($this->attachments)){
228 //if got a attachments
229 $header = $mime->headers($parts[1]);
231 if (isset($parts[1]['Content-Type'])) {
232 unset($parts[1]['Content-Type']);
237 if(preg_match('/text\/html/', $header['Content-Type'])){
238 $mime->setHTMLBody($parts[2]);
239 $mime->setTXTBody('This message is in HTML only');
241 $mime->setTXTBody($parts[2]);
242 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
245 foreach($this->attachments as $attch){
246 $mime->addAttachment(
249 (!empty($attch['name'])) ? $attch['name'] : '',
258 $parts[2] = $mime->get();
259 $parts[1] = $mime->headers($parts[1]);
263 // print_r($parts[2]);
265 // list($recipents,$headers,$body) = $parts;
267 'recipents' => $parts[0],
268 'headers' => $parts[1],
273 function send($email = false)
276 $pg = HTML_FlexyFramework::get()->page;
279 $email = is_array($email) ? $email : $this->toData();
280 if (is_a($email, 'PEAR_Error')) {
281 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
287 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
289 ///$recipents = array($this->email);
290 $mailOptions = PEAR::getStaticProperty('Mail','options');
291 //print_R($mailOptions);exit;
293 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
294 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
298 $mail = Mail::factory($this->mail_method,$mailOptions);
300 $mail->debug = $this->debug;
303 $email['headers']['Date'] = date('r');
304 if (PEAR::isError($mail)) {
305 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
310 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
312 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
313 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
316 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
317 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
318 error_reporting($oe);
320 $pg->addEvent("COREMAILER-SENT", false,
321 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
322 'Subject: ' . @$email['headers']['Subject']
325 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
331 function htmlbodytoCID($html)
333 $dom = new DOMDocument();
334 // this may raise parse errors as some html may be a component..
335 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
336 $imgs= $dom->getElementsByTagName('img');
338 foreach ($imgs as $i=>$img) {
339 $url = $img->getAttribute('src');
340 if (preg_match('#^cid:#', $url)) {
343 $me = $img->getAttribute('mailembed');
348 $conv = $this->fetchImage($url);
349 $this->images[$conv['contentid']] = $conv;
351 $img->setAttribute('src', 'cid:' . $conv['contentid']);
355 return $dom->saveHTML();
360 function htmlbodyCssEmbed($html)
362 $ff = HTML_FlexyFramework::get();
363 $dom = new DOMDocument();
365 // this may raise parse errors as some html may be a component..
366 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
367 $links = $dom->getElementsByTagName('link');
369 foreach ($links as $link) { // duplicate as links is dynamic and we change it..!
372 //<link rel="stylesheet" type="text/css" href="{rootURL}/roojs1/css-mailer/mailer.css">
374 foreach ($lc as $i=>$link) {
375 //var_dump($link->getAttribute('href'));
377 if ($link->getAttribute('rel') != 'stylesheet') {
380 $url = $link->getAttribute('href');
381 $file = $ff->rootDir . $url;
383 if (!preg_match('#^http://#', $url)) {
384 $file = $ff->rootDir . $url;
386 if (!file_exists($file)) {
388 $link->setAttribute('href', 'missing:' . $file);
395 $par = $link->parentNode;
396 $par->removeChild($link);
397 $s = $dom->createElement('style');
398 $e = $dom->createTextNode(file_get_contents($file));
400 $par->appendChild($s);
403 return $dom->saveHTML();
410 function fetchImage($url)
413 echo "FETCH : $url\n";
415 if ($url[0] == '/') {
416 $ff = HTML_FlexyFramework::get();
417 $file = $ff->rootDir . $url;
418 require_once 'File/MimeType.php';
419 $m = new File_MimeType();
420 $mt = $m->fromFilename($file);
421 $ext = $m->toExt($mt);
426 'contentid' => md5($file),
434 //print_R($url); exit;
437 if (preg_match('#^file:///#', $url)) {
438 $file = preg_replace('#^file://#', '', $url);
439 require_once 'File/MimeType.php';
440 $m = new File_MimeType();
441 $mt = $m->fromFilename($file);
442 $ext = $m->toExt($mt);
447 'contentid' => md5($file),
454 // 2 files --- the info file.. and the actual file...
457 $uinfo = posix_getpwuid( posix_getuid () );
458 $user = $uinfo['name'];
460 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
461 if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
462 $ret = json_decode(file_get_contents($cache), true);
463 $ret['file'] = $cache . '.data';
466 if (!file_exists(dirname($cache))) {
467 mkdir(dirname($cache),0700, true);
470 require_once 'HTTP/Request.php';
471 $a = new HTTP_Request($url);
473 file_put_contents($cache .'.data', $a->getResponseBody());
475 $mt = $a->getResponseHeader('Content-Type');
477 require_once 'File/MimeType.php';
478 $m = new File_MimeType();
479 $ext = $m->toExt($mt);
484 'contentid' => md5($url)
488 file_put_contents($cache, json_encode($ret));
489 $ret['file'] = $cache . '.data';