c439432bb6787c6a569825f73cd27afdf9a79324
[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   
152     /**
153      * onUpload (singlely attached image to a table)
154      */
155     
156     function onUploadWithTbl($tbl,  $fld)
157     {
158         if ( $tbl->__table == 'Images') {
159             return; // not upload to self...
160         }
161         if (empty($_FILES['imageUpload']['tmp_name']) || 
162             empty($_FILES['imageUpload']['name']) || 
163             empty($_FILES['imageUpload']['type'])
164         ) {
165             return false;
166         }
167         if ($tbl->$fld) {
168             $image = DB_DataObject::factory('Images');
169             $image->get($tbl->$fld);
170             $image->beforeDelete();
171             $image->delete();
172         }
173         
174         $image = DB_DataObject::factory('Images');
175         $image->onid = $tbl->id;
176         $image->ontable = $tbl->__table;
177         $image->filename = $_FILES['imageUpload']['name']; 
178         $image->mimetype = $_FILES['imageUpload']['type'];
179        
180         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
181             return false;
182         }
183         $old = clone($tbl);
184         $tbl->$fld = $image->id;
185         $tbl->update($old);
186          
187     }
188     
189     // direct via roo...
190     function onUpload($ctrl)
191     {
192         
193         if (empty($_FILES['imageUpload']['tmp_name']) || 
194             empty($_FILES['imageUpload']['name']) || 
195             empty($_FILES['imageUpload']['type'])
196         ) {
197             $this->err = "Missing file details";
198             return false;
199         }
200         
201         if ($this->id) {
202             $this->beforeDelete();
203         }
204         if ( empty($this->ontable)) {
205             $this->err = "Missing  ontable";
206             return false;
207         }
208         
209         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
210             // then its an upload 
211             $img  = DB_DataObject::factory('Images');
212             $img->onid = $this->onid;
213             $img->ontable = $this->ontable;
214             $img->imgtype = $this->imgtype;
215             
216             $img->find();
217             while ($img->fetch()) {
218                 $img->beforeDelete();
219                 $img->delete();
220             }
221             
222         }
223         
224         
225         
226         require_once 'File/MimeType.php';
227         $y = new File_MimeType();
228         $this->mimetype = $_FILES['imageUpload']['type'];
229         if (in_array($this->mimetype, array('text/application', 'application/octet-stream'))) { // weird tyeps..
230             $inf = pathinfo($_FILES['imageUpload']['name']);
231             $this->mimetype  = $y->fromExt($inf['extension']);
232         }
233         
234         
235         $ext = $y->toExt(trim((string) $this->mimetype ));
236         
237         $this->filename = empty($this->filename) ? 
238             $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext); 
239         
240         
241         
242         if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
243             return false;
244         }
245         return true;
246          
247     }
248      
249     /**
250      * return a list of images for an object, optionally with a mime regex.
251      * eg. '%/pdf' or 'image/%'
252      */
253     function gather($obj, $mime_like='')
254     {
255         //DB_DataObject::debugLevel(1);
256         if (empty($obj->id)) {
257             return array();
258         }
259         
260         $c = clone($this);
261         $c->ontable = $obj->tableName();
262         $c->onid = $obj->id;
263         $c->autoJoin();
264         if (!empty($mime_like)) {
265             $c->whereAdd("mimetype LIKE '". $c->escape($mime_like) ."'");
266         }
267
268         return $c->fetchAll();
269     }
270     /**
271      * creation - associate this image with a dataobject
272      * - currently assumes id is the key column
273      * @param DB_DataObject $obj a dataobject
274      */
275     function associate($obj)
276     {
277         $this->ontable = $obj->tableName();
278         $this->onid = $obj->id; /// assumes our nice standard of using ids..
279         
280     }
281     
282     /**
283     * set or get the dataobject this image is associated with
284     * @param DB_DataObject $obj An object to associate this image with
285     *        (does not store it - you need to call update() to do that)
286     * @return DB_DataObject the dataobject this image is attached to.
287      */
288     function object($obj=false)
289     {
290         if ($obj === false) {
291             $ret = DB_DataObject::factory($this->ontable);
292             $ret->get($this->onid);
293             return $ret;
294         }
295         $this->ontable = $obj->tableName();
296         $this->onid = $obj->id; /// assumes our nice standard of using ids..
297         return $obj;
298     }
299     
300      
301     function toRooArray($req = array()) {
302       //  echo '<PRE>';print_r($req);exit;
303         $ret= $this->toArray();
304       
305       
306         if (!empty($req['query']['imagesize'])) {
307              $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : false;
308             
309             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
310             
311             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
312             
313             if (!empty($req['query']['imagesize'])) {
314                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
315             }
316         }
317         
318          
319          
320         return $ret;
321     }
322     
323     /**
324      * URL - create  a url for the image.
325      * size - use -1 to show full size.
326      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
327      * 
328      * 
329      */
330     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
331     {
332         if (!$this->id) {
333             return 'about:blank';
334             
335         }
336
337         $ff = HTML_FlexyFramework::get();
338         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
339         if ($size < 0) {
340             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
341         }
342         //-- max?
343         //$size = max(100, (int) $size);
344         //$size = min(1024, (int) $size);
345         
346         
347         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
348     }
349     /**
350      * size could be 123x345
351      * 
352      * 
353      */
354     function toHTML($size, $provider = '/Images/Thumb') 
355     {
356         
357         
358         
359         $sz = explode('x', $size);
360         $sx = $sz[0];
361         //var_dump($sz);
362         if (!$this->id || empty($this->width)) {
363             $this->height = $sx;
364             $this->width = empty($sz[1]) ? $sx : $sz[1];
365             $sy = $this->width ;
366         }
367         if (empty($sz[1])) {
368             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
369             $sy = $ratio * $sx;
370         } else {
371             $sy = $sz[1];
372         }
373         // create it?
374         
375         
376         return '<img src="' . $this->URL($size, $provider) . '" width="'. $sx . '" height="'. $sy . '">';
377         
378         
379     }
380     
381     
382     
383     
384     function setFromRoo($ar, $roo)
385     {
386         // not sure why we do this.. 
387         
388         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
389         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
390             $this->setFrom($ar);
391             $this->limit(1);
392             if ($this->find(true)) {
393                 $roo->old = clone($this);
394             }
395         }   
396             
397         
398         if (!empty($ar['_copy_from'])) {
399             $copy = DB_DataObject::factory('Images');
400             $copy->get($ar['_copy_from']);
401             $this->setFrom($copy->toArray());
402             $this->setFrom($ar);
403             $this->createFrom($copy->getStoreName());
404             
405             $roo->addEvent("ADD", $this, $this->toEventString());
406             
407             $r = DB_DataObject::factory($this->tableName());
408             $r->id = $this->id;
409             $roo->loadMap($r);
410             $r->limit(1);
411             $r->find(true);
412             $roo->jok($r->toArray());
413             
414             
415         }
416         
417          
418         
419         // FIXME - we should be checking perms here...
420         //if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser))  {
421         //    $this->jerr("PERMISSION DENIED");
422         // }
423         // this should be doign update
424         $this->setFrom($ar);
425         
426         if (!isset($_FILES['imageUpload'])) {
427             return; // standard update...
428         }
429         
430         if ( !$this->onUpload($this)) {
431             $this->jerr("File upload failed");
432         }
433         $roo->addEvent("ADD", $this, $this->toEventString());
434         
435         $r = DB_DataObject::factory($this->tableName());
436         $r->id = $this->id;
437         $roo->loadMap($r);
438         $r->limit(1);
439         $r->find(true);
440         $roo->jok($r->toArray());
441          
442     }
443     function toEventString()
444     {
445         
446         //$p = DB_DataObject::factory($this->ontable);
447         //if (!is_$p) {
448         //    return "ERROR unknown table? {$this->ontable}";
449        // }
450         //$p->get($p->onid);
451         
452         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
453         //$p->toEventString();
454     }
455  }