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             $cid = explode('#', $href);
192             if(isset($cid[1])){
193                 $img->setAttribute('src', 'cid:' . $cid[1]);
194             }
195         }
196         
197         $unsubscribe = false;
198         
199         if(!empty($cfg)){
200             $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
201         }
202        
203         foreach ($xpath->query('//a[@href]') as $a) { 
204             
205             $href = $a->getAttribute('href');
206             
207             if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
208                 $a->setAttribute('href', $unsubscribe);
209                 continue;
210             }
211             
212             if(!preg_match('/^http(.*)/', $href)){
213                 continue;
214             }
215             if (!$replace_links) {
216                 continue;
217             }
218             $link = DB_DataObject::factory('crm_mailing_list_link');
219             $link->setFrom(array(
220                 'url' => $href
221             ));
222             
223             if(!$link->find(true)){
224                 $link->insert();
225             }
226             
227             if(!$link->id){
228                 continue;
229             }
230             
231             $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
232             
233             $a->setAttribute('href', $l);
234             
235         }
236         
237         if(!empty($unsubscribe)){
238             $element = $doc->createElement('img');
239         
240             $element->setAttribute('src', $cfg ['server_baseurl']  . '/Crm/Open/' . $this->id . '/{person.id}.html');
241             $element->setAttribute('width', '1');
242             $element->setAttribute('height', '1');
243
244             $html = $doc->getElementsByTagName('html');
245             if ($html->length) {
246                 $html->item(0)->appendChild($element);
247             }
248             
249             $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
250         }
251         
252         
253         $this->bodytext = $doc->saveHTML();
254         
255         libxml_use_internal_errors (false);
256         
257         $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
258         $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
259          
260         return;
261     }
262     
263     function unsubscribe_url()
264     {
265         $unsubscribe = false;
266         
267         $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
268         
269         if(!empty($cfg)){
270             $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
271         }
272         
273         return $unsubscribe;
274     }
275     /**
276      *
277      * Usage:
278      * $this->rcpts = array('sales@roojs.com');
279      * // or 
280      * $this->rcpts = "Tester <sales@roojs.com>";
281      *
282      * 
283      * // then send it..
284      * $x = DB_DataObject::factory('core_enum');
285      * $x->get('name', 'NAME OF TEMPLATE');
286      * $x->send(array(
287      *      'rcpts' => "Tester <sales@roojs.com>",
288      *      'page' => $this
289      *       'link' => 'http://......'
290        );
291      * // on the template use {link:h} to render the link
292      *
293      *
294      */
295     function send($obj, $force = true, $send = true)
296     {   
297         $contents = (array)$obj;
298
299         if(empty($this->id)){
300             $this->get('name', $contents['template']);
301         }
302         
303         if(empty($this->id)){
304             $p = new PEAR();
305             return $p->raiseError("template [{$contents['template']}] has not been set");
306         }
307         if(empty($contents['subject'])){
308            $contents['subject'] = $this->subject; 
309         }
310         
311         if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
312             $contents['rcpts'] = implode(',', $contents['rcpts']);
313         }
314         
315         $ui = posix_getpwuid(posix_geteuid());
316         
317         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
318         
319         if($force || !$this->isGenerated($cachePath)){
320             $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
321         }
322          
323         require_once 'Pman/Core/Mailer.php';
324         
325         $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
326         //print_r($this);
327         
328         
329         $cfg = array(
330             'template'=> $this->tableName() . '-' . $this->id,
331             'templateDir' => $templateDir,
332             'page' => $this,
333             'contents' => $contents
334         );
335         if (isset($contents['rcpts'])) {
336             $cfg['rcpts'] = $contents['rcpts'];
337         }
338         
339         $r = new Pman_Core_Mailer($cfg);
340         
341         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
342         
343         if(file_exists($imageCache) && filesize($imageCache)){
344             $images = json_decode(file_get_contents($imageCache), true);
345             $r->images = $images;
346         }
347         
348         $ret = $r->toData();
349         
350         if(!$send){
351             return $ret;
352         }
353         
354         return $r->send();
355     }
356     
357     function cachedMailWithOutImages($force = false, $replace_links = true)
358     {  
359         
360         $ui = posix_getpwuid(posix_geteuid());
361         
362         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
363           
364         if (!$force && $this->isGenerated($cachePath)) {
365             return;
366         }
367         
368         if (!file_exists(dirname($cachePath))) {
369             mkdir(dirname($cachePath), 0700, true);
370         }
371         
372         $random_hash = md5(date('r', time()));
373         
374         $this->cachedImages();
375         
376         $fh = fopen($cachePath, 'w');
377
378         fwrite($fh, implode("\n", array(
379             "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
380             "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
381             "Subject: {t.subject} ",
382             "X-Message-ID: {t.id} ",
383             "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
384             "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
385         ))."\n");
386         
387         
388 // note the extra space to finish the last line..
389         fwrite($fh, " " . "
390 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
391
392 --alt-{$random_hash}
393 Content-Type: text/plain; charset=utf-8; format=flowed
394 Content-Transfer-Encoding: 7bit
395
396 {$this->plaintext}
397
398 ");
399         fclose($fh);
400         
401         // cache body
402         
403         $this->processRelacements($replace_links);
404         
405         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
406         
407         if (!file_exists(dirname($cachePath))) {
408             mkdir(dirname($cachePath), 0700, true);
409         }
410         
411         file_put_contents($cachePath, $this->bodytext);
412         
413     }
414     
415     function cachedImages()
416     {
417         $ui = posix_getpwuid(posix_geteuid());
418         
419         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
420         
421         $ids = $this->attachmentIds();
422         
423          
424         $fh = fopen($imageCache, 'w');
425         
426         $i = DB_DataObject::factory('Images');
427         $i->onid = $this->id;
428         $i->ontable = $this->tableName();
429         $i->whereAddIn('id', $ids, 'int');
430         $i->find();
431         
432         $images = array();
433         
434         require_once 'File/MimeType.php';
435         $y = new File_MimeType();
436         
437         while ($i->fetch()){
438             if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
439                 continue;
440             }
441             
442             $images["attachment-$i->id"] = array(
443                 'file' => $i->getStoreName(),
444                 'mimetype' => $i->mimetype,
445                 'ext' => $y->toExt($i->mimetype),
446                 'contentid' => "attachment-$i->id"
447             );
448         }
449             
450         file_put_contents($imageCache, json_encode($images));
451         
452     }
453     
454     function isGenerated($cachePath)
455     {
456         if (!file_exists($cachePath) || !filesize($cachePath)) {
457             return false;
458         }
459         
460         
461         $ctime = filemtime($cachePath);
462         $mtime = array();
463         $mtime[] = $this->updated_dt;
464         $i = DB_DataObject::factory('Images');
465         $i->onid = $this->id;
466         $i->ontable = $this->tableName();
467         $i->selectAdd();
468         $i->selectAdd('max(created) as created');
469         $i->find(true);
470         $mtime[] = $i->created;
471         if($ctime >= strtotime(max($mtime))){
472             return true;
473         }
474         
475         return false;
476     }
477     
478     function messageFrom()
479     {
480         if (empty($this->from_name)) {
481             return trim($this->from_email);
482         }
483         return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>')  ;
484     }
485     
486     function formatDate($dt, $format = 'd/M/Y')
487     {
488         return date($format, strtotime($dt));
489     } 
490     
491     
492     
493 }