oops
[Pman.Core] / DataObjects / Images.php
1 <?php
2 /**
3  * Table Definition for Images
4  */
5 require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Images extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'Images';                          // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $filename;                        // string(255)  not_null
15     public $ontable;                         // string(32)  not_null multiple_key
16     public $onid;                            // int(11)  not_null
17     public $mimetype;                        // string(64)  not_null
18     public $width;                           // int(11)  not_null
19     public $height;                          // int(11)  not_null
20     public $filesize;                        // int(11)  not_null
21     public $displayorder;                    // int(11)  not_null
22     public $language;                        // string(6)  not_null
23     public $parent_image_id;                 // int(11)  not_null
24     public $created;                         // datetime(19)  not_null binary
25     public $imgtype;                         // string(32)  not_null
26     public $linkurl;                         // string(254)  not_null
27     public $descript;                        // blob(65535)  not_null blob
28     public $title;                           // string(128)  not_null
29
30     
31     /* the code above is auto generated do not remove the tag below */
32     ###END_AUTOCODE
33     /**
34      * create an email from file.
35      * these must have been set first.
36      * ontable / onid.
37      * 
38      */
39     function createFrom($file)
40     {
41         // copy the file into the storage area..
42         if (!file_exists($file) || !filesize($file)) {
43             return false;
44         }
45         
46         
47         $imgs = @getimagesize($file);
48         
49         if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
50             // it's a file!!!!
51         } else {
52             list($this->width , $this->height)  = $imgs;
53         }
54         
55         $this->filesize = filesize($file);
56         $this->created = date('Y-m-d H:i:s');
57         
58         if (empty($this->mimetype)) {
59             require_once 'File/MimeType.php';
60             $y = new File_MimeType();
61             $this->mimetype = $y->fromFilename($file);
62         }
63         
64         
65         if (empty($this->filename)) {
66             $this->filename = basename($file);
67         }
68         
69         //DB_DataObject::debugLevel(1);
70         if (!$this->id) {
71             $this->insert();
72         } else {
73             $this->update();
74         }
75         
76         
77         
78         $f = $this->getStoreName();
79         $dest = dirname($f);
80         if (!file_exists($dest)) {
81             
82             $oldumask = umask(0);
83             mkdir($dest, 0770, true);
84             umask($oldumask);  
85         }
86         
87         copy($file,$f);
88         
89         // fill in details..
90         
91         /* thumbnails */
92         
93      
94        // $this->createThumbnail(0,50);
95         return true;
96         
97     }
98
99     /**
100      * Calculate target file name
101      *
102      * @return - target file name
103      */
104     function getStoreName() 
105     {
106         $opts = PEAR::getStaticProperty('Pman', 'options');
107         $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
108         return implode( '/', array(
109             $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
110         ));
111           
112     }
113
114      
115     /**
116      * deletes all the image instances of it...
117      * 
118      * 
119      */
120     function beforeDelete()
121     {
122         $fn = $this->getStoreName();
123         if (file_exists($fn)) {
124             unlink($fn);
125         }
126         // delete thumbs..
127         $b = basename($fn);
128         $d = dirname($fn);
129         if (file_exists($d)) {
130                 
131             $dh = opendir($d);
132             while (false !== ($fn = readdir($dh))) {
133                 if (substr($fn, 0, strlen($b)) == $b) {
134                     unlink($d. '/'. $fn);
135                 }
136             }
137         }
138         
139     }
140     
141   
142     /**
143      * onUpload (singlely attached image to a table)
144      */
145     
146     function onUploadWithTbl($tbl,  $fld)
147     {
148         if ( $tbl->__table == 'Images') {
149             return; // not upload to self...
150         }
151         if (empty($_FILES['imageUpload']['tmp_name']) || 
152             empty($_FILES['imageUpload']['name']) || 
153             empty($_FILES['imageUpload']['type'])
154         ) {
155             return false;
156         }
157         if ($tbl->$fld) {
158             $image = DB_DataObject::factory('Images');
159             $image->get($tbl->$fld);
160             $image->beforeDelete();
161             $image->delete();
162         }
163         
164         $image = DB_DataObject::factory('Images');
165         $image->onid = $tbl->id;
166         $image->ontable = $tbl->__table;
167         $image->filename = $_FILES['imageUpload']['name']; 
168         $image->mimetype = $_FILES['imageUpload']['type'];
169        
170         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
171             return false;
172         }
173         $old = clone($tbl);
174         $tbl->$fld = $image->id;
175         $tbl->update($old);
176          
177     }
178     
179     // direct via roo...
180     function onUpload($ctrl)
181     {
182         
183         if (empty($_FILES['imageUpload']['tmp_name']) || 
184             empty($_FILES['imageUpload']['name']) || 
185             empty($_FILES['imageUpload']['type'])
186         ) {
187             $this->err = "Missing file details";
188             return false;
189         }
190         
191         if ($this->id) {
192             $this->beforeDelete();
193         }
194         if ( empty($this->ontable)) {
195             $this->err = "Missing  ontable";
196             return false;
197         }
198         
199         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
200             // then its an upload 
201             $img  = DB_DataObject::factory('Images');
202             $img->onid = $this->onid;
203             $img->ontable = $this->ontable;
204             $img->imgtype = $this->imgtype;
205             
206             $img->find();
207             while ($img->fetch()) {
208                 $img->beforeDelete();
209                 $img->delete();
210             }
211             
212         }
213         
214         
215         
216         require_once 'File/MimeType.php';
217         $y = new File_MimeType();
218         $this->mimetype = $_FILES['imageUpload']['type'];
219         if (in_array($this->mimetype, array('text/application', 'application/octet-stream'))) { // weird tyeps..
220             $inf = pathinfo($_FILES['imageUpload']['name']);
221             $this->mimetype  = $y->fromExt($inf['extension']);
222         }
223         
224         
225         $ext = $y->toExt(trim((string) $this->mimetype ));
226         
227         $this->filename = empty($this->filename) ? 
228             $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext); 
229         
230         
231         
232         if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
233             return false;
234         }
235         return true;
236          
237     }
238      
239     /**
240      * return a list of images for an object, optionally with a mime regex.
241      * eg. '%/pdf' or 'image/%'
242      */
243     function gather($obj, $mime_like='')
244     {
245         //DB_DataObject::debugLevel(1);
246         if (empty($obj->id)) {
247             return array();
248         }
249         $c = clone($this);
250         $c->ontable = $obj->tableName();
251         $c->onid = $obj->id;
252         if (!empty($mime_like)) {
253             $c->whereAdd("mimetype LIKE '". $c->escape($mime_like) ."'");
254         }
255
256         return $c->fetchAll();
257     }
258     
259      
260     function toRooArray($req = array()) {
261       //  echo '<PRE>';print_r($req);exit;
262         $ret= $this->toArray();
263       
264       
265         if (!empty($req['query']['imagesize'])) {
266              $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : false;
267             
268             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
269             
270             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
271             
272             if (!empty($req['query']['imagesize'])) {
273                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
274             }
275         }
276         
277          
278          
279         return $ret;
280     }
281     
282     /**
283      * URL - create  a url for the image.
284      * size - use -1 to show full size.
285      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
286      * 
287      * 
288      */
289     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
290     {
291         if (!$this->id) {
292             return 'about:blank';
293             
294         }
295
296         $ff = HTML_FlexyFramework::get();
297         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
298         if ($size < 0) {
299             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
300         }
301         //-- max?
302         //$size = max(100, (int) $size);
303         //$size = min(1024, (int) $size);
304         
305         
306         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
307     }
308     /**
309      * size could be 123x345
310      * 
311      * 
312      */
313     function toHTML($size, $provider = '/Images/Thumb') 
314     {
315         
316         
317         
318         $sz = explode('x', $size);
319         $sx = $sz[0];
320         //var_dump($sz);
321         if (!$this->id) {
322             $this->height = $sx;
323             $this->width = empty($sz[1]) ? $sx : $sz[1];
324             $sy = $this->width ;
325         }
326         if (empty($sz[1])) {
327             $ratio =  $this->height/ ($this->width *1.0);
328             $sy = $ration * $sx;
329         } else {
330             $sy = $sz[1];
331         }
332         // create it?
333         
334         
335         return '<img src="' . $this->URL($size, $provider) . '" width="'. $sx . '" height="'. $sy . '">';
336         
337         
338     }
339     
340     
341     
342     
343     function setFromRoo($ar, $roo)
344     {
345         // not sure why we do this.. 
346         
347         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
348         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
349             $this->setFrom($ar);
350             $this->limit(1);
351             if ($this->find(true)) {
352                 $roo->old = clone($this);
353             }
354         }   
355             
356         
357         if (!empty($ar['_copy_from'])) {
358             $copy = DB_DataObject::factory('Images');
359             $copy->get($ar['_copy_from']);
360             $this->setFrom($copy->toArray());
361             $this->setFrom($ar);
362             $this->createFrom($copy->getStoreName());
363             
364             $roo->addEvent("ADD", $this, $this->toEventString());
365             
366             $r = DB_DataObject::factory($this->tableName());
367             $r->id = $this->id;
368             $roo->loadMap($r);
369             $r->limit(1);
370             $r->find(true);
371             $roo->jok($r->toArray());
372             
373             
374         }
375         
376          
377         
378         // FIXME - we should be checking perms here...
379         //if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser))  {
380         //    $this->jerr("PERMISSION DENIED");
381         // }
382         // this should be doign update
383         $this->setFrom($ar);
384         
385         if (!isset($_FILES['imageUpload'])) {
386             return; // standard update...
387         }
388         
389         if ( !$this->onUpload($this)) {
390             $this->jerr("File upload failed");
391         }
392         $roo->addEvent("ADD", $this, $this->toEventString());
393         
394         $r = DB_DataObject::factory($this->tableName());
395         $r->id = $this->id;
396         $roo->loadMap($r);
397         $r->limit(1);
398         $r->find(true);
399         $roo->jok($r->toArray());
400          
401     }
402     function toEventString()
403     {
404         
405         //$p = DB_DataObject::factory($this->ontable);
406         //if (!is_$p) {
407         //    return "ERROR unknown table? {$this->ontable}";
408        // }
409         //$p->get($p->onid);
410         
411         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
412         //$p->toEventString();
413     }
414  }