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
30 /* the code above is auto generated do not remove the tag below */
33 function applyFilters($q, $au, $roo)
35 $tn = $this->tableName();
37 if(!empty($q['search']['nameortitle'])){
39 $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
41 $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
52 to_group_id = core_group_member.group_id
58 function beforeDelete($dependants_array, $roo)
60 $i = DB_DataObject::factory('Images');
62 $i->ontable = $this->tableName();
70 function beforeUpdate($old, $request,$roo)
72 if (!empty($request['_make_copy'])) {
73 $this->makeCopy($roo);
77 if ($this->to_group != -1) {
78 $c = DB_DataObject::factory('core_group_member');
80 'groud_id' => $this->to_group
82 print_r($this->to_group);
84 print_r($c->count());exit;
85 if (!$c->find(true)) {
91 function makeCopy($roo)
93 $c = DB_DataObject::Factory($this->tableName());
95 $c->name = "COPY of " . $this->name;
96 $c->updated_dt = $this->sqlValue('NOW()');
99 $c = DB_DataObject::Factory($this->tableName());
105 $i = DB_DataObject::factory('Images');
106 $i->onid = $this->id;
107 $i->ontable = $this->tableName();
111 $new_image = DB_DataObject::factory('Images');
112 $new_image->onid = $c->id;
113 $new_image->ontable = $this->tableName();
114 $new_image->createFrom($i->getStoreName(), $i->filename);
116 $map[$i->id] = $new_image->id;
120 libxml_use_internal_errors (true);
121 $doc = new DOMDocument('1.0', 'UTF-8');
122 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
123 $doc->formatOutput = true;
125 //echo '<PRE>'; print_R($doc);
128 $xpath = new DOMXpath($doc);
129 foreach ($xpath->query('//img[@src]') as $img) {
130 $href = $img->getAttribute('src');
133 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
137 if (!isset($map[$oid])) {
138 //echo "skip no new id for $oid";
142 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
144 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
150 $c->bodytext = $doc->saveHTML();
152 libxml_use_internal_errors (false);
155 $roo->jok("duplicated");
158 function onInsert($q,$roo)
160 $i = DB_DataObject::factory('Images');
162 $i->ontable = $this->tableName();
166 $i->onid = $this->id;
170 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
171 // $this->cachedMailWithOutImages(true, false);
175 function onUpdate($old, $q,$roo)
177 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
181 function attachmentIds()
183 libxml_use_internal_errors (true);
184 $doc = new DOMDocument('1.0', 'UTF-8');
185 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
187 $xpath = new DOMXpath($doc);
190 foreach ($xpath->query('//img[@src]') as $img) { // process images!
191 $href = $img->getAttribute('src');
192 $cid = explode('#', $href);
196 $cid = explode('-', $cid[1]);
197 if (!isset($cid[1])||!is_numeric($cid[1])) {
206 * process replacements is run to generate a template - not the final content..
210 function processRelacements($replace_links = true)
212 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
214 libxml_use_internal_errors (true);
215 $doc = new DOMDocument('1.0', 'UTF-8');
216 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
218 $xpath = new DOMXpath($doc);
220 foreach ($xpath->query('//img[@src]') as $img) { // process images!
221 $href = $img->getAttribute('src');
222 $hash = explode('#', $href);
223 // we name all our cid's as attachment-*
224 // however the src url may be #image-*
227 if(!isset($hash[1])){
230 $cid = explode('-', $hash[1]);
232 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
236 $unsubscribe = $this->unsubscribe_url();
238 foreach ($xpath->query('//a[@href]') as $a) {
240 $href = $a->getAttribute('href');
242 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
243 $a->setAttribute('href', $unsubscribe);
247 if(!preg_match('/^http(.*)/', $href)){
250 if (!$replace_links) {
253 $link = DB_DataObject::factory('crm_mailing_list_link');
254 $link->setFrom(array(
258 if(!$link->find(true)){
266 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
268 $a->setAttribute('href', $l);
272 if(!empty($unsubscribe)){
273 $element = $doc->createElement('img');
274 $element->setAttribute('mailembed', 'no');
275 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
276 $element->setAttribute('width', '1');
277 $element->setAttribute('height', '1');
279 $html = $doc->getElementsByTagName('html');
281 $html->item(0)->appendChild($element);
284 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
288 $this->bodytext = $doc->saveHTML();
290 libxml_use_internal_errors (false);
292 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
293 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
298 function unsubscribe_url()
300 $unsubscribe = false;
302 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
305 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
312 * convert email with contents into a core mailer object. - ready to send..
313 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
315 * + rcpts || person << if person is set - then it goes to them...
316 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
320 * + person << who it actually goes to..
322 * @param bool $force - force re-creation of cached version of email.
324 * @returns Pman_Core_Mailer||PEAR_Error
327 function toMailer($obj,$force=false)
329 require_once 'PEAR.php';
332 $contents = (array)$obj;
334 if(empty($this->id) && !empty($contents['template'])){
335 $this->get('name', $contents['template']);
339 if(empty($this->active)){
340 return $p->raiseError("template [{$contents['template']}] is Disabled");
344 if(empty($this->id)){
345 return $p->raiseError("template [{$contents['template']}] has not been set");
350 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
351 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
354 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
357 $contents['bcc'] = $admin ;
359 if (!empty($contents['rcpts_group'])) {
361 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
364 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
366 $contents['rcpts'] = $admin;
369 //subject replacement
370 if(empty($contents['subject'])){
371 $contents['subject'] = $this->subject;
374 if (!empty($contents['subject_replace'])) {
375 foreach ($contents['mapping'] as $pattern => $replace) {
376 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
380 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
381 $contents['rcpts'] = implode(',', $contents['rcpts']);
384 $ui = posix_getpwuid(posix_geteuid());
386 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
388 if($force || !$this->isGenerated($cachePath)){
389 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
392 require_once 'Pman/Core/Mailer.php';
395 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
400 'template'=> $this->tableName() . '-' . $this->id,
401 'templateDir' => $templateDir,
403 'contents' => $contents,
404 'css_embed' => true, // we should always try and do this with emails...
407 if (isset($contents['rcpts'])) {
408 $cfg['rcpts'] = $contents['rcpts'];
411 if (isset($contents['attachments'])) {
412 $cfg['attachments'] = $contents['attachments'];
415 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
416 $cfg = array_merge($contents['mailer_opts'], $cfg);
419 $r = new Pman_Core_Mailer($cfg);
421 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
423 if(file_exists($imageCache) && filesize($imageCache)){
424 $images = json_decode(file_get_contents($imageCache), true);
425 $r->images = $images;
430 function toMailerData($obj,$force=false)
432 $r = $this->toMailer($obj, $force);
433 if (is_a($r, 'PEAR_Error')) {
441 * DEPRICATED !!! - DO NOT USE THIS !!!
443 * use: toMailerData() -- to return the email data..
445 * $mailer = $core_email->toMailer($obj, false);
446 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
448 * toMailer($obj, false)->send()
453 function send($obj, $force = true, $send = true)
456 return $this->toMailerData($obj,$force);
459 $r = $this->toMailer($obj, $force);
461 if (is_a($r, 'PEAR_Error')) {
468 function cachedMailWithOutImages($force = false, $replace_links = true)
471 $ui = posix_getpwuid(posix_geteuid());
473 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
475 if (!$force && $this->isGenerated($cachePath)) {
479 if (!file_exists(dirname($cachePath))) {
480 mkdir(dirname($cachePath), 0700, true);
483 $random_hash = md5(date('r', time()));
485 $this->cachedImages();
487 $fh = fopen($cachePath, 'w');
489 fwrite($fh, implode("\n", array(
490 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
491 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
492 "Subject: {t.subject:h} ",
493 "X-Message-ID: {t.id} ",
494 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
495 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
499 // note the extra space to finish the last line..
501 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
504 Content-Type: text/plain; charset=utf-8; format=flowed
505 Content-Transfer-Encoding: 7bit
514 $this->processRelacements($replace_links);
516 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
518 if (!file_exists(dirname($cachePath))) {
519 mkdir(dirname($cachePath), 0700, true);
522 file_put_contents($cachePath, $this->bodytext);
526 function cachedImages()
528 $ui = posix_getpwuid(posix_geteuid());
530 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
532 $ids = $this->attachmentIds();
535 $fh = fopen($imageCache, 'w');
537 $i = DB_DataObject::factory('Images');
538 $i->onid = $this->id;
539 $i->ontable = $this->tableName();
540 $i->whereAddIn('id', $ids, 'int');
545 require_once 'File/MimeType.php';
546 $y = new File_MimeType();
549 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
553 $images["attachment-{$i->id}"] = array(
554 'file' => $i->getStoreName(),
555 'mimetype' => $i->mimetype,
556 'ext' => $y->toExt($i->mimetype),
557 'contentid' => "attachment-$i->id"
561 file_put_contents($imageCache, json_encode($images));
565 function isGenerated($cachePath)
567 if (!file_exists($cachePath) || !filesize($cachePath)) {
572 $ctime = filemtime($cachePath);
574 $mtime[] = $this->updated_dt;
575 $i = DB_DataObject::factory('Images');
576 $i->onid = $this->id;
577 $i->ontable = $this->tableName();
579 $i->selectAdd('max(created) as created');
581 $mtime[] = $i->created;
582 if($ctime >= strtotime(max($mtime))){
589 function messageFrom()
591 if (empty($this->from_name)) {
592 return trim($this->from_email);
594 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
597 function formatDate($dt, $format = 'd/M/Y')
599 return date($format, strtotime($dt));
603 // fixme - this is now in core/udatedatabase..
605 function initMail($mail_template_dir, $name, $master='')
607 $cm = DB_DataObject::factory('core_email');
608 if ($cm->get('name', $name)) {
612 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
616 $opts['file'] = $mail_template_dir. $name .'.html';
617 if (!empty($master)) {
618 $opts['master'] = $mail_template_dir . $master .'.html';
621 require_once 'Pman/Core/Import/Core_email.php';
622 $x = new Pman_Core_Import_Core_email();