remove debug
[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     /* the code above is auto generated do not remove the tag below */
28     ###END_AUTOCODE
29     
30     function applyFilters($q, $au, $roo)
31     {
32         $tn = $this->tableName();
33         
34         if(!empty($q['search']['nameortitle'])){
35             $this->whereAdd("
36                 $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
37                 OR
38                 $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
39             ");
40         }
41         $cgm = DB_DataObject::Factory('core_group_member')->tableName();;
42       
43         $this->selectAdd("
44             (
45                 SELECT 
46                     count(id) 
47                 FROM 
48                     {$cgm}
49                 WHERE 
50                     to_group_id = {$cgm}.group_id
51             )  AS group_member_count,
52             
53             (
54                 SELECT 
55                     count(id) 
56                 FROM 
57                     {$cgm}
58                 WHERE 
59                     bcc_group_id = {$cgm}.group_id
60             )  AS bcc_group_member_count
61         ");
62         
63         if (!empty($_REQUEST['_hide_system_emails'])) {
64             $this->whereAddIn("!{$this->tableName()}.name", array('EVENT_ERRORS_REPORT'), 'string');
65         }
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() && empty($request['_ignore_group_count'])) {
94                 $roo->jerr('Failed to create email template - No member found in recieptent group',array('errcode'=> 100));
95             }
96         }
97     }
98     
99     function makeCopy($roo)
100     {
101         $c = DB_DataObject::Factory($this->tableName());
102         $c->setFrom($this);
103         $c->name = "COPY of " . $this->name;
104         $c->updated_dt = $this->sqlValue('NOW()');
105         
106         $id = $c->insert();
107         $c = DB_DataObject::Factory($this->tableName());
108         $c->get($id);
109         
110         
111         // copy images.
112         
113         $i = DB_DataObject::factory('Images');
114         $i->onid = $this->id;
115         $i->ontable = $this->tableName();
116         $i->find();
117         while ($i->fetch()){
118             
119             $new_image = DB_DataObject::factory('Images');
120             $new_image->onid = $c->id;
121             $new_image->ontable = $this->tableName();
122             $new_image->createFrom($i->getStoreName(), $i->filename);
123             
124             $map[$i->id] = $new_image->id;
125         }
126         
127         
128         libxml_use_internal_errors (true);
129         $doc = new DOMDocument('1.0', 'UTF-8');
130         $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
131         $doc->formatOutput = true;
132
133        //echo '<PRE>'; print_R($doc);
134         
135         
136         $xpath = new DOMXpath($doc);
137         foreach ($xpath->query('//img[@src]') as $img) {
138             $href = $img->getAttribute('src');
139             //var_dump($href);
140             $matches = array();
141             if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
142                  
143                 $oid = $matches[1];
144                 
145                 if (!isset($map[$oid])) {
146                     //echo "skip no new id for $oid";
147                     continue;
148                 }
149                 $nid = $map[$oid];
150                 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
151                 
152                 $img->setAttribute('src',  str_replace($matches[0], $nstr, $href ));
153                     
154                  
155             }
156         }
157         $cc = clone($c);
158         $c->bodytext = $doc->saveHTML();
159         $c->update($cc);
160         libxml_use_internal_errors (false);
161         
162         
163         $roo->jok("duplicated");
164     }
165     
166     function onInsert($q,$roo)
167     {   
168         $i = DB_DataObject::factory('Images');
169         $i->onid = 0;
170         $i->ontable = $this->tableName();
171         $i->find();
172         while ($i->fetch()){
173             $ii = clone ($i);
174             $i->onid = $this->id;
175             $i->update($ii);
176         }
177         
178         $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
179 //        $this->cachedMailWithOutImages(true, false);
180        
181     }
182     
183     function onUpdate($old, $q,$roo)
184     {
185         $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
186     }
187
188
189     function attachmentIds()
190     {
191         libxml_use_internal_errors (true);
192         $doc = new DOMDocument('1.0', 'UTF-8');
193         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
194         
195         $xpath = new DOMXpath($doc);
196         $ret = array();
197         
198         foreach ($xpath->query('//img[@src]') as $img) { // process images!
199             $href = $img->getAttribute('src');
200             $cid = explode('#', $href);
201             if(!isset($cid[1])){
202                 continue;
203             }
204             $cid = explode('-', $cid[1]);
205             if (!isset($cid[1])||!is_numeric($cid[1])) {
206                 continue;
207             }
208             $ret[] = $cid[1];
209         }
210         
211         return $ret;
212     }
213     /**
214      * process replacements is run to generate a template - not the final content..
215      *
216      */
217     
218     function processRelacements($replace_links = true)
219     {   
220         $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
221         
222         libxml_use_internal_errors (true);
223         $doc = new DOMDocument('1.0', 'UTF-8');
224         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
225         
226         $xpath = new DOMXpath($doc);
227         
228         foreach ($xpath->query('//img[@src]') as $img) { // process images!
229             $href = $img->getAttribute('src');
230             $hash = explode('#', $href);
231             // we name all our cid's as attachment-*
232             // however the src url may be #image-*
233             
234             
235             if(!isset($hash[1])){
236                 continue;
237             }
238             $cid = explode('-', $hash[1]);
239             if(!empty($cid[1])){
240                 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
241             }
242         }
243         
244         $unsubscribe = $this->unsubscribe_url();
245         
246         foreach ($xpath->query('//a[@href]') as $a) { 
247             
248             $href = $a->getAttribute('href');
249             
250             if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
251                 $a->setAttribute('href', $unsubscribe);
252                 continue;
253             }
254             
255             if(!preg_match('/^http(.*)/', $href)){
256                 continue;
257             }
258             if (!$replace_links) {
259                 continue;
260             }
261             if (empty($cfg)) {
262                 continue;
263             }
264             // not available if server_baseurl not set... and crm module not used.
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) && !empty($cfg)){
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) && $this->bcc_group_id > 0 && empty($contents['bcc']) && empty($contents['rcpts_group'])) {
363             $admin_grp = DB_DAtaObject::Factory('core_group')->load($this->bcc_group_id);
364             
365             $admin = $admin_grp ?  $admin_grp->members('email') : false;
366             
367             if (empty($admin) && $admin_grp->name != 'Empty Group') { // allow 'empty group mname'
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         if (empty($contents['rcpts']) && $this->to_group_id > 0) {
383             $members = $this->to_group()->members();
384             $contents['rcpts'] = array();
385             foreach($this->to_group()->members() as $m) {
386                 $contents['rcpts'][] = $m->email;
387             }
388             //var_dump($contents['rcpts']);
389             
390         }
391         //subject replacement
392         if(empty($contents['subject'])){
393            $contents['subject'] = $this->subject; 
394         }
395         
396         if (!empty($contents['subject_replace'])) {
397             
398             // do not use the mapping 
399             if (isset($contents['mapping'])) {
400                 foreach ($contents['mapping'] as $pattern => $replace) {
401                     $contents['subject'] = preg_replace($pattern,$replace,$contents['subject']);
402                 }
403             }
404             
405             foreach ($contents as $k => $v) {
406                 if (is_string($v)) {
407                     $contents['subject'] = str_replace('{'. $k . '}', $v, $contents['subject']);
408                 }
409             }
410         }
411         
412         if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
413             $contents['rcpts'] = implode(',', $contents['rcpts']);
414         }     
415         
416         $ui = posix_getpwuid(posix_geteuid());
417         
418         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
419         
420         if($force || !$this->isGenerated($cachePath)){
421             $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
422         }
423          
424         require_once 'Pman/Core/Mailer.php';
425         
426         $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
427         
428         $cfg = array(
429             'template'=> $this->tableName() . '-' . $this->id,
430             'templateDir' => $templateDir,
431             'page' => $this,
432             'contents' => $contents,
433             'css_embed' => true, // we should always try and do this with emails...
434         );
435         
436         if (isset($contents['rcpts'])) {
437             $cfg['rcpts'] = $contents['rcpts'];
438         }
439         
440         if (isset($contents['attachments'])) {
441             $cfg['attachments'] = $contents['attachments'];
442         }
443         
444         if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
445             $cfg = array_merge($contents['mailer_opts'], $cfg);
446         }
447         
448         if(isset($contents['css_inline'])){
449             $cfg['css_inline'] = $contents['css_inline'];
450         }
451         
452         $r = new Pman_Core_Mailer($cfg);
453         
454         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
455         
456         if(file_exists($imageCache) && filesize($imageCache)){
457             $images = json_decode(file_get_contents($imageCache), true);
458             $r->images = $images;
459         }
460         
461         return $r;
462     }
463     function toMailerData($obj,$force=false)
464     {   
465         $r = $this->toMailer($obj, $force);
466         if (is_a($r, 'PEAR_Error')) {
467             return $r;
468         }
469         return $r->toData();
470     }
471     
472     /**
473      *
474      * DEPRICATED !!! - DO NOT USE THIS !!!
475      *
476      * use: toMailerData() -- to return the email data..
477      * or
478      * $mailer = $core_email->toMailer($obj, false);
479      * $sent = is_a($mailer,'PEAR_Error') ? false : $mailer->send();
480
481      * toMailer($obj, false)->send()
482      *
483      * 
484      */
485     
486     function send($obj, $force = true, $send = true)
487     {   
488         if (!$send) {
489             return $this->toMailerData($obj,$force);
490         }
491         
492         $r = $this->toMailer($obj, $force);
493         
494         if (is_a($r, 'PEAR_Error')) {
495             return $r;
496         }
497         
498         return $r->send();
499     }
500     
501     function cachedMailWithOutImages($force = false, $replace_links = true)
502     {  
503         
504         $ui = posix_getpwuid(posix_geteuid());
505         
506         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
507           
508         if (!$force && $this->isGenerated($cachePath)) {
509             return;
510         }
511         
512         if (!file_exists(dirname($cachePath))) {
513             mkdir(dirname($cachePath), 0700, true);
514         }
515         
516         $random_hash = md5(date('r', time()));
517         
518         $this->cachedImages();
519         
520         $fh = fopen($cachePath, 'w');
521
522         fwrite($fh, implode("\n", array(
523             "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
524             "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
525             "Subject: {t.subject:h} ",
526             "X-Message-ID: {t.id} ",
527             "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
528             "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
529         ))."\n");
530         
531         
532 // note the extra space to finish the last line..
533         fwrite($fh, " " . "
534 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
535
536 --alt-{$random_hash}
537 Content-Type: text/plain; charset=utf-8; format=flowed
538 Content-Transfer-Encoding: 7bit
539
540 {$this->plaintext}
541
542 ");
543         fclose($fh);
544         
545         // cache body
546         
547         $this->processRelacements($replace_links);
548         
549         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
550         
551         if (!file_exists(dirname($cachePath))) {
552             mkdir(dirname($cachePath), 0700, true);
553         }
554         
555         if (empty($this->use_file)) {
556             file_put_contents($cachePath, $this->bodytext);
557             return;
558         }
559         // use-file -- uses the original template...
560         $mailtext = file_get_contents($this->use_file);        
561          
562         require_once 'Mail/mimeDecode.php';
563         require_once 'Mail/RFC822.php';
564         
565         $decoder = new Mail_mimeDecode($mailtext);
566         $parts = $decoder->getSendArray();
567         file_put_contents($cachePath,$parts[2]);
568          
569     }
570     
571     function cachedImages()
572     {
573         $ui = posix_getpwuid(posix_geteuid());
574         
575         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
576         
577         $ids = $this->attachmentIds();
578         
579          
580         $fh = fopen($imageCache, 'w');
581         
582         $i = DB_DataObject::factory('Images');
583         $i->onid = $this->id;
584         $i->ontable = $this->tableName();
585         $i->whereAddIn('id', $ids, 'int');
586         $i->find();
587         
588         $images = array();
589         
590         require_once 'File/MimeType.php';
591         $y = new File_MimeType();
592         
593         while ($i->fetch()){
594             if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
595                 continue;
596             }
597             
598             $images["attachment-{$i->id}"] = array(
599                 'file' => $i->getStoreName(),
600                 'mimetype' => $i->mimetype,
601                 'ext' => $y->toExt($i->mimetype),
602                 'contentid' => "attachment-$i->id"
603             );
604         }
605             
606         file_put_contents($imageCache, json_encode($images));
607         
608     }
609     
610     function isGenerated($cachePath)
611     {
612         if (!file_exists($cachePath) || !filesize($cachePath)) {
613             return false;
614         }
615         
616         if (!empty($this->use_file)) {
617             $ctime = filemtime($cachePath);
618             $mtime = filemtime($this->use_file);
619             if($ctime >= $mtime){
620                 return true;
621             }
622             return false;
623             
624         }
625         
626         
627         
628         $ctime = filemtime($cachePath);
629         $mtime = array();
630         $mtime[] = $this->updated_dt;
631         $i = DB_DataObject::factory('Images');
632         $i->onid = $this->id;
633         $i->ontable = $this->tableName();
634         $i->selectAdd();
635         $i->selectAdd('max(created) as created');
636         $i->find(true);
637         $mtime[] = $i->created;
638         if($ctime >= strtotime(max($mtime))){
639             return true;
640         }
641         
642         return false;
643     }
644     
645     function messageFrom()
646     {
647         if (empty($this->from_name)) {
648             return trim($this->from_email);
649         }
650         return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>')  ;
651     }
652     
653     function formatDate($dt, $format = 'd/M/Y')
654     {
655         return date($format, strtotime($dt));
656     } 
657     
658     
659      // fixme - this is now in core/udatedatabase..
660     
661     function initMail($mail_template_dir,  $name, $master='')
662     {
663         $cm = DB_DataObject::factory('core_email');
664         if ($cm->get('name', $name)) {
665             return;
666         }
667         
668 //        $basedir = $this->bootLoader->rootDir . $mail_template_dir;
669         
670         $opts = array();
671         
672         $opts['file'] = $mail_template_dir. $name .'.html';
673         if (!empty($master)) {
674             $opts['master'] = $mail_template_dir . $master .'.html';
675         }
676         //print_r($opts);
677         require_once 'Pman/Core/Import/Core_email.php';
678         $x = new Pman_Core_Import_Core_email();
679         $x->get('', $opts);
680          
681     }
682     
683     
684     function testData($person, $dt , $core_notify)
685     {
686          
687         // should return the formated email???
688         $pg = HTML_FlexyFramework::get()->page;
689         
690          
691         
692         
693         if(empty($this->test_class)){
694             $pg->jerr("[{$this->name}] does not has test class");
695         }
696         
697         require_once "{$this->test_class}.php";
698         
699         $cls = str_replace('/', '_', $this->test_class);
700         
701         $x = new $cls;
702         
703         $method = "test_{$this->name}";
704         
705         if(!method_exists($x, $method)){
706             $pg->jerr("{$method} does not exists in {$cls}");
707         }
708         
709         $content = $x->{$method}($this, $person);
710         $content['to'] = $person->getEmailFrom();
711
712         $content['bcc'] = array();
713         $data = $this->toMailerData($content);
714         return $data;
715         
716            
717     }
718     
719     function to_group()
720     {
721         $g = DB_DataObject::Factory('core_group');
722         $g->get($this->to_group_id);
723         return $g;
724     }
725 }