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                         'image/x-png',  // WTF does this?
302                         'image/pjpeg',  // WTF does this?
303                         'application/x-apple-msg-attachment', /// apple doing it's magic...
304                         'application/vnd.ms-excel',   /// sometimes windows reports csv as excel???
305                         'application/csv-tab-delimited-table', // windows again!!?
306                 ))) { // weird tyeps..
307             $inf = pathinfo($_FILES['imageUpload']['name']);
308             $this->mimetype  = $y->fromExt($inf['extension']);
309         }
310         
311         
312         $ext = $y->toExt(trim((string) $this->mimetype ));
313         
314         $this->filename = empty($this->filename) ? 
315             $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext); 
316         
317         
318         
319         if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
320             return false;
321         }
322         return true;
323          
324     }
325      
326     
327     
328     /**
329      * return a list of images for an object, optionally with a mime regex.
330      * eg. '%/pdf' or 'image/%'
331      *
332      * usage:
333      *
334      * $i = DB_DataObject::factory('Images');
335      * $i->imgtype = 'LOGO';
336      * $ar = $i->gather($somedataobject, 'image/%');
337      * 
338      * @param {DB_DataObject} dataobject  = the object to gather data on.
339      * @param {String} mimelike  LIKE query to use for search
340      
341      */
342     function gather($obj, $mime_like='', $opts=array())
343     {
344         //DB_DataObject::debugLevel(1);
345         if (empty($obj->id)) {
346             return array();
347         }
348         
349         $c = clone($this);
350         $c->ontable = $obj->tableName();
351         $c->onid = $obj->id;
352         $c->autoJoin();
353         if (!empty($mime_like)) {
354             $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
355         }
356
357         return $c->fetchAll();
358     }
359      
360     
361     /**
362     * set or get the dataobject this image is associated with
363     * @param DB_DataObject $obj An object to associate this image with
364     *        (does not store it - you need to call update() to do that)
365     * @return DB_DataObject the dataobject this image is attached to.
366     */
367     function object($obj=false)
368     {
369         if ($obj === false) {
370             if (empty($this->ontable) || empty($this->onid)) {
371                 return false;
372             }
373             $ret = DB_DataObject::factory($this->ontable);
374             $ret->get($this->onid);
375             return $ret;
376         }
377         
378         
379         $this->ontable = $obj->tableName();
380         $this->onid = $obj->id; /// assumes our nice standard of using ids..
381         return $obj;
382     }
383     
384      
385     function toRooArray($req = array()) {
386       //  echo '<PRE>';print_r($req);exit;
387         $ret= $this->toArray();
388       
389         static $ff = false;
390         if (!$ff) {
391             $ff = HTML_FlexyFramework::get();
392         }
393         
394         $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
395                     $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
396         
397         if (!empty($req['query']['imagesize'])) {
398              $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : false;
399             
400             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
401             
402             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
403             
404             if (!empty($req['query']['imagesize'])) {
405                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
406             }
407         }
408         
409          
410          
411         return $ret;
412     }
413     
414     /**
415      * URL - create  a url for the image.
416      * size - use -1 to show full size.
417      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
418      * 
419      * 
420      */
421     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
422     {
423         if (!$this->id) {
424             return 'about:blank';
425             
426         }
427
428         $ff = HTML_FlexyFramework::get();
429         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
430         if (preg_match('#^http[s]*://#', $provider)) {
431             $baseURL = '';
432         }
433        
434         if ($size < 0) {
435             $provider = preg_replace('#/Thumb$#', '', $provider);
436             
437             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
438         }
439         //-- max?
440         //$size = max(100, (int) $size);
441         //$size = min(1024, (int) $size);
442         // the size should 200x150 to convert
443         $sizear = preg_split('/(x|c)/', $size);
444         if(empty($sizear[1])){
445             $sizear[1] = 0;
446         }
447         $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
448         print_r($size);
449         $fc = $this->toFileConvert();
450         $fc->convert($this->mimetype, $size);
451         
452         
453         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
454     }
455     /**
456      * size could be 123x345
457      * 
458      * 
459      */
460     function toHTML($size, $provider = '/Images/Thumb') 
461     {
462         
463         
464         
465         $sz = explode('x', $size);
466         $sx = $sz[0];
467         //var_dump($sz);
468         if (!$this->id || empty($this->width)) {
469             $this->height = $sx;
470             $this->width = empty($sz[1]) ? $sx : $sz[1];
471             $sy = $this->width ;
472         }
473         if (empty($sz[1])) {
474             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
475             $sy = $ratio * $sx;
476         } else {
477             $sy = $sz[1];
478         }
479         // create it?
480          
481         return '<img src="' . $this->URL($size, $provider) . '" width="'. $sx . '" height="'. $sy . '">';
482         
483         
484     }
485      
486     /**
487      * to Fileconvert object..
488      *
489      *
490      *
491      */
492     function toFileConvert()
493     {
494         require_once 'File/Convert.php';
495         $fc = new File_Convert($this->getStoreName(), $this->mimetype);
496         return $fc;
497         
498     }
499     
500     function fileExt()
501     {
502         require_once 'File/MimeType.php';
503         
504         $y = new File_MimeType();
505         return  $y->toExt($this->mimetype);
506         
507         
508     }
509     
510     /**
511      *
512      *
513      *
514      */
515     
516     
517     function setFromRoo($ar, $roo)
518     {
519         // not sure why we do this.. 
520         
521         
522         
523         
524         
525         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
526         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
527             $this->setFrom($ar);
528             $this->limit(1);
529             if ($this->find(true)) {
530                 $roo->old = clone($this);
531             }
532         }   
533             
534         
535         if (!empty($ar['_copy_from'])) {
536             
537             if (!$this->checkPerm( 'A' , $roo->authUser))  {
538                 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
539             }
540             
541             $copy = DB_DataObject::factory('Images');
542             $copy->get($ar['_copy_from']);
543             $this->setFrom($copy->toArray());
544             $this->setFrom($ar);
545             $this->createFrom($copy->getStoreName());
546             
547             $roo->addEvent("ADD", $this, $this->toEventString());
548             
549             $r = DB_DataObject::factory($this->tableName());
550             $r->id = $this->id;
551             $roo->loadMap($r);
552             $r->limit(1);
553             $r->find(true);
554             $roo->jok($r->toArray());
555             
556             
557         }
558         
559          
560         
561         // FIXME - we should be checking perms here...
562        
563         // this should be doign update
564         $this->setFrom($ar);
565          
566         if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser))  {
567             $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
568         }
569         
570         
571         
572         if (!isset($_FILES['imageUpload'])) {
573             return; // standard update...
574         }
575         
576         if ( !$this->onUpload($this)) {
577             $roo->jerr("File upload failed : ". $this->err);
578         }
579         
580         $roo->addEvent("ADD", $this, $this->toEventString());
581         
582         $r = DB_DataObject::factory($this->tableName());
583         $r->id = $this->id;
584         $roo->loadMap($r);
585         $r->limit(1);
586         $r->find(true);
587         $roo->jok($r->toArray());
588          
589     }
590     
591     function toEventString()
592     {
593         
594         //$p = DB_DataObject::factory($this->ontable);
595         //if (!is_$p) {
596         //    return "ERROR unknown table? {$this->ontable}";
597        // }
598         //$p->get($p->onid);
599         
600         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
601         //$p->toEventString();
602     }
603  }