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
54 AS group_member_count,
62 bcc_group_id = {$cgm}.group_id
64 AS bcc_group_member_count
68 function beforeDelete($dependants_array, $roo)
70 $i = DB_DataObject::factory('Images');
72 $i->ontable = $this->tableName();
80 function beforeUpdate($old, $request,$roo)
82 if (!empty($request['_make_copy'])) {
83 $this->makeCopy($roo);
87 if ($this->to_group_id != -1) {
89 $c = DB_DataObject::factory('core_group_member');
90 $c->group_id = $this->to_group_id;
93 if (!empty($request['_ignore_group_count'])) {
94 if (!$request['_ignore_group_count']) {
95 $roo->jerr('no_member',array('errcode'=> 100));
98 $roo->jerr('no_member',array('errcode'=> 100));
105 function makeCopy($roo)
107 $c = DB_DataObject::Factory($this->tableName());
109 $c->name = "COPY of " . $this->name;
110 $c->updated_dt = $this->sqlValue('NOW()');
113 $c = DB_DataObject::Factory($this->tableName());
119 $i = DB_DataObject::factory('Images');
120 $i->onid = $this->id;
121 $i->ontable = $this->tableName();
125 $new_image = DB_DataObject::factory('Images');
126 $new_image->onid = $c->id;
127 $new_image->ontable = $this->tableName();
128 $new_image->createFrom($i->getStoreName(), $i->filename);
130 $map[$i->id] = $new_image->id;
134 libxml_use_internal_errors (true);
135 $doc = new DOMDocument('1.0', 'UTF-8');
136 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
137 $doc->formatOutput = true;
139 //echo '<PRE>'; print_R($doc);
142 $xpath = new DOMXpath($doc);
143 foreach ($xpath->query('//img[@src]') as $img) {
144 $href = $img->getAttribute('src');
147 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
151 if (!isset($map[$oid])) {
152 //echo "skip no new id for $oid";
156 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
158 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
164 $c->bodytext = $doc->saveHTML();
166 libxml_use_internal_errors (false);
169 $roo->jok("duplicated");
172 function onInsert($q,$roo)
174 $i = DB_DataObject::factory('Images');
176 $i->ontable = $this->tableName();
180 $i->onid = $this->id;
184 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
185 // $this->cachedMailWithOutImages(true, false);
189 function onUpdate($old, $q,$roo)
191 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
195 function attachmentIds()
197 libxml_use_internal_errors (true);
198 $doc = new DOMDocument('1.0', 'UTF-8');
199 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
201 $xpath = new DOMXpath($doc);
204 foreach ($xpath->query('//img[@src]') as $img) { // process images!
205 $href = $img->getAttribute('src');
206 $cid = explode('#', $href);
210 $cid = explode('-', $cid[1]);
211 if (!isset($cid[1])||!is_numeric($cid[1])) {
220 * process replacements is run to generate a template - not the final content..
224 function processRelacements($replace_links = true)
226 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
228 libxml_use_internal_errors (true);
229 $doc = new DOMDocument('1.0', 'UTF-8');
230 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
232 $xpath = new DOMXpath($doc);
234 foreach ($xpath->query('//img[@src]') as $img) { // process images!
235 $href = $img->getAttribute('src');
236 $hash = explode('#', $href);
237 // we name all our cid's as attachment-*
238 // however the src url may be #image-*
241 if(!isset($hash[1])){
244 $cid = explode('-', $hash[1]);
246 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
250 $unsubscribe = $this->unsubscribe_url();
252 foreach ($xpath->query('//a[@href]') as $a) {
254 $href = $a->getAttribute('href');
256 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
257 $a->setAttribute('href', $unsubscribe);
261 if(!preg_match('/^http(.*)/', $href)){
264 if (!$replace_links) {
267 $link = DB_DataObject::factory('crm_mailing_list_link');
268 $link->setFrom(array(
272 if(!$link->find(true)){
280 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
282 $a->setAttribute('href', $l);
286 if(!empty($unsubscribe)){
287 $element = $doc->createElement('img');
288 $element->setAttribute('mailembed', 'no');
289 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
290 $element->setAttribute('width', '1');
291 $element->setAttribute('height', '1');
293 $html = $doc->getElementsByTagName('html');
295 $html->item(0)->appendChild($element);
298 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
302 $this->bodytext = $doc->saveHTML();
304 libxml_use_internal_errors (false);
306 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
307 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
312 function unsubscribe_url()
314 $unsubscribe = false;
316 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
319 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
326 * convert email with contents into a core mailer object. - ready to send..
327 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
329 * + rcpts || person << if person is set - then it goes to them...
330 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
334 * + person << who it actually goes to..
336 * @param bool $force - force re-creation of cached version of email.
338 * @returns Pman_Core_Mailer||PEAR_Error
341 function toMailer($obj,$force=false)
343 require_once 'PEAR.php';
346 $contents = (array)$obj;
348 if(empty($this->id) && !empty($contents['template'])){
349 $this->get('name', $contents['template']);
353 if(empty($this->active)){
354 return $p->raiseError("template [{$contents['template']}] is Disabled");
358 if(empty($this->id)){
359 return $p->raiseError("template [{$contents['template']}] has not been set");
364 if (!empty($this->bcc_group_id) && empty($contents['rcpts_group'])) {
365 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group_id,'email');
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;
383 //subject replacement
384 if(empty($contents['subject'])){
385 $contents['subject'] = $this->subject;
388 if (!empty($contents['subject_replace'])) {
389 foreach ($contents['mapping'] as $pattern => $replace) {
390 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
394 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
395 $contents['rcpts'] = implode(',', $contents['rcpts']);
398 $ui = posix_getpwuid(posix_geteuid());
400 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
402 if($force || !$this->isGenerated($cachePath)){
403 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
406 require_once 'Pman/Core/Mailer.php';
409 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
414 'template'=> $this->tableName() . '-' . $this->id,
415 'templateDir' => $templateDir,
417 'contents' => $contents,
418 'css_embed' => true, // we should always try and do this with emails...
421 if (isset($contents['rcpts'])) {
422 $cfg['rcpts'] = $contents['rcpts'];
425 if (isset($contents['attachments'])) {
426 $cfg['attachments'] = $contents['attachments'];
429 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
430 $cfg = array_merge($contents['mailer_opts'], $cfg);
433 if(isset($contents['css_inline'])){
434 $cfg['css_inline'] = $contents['css_inline'];
437 $r = new Pman_Core_Mailer($cfg);
439 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
441 if(file_exists($imageCache) && filesize($imageCache)){
442 $images = json_decode(file_get_contents($imageCache), true);
443 $r->images = $images;
448 function toMailerData($obj,$force=false)
450 $r = $this->toMailer($obj, $force);
451 if (is_a($r, 'PEAR_Error')) {
459 * DEPRICATED !!! - DO NOT USE THIS !!!
461 * use: toMailerData() -- to return the email data..
463 * $mailer = $core_email->toMailer($obj, false);
464 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
466 * toMailer($obj, false)->send()
471 function send($obj, $force = true, $send = true)
474 return $this->toMailerData($obj,$force);
477 $r = $this->toMailer($obj, $force);
479 if (is_a($r, 'PEAR_Error')) {
486 function cachedMailWithOutImages($force = false, $replace_links = true)
489 $ui = posix_getpwuid(posix_geteuid());
491 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
493 if (!$force && $this->isGenerated($cachePath)) {
497 if (!file_exists(dirname($cachePath))) {
498 mkdir(dirname($cachePath), 0700, true);
501 $random_hash = md5(date('r', time()));
503 $this->cachedImages();
505 $fh = fopen($cachePath, 'w');
507 fwrite($fh, implode("\n", array(
508 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
509 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
510 "Subject: {t.subject:h} ",
511 "X-Message-ID: {t.id} ",
512 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
513 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
517 // note the extra space to finish the last line..
519 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
522 Content-Type: text/plain; charset=utf-8; format=flowed
523 Content-Transfer-Encoding: 7bit
532 $this->processRelacements($replace_links);
534 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
536 if (!file_exists(dirname($cachePath))) {
537 mkdir(dirname($cachePath), 0700, true);
539 print_R($this->bodytext);exit;
540 file_put_contents($cachePath, $this->bodytext);
544 function cachedImages()
546 $ui = posix_getpwuid(posix_geteuid());
548 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
550 $ids = $this->attachmentIds();
553 $fh = fopen($imageCache, 'w');
555 $i = DB_DataObject::factory('Images');
556 $i->onid = $this->id;
557 $i->ontable = $this->tableName();
558 $i->whereAddIn('id', $ids, 'int');
563 require_once 'File/MimeType.php';
564 $y = new File_MimeType();
567 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
571 $images["attachment-{$i->id}"] = array(
572 'file' => $i->getStoreName(),
573 'mimetype' => $i->mimetype,
574 'ext' => $y->toExt($i->mimetype),
575 'contentid' => "attachment-$i->id"
579 file_put_contents($imageCache, json_encode($images));
583 function isGenerated($cachePath)
585 if (!file_exists($cachePath) || !filesize($cachePath)) {
590 $ctime = filemtime($cachePath);
592 $mtime[] = $this->updated_dt;
593 $i = DB_DataObject::factory('Images');
594 $i->onid = $this->id;
595 $i->ontable = $this->tableName();
597 $i->selectAdd('max(created) as created');
599 $mtime[] = $i->created;
600 if($ctime >= strtotime(max($mtime))){
607 function messageFrom()
609 if (empty($this->from_name)) {
610 return trim($this->from_email);
612 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
615 function formatDate($dt, $format = 'd/M/Y')
617 return date($format, strtotime($dt));
621 // fixme - this is now in core/udatedatabase..
623 function initMail($mail_template_dir, $name, $master='')
625 $cm = DB_DataObject::factory('core_email');
626 if ($cm->get('name', $name)) {
630 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
634 $opts['file'] = $mail_template_dir. $name .'.html';
635 if (!empty($master)) {
636 $opts['master'] = $mail_template_dir . $master .'.html';
639 require_once 'Pman/Core/Import/Core_email.php';
640 $x = new Pman_Core_Import_Core_email();