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