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