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;
68 var $mail_method = 'SMTP';
70 function Pman_Core_Mailer($args) {
71 foreach($args as $k=>$v) {
78 * ---------------- Global Tools ---------------
84 $templateFile = $this->template;
85 $args = $this->contents;
87 $content = clone($this->page);
89 foreach((array)$args as $k=>$v) {
93 $content->msgid = empty($content->msgid ) ? md5(time() . rand()) : $content->msgid ;
95 $ff = HTML_FlexyFramework::get();
96 $http_host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : 'pman.HTTP_HOST.not.set';
97 if (isset($ff->Pman['HTTP_HOST'])) {
98 $http_host = $ff->Pman['HTTP_HOST'];
102 $content->HTTP_HOST = $http_host;
107 // this should be done by having multiple template sources...!!!
109 require_once 'HTML/Template/Flexy.php';
112 // 'forceCompile' => true,
113 'site_prefix' => false,
115 if (!empty($this->templateDir)) {
116 $tmp_opts['templateDir'] = $this->templateDir;
118 $fopts = HTML_FlexyFramework::get()->HTML_Template_Flexy;
119 if (!empty($fopts['DB_DataObject_translator'])) {
120 $tmp_opts['DB_DataObject_translator'] = $fopts['DB_DataObject_translator'];
122 if (!empty($fopts['locale'])) {
123 $tmp_opts['locale'] = $fopts['locale'];
126 // local opt's overwrite
127 if (!empty($this->locale)) {
128 $tmp_opts['locale'] = $this->locale;
132 $html_tmp_opts = $tmp_opts;
133 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
134 if (is_string($htmltemplate->resolvePath('mail/'.$templateFile.'.body.html')) ) {
135 // then we have a multi-part email...
137 if (!empty($this->html_locale)) {
138 $html_tmp_opts['locale'] = $this->html_locale;
140 $htmltemplate = new HTML_Template_Flexy( $html_tmp_opts );
142 $htmltemplate->compile('mail/'. $templateFile.'.body.html');
143 $htmlbody = $htmltemplate->bufferedOutputObject($content);
145 // for the html body, we may want to convert the attachments to images.
146 // var_dump($htmlbody);exit;
147 if ($this->replaceImages) {
148 $htmlbody = $this->htmlbodytoCID($htmlbody);
153 $tmp_opts['nonHTML'] = true;
156 //print_R($tmp_opts);
157 // $tmp_opts['force'] = true;
158 $template = new HTML_Template_Flexy( $tmp_opts );
160 $template->compile('mail/'. $templateFile.'.txt');
162 /* use variables from this object to ouput data. */
163 $mailtext = $template->bufferedOutputObject($content);
164 //print_r($mailtext);exit;
168 //echo "<PRE>";print_R($mailtext);
170 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
171 require_once 'Mail/mimeDecode.php';
172 require_once 'Mail.php';
174 $decoder = new Mail_mimeDecode($mailtext);
175 $parts = $decoder->getSendArray();
176 if (PEAR::isError($parts)) {
178 //echo "PROBLEM: {$parts->message}";
184 require_once 'Mail/mime.php';
185 $mime = new Mail_mime(array(
187 //'html_encoding' => 'base64',
188 'html_charset' => 'utf-8',
189 'text_charset' => 'utf-8',
190 'head_charset' => 'utf-8',
192 // clean up the headers...
195 $parts[1]['Message-Id'] = '<' . $content->msgid .
196 '@' . $content->HTTP_HOST .'>';
199 if ($htmlbody !== false) {
200 // got a html headers...
202 if (isset($parts[1]['Content-Type'])) {
203 unset($parts[1]['Content-Type']);
205 $mime->setTXTBody($parts[2]);
206 $mime->setHTMLBody($htmlbody);
207 // var_dump($mime);exit;
208 foreach($this->images as $cid=>$cdata) {
213 $cid.'.'.$cdata['ext'],
221 if(!empty($this->attachments)){
222 //if got a attachments
223 $header = $mime->headers($parts[1]);
225 if (isset($parts[1]['Content-Type'])) {
226 unset($parts[1]['Content-Type']);
231 if(preg_match('/text\/html/', $header['Content-Type'])){
232 $mime->setHTMLBody($parts[2]);
233 $mime->setTXTBody('This message is in HTML only');
235 $mime->setTXTBody($parts[2]);
236 $mime->setHTMLBody('<PRE>'.htmlspecialchars($parts[2]).'</PRE>');
239 foreach($this->attachments as $attch){
240 $mime->addAttachment(
243 (!empty($attch['name'])) ? $attch['name'] : '',
252 $parts[2] = $mime->get();
253 $parts[1] = $mime->headers($parts[1]);
257 // print_r($parts[2]);
259 // list($recipents,$headers,$body) = $parts;
261 'recipents' => $parts[0],
262 'headers' => $parts[1],
266 function send($email = false)
269 $pg = HTML_FlexyFramework::get()->page;
272 $email = is_array($email) ? $email : $this->toData();
273 if (is_a($email, 'PEAR_Error')) {
274 $pg->addEvent("COREMAILER-FAIL", false, "email toData failed");
280 echo '<PRE>';echo htmlspecialchars(print_r($email,true));
282 ///$recipents = array($this->email);
283 $mailOptions = PEAR::getStaticProperty('Mail','options');
284 //print_R($mailOptions);exit;
285 $mail = Mail::factory($this->mail_method,$mailOptions);
287 $mail->debug = $this->debug;
290 $email['headers']['Date'] = date('r');
291 if (PEAR::isError($mail)) {
292 $pg->addEvent("COREMAILER-FAIL", false, "mail factory failed");
297 $rcpts = $this->rcpts == false ? $email['recipents'] : $this->rcpts;
299 if (!empty($this->contents['bcc']) && is_array($this->contents['bcc'])) {
300 $rcpts =array_merge(is_array($rcpts) ? $rcpts : array($rcpts), $this->contents['bcc']);
303 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
304 $ret = $mail->send($rcpts,$email['headers'],$email['body']);
305 error_reporting($oe);
307 $pg->addEvent("COREMAILER-SENT", false,
308 'To: ' . ( is_array($rcpts) ? implode(', ', $rcpts) : $rcpts ) .
309 'Subject: ' . @$email['headers']['Subject']
316 function htmlbodytoCID($html)
318 $dom = new DOMDocument();
319 // this may raise parse errors as some html may be a component..
320 @$dom->loadHTML('<?xml encoding="UTF-8">' .$html);
321 $imgs= $dom->getElementsByTagName('img');
323 foreach ($imgs as $i=>$img) {
324 $url = $img->getAttribute('src');
325 if (preg_match('#^cid:#', $url)) {
328 $conv = $this->fetchImage($url);
329 $this->images[$conv['contentid']] = $conv;
331 $img->setAttribute('src', 'cid:' . $conv['contentid']);
335 return $dom->saveHTML();
340 function fetchImage($url)
343 if ($url[0] == '/') {
344 $ff = HTML_FlexyFramework::get();
345 $file = $ff->rootDir . $url;
346 require_once 'File/MimeType.php';
347 $m = new File_MimeType();
348 $mt = $m->fromFilename($file);
349 $ext = $m->toExt($mt);
354 'contentid' => md5($file),
362 //print_R($url); exit;
365 if (preg_match('#^file:///#', $url)) {
366 $file = preg_replace('#^file://#', '', $url);
367 require_once 'File/MimeType.php';
368 $m = new File_MimeType();
369 $mt = $m->fromFilename($file);
370 $ext = $m->toExt($mt);
375 'contentid' => md5($file),
382 // 2 files --- the info file.. and the actual file...
385 $uinfo = posix_getpwuid( posix_getuid () );
386 $user = $uinfo['name'];
388 $cache = ini_get('session.save_path')."/Pman_Core_Mailer-{$user}/" . md5($url);
389 if (file_exists($cache) and filemtime($cache) > strtotime('NOW - 1 WEEK')) {
390 $ret = json_decode(file_get_contents($cache), true);
391 $ret['file'] = $cache . '.data';
394 if (!file_exists(dirname($cache))) {
395 mkdir(dirname($cache),0700, true);
398 require_once 'HTTP/Request.php';
399 $a = new HTTP_Request($url);
401 file_put_contents($cache .'.data', $a->getResponseBody());
403 $mt = $a->getResponseHeader('Content-Type');
405 require_once 'File/MimeType.php';
406 $m = new File_MimeType();
407 $ext = $m->toExt($mt);
412 'contentid' => md5($url)
416 file_put_contents($cache, json_encode($ret));
417 $ret['file'] = $cache . '.data';