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