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