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