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
64 if (!empty($_REQUEST['_hide_system_emails'])) {
65 $this->whereAddIn("!{$this->tableName()}.name", array('EVENT_ERRORS_REPORT'), 'string');
70 function beforeDelete($dependants_array, $roo)
72 $i = DB_DataObject::factory('Images');
74 $i->ontable = $this->tableName();
82 function beforeUpdate($old, $request,$roo)
84 if (!empty($request['_make_copy'])) {
85 $this->makeCopy($roo);
89 if ($this->to_group_id != -1) {
91 $c = DB_DataObject::factory('core_group_member');
92 $c->group_id = $this->to_group_id;
94 if (!$c->count() && empty($request['_ignore_group_count'])) {
95 $roo->jerr('Failed to create email template - No member found in recieptent group',array('errcode'=> 100));
100 function makeCopy($roo)
102 $c = DB_DataObject::Factory($this->tableName());
104 $c->name = "COPY of " . $this->name;
105 $c->updated_dt = $this->sqlValue('NOW()');
108 $c = DB_DataObject::Factory($this->tableName());
114 $i = DB_DataObject::factory('Images');
115 $i->onid = $this->id;
116 $i->ontable = $this->tableName();
120 $new_image = DB_DataObject::factory('Images');
121 $new_image->onid = $c->id;
122 $new_image->ontable = $this->tableName();
123 $new_image->createFrom($i->getStoreName(), $i->filename);
125 $map[$i->id] = $new_image->id;
129 libxml_use_internal_errors (true);
130 $doc = new DOMDocument('1.0', 'UTF-8');
131 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
132 $doc->formatOutput = true;
134 //echo '<PRE>'; print_R($doc);
137 $xpath = new DOMXpath($doc);
138 foreach ($xpath->query('//img[@src]') as $img) {
139 $href = $img->getAttribute('src');
142 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
146 if (!isset($map[$oid])) {
147 //echo "skip no new id for $oid";
151 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
153 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
159 $c->bodytext = $doc->saveHTML();
161 libxml_use_internal_errors (false);
164 $roo->jok("duplicated");
167 function onInsert($q,$roo)
169 $i = DB_DataObject::factory('Images');
171 $i->ontable = $this->tableName();
175 $i->onid = $this->id;
179 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
180 // $this->cachedMailWithOutImages(true, false);
184 function onUpdate($old, $q,$roo)
186 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
190 function attachmentIds()
192 libxml_use_internal_errors (true);
193 $doc = new DOMDocument('1.0', 'UTF-8');
194 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
196 $xpath = new DOMXpath($doc);
199 foreach ($xpath->query('//img[@src]') as $img) { // process images!
200 $href = $img->getAttribute('src');
201 $cid = explode('#', $href);
205 $cid = explode('-', $cid[1]);
206 if (!isset($cid[1])||!is_numeric($cid[1])) {
215 * process replacements is run to generate a template - not the final content..
219 function processRelacements($replace_links = true)
221 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
223 libxml_use_internal_errors (true);
224 $doc = new DOMDocument('1.0', 'UTF-8');
225 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
227 $xpath = new DOMXpath($doc);
229 foreach ($xpath->query('//img[@src]') as $img) { // process images!
230 $href = $img->getAttribute('src');
231 $hash = explode('#', $href);
232 // we name all our cid's as attachment-*
233 // however the src url may be #image-*
236 if(!isset($hash[1])){
239 $cid = explode('-', $hash[1]);
241 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
245 $unsubscribe = $this->unsubscribe_url();
247 foreach ($xpath->query('//a[@href]') as $a) {
249 $href = $a->getAttribute('href');
251 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
252 $a->setAttribute('href', $unsubscribe);
256 if(!preg_match('/^http(.*)/', $href)){
259 if (!$replace_links) {
265 // not available if server_baseurl not set... and crm module not used.
266 $link = DB_DataObject::factory('crm_mailing_list_link');
267 $link->setFrom(array(
271 if(!$link->find(true)){
279 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
281 $a->setAttribute('href', $l);
285 if(!empty($unsubscribe) && !empty($cfg)){
286 $element = $doc->createElement('img');
287 $element->setAttribute('mailembed', 'no');
288 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
289 $element->setAttribute('width', '1');
290 $element->setAttribute('height', '1');
292 $html = $doc->getElementsByTagName('html');
294 $html->item(0)->appendChild($element);
297 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
301 $this->bodytext = $doc->saveHTML();
303 libxml_use_internal_errors (false);
305 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
306 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
311 function unsubscribe_url()
313 $unsubscribe = false;
315 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
318 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
325 * convert email with contents into a core mailer object. - ready to send..
326 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
328 * + rcpts || person << if person is set - then it goes to them...
329 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
333 * + person << who it actually goes to..
335 * @param bool $force - force re-creation of cached version of email.
337 * @returns Pman_Core_Mailer||PEAR_Error
340 function toMailer($obj,$force=false)
342 require_once 'PEAR.php';
345 $contents = (array)$obj;
347 if(empty($this->id) && !empty($contents['template'])){
348 $this->get('name', $contents['template']);
352 if(empty($this->active)){
353 return $p->raiseError("template [{$contents['template']}] is Disabled");
357 if(empty($this->id)){
358 return $p->raiseError("template [{$contents['template']}] has not been set");
363 if (!empty($this->bcc_group_id) && $this->bcc_group_id > 0 && empty($contents['bcc']) && empty($contents['rcpts_group'])) {
364 $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
366 $admin = $admin_grp ? $admin_grp->members('email') : false;
368 if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
369 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
372 $contents['bcc'] = $admin ;
374 if (!empty($contents['rcpts_group'])) {
376 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
379 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
381 $contents['rcpts'] = $admin;
383 if (empty($contents['rcpts']) && $this->to_group_id > 0) {
384 $members = $this->to_group()->members();
385 $contents['rcpts'] = array();
386 foreach($this->to_group()->members() as $m) {
387 $contents['rcpts'][] = $m->email;
389 //var_dump($contents['rcpts']);
392 //subject replacement
393 if(empty($contents['subject'])){
394 $contents['subject'] = $this->subject;
397 if (!empty($contents['subject_replace'])) {
399 // do not use the mapping
400 if (isset($contents['mapping'])) {
401 foreach ($contents['mapping'] as $pattern => $replace) {
402 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
406 foreach ($contents as $k => $v) {
408 $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
413 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
414 $contents['rcpts'] = implode(',', $contents['rcpts']);
417 $ui = posix_getpwuid(posix_geteuid());
419 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
421 if($force || !$this->isGenerated($cachePath)){
422 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
425 require_once 'Pman/Core/Mailer.php';
427 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
430 'template'=> $this->tableName() . '-' . $this->id,
431 'templateDir' => $templateDir,
433 'contents' => $contents,
434 'css_embed' => true, // we should always try and do this with emails...
437 if (isset($contents['rcpts'])) {
438 $cfg['rcpts'] = $contents['rcpts'];
441 if (isset($contents['attachments'])) {
442 $cfg['attachments'] = $contents['attachments'];
445 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
446 $cfg = array_merge($contents['mailer_opts'], $cfg);
449 if(isset($contents['css_inline'])){
450 $cfg['css_inline'] = $contents['css_inline'];
453 $r = new Pman_Core_Mailer($cfg);
455 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
457 if(file_exists($imageCache) && filesize($imageCache)){
458 $images = json_decode(file_get_contents($imageCache), true);
459 $r->images = $images;
464 function toMailerData($obj,$force=false)
466 $r = $this->toMailer($obj, $force);
467 if (is_a($r, 'PEAR_Error')) {
475 * DEPRICATED !!! - DO NOT USE THIS !!!
477 * use: toMailerData() -- to return the email data..
479 * $mailer = $core_email->toMailer($obj, false);
480 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
482 * toMailer($obj, false)->send()
487 function send($obj, $force = true, $send = true)
490 return $this->toMailerData($obj,$force);
493 $r = $this->toMailer($obj, $force);
495 if (is_a($r, 'PEAR_Error')) {
502 function cachedMailWithOutImages($force = false, $replace_links = true)
505 $ui = posix_getpwuid(posix_geteuid());
507 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
509 if (!$force && $this->isGenerated($cachePath)) {
513 if (!file_exists(dirname($cachePath))) {
514 mkdir(dirname($cachePath), 0700, true);
517 $random_hash = md5(date('r', time()));
519 $this->cachedImages();
521 $fh = fopen($cachePath, 'w');
523 fwrite($fh, implode("\n", array(
524 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
525 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
526 "Subject: {t.subject:h} ",
527 "X-Message-ID: {t.id} ",
528 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
529 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
533 // note the extra space to finish the last line..
535 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
538 Content-Type: text/plain; charset=utf-8; format=flowed
539 Content-Transfer-Encoding: 7bit
548 $this->processRelacements($replace_links);
550 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
552 if (!file_exists(dirname($cachePath))) {
553 mkdir(dirname($cachePath), 0700, true);
556 if (empty($this->use_file)) {
557 file_put_contents($cachePath, $this->bodytext);
560 // use-file -- uses the original template...
561 $mailtext = file_get_contents($this->use_file);
563 require_once 'Mail/mimeDecode.php';
564 require_once 'Mail/RFC822.php';
566 $decoder = new Mail_mimeDecode($mailtext);
567 $parts = $decoder->getSendArray();
568 file_put_contents($cachePath,$parts[2]);
572 function cachedImages()
574 $ui = posix_getpwuid(posix_geteuid());
576 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
578 $ids = $this->attachmentIds();
581 $fh = fopen($imageCache, 'w');
583 $i = DB_DataObject::factory('Images');
584 $i->onid = $this->id;
585 $i->ontable = $this->tableName();
586 $i->whereAddIn('id', $ids, 'int');
591 require_once 'File/MimeType.php';
592 $y = new File_MimeType();
595 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
599 $images["attachment-{$i->id}"] = array(
600 'file' => $i->getStoreName(),
601 'mimetype' => $i->mimetype,
602 'ext' => $y->toExt($i->mimetype),
603 'contentid' => "attachment-$i->id"
607 file_put_contents($imageCache, json_encode($images));
611 function isGenerated($cachePath)
613 if (!file_exists($cachePath) || !filesize($cachePath)) {
617 if (!empty($this->use_file)) {
618 $ctime = filemtime($cachePath);
619 $mtime = filemtime($this->use_file);
620 if($ctime >= $mtime){
629 $ctime = filemtime($cachePath);
631 $mtime[] = $this->updated_dt;
632 $i = DB_DataObject::factory('Images');
633 $i->onid = $this->id;
634 $i->ontable = $this->tableName();
636 $i->selectAdd('max(created) as created');
638 $mtime[] = $i->created;
639 if($ctime >= strtotime(max($mtime))){
646 function messageFrom()
648 if (empty($this->from_name)) {
649 return trim($this->from_email);
651 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
654 function formatDate($dt, $format = 'd/M/Y')
656 return date($format, strtotime($dt));
660 // fixme - this is now in core/udatedatabase..
662 function initMail($mail_template_dir, $name, $master='')
664 $cm = DB_DataObject::factory('core_email');
665 if ($cm->get('name', $name)) {
669 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
673 $opts['file'] = $mail_template_dir. $name .'.html';
674 if (!empty($master)) {
675 $opts['master'] = $mail_template_dir . $master .'.html';
678 require_once 'Pman/Core/Import/Core_email.php';
679 $x = new Pman_Core_Import_Core_email();
685 function testData($person, $dt , $core_notify)
688 // should return the formated email???
689 $pg = HTML_FlexyFramework::get()->page;
694 if(empty($this->test_class)){
695 $pg->jerr("[{$this->name}] does not has test class");
698 require_once "{$this->test_class}.php";
700 $cls = str_replace('/', '_', $this->test_class);
704 $method = "test_{$this->name}";
706 if(!method_exists($x, $method)){
707 $pg->jerr("{$method} does not exists in {$cls}");
710 $content = $x->{$method}($this, $person);
711 $content['to'] = $person->getEmailFrom();
713 $content['bcc'] = array();
714 $data = $this->toMailerData($content);
722 $g = DB_DataObject::Factory('core_group');
723 $g->get($this->to_group_id);