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