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