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