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
54 AS group_member_count,
62 bcc_group = core_group_member.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 != -1) {
89 $c = DB_DataObject::factory('core_group_member');
90 $c->whereAdd("group_id = {$this->to_group}");
92 if (!$c->count() && !$request['_ignore_group_count']) {
93 $roo->jerr('no_member',array('errcode'=> 100));
98 function makeCopy($roo)
100 $c = DB_DataObject::Factory($this->tableName());
102 $c->name = "COPY of " . $this->name;
103 $c->updated_dt = $this->sqlValue('NOW()');
106 $c = DB_DataObject::Factory($this->tableName());
112 $i = DB_DataObject::factory('Images');
113 $i->onid = $this->id;
114 $i->ontable = $this->tableName();
118 $new_image = DB_DataObject::factory('Images');
119 $new_image->onid = $c->id;
120 $new_image->ontable = $this->tableName();
121 $new_image->createFrom($i->getStoreName(), $i->filename);
123 $map[$i->id] = $new_image->id;
127 libxml_use_internal_errors (true);
128 $doc = new DOMDocument('1.0', 'UTF-8');
129 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
130 $doc->formatOutput = true;
132 //echo '<PRE>'; print_R($doc);
135 $xpath = new DOMXpath($doc);
136 foreach ($xpath->query('//img[@src]') as $img) {
137 $href = $img->getAttribute('src');
140 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
144 if (!isset($map[$oid])) {
145 //echo "skip no new id for $oid";
149 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
151 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
157 $c->bodytext = $doc->saveHTML();
159 libxml_use_internal_errors (false);
162 $roo->jok("duplicated");
165 function onInsert($q,$roo)
167 $i = DB_DataObject::factory('Images');
169 $i->ontable = $this->tableName();
173 $i->onid = $this->id;
177 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
178 // $this->cachedMailWithOutImages(true, false);
182 function onUpdate($old, $q,$roo)
184 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
188 function attachmentIds()
190 libxml_use_internal_errors (true);
191 $doc = new DOMDocument('1.0', 'UTF-8');
192 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
194 $xpath = new DOMXpath($doc);
197 foreach ($xpath->query('//img[@src]') as $img) { // process images!
198 $href = $img->getAttribute('src');
199 $cid = explode('#', $href);
203 $cid = explode('-', $cid[1]);
204 if (!isset($cid[1])||!is_numeric($cid[1])) {
213 * process replacements is run to generate a template - not the final content..
217 function processRelacements($replace_links = true)
219 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
221 libxml_use_internal_errors (true);
222 $doc = new DOMDocument('1.0', 'UTF-8');
223 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
225 $xpath = new DOMXpath($doc);
227 foreach ($xpath->query('//img[@src]') as $img) { // process images!
228 $href = $img->getAttribute('src');
229 $hash = explode('#', $href);
230 // we name all our cid's as attachment-*
231 // however the src url may be #image-*
234 if(!isset($hash[1])){
237 $cid = explode('-', $hash[1]);
239 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
243 $unsubscribe = $this->unsubscribe_url();
245 foreach ($xpath->query('//a[@href]') as $a) {
247 $href = $a->getAttribute('href');
249 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
250 $a->setAttribute('href', $unsubscribe);
254 if(!preg_match('/^http(.*)/', $href)){
257 if (!$replace_links) {
260 $link = DB_DataObject::factory('crm_mailing_list_link');
261 $link->setFrom(array(
265 if(!$link->find(true)){
273 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
275 $a->setAttribute('href', $l);
279 if(!empty($unsubscribe)){
280 $element = $doc->createElement('img');
281 $element->setAttribute('mailembed', 'no');
282 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
283 $element->setAttribute('width', '1');
284 $element->setAttribute('height', '1');
286 $html = $doc->getElementsByTagName('html');
288 $html->item(0)->appendChild($element);
291 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
295 $this->bodytext = $doc->saveHTML();
297 libxml_use_internal_errors (false);
299 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
300 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
305 function unsubscribe_url()
307 $unsubscribe = false;
309 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
312 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
319 * convert email with contents into a core mailer object. - ready to send..
320 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
322 * + rcpts || person << if person is set - then it goes to them...
323 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
327 * + person << who it actually goes to..
329 * @param bool $force - force re-creation of cached version of email.
331 * @returns Pman_Core_Mailer||PEAR_Error
334 function toMailer($obj,$force=false)
336 require_once 'PEAR.php';
339 $contents = (array)$obj;
341 if(empty($this->id) && !empty($contents['template'])){
342 $this->get('name', $contents['template']);
346 if(empty($this->active)){
347 return $p->raiseError("template [{$contents['template']}] is Disabled");
351 if(empty($this->id)){
352 return $p->raiseError("template [{$contents['template']}] has not been set");
357 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
358 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
361 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
364 $contents['bcc'] = $admin ;
366 if (!empty($contents['rcpts_group'])) {
368 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
371 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
373 $contents['rcpts'] = $admin;
376 //subject replacement
377 if(empty($contents['subject'])){
378 $contents['subject'] = $this->subject;
381 if (!empty($contents['subject_replace'])) {
382 foreach ($contents['mapping'] as $pattern => $replace) {
383 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
387 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
388 $contents['rcpts'] = implode(',', $contents['rcpts']);
391 $ui = posix_getpwuid(posix_geteuid());
393 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
395 if($force || !$this->isGenerated($cachePath)){
396 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
399 require_once 'Pman/Core/Mailer.php';
402 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
407 'template'=> $this->tableName() . '-' . $this->id,
408 'templateDir' => $templateDir,
410 'contents' => $contents,
411 'css_embed' => true, // we should always try and do this with emails...
414 if (isset($contents['rcpts'])) {
415 $cfg['rcpts'] = $contents['rcpts'];
418 if (isset($contents['attachments'])) {
419 $cfg['attachments'] = $contents['attachments'];
422 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
423 $cfg = array_merge($contents['mailer_opts'], $cfg);
426 $r = new Pman_Core_Mailer($cfg);
428 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
430 if(file_exists($imageCache) && filesize($imageCache)){
431 $images = json_decode(file_get_contents($imageCache), true);
432 $r->images = $images;
437 function toMailerData($obj,$force=false)
439 $r = $this->toMailer($obj, $force);
440 if (is_a($r, 'PEAR_Error')) {
448 * DEPRICATED !!! - DO NOT USE THIS !!!
450 * use: toMailerData() -- to return the email data..
452 * $mailer = $core_email->toMailer($obj, false);
453 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
455 * toMailer($obj, false)->send()
460 function send($obj, $force = true, $send = true)
463 return $this->toMailerData($obj,$force);
466 $r = $this->toMailer($obj, $force);
468 if (is_a($r, 'PEAR_Error')) {
475 function cachedMailWithOutImages($force = false, $replace_links = true)
478 $ui = posix_getpwuid(posix_geteuid());
480 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
482 if (!$force && $this->isGenerated($cachePath)) {
486 if (!file_exists(dirname($cachePath))) {
487 mkdir(dirname($cachePath), 0700, true);
490 $random_hash = md5(date('r', time()));
492 $this->cachedImages();
494 $fh = fopen($cachePath, 'w');
496 fwrite($fh, implode("\n", array(
497 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
498 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
499 "Subject: {t.subject:h} ",
500 "X-Message-ID: {t.id} ",
501 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
502 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
506 // note the extra space to finish the last line..
508 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
511 Content-Type: text/plain; charset=utf-8; format=flowed
512 Content-Transfer-Encoding: 7bit
521 $this->processRelacements($replace_links);
523 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
525 if (!file_exists(dirname($cachePath))) {
526 mkdir(dirname($cachePath), 0700, true);
529 file_put_contents($cachePath, $this->bodytext);
533 function cachedImages()
535 $ui = posix_getpwuid(posix_geteuid());
537 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
539 $ids = $this->attachmentIds();
542 $fh = fopen($imageCache, 'w');
544 $i = DB_DataObject::factory('Images');
545 $i->onid = $this->id;
546 $i->ontable = $this->tableName();
547 $i->whereAddIn('id', $ids, 'int');
552 require_once 'File/MimeType.php';
553 $y = new File_MimeType();
556 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
560 $images["attachment-{$i->id}"] = array(
561 'file' => $i->getStoreName(),
562 'mimetype' => $i->mimetype,
563 'ext' => $y->toExt($i->mimetype),
564 'contentid' => "attachment-$i->id"
568 file_put_contents($imageCache, json_encode($images));
572 function isGenerated($cachePath)
574 if (!file_exists($cachePath) || !filesize($cachePath)) {
579 $ctime = filemtime($cachePath);
581 $mtime[] = $this->updated_dt;
582 $i = DB_DataObject::factory('Images');
583 $i->onid = $this->id;
584 $i->ontable = $this->tableName();
586 $i->selectAdd('max(created) as created');
588 $mtime[] = $i->created;
589 if($ctime >= strtotime(max($mtime))){
596 function messageFrom()
598 if (empty($this->from_name)) {
599 return trim($this->from_email);
601 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
604 function formatDate($dt, $format = 'd/M/Y')
606 return date($format, strtotime($dt));
610 // fixme - this is now in core/udatedatabase..
612 function initMail($mail_template_dir, $name, $master='')
614 $cm = DB_DataObject::factory('core_email');
615 if ($cm->get('name', $name)) {
619 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
623 $opts['file'] = $mail_template_dir. $name .'.html';
624 if (!empty($master)) {
625 $opts['master'] = $mail_template_dir . $master .'.html';
628 require_once 'Pman/Core/Import/Core_email.php';
629 $x = new Pman_Core_Import_Core_email();