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