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
29 /* the code above is auto generated do not remove the tag below */
32 function applyFilters($q, $au, $roo)
34 $tn = $this->tableName();
36 if(!empty($q['search']['nameortitle'])){
38 $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
40 $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
43 $cgm = DB_DataObject::Factory('core_group_member')->tableName();;
52 to_group_id = {$cgm}.group_id
53 ) AS group_member_count,
61 bcc_group_id = {$cgm}.group_id
62 ) AS bcc_group_member_count
65 if (!empty($_REQUEST['_hide_system_emails'])) {
66 $this->whereAddIn("!{$this->tableName()}.name", array('EVENT_ERRORS_REPORT'), 'string');
71 function beforeDelete($dependants_array, $roo)
73 $i = DB_DataObject::factory('Images');
75 $i->ontable = $this->tableName();
83 function beforeUpdate($old, $request,$roo)
85 if (!empty($request['_make_copy'])) {
86 $this->makeCopy($roo);
90 if ($this->to_group_id != -1) {
92 $c = DB_DataObject::factory('core_group_member');
93 $c->group_id = $this->to_group_id;
95 if (!$c->count() && empty($request['_ignore_group_count'])) {
96 $roo->jerr('Failed to create email template - No member found in recieptent group',array('errcode'=> 100));
101 function makeCopy($roo)
103 $c = DB_DataObject::Factory($this->tableName());
105 $c->name = "COPY of " . $this->name;
106 $c->updated_dt = $this->sqlValue('NOW()');
109 $c = DB_DataObject::Factory($this->tableName());
115 $i = DB_DataObject::factory('Images');
116 $i->onid = $this->id;
117 $i->ontable = $this->tableName();
121 $new_image = DB_DataObject::factory('Images');
122 $new_image->onid = $c->id;
123 $new_image->ontable = $this->tableName();
124 $new_image->createFrom($i->getStoreName(), $i->filename);
126 $map[$i->id] = $new_image->id;
130 libxml_use_internal_errors (true);
131 $doc = new DOMDocument('1.0', 'UTF-8');
132 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
133 $doc->formatOutput = true;
135 //echo '<PRE>'; print_R($doc);
138 $xpath = new DOMXpath($doc);
139 foreach ($xpath->query('//img[@src]') as $img) {
140 $href = $img->getAttribute('src');
143 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
147 if (!isset($map[$oid])) {
148 //echo "skip no new id for $oid";
152 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
154 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
160 $c->bodytext = $doc->saveHTML();
162 libxml_use_internal_errors (false);
165 $roo->jok("duplicated");
168 function onInsert($q,$roo)
170 $i = DB_DataObject::factory('Images');
172 $i->ontable = $this->tableName();
176 $i->onid = $this->id;
180 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
181 // $this->cachedMailWithOutImages(true, false);
185 function onUpdate($old, $q,$roo)
187 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
191 function attachmentIds()
193 libxml_use_internal_errors (true);
194 $doc = new DOMDocument('1.0', 'UTF-8');
195 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
197 $xpath = new DOMXpath($doc);
200 foreach ($xpath->query('//img[@src]') as $img) { // process images!
201 $href = $img->getAttribute('src');
202 $cid = explode('#', $href);
206 $cid = explode('-', $cid[1]);
207 if (!isset($cid[1])||!is_numeric($cid[1])) {
216 * process replacements is run to generate a template - not the final content..
220 function processRelacements($replace_links = true)
222 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
224 libxml_use_internal_errors (true);
225 $doc = new DOMDocument('1.0', 'UTF-8');
226 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
228 $xpath = new DOMXpath($doc);
230 foreach ($xpath->query('//img[@src]') as $img) { // process images!
231 $href = $img->getAttribute('src');
232 $hash = explode('#', $href);
233 // we name all our cid's as attachment-*
234 // however the src url may be #image-*
237 if(!isset($hash[1])){
240 $cid = explode('-', $hash[1]);
242 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
246 $unsubscribe = $this->unsubscribe_url();
248 foreach ($xpath->query('//a[@href]') as $a) {
250 $href = $a->getAttribute('href');
252 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
253 $a->setAttribute('href', $unsubscribe);
257 if(!preg_match('/^http(.*)/', $href)){
260 if (!$replace_links) {
266 // not available if server_baseurl not set... and crm module not used.
267 $link = DB_DataObject::factory('crm_mailing_list_link');
268 $link->setFrom(array(
272 if(!$link->find(true)){
280 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
282 $a->setAttribute('href', $l);
286 if(!empty($unsubscribe) && !empty($cfg)){
287 $element = $doc->createElement('img');
288 $element->setAttribute('mailembed', 'no');
289 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
290 $element->setAttribute('width', '1');
291 $element->setAttribute('height', '1');
293 $html = $doc->getElementsByTagName('html');
295 $html->item(0)->appendChild($element);
298 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
302 $this->bodytext = $doc->saveHTML();
304 libxml_use_internal_errors (false);
306 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
307 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
312 function unsubscribe_url()
314 $unsubscribe = false;
316 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
319 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
326 * convert email with contents into a core mailer object. - ready to send..
327 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
329 * + rcpts || person << if person is set - then it goes to them...
330 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
334 * + person << who it actually goes to..
336 * @param bool $force - force re-creation of cached version of email.
338 * @returns Pman_Core_Mailer||PEAR_Error
341 function toMailer($obj,$force=false)
343 require_once 'PEAR.php';
346 $contents = (array)$obj;
348 if(empty($this->id) && !empty($contents['template'])){
349 $this->get('name', $contents['template']);
353 if(empty($this->active)){
354 return $p->raiseError("template [{$contents['template']}] is Disabled");
358 if(empty($this->id)){
359 return $p->raiseError("template [{$contents['template']}] has not been set");
364 if (!empty($this->bcc_group_id) && $this->bcc_group_id > 0 && empty($contents['bcc']) && empty($contents['rcpts_group'])) {
365 $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
367 $admin = $admin_grp ? $admin_grp->members('email') : false;
369 if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
370 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
373 $contents['bcc'] = $admin ;
375 if (!empty($contents['rcpts_group'])) {
377 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
380 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
382 $contents['rcpts'] = $admin;
385 //subject replacement
386 if(empty($contents['subject'])){
387 $contents['subject'] = $this->subject;
390 if (!empty($contents['subject_replace'])) {
392 // do not use the mapping
393 if (isset($contents['mapping'])) {
394 foreach ($contents['mapping'] as $pattern => $replace) {
395 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
399 foreach ($contents as $k => $v) {
401 $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
406 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
407 $contents['rcpts'] = implode(',', $contents['rcpts']);
410 $ui = posix_getpwuid(posix_geteuid());
412 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
414 if($force || !$this->isGenerated($cachePath)){
415 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
418 require_once 'Pman/Core/Mailer.php';
420 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
423 'template'=> $this->tableName() . '-' . $this->id,
424 'templateDir' => $templateDir,
426 'contents' => $contents,
427 'css_embed' => true, // we should always try and do this with emails...
430 if (isset($contents['rcpts'])) {
431 $cfg['rcpts'] = $contents['rcpts'];
434 if (isset($contents['attachments'])) {
435 $cfg['attachments'] = $contents['attachments'];
438 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
439 $cfg = array_merge($contents['mailer_opts'], $cfg);
442 if(isset($contents['css_inline'])){
443 $cfg['css_inline'] = $contents['css_inline'];
446 $r = new Pman_Core_Mailer($cfg);
448 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
450 if(file_exists($imageCache) && filesize($imageCache)){
451 $images = json_decode(file_get_contents($imageCache), true);
452 $r->images = $images;
457 function toMailerData($obj,$force=false)
459 $r = $this->toMailer($obj, $force);
460 if (is_a($r, 'PEAR_Error')) {
468 * DEPRICATED !!! - DO NOT USE THIS !!!
470 * use: toMailerData() -- to return the email data..
472 * $mailer = $core_email->toMailer($obj, false);
473 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
475 * toMailer($obj, false)->send()
480 function send($obj, $force = true, $send = true)
483 return $this->toMailerData($obj,$force);
486 $r = $this->toMailer($obj, $force);
488 if (is_a($r, 'PEAR_Error')) {
495 function cachedMailWithOutImages($force = false, $replace_links = true)
498 $ui = posix_getpwuid(posix_geteuid());
500 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
502 if (!$force && $this->isGenerated($cachePath)) {
506 if (!file_exists(dirname($cachePath))) {
507 mkdir(dirname($cachePath), 0700, true);
510 $random_hash = md5(date('r', time()));
512 $this->cachedImages();
514 $fh = fopen($cachePath, 'w');
516 fwrite($fh, implode("\n", array(
517 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
518 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
519 "Subject: {t.subject:h} ",
520 "X-Message-ID: {t.id} ",
521 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
522 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
526 // note the extra space to finish the last line..
528 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
531 Content-Type: text/plain; charset=utf-8; format=flowed
532 Content-Transfer-Encoding: 7bit
541 $this->processRelacements($replace_links);
543 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
545 if (!file_exists(dirname($cachePath))) {
546 mkdir(dirname($cachePath), 0700, true);
549 if (empty($this->use_file)) {
550 file_put_contents($cachePath, $this->bodytext);
553 // use-file -- uses the original template...
554 $mailtext = file_get_contents($this->use_file);
556 require_once 'Mail/mimeDecode.php';
557 require_once 'Mail/RFC822.php';
559 $decoder = new Mail_mimeDecode($mailtext);
560 $parts = $decoder->getSendArray();
561 file_put_contents($cachePath,$parts[2]);
565 function cachedImages()
567 $ui = posix_getpwuid(posix_geteuid());
569 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
571 $ids = $this->attachmentIds();
574 $fh = fopen($imageCache, 'w');
576 $i = DB_DataObject::factory('Images');
577 $i->onid = $this->id;
578 $i->ontable = $this->tableName();
579 $i->whereAddIn('id', $ids, 'int');
584 require_once 'File/MimeType.php';
585 $y = new File_MimeType();
588 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
592 $images["attachment-{$i->id}"] = array(
593 'file' => $i->getStoreName(),
594 'mimetype' => $i->mimetype,
595 'ext' => $y->toExt($i->mimetype),
596 'contentid' => "attachment-$i->id"
600 file_put_contents($imageCache, json_encode($images));
604 function isGenerated($cachePath)
606 if (!file_exists($cachePath) || !filesize($cachePath)) {
610 if (!empty($this->use_file)) {
611 $ctime = filemtime($cachePath);
612 $mtime = filemtime($this->use_file);
613 if($ctime >= $mtime){
622 $ctime = filemtime($cachePath);
624 $mtime[] = $this->updated_dt;
625 $i = DB_DataObject::factory('Images');
626 $i->onid = $this->id;
627 $i->ontable = $this->tableName();
629 $i->selectAdd('max(created) as created');
631 $mtime[] = $i->created;
632 if($ctime >= strtotime(max($mtime))){
639 function messageFrom()
641 if (empty($this->from_name)) {
642 return trim($this->from_email);
644 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
647 function formatDate($dt, $format = 'd/M/Y')
649 return date($format, strtotime($dt));
653 // fixme - this is now in core/udatedatabase..
655 function initMail($mail_template_dir, $name, $master='')
657 $cm = DB_DataObject::factory('core_email');
658 if ($cm->get('name', $name)) {
662 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
666 $opts['file'] = $mail_template_dir. $name .'.html';
667 if (!empty($master)) {
668 $opts['master'] = $mail_template_dir . $master .'.html';
671 require_once 'Pman/Core/Import/Core_email.php';
672 $x = new Pman_Core_Import_Core_email();
678 function testData($person, $dt , $core_notify)
681 // should return the formated email???
682 $pg = HTML_FlexyFramework::get()->page;
687 if(empty($this->test_class)){
688 $pg->jerr("[{$this->name}] does not has test class");
691 require_once "{$this->test_class}.php";
693 $cls = str_replace('/', '_', $this->test_class);
697 $method = "test_{$this->name}";
699 if(!method_exists($x, $method)){
700 $pg->jerr("{$method} does not exists in {$cls}");
703 $content = $x->{$method}($this, $person);
704 $content['to'] = $person->getEmailFrom();
706 $content['bcc'] = array();
707 $data = $this->toMailerData($content);