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 DB_DataObject::debugLevel(1);
37 $tn = $this->tableName();
39 if(!empty($q['search']['nameortitle'])){
41 $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
43 $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
48 function beforeDelete($dependants_array, $roo)
50 $i = DB_DataObject::factory('Images');
52 $i->ontable = $this->tableName();
60 function beforeUpdate($old, $request,$roo)
62 if (!empty($request['_make_copy'])) {
63 $this->makeCopy($roo);
68 function makeCopy($roo)
70 $c = DB_DataObject::Factory($this->tableName());
72 $c->name = "COPY of " . $this->name;
73 $c->updated_dt = $this->sqlValue('NOW()');
76 $c = DB_DataObject::Factory($this->tableName());
82 $i = DB_DataObject::factory('Images');
84 $i->ontable = $this->tableName();
88 $new_image = DB_DataObject::factory('Images');
89 $new_image->onid = $c->id;
90 $new_image->ontable = $this->tableName();
91 $new_image->createFrom($i->getStoreName(), $i->filename);
93 $map[$i->id] = $new_image->id;
97 libxml_use_internal_errors (true);
98 $doc = new DOMDocument('1.0', 'UTF-8');
99 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
100 $doc->formatOutput = true;
102 //echo '<PRE>'; print_R($doc);
105 $xpath = new DOMXpath($doc);
106 foreach ($xpath->query('//img[@src]') as $img) {
107 $href = $img->getAttribute('src');
110 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
114 if (!isset($map[$oid])) {
115 //echo "skip no new id for $oid";
119 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
121 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
127 $c->bodytext = $doc->saveHTML();
129 libxml_use_internal_errors (false);
132 $roo->jok("duplicated");
135 function onInsert($q,$roo)
137 $i = DB_DataObject::factory('Images');
139 $i->ontable = $this->tableName();
143 $i->onid = $this->id;
147 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
148 // $this->cachedMailWithOutImages(true, false);
152 function onUpdate($old, $q,$roo)
154 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
158 function attachmentIds()
160 libxml_use_internal_errors (true);
161 $doc = new DOMDocument('1.0', 'UTF-8');
162 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
164 $xpath = new DOMXpath($doc);
167 foreach ($xpath->query('//img[@src]') as $img) { // process images!
168 $href = $img->getAttribute('src');
169 $cid = explode('#', $href);
173 $cid = explode('-', $cid[1]);
174 if (!isset($cid[1])||!is_numeric($cid[1])) {
183 * process replacements is run to generate a template - not the final content..
187 function processRelacements($replace_links = true)
189 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
191 libxml_use_internal_errors (true);
192 $doc = new DOMDocument('1.0', 'UTF-8');
193 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
195 $xpath = new DOMXpath($doc);
197 foreach ($xpath->query('//img[@src]') as $img) { // process images!
198 $href = $img->getAttribute('src');
199 $hash = explode('#', $href);
200 // we name all our cid's as attachment-*
201 // however the src url may be #image-*
204 if(!isset($hash[1])){
207 $cid = explode('-', $hash[1]);
209 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
213 $unsubscribe = $this->unsubscribe_url();
215 foreach ($xpath->query('//a[@href]') as $a) {
217 $href = $a->getAttribute('href');
219 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
220 $a->setAttribute('href', $unsubscribe);
224 if(!preg_match('/^http(.*)/', $href)){
227 if (!$replace_links) {
230 $link = DB_DataObject::factory('crm_mailing_list_link');
231 $link->setFrom(array(
235 if(!$link->find(true)){
243 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
245 $a->setAttribute('href', $l);
249 if(!empty($unsubscribe)){
250 $element = $doc->createElement('img');
251 $element->setAttribute('mailembed', 'no');
252 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
253 $element->setAttribute('width', '1');
254 $element->setAttribute('height', '1');
256 $html = $doc->getElementsByTagName('html');
258 $html->item(0)->appendChild($element);
261 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
265 $this->bodytext = $doc->saveHTML();
267 libxml_use_internal_errors (false);
269 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
270 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
275 function unsubscribe_url()
277 $unsubscribe = false;
279 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
282 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
289 * convert email with contents into a core mailer object. - ready to send..
290 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
292 * + rcpts || person << if person is set - then it goes to them...
293 * + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
297 * + person << who it actually goes to..
299 * @param bool $force - force re-creation of cached version of email.
301 * @returns Pman_Core_Mailer||PEAR_Error
304 function toMailer($obj,$force=false)
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...
371 if (isset($contents['rcpts'])) {
372 $cfg['rcpts'] = $contents['rcpts'];
374 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
375 $cfg = array_merge($contents['mailer_opts'], $cfg);
379 $r = new Pman_Core_Mailer($cfg);
381 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
383 if(file_exists($imageCache) && filesize($imageCache)){
384 $images = json_decode(file_get_contents($imageCache), true);
385 $r->images = $images;
390 function toMailerData($obj,$force=false)
392 $r = $this->toMailer($obj, $force);
393 if (is_a($r, 'PEAR_Error')) {
401 * DEPRICATED !!! - DO NOT USE THIS !!!
404 function send($obj, $force = true, $send = true)
407 return $this->toMailerData($obj,$force);
409 $r = $this->toMailer($obj, $force);
410 if (is_a($r, 'PEAR_Error')) {
418 function cachedMailWithOutImages($force = false, $replace_links = true)
421 $ui = posix_getpwuid(posix_geteuid());
423 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
425 if (!$force && $this->isGenerated($cachePath)) {
429 if (!file_exists(dirname($cachePath))) {
430 mkdir(dirname($cachePath), 0700, true);
433 $random_hash = md5(date('r', time()));
435 $this->cachedImages();
437 $fh = fopen($cachePath, 'w');
439 fwrite($fh, implode("\n", array(
440 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
441 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
442 "Subject: {t.subject} ",
443 "X-Message-ID: {t.id} ",
444 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
445 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
449 // note the extra space to finish the last line..
451 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
454 Content-Type: text/plain; charset=utf-8; format=flowed
455 Content-Transfer-Encoding: 7bit
464 $this->processRelacements($replace_links);
466 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
468 if (!file_exists(dirname($cachePath))) {
469 mkdir(dirname($cachePath), 0700, true);
472 file_put_contents($cachePath, $this->bodytext);
476 function cachedImages()
478 $ui = posix_getpwuid(posix_geteuid());
480 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
482 $ids = $this->attachmentIds();
485 $fh = fopen($imageCache, 'w');
487 $i = DB_DataObject::factory('Images');
488 $i->onid = $this->id;
489 $i->ontable = $this->tableName();
490 $i->whereAddIn('id', $ids, 'int');
495 require_once 'File/MimeType.php';
496 $y = new File_MimeType();
499 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
503 $images["attachment-{$i->id}"] = array(
504 'file' => $i->getStoreName(),
505 'mimetype' => $i->mimetype,
506 'ext' => $y->toExt($i->mimetype),
507 'contentid' => "attachment-$i->id"
511 file_put_contents($imageCache, json_encode($images));
515 function isGenerated($cachePath)
517 if (!file_exists($cachePath) || !filesize($cachePath)) {
522 $ctime = filemtime($cachePath);
524 $mtime[] = $this->updated_dt;
525 $i = DB_DataObject::factory('Images');
526 $i->onid = $this->id;
527 $i->ontable = $this->tableName();
529 $i->selectAdd('max(created) as created');
531 $mtime[] = $i->created;
532 if($ctime >= strtotime(max($mtime))){
539 function messageFrom()
541 if (empty($this->from_name)) {
542 return trim($this->from_email);
544 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
547 function formatDate($dt, $format = 'd/M/Y')
549 return date($format, strtotime($dt));
553 // fixme - this is now in core/udatedatabase..
555 function initMail($mail_template_dir, $name, $master='')
557 $cm = DB_DataObject::factory('core_email');
558 if ($cm->get('name', $name)) {
562 // $basedir = $this->bootLoader->rootDir . $mail_template_dir;
566 $opts['file'] = $mail_template_dir. $name .'.html';
567 if (!empty($master)) {
568 $opts['master'] = $mail_template_dir . $master .'.html';
571 require_once 'Pman/Core/Import/Core_email.php';
572 $x = new Pman_Core_Import_Core_email();