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, false);
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         libxml_use_internal_errors (true);
182         $doc = new DOMDocument('1.0', 'UTF-8');
183         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
184         
185         $xpath = new DOMXpath($doc);
186         
187         foreach ($xpath->query('//img[@src]') as $img) { // process images!
188             $href = $img->getAttribute('src');
189             $cid = explode('#', $href);
190             if(isset($cid[1])){
191                 $img->setAttribute('src', 'cid:' . $cid[1]);
192             }
193         }
194         
195         $this->bodytext = $doc->saveHTML();
196         
197         libxml_use_internal_errors (false);
198         
199         $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
200         $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
201         
202         return;
203     }
204     
205     function send($obj)
206     {    
207         $contents = (array)$obj;
208         
209         $this->cachedMailWithOutImages(true, false);
210         
211         $contents['subject'] = $this->subject;
212         
213         $ui = posix_getpwuid(posix_geteuid());
214         
215         require_once 'Pman/Core/Mailer.php';
216         
217         $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
218         $r = new Pman_Core_Mailer(array(
219             'template'=> $this->tableName() . '-' . $this->id,
220             'templateDir' => $templateDir,
221             'page' => $this,
222             'contents' => $contents
223         ));
224         
225         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
226         
227         if(file_exists($imageCache) && filesize($imageCache)){
228             $images = json_decode(file_get_contents($imageCache));
229             array_merge($r->images, $images);
230         }
231         
232         $ret = $r->toData();
233         
234         
235         
236         $ret['body'] = str_replace('%Images%', $images, $ret['body']);
237         
238         return $r->send($ret);
239     }
240     
241     function cachedMailWithOutImages($force = false, $replace_links = true)
242     {  
243         $random_hash = md5(date('r', time()));
244         
245         $this->cachedImages($random_hash);
246         
247         $ui = posix_getpwuid(posix_geteuid());
248         
249         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
250           
251         if (!$force && $this->isGenerated($cachePath)) {
252             return;
253         }
254         
255         if (!file_exists(dirname($cachePath))) {
256             mkdir(dirname($cachePath), 0700, true);
257         }
258         
259         $this->processRelacements($replace_links);
260         
261         $fh = fopen($cachePath, 'w');
262
263         fwrite($fh, implode("\n", array(
264             "From: {t.messageFrom():h} ",
265             "To: {t.person.getEmailFrom():h} ",
266             "Subject: {t.subject} ",
267             "X-Message-ID: {t.id} "
268         ))."\n");
269         
270         
271 // note the extra space to finish the last line..
272         fwrite($fh, " " . "
273 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
274
275 --alt-{$random_hash}
276 Content-Type: text/plain; charset=utf-8; format=flowed
277 Content-Transfer-Encoding: 7bit
278
279 {$this->plaintext}
280
281 ");
282         fclose($fh);
283         
284         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.body.html';
285           
286         
287         if (!file_exists(dirname($cachePath))) {
288             mkdir(dirname($cachePath), 0700, true);
289         }
290         
291         file_put_contents($cachePath, $this->bodytext);
292         
293     }
294     
295     function cachedImages($random_hash)
296     {
297         $ui = posix_getpwuid(posix_geteuid());
298         
299         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
300         
301         $ids = $this->attachmentIds();
302         
303          
304         $fh = fopen($imageCache, 'w');
305         
306         $i = DB_DataObject::factory('Images');
307         $i->onid = $this->id;
308         $i->ontable = $this->tableName();
309         $i->whereAddIn('id', $ids, 'int');
310         $i->find();
311         
312         $images = array();
313         
314         require_once 'File/MimeType.php';
315         $y = new File_MimeType();
316         
317         while ($i->fetch()){
318             if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
319                 continue;
320             }
321 //            $out = chunk_split(base64_encode(file_get_contents($i->getStoreName())));
322 //            if (empty($out)) {
323 //                continue;
324 //            }
325             
326 //            $imgfn = urlencode(preg_replace('/#.*$/i', '' , $i->filename));
327             
328             
329             $images["attachment-$i->id"] = array(
330                 'file' => $i->getStoreName(),
331                 'mimetype' => $i->mimetype,
332                 'ext' => $y->toExt($i->mimetype),
333                 'contentid' => "attachment-$i->id"
334             );
335 //            
336 //            
337 //            fwrite($fh, "--rel-{$random_hash}
338 //Content-Type: {$i->mimetype}; name={$imgfn}
339 //Content-Transfer-Encoding: base64
340 //Content-ID: <attachment-{$i->id}>
341 //Content-Disposition: inline; filename={$imgfn}
342 //
343 //" . $out  . "");
344
345             }
346             
347             file_put_contents($imageCache, json_encode($images));
348         
349     }
350     
351     function isGenerated($cachePath)
352     {
353         if (!file_exists($cachePath) || !filesize($cachePath)) {
354             return false;
355         }
356         
357         
358         $ctime = filemtime($cachePath);
359         $mtime = array();
360         $mtime[] = $this->updated_dt;
361         $i = DB_DataObject::factory('Images');
362         $i->onid = $this->id;
363         $i->ontable = $this->tableName();
364         $i->selectAdd();
365         $i->selectAdd('max(created) as created');
366         $i->find(true);
367         $mtime[] = $i->created;
368         if($ctime >= strtotime(max($mtime))){
369             return true;
370         }
371         
372         return false;
373     }
374     
375     function messageFrom()
376     {
377         return '"' . addslashes($this->from_name) . '" <' . $this->from_email. '>'  ;
378     }
379     
380     function formatDate($dt, $format = 'd/M/Y')
381     {
382         return date($format, strtotime($dt));
383     } 
384     
385     
386     
387 }