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
63 if (!empty($_REQUEST['_hide_system_emails'])) {
64 $this->whereAddIn("!{$this->tableName()}.name", array('EVENT_ERRORS_REPORT'), 'string');
69 function beforeDelete($dependants_array, $roo)
71 $i = DB_DataObject::factory('Images');
73 $i->ontable = $this->tableName();
81 function beforeUpdate($old, $request,$roo)
83 if (!empty($request['_make_copy'])) {
84 $this->makeCopy($roo);
88 if ($this->to_group_id != -1) {
90 $c = DB_DataObject::factory('core_group_member');
91 $c->group_id = $this->to_group_id;
93 if (!$c->count() && empty($request['_ignore_group_count'])) {
94 $roo->jerr('Failed to create email template - No member found in recieptent group',array('errcode'=> 100));
99 function makeCopy($roo)
101 $c = DB_DataObject::Factory($this->tableName());
103 $c->name = "COPY of " . $this->name;
104 $c->updated_dt = $this->sqlValue('NOW()');
107 $c = DB_DataObject::Factory($this->tableName());
113 $i = DB_DataObject::factory('Images');
114 $i->onid = $this->id;
115 $i->ontable = $this->tableName();
119 $new_image = DB_DataObject::factory('Images');
120 $new_image->onid = $c->id;
121 $new_image->ontable = $this->tableName();
122 $new_image->createFrom($i->getStoreName(), $i->filename);
124 $map[$i->id] = $new_image->id;
128 libxml_use_internal_errors (true);
129 $doc = new DOMDocument('1.0', 'UTF-8');
130 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
131 $doc->formatOutput = true;
133 //echo '<PRE>'; print_R($doc);
136 $xpath = new DOMXpath($doc);
137 foreach ($xpath->query('//img[@src]') as $img) {
138 $href = $img->getAttribute('src');
141 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
145 if (!isset($map[$oid])) {
146 //echo "skip no new id for $oid";
150 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
152 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
158 $c->bodytext = $doc->saveHTML();
160 libxml_use_internal_errors (false);
163 $roo->jok("duplicated");
166 function onInsert($q,$roo)
168 $i = DB_DataObject::factory('Images');
170 $i->ontable = $this->tableName();
174 $i->onid = $this->id;
178 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
179 // $this->cachedMailWithOutImages(true, false);
183 function onUpdate($old, $q,$roo)
185 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
189 function attachmentIds()
191 libxml_use_internal_errors (true);
192 $doc = new DOMDocument('1.0', 'UTF-8');
193 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
195 $xpath = new DOMXpath($doc);
198 foreach ($xpath->query('//img[@src]') as $img) { // process images!
199 $href = $img->getAttribute('src');
200 $cid = explode('#', $href);
204 $cid = explode('-', $cid[1]);
205 if (!isset($cid[1])||!is_numeric($cid[1])) {
214 * process replacements is run to generate a template - not the final content..
218 function processRelacements($replace_links = true)
220 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
222 libxml_use_internal_errors (true);
223 $doc = new DOMDocument('1.0', 'UTF-8');
224 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
226 $xpath = new DOMXpath($doc);
228 foreach ($xpath->query('//img[@src]') as $img) { // process images!
229 $href = $img->getAttribute('src');
230 $hash = explode('#', $href);
231 // we name all our cid's as attachment-*
232 // however the src url may be #image-*
235 if(!isset($hash[1])){
238 $cid = explode('-', $hash[1]);
240 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
244 $unsubscribe = $this->unsubscribe_url();
246 foreach ($xpath->query('//a[@href]') as $a) {
248 $href = $a->getAttribute('href');
250 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
251 $a->setAttribute('href', $unsubscribe);
255 if(!preg_match('/^http(.*)/', $href)){
258 if (!$replace_links) {
264 // not available if server_baseurl not set... and crm module not used.
265 $link = DB_DataObject::factory('crm_mailing_list_link');
266 $link->setFrom(array(
270 if(!$link->find(true)){
278 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
280 $a->setAttribute('href', $l);
284 if(!empty($unsubscribe) && !empty($cfg)){
285 $element = $doc->createElement('img');
286 $element->setAttribute('mailembed', 'no');
287 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
288 $element->setAttribute('width', '1');
289 $element->setAttribute('height', '1');
291 $html = $doc->getElementsByTagName('html');
293 $html->item(0)->appendChild($element);
296 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
300 $this->bodytext = $doc->saveHTML();
302 libxml_use_internal_errors (false);
304 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
305 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
310 function unsubscribe_url()
312 $unsubscribe = false;
314 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
317 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
324 * convert email with contents into a core mailer object. - ready to send..
325 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
327 * + rcpts || person << if person is set - then it goes to them...
328 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
332 * + person << who it actually goes to..
334 * @param bool $force - force re-creation of cached version of email.
336 * @returns Pman_Core_Mailer||PEAR_Error
339 function toMailer($obj,$force=false)
341 require_once 'PEAR.php';
344 $contents = (array)$obj;
346 if(empty($this->id) && !empty($contents['template'])){
347 $this->get('name', $contents['template']);
351 if(empty($this->active)){
352 return $p->raiseError("template [{$contents['template']}] is Disabled");
356 if(empty($this->id)){
357 return $p->raiseError("template [{$contents['template']}] has not been set");
362 if (!empty($this->bcc_group_id) && $this->bcc_group_id > 0 && empty($contents['bcc']) && empty($contents['rcpts_group'])) {
363 $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
365 $admin = $admin_grp ? $admin_grp->members('email') : false;
367 if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
368 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
371 $contents['bcc'] = $admin ;
373 if (!empty($contents['rcpts_group'])) {
375 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
378 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
380 $contents['rcpts'] = $admin;
382 if (empty($contents['rcpts']) && $this->to_group_id > 0) {
383 $members = $this->to_group()->members();
384 $contents['rcpts'] = array();
385 foreach($this->to_group()->members() as $m) {
386 $contents['rcpts'][] = $m->email;
388 //var_dump($contents['rcpts']);
391 //subject replacement
392 if(empty($contents['subject'])){
393 $contents['subject'] = $this->subject;
396 if (!empty($contents['subject_replace'])) {
398 // do not use the mapping
399 if (isset($contents['mapping'])) {
400 foreach ($contents['mapping'] as $pattern => $replace) {
401 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
405 foreach ($contents as $k => $v) {
407 $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
412 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
413 $contents['rcpts'] = implode(',', $contents['rcpts']);
416 $ui = posix_getpwuid(posix_geteuid());
418 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
420 if($force || !$this->isGenerated($cachePath)){
421 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
424 require_once 'Pman/Core/Mailer.php';
426 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
429 'template'=> $this->tableName() . '-' . $this->id,
430 'templateDir' => $templateDir,
432 'contents' => $contents,
433 'css_embed' => true, // we should always try and do this with emails...
436 if (isset($contents['rcpts'])) {
437 $cfg['rcpts'] = $contents['rcpts'];
440 if (isset($contents['attachments'])) {
441 $cfg['attachments'] = $contents['attachments'];
444 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
445 $cfg = array_merge($contents['mailer_opts'], $cfg);
448 if(isset($contents['css_inline'])){
449 $cfg['css_inline'] = $contents['css_inline'];
452 $r = new Pman_Core_Mailer($cfg);
454 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
456 if(file_exists($imageCache) && filesize($imageCache)){
457 $images = json_decode(file_get_contents($imageCache), true);
458 $r->images = $images;
463 function toMailerData($obj,$force=false)
465 $r = $this->toMailer($obj, $force);
466 if (is_a($r, 'PEAR_Error')) {
474 * DEPRICATED !!! - DO NOT USE THIS !!!
476 * use: toMailerData() -- to return the email data..
478 * $mailer = $core_email->toMailer($obj, false);
479 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
481 * toMailer($obj, false)->send()
486 function send($obj, $force = true, $send = true)
489 return $this->toMailerData($obj,$force);
492 $r = $this->toMailer($obj, $force);
494 if (is_a($r, 'PEAR_Error')) {
501 function cachedMailWithOutImages($force = false, $replace_links = true)
504 $ui = posix_getpwuid(posix_geteuid());
506 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
508 if (!$force && $this->isGenerated($cachePath)) {
512 if (!file_exists(dirname($cachePath))) {
513 mkdir(dirname($cachePath), 0700, true);
516 $random_hash = md5(date('r', time()));
518 $this->cachedImages();
520 $fh = fopen($cachePath, 'w');
522 fwrite($fh, implode("\n", array(
523 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
524 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
525 "Subject: {t.subject:h} ",
526 "X-Message-ID: {t.id} ",
527 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
528 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
532 // note the extra space to finish the last line..
534 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
537 Content-Type: text/plain; charset=utf-8; format=flowed
538 Content-Transfer-Encoding: 7bit
547 $this->processRelacements($replace_links);
549 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
551 if (!file_exists(dirname($cachePath))) {
552 mkdir(dirname($cachePath), 0700, true);
555 if (empty($this->use_file)) {
556 file_put_contents($cachePath, $this->bodytext);
559 // use-file -- uses the original template...
560 $mailtext = file_get_contents($this->use_file);
562 require_once 'Mail/mimeDecode.php';
563 require_once 'Mail/RFC822.php';
565 $decoder = new Mail_mimeDecode($mailtext);
566 $parts = $decoder->getSendArray();
567 file_put_contents($cachePath,$parts[2]);
571 function cachedImages()
573 $ui = posix_getpwuid(posix_geteuid());
575 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
577 $ids = $this->attachmentIds();
580 $fh = fopen($imageCache, 'w');
582 $i = DB_DataObject::factory('Images');
583 $i->onid = $this->id;
584 $i->ontable = $this->tableName();
585 $i->whereAddIn('id', $ids, 'int');
590 require_once 'File/MimeType.php';
591 $y = new File_MimeType();
594 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
598 $images["attachment-{$i->id}"] = array(
599 'file' => $i->getStoreName(),
600 'mimetype' => $i->mimetype,
601 'ext' => $y->toExt($i->mimetype),
602 'contentid' => "attachment-$i->id"
606 file_put_contents($imageCache, json_encode($images));
610 function isGenerated($cachePath)
612 if (!file_exists($cachePath) || !filesize($cachePath)) {
616 if (!empty($this->use_file)) {
617 $ctime = filemtime($cachePath);
618 $mtime = filemtime($this->use_file);
619 if($ctime >= $mtime){
628 $ctime = filemtime($cachePath);
630 $mtime[] = $this->updated_dt;
631 $i = DB_DataObject::factory('Images');
632 $i->onid = $this->id;
633 $i->ontable = $this->tableName();
635 $i->selectAdd('max(created) as created');
637 $mtime[] = $i->created;
638 if($ctime >= strtotime(max($mtime))){
645 function messageFrom()
647 if (empty($this->from_name)) {
648 return trim($this->from_email);
650 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
653 function formatDate($dt, $format = 'd/M/Y')
655 return date($format, strtotime($dt));
659 // fixme - this is now in core/udatedatabase..
661 function initMail($mail_template_dir, $name, $master='')
663 $cm = DB_DataObject::factory('core_email');
664 if ($cm->get('name', $name)) {
668 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
672 $opts['file'] = $mail_template_dir. $name .'.html';
673 if (!empty($master)) {
674 $opts['master'] = $mail_template_dir . $master .'.html';
677 require_once 'Pman/Core/Import/Core_email.php';
678 $x = new Pman_Core_Import_Core_email();
684 function testData($person, $dt , $core_notify)
687 // should return the formated email???
688 $pg = HTML_FlexyFramework::get()->page;
693 if(empty($this->test_class)){
694 $pg->jerr("[{$this->name}] does not has test class");
697 require_once "{$this->test_class}.php";
699 $cls = str_replace('/', '_', $this->test_class);
703 $method = "test_{$this->name}";
705 if(!method_exists($x, $method)){
706 $pg->jerr("{$method} does not exists in {$cls}");
709 $content = $x->{$method}($this, $person);
710 $content['to'] = $person->getEmailFrom();
712 $content['bcc'] = array();
713 $data = $this->toMailerData($content);
721 $g = DB_DataObject::Factory('core_group');
722 $g->get($this->to_group_id);