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