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