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