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;
310 if(empty($this->id) && !empty($contents['template'])){
311 $this->get('name', $contents['template']);
314 if(empty($this->active)){
315 return $p->raiseError("template [{$contents['template']}] is Disabled");
318 if(empty($this->id)){
319 return $p->raiseError("template [{$contents['template']}] has not been set");
323 if (!empty($this->bcc_group) && empty($contents['rcpts_group'])) {
324 $admin = DB_DAtaObject::Factory('core_group')->lookupMembersByGroupId($this->bcc_group,'email');
327 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
330 $contents['bcc'] = $admin ;
332 if (!empty($contents['rcpts_group'])) {
334 $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
337 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
339 $contents['rcpts'] = $admin;
342 if(empty($contents['subject'])){
343 $contents['subject'] = $this->subject;
346 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
347 $contents['rcpts'] = implode(',', $contents['rcpts']);
350 $ui = posix_getpwuid(posix_geteuid());
352 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
354 if($force || !$this->isGenerated($cachePath)){
355 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
358 require_once 'Pman/Core/Mailer.php';
360 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
365 'template'=> $this->tableName() . '-' . $this->id,
366 'templateDir' => $templateDir,
368 'contents' => $contents,
369 'css_embed' => true, // we should always try and do this with emails...
372 if (isset($contents['rcpts'])) {
373 $cfg['rcpts'] = $contents['rcpts'];
376 if (isset($contents['attachments'])) {
377 $cfg['attachments'] = $contents['attachments'];
380 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
381 $cfg = array_merge($contents['mailer_opts'], $cfg);
384 $r = new Pman_Core_Mailer($cfg);
386 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
388 if(file_exists($imageCache) && filesize($imageCache)){
389 $images = json_decode(file_get_contents($imageCache), true);
390 $r->images = $images;
395 function toMailerData($obj,$force=false)
397 $r = $this->toMailer($obj, $force);
398 if (is_a($r, 'PEAR_Error')) {
406 * DEPRICATED !!! - DO NOT USE THIS !!!
409 function send($obj, $force = true, $send = true)
412 return $this->toMailerData($obj,$force);
415 if(!empty($obj['rcpts'])) {
420 $r = $this->toMailer($obj, $force);
421 if (is_a($r, 'PEAR_Error')) {
429 function cachedMailWithOutImages($force = false, $replace_links = true)
432 $ui = posix_getpwuid(posix_geteuid());
434 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
436 if (!$force && $this->isGenerated($cachePath)) {
440 if (!file_exists(dirname($cachePath))) {
441 mkdir(dirname($cachePath), 0700, true);
444 $random_hash = md5(date('r', time()));
446 $this->cachedImages();
448 $fh = fopen($cachePath, 'w');
450 fwrite($fh, implode("\n", array(
451 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
452 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
453 "Subject: {t.subject:h} ",
454 "X-Message-ID: {t.id} ",
455 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
456 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
460 // note the extra space to finish the last line..
462 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
465 Content-Type: text/plain; charset=utf-8; format=flowed
466 Content-Transfer-Encoding: 7bit
475 $this->processRelacements($replace_links);
477 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
479 if (!file_exists(dirname($cachePath))) {
480 mkdir(dirname($cachePath), 0700, true);
483 file_put_contents($cachePath, $this->bodytext);
487 function cachedImages()
489 $ui = posix_getpwuid(posix_geteuid());
491 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
493 $ids = $this->attachmentIds();
496 $fh = fopen($imageCache, 'w');
498 $i = DB_DataObject::factory('Images');
499 $i->onid = $this->id;
500 $i->ontable = $this->tableName();
501 $i->whereAddIn('id', $ids, 'int');
506 require_once 'File/MimeType.php';
507 $y = new File_MimeType();
510 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
514 $images["attachment-{$i->id}"] = array(
515 'file' => $i->getStoreName(),
516 'mimetype' => $i->mimetype,
517 'ext' => $y->toExt($i->mimetype),
518 'contentid' => "attachment-$i->id"
522 file_put_contents($imageCache, json_encode($images));
526 function isGenerated($cachePath)
528 if (!file_exists($cachePath) || !filesize($cachePath)) {
533 $ctime = filemtime($cachePath);
535 $mtime[] = $this->updated_dt;
536 $i = DB_DataObject::factory('Images');
537 $i->onid = $this->id;
538 $i->ontable = $this->tableName();
540 $i->selectAdd('max(created) as created');
542 $mtime[] = $i->created;
543 if($ctime >= strtotime(max($mtime))){
550 function messageFrom()
552 if (empty($this->from_name)) {
553 return trim($this->from_email);
555 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
558 function formatDate($dt, $format = 'd/M/Y')
560 return date($format, strtotime($dt));
564 // fixme - this is now in core/udatedatabase..
566 function initMail($mail_template_dir, $name, $master='')
568 $cm = DB_DataObject::factory('core_email');
569 if ($cm->get('name', $name)) {
573 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
577 $opts['file'] = $mail_template_dir. $name .'.html';
578 if (!empty($master)) {
579 $opts['master'] = $mail_template_dir . $master .'.html';
582 require_once 'Pman/Core/Import/Core_email.php';
583 $x = new Pman_Core_Import_Core_email();