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');
79 $c->groud_id = $this->to_group;
82 // 'groud_id' => $this->to_group
85 if (!$c->find(true)) {
89 print_r($this->to_group);
91 print_r($c->count());exit;
95 function makeCopy($roo)
97 $c = DB_DataObject::Factory($this->tableName());
99 $c->name = "COPY of " . $this->name;
100 $c->updated_dt = $this->sqlValue('NOW()');
103 $c = DB_DataObject::Factory($this->tableName());
109 $i = DB_DataObject::factory('Images');
110 $i->onid = $this->id;
111 $i->ontable = $this->tableName();
115 $new_image = DB_DataObject::factory('Images');
116 $new_image->onid = $c->id;
117 $new_image->ontable = $this->tableName();
118 $new_image->createFrom($i->getStoreName(), $i->filename);
120 $map[$i->id] = $new_image->id;
124 libxml_use_internal_errors (true);
125 $doc = new DOMDocument('1.0', 'UTF-8');
126 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
127 $doc->formatOutput = true;
129 //echo '<PRE>'; print_R($doc);
132 $xpath = new DOMXpath($doc);
133 foreach ($xpath->query('//img[@src]') as $img) {
134 $href = $img->getAttribute('src');
137 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
141 if (!isset($map[$oid])) {
142 //echo "skip no new id for $oid";
146 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
148 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
154 $c->bodytext = $doc->saveHTML();
156 libxml_use_internal_errors (false);
159 $roo->jok("duplicated");
162 function onInsert($q,$roo)
164 $i = DB_DataObject::factory('Images');
166 $i->ontable = $this->tableName();
170 $i->onid = $this->id;
174 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
175 // $this->cachedMailWithOutImages(true, false);
179 function onUpdate($old, $q,$roo)
181 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
185 function attachmentIds()
187 libxml_use_internal_errors (true);
188 $doc = new DOMDocument('1.0', 'UTF-8');
189 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
191 $xpath = new DOMXpath($doc);
194 foreach ($xpath->query('//img[@src]') as $img) { // process images!
195 $href = $img->getAttribute('src');
196 $cid = explode('#', $href);
200 $cid = explode('-', $cid[1]);
201 if (!isset($cid[1])||!is_numeric($cid[1])) {
210 * process replacements is run to generate a template - not the final content..
214 function processRelacements($replace_links = true)
216 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
218 libxml_use_internal_errors (true);
219 $doc = new DOMDocument('1.0', 'UTF-8');
220 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
222 $xpath = new DOMXpath($doc);
224 foreach ($xpath->query('//img[@src]') as $img) { // process images!
225 $href = $img->getAttribute('src');
226 $hash = explode('#', $href);
227 // we name all our cid's as attachment-*
228 // however the src url may be #image-*
231 if(!isset($hash[1])){
234 $cid = explode('-', $hash[1]);
236 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
240 $unsubscribe = $this->unsubscribe_url();
242 foreach ($xpath->query('//a[@href]') as $a) {
244 $href = $a->getAttribute('href');
246 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
247 $a->setAttribute('href', $unsubscribe);
251 if(!preg_match('/^http(.*)/', $href)){
254 if (!$replace_links) {
257 $link = DB_DataObject::factory('crm_mailing_list_link');
258 $link->setFrom(array(
262 if(!$link->find(true)){
270 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
272 $a->setAttribute('href', $l);
276 if(!empty($unsubscribe)){
277 $element = $doc->createElement('img');
278 $element->setAttribute('mailembed', 'no');
279 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
280 $element->setAttribute('width', '1');
281 $element->setAttribute('height', '1');
283 $html = $doc->getElementsByTagName('html');
285 $html->item(0)->appendChild($element);
288 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
292 $this->bodytext = $doc->saveHTML();
294 libxml_use_internal_errors (false);
296 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
297 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
302 function unsubscribe_url()
304 $unsubscribe = false;
306 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
309 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
316 * convert email with contents into a core mailer object. - ready to send..
317 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
319 * + rcpts || person << if person is set - then it goes to them...
320 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
324 * + person << who it actually goes to..
326 * @param bool $force - force re-creation of cached version of email.
328 * @returns Pman_Core_Mailer||PEAR_Error
331 function toMailer($obj,$force=false)
333 require_once 'PEAR.php';
336 $contents = (array)$obj;
338 if(empty($this->id) && !empty($contents['template'])){
339 $this->get('name', $contents['template']);
343 if(empty($this->active)){
344 return $p->raiseError("template [{$contents['template']}] is Disabled");
348 if(empty($this->id)){
349 return $p->raiseError("template [{$contents['template']}] has not been set");
354 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
355 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
358 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
361 $contents['bcc'] = $admin ;
363 if (!empty($contents['rcpts_group'])) {
365 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
368 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
370 $contents['rcpts'] = $admin;
373 //subject replacement
374 if(empty($contents['subject'])){
375 $contents['subject'] = $this->subject;
378 if (!empty($contents['subject_replace'])) {
379 foreach ($contents['mapping'] as $pattern => $replace) {
380 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
384 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
385 $contents['rcpts'] = implode(',', $contents['rcpts']);
388 $ui = posix_getpwuid(posix_geteuid());
390 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
392 if($force || !$this->isGenerated($cachePath)){
393 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
396 require_once 'Pman/Core/Mailer.php';
399 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
404 'template'=> $this->tableName() . '-' . $this->id,
405 'templateDir' => $templateDir,
407 'contents' => $contents,
408 'css_embed' => true, // we should always try and do this with emails...
411 if (isset($contents['rcpts'])) {
412 $cfg['rcpts'] = $contents['rcpts'];
415 if (isset($contents['attachments'])) {
416 $cfg['attachments'] = $contents['attachments'];
419 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
420 $cfg = array_merge($contents['mailer_opts'], $cfg);
423 $r = new Pman_Core_Mailer($cfg);
425 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
427 if(file_exists($imageCache) && filesize($imageCache)){
428 $images = json_decode(file_get_contents($imageCache), true);
429 $r->images = $images;
434 function toMailerData($obj,$force=false)
436 $r = $this->toMailer($obj, $force);
437 if (is_a($r, 'PEAR_Error')) {
445 * DEPRICATED !!! - DO NOT USE THIS !!!
447 * use: toMailerData() -- to return the email data..
449 * $mailer = $core_email->toMailer($obj, false);
450 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
452 * toMailer($obj, false)->send()
457 function send($obj, $force = true, $send = true)
460 return $this->toMailerData($obj,$force);
463 $r = $this->toMailer($obj, $force);
465 if (is_a($r, 'PEAR_Error')) {
472 function cachedMailWithOutImages($force = false, $replace_links = true)
475 $ui = posix_getpwuid(posix_geteuid());
477 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
479 if (!$force && $this->isGenerated($cachePath)) {
483 if (!file_exists(dirname($cachePath))) {
484 mkdir(dirname($cachePath), 0700, true);
487 $random_hash = md5(date('r', time()));
489 $this->cachedImages();
491 $fh = fopen($cachePath, 'w');
493 fwrite($fh, implode("\n", array(
494 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
495 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
496 "Subject: {t.subject:h} ",
497 "X-Message-ID: {t.id} ",
498 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
499 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
503 // note the extra space to finish the last line..
505 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
508 Content-Type: text/plain; charset=utf-8; format=flowed
509 Content-Transfer-Encoding: 7bit
518 $this->processRelacements($replace_links);
520 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
522 if (!file_exists(dirname($cachePath))) {
523 mkdir(dirname($cachePath), 0700, true);
526 file_put_contents($cachePath, $this->bodytext);
530 function cachedImages()
532 $ui = posix_getpwuid(posix_geteuid());
534 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
536 $ids = $this->attachmentIds();
539 $fh = fopen($imageCache, 'w');
541 $i = DB_DataObject::factory('Images');
542 $i->onid = $this->id;
543 $i->ontable = $this->tableName();
544 $i->whereAddIn('id', $ids, 'int');
549 require_once 'File/MimeType.php';
550 $y = new File_MimeType();
553 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
557 $images["attachment-{$i->id}"] = array(
558 'file' => $i->getStoreName(),
559 'mimetype' => $i->mimetype,
560 'ext' => $y->toExt($i->mimetype),
561 'contentid' => "attachment-$i->id"
565 file_put_contents($imageCache, json_encode($images));
569 function isGenerated($cachePath)
571 if (!file_exists($cachePath) || !filesize($cachePath)) {
576 $ctime = filemtime($cachePath);
578 $mtime[] = $this->updated_dt;
579 $i = DB_DataObject::factory('Images');
580 $i->onid = $this->id;
581 $i->ontable = $this->tableName();
583 $i->selectAdd('max(created) as created');
585 $mtime[] = $i->created;
586 if($ctime >= strtotime(max($mtime))){
593 function messageFrom()
595 if (empty($this->from_name)) {
596 return trim($this->from_email);
598 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
601 function formatDate($dt, $format = 'd/M/Y')
603 return date($format, strtotime($dt));
607 // fixme - this is now in core/udatedatabase..
609 function initMail($mail_template_dir, $name, $master='')
611 $cm = DB_DataObject::factory('core_email');
612 if ($cm->get('name', $name)) {
616 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
620 $opts['file'] = $mail_template_dir. $name .'.html';
621 if (!empty($master)) {
622 $opts['master'] = $mail_template_dir . $master .'.html';
625 require_once 'Pman/Core/Import/Core_email.php';
626 $x = new Pman_Core_Import_Core_email();