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