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);
157 $tmp_opts['nonHTML'] = true;
160 //print_R($tmp_opts);
161 // $tmp_opts['force'] = true;
162 $template = new HTML_Template_Flexy( $tmp_opts );
164 $template->compile('mail/'. $templateFile.'.txt');
166 /* use variables from this object to ouput data. */
167 $mailtext = $template->bufferedOutputObject($content);
168 //print_r($mailtext);exit;
172 //echo "<PRE>";print_R($mailtext);
174 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
175 require_once 'Mail/mimeDecode.php';
176 require_once 'Mail.php';
178 $decoder = new Mail_mimeDecode($mailtext);
179 $parts = $decoder->getSendArray();
180 if (PEAR::isError($parts)) {
182 //echo "PROBLEM: {$parts->message}";
188 require_once 'Mail/mime.php';
189 $mime = new Mail_mime(array(
191 //'html_encoding' => 'base64',
192 'html_charset' => 'utf-8',
193 'text_charset' => 'utf-8',
194 'head_charset' => 'utf-8',
196 // clean up the headers...
199 $parts[1]['Message-Id'] = '<' . $content->msgid .
200 '@' . $content->HTTP_HOST .'>';
203 if ($htmlbody !== false) {
204 // got a html headers...
206 if (isset($parts[1]['Content-Type'])) {
207 unset($parts[1]['Content-Type']);
209 $mime->setTXTBody($parts[2]);
210 $mime->setHTMLBody($htmlbody);
211 // var_dump($mime);exit;
212 foreach($this->images as $cid=>$cdata) {
217 $cid.'.'.$cdata['ext'],
225 if(!empty($this->attachments)){
226 //if got a attachments
227 $header = $mime->headers($parts[1]);
229 if (isset($parts[1]['Content-Type'])) {
230 unset($parts[1]['Content-Type']);
235 if(preg_match('/text\/html/', $header['Content-Type'])){
236 $mime->setHTMLBody($parts[2]);
237 $mime->setTXTBody('This message is in HTML only');
239 $mime->setTXTBody($parts[2]);
240 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
243 foreach($this->attachments as $attch){
244 $mime->addAttachment(
247 (!empty($attch['name'])) ? $attch['name'] : '',
256 $parts[2] = $mime->get();
257 $parts[1] = $mime->headers($parts[1]);
261 // print_r($parts[2]);
263 // list($recipents,$headers,$body) = $parts;
265 'recipents' => $parts[0],
266 'headers' => $parts[1],
271 function send($email = false)
274 $pg = HTML_FlexyFramework::get()->page;
277 $email = is_array($email) ? $email : $this->toData();
278 if (is_a($email, 'PEAR_Error')) {
279 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
285 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
287 ///$recipents = array($this->email);
288 $mailOptions = PEAR::getStaticProperty('Mail','options');
289 //print_R($mailOptions);exit;
291 if ($this->mail_method == 'SMTPMX' && empty($mailOptions['mailname'])) {
292 $pg->jerr("Mail[mailname] is not set - this is required for SMTPMX");
296 $mail = Mail::factory($this->mail_method,$mailOptions);
298 $mail->debug = $this->debug;
301 $email['headers']['Date'] = date('r');
302 if (PEAR::isError($mail)) {
303 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
308 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
310 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
311 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
314 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
315 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
316 error_reporting($oe);
318 $pg->addEvent("COREMAILER-SENT", false,
319 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
320 'Subject: ' . @$email['headers']['Subject']
323 $pg->addEvent("COREMAILER-FAIL", false, $ret->toString());
329 function htmlbodytoCID($html)
331 $dom = new DOMDocument();
332 // this may raise parse errors as some html may be a component..
333 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
334 $imgs= $dom->getElementsByTagName('img');
336 foreach ($imgs as $i=>$img) {
337 $url = $img->getAttribute('src');
338 if (preg_match('#^cid:#', $url)) {
341 $conv = $this->fetchImage($url);
342 $this->images[$conv['contentid']] = $conv;
344 $img->setAttribute('src', 'cid:' . $conv['contentid']);
348 return $dom->saveHTML();
353 function fetchImage($url)
356 if ($url[0] == '/') {
357 $ff = HTML_FlexyFramework::get();
358 $file = $ff->rootDir . $url;
359 require_once 'File/MimeType.php';
360 $m = new File_MimeType();
361 $mt = $m->fromFilename($file);
362 $ext = $m->toExt($mt);
367 'contentid' => md5($file),
375 //print_R($url); exit;
378 if (preg_match('#^file:///#', $url)) {
379 $file = preg_replace('#^file://#', '', $url);
380 require_once 'File/MimeType.php';
381 $m = new File_MimeType();
382 $mt = $m->fromFilename($file);
383 $ext = $m->toExt($mt);
388 'contentid' => md5($file),
395 // 2 files --- the info file.. and the actual file...
398 $uinfo = posix_getpwuid( posix_getuid () );
399 $user = $uinfo['name'];
401 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
402 if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
403 $ret = json_decode(file_get_contents($cache), true);
404 $ret['file'] = $cache . '.data';
407 if (!file_exists(dirname($cache))) {
408 mkdir(dirname($cache),0700, true);
411 require_once 'HTTP/Request.php';
412 $a = new HTTP_Request($url);
414 file_put_contents($cache .'.data', $a->getResponseBody());
416 $mt = $a->getResponseHeader('Content-Type');
418 require_once 'File/MimeType.php';
419 $m = new File_MimeType();
420 $ext = $m->toExt($mt);
425 'contentid' => md5($url)
429 file_put_contents($cache, json_encode($ret));
430 $ret['file'] = $cache . '.data';