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