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