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