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