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
24 /* the code above is auto generated do not remove the tag below */
27 function applyFilters($q, $au, $roo)
29 $tn = $this->tableName();
31 if(!empty($q['search']['nameortitle'])){
33 $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
35 $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
40 function beforeDelete($dependants_array, $roo)
42 $i = DB_DataObject::factory('Images');
44 $i->ontable = $this->tableName();
52 function beforeUpdate($old, $request,$roo)
54 if (!empty($request['_make_copy'])) {
55 $this->makeCopy($roo);
60 function makeCopy($roo)
62 $c = DB_DataObject::Factory($this->tableName());
64 $c->name = "COPY of " . $this->name;
65 $c->updated_dt = $this->sqlValue('NOW()');
68 $c = DB_DataObject::Factory($this->tableName());
74 $i = DB_DataObject::factory('Images');
76 $i->ontable = $this->tableName();
80 $new_image = DB_DataObject::factory('Images');
81 $new_image->onid = $c->id;
82 $new_image->ontable = $this->tableName();
83 $new_image->createFrom($i->getStoreName(), $i->filename);
85 $map[$i->id] = $new_image->id;
89 libxml_use_internal_errors (true);
90 $doc = new DOMDocument('1.0', 'UTF-8');
91 $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
92 $doc->formatOutput = true;
94 //echo '<PRE>'; print_R($doc);
97 $xpath = new DOMXpath($doc);
98 foreach ($xpath->query('//img[@src]') as $img) {
99 $href = $img->getAttribute('src');
102 if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
106 if (!isset($map[$oid])) {
107 //echo "skip no new id for $oid";
111 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
113 $img->setAttribute('src', str_replace($matches[0], $nstr, $href ));
119 $c->bodytext = $doc->saveHTML();
121 libxml_use_internal_errors (false);
124 $roo->jok("duplicated");
127 function onInsert($q,$roo)
129 $i = DB_DataObject::factory('Images');
131 $i->ontable = $this->tableName();
135 $i->onid = $this->id;
139 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
140 // $this->cachedMailWithOutImages(true, false);
144 function onUpdate($old, $q,$roo)
146 $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
150 function attachmentIds()
152 libxml_use_internal_errors (true);
153 $doc = new DOMDocument('1.0', 'UTF-8');
154 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
156 $xpath = new DOMXpath($doc);
159 foreach ($xpath->query('//img[@src]') as $img) { // process images!
160 $href = $img->getAttribute('src');
161 $cid = explode('#', $href);
165 $cid = explode('-', $cid[1]);
166 if (!isset($cid[1])||!is_numeric($cid[1])) {
175 * process replacements is run to generate a template - not the final content..
179 function processRelacements($replace_links = true)
181 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
183 libxml_use_internal_errors (true);
184 $doc = new DOMDocument('1.0', 'UTF-8');
185 $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
187 $xpath = new DOMXpath($doc);
189 foreach ($xpath->query('//img[@src]') as $img) { // process images!
190 $href = $img->getAttribute('src');
191 $hash = explode('#', $href);
192 // we name all our cid's as attachment-*
193 // however the src url may be #image-*
196 if(!isset($hash[1])){
199 $cid = explode('-', $hash[1]);
201 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
205 $unsubscribe = $this->unsubscribe_url();
207 foreach ($xpath->query('//a[@href]') as $a) {
209 $href = $a->getAttribute('href');
211 if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
212 $a->setAttribute('href', $unsubscribe);
216 if(!preg_match('/^http(.*)/', $href)){
219 if (!$replace_links) {
222 $link = DB_DataObject::factory('crm_mailing_list_link');
223 $link->setFrom(array(
227 if(!$link->find(true)){
235 $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
237 $a->setAttribute('href', $l);
241 if(!empty($unsubscribe)){
242 $element = $doc->createElement('img');
244 $element->setAttribute('src', $cfg ['server_baseurl'] . '/Crm/Open/' . $this->id . '/{person.id}.html');
245 $element->setAttribute('width', '1');
246 $element->setAttribute('height', '1');
248 $html = $doc->getElementsByTagName('html');
250 $html->item(0)->appendChild($element);
253 $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
257 $this->bodytext = $doc->saveHTML();
259 libxml_use_internal_errors (false);
261 $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
262 $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
267 function unsubscribe_url()
269 $unsubscribe = false;
271 $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
274 $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
281 * convert email with contents into a core mailer object. - ready to send..
282 * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
288 * @param bool $force - force re-creation of cached version of email.
291 function toMailer($obj,$force=false)
294 $contents = (array)$obj;
296 if(empty($this->id) && !empty($contents['template'])){
297 $this->get('name', $contents['template']);
300 if(empty($this->id)){
302 return $p->raiseError("template [{$contents['template']}] has not been set");
305 if(empty($contents['subject'])){
306 $contents['subject'] = $this->subject;
309 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
310 $contents['rcpts'] = implode(',', $contents['rcpts']);
313 $ui = posix_getpwuid(posix_geteuid());
315 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
317 if($force || !$this->isGenerated($cachePath)){
318 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
321 require_once 'Pman/Core/Mailer.php';
323 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
328 'template'=> $this->tableName() . '-' . $this->id,
329 'templateDir' => $templateDir,
331 'contents' => $contents,
332 'css_embed' => true, // we should always try and do this with emails...
334 if (isset($contents['rcpts'])) {
335 $cfg['rcpts'] = $contents['rcpts'];
337 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
338 $cfg = array_merge($contents['mailer_opts'], $cfg);
342 $r = new Pman_Core_Mailer($cfg);
344 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
346 if(file_exists($imageCache) && filesize($imageCache)){
347 $images = json_decode(file_get_contents($imageCache), true);
348 $r->images = $images;
369 * $this->rcpts = array('sales@roojs.com');
371 * $this->rcpts = "Tester <sales@roojs.com>";
375 * $x = DB_DataObject::factory('core_enum');
376 * $x->get('name', 'NAME OF TEMPLATE');
378 * 'rcpts' => "Tester <sales@roojs.com>",
380 * 'mailer_opts' => array( <<< additional options, like urlmap..)
381 * 'link' => 'http://......'
383 * // on the template use {link:h} to render the link
387 function send($obj, $force = true, $send = true)
389 $contents = (array)$obj;
391 if(empty($this->id)){
392 $this->get('name', $contents['template']);
395 if(empty($this->id)){
397 return $p->raiseError("template [{$contents['template']}] has not been set");
399 if(empty($contents['subject'])){
400 $contents['subject'] = $this->subject;
403 if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
404 $contents['rcpts'] = implode(',', $contents['rcpts']);
407 $ui = posix_getpwuid(posix_geteuid());
409 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
411 if($force || !$this->isGenerated($cachePath)){
412 $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
415 require_once 'Pman/Core/Mailer.php';
417 $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
422 'template'=> $this->tableName() . '-' . $this->id,
423 'templateDir' => $templateDir,
425 'contents' => $contents,
426 'css_embed' => true, // we should always try and do this with emails...
428 if (isset($contents['rcpts'])) {
429 $cfg['rcpts'] = $contents['rcpts'];
431 if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
432 $cfg = array_merge($contents['mailer_opts'], $cfg);
436 $r = new Pman_Core_Mailer($cfg);
438 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
440 if(file_exists($imageCache) && filesize($imageCache)){
441 $images = json_decode(file_get_contents($imageCache), true);
442 $r->images = $images;
454 function cachedMailWithOutImages($force = false, $replace_links = true)
457 $ui = posix_getpwuid(posix_geteuid());
459 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
461 if (!$force && $this->isGenerated($cachePath)) {
465 if (!file_exists(dirname($cachePath))) {
466 mkdir(dirname($cachePath), 0700, true);
469 $random_hash = md5(date('r', time()));
471 $this->cachedImages();
473 $fh = fopen($cachePath, 'w');
475 fwrite($fh, implode("\n", array(
476 "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
477 "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
478 "Subject: {t.subject} ",
479 "X-Message-ID: {t.id} ",
480 "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
481 "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
485 // note the extra space to finish the last line..
487 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
490 Content-Type: text/plain; charset=utf-8; format=flowed
491 Content-Transfer-Encoding: 7bit
500 $this->processRelacements($replace_links);
502 $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
504 if (!file_exists(dirname($cachePath))) {
505 mkdir(dirname($cachePath), 0700, true);
508 file_put_contents($cachePath, $this->bodytext);
512 function cachedImages()
514 $ui = posix_getpwuid(posix_geteuid());
516 $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
518 $ids = $this->attachmentIds();
521 $fh = fopen($imageCache, 'w');
523 $i = DB_DataObject::factory('Images');
524 $i->onid = $this->id;
525 $i->ontable = $this->tableName();
526 $i->whereAddIn('id', $ids, 'int');
531 require_once 'File/MimeType.php';
532 $y = new File_MimeType();
535 if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
539 $images["attachment-$i->id"] = array(
540 'file' => $i->getStoreName(),
541 'mimetype' => $i->mimetype,
542 'ext' => $y->toExt($i->mimetype),
543 'contentid' => "attachment-$i->id"
547 file_put_contents($imageCache, json_encode($images));
551 function isGenerated($cachePath)
553 if (!file_exists($cachePath) || !filesize($cachePath)) {
558 $ctime = filemtime($cachePath);
560 $mtime[] = $this->updated_dt;
561 $i = DB_DataObject::factory('Images');
562 $i->onid = $this->id;
563 $i->ontable = $this->tableName();
565 $i->selectAdd('max(created) as created');
567 $mtime[] = $i->created;
568 if($ctime >= strtotime(max($mtime))){
575 function messageFrom()
577 if (empty($this->from_name)) {
578 return trim($this->from_email);
580 return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>') ;
583 function formatDate($dt, $format = 'd/M/Y')
585 return date($format, strtotime($dt));