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->whereAdd(" name NOT IN (
73 function beforeDelete($dependants_array, $roo)
75 $i = DB_DataObject::factory('Images');
77 $i->ontable = $this->tableName();
85 function beforeUpdate($old, $request,$roo)
87 if (!empty($request['_make_copy'])) {
88 $this->makeCopy($roo);
92 if ($this->to_group_id != -1) {
94 $c = DB_DataObject::factory('core_group_member');
95 $c->group_id = $this->to_group_id;
98 //cannot go to second check
99 if (!empty($request['_ignore_group_count'])) {
100 if (!$request['_ignore_group_count']) {
101 $roo->jerr('no_member',array('errcode'=> 100));
104 $roo->jerr('no_member',array('errcode'=> 100));
111 function makeCopy($roo)
113 $c = DB_DataObject::Factory($this->tableName());
115 $c->name = "COPY of " . $this->name;
116 $c->updated_dt = $this->sqlValue('NOW()');
119 $c = DB_DataObject::Factory($this->tableName());
125 $i = DB_DataObject::factory('Images');
126 $i->onid = $this->id;
127 $i->ontable = $this->tableName();
131 $new_image = DB_DataObject::factory('Images');
132 $new_image->onid = $c->id;
133 $new_image->ontable = $this->tableName();
134 $new_image->createFrom($i->getStoreName(), $i->filename);
136 $map[$i->id] = $new_image->id;
140 libxml_use_internal_errors (true);
141 $doc = new DOMDocument('1.0', 'UTF-8');
142 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
143 $doc->formatOutput = true;
145 //echo '<PRE>'; print_R($doc);
148 $xpath = new DOMXpath($doc);
149 foreach ($xpath->query('//img[@src]') as $img) {
150 $href = $img->getAttribute('src');
153 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
157 if (!isset($map[$oid])) {
158 //echo "skip no new id for $oid";
162 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
164 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
170 $c->bodytext = $doc->saveHTML();
172 libxml_use_internal_errors (false);
175 $roo->jok("duplicated");
178 function onInsert($q,$roo)
180 $i = DB_DataObject::factory('Images');
182 $i->ontable = $this->tableName();
186 $i->onid = $this->id;
190 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
191 // $this->cachedMailWithOutImages(true, false);
195 function onUpdate($old, $q,$roo)
197 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
201 function attachmentIds()
203 libxml_use_internal_errors (true);
204 $doc = new DOMDocument('1.0', 'UTF-8');
205 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
207 $xpath = new DOMXpath($doc);
210 foreach ($xpath->query('//img[@src]') as $img) { // process images!
211 $href = $img->getAttribute('src');
212 $cid = explode('#', $href);
216 $cid = explode('-', $cid[1]);
217 if (!isset($cid[1])||!is_numeric($cid[1])) {
226 * process replacements is run to generate a template - not the final content..
230 function processRelacements($replace_links = true)
232 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
234 libxml_use_internal_errors (true);
235 $doc = new DOMDocument('1.0', 'UTF-8');
236 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
238 $xpath = new DOMXpath($doc);
240 foreach ($xpath->query('//img[@src]') as $img) { // process images!
241 $href = $img->getAttribute('src');
242 $hash = explode('#', $href);
243 // we name all our cid's as attachment-*
244 // however the src url may be #image-*
247 if(!isset($hash[1])){
250 $cid = explode('-', $hash[1]);
252 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
256 $unsubscribe = $this->unsubscribe_url();
258 foreach ($xpath->query('//a[@href]') as $a) {
260 $href = $a->getAttribute('href');
262 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
263 $a->setAttribute('href', $unsubscribe);
267 if(!preg_match('/^http(.*)/', $href)){
270 if (!$replace_links) {
276 // not available if server_baseurl not set... and crm module not used.
277 $link = DB_DataObject::factory('crm_mailing_list_link');
278 $link->setFrom(array(
282 if(!$link->find(true)){
290 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
292 $a->setAttribute('href', $l);
296 if(!empty($unsubscribe) && !empty($cfg)){
297 $element = $doc->createElement('img');
298 $element->setAttribute('mailembed', 'no');
299 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
300 $element->setAttribute('width', '1');
301 $element->setAttribute('height', '1');
303 $html = $doc->getElementsByTagName('html');
305 $html->item(0)->appendChild($element);
308 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
312 $this->bodytext = $doc->saveHTML();
314 libxml_use_internal_errors (false);
316 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
317 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
322 function unsubscribe_url()
324 $unsubscribe = false;
326 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
329 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
336 * convert email with contents into a core mailer object. - ready to send..
337 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
339 * + rcpts || person << if person is set - then it goes to them...
340 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
344 * + person << who it actually goes to..
346 * @param bool $force - force re-creation of cached version of email.
348 * @returns Pman_Core_Mailer||PEAR_Error
351 function toMailer($obj,$force=false)
353 require_once 'PEAR.php';
356 $contents = (array)$obj;
358 if(empty($this->id) && !empty($contents['template'])){
359 $this->get('name', $contents['template']);
363 if(empty($this->active)){
364 return $p->raiseError("template [{$contents['template']}] is Disabled");
368 if(empty($this->id)){
369 return $p->raiseError("template [{$contents['template']}] has not been set");
374 if (!empty($this->bcc_group_id) && $this->bcc_group_id > 0 && empty($contents['bcc']) && empty($contents['rcpts_group'])) {
375 $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
376 $admin = $admin_grp->members('email');
378 if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
379 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
382 $contents['bcc'] = $admin ;
384 if (!empty($contents['rcpts_group'])) {
386 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
389 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
391 $contents['rcpts'] = $admin;
394 //subject replacement
395 if(empty($contents['subject'])){
396 $contents['subject'] = $this->subject;
399 if (!empty($contents['subject_replace'])) {
401 // do not use the mapping
402 if (isset($contents['mapping'])) {
403 foreach ($contents['mapping'] as $pattern => $replace) {
404 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
408 foreach ($contents as $k => $v) {
410 $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
415 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
416 $contents['rcpts'] = implode(',', $contents['rcpts']);
419 $ui = posix_getpwuid(posix_geteuid());
421 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
423 if($force || !$this->isGenerated($cachePath)){
424 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
427 require_once 'Pman/Core/Mailer.php';
429 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
432 'template'=> $this->tableName() . '-' . $this->id,
433 'templateDir' => $templateDir,
435 'contents' => $contents,
436 'css_embed' => true, // we should always try and do this with emails...
439 if (isset($contents['rcpts'])) {
440 $cfg['rcpts'] = $contents['rcpts'];
443 if (isset($contents['attachments'])) {
444 $cfg['attachments'] = $contents['attachments'];
447 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
448 $cfg = array_merge($contents['mailer_opts'], $cfg);
451 if(isset($contents['css_inline'])){
452 $cfg['css_inline'] = $contents['css_inline'];
455 $r = new Pman_Core_Mailer($cfg);
457 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
459 if(file_exists($imageCache) && filesize($imageCache)){
460 $images = json_decode(file_get_contents($imageCache), true);
461 $r->images = $images;
466 function toMailerData($obj,$force=false)
468 $r = $this->toMailer($obj, $force);
469 if (is_a($r, 'PEAR_Error')) {
477 * DEPRICATED !!! - DO NOT USE THIS !!!
479 * use: toMailerData() -- to return the email data..
481 * $mailer = $core_email->toMailer($obj, false);
482 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
484 * toMailer($obj, false)->send()
489 function send($obj, $force = true, $send = true)
492 return $this->toMailerData($obj,$force);
495 $r = $this->toMailer($obj, $force);
497 if (is_a($r, 'PEAR_Error')) {
504 function cachedMailWithOutImages($force = false, $replace_links = true)
507 $ui = posix_getpwuid(posix_geteuid());
509 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
511 if (!$force && $this->isGenerated($cachePath)) {
515 if (!file_exists(dirname($cachePath))) {
516 mkdir(dirname($cachePath), 0700, true);
519 $random_hash = md5(date('r', time()));
521 $this->cachedImages();
523 $fh = fopen($cachePath, 'w');
525 fwrite($fh, implode("\n", array(
526 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
527 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
528 "Subject: {t.subject:h} ",
529 "X-Message-ID: {t.id} ",
530 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
531 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
535 // note the extra space to finish the last line..
537 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
540 Content-Type: text/plain; charset=utf-8; format=flowed
541 Content-Transfer-Encoding: 7bit
550 $this->processRelacements($replace_links);
552 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
554 if (!file_exists(dirname($cachePath))) {
555 mkdir(dirname($cachePath), 0700, true);
558 if (empty($this->use_file)) {
559 file_put_contents($cachePath, $this->bodytext);
562 // use-file -- uses the original template...
563 $mailtext = file_get_contents($this->use_file);
565 require_once 'Mail/mimeDecode.php';
566 require_once 'Mail/RFC822.php';
568 $decoder = new Mail_mimeDecode($mailtext);
569 $parts = $decoder->getSendArray();
570 file_put_contents($cachePath,$parts[2]);
574 function cachedImages()
576 $ui = posix_getpwuid(posix_geteuid());
578 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
580 $ids = $this->attachmentIds();
583 $fh = fopen($imageCache, 'w');
585 $i = DB_DataObject::factory('Images');
586 $i->onid = $this->id;
587 $i->ontable = $this->tableName();
588 $i->whereAddIn('id', $ids, 'int');
593 require_once 'File/MimeType.php';
594 $y = new File_MimeType();
597 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
601 $images["attachment-{$i->id}"] = array(
602 'file' => $i->getStoreName(),
603 'mimetype' => $i->mimetype,
604 'ext' => $y->toExt($i->mimetype),
605 'contentid' => "attachment-$i->id"
609 file_put_contents($imageCache, json_encode($images));
613 function isGenerated($cachePath)
615 if (!file_exists($cachePath) || !filesize($cachePath)) {
619 if (!empty($this->use_file)) {
620 $ctime = filemtime($cachePath);
621 $mtime = filemtime($this->use_file);
622 if($ctime >= $mtime){
631 $ctime = filemtime($cachePath);
633 $mtime[] = $this->updated_dt;
634 $i = DB_DataObject::factory('Images');
635 $i->onid = $this->id;
636 $i->ontable = $this->tableName();
638 $i->selectAdd('max(created) as created');
640 $mtime[] = $i->created;
641 if($ctime >= strtotime(max($mtime))){
648 function messageFrom()
650 if (empty($this->from_name)) {
651 return trim($this->from_email);
653 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
656 function formatDate($dt, $format = 'd/M/Y')
658 return date($format, strtotime($dt));
662 // fixme - this is now in core/udatedatabase..
664 function initMail($mail_template_dir, $name, $master='')
666 $cm = DB_DataObject::factory('core_email');
667 if ($cm->get('name', $name)) {
671 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
675 $opts['file'] = $mail_template_dir. $name .'.html';
676 if (!empty($master)) {
677 $opts['master'] = $mail_template_dir . $master .'.html';
680 require_once 'Pman/Core/Import/Core_email.php';
681 $x = new Pman_Core_Import_Core_email();