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