3 * Table Definition for core_email
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Core_email extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'core_email'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
15 public $subject; // blob(65535) blob
16 public $bodytext; // blob(65535) blob
18 public $updated_dt; //datetime not_null
27 /* the code above is auto generated do not remove the tag below */
30 function applyFilters($q, $au, $roo)
32 $tn = $this->tableName();
34 if(!empty($q['search']['nameortitle'])){
36 $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
38 $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
41 $cgm = DB_DataObject::Factory('core_group_member')->tableName();;
45 if (!empty($_REQUEST['_hide_system_emails'])) {
46 $this->whereAddIn("!{$this->tableName()}.name", array('EVENT_ERRORS_REPORT'), 'string');
51 function beforeDelete($dependants_array, $roo)
53 $i = DB_DataObject::factory('Images');
55 $i->ontable = $this->tableName();
63 function beforeUpdate($old, $request,$roo)
65 if (!empty($request['_make_copy'])) {
66 $this->makeCopy($roo);
70 if ($this->to_group_id != -1) {
72 $c = DB_DataObject::factory('core_group_member');
73 $c->group_id = $this->to_group_id;
75 if (!$c->count() && empty($request['_ignore_group_count'])) {
76 $roo->jerr('Failed to create email template - No member found in recieptent group',array('errcode'=> 100));
81 function makeCopy($roo)
83 $c = DB_DataObject::Factory($this->tableName());
85 $c->name = "COPY of " . $this->name;
86 $c->updated_dt = $this->sqlValue('NOW()');
89 $c = DB_DataObject::Factory($this->tableName());
95 $i = DB_DataObject::factory('Images');
97 $i->ontable = $this->tableName();
101 $new_image = DB_DataObject::factory('Images');
102 $new_image->onid = $c->id;
103 $new_image->ontable = $this->tableName();
104 $new_image->createFrom($i->getStoreName(), $i->filename);
106 $map[$i->id] = $new_image->id;
110 libxml_use_internal_errors (true);
111 $doc = new DOMDocument('1.0', 'UTF-8');
112 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
113 $doc->formatOutput = true;
115 //echo '<PRE>'; print_R($doc);
118 $xpath = new DOMXpath($doc);
119 foreach ($xpath->query('//img[@src]') as $img) {
120 $href = $img->getAttribute('src');
123 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
127 if (!isset($map[$oid])) {
128 //echo "skip no new id for $oid";
132 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
134 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
140 $c->bodytext = $doc->saveHTML();
142 libxml_use_internal_errors (false);
145 $roo->jok("duplicated");
148 function onInsert($q,$roo)
150 $i = DB_DataObject::factory('Images');
152 $i->ontable = $this->tableName();
156 $i->onid = $this->id;
160 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
161 // $this->cachedMailWithOutImages(true, false);
165 function onUpdate($old, $q,$roo)
167 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
171 function attachmentIds()
173 libxml_use_internal_errors (true);
174 $doc = new DOMDocument('1.0', 'UTF-8');
175 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
177 $xpath = new DOMXpath($doc);
180 foreach ($xpath->query('//img[@src]') as $img) { // process images!
181 $href = $img->getAttribute('src');
182 $cid = explode('#', $href);
186 $cid = explode('-', $cid[1]);
187 if (!isset($cid[1])||!is_numeric($cid[1])) {
196 * process replacements is run to generate a template - not the final content..
200 function processRelacements($replace_links = true)
202 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
204 libxml_use_internal_errors (true);
205 $doc = new DOMDocument('1.0', 'UTF-8');
206 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
208 $xpath = new DOMXpath($doc);
210 foreach ($xpath->query('//img[@src]') as $img) { // process images!
211 $href = $img->getAttribute('src');
212 $hash = explode('#', $href);
213 // we name all our cid's as attachment-*
214 // however the src url may be #image-*
217 if(!isset($hash[1])){
220 $cid = explode('-', $hash[1]);
222 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
226 $unsubscribe = $this->unsubscribe_url();
228 foreach ($xpath->query('//a[@href]') as $a) {
230 $href = $a->getAttribute('href');
232 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
233 $a->setAttribute('href', $unsubscribe);
237 if(!preg_match('/^http(.*)/', $href)){
240 if (!$replace_links) {
246 // not available if server_baseurl not set... and crm module not used.
247 $link = DB_DataObject::factory('crm_mailing_list_link');
248 $link->setFrom(array(
252 if(!$link->find(true)){
260 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
262 $a->setAttribute('href', $l);
266 if(!empty($unsubscribe) && !empty($cfg)){
267 $element = $doc->createElement('img');
268 $element->setAttribute('mailembed', 'no');
269 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
270 $element->setAttribute('width', '1');
271 $element->setAttribute('height', '1');
273 $html = $doc->getElementsByTagName('html');
275 $html->item(0)->appendChild($element);
278 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
282 $this->bodytext = $doc->saveHTML();
284 libxml_use_internal_errors (false);
286 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
287 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
292 function unsubscribe_url()
294 $unsubscribe = false;
296 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
299 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
306 * convert email with contents into a core mailer object. - ready to send..
307 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
309 * + rcpts || person << if person is set - then it goes to them...
310 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
314 * + person << who it actually goes to..
316 * @param bool $force - force re-creation of cached version of email.
318 * @returns Pman_Core_Mailer||PEAR_Error
321 function toMailer($obj,$force=false)
323 require_once 'PEAR.php';
326 $contents = (array)$obj;
328 if(empty($this->id) && !empty($contents['template'])){
329 $this->get('name', $contents['template']);
333 if(empty($this->active)){
334 return $p->raiseError("template [{$contents['template']}] is Disabled");
338 if(empty($this->id)){
339 return $p->raiseError("template [{$contents['template']}] has not been set");
344 if (!empty($this->bcc_group_id) && $this->bcc_group_id > 0 && empty($contents['bcc']) && empty($contents['rcpts_group'])) {
345 $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
347 $admin = $admin_grp ? $admin_grp->members('email') : false;
349 if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
350 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
353 $contents['bcc'] = $admin ;
355 if (!empty($contents['rcpts_group'])) {
357 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
360 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
362 $contents['rcpts'] = $admin;
364 if (empty($contents['rcpts']) && $this->to_group_id > 0) {
365 $members = $this->to_group()->members();
366 $contents['rcpts'] = array();
367 foreach($this->to_group()->members() as $m) {
368 $contents['rcpts'][] = $m->email;
370 //var_dump($contents['rcpts']);
373 //subject replacement
374 if(empty($contents['subject'])){
375 $contents['subject'] = $this->subject;
378 if (!empty($contents['subject_replace'])) {
380 // do not use the mapping
381 if (isset($contents['mapping'])) {
382 foreach ($contents['mapping'] as $pattern => $replace) {
383 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
387 foreach ($contents as $k => $v) {
389 $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
394 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
395 $contents['rcpts'] = implode(',', $contents['rcpts']);
398 $ui = posix_getpwuid(posix_geteuid());
400 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
402 if($force || !$this->isGenerated($cachePath)){
403 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
406 require_once 'Pman/Core/Mailer.php';
408 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
411 'template'=> $this->tableName() . '-' . $this->id,
412 'templateDir' => $templateDir,
414 'contents' => $contents,
415 'css_embed' => true, // we should always try and do this with emails...
418 if (isset($contents['rcpts'])) {
419 $cfg['rcpts'] = $contents['rcpts'];
422 if (isset($contents['attachments'])) {
423 $cfg['attachments'] = $contents['attachments'];
426 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
427 $cfg = array_merge($contents['mailer_opts'], $cfg);
430 if(isset($contents['css_inline'])){
431 $cfg['css_inline'] = $contents['css_inline'];
434 $r = new Pman_Core_Mailer($cfg);
436 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
438 if(file_exists($imageCache) && filesize($imageCache)){
439 $images = json_decode(file_get_contents($imageCache), true);
440 $r->images = $images;
445 function toMailerData($obj,$force=false)
447 $r = $this->toMailer($obj, $force);
448 if (is_a($r, 'PEAR_Error')) {
456 * DEPRICATED !!! - DO NOT USE THIS !!!
458 * use: toMailerData() -- to return the email data..
460 * $mailer = $core_email->toMailer($obj, false);
461 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
463 * toMailer($obj, false)->send()
468 function send($obj, $force = true, $send = true)
471 return $this->toMailerData($obj,$force);
474 $r = $this->toMailer($obj, $force);
476 if (is_a($r, 'PEAR_Error')) {
483 function cachedMailWithOutImages($force = false, $replace_links = true)
486 $ui = posix_getpwuid(posix_geteuid());
488 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
490 if (!$force && $this->isGenerated($cachePath)) {
494 if (!file_exists(dirname($cachePath))) {
495 mkdir(dirname($cachePath), 0700, true);
498 $random_hash = md5(date('r', time()));
500 $this->cachedImages();
502 $fh = fopen($cachePath, 'w');
504 fwrite($fh, implode("\n", array(
505 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
506 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
507 "Subject: {t.subject:h} ",
508 "X-Message-ID: {t.id} ",
509 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
510 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
514 // note the extra space to finish the last line..
516 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
519 Content-Type: text/plain; charset=utf-8; format=flowed
520 Content-Transfer-Encoding: 7bit
529 $this->processRelacements($replace_links);
531 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
533 if (!file_exists(dirname($cachePath))) {
534 mkdir(dirname($cachePath), 0700, true);
537 if (empty($this->use_file)) {
538 file_put_contents($cachePath, $this->bodytext);
541 // use-file -- uses the original template...
542 $mailtext = file_get_contents($this->use_file);
544 require_once 'Mail/mimeDecode.php';
545 require_once 'Mail/RFC822.php';
547 $decoder = new Mail_mimeDecode($mailtext);
548 $parts = $decoder->getSendArray();
549 file_put_contents($cachePath,$parts[2]);
553 function cachedImages()
555 $ui = posix_getpwuid(posix_geteuid());
557 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
559 $ids = $this->attachmentIds();
562 $fh = fopen($imageCache, 'w');
564 $i = DB_DataObject::factory('Images');
565 $i->onid = $this->id;
566 $i->ontable = $this->tableName();
567 $i->whereAddIn('id', $ids, 'int');
572 require_once 'File/MimeType.php';
573 $y = new File_MimeType();
576 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
580 $images["attachment-{$i->id}"] = array(
581 'file' => $i->getStoreName(),
582 'mimetype' => $i->mimetype,
583 'ext' => $y->toExt($i->mimetype),
584 'contentid' => "attachment-$i->id"
588 file_put_contents($imageCache, json_encode($images));
592 function isGenerated($cachePath)
594 if (!file_exists($cachePath) || !filesize($cachePath)) {
598 if (!empty($this->use_file)) {
599 $ctime = filemtime($cachePath);
600 $mtime = filemtime($this->use_file);
601 if($ctime >= $mtime){
610 $ctime = filemtime($cachePath);
612 $mtime[] = $this->updated_dt;
613 $i = DB_DataObject::factory('Images');
614 $i->onid = $this->id;
615 $i->ontable = $this->tableName();
617 $i->selectAdd('max(created) as created');
619 $mtime[] = $i->created;
620 if($ctime >= strtotime(max($mtime))){
627 function messageFrom()
629 if (empty($this->from_name)) {
630 return trim($this->from_email);
632 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
635 function formatDate($dt, $format = 'd/M/Y')
637 return date($format, strtotime($dt));
641 // fixme - this is now in core/udatedatabase..
643 function initMail($mail_template_dir, $name, $master='')
645 $cm = DB_DataObject::factory('core_email');
646 if ($cm->get('name', $name)) {
650 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
654 $opts['file'] = $mail_template_dir. $name .'.html';
655 if (!empty($master)) {
656 $opts['master'] = $mail_template_dir . $master .'.html';
659 require_once 'Pman/Core/Import/Core_email.php';
660 $x = new Pman_Core_Import_Core_email();
666 function testData($person, $dt , $core_notify)
669 // should return the formated email???
670 $pg = HTML_FlexyFramework::get()->page;
675 if(empty($this->test_class)){
676 $pg->jerr("[{$this->name}] does not has test class");
679 require_once "{$this->test_class}.php";
681 $cls = str_replace('/', '_', $this->test_class);
685 $method = "test_{$this->name}";
687 if(!method_exists($x, $method)){
688 $pg->jerr("{$method} does not exists in {$cls}");
691 $content = $x->{$method}($this, $person);
692 $content['to'] = $person->getEmailFrom();
694 $content['bcc'] = array();
695 $data = $this->toMailerData($content);
703 $g = DB_DataObject::Factory('core_group');
704 $g->get($this->to_group_id);