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