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