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)
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
37 * recipents is gathered from the resulting template
45 * $x->asData(); // returns data needed for notify?? - notify should really
46 * // just use this to pass around later..
52 class Pman_Core_Mailer {
54 var $page = false; /* usually a html_flexyframework_page */
55 var $contents = false; /* object or array */
56 var $template = false; /* string */
57 var $replaceImages = false; /* boolean */
59 var $templateDir = false;
60 var $locale = false; // eg. 'en' or 'zh_HK'
62 var $html_locale = false; // eg. 'en' or 'zh_HK'
63 var $images = array(); // generated list of cid images for sending
64 var $attachments = false;
66 function Pman_Core_Mailer($args) {
67 foreach($args as $k=>$v) {
74 * ---------------- Global Tools ---------------
80 $templateFile = $this->template;
81 $args = $this->contents;
83 $content = clone($this->page);
85 foreach((array)$args as $k=>$v) {
89 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
91 $ff = HTML_FlexyFramework::get();
92 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
93 if (isset($ff->Pman['HTTP_HOST'])) {
94 $http_host = $ff->Pman['HTTP_HOST'];
98 $content->HTTP_HOST = $http_host;
103 // this should be done by having multiple template sources...!!!
105 require_once 'HTML/Template/Flexy.php';
108 // 'forceCompile' => true,
109 'site_prefix' => false,
111 if (!empty($this->templateDir)) {
112 $tmp_opts['templateDir'] = $this->templateDir;
114 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
115 if (!empty($fopts['DB_DataObject_translator'])) {
116 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
118 if (!empty($fopts['locale'])) {
119 $tmp_opts['locale'] = $fopts['locale'];
122 // local opt's overwrite
123 if (!empty($this->locale)) {
124 $tmp_opts['locale'] = $this->locale;
128 $html_tmp_opts = $tmp_opts;
129 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
130 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
131 // then we have a multi-part email...
133 if (!empty($this->html_locale)) {
134 $html_tmp_opts['locale'] = $this->html_locale;
136 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
138 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
139 $htmlbody = $htmltemplate->bufferedOutputObject($content);
141 // for the html body, we may want to convert the attachments to images.
142 // var_dump($htmlbody);exit;
143 $htmlbody = $this->htmlbodytoCID($htmlbody);
147 $tmp_opts['nonHTML'] = true;
150 //print_R($tmp_opts);
151 // $tmp_opts['force'] = true;
152 $template = new HTML_Template_Flexy( $tmp_opts );
154 $template->compile('mail/'. $templateFile.'.txt');
156 /* use variables from this object to ouput data. */
157 $mailtext = $template->bufferedOutputObject($content);
158 //print_r($mailtext);exit;
162 //echo "<PRE>";print_R($mailtext);
164 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
165 require_once 'Mail/mimeDecode.php';
166 require_once 'Mail.php';
168 $decoder = new Mail_mimeDecode($mailtext);
169 $parts = $decoder->getSendArray();
170 if (PEAR::isError($parts)) {
172 //echo "PROBLEM: {$parts->message}";
178 require_once 'Mail/mime.php';
179 $mime = new Mail_mime(array(
181 //'html_encoding' => 'base64',
182 'html_charset' => 'utf-8',
183 'text_charset' => 'utf-8',
184 'head_charset' => 'utf-8',
186 // clean up the headers...
189 $parts[1]['Message-Id'] = '<' . $content->msgid .
190 '@' . $content->HTTP_HOST .'>';
193 if ($htmlbody !== false) {
194 // got a html headers...
196 if (isset($parts[1]['Content-Type'])) {
197 unset($parts[1]['Content-Type']);
199 $mime->setTXTBody($parts[2]);
200 $mime->setHTMLBody($htmlbody);
201 // var_dump($mime);exit;
202 print_r($this->images);exit;
203 foreach($this->images as $cid=>$cdata) {
208 $cid.'.'.$cdata['ext'],
216 if(!empty($this->attachments)){
217 //if got a attachments
218 $header = $mime->headers($parts[1]);
220 if (isset($parts[1]['Content-Type'])) {
221 unset($parts[1]['Content-Type']);
226 if(preg_match('/text\/html/', $header['Content-Type'])){
227 $mime->setHTMLBody($parts[2]);
228 $mime->setTXTBody('This message is in HTML only');
230 $mime->setTXTBody($parts[2]);
231 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
234 foreach($this->attachments as $attch){
235 $mime->addAttachment(
238 (!empty($attch['name'])) ? $attch['name'] : '',
247 $parts[2] = $mime->get();
248 $parts[1] = $mime->headers($parts[1]);
252 // print_r($parts[2]);
254 // list($recipents,$headers,$body) = $parts;
256 'recipents' => $parts[0],
257 'headers' => $parts[1],
261 function send($email = false)
264 $pg = HTML_FlexyFramework::get()->page;
267 $email = is_array($email) ? $email : $this->toData();
268 if (is_a($email, 'PEAR_Error')) {
269 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
275 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
277 ///$recipents = array($this->email);
278 $mailOptions = PEAR::getStaticProperty('Mail','options');
279 //print_R($mailOptions);exit;
280 $mail = Mail::factory("SMTP",$mailOptions);
281 $email['headers']['Date'] = date('r');
282 if (PEAR::isError($mail)) {
283 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
288 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
290 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
291 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
294 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
295 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
296 error_reporting($oe);
298 $pg->addEvent("COREMAILER-SENT", false,
299 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
300 'Subject: ' . @$email['headers']['Subject']
307 function htmlbodytoCID($html)
309 $dom = new DOMDocument();
310 // this may raise parse errors as some html may be a component..
311 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
312 $imgs= $dom->getElementsByTagName('img');
314 foreach ($imgs as $i=>$img) {
315 $url = $img->getAttribute('src');
316 if (preg_match('#^cid:#', $url)) {
319 $conv = $this->fetchImage($url);
320 $this->images[$conv['contentid']] = $conv;
322 $img->setAttribute('src', 'cid:' . $conv['contentid']);
326 return $dom->saveHTML();
331 function fetchImage($url)
334 if ($url[0] == '/') {
335 $ff = HTML_FlexyFramework::get();
336 $file = $ff->rootDir . $url;
337 require_once 'File/MimeType.php';
338 $m = new File_MimeType();
339 $mt = $m->fromFilename($file);
340 $ext = $m->toExt($mt);
345 'contentid' => md5($file),
353 //print_R($url); exit;
356 if (preg_match('#^file:///#', $url)) {
357 $file = preg_replace('#^file://#', '', $url);
358 require_once 'File/MimeType.php';
359 $m = new File_MimeType();
360 $mt = $m->fromFilename($file);
361 $ext = $m->toExt($mt);
366 'contentid' => md5($file),
373 // 2 files --- the info file.. and the actual file...
376 $uinfo = posix_getpwuid( posix_getuid () );
377 $user = $uinfo['name'];
379 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
380 if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
381 $ret = json_decode($cache);
382 $ret['file'] = $cache . '.data';
385 if (!file_exists(dirname($cache))) {
386 mkdir(dirname($cache),0700, true);
389 require_once 'HTTP/Request.php';
390 $a = new HTTP_Request($url);
392 file_put_contents($cache .'.data', $a->getResponseBody());
394 $mt = $a->getResponseHeader('Content-Type');
396 require_once 'File/MimeType.php';
397 $m = new File_MimeType();
398 $ext = $m->toExt($mt);
403 'contentid' => md5($url)
407 file_put_contents($cache, json_encode($ret));
408 $ret['file'] = $cache . '.data';