c0d3721b4d9170b798d14c6fb811c60b37a9b3ca
[Pman.Core] / DataObjects / Core_email.php
1 <?php
2 /**
3  * Table Definition for core_email
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_email extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11   
12     public $__table = 'core_email';    // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $name;                            // 
15     public $subject;                         // blob(65535)  blob
16     public $bodytext;                        // blob(65535)  blob
17     public $plaintext;
18     public $updated_dt;                      //datetime not_null
19     public $from_email;
20     public $from_name;
21     public $owner_id;
22     public $is_system;
23     public $active;
24     public $bcc_group_id;
25     public $test_class;
26      
27     /* the code above is auto generated do not remove the tag below */
28     ###END_AUTOCODE
29     
30     function applyFilters($q, $au, $roo)
31     {
32         $tn = $this->tableName();
33         
34         if(!empty($q['search']['nameortitle'])){
35             $this->whereAdd("
36                 $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
37                 OR
38                 $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
39             ");
40         }
41         $cgm = DB_DataObject::Factory('core_group_member')->tableName();;
42       
43         
44         
45         if (!empty($_REQUEST['_hide_system_emails'])) {
46             $this->whereAddIn("!{$this->tableName()}.name", array('EVENT_ERRORS_REPORT'), 'string');
47         }
48         
49     }
50     
51     function beforeDelete($dependants_array, $roo)
52     {   
53         $i = DB_DataObject::factory('Images');
54         $i->onid = $this->id;
55         $i->ontable = $this->tableName();
56         $i->find();
57         while ($i->fetch()){
58             $i->beforeDelete();
59             $i->delete();
60         }
61     }
62     
63     function beforeUpdate($old, $request,$roo)
64     {   
65         if (!empty($request['_make_copy'])) {
66             $this->makeCopy($roo);
67             
68         }
69         
70         if ($this->to_group_id != -1) {
71                    
72             $c = DB_DataObject::factory('core_group_member');            
73             $c->group_id = $this->to_group_id;
74                         
75             if (!$c->count() && empty($request['_ignore_group_count'])) {
76                 $roo->jerr('Failed to create email template - No member found in recieptent group',array('errcode'=> 100));
77             }
78         }
79     }
80     
81     function makeCopy($roo)
82     {
83         $c = DB_DataObject::Factory($this->tableName());
84         $c->setFrom($this);
85         $c->name = "COPY of " . $this->name;
86         $c->updated_dt = $this->sqlValue('NOW()');
87         
88         $id = $c->insert();
89         $c = DB_DataObject::Factory($this->tableName());
90         $c->get($id);
91         
92         
93         // copy images.
94         
95         $i = DB_DataObject::factory('Images');
96         $i->onid = $this->id;
97         $i->ontable = $this->tableName();
98         $i->find();
99         while ($i->fetch()){
100             
101             $new_image = DB_DataObject::factory('Images');
102             $new_image->onid = $c->id;
103             $new_image->ontable = $this->tableName();
104             $new_image->createFrom($i->getStoreName(), $i->filename);
105             
106             $map[$i->id] = $new_image->id;
107         }
108         
109         
110         libxml_use_internal_errors (true);
111         $doc = new DOMDocument('1.0', 'UTF-8');
112         $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
113         $doc->formatOutput = true;
114
115        //echo '<PRE>'; print_R($doc);
116         
117         
118         $xpath = new DOMXpath($doc);
119         foreach ($xpath->query('//img[@src]') as $img) {
120             $href = $img->getAttribute('src');
121             //var_dump($href);
122             $matches = array();
123             if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
124                  
125                 $oid = $matches[1];
126                 
127                 if (!isset($map[$oid])) {
128                     //echo "skip no new id for $oid";
129                     continue;
130                 }
131                 $nid = $map[$oid];
132                 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
133                 
134                 $img->setAttribute('src',  str_replace($matches[0], $nstr, $href ));
135                     
136                  
137             }
138         }
139         $cc = clone($c);
140         $c->bodytext = $doc->saveHTML();
141         $c->update($cc);
142         libxml_use_internal_errors (false);
143         
144         
145         $roo->jok("duplicated");
146     }
147     
148     function onInsert($q,$roo)
149     {   
150         $i = DB_DataObject::factory('Images');
151         $i->onid = 0;
152         $i->ontable = $this->tableName();
153         $i->find();
154         while ($i->fetch()){
155             $ii = clone ($i);
156             $i->onid = $this->id;
157             $i->update($ii);
158         }
159         
160         $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
161 //        $this->cachedMailWithOutImages(true, false);
162        
163     }
164     
165     function onUpdate($old, $q,$roo)
166     {
167         $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
168     }
169
170
171     function attachmentIds()
172     {
173         libxml_use_internal_errors (true);
174         $doc = new DOMDocument('1.0', 'UTF-8');
175         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
176         
177         $xpath = new DOMXpath($doc);
178         $ret = array();
179         
180         foreach ($xpath->query('//img[@src]') as $img) { // process images!
181             $href = $img->getAttribute('src');
182             $cid = explode('#', $href);
183             if(!isset($cid[1])){
184                 continue;
185             }
186             $cid = explode('-', $cid[1]);
187             if (!isset($cid[1])||!is_numeric($cid[1])) {
188                 continue;
189             }
190             $ret[] = $cid[1];
191         }
192         
193         return $ret;
194     }
195     /**
196      * process replacements is run to generate a template - not the final content..
197      *
198      */
199     
200     function processRelacements($replace_links = true)
201     {   
202         $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
203         
204         libxml_use_internal_errors (true);
205         $doc = new DOMDocument('1.0', 'UTF-8');
206         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
207         
208         $xpath = new DOMXpath($doc);
209         
210         foreach ($xpath->query('//img[@src]') as $img) { // process images!
211             $href = $img->getAttribute('src');
212             $hash = explode('#', $href);
213             // we name all our cid's as attachment-*
214             // however the src url may be #image-*
215             
216             
217             if(!isset($hash[1])){
218                 continue;
219             }
220             $cid = explode('-', $hash[1]);
221             if(!empty($cid[1])){
222                 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
223             }
224         }
225         
226         $unsubscribe = $this->unsubscribe_url();
227         
228         foreach ($xpath->query('//a[@href]') as $a) { 
229             
230             $href = $a->getAttribute('href');
231             
232             if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
233                 $a->setAttribute('href', $unsubscribe);
234                 continue;
235             }
236             
237             if(!preg_match('/^http(.*)/', $href)){
238                 continue;
239             }
240             if (!$replace_links) {
241                 continue;
242             }
243             if (empty($cfg)) {
244                 continue;
245             }
246             // not available if server_baseurl not set... and crm module not used.
247             $link = DB_DataObject::factory('crm_mailing_list_link');
248             $link->setFrom(array(
249                 'url' => $href
250             ));
251             
252             if(!$link->find(true)){
253                 $link->insert();
254             }
255             
256             if(!$link->id){
257                 continue;
258             }
259             
260             $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
261             
262             $a->setAttribute('href', $l);
263             
264         }
265         
266         if(!empty($unsubscribe) && !empty($cfg)){
267             $element = $doc->createElement('img');
268             $element->setAttribute('mailembed', 'no');
269             $element->setAttribute('src', $cfg ['server_baseurl']  . '/Crm/Open/' . $this->id . '/{person.id}.html');
270             $element->setAttribute('width', '1');
271             $element->setAttribute('height', '1');
272
273             $html = $doc->getElementsByTagName('html');
274             if ($html->length) {
275                 $html->item(0)->appendChild($element);
276             }
277             
278             $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
279         }
280         
281         
282         $this->bodytext = $doc->saveHTML();
283         
284         libxml_use_internal_errors (false);
285         
286         $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
287         $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
288          
289         return;
290     }
291     
292     function unsubscribe_url()
293     {
294         $unsubscribe = false;
295         
296         $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
297         
298         if(!empty($cfg)){
299             $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
300         }
301         
302         return $unsubscribe;
303     }
304     
305     /**
306      * convert email with contents into a core mailer object. - ready to send..
307      * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
308      *    + subject
309      *    + rcpts || person   << if person is set - then it goes to them...
310      *    + rcpts_group (string) << name of group - normally to send admin emails.. (if set, then bcc_group is ignored.)
311      *    + replace_links
312      *    + template
313      *    + mailer_opts
314      *    + person << who it actually goes to..
315      *    
316      * @param bool $force - force re-creation of cached version of email.
317      *
318      * @returns Pman_Core_Mailer||PEAR_Error
319      */
320     
321     function toMailer($obj,$force=false)
322     {
323         require_once 'PEAR.php';
324         
325         $p = new PEAR();
326         $contents = (array)$obj;
327         
328         if(empty($this->id) && !empty($contents['template'])){
329             $this->get('name', $contents['template']);
330         }
331              
332         
333         if(empty($this->active)){
334             return $p->raiseError("template [{$contents['template']}] is Disabled");
335         }
336         
337         
338         if(empty($this->id)){
339             return $p->raiseError("template [{$contents['template']}] has not been set");
340         }
341         
342         // fill in BCC
343         
344         if (!empty($this->bcc_group_id) && $this->bcc_group_id > 0 && empty($contents['bcc']) && empty($contents['rcpts_group'])) {
345             $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
346             
347             $admin = $admin_grp ?  $admin_grp->members('email') : false;
348             
349             if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
350                 return $p->raiseError("template [{$contents['template']}] - bcc group is empty");
351             }
352             
353             $contents['bcc'] = $admin ;
354         }
355         if (!empty($contents['rcpts_group'])) {
356             
357             $admin = DB_DAtaObject::Factory('core_group')->lookupMembers($contents['rcpts_group'],'email');
358             
359             if (empty($admin)) {
360                 return $p->raiseError("Trying to send to {$contents['rcpts_group']} - group is empty");
361             }
362             $contents['rcpts'] = $admin;
363         }
364         if (empty($contents['rcpts']) && $this->to_group_id > 0) {
365             $members = $this->to_group()->members();
366             $contents['rcpts'] = array();
367             foreach($this->to_group()->members() as $m) {
368                 $contents['rcpts'][] = $m->email;
369             }
370             //var_dump($contents['rcpts']);
371             
372         }
373         //subject replacement
374         if(empty($contents['subject'])){
375            $contents['subject'] = $this->subject; 
376         }
377         
378         if (!empty($contents['subject_replace'])) {
379             
380             // do not use the mapping 
381             if (isset($contents['mapping'])) {
382                 foreach ($contents['mapping'] as $pattern => $replace) {
383                     $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
384                 }
385             }
386             
387             foreach ($contents as $k => $v) {
388                 if (is_string($v)) {
389                     $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
390                 }
391             }
392         }
393         
394         if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
395             $contents['rcpts'] = implode(',', $contents['rcpts']);
396         }     
397         
398         $ui = posix_getpwuid(posix_geteuid());
399         
400         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
401         
402         if($force || !$this->isGenerated($cachePath)){
403             $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
404         }
405          
406         require_once 'Pman/Core/Mailer.php';
407         
408         $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
409         
410         $cfg = array(
411             'template'=> $this->tableName() . '-' . $this->id,
412             'templateDir' => $templateDir,
413             'page' => $this,
414             'contents' => $contents,
415             'css_embed' => true, // we should always try and do this with emails...
416         );
417         
418         if (isset($contents['rcpts'])) {
419             $cfg['rcpts'] = $contents['rcpts'];
420         }
421         
422         if (isset($contents['attachments'])) {
423             $cfg['attachments'] = $contents['attachments'];
424         }
425         
426         if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
427             $cfg = array_merge($contents['mailer_opts'], $cfg);
428         }
429         
430         if(isset($contents['css_inline'])){
431             $cfg['css_inline'] = $contents['css_inline'];
432         }
433         
434         $r = new Pman_Core_Mailer($cfg);
435         
436         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
437         
438         if(file_exists($imageCache) && filesize($imageCache)){
439             $images = json_decode(file_get_contents($imageCache), true);
440             $r->images = $images;
441         }
442         
443         return $r;
444     }
445     function toMailerData($obj,$force=false)
446     {   
447         $r = $this->toMailer($obj, $force);
448         if (is_a($r, 'PEAR_Error')) {
449             return $r;
450         }
451         return $r->toData();
452     }
453     
454     /**
455      *
456      * DEPRICATED !!! - DO NOT USE THIS !!!
457      *
458      * use: toMailerData() -- to return the email data..
459      * or
460      * $mailer = $core_email->toMailer($obj, false);
461      * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
462
463      * toMailer($obj, false)->send()
464      *
465      * 
466      */
467     
468     function send($obj, $force = true, $send = true)
469     {   
470         if (!$send) {
471             return $this->toMailerData($obj,$force);
472         }
473         
474         $r = $this->toMailer($obj, $force);
475         
476         if (is_a($r, 'PEAR_Error')) {
477             return $r;
478         }
479         
480         return $r->send();
481     }
482     
483     function cachedMailWithOutImages($force = false, $replace_links = true)
484     {  
485         
486         $ui = posix_getpwuid(posix_geteuid());
487         
488         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
489           
490         if (!$force && $this->isGenerated($cachePath)) {
491             return;
492         }
493         
494         if (!file_exists(dirname($cachePath))) {
495             mkdir(dirname($cachePath), 0700, true);
496         }
497         
498         $random_hash = md5(date('r', time()));
499         
500         $this->cachedImages();
501         
502         $fh = fopen($cachePath, 'w');
503
504         fwrite($fh, implode("\n", array(
505             "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
506             "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
507             "Subject: {t.subject:h} ",
508             "X-Message-ID: {t.id} ",
509             "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
510             "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
511         ))."\n");
512         
513         
514 // note the extra space to finish the last line..
515         fwrite($fh, " " . "
516 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
517
518 --alt-{$random_hash}
519 Content-Type: text/plain; charset=utf-8; format=flowed
520 Content-Transfer-Encoding: 7bit
521
522 {$this->plaintext}
523
524 ");
525         fclose($fh);
526         
527         // cache body
528         
529         $this->processRelacements($replace_links);
530         
531         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
532         
533         if (!file_exists(dirname($cachePath))) {
534             mkdir(dirname($cachePath), 0700, true);
535         }
536         
537         if (empty($this->use_file)) {
538             file_put_contents($cachePath, $this->bodytext);
539             return;
540         }
541         // use-file -- uses the original template...
542         $mailtext = file_get_contents($this->use_file);        
543          
544         require_once 'Mail/mimeDecode.php';
545         require_once 'Mail/RFC822.php';
546         
547         $decoder = new Mail_mimeDecode($mailtext);
548         $parts = $decoder->getSendArray();
549         file_put_contents($cachePath,$parts[2]);
550          
551     }
552     
553     function cachedImages()
554     {
555         $ui = posix_getpwuid(posix_geteuid());
556         
557         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
558         
559         $ids = $this->attachmentIds();
560         
561          
562         $fh = fopen($imageCache, 'w');
563         
564         $i = DB_DataObject::factory('Images');
565         $i->onid = $this->id;
566         $i->ontable = $this->tableName();
567         $i->whereAddIn('id', $ids, 'int');
568         $i->find();
569         
570         $images = array();
571         
572         require_once 'File/MimeType.php';
573         $y = new File_MimeType();
574         
575         while ($i->fetch()){
576             if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
577                 continue;
578             }
579             
580             $images["attachment-{$i->id}"] = array(
581                 'file' => $i->getStoreName(),
582                 'mimetype' => $i->mimetype,
583                 'ext' => $y->toExt($i->mimetype),
584                 'contentid' => "attachment-$i->id"
585             );
586         }
587             
588         file_put_contents($imageCache, json_encode($images));
589         
590     }
591     
592     function isGenerated($cachePath)
593     {
594         if (!file_exists($cachePath) || !filesize($cachePath)) {
595             return false;
596         }
597         
598         if (!empty($this->use_file)) {
599             $ctime = filemtime($cachePath);
600             $mtime = filemtime($this->use_file);
601             if($ctime >= $mtime){
602                 return true;
603             }
604             return false;
605             
606         }
607         
608         
609         
610         $ctime = filemtime($cachePath);
611         $mtime = array();
612         $mtime[] = $this->updated_dt;
613         $i = DB_DataObject::factory('Images');
614         $i->onid = $this->id;
615         $i->ontable = $this->tableName();
616         $i->selectAdd();
617         $i->selectAdd('max(created) as created');
618         $i->find(true);
619         $mtime[] = $i->created;
620         if($ctime >= strtotime(max($mtime))){
621             return true;
622         }
623         
624         return false;
625     }
626     
627     function messageFrom()
628     {
629         if (empty($this->from_name)) {
630             return trim($this->from_email);
631         }
632         return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>')  ;
633     }
634     
635     function formatDate($dt, $format = 'd/M/Y')
636     {
637         return date($format, strtotime($dt));
638     } 
639     
640     
641      // fixme - this is now in core/udatedatabase..
642     
643     function initMail($mail_template_dir,  $name, $master='')
644     {
645         $cm = DB_DataObject::factory('core_email');
646         if ($cm->get('name', $name)) {
647             return;
648         }
649         
650 //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
651         
652         $opts = array();
653         
654         $opts['file'] = $mail_template_dir. $name .'.html';
655         if (!empty($master)) {
656             $opts['master'] = $mail_template_dir . $master .'.html';
657         }
658         //print_r($opts);
659         require_once 'Pman/Core/Import/Core_email.php';
660         $x = new Pman_Core_Import_Core_email();
661         $x->get('', $opts);
662          
663     }
664     
665     
666     function testData($person, $dt , $core_notify)
667     {
668          
669         // should return the formated email???
670         $pg = HTML_FlexyFramework::get()->page;
671         
672          
673         
674         
675         if(empty($this->test_class)){
676             $pg->jerr("[{$this->name}] does not has test class");
677         }
678         
679         require_once "{$this->test_class}.php";
680         
681         $cls = str_replace('/', '_', $this->test_class);
682         
683         $x = new $cls;
684         
685         $method = "test_{$this->name}";
686         
687         if(!method_exists($x, $method)){
688             $pg->jerr("{$method} does not exists in {$cls}");
689         }
690         
691         $content = $x->{$method}($this, $person);
692         $content['to'] = $person->getEmailFrom();
693
694         $content['bcc'] = array();
695         $data = $this->toMailerData($content);
696         return $data;
697         
698            
699     }
700     
701     function to_group()
702     {
703         $g = DB_DataObject::Factory('core_group');
704         $g->get($this->to_group_id);
705         return $g;
706     }
707 }