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