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