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         $this->retrieveAutoSave();
143        
144     }
145     
146     function onUpdate($old, $q,$roo)
147     {
148         $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
149     }
150
151
152     function attachmentIds()
153     {
154         libxml_use_internal_errors (true);
155         $doc = new DOMDocument('1.0', 'UTF-8');
156         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
157         
158         $xpath = new DOMXpath($doc);
159         $ret = array();
160         
161         foreach ($xpath->query('//img[@src]') as $img) { // process images!
162             $href = $img->getAttribute('src');
163             $cid = explode('#', $href);
164             if(!isset($cid[1])){
165                 continue;
166             }
167             $cid = explode('-', $cid[1]);
168             if (!isset($cid[1])||!is_numeric($cid[1])) {
169                 continue;
170             }
171             $ret[] = $cid[1];
172         }
173         
174         return $ret;
175     }
176     /**
177      * process replacements is run to generate a template - not the final content..
178      *
179      */
180     
181     function processRelacements($replace_links = true)
182     {   
183         $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
184         
185         libxml_use_internal_errors (true);
186         $doc = new DOMDocument('1.0', 'UTF-8');
187         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
188         
189         $xpath = new DOMXpath($doc);
190         
191         foreach ($xpath->query('//img[@src]') as $img) { // process images!
192             $href = $img->getAttribute('src');
193             $hash = explode('#', $href);
194             // we name all our cid's as attachment-*
195             // however the src url may be #image-*
196             
197             
198             if(!isset($hash[1])){
199                 continue;
200             }
201             $cid = explode('-', $hash[1]);
202             if(!empty($cid[1])){
203                 $img->setAttribute('src', 'cid:attachment-' . $cid[1]);
204             }
205         }
206         
207         $unsubscribe = $this->unsubscribe_url();
208         
209         foreach ($xpath->query('//a[@href]') as $a) { 
210             
211             $href = $a->getAttribute('href');
212             
213             if(preg_match('/#unsubscribe/', $href) && !empty($unsubscribe)){
214                 $a->setAttribute('href', $unsubscribe);
215                 continue;
216             }
217             
218             if(!preg_match('/^http(.*)/', $href)){
219                 continue;
220             }
221             if (!$replace_links) {
222                 continue;
223             }
224             $link = DB_DataObject::factory('crm_mailing_list_link');
225             $link->setFrom(array(
226                 'url' => $href
227             ));
228             
229             if(!$link->find(true)){
230                 $link->insert();
231             }
232             
233             if(!$link->id){
234                 continue;
235             }
236             
237             $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
238             
239             $a->setAttribute('href', $l);
240             
241         }
242         
243         if(!empty($unsubscribe)){
244             $element = $doc->createElement('img');
245             $element->setAttribute('mailembed', 'no');
246             $element->setAttribute('src', $cfg ['server_baseurl']  . '/Crm/Open/' . $this->id . '/{person.id}.html');
247             $element->setAttribute('width', '1');
248             $element->setAttribute('height', '1');
249
250             $html = $doc->getElementsByTagName('html');
251             if ($html->length) {
252                 $html->item(0)->appendChild($element);
253             }
254             
255             $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
256         }
257         
258         
259         $this->bodytext = $doc->saveHTML();
260         
261         libxml_use_internal_errors (false);
262         
263         $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
264         $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
265          
266         return;
267     }
268     
269     function unsubscribe_url()
270     {
271         $unsubscribe = false;
272         
273         $cfg = isset(HTML_FlexyFramework::get()->Pman_Crm) ? HTML_FlexyFramework::get()->Pman_Crm : false;
274         
275         if(!empty($cfg)){
276             $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
277         }
278         
279         return $unsubscribe;
280     }
281     
282     /**
283      * convert email with contents into a core mailer object. - ready to send..
284      * @param Object|Array $obj Object (or array) to send @see Pman_Core_Mailer
285      *    + subject
286      *    + rcpts || person   << if person is set - then it goes to them...
287      *    + replace_links
288      *    + template
289      *    + mailer_opts
290      *    + person << who it actually goes to..
291      *    
292      * @param bool $force - force re-creation of cached version of email.
293      *
294      * @returns Pman_Core_Mailer
295      */
296     
297     function toMailer($obj,$force=false)
298     {
299         
300         $contents = (array)$obj;
301
302         if(empty($this->id) && !empty($contents['template'])){
303             $this->get('name', $contents['template']);
304         }
305         
306         if(empty($this->id)){
307             $p = new PEAR();
308             return $p->raiseError("template [{$contents['template']}] has not been set");
309         }
310         
311         if(empty($contents['subject'])){
312            $contents['subject'] = $this->subject; 
313         }
314         
315         if(!empty($contents['rcpts']) && is_array($contents['rcpts'])){
316             $contents['rcpts'] = implode(',', $contents['rcpts']);
317         }
318         
319         $ui = posix_getpwuid(posix_geteuid());
320         
321         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
322         
323         if($force || !$this->isGenerated($cachePath)){
324             $this->cachedMailWithOutImages($force, empty($contents['replace_links']) ? false : $contents['replace_links']);
325         }
326          
327         require_once 'Pman/Core/Mailer.php';
328         
329         $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
330         //print_r($this);
331         
332         
333         $cfg = array(
334             'template'=> $this->tableName() . '-' . $this->id,
335             'templateDir' => $templateDir,
336             'page' => $this,
337             'contents' => $contents,
338             'css_embed' => true, // we should always try and do this with emails...
339         );
340         if (isset($contents['rcpts'])) {
341             $cfg['rcpts'] = $contents['rcpts'];
342         }
343         if (isset($contents['mailer_opts']) && is_array($contents['mailer_opts'])) {
344             $cfg = array_merge($contents['mailer_opts'], $cfg);
345         }
346         
347         
348         $r = new Pman_Core_Mailer($cfg);
349         
350         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
351         
352         if(file_exists($imageCache) && filesize($imageCache)){
353             $images = json_decode(file_get_contents($imageCache), true);
354             $r->images = $images;
355         }
356         
357         return $r;
358     }
359     function toMailerData($obj,$force=false)
360     {   
361         $r = $this->toMailer($obj, $force);
362         if (is_a($r, 'PEAR_Error')) {
363             return $r;
364         }
365         return $r->toData();
366     }
367     
368     /**
369      *
370      * DEPRICATED !!! - DO NOT USE THIS !!!
371      */
372     
373     function send($obj, $force = true, $send = true)
374     {   
375         if (!$send) {
376             return $this->toMailerData($obj,$force);
377         }
378         $r = $this->toMailer($obj, $force);
379         if (is_a($r, 'PEAR_Error')) {
380             return $r;
381         }
382          
383         
384         return $r->send();
385     }
386     
387     function cachedMailWithOutImages($force = false, $replace_links = true)
388     {  
389         
390         $ui = posix_getpwuid(posix_geteuid());
391         
392         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
393           
394         if (!$force && $this->isGenerated($cachePath)) {
395             return;
396         }
397         
398         if (!file_exists(dirname($cachePath))) {
399             mkdir(dirname($cachePath), 0700, true);
400         }
401         
402         $random_hash = md5(date('r', time()));
403         
404         $this->cachedImages();
405         
406         $fh = fopen($cachePath, 'w');
407
408         fwrite($fh, implode("\n", array(
409             "From: {if:t.messageFrom}{t.messageFrom:h}{else:}{t.messageFrom():h}{end:}",
410             "To: {if:t.person}{t.person.getEmailFrom():h}{else:}{rcpts:h}{end:}",
411             "Subject: {t.subject} ",
412             "X-Message-ID: {t.id} ",
413             "{if:t.replyTo}Reply-To: {t.replyTo:h}{end:}",
414             "{if:t.mailgunVariables}X-Mailgun-Variables: {t.mailgunVariables:h}{end:}"
415         ))."\n");
416         
417         
418 // note the extra space to finish the last line..
419         fwrite($fh, " " . "
420 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
421
422 --alt-{$random_hash}
423 Content-Type: text/plain; charset=utf-8; format=flowed
424 Content-Transfer-Encoding: 7bit
425
426 {$this->plaintext}
427
428 ");
429         fclose($fh);
430         
431         // cache body
432         
433         $this->processRelacements($replace_links);
434         
435         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
436         
437         if (!file_exists(dirname($cachePath))) {
438             mkdir(dirname($cachePath), 0700, true);
439         }
440         
441         file_put_contents($cachePath, $this->bodytext);
442         
443     }
444     
445     function cachedImages()
446     {
447         $ui = posix_getpwuid(posix_geteuid());
448         
449         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
450         
451         $ids = $this->attachmentIds();
452         
453          
454         $fh = fopen($imageCache, 'w');
455         
456         $i = DB_DataObject::factory('Images');
457         $i->onid = $this->id;
458         $i->ontable = $this->tableName();
459         $i->whereAddIn('id', $ids, 'int');
460         $i->find();
461         
462         $images = array();
463         
464         require_once 'File/MimeType.php';
465         $y = new File_MimeType();
466         
467         while ($i->fetch()){
468             if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
469                 continue;
470             }
471             
472             $images["attachment-{$i->id}"] = array(
473                 'file' => $i->getStoreName(),
474                 'mimetype' => $i->mimetype,
475                 'ext' => $y->toExt($i->mimetype),
476                 'contentid' => "attachment-$i->id"
477             );
478         }
479             
480         file_put_contents($imageCache, json_encode($images));
481         
482     }
483     
484     function isGenerated($cachePath)
485     {
486         if (!file_exists($cachePath) || !filesize($cachePath)) {
487             return false;
488         }
489         
490         
491         $ctime = filemtime($cachePath);
492         $mtime = array();
493         $mtime[] = $this->updated_dt;
494         $i = DB_DataObject::factory('Images');
495         $i->onid = $this->id;
496         $i->ontable = $this->tableName();
497         $i->selectAdd();
498         $i->selectAdd('max(created) as created');
499         $i->find(true);
500         $mtime[] = $i->created;
501         if($ctime >= strtotime(max($mtime))){
502             return true;
503         }
504         
505         return false;
506     }
507     
508     function messageFrom()
509     {
510         if (empty($this->from_name)) {
511             return trim($this->from_email);
512         }
513         return trim('"' . addslashes($this->from_name) . '" <' . $this->from_email. '>')  ;
514     }
515     
516     function formatDate($dt, $format = 'd/M/Y')
517     {
518         return date($format, strtotime($dt));
519     } 
520     
521     
522     
523 }