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