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