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
83 if (!$c->find(true)) {
87 print_r($this->to_group);
89 print_r($c->count());exit;
93 function makeCopy($roo)
95 $c = DB_DataObject::Factory($this->tableName());
97 $c->name = "COPY of " . $this->name;
98 $c->updated_dt = $this->sqlValue('NOW()');
101 $c = DB_DataObject::Factory($this->tableName());
107 $i = DB_DataObject::factory('Images');
108 $i->onid = $this->id;
109 $i->ontable = $this->tableName();
113 $new_image = DB_DataObject::factory('Images');
114 $new_image->onid = $c->id;
115 $new_image->ontable = $this->tableName();
116 $new_image->createFrom($i->getStoreName(), $i->filename);
118 $map[$i->id] = $new_image->id;
122 libxml_use_internal_errors (true);
123 $doc = new DOMDocument('1.0', 'UTF-8');
124 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
125 $doc->formatOutput = true;
127 //echo '<PRE>'; print_R($doc);
130 $xpath = new DOMXpath($doc);
131 foreach ($xpath->query('//img[@src]') as $img) {
132 $href = $img->getAttribute('src');
135 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
139 if (!isset($map[$oid])) {
140 //echo "skip no new id for $oid";
144 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
146 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
152 $c->bodytext = $doc->saveHTML();
154 libxml_use_internal_errors (false);
157 $roo->jok("duplicated");
160 function onInsert($q,$roo)
162 $i = DB_DataObject::factory('Images');
164 $i->ontable = $this->tableName();
168 $i->onid = $this->id;
172 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
173 // $this->cachedMailWithOutImages(true, false);
177 function onUpdate($old, $q,$roo)
179 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
183 function attachmentIds()
185 libxml_use_internal_errors (true);
186 $doc = new DOMDocument('1.0', 'UTF-8');
187 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
189 $xpath = new DOMXpath($doc);
192 foreach ($xpath->query('//img[@src]') as $img) { // process images!
193 $href = $img->getAttribute('src');
194 $cid = explode('#', $href);
198 $cid = explode('-', $cid[1]);
199 if (!isset($cid[1])||!is_numeric($cid[1])) {
208 * process replacements is run to generate a template - not the final content..
212 function processRelacements($replace_links = true)
214 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
216 libxml_use_internal_errors (true);
217 $doc = new DOMDocument('1.0', 'UTF-8');
218 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
220 $xpath = new DOMXpath($doc);
222 foreach ($xpath->query('//img[@src]') as $img) { // process images!
223 $href = $img->getAttribute('src');
224 $hash = explode('#', $href);
225 // we name all our cid's as attachment-*
226 // however the src url may be #image-*
229 if(!isset($hash[1])){
232 $cid = explode('-', $hash[1]);
234 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
238 $unsubscribe = $this->unsubscribe_url();
240 foreach ($xpath->query('//a[@href]') as $a) {
242 $href = $a->getAttribute('href');
244 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
245 $a->setAttribute('href', $unsubscribe);
249 if(!preg_match('/^http(.*)/', $href)){
252 if (!$replace_links) {
255 $link = DB_DataObject::factory('crm_mailing_list_link');
256 $link->setFrom(array(
260 if(!$link->find(true)){
268 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
270 $a->setAttribute('href', $l);
274 if(!empty($unsubscribe)){
275 $element = $doc->createElement('img');
276 $element->setAttribute('mailembed', 'no');
277 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
278 $element->setAttribute('width', '1');
279 $element->setAttribute('height', '1');
281 $html = $doc->getElementsByTagName('html');
283 $html->item(0)->appendChild($element);
286 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
290 $this->bodytext = $doc->saveHTML();
292 libxml_use_internal_errors (false);
294 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
295 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
300 function unsubscribe_url()
302 $unsubscribe = false;
304 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
307 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
314 * convert email with contents into a core mailer object. - ready to send..
315 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
317 * + rcpts || person << if person is set - then it goes to them...
318 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
322 * + person << who it actually goes to..
324 * @param bool $force - force re-creation of cached version of email.
326 * @returns Pman_Core_Mailer||PEAR_Error
329 function toMailer($obj,$force=false)
331 require_once 'PEAR.php';
334 $contents = (array)$obj;
336 if(empty($this->id) && !empty($contents['template'])){
337 $this->get('name', $contents['template']);
341 if(empty($this->active)){
342 return $p->raiseError("template [{$contents['template']}] is Disabled");
346 if(empty($this->id)){
347 return $p->raiseError("template [{$contents['template']}] has not been set");
352 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
353 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
356 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
359 $contents['bcc'] = $admin ;
361 if (!empty($contents['rcpts_group'])) {
363 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
366 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
368 $contents['rcpts'] = $admin;
371 //subject replacement
372 if(empty($contents['subject'])){
373 $contents['subject'] = $this->subject;
376 if (!empty($contents['subject_replace'])) {
377 foreach ($contents['mapping'] as $pattern => $replace) {
378 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
382 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
383 $contents['rcpts'] = implode(',', $contents['rcpts']);
386 $ui = posix_getpwuid(posix_geteuid());
388 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
390 if($force || !$this->isGenerated($cachePath)){
391 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
394 require_once 'Pman/Core/Mailer.php';
397 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
402 'template'=> $this->tableName() . '-' . $this->id,
403 'templateDir' => $templateDir,
405 'contents' => $contents,
406 'css_embed' => true, // we should always try and do this with emails...
409 if (isset($contents['rcpts'])) {
410 $cfg['rcpts'] = $contents['rcpts'];
413 if (isset($contents['attachments'])) {
414 $cfg['attachments'] = $contents['attachments'];
417 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
418 $cfg = array_merge($contents['mailer_opts'], $cfg);
421 $r = new Pman_Core_Mailer($cfg);
423 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
425 if(file_exists($imageCache) && filesize($imageCache)){
426 $images = json_decode(file_get_contents($imageCache), true);
427 $r->images = $images;
432 function toMailerData($obj,$force=false)
434 $r = $this->toMailer($obj, $force);
435 if (is_a($r, 'PEAR_Error')) {
443 * DEPRICATED !!! - DO NOT USE THIS !!!
445 * use: toMailerData() -- to return the email data..
447 * $mailer = $core_email->toMailer($obj, false);
448 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
450 * toMailer($obj, false)->send()
455 function send($obj, $force = true, $send = true)
458 return $this->toMailerData($obj,$force);
461 $r = $this->toMailer($obj, $force);
463 if (is_a($r, 'PEAR_Error')) {
470 function cachedMailWithOutImages($force = false, $replace_links = true)
473 $ui = posix_getpwuid(posix_geteuid());
475 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
477 if (!$force && $this->isGenerated($cachePath)) {
481 if (!file_exists(dirname($cachePath))) {
482 mkdir(dirname($cachePath), 0700, true);
485 $random_hash = md5(date('r', time()));
487 $this->cachedImages();
489 $fh = fopen($cachePath, 'w');
491 fwrite($fh, implode("\n", array(
492 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
493 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
494 "Subject: {t.subject:h} ",
495 "X-Message-ID: {t.id} ",
496 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
497 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
501 // note the extra space to finish the last line..
503 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
506 Content-Type: text/plain; charset=utf-8; format=flowed
507 Content-Transfer-Encoding: 7bit
516 $this->processRelacements($replace_links);
518 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
520 if (!file_exists(dirname($cachePath))) {
521 mkdir(dirname($cachePath), 0700, true);
524 file_put_contents($cachePath, $this->bodytext);
528 function cachedImages()
530 $ui = posix_getpwuid(posix_geteuid());
532 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
534 $ids = $this->attachmentIds();
537 $fh = fopen($imageCache, 'w');
539 $i = DB_DataObject::factory('Images');
540 $i->onid = $this->id;
541 $i->ontable = $this->tableName();
542 $i->whereAddIn('id', $ids, 'int');
547 require_once 'File/MimeType.php';
548 $y = new File_MimeType();
551 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
555 $images["attachment-{$i->id}"] = array(
556 'file' => $i->getStoreName(),
557 'mimetype' => $i->mimetype,
558 'ext' => $y->toExt($i->mimetype),
559 'contentid' => "attachment-$i->id"
563 file_put_contents($imageCache, json_encode($images));
567 function isGenerated($cachePath)
569 if (!file_exists($cachePath) || !filesize($cachePath)) {
574 $ctime = filemtime($cachePath);
576 $mtime[] = $this->updated_dt;
577 $i = DB_DataObject::factory('Images');
578 $i->onid = $this->id;
579 $i->ontable = $this->tableName();
581 $i->selectAdd('max(created) as created');
583 $mtime[] = $i->created;
584 if($ctime >= strtotime(max($mtime))){
591 function messageFrom()
593 if (empty($this->from_name)) {
594 return trim($this->from_email);
596 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
599 function formatDate($dt, $format = 'd/M/Y')
601 return date($format, strtotime($dt));
605 // fixme - this is now in core/udatedatabase..
607 function initMail($mail_template_dir, $name, $master='')
609 $cm = DB_DataObject::factory('core_email');
610 if ($cm->get('name', $name)) {
614 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
618 $opts['file'] = $mail_template_dir. $name .'.html';
619 if (!empty($master)) {
620 $opts['master'] = $mail_template_dir . $master .'.html';
623 require_once 'Pman/Core/Import/Core_email.php';
624 $x = new Pman_Core_Import_Core_email();