DataObjects/core.sql
[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     function checkPerm($perm, $au)
35     {
36         // default permissons are to
37         // allow create / edit / if the user has
38         if (!$au) {
39             
40           
41             
42             return false;
43         }
44          
45         
46         
47         $o = $this->object();
48         //print_r($o);
49         if (method_exists($o, 'hasPerm')) {
50             // edit permissions on related object needed...
51             return $o->hasPerm( $perm == 'S' ? 'S' : 'E' , $au);
52             
53         }
54         
55         return true; //// ??? not really that safe...
56         
57     }
58     
59     
60     
61     
62     
63     
64     /**
65      * create an email from file.
66      * these must have been set first.
67      * ontable / onid.
68      * 
69      */
70     function createFrom($file, $filename=false)
71     {
72         // copy the file into the storage area..
73         if (!file_exists($file) || !filesize($file)) {
74             return false;
75         }
76         
77         $filename = empty($filename) ? $file : $filename;
78         
79         if (empty($this->mimetype)) {
80             require_once 'File/MimeType.php';
81             $y = new File_MimeType();
82             $this->mimetype = $y->fromFilename($filename);
83         }
84         
85         $this->mimetype= strtolower($this->mimetype);
86         
87         if (array_shift(explode('/', $this->mimetype)) == 'image') { 
88         
89             $imgs = @getimagesize($file);
90             
91             if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
92                 // it's a file!!!!
93             } else {
94                 list($this->width , $this->height)  = $imgs;
95             }
96         }
97         
98         $this->filesize = filesize($file);
99         $this->created = date('Y-m-d H:i:s');
100          
101         
102         if (empty($this->filename)) {
103             $this->filename = basename($filename);
104         }
105         
106         //DB_DataObject::debugLevel(1);
107         if (!$this->id) {
108             $this->insert();
109         } else {
110             $this->update();
111         }
112         
113         
114         
115         $f = $this->getStoreName();
116         $dest = dirname($f);
117         if (!file_exists($dest)) {
118             // currently this is 0775 due to problems using shared hosing (FTP)
119             // it makes all the files unaccessable..
120             // you can normally solve this by giving the storedirectory better perms
121             // if needed on a dedicated server..
122             $oldumask = umask(0);
123             mkdir($dest, 0775, true);
124             umask($oldumask);  
125         }
126         
127         copy($file,$f);
128         
129         // fill in details..
130         
131         /* thumbnails */
132         
133      
134        // $this->createThumbnail(0,50);
135         return true;
136         
137     }
138
139     /**
140      * Calculate target file name
141      *
142      * @return - target file name
143      */
144     function getStoreName() 
145     {
146         $opts = HTML_FlexyFramework::get()->Pman;
147         $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
148         return implode( '/', array(
149             $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
150         ));
151           
152     }
153
154      
155     /**
156      * deletes all the image instances of it...
157      * 
158      * 
159      */
160     function beforeDelete()
161     {
162         $fn = $this->getStoreName();
163         if (file_exists($fn)) {
164             unlink($fn);
165         }
166         // delete thumbs..
167         $b = basename($fn);
168         $d = dirname($fn);
169         if (file_exists($d)) {
170                 
171             $dh = opendir($d);
172             while (false !== ($fn = readdir($dh))) {
173                 if (substr($fn, 0, strlen($b)) == $b) {
174                     unlink($d. '/'. $fn);
175                 }
176             }
177         }
178         
179     }
180     /**
181      * check mimetype against type
182      * - eg. img.is(#image#)
183      *
184      */
185     function is($type)
186     {
187         if (empty($this->mimetype)) {
188             return false;
189         }
190         return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
191     }
192   
193     /**
194      * onUpload (singlely attached image to a table)
195      */
196     
197     function onUploadWithTbl($tbl,  $fld)
198     {
199         if ( $tbl->__table == 'Images') {
200             return; // not upload to self...
201         }
202         if (empty($_FILES['imageUpload']['tmp_name']) || 
203             empty($_FILES['imageUpload']['name']) || 
204             empty($_FILES['imageUpload']['type'])
205         ) {
206             return false;
207         }
208         if ($tbl->$fld) {
209             $image = DB_DataObject::factory('Images');
210             $image->get($tbl->$fld);
211             $image->beforeDelete();
212             $image->delete();
213         }
214         
215         $image = DB_DataObject::factory('Images');
216         $image->onid = $tbl->id;
217         $image->ontable = $tbl->__table;
218         $image->filename = $_FILES['imageUpload']['name']; 
219         $image->mimetype = $_FILES['imageUpload']['type'];
220        
221         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
222             return false;
223         }
224         $old = clone($tbl);
225         $tbl->$fld = $image->id;
226         $tbl->update($old);
227          
228     }
229     
230     // direct via roo...
231     function onUpload($ctrl)
232     {
233         
234         if (empty($_FILES['imageUpload']['tmp_name']) || 
235             empty($_FILES['imageUpload']['name']) || 
236             empty($_FILES['imageUpload']['type'])
237         ) {
238             $this->err = "Missing file details";
239             return false;
240         }
241         
242         if ($this->id) {
243             $this->beforeDelete();
244         }
245         if ( empty($this->ontable)) {
246             $this->err = "Missing  ontable";
247             return false;
248         }
249         
250         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
251             // then its an upload 
252             $img  = DB_DataObject::factory('Images');
253             $img->onid = $this->onid;
254             $img->ontable = $this->ontable;
255             $img->imgtype = $this->imgtype;
256             
257             $img->find();
258             while ($img->fetch()) {
259                 $img->beforeDelete();
260                 $img->delete();
261             }
262             
263         }
264         
265         
266         
267         require_once 'File/MimeType.php';
268         $y = new File_MimeType();
269         $this->mimetype = $_FILES['imageUpload']['type'];
270         if (in_array($this->mimetype, array('text/application', 'application/octet-stream'))) { // weird tyeps..
271             $inf = pathinfo($_FILES['imageUpload']['name']);
272             $this->mimetype  = $y->fromExt($inf['extension']);
273         }
274         
275         
276         $ext = $y->toExt(trim((string) $this->mimetype ));
277         
278         $this->filename = empty($this->filename) ? 
279             $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext); 
280         
281         
282         
283         if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
284             return false;
285         }
286         return true;
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       
352         if (!empty($req['query']['imagesize'])) {
353              $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : false;
354             
355             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
356             
357             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
358             
359             if (!empty($req['query']['imagesize'])) {
360                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
361             }
362         }
363         
364          
365          
366         return $ret;
367     }
368     
369     /**
370      * URL - create  a url for the image.
371      * size - use -1 to show full size.
372      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
373      * 
374      * 
375      */
376     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
377     {
378         if (!$this->id) {
379             return 'about:blank';
380             
381         }
382
383         $ff = HTML_FlexyFramework::get();
384         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
385         if (preg_match('#^http[s]*://#', $provider)) {
386             $baseURL = '';
387         }
388         
389         if ($size < 0) {
390             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
391         }
392         //-- max?
393         //$size = max(100, (int) $size);
394         //$size = min(1024, (int) $size);
395         
396         
397         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
398     }
399     /**
400      * size could be 123x345
401      * 
402      * 
403      */
404     function toHTML($size, $provider = '/Images/Thumb') 
405     {
406         
407         
408         
409         $sz = explode('x', $size);
410         $sx = $sz[0];
411         //var_dump($sz);
412         if (!$this->id || empty($this->width)) {
413             $this->height = $sx;
414             $this->width = empty($sz[1]) ? $sx : $sz[1];
415             $sy = $this->width ;
416         }
417         if (empty($sz[1])) {
418             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
419             $sy = $ratio * $sx;
420         } else {
421             $sy = $sz[1];
422         }
423         // create it?
424         
425         
426         return '<img src="' . $this->URL($size, $provider) . '" width="'. $sx . '" height="'. $sy . '">';
427         
428         
429     }
430     
431     /**
432      *
433      *
434      *
435      */
436     
437     
438     function setFromRoo($ar, $roo)
439     {
440         // not sure why we do this.. 
441         
442         
443         
444         
445         
446         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
447         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
448             $this->setFrom($ar);
449             $this->limit(1);
450             if ($this->find(true)) {
451                 $roo->old = clone($this);
452             }
453         }   
454             
455         
456         if (!empty($ar['_copy_from'])) {
457             
458             if (!$this->checkPerm( 'A' , $roo->authUser))  {
459                 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
460             }
461             
462             $copy = DB_DataObject::factory('Images');
463             $copy->get($ar['_copy_from']);
464             $this->setFrom($copy->toArray());
465             $this->setFrom($ar);
466             $this->createFrom($copy->getStoreName());
467             
468             $roo->addEvent("ADD", $this, $this->toEventString());
469             
470             $r = DB_DataObject::factory($this->tableName());
471             $r->id = $this->id;
472             $roo->loadMap($r);
473             $r->limit(1);
474             $r->find(true);
475             $roo->jok($r->toArray());
476             
477             
478         }
479         
480          
481         
482         // FIXME - we should be checking perms here...
483        
484         // this should be doign update
485         $this->setFrom($ar);
486          
487         if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser))  {
488             $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
489         }
490         
491         if (!isset($_FILES['imageUpload'])) {
492             return; // standard update...
493         }
494         
495         if ( !$this->onUpload($this)) {
496             $roo->jerr("File upload failed : ". $this->err);
497         }
498         
499         $roo->addEvent("ADD", $this, $this->toEventString());
500         
501         $r = DB_DataObject::factory($this->tableName());
502         $r->id = $this->id;
503         $roo->loadMap($r);
504         $r->limit(1);
505         $r->find(true);
506         $roo->jok($r->toArray());
507          
508     }
509     
510     function toEventString()
511     {
512         
513         //$p = DB_DataObject::factory($this->ontable);
514         //if (!is_$p) {
515         //    return "ERROR unknown table? {$this->ontable}";
516        // }
517         //$p->get($p->onid);
518         
519         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
520         //$p->toEventString();
521     }
522  }