DataObjects/Person.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 $filesize;                        // int(11)  not_null
19     public $created;                         // datetime(19)  not_null binary
20     public $created_by;                         // int(11)  not_null
21
22     public $width;                           // int(11)  not_null
23     public $height;                          // int(11)  not_null
24     
25
26     public $imgtype;                         // string(32)  not_null
27     public $parent_image_id;                 // int(11)  not_null
28     public $linkurl;                         // string(254)  not_null
29     public $descript;                        // blob(65535)  not_null blob
30     public $title;                           // string(128)  not_null
31     public $displayorder;                    // int(11)  not_null
32     public $language;                        // string(6)  not_null
33     
34     
35     /* the code above is auto generated do not remove the tag below */
36     ###END_AUTOCODE
37     /**
38      * create an email from file.
39      * these must have been set first.
40      * ontable / onid.
41      * 
42      */
43     function createFrom($file, $filename=false)
44     {
45         // copy the file into the storage area..
46         if (!file_exists($file) || !filesize($file)) {
47             return false;
48         }
49         
50         $filename = empty($filename) ? $file : $filename;
51         
52         if (empty($this->mimetype)) {
53             require_once 'File/MimeType.php';
54             $y = new File_MimeType();
55             $this->mimetype = $y->fromFilename($filename);
56         }
57         
58         $this->mimetype= strtolower($this->mimetype);
59         
60         if (array_shift(explode('/', $this->mimetype)) == 'image') { 
61         
62             $imgs = @getimagesize($file);
63             
64             if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
65                 // it's a file!!!!
66             } else {
67                 list($this->width , $this->height)  = $imgs;
68             }
69         }
70         
71         $this->filesize = filesize($file);
72         $this->created = date('Y-m-d H:i:s');
73          
74         
75         if (empty($this->filename)) {
76             $this->filename = basename($filename);
77         }
78         
79         //DB_DataObject::debugLevel(1);
80         if (!$this->id) {
81             $this->insert();
82         } else {
83             $this->update();
84         }
85         
86         
87         
88         $f = $this->getStoreName();
89         $dest = dirname($f);
90         if (!file_exists($dest)) {
91             
92             $oldumask = umask(0);
93             mkdir($dest, 0770, true);
94             umask($oldumask);  
95         }
96         
97         copy($file,$f);
98         
99         // fill in details..
100         
101         /* thumbnails */
102         
103      
104        // $this->createThumbnail(0,50);
105         return true;
106         
107     }
108
109     /**
110      * Calculate target file name
111      *
112      * @return - target file name
113      */
114     function getStoreName() 
115     {
116         $opts = HTML_FlexyFramework::get()->Pman;
117         $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
118         return implode( '/', array(
119             $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
120         ));
121           
122     }
123
124      
125     /**
126      * deletes all the image instances of it...
127      * 
128      * 
129      */
130     function beforeDelete()
131     {
132         $fn = $this->getStoreName();
133         if (file_exists($fn)) {
134             unlink($fn);
135         }
136         // delete thumbs..
137         $b = basename($fn);
138         $d = dirname($fn);
139         if (file_exists($d)) {
140                 
141             $dh = opendir($d);
142             while (false !== ($fn = readdir($dh))) {
143                 if (substr($fn, 0, strlen($b)) == $b) {
144                     unlink($d. '/'. $fn);
145                 }
146             }
147         }
148         
149     }
150     /**
151      * check mimetype against type
152      * - eg. img.is(#image#)
153      *
154      */
155     function is($type)
156     {
157         if (empty($this->mimetype)) {
158             return false;
159         }
160         return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
161     }
162   
163     /**
164      * onUpload (singlely attached image to a table)
165      */
166     
167     function onUploadWithTbl($tbl,  $fld)
168     {
169         if ( $tbl->__table == 'Images') {
170             return; // not upload to self...
171         }
172         if (empty($_FILES['imageUpload']['tmp_name']) || 
173             empty($_FILES['imageUpload']['name']) || 
174             empty($_FILES['imageUpload']['type'])
175         ) {
176             return false;
177         }
178         if ($tbl->$fld) {
179             $image = DB_DataObject::factory('Images');
180             $image->get($tbl->$fld);
181             $image->beforeDelete();
182             $image->delete();
183         }
184         
185         $image = DB_DataObject::factory('Images');
186         $image->onid = $tbl->id;
187         $image->ontable = $tbl->__table;
188         $image->filename = $_FILES['imageUpload']['name']; 
189         $image->mimetype = $_FILES['imageUpload']['type'];
190        
191         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
192             return false;
193         }
194         $old = clone($tbl);
195         $tbl->$fld = $image->id;
196         $tbl->update($old);
197          
198     }
199     
200     // direct via roo...
201     function onUpload($ctrl)
202     {
203         
204         if (empty($_FILES['imageUpload']['tmp_name']) || 
205             empty($_FILES['imageUpload']['name']) || 
206             empty($_FILES['imageUpload']['type'])
207         ) {
208             $this->err = "Missing file details";
209             return false;
210         }
211         
212         if ($this->id) {
213             $this->beforeDelete();
214         }
215         if ( empty($this->ontable)) {
216             $this->err = "Missing  ontable";
217             return false;
218         }
219         
220         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
221             // then its an upload 
222             $img  = DB_DataObject::factory('Images');
223             $img->onid = $this->onid;
224             $img->ontable = $this->ontable;
225             $img->imgtype = $this->imgtype;
226             
227             $img->find();
228             while ($img->fetch()) {
229                 $img->beforeDelete();
230                 $img->delete();
231             }
232             
233         }
234         
235         
236         
237         require_once 'File/MimeType.php';
238         $y = new File_MimeType();
239         $this->mimetype = $_FILES['imageUpload']['type'];
240         if (in_array($this->mimetype, array('text/application', 'application/octet-stream'))) { // weird tyeps..
241             $inf = pathinfo($_FILES['imageUpload']['name']);
242             $this->mimetype  = $y->fromExt($inf['extension']);
243         }
244         
245         
246         $ext = $y->toExt(trim((string) $this->mimetype ));
247         
248         $this->filename = empty($this->filename) ? 
249             $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext); 
250         
251         
252         
253         if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
254             return false;
255         }
256         return true;
257          
258     }
259      
260     /**
261      * return a list of images for an object, optionally with a mime regex.
262      * eg. '%/pdf' or 'image/%'
263      */
264     function gather($obj, $mime_like='')
265     {
266         //DB_DataObject::debugLevel(1);
267         if (empty($obj->id)) {
268             return array();
269         }
270         
271         $c = clone($this);
272         $c->ontable = $obj->tableName();
273         $c->onid = $obj->id;
274         $c->autoJoin();
275         if (!empty($mime_like)) {
276             $c->whereAdd("mimetype LIKE '". $c->escape($mime_like) ."'");
277         }
278
279         return $c->fetchAll();
280     }
281      
282     
283     /**
284     * set or get the dataobject this image is associated with
285     * @param DB_DataObject $obj An object to associate this image with
286     *        (does not store it - you need to call update() to do that)
287     * @return DB_DataObject the dataobject this image is attached to.
288     */
289     function object($obj=false)
290     {
291         if ($obj === false) {
292             $ret = DB_DataObject::factory($this->ontable);
293             $ret->get($this->onid);
294             return $ret;
295         }
296         $this->ontable = $obj->tableName();
297         $this->onid = $obj->id; /// assumes our nice standard of using ids..
298         return $obj;
299     }
300     
301      
302     function toRooArray($req = array()) {
303       //  echo '<PRE>';print_r($req);exit;
304         $ret= $this->toArray();
305       
306       
307         if (!empty($req['query']['imagesize'])) {
308              $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : false;
309             
310             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
311             
312             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
313             
314             if (!empty($req['query']['imagesize'])) {
315                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
316             }
317         }
318         
319          
320          
321         return $ret;
322     }
323     
324     /**
325      * URL - create  a url for the image.
326      * size - use -1 to show full size.
327      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
328      * 
329      * 
330      */
331     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
332     {
333         if (!$this->id) {
334             return 'about:blank';
335             
336         }
337
338         $ff = HTML_FlexyFramework::get();
339         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
340         if ($size < 0) {
341             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
342         }
343         //-- max?
344         //$size = max(100, (int) $size);
345         //$size = min(1024, (int) $size);
346         
347         
348         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
349     }
350     /**
351      * size could be 123x345
352      * 
353      * 
354      */
355     function toHTML($size, $provider = '/Images/Thumb') 
356     {
357         
358         
359         
360         $sz = explode('x', $size);
361         $sx = $sz[0];
362         //var_dump($sz);
363         if (!$this->id || empty($this->width)) {
364             $this->height = $sx;
365             $this->width = empty($sz[1]) ? $sx : $sz[1];
366             $sy = $this->width ;
367         }
368         if (empty($sz[1])) {
369             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
370             $sy = $ratio * $sx;
371         } else {
372             $sy = $sz[1];
373         }
374         // create it?
375         
376         
377         return '<img src="' . $this->URL($size, $provider) . '" width="'. $sx . '" height="'. $sy . '">';
378         
379         
380     }
381     
382     
383     
384     
385     function setFromRoo($ar, $roo)
386     {
387         // not sure why we do this.. 
388         
389         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
390         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
391             $this->setFrom($ar);
392             $this->limit(1);
393             if ($this->find(true)) {
394                 $roo->old = clone($this);
395             }
396         }   
397             
398         
399         if (!empty($ar['_copy_from'])) {
400             $copy = DB_DataObject::factory('Images');
401             $copy->get($ar['_copy_from']);
402             $this->setFrom($copy->toArray());
403             $this->setFrom($ar);
404             $this->createFrom($copy->getStoreName());
405             
406             $roo->addEvent("ADD", $this, $this->toEventString());
407             
408             $r = DB_DataObject::factory($this->tableName());
409             $r->id = $this->id;
410             $roo->loadMap($r);
411             $r->limit(1);
412             $r->find(true);
413             $roo->jok($r->toArray());
414             
415             
416         }
417         
418          
419         
420         // FIXME - we should be checking perms here...
421         //if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser))  {
422         //    $this->jerr("PERMISSION DENIED");
423         // }
424         // this should be doign update
425         $this->setFrom($ar);
426         
427         if (!isset($_FILES['imageUpload'])) {
428             return; // standard update...
429         }
430         
431         if ( !$this->onUpload($this)) {
432             $this->jerr("File upload failed");
433         }
434         $roo->addEvent("ADD", $this, $this->toEventString());
435         
436         $r = DB_DataObject::factory($this->tableName());
437         $r->id = $this->id;
438         $roo->loadMap($r);
439         $r->limit(1);
440         $r->find(true);
441         $roo->jok($r->toArray());
442          
443     }
444     function toEventString()
445     {
446         
447         //$p = DB_DataObject::factory($this->ontable);
448         //if (!is_$p) {
449         //    return "ERROR unknown table? {$this->ontable}";
450        // }
451         //$p->get($p->onid);
452         
453         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
454         //$p->toEventString();
455     }
456  }