DataObjects/core.sql
[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             if (empty($this->ontable) || empty($this->onid)) {
330                 return false;
331             }
332             $ret = DB_DataObject::factory($this->ontable);
333             $ret->get($this->onid);
334             return $ret;
335         }
336         
337         
338         $this->ontable = $obj->tableName();
339         $this->onid = $obj->id; /// assumes our nice standard of using ids..
340         return $obj;
341     }
342     
343      
344     function toRooArray($req = array()) {
345       //  echo '<PRE>';print_r($req);exit;
346         $ret= $this->toArray();
347       
348       
349         if (!empty($req['query']['imagesize'])) {
350              $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : false;
351             
352             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
353             
354             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
355             
356             if (!empty($req['query']['imagesize'])) {
357                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
358             }
359         }
360         
361          
362          
363         return $ret;
364     }
365     
366     /**
367      * URL - create  a url for the image.
368      * size - use -1 to show full size.
369      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
370      * 
371      * 
372      */
373     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
374     {
375         if (!$this->id) {
376             return 'about:blank';
377             
378         }
379
380         $ff = HTML_FlexyFramework::get();
381         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
382         if (preg_match('#^http[s]*://#', $provider)) {
383             $baseURL = '';
384         }
385         
386         if ($size < 0) {
387             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
388         }
389         //-- max?
390         //$size = max(100, (int) $size);
391         //$size = min(1024, (int) $size);
392         
393         
394         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
395     }
396     /**
397      * size could be 123x345
398      * 
399      * 
400      */
401     function toHTML($size, $provider = '/Images/Thumb') 
402     {
403         
404         
405         
406         $sz = explode('x', $size);
407         $sx = $sz[0];
408         //var_dump($sz);
409         if (!$this->id || empty($this->width)) {
410             $this->height = $sx;
411             $this->width = empty($sz[1]) ? $sx : $sz[1];
412             $sy = $this->width ;
413         }
414         if (empty($sz[1])) {
415             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
416             $sy = $ratio * $sx;
417         } else {
418             $sy = $sz[1];
419         }
420         // create it?
421         
422         
423         return '<img src="' . $this->URL($size, $provider) . '" width="'. $sx . '" height="'. $sy . '">';
424         
425         
426     }
427     
428     /**
429      *
430      *
431      *
432      */
433     
434     
435     function setFromRoo($ar, $roo)
436     {
437         // not sure why we do this.. 
438         
439         
440         
441         
442         
443         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
444         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
445             $this->setFrom($ar);
446             $this->limit(1);
447             if ($this->find(true)) {
448                 $roo->old = clone($this);
449             }
450         }   
451             
452         
453         if (!empty($ar['_copy_from'])) {
454             
455             if (!$this->checkPerm( 'A' , $roo->authUser))  {
456                 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
457             }
458             
459             $copy = DB_DataObject::factory('Images');
460             $copy->get($ar['_copy_from']);
461             $this->setFrom($copy->toArray());
462             $this->setFrom($ar);
463             $this->createFrom($copy->getStoreName());
464             
465             $roo->addEvent("ADD", $this, $this->toEventString());
466             
467             $r = DB_DataObject::factory($this->tableName());
468             $r->id = $this->id;
469             $roo->loadMap($r);
470             $r->limit(1);
471             $r->find(true);
472             $roo->jok($r->toArray());
473             
474             
475         }
476         
477          
478         
479         // FIXME - we should be checking perms here...
480        
481         // this should be doign update
482         $this->setFrom($ar);
483          
484         if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser))  {
485             $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
486         }
487         
488         if (!isset($_FILES['imageUpload'])) {
489             return; // standard update...
490         }
491         
492         if ( !$this->onUpload($this)) {
493             $roo->jerr("File upload failed : ". $this->err);
494         }
495         
496         $roo->addEvent("ADD", $this, $this->toEventString());
497         
498         $r = DB_DataObject::factory($this->tableName());
499         $r->id = $this->id;
500         $roo->loadMap($r);
501         $r->limit(1);
502         $r->find(true);
503         $roo->jok($r->toArray());
504          
505     }
506     
507     function toEventString()
508     {
509         
510         //$p = DB_DataObject::factory($this->ontable);
511         //if (!is_$p) {
512         //    return "ERROR unknown table? {$this->ontable}";
513        // }
514         //$p->get($p->onid);
515         
516         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
517         //$p->toEventString();
518     }
519  }