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 //cannot go to second check
92 if (!empty($request['_ignore_group_count'])) {
93 if (!$request['_ignore_group_count']) {
94 $roo->jerr('no_member',array('errcode'=> 100));
97 $roo->jerr('no_member',array('errcode'=> 100));
104 function makeCopy($roo)
106 $c = DB_DataObject::Factory($this->tableName());
108 $c->name = "COPY of " . $this->name;
109 $c->updated_dt = $this->sqlValue('NOW()');
112 $c = DB_DataObject::Factory($this->tableName());
118 $i = DB_DataObject::factory('Images');
119 $i->onid = $this->id;
120 $i->ontable = $this->tableName();
124 $new_image = DB_DataObject::factory('Images');
125 $new_image->onid = $c->id;
126 $new_image->ontable = $this->tableName();
127 $new_image->createFrom($i->getStoreName(), $i->filename);
129 $map[$i->id] = $new_image->id;
133 libxml_use_internal_errors (true);
134 $doc = new DOMDocument('1.0', 'UTF-8');
135 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
136 $doc->formatOutput = true;
138 //echo '<PRE>'; print_R($doc);
141 $xpath = new DOMXpath($doc);
142 foreach ($xpath->query('//img[@src]') as $img) {
143 $href = $img->getAttribute('src');
146 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
150 if (!isset($map[$oid])) {
151 //echo "skip no new id for $oid";
155 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
157 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
163 $c->bodytext = $doc->saveHTML();
165 libxml_use_internal_errors (false);
168 $roo->jok("duplicated");
171 function onInsert($q,$roo)
173 $i = DB_DataObject::factory('Images');
175 $i->ontable = $this->tableName();
179 $i->onid = $this->id;
183 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
184 // $this->cachedMailWithOutImages(true, false);
188 function onUpdate($old, $q,$roo)
190 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
194 function attachmentIds()
196 libxml_use_internal_errors (true);
197 $doc = new DOMDocument('1.0', 'UTF-8');
198 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
200 $xpath = new DOMXpath($doc);
203 foreach ($xpath->query('//img[@src]') as $img) { // process images!
204 $href = $img->getAttribute('src');
205 $cid = explode('#', $href);
209 $cid = explode('-', $cid[1]);
210 if (!isset($cid[1])||!is_numeric($cid[1])) {
219 * process replacements is run to generate a template - not the final content..
223 function processRelacements($replace_links = true)
225 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
227 libxml_use_internal_errors (true);
228 $doc = new DOMDocument('1.0', 'UTF-8');
229 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
231 $xpath = new DOMXpath($doc);
233 foreach ($xpath->query('//img[@src]') as $img) { // process images!
234 $href = $img->getAttribute('src');
235 $hash = explode('#', $href);
236 // we name all our cid's as attachment-*
237 // however the src url may be #image-*
240 if(!isset($hash[1])){
243 $cid = explode('-', $hash[1]);
245 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
249 $unsubscribe = $this->unsubscribe_url();
251 foreach ($xpath->query('//a[@href]') as $a) {
253 $href = $a->getAttribute('href');
255 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
256 $a->setAttribute('href', $unsubscribe);
260 if(!preg_match('/^http(.*)/', $href)){
263 if (!$replace_links) {
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)){
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['rcpts_group'])) {
364 $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
365 $admin = $admin_grp->members('email');
367 if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
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 if (isset($contents['mapping'])) {
390 foreach ($contents['mapping'] as $pattern => $replace) {
391 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
394 foreach ($contents as $k => $v) {
396 $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
401 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
402 $contents['rcpts'] = implode(',', $contents['rcpts']);
405 $ui = posix_getpwuid(posix_geteuid());
407 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
409 if($force || !$this->isGenerated($cachePath)){
410 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
413 require_once 'Pman/Core/Mailer.php';
416 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
421 'template'=> $this->tableName() . '-' . $this->id,
422 'templateDir' => $templateDir,
424 'contents' => $contents,
425 'css_embed' => true, // we should always try and do this with emails...
428 if (isset($contents['rcpts'])) {
429 $cfg['rcpts'] = $contents['rcpts'];
432 if (isset($contents['attachments'])) {
433 $cfg['attachments'] = $contents['attachments'];
436 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
437 $cfg = array_merge($contents['mailer_opts'], $cfg);
440 if(isset($contents['css_inline'])){
441 $cfg['css_inline'] = $contents['css_inline'];
444 $r = new Pman_Core_Mailer($cfg);
446 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
448 if(file_exists($imageCache) && filesize($imageCache)){
449 $images = json_decode(file_get_contents($imageCache), true);
450 $r->images = $images;
455 function toMailerData($obj,$force=false)
457 $r = $this->toMailer($obj, $force);
458 if (is_a($r, 'PEAR_Error')) {
466 * DEPRICATED !!! - DO NOT USE THIS !!!
468 * use: toMailerData() -- to return the email data..
470 * $mailer = $core_email->toMailer($obj, false);
471 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
473 * toMailer($obj, false)->send()
478 function send($obj, $force = true, $send = true)
481 return $this->toMailerData($obj,$force);
484 $r = $this->toMailer($obj, $force);
486 if (is_a($r, 'PEAR_Error')) {
493 function cachedMailWithOutImages($force = false, $replace_links = true)
496 $ui = posix_getpwuid(posix_geteuid());
498 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
500 if (!$force && $this->isGenerated($cachePath)) {
504 if (!file_exists(dirname($cachePath))) {
505 mkdir(dirname($cachePath), 0700, true);
508 $random_hash = md5(date('r', time()));
510 $this->cachedImages();
512 $fh = fopen($cachePath, 'w');
514 fwrite($fh, implode("\n", array(
515 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
516 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
517 "Subject: {t.subject:h} ",
518 "X-Message-ID: {t.id} ",
519 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
520 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
524 // note the extra space to finish the last line..
526 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
529 Content-Type: text/plain; charset=utf-8; format=flowed
530 Content-Transfer-Encoding: 7bit
539 $this->processRelacements($replace_links);
541 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
543 if (!file_exists(dirname($cachePath))) {
544 mkdir(dirname($cachePath), 0700, true);
547 if (empty($this->use_file)) {
548 file_put_contents($cachePath, $this->bodytext);
551 // use-file -- uses the original template...
552 $mailtext = file_get_contents($this->use_file);
554 require_once 'Mail/mimeDecode.php';
555 require_once 'Mail/RFC822.php';
557 $decoder = new Mail_mimeDecode($mailtext);
558 $parts = $decoder->getSendArray();
559 file_put_contents($cachePath,$parts[2]);
563 function cachedImages()
565 $ui = posix_getpwuid(posix_geteuid());
567 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
569 $ids = $this->attachmentIds();
572 $fh = fopen($imageCache, 'w');
574 $i = DB_DataObject::factory('Images');
575 $i->onid = $this->id;
576 $i->ontable = $this->tableName();
577 $i->whereAddIn('id', $ids, 'int');
582 require_once 'File/MimeType.php';
583 $y = new File_MimeType();
586 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
590 $images["attachment-{$i->id}"] = array(
591 'file' => $i->getStoreName(),
592 'mimetype' => $i->mimetype,
593 'ext' => $y->toExt($i->mimetype),
594 'contentid' => "attachment-$i->id"
598 file_put_contents($imageCache, json_encode($images));
602 function isGenerated($cachePath)
604 if (!file_exists($cachePath) || !filesize($cachePath)) {
608 if (!empty($this->use_file)) {
609 $ctime = filemtime($cachePath);
610 $mtime = filemtime($this->use_file);
611 if($ctime >= $mtime){
620 $ctime = filemtime($cachePath);
622 $mtime[] = $this->updated_dt;
623 $i = DB_DataObject::factory('Images');
624 $i->onid = $this->id;
625 $i->ontable = $this->tableName();
627 $i->selectAdd('max(created) as created');
629 $mtime[] = $i->created;
630 if($ctime >= strtotime(max($mtime))){
637 function messageFrom()
639 if (empty($this->from_name)) {
640 return trim($this->from_email);
642 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
645 function formatDate($dt, $format = 'd/M/Y')
647 return date($format, strtotime($dt));
651 // fixme - this is now in core/udatedatabase..
653 function initMail($mail_template_dir, $name, $master='')
655 $cm = DB_DataObject::factory('core_email');
656 if ($cm->get('name', $name)) {
660 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
664 $opts['file'] = $mail_template_dir. $name .'.html';
665 if (!empty($master)) {
666 $opts['master'] = $mail_template_dir . $master .'.html';
669 require_once 'Pman/Core/Import/Core_email.php';
670 $x = new Pman_Core_Import_Core_email();