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