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