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