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