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