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
84 //$c->whereAdd("group_id = {$this->to_group}");
85 $c->whereAdd("group_id = 99");
86 if (!$c->find(true)) {
90 //print_r($this->to_group);
92 print_r(count($c));exit;
96 function makeCopy($roo)
98 $c = DB_DataObject::Factory($this->tableName());
100 $c->name = "COPY of " . $this->name;
101 $c->updated_dt = $this->sqlValue('NOW()');
104 $c = DB_DataObject::Factory($this->tableName());
110 $i = DB_DataObject::factory('Images');
111 $i->onid = $this->id;
112 $i->ontable = $this->tableName();
116 $new_image = DB_DataObject::factory('Images');
117 $new_image->onid = $c->id;
118 $new_image->ontable = $this->tableName();
119 $new_image->createFrom($i->getStoreName(), $i->filename);
121 $map[$i->id] = $new_image->id;
125 libxml_use_internal_errors (true);
126 $doc = new DOMDocument('1.0', 'UTF-8');
127 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
128 $doc->formatOutput = true;
130 //echo '<PRE>'; print_R($doc);
133 $xpath = new DOMXpath($doc);
134 foreach ($xpath->query('//img[@src]') as $img) {
135 $href = $img->getAttribute('src');
138 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
142 if (!isset($map[$oid])) {
143 //echo "skip no new id for $oid";
147 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
149 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
155 $c->bodytext = $doc->saveHTML();
157 libxml_use_internal_errors (false);
160 $roo->jok("duplicated");
163 function onInsert($q,$roo)
165 $i = DB_DataObject::factory('Images');
167 $i->ontable = $this->tableName();
171 $i->onid = $this->id;
175 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
176 // $this->cachedMailWithOutImages(true, false);
180 function onUpdate($old, $q,$roo)
182 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
186 function attachmentIds()
188 libxml_use_internal_errors (true);
189 $doc = new DOMDocument('1.0', 'UTF-8');
190 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
192 $xpath = new DOMXpath($doc);
195 foreach ($xpath->query('//img[@src]') as $img) { // process images!
196 $href = $img->getAttribute('src');
197 $cid = explode('#', $href);
201 $cid = explode('-', $cid[1]);
202 if (!isset($cid[1])||!is_numeric($cid[1])) {
211 * process replacements is run to generate a template - not the final content..
215 function processRelacements($replace_links = true)
217 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
219 libxml_use_internal_errors (true);
220 $doc = new DOMDocument('1.0', 'UTF-8');
221 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
223 $xpath = new DOMXpath($doc);
225 foreach ($xpath->query('//img[@src]') as $img) { // process images!
226 $href = $img->getAttribute('src');
227 $hash = explode('#', $href);
228 // we name all our cid's as attachment-*
229 // however the src url may be #image-*
232 if(!isset($hash[1])){
235 $cid = explode('-', $hash[1]);
237 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
241 $unsubscribe = $this->unsubscribe_url();
243 foreach ($xpath->query('//a[@href]') as $a) {
245 $href = $a->getAttribute('href');
247 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
248 $a->setAttribute('href', $unsubscribe);
252 if(!preg_match('/^http(.*)/', $href)){
255 if (!$replace_links) {
258 $link = DB_DataObject::factory('crm_mailing_list_link');
259 $link->setFrom(array(
263 if(!$link->find(true)){
271 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
273 $a->setAttribute('href', $l);
277 if(!empty($unsubscribe)){
278 $element = $doc->createElement('img');
279 $element->setAttribute('mailembed', 'no');
280 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
281 $element->setAttribute('width', '1');
282 $element->setAttribute('height', '1');
284 $html = $doc->getElementsByTagName('html');
286 $html->item(0)->appendChild($element);
289 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
293 $this->bodytext = $doc->saveHTML();
295 libxml_use_internal_errors (false);
297 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
298 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
303 function unsubscribe_url()
305 $unsubscribe = false;
307 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
310 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
317 * convert email with contents into a core mailer object. - ready to send..
318 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
320 * + rcpts || person << if person is set - then it goes to them...
321 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
325 * + person << who it actually goes to..
327 * @param bool $force - force re-creation of cached version of email.
329 * @returns Pman_Core_Mailer||PEAR_Error
332 function toMailer($obj,$force=false)
334 require_once 'PEAR.php';
337 $contents = (array)$obj;
339 if(empty($this->id) && !empty($contents['template'])){
340 $this->get('name', $contents['template']);
344 if(empty($this->active)){
345 return $p->raiseError("template [{$contents['template']}] is Disabled");
349 if(empty($this->id)){
350 return $p->raiseError("template [{$contents['template']}] has not been set");
355 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
356 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
359 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
362 $contents['bcc'] = $admin ;
364 if (!empty($contents['rcpts_group'])) {
366 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
369 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
371 $contents['rcpts'] = $admin;
374 //subject replacement
375 if(empty($contents['subject'])){
376 $contents['subject'] = $this->subject;
379 if (!empty($contents['subject_replace'])) {
380 foreach ($contents['mapping'] as $pattern => $replace) {
381 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
385 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
386 $contents['rcpts'] = implode(',', $contents['rcpts']);
389 $ui = posix_getpwuid(posix_geteuid());
391 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
393 if($force || !$this->isGenerated($cachePath)){
394 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
397 require_once 'Pman/Core/Mailer.php';
400 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
405 'template'=> $this->tableName() . '-' . $this->id,
406 'templateDir' => $templateDir,
408 'contents' => $contents,
409 'css_embed' => true, // we should always try and do this with emails...
412 if (isset($contents['rcpts'])) {
413 $cfg['rcpts'] = $contents['rcpts'];
416 if (isset($contents['attachments'])) {
417 $cfg['attachments'] = $contents['attachments'];
420 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
421 $cfg = array_merge($contents['mailer_opts'], $cfg);
424 $r = new Pman_Core_Mailer($cfg);
426 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
428 if(file_exists($imageCache) && filesize($imageCache)){
429 $images = json_decode(file_get_contents($imageCache), true);
430 $r->images = $images;
435 function toMailerData($obj,$force=false)
437 $r = $this->toMailer($obj, $force);
438 if (is_a($r, 'PEAR_Error')) {
446 * DEPRICATED !!! - DO NOT USE THIS !!!
448 * use: toMailerData() -- to return the email data..
450 * $mailer = $core_email->toMailer($obj, false);
451 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
453 * toMailer($obj, false)->send()
458 function send($obj, $force = true, $send = true)
461 return $this->toMailerData($obj,$force);
464 $r = $this->toMailer($obj, $force);
466 if (is_a($r, 'PEAR_Error')) {
473 function cachedMailWithOutImages($force = false, $replace_links = true)
476 $ui = posix_getpwuid(posix_geteuid());
478 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
480 if (!$force && $this->isGenerated($cachePath)) {
484 if (!file_exists(dirname($cachePath))) {
485 mkdir(dirname($cachePath), 0700, true);
488 $random_hash = md5(date('r', time()));
490 $this->cachedImages();
492 $fh = fopen($cachePath, 'w');
494 fwrite($fh, implode("\n", array(
495 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
496 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
497 "Subject: {t.subject:h} ",
498 "X-Message-ID: {t.id} ",
499 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
500 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
504 // note the extra space to finish the last line..
506 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
509 Content-Type: text/plain; charset=utf-8; format=flowed
510 Content-Transfer-Encoding: 7bit
519 $this->processRelacements($replace_links);
521 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
523 if (!file_exists(dirname($cachePath))) {
524 mkdir(dirname($cachePath), 0700, true);
527 file_put_contents($cachePath, $this->bodytext);
531 function cachedImages()
533 $ui = posix_getpwuid(posix_geteuid());
535 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
537 $ids = $this->attachmentIds();
540 $fh = fopen($imageCache, 'w');
542 $i = DB_DataObject::factory('Images');
543 $i->onid = $this->id;
544 $i->ontable = $this->tableName();
545 $i->whereAddIn('id', $ids, 'int');
550 require_once 'File/MimeType.php';
551 $y = new File_MimeType();
554 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
558 $images["attachment-{$i->id}"] = array(
559 'file' => $i->getStoreName(),
560 'mimetype' => $i->mimetype,
561 'ext' => $y->toExt($i->mimetype),
562 'contentid' => "attachment-$i->id"
566 file_put_contents($imageCache, json_encode($images));
570 function isGenerated($cachePath)
572 if (!file_exists($cachePath) || !filesize($cachePath)) {
577 $ctime = filemtime($cachePath);
579 $mtime[] = $this->updated_dt;
580 $i = DB_DataObject::factory('Images');
581 $i->onid = $this->id;
582 $i->ontable = $this->tableName();
584 $i->selectAdd('max(created) as created');
586 $mtime[] = $i->created;
587 if($ctime >= strtotime(max($mtime))){
594 function messageFrom()
596 if (empty($this->from_name)) {
597 return trim($this->from_email);
599 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
602 function formatDate($dt, $format = 'd/M/Y')
604 return date($format, strtotime($dt));
608 // fixme - this is now in core/udatedatabase..
610 function initMail($mail_template_dir, $name, $master='')
612 $cm = DB_DataObject::factory('core_email');
613 if ($cm->get('name', $name)) {
617 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
621 $opts['file'] = $mail_template_dir. $name .'.html';
622 if (!empty($master)) {
623 $opts['master'] = $mail_template_dir . $master .'.html';
626 require_once 'Pman/Core/Import/Core_email.php';
627 $x = new Pman_Core_Import_Core_email();