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 replaceImages => true|false,
24 locale => 'en' .... or zh_hk....
25 rcpts => array() // override recipients..
29 name : (optional) - uses basename of file
36 * recipents is gathered from the resulting template
44 * $x->asData(); // returns data needed for notify?? - notify should really
45 * // just use this to pass around later..
51 class Pman_Core_Mailer {
53 var $page = false; /* usually a html_flexyframework_page */
54 var $contents = false; /* object or array */
55 var $template = false; /* string */
56 var $replaceImages = false; /* boolean */
58 var $templateDir = false;
59 var $locale = false; // eg. 'en' or 'zh_HK'
61 var $html_locale = false; // eg. 'en' or 'zh_HK'
62 var $images = array(); // generated list of cid images for sending
63 var $attachments = false;
65 function Pman_Core_Mailer($args) {
66 foreach($args as $k=>$v) {
73 * ---------------- Global Tools ---------------
79 $templateFile = $this->template;
80 $args = $this->contents;
82 $content = clone($this->page);
84 foreach((array)$args as $k=>$v) {
88 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
90 $ff = HTML_FlexyFramework::get();
91 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
92 if (isset($ff->Pman['HTTP_HOST'])) {
93 $http_host = $ff->Pman['HTTP_HOST'];
97 $content->HTTP_HOST = $http_host;
102 // this should be done by having multiple template sources...!!!
104 require_once 'HTML/Template/Flexy.php';
107 // 'forceCompile' => true,
108 'site_prefix' => false,
110 if (!empty($this->templateDir)) {
111 $tmp_opts['templateDir'] = $this->templateDir;
113 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
114 if (!empty($fopts['DB_DataObject_translator'])) {
115 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
117 if (!empty($fopts['locale'])) {
118 $tmp_opts['locale'] = $fopts['locale'];
121 // local opt's overwrite
122 if (!empty($this->locale)) {
123 $tmp_opts['locale'] = $this->locale;
127 $html_tmp_opts = $tmp_opts;
128 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
129 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
130 // then we have a multi-part email...
132 if (!empty($this->html_locale)) {
133 $html_tmp_opts['locale'] = $this->html_locale;
135 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
137 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
138 $htmlbody = $htmltemplate->bufferedOutputObject($content);
140 // for the html body, we may want to convert the attachments to images.
141 // var_dump($htmlbody);exit;
142 $htmlbody = $this->htmlbodytoCID($htmlbody);
146 $tmp_opts['nonHTML'] = true;
149 //print_R($tmp_opts);
150 // $tmp_opts['force'] = true;
151 $template = new HTML_Template_Flexy( $tmp_opts );
153 $template->compile('mail/'. $templateFile.'.txt');
155 /* use variables from this object to ouput data. */
156 $mailtext = $template->bufferedOutputObject($content);
157 //print_r($mailtext);exit;
161 //echo "<PRE>";print_R($mailtext);
163 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
164 require_once 'Mail/mimeDecode.php';
165 require_once 'Mail.php';
167 $decoder = new Mail_mimeDecode($mailtext);
168 $parts = $decoder->getSendArray();
169 if (PEAR::isError($parts)) {
171 //echo "PROBLEM: {$parts->message}";
177 require_once 'Mail/mime.php';
178 $mime = new Mail_mime(array(
180 //'html_encoding' => 'base64',
181 'html_charset' => 'utf-8',
182 'text_charset' => 'utf-8',
183 'head_charset' => 'utf-8',
185 // clean up the headers...
188 $parts[1]['Message-Id'] = '<' . $content->msgid .
189 '@' . $content->HTTP_HOST .'>';
192 if ($htmlbody !== false) {
193 // got a html headers...
195 if (isset($parts[1]['Content-Type'])) {
196 unset($parts[1]['Content-Type']);
198 $mime->setTXTBody($parts[2]);
199 $mime->setHTMLBody($htmlbody);
200 // var_dump($mime);exit;
201 foreach($this->images as $cid=>$cdata) {
206 $cid.'.'.$cdata['ext'],
214 if(!empty($this->attachments)){
215 //if got a attachments
216 $header = $mime->headers($parts[1]);
218 if (isset($parts[1]['Content-Type'])) {
219 unset($parts[1]['Content-Type']);
224 if(preg_match('/text\/html/', $header['Content-Type'])){
225 $mime->setHTMLBody($parts[2]);
226 $mime->setTXTBody('This message is in HTML only');
228 $mime->setTXTBody($parts[2]);
229 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
232 foreach($this->attachments as $attch){
233 $mime->addAttachment(
236 (!empty($attch['name'])) ? $attch['name'] : '',
245 $parts[2] = $mime->get();
246 $parts[1] = $mime->headers($parts[1]);
250 // print_r($parts[2]);
252 // list($recipents,$headers,$body) = $parts;
254 'recipents' => $parts[0],
255 'headers' => $parts[1],
262 $pg = HTML_FlexyFramework::get()->page;
265 $email = $this->toData();
266 if (is_a($email, 'PEAR_Error')) {
267 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
273 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
275 ///$recipents = array($this->email);
276 $mailOptions = PEAR::getStaticProperty('Mail','options');
277 //print_R($mailOptions);exit;
278 $mail = Mail::factory("SMTP",$mailOptions);
279 $email['headers']['Date'] = date('r');
280 if (PEAR::isError($mail)) {
281 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
286 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
288 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
289 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
292 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
293 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
294 error_reporting($oe);
296 $pg->addEvent("COREMAILER-SENT", false,
297 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
298 'Subject: ' . @$email['headers']['Subject']
305 function htmlbodytoCID($html)
307 $dom = new DOMDocument();
308 // this may raise parse errors as some html may be a component..
309 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
310 $imgs= $dom->getElementsByTagName('img');
312 foreach ($imgs as $i=>$img) {
313 $url = $img->getAttribute('src');
314 $conv = $this->fetchImage($url);
315 $this->images[$conv['contentid']] = $conv;
317 $img->setAttribute('src', 'cid:' . $conv['contentid']);
321 return $dom->saveHTML();
326 function fetchImage($url)
329 if ($url[0] == '/') {
330 $ff = HTML_FlexyFramework::get();
331 $file = $ff->rootDir . $url;
332 require_once 'File/MimeType.php';
333 $m = new File_MimeType();
334 $mt = $m->fromFilename($file);
335 $ext = $m->toExt($mt);
340 'contentid' => md5($file),
348 //print_R($url); exit;
351 if (preg_match('#^file:///#', $url)) {
352 $file = preg_replace('#^file://#', '', $url);
353 require_once 'File/MimeType.php';
354 $m = new File_MimeType();
355 $mt = $m->fromFilename($file);
356 $ext = $m->toExt($mt);
361 'contentid' => md5($file),
368 // 2 files --- the info file.. and the actual file...
371 $uinfo = posix_getpwuid( posix_getuid () );
372 $user = $uinfo['name'];
374 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
375 if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
376 $ret = json_decode($cache);
377 $ret['file'] = $cache . '.data';
380 if (!file_exists(dirname($cache))) {
381 mkdir(dirname($cache),0700, true);
384 require_once 'HTTP/Request.php';
385 $a = new HTTP_Request($url);
387 file_put_contents($cache .'.data', $a->getResponseBody());
389 $mt = $a->getResponseHeader('Content-Type');
391 require_once 'File/MimeType.php';
392 $m = new File_MimeType();
393 $ext = $m->toExt($mt);
398 'contentid' => md5($url)
402 file_put_contents($cache, json_encode($ret));
403 $ret['file'] = $cache . '.data';