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) {
79 $c = DB_DataObject::factory('core_group_member');
80 $c->whereAdd("group_id = {$this->to_group}");
82 if (!$c->find(true)) {
83 if (empty($request['_ignore_group_count'])) {
84 $roo->jerr('no_member');
87 if (!$request['_ignore_group_count']) {
88 $roo->jerr('no_member');
94 function makeCopy($roo)
96 $c = DB_DataObject::Factory($this->tableName());
98 $c->name = "COPY of " . $this->name;
99 $c->updated_dt = $this->sqlValue('NOW()');
102 $c = DB_DataObject::Factory($this->tableName());
108 $i = DB_DataObject::factory('Images');
109 $i->onid = $this->id;
110 $i->ontable = $this->tableName();
114 $new_image = DB_DataObject::factory('Images');
115 $new_image->onid = $c->id;
116 $new_image->ontable = $this->tableName();
117 $new_image->createFrom($i->getStoreName(), $i->filename);
119 $map[$i->id] = $new_image->id;
123 libxml_use_internal_errors (true);
124 $doc = new DOMDocument('1.0', 'UTF-8');
125 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
126 $doc->formatOutput = true;
128 //echo '<PRE>'; print_R($doc);
131 $xpath = new DOMXpath($doc);
132 foreach ($xpath->query('//img[@src]') as $img) {
133 $href = $img->getAttribute('src');
136 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
140 if (!isset($map[$oid])) {
141 //echo "skip no new id for $oid";
145 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
147 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
153 $c->bodytext = $doc->saveHTML();
155 libxml_use_internal_errors (false);
158 $roo->jok("duplicated");
161 function onInsert($q,$roo)
163 $i = DB_DataObject::factory('Images');
165 $i->ontable = $this->tableName();
169 $i->onid = $this->id;
173 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
174 // $this->cachedMailWithOutImages(true, false);
178 function onUpdate($old, $q,$roo)
180 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
184 function attachmentIds()
186 libxml_use_internal_errors (true);
187 $doc = new DOMDocument('1.0', 'UTF-8');
188 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
190 $xpath = new DOMXpath($doc);
193 foreach ($xpath->query('//img[@src]') as $img) { // process images!
194 $href = $img->getAttribute('src');
195 $cid = explode('#', $href);
199 $cid = explode('-', $cid[1]);
200 if (!isset($cid[1])||!is_numeric($cid[1])) {
209 * process replacements is run to generate a template - not the final content..
213 function processRelacements($replace_links = true)
215 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
217 libxml_use_internal_errors (true);
218 $doc = new DOMDocument('1.0', 'UTF-8');
219 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
221 $xpath = new DOMXpath($doc);
223 foreach ($xpath->query('//img[@src]') as $img) { // process images!
224 $href = $img->getAttribute('src');
225 $hash = explode('#', $href);
226 // we name all our cid's as attachment-*
227 // however the src url may be #image-*
230 if(!isset($hash[1])){
233 $cid = explode('-', $hash[1]);
235 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
239 $unsubscribe = $this->unsubscribe_url();
241 foreach ($xpath->query('//a[@href]') as $a) {
243 $href = $a->getAttribute('href');
245 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
246 $a->setAttribute('href', $unsubscribe);
250 if(!preg_match('/^http(.*)/', $href)){
253 if (!$replace_links) {
256 $link = DB_DataObject::factory('crm_mailing_list_link');
257 $link->setFrom(array(
261 if(!$link->find(true)){
269 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
271 $a->setAttribute('href', $l);
275 if(!empty($unsubscribe)){
276 $element = $doc->createElement('img');
277 $element->setAttribute('mailembed', 'no');
278 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
279 $element->setAttribute('width', '1');
280 $element->setAttribute('height', '1');
282 $html = $doc->getElementsByTagName('html');
284 $html->item(0)->appendChild($element);
287 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
291 $this->bodytext = $doc->saveHTML();
293 libxml_use_internal_errors (false);
295 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
296 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
301 function unsubscribe_url()
303 $unsubscribe = false;
305 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
308 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
315 * convert email with contents into a core mailer object. - ready to send..
316 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
318 * + rcpts || person << if person is set - then it goes to them...
319 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
323 * + person << who it actually goes to..
325 * @param bool $force - force re-creation of cached version of email.
327 * @returns Pman_Core_Mailer||PEAR_Error
330 function toMailer($obj,$force=false)
332 require_once 'PEAR.php';
335 $contents = (array)$obj;
337 if(empty($this->id) && !empty($contents['template'])){
338 $this->get('name', $contents['template']);
342 if(empty($this->active)){
343 return $p->raiseError("template [{$contents['template']}] is Disabled");
347 if(empty($this->id)){
348 return $p->raiseError("template [{$contents['template']}] has not been set");
353 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
354 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
357 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
360 $contents['bcc'] = $admin ;
362 if (!empty($contents['rcpts_group'])) {
364 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
367 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
369 $contents['rcpts'] = $admin;
372 //subject replacement
373 if(empty($contents['subject'])){
374 $contents['subject'] = $this->subject;
377 if (!empty($contents['subject_replace'])) {
378 foreach ($contents['mapping'] as $pattern => $replace) {
379 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
383 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
384 $contents['rcpts'] = implode(',', $contents['rcpts']);
387 $ui = posix_getpwuid(posix_geteuid());
389 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
391 if($force || !$this->isGenerated($cachePath)){
392 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
395 require_once 'Pman/Core/Mailer.php';
398 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
403 'template'=> $this->tableName() . '-' . $this->id,
404 'templateDir' => $templateDir,
406 'contents' => $contents,
407 'css_embed' => true, // we should always try and do this with emails...
410 if (isset($contents['rcpts'])) {
411 $cfg['rcpts'] = $contents['rcpts'];
414 if (isset($contents['attachments'])) {
415 $cfg['attachments'] = $contents['attachments'];
418 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
419 $cfg = array_merge($contents['mailer_opts'], $cfg);
422 $r = new Pman_Core_Mailer($cfg);
424 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
426 if(file_exists($imageCache) && filesize($imageCache)){
427 $images = json_decode(file_get_contents($imageCache), true);
428 $r->images = $images;
433 function toMailerData($obj,$force=false)
435 $r = $this->toMailer($obj, $force);
436 if (is_a($r, 'PEAR_Error')) {
444 * DEPRICATED !!! - DO NOT USE THIS !!!
446 * use: toMailerData() -- to return the email data..
448 * $mailer = $core_email->toMailer($obj, false);
449 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
451 * toMailer($obj, false)->send()
456 function send($obj, $force = true, $send = true)
459 return $this->toMailerData($obj,$force);
462 $r = $this->toMailer($obj, $force);
464 if (is_a($r, 'PEAR_Error')) {
471 function cachedMailWithOutImages($force = false, $replace_links = true)
474 $ui = posix_getpwuid(posix_geteuid());
476 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
478 if (!$force && $this->isGenerated($cachePath)) {
482 if (!file_exists(dirname($cachePath))) {
483 mkdir(dirname($cachePath), 0700, true);
486 $random_hash = md5(date('r', time()));
488 $this->cachedImages();
490 $fh = fopen($cachePath, 'w');
492 fwrite($fh, implode("\n", array(
493 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
494 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
495 "Subject: {t.subject:h} ",
496 "X-Message-ID: {t.id} ",
497 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
498 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
502 // note the extra space to finish the last line..
504 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
507 Content-Type: text/plain; charset=utf-8; format=flowed
508 Content-Transfer-Encoding: 7bit
517 $this->processRelacements($replace_links);
519 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
521 if (!file_exists(dirname($cachePath))) {
522 mkdir(dirname($cachePath), 0700, true);
525 file_put_contents($cachePath, $this->bodytext);
529 function cachedImages()
531 $ui = posix_getpwuid(posix_geteuid());
533 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
535 $ids = $this->attachmentIds();
538 $fh = fopen($imageCache, 'w');
540 $i = DB_DataObject::factory('Images');
541 $i->onid = $this->id;
542 $i->ontable = $this->tableName();
543 $i->whereAddIn('id', $ids, 'int');
548 require_once 'File/MimeType.php';
549 $y = new File_MimeType();
552 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
556 $images["attachment-{$i->id}"] = array(
557 'file' => $i->getStoreName(),
558 'mimetype' => $i->mimetype,
559 'ext' => $y->toExt($i->mimetype),
560 'contentid' => "attachment-$i->id"
564 file_put_contents($imageCache, json_encode($images));
568 function isGenerated($cachePath)
570 if (!file_exists($cachePath) || !filesize($cachePath)) {
575 $ctime = filemtime($cachePath);
577 $mtime[] = $this->updated_dt;
578 $i = DB_DataObject::factory('Images');
579 $i->onid = $this->id;
580 $i->ontable = $this->tableName();
582 $i->selectAdd('max(created) as created');
584 $mtime[] = $i->created;
585 if($ctime >= strtotime(max($mtime))){
592 function messageFrom()
594 if (empty($this->from_name)) {
595 return trim($this->from_email);
597 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
600 function formatDate($dt, $format = 'd/M/Y')
602 return date($format, strtotime($dt));
606 // fixme - this is now in core/udatedatabase..
608 function initMail($mail_template_dir, $name, $master='')
610 $cm = DB_DataObject::factory('core_email');
611 if ($cm->get('name', $name)) {
615 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
619 $opts['file'] = $mail_template_dir. $name .'.html';
620 if (!empty($master)) {
621 $opts['master'] = $mail_template_dir . $master .'.html';
624 require_once 'Pman/Core/Import/Core_email.php';
625 $x = new Pman_Core_Import_Core_email();