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