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 if ($this->replaceImages) {
144 $htmlbody = $this->htmlbodytoCID($htmlbody);
149 $tmp_opts['nonHTML'] = true;
152 //print_R($tmp_opts);
153 // $tmp_opts['force'] = true;
154 $template = new HTML_Template_Flexy( $tmp_opts );
156 $template->compile('mail/'. $templateFile.'.txt');
158 /* use variables from this object to ouput data. */
159 $mailtext = $template->bufferedOutputObject($content);
160 //print_r($mailtext);exit;
164 //echo "<PRE>";print_R($mailtext);
166 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
167 require_once 'Mail/mimeDecode.php';
168 require_once 'Mail.php';
170 $decoder = new Mail_mimeDecode($mailtext);
171 $parts = $decoder->getSendArray();
172 if (PEAR::isError($parts)) {
174 //echo "PROBLEM: {$parts->message}";
180 require_once 'Mail/mime.php';
181 $mime = new Mail_mime(array(
183 //'html_encoding' => 'base64',
184 'html_charset' => 'utf-8',
185 'text_charset' => 'utf-8',
186 'head_charset' => 'utf-8',
188 // clean up the headers...
191 $parts[1]['Message-Id'] = '<' . $content->msgid .
192 '@' . $content->HTTP_HOST .'>';
195 if ($htmlbody !== false) {
196 // got a html headers...
198 if (isset($parts[1]['Content-Type'])) {
199 unset($parts[1]['Content-Type']);
201 $mime->setTXTBody($parts[2]);
202 $mime->setHTMLBody($htmlbody);
203 // var_dump($mime);exit;
204 foreach($this->images as $cid=>$cdata) {
209 $cid.'.'.$cdata['ext'],
217 if(!empty($this->attachments)){
218 //if got a attachments
219 $header = $mime->headers($parts[1]);
221 if (isset($parts[1]['Content-Type'])) {
222 unset($parts[1]['Content-Type']);
227 if(preg_match('/text\/html/', $header['Content-Type'])){
228 $mime->setHTMLBody($parts[2]);
229 $mime->setTXTBody('This message is in HTML only');
231 $mime->setTXTBody($parts[2]);
232 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
235 foreach($this->attachments as $attch){
236 $mime->addAttachment(
239 (!empty($attch['name'])) ? $attch['name'] : '',
248 $parts[2] = $mime->get();
249 $parts[1] = $mime->headers($parts[1]);
253 // print_r($parts[2]);
255 // list($recipents,$headers,$body) = $parts;
257 'recipents' => $parts[0],
258 'headers' => $parts[1],
262 function send($email = false)
265 $pg = HTML_FlexyFramework::get()->page;
268 $email = is_array($email) ? $email : $this->toData();
269 if (is_a($email, 'PEAR_Error')) {
270 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
276 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
278 ///$recipents = array($this->email);
279 $mailOptions = PEAR::getStaticProperty('Mail','options');
280 //print_R($mailOptions);exit;
281 $mail = Mail::factory("SMTP",$mailOptions);
282 $email['headers']['Date'] = date('r');
283 if (PEAR::isError($mail)) {
284 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
289 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
291 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
292 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
295 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
296 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
297 error_reporting($oe);
299 $pg->addEvent("COREMAILER-SENT", false,
300 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
301 'Subject: ' . @$email['headers']['Subject']
308 function htmlbodytoCID($html)
310 $dom = new DOMDocument();
311 // this may raise parse errors as some html may be a component..
312 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
313 $imgs= $dom->getElementsByTagName('img');
315 foreach ($imgs as $i=>$img) {
316 $url = $img->getAttribute('src');
317 if (preg_match('#^cid:#', $url)) {
320 $conv = $this->fetchImage($url);
321 $this->images[$conv['contentid']] = $conv;
323 $img->setAttribute('src', 'cid:' . $conv['contentid']);
327 return $dom->saveHTML();
332 function fetchImage($url)
335 if ($url[0] == '/') {
336 $ff = HTML_FlexyFramework::get();
337 $file = $ff->rootDir . $url;
338 require_once 'File/MimeType.php';
339 $m = new File_MimeType();
340 $mt = $m->fromFilename($file);
341 $ext = $m->toExt($mt);
346 'contentid' => md5($file),
354 //print_R($url); exit;
357 if (preg_match('#^file:///#', $url)) {
358 $file = preg_replace('#^file://#', '', $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),
374 // 2 files --- the info file.. and the actual file...
377 $uinfo = posix_getpwuid( posix_getuid () );
378 $user = $uinfo['name'];
380 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
381 if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
382 $ret = json_decode(file_get_contents($cache), true);
383 $ret['file'] = $cache . '.data';
386 if (!file_exists(dirname($cache))) {
387 mkdir(dirname($cache),0700, true);
390 require_once 'HTTP/Request.php';
391 $a = new HTTP_Request($url);
393 file_put_contents($cache .'.data', $a->getResponseBody());
395 $mt = $a->getResponseHeader('Content-Type');
397 require_once 'File/MimeType.php';
398 $m = new File_MimeType();
399 $ext = $m->toExt($mt);
404 'contentid' => md5($url)
408 file_put_contents($cache, json_encode($ret));
409 $ret['file'] = $cache . '.data';