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