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();;
50 to_group_id = {$cgm}.group_id
51 ) AS group_member_count,
59 bcc_group_id = {$cgm}.group_id
60 ) AS bcc_group_member_count
66 COUNT(DISTINCT(crm_person_id))
72 person_table = 'crm_person'
76 ontable = 'crm_mailing_list_queue'
83 crm_mailing_list_queue cmlq
84 WHERE message_id = crm_mailing_list_message.id
94 COUNT(DISTINCT(person_id))
100 person_table = 'Person'
104 ontable = 'crm_mailing_list_queue'
111 crm_mailing_list_queue cmlq
112 WHERE message_id = crm_mailing_list_message.id
125 COUNT(DISTINCT(crm_person_id))
131 person_table = 'crm_person'
135 ontable = 'crm_mailing_list_queue'
142 crm_mailing_list_queue cmlq
143 WHERE message_id = crm_mailing_list_message.id
155 COUNT(DISTINCT(person_id))
161 person_table = 'Person'
165 ontable = 'crm_mailing_list_queue'
172 crm_mailing_list_queue cmlq
173 WHERE message_id = crm_mailing_list_message.id
194 ontable = 'crm_mailing_list_queue'
201 crm_mailing_list_queue cmlq
202 WHERE message_id = crm_mailing_list_message.id
212 if (!empty($_REQUEST['_hide_system_emails'])) {
213 $this->whereAddIn("!{$this->tableName()}.name", array('EVENT_ERRORS_REPORT'), 'string');
218 function beforeDelete($dependants_array, $roo)
220 $i = DB_DataObject::factory('Images');
221 $i->onid = $this->id;
222 $i->ontable = $this->tableName();
230 function beforeUpdate($old, $request,$roo)
232 if (!empty($request['_make_copy'])) {
233 $this->makeCopy($roo);
237 if ($this->to_group_id != -1) {
239 $c = DB_DataObject::factory('core_group_member');
240 $c->group_id = $this->to_group_id;
242 if (!$c->count() && empty($request['_ignore_group_count'])) {
243 $roo->jerr('Failed to create email template - No member found in recieptent group',array('errcode'=> 100));
248 function makeCopy($roo)
250 $c = DB_DataObject::Factory($this->tableName());
252 $c->name = "COPY of " . $this->name;
253 $c->updated_dt = $this->sqlValue('NOW()');
256 $c = DB_DataObject::Factory($this->tableName());
262 $i = DB_DataObject::factory('Images');
263 $i->onid = $this->id;
264 $i->ontable = $this->tableName();
268 $new_image = DB_DataObject::factory('Images');
269 $new_image->onid = $c->id;
270 $new_image->ontable = $this->tableName();
271 $new_image->createFrom($i->getStoreName(), $i->filename);
273 $map[$i->id] = $new_image->id;
277 libxml_use_internal_errors (true);
278 $doc = new DOMDocument('1.0', 'UTF-8');
279 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
280 $doc->formatOutput = true;
282 //echo '<PRE>'; print_R($doc);
285 $xpath = new DOMXpath($doc);
286 foreach ($xpath->query('//img[@src]') as $img) {
287 $href = $img->getAttribute('src');
290 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
294 if (!isset($map[$oid])) {
295 //echo "skip no new id for $oid";
299 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
301 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
307 $c->bodytext = $doc->saveHTML();
309 libxml_use_internal_errors (false);
312 $roo->jok("duplicated");
315 function onInsert($q,$roo)
317 $i = DB_DataObject::factory('Images');
319 $i->ontable = $this->tableName();
323 $i->onid = $this->id;
327 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
328 // $this->cachedMailWithOutImages(true, false);
332 function onUpdate($old, $q,$roo)
334 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
338 function attachmentIds()
340 libxml_use_internal_errors (true);
341 $doc = new DOMDocument('1.0', 'UTF-8');
342 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
344 $xpath = new DOMXpath($doc);
347 foreach ($xpath->query('//img[@src]') as $img) { // process images!
348 $href = $img->getAttribute('src');
349 $cid = explode('#', $href);
353 $cid = explode('-', $cid[1]);
354 if (!isset($cid[1])||!is_numeric($cid[1])) {
363 * process replacements is run to generate a template - not the final content..
367 function processRelacements($replace_links = true)
369 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
371 libxml_use_internal_errors (true);
372 $doc = new DOMDocument('1.0', 'UTF-8');
373 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
375 $xpath = new DOMXpath($doc);
377 foreach ($xpath->query('//img[@src]') as $img) { // process images!
378 $href = $img->getAttribute('src');
379 $hash = explode('#', $href);
380 // we name all our cid's as attachment-*
381 // however the src url may be #image-*
384 if(!isset($hash[1])){
387 $cid = explode('-', $hash[1]);
389 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
393 $unsubscribe = $this->unsubscribe_url();
395 foreach ($xpath->query('//a[@href]') as $a) {
397 $href = $a->getAttribute('href');
399 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
400 $a->setAttribute('href', $unsubscribe);
404 if(!preg_match('/^http(.*)/', $href)){
407 if (!$replace_links) {
413 // not available if server_baseurl not set... and crm module not used.
414 $link = DB_DataObject::factory('crm_mailing_list_link');
415 $link->setFrom(array(
419 if(!$link->find(true)){
427 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
429 $a->setAttribute('href', $l);
433 if(!empty($unsubscribe) && !empty($cfg)){
434 $element = $doc->createElement('img');
435 $element->setAttribute('mailembed', 'no');
436 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
437 $element->setAttribute('width', '1');
438 $element->setAttribute('height', '1');
440 $html = $doc->getElementsByTagName('html');
442 $html->item(0)->appendChild($element);
445 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
449 $this->bodytext = $doc->saveHTML();
451 libxml_use_internal_errors (false);
453 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
454 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
459 function unsubscribe_url()
461 $unsubscribe = false;
463 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
466 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
473 * convert email with contents into a core mailer object. - ready to send..
474 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
476 * + rcpts || person << if person is set - then it goes to them...
477 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
481 * + person << who it actually goes to..
483 * @param bool $force - force re-creation of cached version of email.
485 * @returns Pman_Core_Mailer||PEAR_Error
488 function toMailer($obj,$force=false)
490 require_once 'PEAR.php';
493 $contents = (array)$obj;
495 if(empty($this->id) && !empty($contents['template'])){
496 $this->get('name', $contents['template']);
500 if(empty($this->active)){
501 return $p->raiseError("template [{$contents['template']}] is Disabled");
505 if(empty($this->id)){
506 return $p->raiseError("template [{$contents['template']}] has not been set");
511 if (!empty($this->bcc_group_id) && $this->bcc_group_id > 0 && empty($contents['bcc']) && empty($contents['rcpts_group'])) {
512 $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
514 $admin = $admin_grp ? $admin_grp->members('email') : false;
516 if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
517 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
520 $contents['bcc'] = $admin ;
522 if (!empty($contents['rcpts_group'])) {
524 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
527 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
529 $contents['rcpts'] = $admin;
531 if (empty($contents['rcpts']) && $this->to_group_id > 0) {
532 $members = $this->to_group()->members();
533 $contents['rcpts'] = array();
534 foreach($this->to_group()->members() as $m) {
535 $contents['rcpts'][] = $m->email;
537 //var_dump($contents['rcpts']);
540 //subject replacement
541 if(empty($contents['subject'])){
542 $contents['subject'] = $this->subject;
545 if (!empty($contents['subject_replace'])) {
547 // do not use the mapping
548 if (isset($contents['mapping'])) {
549 foreach ($contents['mapping'] as $pattern => $replace) {
550 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
554 foreach ($contents as $k => $v) {
556 $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
561 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
562 $contents['rcpts'] = implode(',', $contents['rcpts']);
565 $ui = posix_getpwuid(posix_geteuid());
567 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
569 if($force || !$this->isGenerated($cachePath)){
570 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
573 require_once 'Pman/Core/Mailer.php';
575 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
578 'template'=> $this->tableName() . '-' . $this->id,
579 'templateDir' => $templateDir,
581 'contents' => $contents,
582 'css_embed' => true, // we should always try and do this with emails...
585 if (isset($contents['rcpts'])) {
586 $cfg['rcpts'] = $contents['rcpts'];
589 if (isset($contents['attachments'])) {
590 $cfg['attachments'] = $contents['attachments'];
593 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
594 $cfg = array_merge($contents['mailer_opts'], $cfg);
597 if(isset($contents['css_inline'])){
598 $cfg['css_inline'] = $contents['css_inline'];
601 $r = new Pman_Core_Mailer($cfg);
603 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
605 if(file_exists($imageCache) && filesize($imageCache)){
606 $images = json_decode(file_get_contents($imageCache), true);
607 $r->images = $images;
612 function toMailerData($obj,$force=false)
614 $r = $this->toMailer($obj, $force);
615 if (is_a($r, 'PEAR_Error')) {
623 * DEPRICATED !!! - DO NOT USE THIS !!!
625 * use: toMailerData() -- to return the email data..
627 * $mailer = $core_email->toMailer($obj, false);
628 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
630 * toMailer($obj, false)->send()
635 function send($obj, $force = true, $send = true)
638 return $this->toMailerData($obj,$force);
641 $r = $this->toMailer($obj, $force);
643 if (is_a($r, 'PEAR_Error')) {
650 function cachedMailWithOutImages($force = false, $replace_links = true)
653 $ui = posix_getpwuid(posix_geteuid());
655 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
657 if (!$force && $this->isGenerated($cachePath)) {
661 if (!file_exists(dirname($cachePath))) {
662 mkdir(dirname($cachePath), 0700, true);
665 $random_hash = md5(date('r', time()));
667 $this->cachedImages();
669 $fh = fopen($cachePath, 'w');
671 fwrite($fh, implode("\n", array(
672 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
673 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
674 "Subject: {t.subject:h} ",
675 "X-Message-ID: {t.id} ",
676 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
677 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
681 // note the extra space to finish the last line..
683 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
686 Content-Type: text/plain; charset=utf-8; format=flowed
687 Content-Transfer-Encoding: 7bit
696 $this->processRelacements($replace_links);
698 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
700 if (!file_exists(dirname($cachePath))) {
701 mkdir(dirname($cachePath), 0700, true);
704 if (empty($this->use_file)) {
705 file_put_contents($cachePath, $this->bodytext);
708 // use-file -- uses the original template...
709 $mailtext = file_get_contents($this->use_file);
711 require_once 'Mail/mimeDecode.php';
712 require_once 'Mail/RFC822.php';
714 $decoder = new Mail_mimeDecode($mailtext);
715 $parts = $decoder->getSendArray();
716 file_put_contents($cachePath,$parts[2]);
720 function cachedImages()
722 $ui = posix_getpwuid(posix_geteuid());
724 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
726 $ids = $this->attachmentIds();
729 $fh = fopen($imageCache, 'w');
731 $i = DB_DataObject::factory('Images');
732 $i->onid = $this->id;
733 $i->ontable = $this->tableName();
734 $i->whereAddIn('id', $ids, 'int');
739 require_once 'File/MimeType.php';
740 $y = new File_MimeType();
743 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
747 $images["attachment-{$i->id}"] = array(
748 'file' => $i->getStoreName(),
749 'mimetype' => $i->mimetype,
750 'ext' => $y->toExt($i->mimetype),
751 'contentid' => "attachment-$i->id"
755 file_put_contents($imageCache, json_encode($images));
759 function isGenerated($cachePath)
761 if (!file_exists($cachePath) || !filesize($cachePath)) {
765 if (!empty($this->use_file)) {
766 $ctime = filemtime($cachePath);
767 $mtime = filemtime($this->use_file);
768 if($ctime >= $mtime){
777 $ctime = filemtime($cachePath);
779 $mtime[] = $this->updated_dt;
780 $i = DB_DataObject::factory('Images');
781 $i->onid = $this->id;
782 $i->ontable = $this->tableName();
784 $i->selectAdd('max(created) as created');
786 $mtime[] = $i->created;
787 if($ctime >= strtotime(max($mtime))){
794 function messageFrom()
796 if (empty($this->from_name)) {
797 return trim($this->from_email);
799 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
802 function formatDate($dt, $format = 'd/M/Y')
804 return date($format, strtotime($dt));
808 // fixme - this is now in core/udatedatabase..
810 function initMail($mail_template_dir, $name, $master='')
812 $cm = DB_DataObject::factory('core_email');
813 if ($cm->get('name', $name)) {
817 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
821 $opts['file'] = $mail_template_dir. $name .'.html';
822 if (!empty($master)) {
823 $opts['master'] = $mail_template_dir . $master .'.html';
826 require_once 'Pman/Core/Import/Core_email.php';
827 $x = new Pman_Core_Import_Core_email();
833 function testData($person, $dt , $core_notify)
836 // should return the formated email???
837 $pg = HTML_FlexyFramework::get()->page;
842 if(empty($this->test_class)){
843 $pg->jerr("[{$this->name}] does not has test class");
846 require_once "{$this->test_class}.php";
848 $cls = str_replace('/', '_', $this->test_class);
852 $method = "test_{$this->name}";
854 if(!method_exists($x, $method)){
855 $pg->jerr("{$method} does not exists in {$cls}");
858 $content = $x->{$method}($this, $person);
859 $content['to'] = $person->getEmailFrom();
861 $content['bcc'] = array();
862 $data = $this->toMailerData($content);
870 $g = DB_DataObject::Factory('core_group');
871 $g->get($this->to_group_id);