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
82 print_r($c->count());exit;
83 if (!$c->find(true)) {
89 function makeCopy($roo)
91 $c = DB_DataObject::Factory($this->tableName());
93 $c->name = "COPY of " . $this->name;
94 $c->updated_dt = $this->sqlValue('NOW()');
97 $c = DB_DataObject::Factory($this->tableName());
103 $i = DB_DataObject::factory('Images');
104 $i->onid = $this->id;
105 $i->ontable = $this->tableName();
109 $new_image = DB_DataObject::factory('Images');
110 $new_image->onid = $c->id;
111 $new_image->ontable = $this->tableName();
112 $new_image->createFrom($i->getStoreName(), $i->filename);
114 $map[$i->id] = $new_image->id;
118 libxml_use_internal_errors (true);
119 $doc = new DOMDocument('1.0', 'UTF-8');
120 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
121 $doc->formatOutput = true;
123 //echo '<PRE>'; print_R($doc);
126 $xpath = new DOMXpath($doc);
127 foreach ($xpath->query('//img[@src]') as $img) {
128 $href = $img->getAttribute('src');
131 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
135 if (!isset($map[$oid])) {
136 //echo "skip no new id for $oid";
140 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
142 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
148 $c->bodytext = $doc->saveHTML();
150 libxml_use_internal_errors (false);
153 $roo->jok("duplicated");
156 function onInsert($q,$roo)
158 $i = DB_DataObject::factory('Images');
160 $i->ontable = $this->tableName();
164 $i->onid = $this->id;
168 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
169 // $this->cachedMailWithOutImages(true, false);
173 function onUpdate($old, $q,$roo)
175 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
179 function attachmentIds()
181 libxml_use_internal_errors (true);
182 $doc = new DOMDocument('1.0', 'UTF-8');
183 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
185 $xpath = new DOMXpath($doc);
188 foreach ($xpath->query('//img[@src]') as $img) { // process images!
189 $href = $img->getAttribute('src');
190 $cid = explode('#', $href);
194 $cid = explode('-', $cid[1]);
195 if (!isset($cid[1])||!is_numeric($cid[1])) {
204 * process replacements is run to generate a template - not the final content..
208 function processRelacements($replace_links = true)
210 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
212 libxml_use_internal_errors (true);
213 $doc = new DOMDocument('1.0', 'UTF-8');
214 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
216 $xpath = new DOMXpath($doc);
218 foreach ($xpath->query('//img[@src]') as $img) { // process images!
219 $href = $img->getAttribute('src');
220 $hash = explode('#', $href);
221 // we name all our cid's as attachment-*
222 // however the src url may be #image-*
225 if(!isset($hash[1])){
228 $cid = explode('-', $hash[1]);
230 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
234 $unsubscribe = $this->unsubscribe_url();
236 foreach ($xpath->query('//a[@href]') as $a) {
238 $href = $a->getAttribute('href');
240 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
241 $a->setAttribute('href', $unsubscribe);
245 if(!preg_match('/^http(.*)/', $href)){
248 if (!$replace_links) {
251 $link = DB_DataObject::factory('crm_mailing_list_link');
252 $link->setFrom(array(
256 if(!$link->find(true)){
264 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
266 $a->setAttribute('href', $l);
270 if(!empty($unsubscribe)){
271 $element = $doc->createElement('img');
272 $element->setAttribute('mailembed', 'no');
273 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
274 $element->setAttribute('width', '1');
275 $element->setAttribute('height', '1');
277 $html = $doc->getElementsByTagName('html');
279 $html->item(0)->appendChild($element);
282 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
286 $this->bodytext = $doc->saveHTML();
288 libxml_use_internal_errors (false);
290 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
291 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
296 function unsubscribe_url()
298 $unsubscribe = false;
300 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
303 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
310 * convert email with contents into a core mailer object. - ready to send..
311 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
313 * + rcpts || person << if person is set - then it goes to them...
314 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
318 * + person << who it actually goes to..
320 * @param bool $force - force re-creation of cached version of email.
322 * @returns Pman_Core_Mailer||PEAR_Error
325 function toMailer($obj,$force=false)
327 require_once 'PEAR.php';
330 $contents = (array)$obj;
332 if(empty($this->id) && !empty($contents['template'])){
333 $this->get('name', $contents['template']);
337 if(empty($this->active)){
338 return $p->raiseError("template [{$contents['template']}] is Disabled");
342 if(empty($this->id)){
343 return $p->raiseError("template [{$contents['template']}] has not been set");
348 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
349 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
352 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
355 $contents['bcc'] = $admin ;
357 if (!empty($contents['rcpts_group'])) {
359 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
362 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
364 $contents['rcpts'] = $admin;
367 //subject replacement
368 if(empty($contents['subject'])){
369 $contents['subject'] = $this->subject;
372 if (!empty($contents['subject_replace'])) {
373 foreach ($contents['mapping'] as $pattern => $replace) {
374 $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
378 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
379 $contents['rcpts'] = implode(',', $contents['rcpts']);
382 $ui = posix_getpwuid(posix_geteuid());
384 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
386 if($force || !$this->isGenerated($cachePath)){
387 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
390 require_once 'Pman/Core/Mailer.php';
393 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
398 'template'=> $this->tableName() . '-' . $this->id,
399 'templateDir' => $templateDir,
401 'contents' => $contents,
402 'css_embed' => true, // we should always try and do this with emails...
405 if (isset($contents['rcpts'])) {
406 $cfg['rcpts'] = $contents['rcpts'];
409 if (isset($contents['attachments'])) {
410 $cfg['attachments'] = $contents['attachments'];
413 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
414 $cfg = array_merge($contents['mailer_opts'], $cfg);
417 $r = new Pman_Core_Mailer($cfg);
419 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
421 if(file_exists($imageCache) && filesize($imageCache)){
422 $images = json_decode(file_get_contents($imageCache), true);
423 $r->images = $images;
428 function toMailerData($obj,$force=false)
430 $r = $this->toMailer($obj, $force);
431 if (is_a($r, 'PEAR_Error')) {
439 * DEPRICATED !!! - DO NOT USE THIS !!!
441 * use: toMailerData() -- to return the email data..
443 * $mailer = $core_email->toMailer($obj, false);
444 * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
446 * toMailer($obj, false)->send()
451 function send($obj, $force = true, $send = true)
454 return $this->toMailerData($obj,$force);
457 $r = $this->toMailer($obj, $force);
459 if (is_a($r, 'PEAR_Error')) {
466 function cachedMailWithOutImages($force = false, $replace_links = true)
469 $ui = posix_getpwuid(posix_geteuid());
471 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
473 if (!$force && $this->isGenerated($cachePath)) {
477 if (!file_exists(dirname($cachePath))) {
478 mkdir(dirname($cachePath), 0700, true);
481 $random_hash = md5(date('r', time()));
483 $this->cachedImages();
485 $fh = fopen($cachePath, 'w');
487 fwrite($fh, implode("\n", array(
488 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
489 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
490 "Subject: {t.subject:h} ",
491 "X-Message-ID: {t.id} ",
492 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
493 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
497 // note the extra space to finish the last line..
499 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
502 Content-Type: text/plain; charset=utf-8; format=flowed
503 Content-Transfer-Encoding: 7bit
512 $this->processRelacements($replace_links);
514 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
516 if (!file_exists(dirname($cachePath))) {
517 mkdir(dirname($cachePath), 0700, true);
520 file_put_contents($cachePath, $this->bodytext);
524 function cachedImages()
526 $ui = posix_getpwuid(posix_geteuid());
528 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
530 $ids = $this->attachmentIds();
533 $fh = fopen($imageCache, 'w');
535 $i = DB_DataObject::factory('Images');
536 $i->onid = $this->id;
537 $i->ontable = $this->tableName();
538 $i->whereAddIn('id', $ids, 'int');
543 require_once 'File/MimeType.php';
544 $y = new File_MimeType();
547 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
551 $images["attachment-{$i->id}"] = array(
552 'file' => $i->getStoreName(),
553 'mimetype' => $i->mimetype,
554 'ext' => $y->toExt($i->mimetype),
555 'contentid' => "attachment-$i->id"
559 file_put_contents($imageCache, json_encode($images));
563 function isGenerated($cachePath)
565 if (!file_exists($cachePath) || !filesize($cachePath)) {
570 $ctime = filemtime($cachePath);
572 $mtime[] = $this->updated_dt;
573 $i = DB_DataObject::factory('Images');
574 $i->onid = $this->id;
575 $i->ontable = $this->tableName();
577 $i->selectAdd('max(created) as created');
579 $mtime[] = $i->created;
580 if($ctime >= strtotime(max($mtime))){
587 function messageFrom()
589 if (empty($this->from_name)) {
590 return trim($this->from_email);
592 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
595 function formatDate($dt, $format = 'd/M/Y')
597 return date($format, strtotime($dt));
601 // fixme - this is now in core/udatedatabase..
603 function initMail($mail_template_dir, $name, $master='')
605 $cm = DB_DataObject::factory('core_email');
606 if ($cm->get('name', $name)) {
610 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
614 $opts['file'] = $mail_template_dir. $name .'.html';
615 if (!empty($master)) {
616 $opts['master'] = $mail_template_dir . $master .'.html';
619 require_once 'Pman/Core/Import/Core_email.php';
620 $x = new Pman_Core_Import_Core_email();