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