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