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