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'])}%'
46 function beforeDelete($dependants_array, $roo)
48 $i = DB_DataObject::factory('Images');
50 $i->ontable = $this->tableName();
58 function beforeUpdate($old, $request,$roo)
60 if (!empty($request['_make_copy'])) {
61 $this->makeCopy($roo);
66 function makeCopy($roo)
68 $c = DB_DataObject::Factory($this->tableName());
70 $c->name = "COPY of " . $this->name;
71 $c->updated_dt = $this->sqlValue('NOW()');
74 $c = DB_DataObject::Factory($this->tableName());
80 $i = DB_DataObject::factory('Images');
82 $i->ontable = $this->tableName();
86 $new_image = DB_DataObject::factory('Images');
87 $new_image->onid = $c->id;
88 $new_image->ontable = $this->tableName();
89 $new_image->createFrom($i->getStoreName(), $i->filename);
91 $map[$i->id] = $new_image->id;
95 libxml_use_internal_errors (true);
96 $doc = new DOMDocument('1.0', 'UTF-8');
97 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
98 $doc->formatOutput = true;
100 //echo '<PRE>'; print_R($doc);
103 $xpath = new DOMXpath($doc);
104 foreach ($xpath->query('//img[@src]') as $img) {
105 $href = $img->getAttribute('src');
108 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
112 if (!isset($map[$oid])) {
113 //echo "skip no new id for $oid";
117 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
119 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
125 $c->bodytext = $doc->saveHTML();
127 libxml_use_internal_errors (false);
130 $roo->jok("duplicated");
133 function onInsert($q,$roo)
135 $i = DB_DataObject::factory('Images');
137 $i->ontable = $this->tableName();
141 $i->onid = $this->id;
145 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
146 // $this->cachedMailWithOutImages(true, false);
150 function onUpdate($old, $q,$roo)
152 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
156 function attachmentIds()
158 libxml_use_internal_errors (true);
159 $doc = new DOMDocument('1.0', 'UTF-8');
160 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
162 $xpath = new DOMXpath($doc);
165 foreach ($xpath->query('//img[@src]') as $img) { // process images!
166 $href = $img->getAttribute('src');
167 $cid = explode('#', $href);
171 $cid = explode('-', $cid[1]);
172 if (!isset($cid[1])||!is_numeric($cid[1])) {
181 * process replacements is run to generate a template - not the final content..
185 function processRelacements($replace_links = true)
187 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
189 libxml_use_internal_errors (true);
190 $doc = new DOMDocument('1.0', 'UTF-8');
191 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
193 $xpath = new DOMXpath($doc);
195 foreach ($xpath->query('//img[@src]') as $img) { // process images!
196 $href = $img->getAttribute('src');
197 $hash = explode('#', $href);
198 // we name all our cid's as attachment-*
199 // however the src url may be #image-*
202 if(!isset($hash[1])){
205 $cid = explode('-', $hash[1]);
207 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
211 $unsubscribe = $this->unsubscribe_url();
213 foreach ($xpath->query('//a[@href]') as $a) {
215 $href = $a->getAttribute('href');
217 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
218 $a->setAttribute('href', $unsubscribe);
222 if(!preg_match('/^http(.*)/', $href)){
225 if (!$replace_links) {
228 $link = DB_DataObject::factory('crm_mailing_list_link');
229 $link->setFrom(array(
233 if(!$link->find(true)){
241 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
243 $a->setAttribute('href', $l);
247 if(!empty($unsubscribe)){
248 $element = $doc->createElement('img');
249 $element->setAttribute('mailembed', 'no');
250 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
251 $element->setAttribute('width', '1');
252 $element->setAttribute('height', '1');
254 $html = $doc->getElementsByTagName('html');
256 $html->item(0)->appendChild($element);
259 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
263 $this->bodytext = $doc->saveHTML();
265 libxml_use_internal_errors (false);
267 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
268 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
273 function unsubscribe_url()
275 $unsubscribe = false;
277 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
280 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
287 * convert email with contents into a core mailer object. - ready to send..
288 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
290 * + rcpts || person << if person is set - then it goes to them...
291 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
295 * + person << who it actually goes to..
297 * @param bool $force - force re-creation of cached version of email.
299 * @returns Pman_Core_Mailer||PEAR_Error
302 function toMailer($obj,$force=false)
304 require_once 'PEAR.php';
307 $contents = (array)$obj;
309 if(empty($this->id) && !empty($contents['template'])){
310 $this->get('name', $contents['template']);
313 if(empty($this->active)){
314 return $p->raiseError("template [{$contents['template']}] is Disabled");
317 if(empty($this->id)){
318 return $p->raiseError("template [{$contents['template']}] has not been set");
322 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
323 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
326 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
329 $contents['bcc'] = $admin ;
331 if (!empty($contents['rcpts_group'])) {
333 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
336 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
338 $contents['rcpts'] = $admin;
341 if(empty($contents['subject'])){
342 $contents['subject'] = $this->subject;
345 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
346 $contents['rcpts'] = implode(',', $contents['rcpts']);
349 $ui = posix_getpwuid(posix_geteuid());
351 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
353 if($force || !$this->isGenerated($cachePath)){
354 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
357 require_once 'Pman/Core/Mailer.php';
359 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
364 'template'=> $this->tableName() . '-' . $this->id,
365 'templateDir' => $templateDir,
367 'contents' => $contents,
368 'css_embed' => true, // we should always try and do this with emails...
371 if (isset($contents['rcpts'])) {
372 $cfg['rcpts'] = $contents['rcpts'];
375 if (isset($contents['attachments'])) {
376 $cfg['attachments'] = $contents['attachments'];
379 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
380 $cfg = array_merge($contents['mailer_opts'], $cfg);
383 $r = new Pman_Core_Mailer($cfg);
385 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
387 if(file_exists($imageCache) && filesize($imageCache)){
388 $images = json_decode(file_get_contents($imageCache), true);
389 $r->images = $images;
394 function toMailerData($obj,$force=false)
396 $r = $this->toMailer($obj, $force);
397 if (is_a($r, 'PEAR_Error')) {
405 * DEPRICATED !!! - DO NOT USE THIS !!!
408 function send($obj, $force = true, $send = true)
411 return $this->toMailerData($obj,$force);
414 if(!empty($obj['rcpts'])) {
415 $rcpts = $obj['rcpts'];
416 if (strpos($obj['rcpts'], '@') == false) {
418 $gp = DB_DataObject::factory('core_group');
419 $gp->get('name', $obj['rcpts']);
420 foreach ($gp->members() as $v) {
421 $rcpts[] = $v->email;
423 $obj['rcpts'] = $rcpts;
427 $r = $this->toMailer($obj, $force);
428 if (is_a($r, 'PEAR_Error')) {
435 function cachedMailWithOutImages($force = false, $replace_links = true)
438 $ui = posix_getpwuid(posix_geteuid());
440 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
442 if (!$force && $this->isGenerated($cachePath)) {
446 if (!file_exists(dirname($cachePath))) {
447 mkdir(dirname($cachePath), 0700, true);
450 $random_hash = md5(date('r', time()));
452 $this->cachedImages();
454 $fh = fopen($cachePath, 'w');
456 fwrite($fh, implode("\n", array(
457 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
458 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
459 "Subject: {t.subject:h} ",
460 "X-Message-ID: {t.id} ",
461 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
462 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
466 // note the extra space to finish the last line..
468 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
471 Content-Type: text/plain; charset=utf-8; format=flowed
472 Content-Transfer-Encoding: 7bit
481 $this->processRelacements($replace_links);
483 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
485 if (!file_exists(dirname($cachePath))) {
486 mkdir(dirname($cachePath), 0700, true);
489 file_put_contents($cachePath, $this->bodytext);
493 function cachedImages()
495 $ui = posix_getpwuid(posix_geteuid());
497 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
499 $ids = $this->attachmentIds();
502 $fh = fopen($imageCache, 'w');
504 $i = DB_DataObject::factory('Images');
505 $i->onid = $this->id;
506 $i->ontable = $this->tableName();
507 $i->whereAddIn('id', $ids, 'int');
512 require_once 'File/MimeType.php';
513 $y = new File_MimeType();
516 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
520 $images["attachment-{$i->id}"] = array(
521 'file' => $i->getStoreName(),
522 'mimetype' => $i->mimetype,
523 'ext' => $y->toExt($i->mimetype),
524 'contentid' => "attachment-$i->id"
528 file_put_contents($imageCache, json_encode($images));
532 function isGenerated($cachePath)
534 if (!file_exists($cachePath) || !filesize($cachePath)) {
539 $ctime = filemtime($cachePath);
541 $mtime[] = $this->updated_dt;
542 $i = DB_DataObject::factory('Images');
543 $i->onid = $this->id;
544 $i->ontable = $this->tableName();
546 $i->selectAdd('max(created) as created');
548 $mtime[] = $i->created;
549 if($ctime >= strtotime(max($mtime))){
556 function messageFrom()
558 if (empty($this->from_name)) {
559 return trim($this->from_email);
561 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
564 function formatDate($dt, $format = 'd/M/Y')
566 return date($format, strtotime($dt));
570 // fixme - this is now in core/udatedatabase..
572 function initMail($mail_template_dir, $name, $master='')
574 $cm = DB_DataObject::factory('core_email');
575 if ($cm->get('name', $name)) {
579 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
583 $opts['file'] = $mail_template_dir. $name .'.html';
584 if (!empty($master)) {
585 $opts['master'] = $mail_template_dir . $master .'.html';
588 require_once 'Pman/Core/Import/Core_email.php';
589 $x = new Pman_Core_Import_Core_email();