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