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
66 function beforeDelete($dependants_array, $roo)
68 $i = DB_DataObject::factory('Images');
70 $i->ontable = $this->tableName();
78 function beforeUpdate($old, $request,$roo)
80 if (!empty($request['_make_copy'])) {
81 $this->makeCopy($roo);
85 if ($this->to_group_id != -1) {
87 $c = DB_DataObject::factory('core_group_member');
88 $c->group_id = $this->to_group_id;
91 if (!empty($request['_ignore_group_count'])) {
92 if (!$request['_ignore_group_count']) {
93 $roo->jerr('no_member',array('errcode'=> 100));
96 $roo->jerr('no_member',array('errcode'=> 100));
103 function makeCopy($roo)
105 $c = DB_DataObject::Factory($this->tableName());
107 $c->name = "COPY of " . $this->name;
108 $c->updated_dt = $this->sqlValue('NOW()');
111 $c = DB_DataObject::Factory($this->tableName());
117 $i = DB_DataObject::factory('Images');
118 $i->onid = $this->id;
119 $i->ontable = $this->tableName();
123 $new_image = DB_DataObject::factory('Images');
124 $new_image->onid = $c->id;
125 $new_image->ontable = $this->tableName();
126 $new_image->createFrom($i->getStoreName(), $i->filename);
128 $map[$i->id] = $new_image->id;
132 libxml_use_internal_errors (true);
133 $doc = new DOMDocument('1.0', 'UTF-8');
134 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
135 $doc->formatOutput = true;
137 //echo '<PRE>'; print_R($doc);
140 $xpath = new DOMXpath($doc);
141 foreach ($xpath->query('//img[@src]') as $img) {
142 $href = $img->getAttribute('src');
145 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
149 if (!isset($map[$oid])) {
150 //echo "skip no new id for $oid";
154 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
156 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
162 $c->bodytext = $doc->saveHTML();
164 libxml_use_internal_errors (false);
167 $roo->jok("duplicated");
170 function onInsert($q,$roo)
172 $i = DB_DataObject::factory('Images');
174 $i->ontable = $this->tableName();
178 $i->onid = $this->id;
182 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
183 // $this->cachedMailWithOutImages(true, false);
187 function onUpdate($old, $q,$roo)
189 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
193 function attachmentIds()
195 libxml_use_internal_errors (true);
196 $doc = new DOMDocument('1.0', 'UTF-8');
197 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
199 $xpath = new DOMXpath($doc);
202 foreach ($xpath->query('//img[@src]') as $img) { // process images!
203 $href = $img->getAttribute('src');
204 $cid = explode('#', $href);
208 $cid = explode('-', $cid[1]);
209 if (!isset($cid[1])||!is_numeric($cid[1])) {
218 * process replacements is run to generate a template - not the final content..
222 function processRelacements($replace_links = true)
224 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
226 libxml_use_internal_errors (true);
227 $doc = new DOMDocument('1.0', 'UTF-8');
228 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
230 $xpath = new DOMXpath($doc);
232 foreach ($xpath->query('//img[@src]') as $img) { // process images!
233 $href = $img->getAttribute('src');
234 $hash = explode('#', $href);
235 // we name all our cid's as attachment-*
236 // however the src url may be #image-*
239 if(!isset($hash[1])){
242 $cid = explode('-', $hash[1]);
244 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
248 $unsubscribe = $this->unsubscribe_url();
250 foreach ($xpath->query('//a[@href]') as $a) {
252 $href = $a->getAttribute('href');
254 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
255 $a->setAttribute('href', $unsubscribe);
259 if(!preg_match('/^http(.*)/', $href)){
262 if (!$replace_links) {
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)){
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) && empty($contents['rcpts_group'])) {
363 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group_id,'email');
366 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
369 $contents['bcc'] = $admin ;
371 if (!empty($contents['rcpts_group'])) {
373 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
376 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
378 $contents['rcpts'] = $admin;
381 //subject replacement
382 if(empty($contents['subject'])){
383 $contents['subject'] = $this->subject;
386 if (!empty($contents['subject_replace'])) {
387 foreach ($contents['mapping'] as $pattern => $replace) {
388 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
392 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
393 $contents['rcpts'] = implode(',', $contents['rcpts']);
396 $ui = posix_getpwuid(posix_geteuid());
398 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
400 if($force || !$this->isGenerated($cachePath)){
401 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
404 require_once 'Pman/Core/Mailer.php';
407 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
412 'template'=> $this->tableName() . '-' . $this->id,
413 'templateDir' => $templateDir,
415 'contents' => $contents,
416 'css_embed' => true, // we should always try and do this with emails...
419 if (isset($contents['rcpts'])) {
420 $cfg['rcpts'] = $contents['rcpts'];
423 if (isset($contents['attachments'])) {
424 $cfg['attachments'] = $contents['attachments'];
427 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
428 $cfg = array_merge($contents['mailer_opts'], $cfg);
431 if(isset($contents['css_inline'])){
432 $cfg['css_inline'] = $contents['css_inline'];
435 $r = new Pman_Core_Mailer($cfg);
437 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
439 if(file_exists($imageCache) && filesize($imageCache)){
440 $images = json_decode(file_get_contents($imageCache), true);
441 $r->images = $images;
446 function toMailerData($obj,$force=false)
448 $r = $this->toMailer($obj, $force);
449 if (is_a($r, 'PEAR_Error')) {
457 * DEPRICATED !!! - DO NOT USE THIS !!!
459 * use: toMailerData() -- to return the email data..
461 * $mailer = $core_email->toMailer($obj, false);
462 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
464 * toMailer($obj, false)->send()
469 function send($obj, $force = true, $send = true)
472 return $this->toMailerData($obj,$force);
475 $r = $this->toMailer($obj, $force);
477 if (is_a($r, 'PEAR_Error')) {
484 function cachedMailWithOutImages($force = false, $replace_links = true)
487 $ui = posix_getpwuid(posix_geteuid());
489 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
491 if (!$force && $this->isGenerated($cachePath)) {
495 if (!file_exists(dirname($cachePath))) {
496 mkdir(dirname($cachePath), 0700, true);
499 $random_hash = md5(date('r', time()));
501 $this->cachedImages();
503 $fh = fopen($cachePath, 'w');
505 fwrite($fh, implode("\n", array(
506 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
507 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
508 "Subject: {t.subject:h} ",
509 "X-Message-ID: {t.id} ",
510 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
511 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
515 // note the extra space to finish the last line..
517 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
520 Content-Type: text/plain; charset=utf-8; format=flowed
521 Content-Transfer-Encoding: 7bit
530 $this->processRelacements($replace_links);
532 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
534 if (!file_exists(dirname($cachePath))) {
535 mkdir(dirname($cachePath), 0700, true);
538 file_put_contents($cachePath, $this->bodytext);
542 function cachedImages()
544 $ui = posix_getpwuid(posix_geteuid());
546 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
548 $ids = $this->attachmentIds();
551 $fh = fopen($imageCache, 'w');
553 $i = DB_DataObject::factory('Images');
554 $i->onid = $this->id;
555 $i->ontable = $this->tableName();
556 $i->whereAddIn('id', $ids, 'int');
561 require_once 'File/MimeType.php';
562 $y = new File_MimeType();
565 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
569 $images["attachment-{$i->id}"] = array(
570 'file' => $i->getStoreName(),
571 'mimetype' => $i->mimetype,
572 'ext' => $y->toExt($i->mimetype),
573 'contentid' => "attachment-$i->id"
577 file_put_contents($imageCache, json_encode($images));
581 function isGenerated($cachePath)
583 if (!file_exists($cachePath) || !filesize($cachePath)) {
588 $ctime = filemtime($cachePath);
590 $mtime[] = $this->updated_dt;
591 $i = DB_DataObject::factory('Images');
592 $i->onid = $this->id;
593 $i->ontable = $this->tableName();
595 $i->selectAdd('max(created) as created');
597 $mtime[] = $i->created;
598 if($ctime >= strtotime(max($mtime))){
605 function messageFrom()
607 if (empty($this->from_name)) {
608 return trim($this->from_email);
610 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
613 function formatDate($dt, $format = 'd/M/Y')
615 return date($format, strtotime($dt));
619 // fixme - this is now in core/udatedatabase..
621 function initMail($mail_template_dir, $name, $master='')
623 $cm = DB_DataObject::factory('core_email');
624 if ($cm->get('name', $name)) {
628 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
632 $opts['file'] = $mail_template_dir. $name .'.html';
633 if (!empty($master)) {
634 $opts['master'] = $mail_template_dir . $master .'.html';
637 require_once 'Pman/Core/Import/Core_email.php';
638 $x = new Pman_Core_Import_Core_email();