3 * Table Definition for core_email
5 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...
294 * + person << who it actually goes to..
296 * @param bool $force - force re-creation of cached version of email.
298 * @returns Pman_Core_Mailer
301 function toMailer($obj,$force=false)
304 $contents = (array)$obj;
307 if (!empty($this->bcc_group)) {
309 $group = DB_DataObject::factory('groups');
310 $group->get($this->bcc_group);
311 $admin = $group->members('email');
315 if(empty($this->id) && !empty($contents['template'])){
316 $this->get('name', $contents['template']);
319 if(empty($this->id)){
321 return $p->raiseError("template [{$contents['template']}] has not been set");
324 if(empty($contents['subject'])){
325 $contents['subject'] = $this->subject;
328 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
329 $contents['rcpts'] = implode(',', $contents['rcpts']);
332 $ui = posix_getpwuid(posix_geteuid());
334 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
336 if($force || !$this->isGenerated($cachePath)){
337 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
340 require_once 'Pman/Core/Mailer.php';
342 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
347 'template'=> $this->tableName() . '-' . $this->id,
348 'templateDir' => $templateDir,
350 'contents' => $contents,
351 'css_embed' => true, // we should always try and do this with emails...
353 if (isset($contents['rcpts'])) {
354 $cfg['rcpts'] = $contents['rcpts'];
356 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
357 $cfg = array_merge($contents['mailer_opts'], $cfg);
361 $r = new Pman_Core_Mailer($cfg);
363 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
365 if(file_exists($imageCache) && filesize($imageCache)){
366 $images = json_decode(file_get_contents($imageCache), true);
367 $r->images = $images;
372 function toMailerData($obj,$force=false)
374 $r = $this->toMailer($obj, $force);
375 if (is_a($r, 'PEAR_Error')) {
383 * DEPRICATED !!! - DO NOT USE THIS !!!
386 function send($obj, $force = true, $send = true)
389 return $this->toMailerData($obj,$force);
391 $r = $this->toMailer($obj, $force);
392 if (is_a($r, 'PEAR_Error')) {
400 function cachedMailWithOutImages($force = false, $replace_links = true)
403 $ui = posix_getpwuid(posix_geteuid());
405 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
407 if (!$force && $this->isGenerated($cachePath)) {
411 if (!file_exists(dirname($cachePath))) {
412 mkdir(dirname($cachePath), 0700, true);
415 $random_hash = md5(date('r', time()));
417 $this->cachedImages();
419 $fh = fopen($cachePath, 'w');
421 fwrite($fh, implode("\n", array(
422 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
423 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
424 "Subject: {t.subject} ",
425 "X-Message-ID: {t.id} ",
426 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
427 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
431 // note the extra space to finish the last line..
433 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
436 Content-Type: text/plain; charset=utf-8; format=flowed
437 Content-Transfer-Encoding: 7bit
446 $this->processRelacements($replace_links);
448 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
450 if (!file_exists(dirname($cachePath))) {
451 mkdir(dirname($cachePath), 0700, true);
454 file_put_contents($cachePath, $this->bodytext);
458 function cachedImages()
460 $ui = posix_getpwuid(posix_geteuid());
462 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
464 $ids = $this->attachmentIds();
467 $fh = fopen($imageCache, 'w');
469 $i = DB_DataObject::factory('Images');
470 $i->onid = $this->id;
471 $i->ontable = $this->tableName();
472 $i->whereAddIn('id', $ids, 'int');
477 require_once 'File/MimeType.php';
478 $y = new File_MimeType();
481 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
485 $images["attachment-{$i->id}"] = array(
486 'file' => $i->getStoreName(),
487 'mimetype' => $i->mimetype,
488 'ext' => $y->toExt($i->mimetype),
489 'contentid' => "attachment-$i->id"
493 file_put_contents($imageCache, json_encode($images));
497 function isGenerated($cachePath)
499 if (!file_exists($cachePath) || !filesize($cachePath)) {
504 $ctime = filemtime($cachePath);
506 $mtime[] = $this->updated_dt;
507 $i = DB_DataObject::factory('Images');
508 $i->onid = $this->id;
509 $i->ontable = $this->tableName();
511 $i->selectAdd('max(created) as created');
513 $mtime[] = $i->created;
514 if($ctime >= strtotime(max($mtime))){
521 function messageFrom()
523 if (empty($this->from_name)) {
524 return trim($this->from_email);
526 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
529 function formatDate($dt, $format = 'd/M/Y')
531 return date($format, strtotime($dt));
535 // fixme - this is now in core/udatedatabase..
537 function initMail($mail_template_dir, $name, $master='')
539 $cm = DB_DataObject::factory('core_email');
540 if ($cm->get('name', $name)) {
544 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
548 $opts['file'] = $mail_template_dir. $name .'.html';
549 if (!empty($master)) {
550 $opts['master'] = $mail_template_dir . $master .'.html';
553 require_once 'Pman/Core/Import/Core_email.php';
554 $x = new Pman_Core_Import_Core_email();