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