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