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