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         $c = DB_DataObject::factory($this->tableName());
30         $c->get(5);
31         
32         $c->send(array());
33         
34         exit;
35         
36         $tn = $this->tableName();
37         
38         if(!empty($q['search']['nameortitle'])){
39             $this->whereAdd("
40                 $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
41                 OR
42                 $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
43             ");
44         }
45     }
46     
47     function beforeDelete($dependants_array, $roo)
48     {   
49         $i = DB_DataObject::factory('Images');
50         $i->onid = $this->id;
51         $i->ontable = $this->tableName();
52         $i->find();
53         while ($i->fetch()){
54             $i->beforeDelete();
55             $i->delete();
56         }
57     }
58     
59     function beforeUpdate($old, $request,$roo)
60     {   
61         if (!empty($request['_make_copy'])) {
62             $this->makeCopy($roo);
63             
64         }
65     }
66     
67     function makeCopy($roo)
68     {
69         $c = DB_DataObject::Factory($this->tableName());
70         $c->setFrom($this);
71         $c->name = "COPY of " . $this->name;
72         $c->updated_dt = $this->sqlValue('NOW()');
73         
74         $id = $c->insert();
75         $c = DB_DataObject::Factory($this->tableName());
76         $c->get($id);
77         
78         
79         // copy images.
80         
81         $i = DB_DataObject::factory('Images');
82         $i->onid = $this->id;
83         $i->ontable = $this->tableName();
84         $i->find();
85         while ($i->fetch()){
86             
87             $new_image = DB_DataObject::factory('Images');
88             $new_image->onid = $c->id;
89             $new_image->ontable = $this->tableName();
90             $new_image->createFrom($i->getStoreName(), $i->filename);
91             
92             $map[$i->id] = $new_image->id;
93         }
94         
95         
96         libxml_use_internal_errors (true);
97         $doc = new DOMDocument('1.0', 'UTF-8');
98         $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
99         $doc->formatOutput = true;
100
101        //echo '<PRE>'; print_R($doc);
102         
103         
104         $xpath = new DOMXpath($doc);
105         foreach ($xpath->query('//img[@src]') as $img) {
106             $href = $img->getAttribute('src');
107             //var_dump($href);
108             $matches = array();
109             if (preg_match("/Images\/([0-9]+)\/([^#]+)\#image\-([0-9]+)$/", $href, $matches)) {
110                  
111                 $oid = $matches[1];
112                 
113                 if (!isset($map[$oid])) {
114                     //echo "skip no new id for $oid";
115                     continue;
116                 }
117                 $nid = $map[$oid];
118                 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
119                 
120                 $img->setAttribute('src',  str_replace($matches[0], $nstr, $href ));
121                     
122                  
123             }
124         }
125         $cc = clone($c);
126         $c->bodytext = $doc->saveHTML();
127         $c->update($cc);
128         libxml_use_internal_errors (false);
129         
130         
131         $roo->jok("duplicated");
132     }
133     
134     function onInsert($q,$roo)
135     {   
136         $i = DB_DataObject::factory('Images');
137         $i->onid = 0;
138         $i->ontable = $this->tableName();
139         $i->find();
140         while ($i->fetch()){
141             $ii = clone ($i);
142             $i->onid = $this->id;
143             $i->update($ii);
144         }
145         
146 //        $this->cachedMailWithOutImages(true, (get_class($this) == 'Pman_Core_DataObjects_Core_email') ? false : true);
147         $this->cachedMailWithOutImages(true, false);
148        
149     }
150     
151     function onUpdate($old, $q,$roo)
152     {
153         $this->cachedMailWithOutImages(true, false);
154     }
155
156
157     function attachmentIds()
158     {
159         libxml_use_internal_errors (true);
160         $doc = new DOMDocument('1.0', 'UTF-8');
161         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
162         
163         $xpath = new DOMXpath($doc);
164         $ret = array();
165         
166         foreach ($xpath->query('//img[@src]') as $img) { // process images!
167             $href = $img->getAttribute('src');
168             $cid = explode('#', $href);
169             if(!isset($cid[1])){
170                 continue;
171             }
172             $cid = explode('-', $cid[1]);
173             if (!isset($cid[1])||!is_numeric($cid[1])) {
174                 continue;
175             }
176             $ret[] = $cid[1];
177         }
178         
179         return $ret;
180     }
181     /**
182      * process replacements is run to generate a template - not the final content..
183      *
184      */
185     
186     function processRelacements($replace_links = true)
187     {   
188         libxml_use_internal_errors (true);
189         $doc = new DOMDocument('1.0', 'UTF-8');
190         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
191         
192         $xpath = new DOMXpath($doc);
193         
194         foreach ($xpath->query('//img[@src]') as $img) { // process images!
195             $href = $img->getAttribute('src');
196             $cid = explode('#', $href);
197             if(isset($cid[1])){
198                 $img->setAttribute('src', 'cid:' . $cid[1]);
199             }
200         }
201         
202         $this->bodytext = $doc->saveHTML();
203         
204         libxml_use_internal_errors (false);
205         
206         $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
207         $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
208         
209         return;
210     }
211     
212     function send($obj)
213     {    
214         
215         $contents = (array)$obj;
216         
217         $this->cachedMailWithOutImages(true, false);
218         exit;
219         $contents['subject'] = $this->subject;
220         
221         require_once 'Pman/Core/Mailer.php';
222         
223         $ui = posix_getpwuid(posix_geteuid());
224         
225         $templateDir = session_save_path() . '/email-cache-' . $ui['name'] ;
226         $r = new Pman_Core_Mailer(array(
227             'template'=> $this->tableName() . '-' . $this->id,
228             'templateDir' => $templateDir,
229             'page' => $this,
230             'contents' => $contents
231         ));
232         
233         $ret = $r->toData();
234         
235         $ui = posix_getpwuid(posix_geteuid());
236         
237         $images = file_get_contents(session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt');
238         
239         $ret['body'] = str_replace('%Images%', $images, $ret['body']);
240         
241         return $r->send($ret);
242     }
243     
244     function cachedMailWithOutImages($force = false, $replace_links = true)
245     {  
246         $random_hash = md5(date('r', time()));
247         
248         $this->cachedImages($random_hash);
249         
250         $ui = posix_getpwuid(posix_geteuid());
251         
252         $cachePath = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
253           
254         if (!$force && $this->isGenerated($cachePath)) {
255             return;
256         }
257         
258         if (!file_exists(dirname($cachePath))) {
259             mkdir(dirname($cachePath), 0700, true);
260         }
261 //        print_r($this->bodytext);exit;
262 //        $this->processRelacements($replace_links);
263         
264         $fh = fopen($cachePath, 'w');
265
266         fwrite($fh, implode("\n", array(
267             "From: {t.messageFrom():h} ",
268             "To: {t.person.getEmailFrom():h} ",
269             "Subject: {t.subject} ",
270             "X-Message-ID: {t.id} "
271         ))."\n");
272         
273         
274 // note the extra space to finish the last line..
275         fwrite($fh, " " . "
276 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
277
278 --alt-{$random_hash}
279 Content-Type: text/plain; charset=utf-8; format=flowed
280 Content-Transfer-Encoding: 7bit
281
282 {$this->plaintext}
283     
284 --alt-{$random_hash}
285 Content-Type: multipart/related; boundary=rel-{$random_hash}
286
287 --rel-{$random_hash}
288 Content-Type: text/html; charset=utf-8
289 Content-Transfer-Encoding: 7bit
290
291
292
293 ");  
294
295 //        fwrite($fh,"%Images%
296 //--rel-{$random_hash}--
297 //
298 //--alt-{$random_hash}--
299 //");
300         fclose($fh);
301         
302     }
303     
304     function cachedImages($random_hash)
305     {
306         $ui = posix_getpwuid(posix_geteuid());
307         
308         $imageCache = session_save_path() . '/email-cache-' . $ui['name'] . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
309         
310         $ids = $this->attachmentIds();
311         
312          
313         $fh = fopen($imageCache, 'w');
314         
315         $i = DB_DataObject::factory('Images');
316         $i->onid = $this->id;
317         $i->ontable = $this->tableName();
318         $i->whereAddIn('id', $ids, 'int');
319         $i->find();
320         while ($i->fetch()){
321             if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
322                 continue;
323             }
324             $out = chunk_split(base64_encode(file_get_contents($i->getStoreName())));
325             if (empty($out)) {
326                 continue;
327             }
328             $imgfn = urlencode(preg_replace('/#.*$/i', '' , $i->filename));
329             fwrite($fh, "--rel-{$random_hash}
330 Content-Type: {$i->mimetype}; name={$imgfn}
331 Content-Transfer-Encoding: base64
332 Content-ID: <attachment-{$i->id}>
333 Content-Disposition: inline; filename={$imgfn}
334
335 " . $out  . "");
336
337             }
338         
339     }
340     
341     function isGenerated($cachePath)
342     {
343         if (!file_exists($cachePath) || !filesize($cachePath)) {
344             return false;
345         }
346         
347         
348         $ctime = filemtime($cachePath);
349         $mtime = array();
350         $mtime[] = $this->updated_dt;
351         $i = DB_DataObject::factory('Images');
352         $i->onid = $this->id;
353         $i->ontable = $this->tableName();
354         $i->selectAdd();
355         $i->selectAdd('max(created) as created');
356         $i->find(true);
357         $mtime[] = $i->created;
358         if($ctime >= strtotime(max($mtime))){
359             return true;
360         }
361         
362         return false;
363     }
364     
365     function messageFrom()
366     {
367         return '"' . addslashes($this->from_name) . '" <' . $this->from_email. '>'  ;
368     }
369     
370     function formatDate($dt, $format = 'd/M/Y')
371     {
372         return date($format, strtotime($dt));
373     } 
374     
375     
376     
377 }