1ea5c9b8f5d946e4d057f91196713fc0d0949f79
[Pman.Core] / DataObjects / Core_mailing_list_message.php
1 <?php
2 /**
3  * Table Definition for core_mailinglist_message
4  */
5 require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_mailing_list_message 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_mailing_list_message';    // 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($request,$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     }
140     
141     function attachmentIds()
142     {
143         libxml_use_internal_errors (true);
144         $doc = new DOMDocument('1.0', 'UTF-8');
145         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
146         
147         $xpath = new DOMXpath($doc);
148         $ret = array();
149         
150         foreach ($xpath->query('//img[@src]') as $img) { // process images!
151             $href = $img->getAttribute('src');
152             $cid = explode('#', $href);
153             if(!isset($cid[1])){
154                 continue;
155             }
156             $cid = explode('-', $cid[1]);
157             if (!isset($cid[1])||!is_numeric($cid[1])) {
158                 continue;
159             }
160             $ret[] = $cid[1];
161         }
162         
163         return $ret;
164     }
165     /**
166      * process replacements is run to generate a template - not the final content..
167      *
168      */
169     
170     function processRelacements($replace_links = true)
171     {   
172         libxml_use_internal_errors (true);
173         $doc = new DOMDocument('1.0', 'UTF-8');
174         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
175         
176         $xpath = new DOMXpath($doc);
177         
178         foreach ($xpath->query('//img[@src]') as $img) { // process images!
179             $href = $img->getAttribute('src');
180             $cid = explode('#', $href);
181             if(isset($cid[1])){
182                 $img->setAttribute('src', 'cid:' . $cid[1]);
183             }
184         }
185         
186         $this->bodytext = $doc->saveHTML();
187         
188         libxml_use_internal_errors (false);
189         
190         $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
191         $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
192         
193         return;
194     }
195     
196     function send($obj)
197     {    
198         $contents = (array)$obj;
199         
200         $this->cachedMailWithOutImages(true, false);
201         
202         $contents['subject'] = $this->subject;
203         
204         require_once 'Pman/Core/Mailer.php';
205         
206         $templateDir = session_save_path() . '/email-cache-' . getenv('APACHE_RUN_USER') ;
207         $r = new Pman_Core_Mailer(array(
208             'template'=> $this->tableName() . '-' . $this->id,
209             'templateDir' => $templateDir,
210             'page' => $this,
211             'contents' => $contents
212         ));
213         
214         $ret = $r->toData();
215         
216         $person = $contents['person'];
217         
218         if(!is_object($person)){
219             
220         }
221         
222         $images = file_get_contents(session_save_path() . '/email-cache-' . getenv('APACHE_RUN_USER') . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt');
223         
224         $ret['body'] = str_replace('%Images%', $images, $ret['body']);
225         
226         return $r->send($ret);
227     }
228     
229     function cachedMailWithOutImages($force = false, $replace_links = true)
230     {  
231         $random_hash = md5(date('r', time()));
232         
233         $this->cachedImages($random_hash);
234         
235         $cachePath = session_save_path() . '/email-cache-' . getenv('APACHE_RUN_USER') . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
236           
237         if (!$force && $this->isGenerated($cachePath)) {
238             return;
239         }
240         
241         if (!file_exists(dirname($cachePath))) {
242             mkdir(dirname($cachePath), 0700, true);
243         }
244         
245         $this->processRelacements($replace_links);
246         
247         $fh = fopen($cachePath, 'w');
248
249         fwrite($fh, implode("\n", array(
250             "From: {t.messageFrom():h} ",
251             "To: {t.person.getEmailFrom():h} ",
252             "Subject: {t.subject} ",
253             "X-Message-ID: {t.id} "
254         ))."\n");
255         
256         
257 // note the extra space to finish the last line..
258         fwrite($fh, " " . "
259 Content-Type: multipart/alternative; boundary=alt-{$random_hash}
260
261 --alt-{$random_hash}
262 Content-Type: text/plain; charset=utf-8; format=flowed
263 Content-Transfer-Encoding: 7bit
264
265 {$this->plaintext}
266     
267 --alt-{$random_hash}
268 Content-Type: multipart/related; boundary=rel-{$random_hash}
269
270 --rel-{$random_hash}
271 Content-Type: text/html; charset=utf-8
272 Content-Transfer-Encoding: 7bit
273
274 <html><body>{$this->bodytext}</body></html>
275
276 ");  
277
278         fwrite($fh,"%Images%
279 --rel-{$random_hash}--
280
281 --alt-{$random_hash}--
282 ");
283         fclose($fh);
284         
285     }
286     
287     function cachedImages($random_hash)
288     {
289         $imageCache = session_save_path() . '/email-cache-' . getenv('APACHE_RUN_USER') . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
290         
291         $ids = $this->attachmentIds();
292         
293         //$this->jerr(print_r($ids,true));
294         
295          
296         $fh = fopen($imageCache, 'w');
297         
298         $i = DB_DataObject::factory('Images');
299         $i->onid = $this->id;
300         $i->ontable = $this->tableName();
301         $i->whereAddIn('id', $ids, 'int');
302         $i->find();
303         while ($i->fetch()){
304             if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
305                 continue;
306             }
307             $out = chunk_split(base64_encode(file_get_contents($i->getStoreName())));
308             if (empty($out)) {
309                 continue;
310             }
311             $imgfn = urlencode(preg_replace('/#.*$/i', '' , $i->filename));
312             fwrite($fh, "--rel-{$random_hash}
313 Content-Type: {$i->mimetype}; name={$imgfn}
314 Content-Transfer-Encoding: base64
315 Content-ID: <attachment-{$i->id}>
316 Content-Disposition: inline; filename={$imgfn}
317
318 " . $out  . "");
319
320             }
321         
322     }
323     
324     function isGenerated($cachePath)
325     {
326         if (!file_exists($cachePath) || !filesize($cachePath)) {
327             return false;
328         }
329         
330         
331         $ctime = filemtime($cachePath);
332         $mtime = array();
333         $mtime[] = $this->updated_dt;
334         $i = DB_DataObject::factory('Images');
335         $i->onid = $this->id;
336         $i->ontable = $this->tableName();
337         $i->selectAdd();
338         $i->selectAdd('max(created) as created');
339         $i->find(true);
340         $mtime[] = $i->created;
341         if($ctime >= strtotime(max($mtime))){
342             return true;
343         }
344         
345         return false;
346     }
347     
348     function messageFrom()
349     {
350         return '"' . addslashes($this->from_name) . '" <' . $this->from_email. '>'  ;
351     }
352     
353     function formatDate($dt, $format = 'd/M/Y')
354     {
355         return date($format, strtotime($dt));
356     } 
357     
358     
359     
360 }