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