fix up cli
[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         
39         if (!$au) {
40             
41           
42             
43             return false;
44         }
45         
46         $o = $this->object();
47         //print_r($o);
48         if (method_exists($o, 'hasPerm')) {
49             // edit permissions on related object needed...
50             return $o->hasPerm( $perm == 'S' ? 'S' : 'E' , $au);
51             
52         }
53         
54         return true; //// ??? not really that safe...
55         
56     }
57     
58     
59     
60     
61     
62     
63     /**
64      * create an email from file.
65      * these must have been set first.
66      * ontable / onid.
67      * 
68      */
69     function createFrom($file, $filename=false)
70     {
71         // copy the file into the storage area..
72         if (!file_exists($file) || !filesize($file)) {
73             return false;
74         }
75         
76         $filename = empty($filename) ? $file : $filename;
77         
78         if (empty($this->mimetype)) {
79             require_once 'File/MimeType.php';
80             $y = new File_MimeType();
81             $this->mimetype = $y->fromFilename($filename);
82         }
83         
84         $this->mimetype= strtolower($this->mimetype);
85         
86         if (array_shift(explode('/', $this->mimetype)) == 'image') { 
87         
88             $imgs = @getimagesize($file);
89             
90             if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
91                 // it's a file!!!!
92             } else {
93                 list($this->width , $this->height)  = $imgs;
94             }
95         }
96         
97         $this->filesize = filesize($file);
98         $this->created = date('Y-m-d H:i:s');
99          
100         
101         if (empty($this->filename)) {
102             $this->filename = basename($filename);
103         }
104         
105         //DB_DataObject::debugLevel(1);
106         if (!$this->id) {
107             $this->insert();
108         } else {
109             $this->update();
110         }
111         
112         
113         
114         $f = $this->getStoreName();
115         $dest = dirname($f);
116         if (!file_exists($dest)) {
117             // currently this is 0775 due to problems using shared hosing (FTP)
118             // it makes all the files unaccessable..
119             // you can normally solve this by giving the storedirectory better perms
120             // if needed on a dedicated server..
121             $oldumask = umask(0);
122             mkdir($dest, 0775, true);
123             umask($oldumask);  
124         }
125         
126         copy($file,$f);
127         
128         // fill in details..
129         
130         /* thumbnails */
131         
132      
133        // $this->createThumbnail(0,50);
134         return true;
135         
136     }
137
138     /**
139      * Calculate target file name
140      *
141      * @return - target file name
142      */
143     function getStoreName() 
144     {
145         $opts = HTML_FlexyFramework::get()->Pman;
146         $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
147         return implode( '/', array(
148             $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
149         ));
150           
151     }
152
153      
154     /**
155      * deletes all the image instances of it...
156      * 
157      * 
158      */
159     function beforeDelete()
160     {
161         $fn = $this->getStoreName();
162         if (file_exists($fn)) {
163             unlink($fn);
164         }
165         // delete thumbs..
166         $b = basename($fn);
167         $d = dirname($fn);
168         if (file_exists($d)) {
169                 
170             $dh = opendir($d);
171             while (false !== ($fn = readdir($dh))) {
172                 if (substr($fn, 0, strlen($b)) == $b) {
173                     unlink($d. '/'. $fn);
174                 }
175             }
176         }
177         
178     }
179     /**
180      * check mimetype against type
181      * - eg. img.is(#image#)
182      *
183      */
184     function is($type)
185     {
186         if (empty($this->mimetype)) {
187             return false;
188         }
189         return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
190     }
191   
192     /**
193      * onUpload (singlely attached image to a table)
194      */
195     
196     function onUploadWithTbl($tbl,  $fld)
197     {
198         if ( $tbl->__table == 'Images') {
199             return; // not upload to self...
200         }
201         if (empty($_FILES['imageUpload']['tmp_name']) || 
202             empty($_FILES['imageUpload']['name']) || 
203             empty($_FILES['imageUpload']['type'])
204         ) {
205             return false;
206         }
207         if ($tbl->$fld) {
208             $image = DB_DataObject::factory('Images');
209             $image->get($tbl->$fld);
210             $image->beforeDelete();
211             $image->delete();
212         }
213         
214         $image = DB_DataObject::factory('Images');
215         $image->onid = $tbl->id;
216         $image->ontable = $tbl->__table;
217         $image->filename = $_FILES['imageUpload']['name']; 
218         $image->mimetype = $_FILES['imageUpload']['type'];
219        
220         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
221             return false;
222         }
223         $old = clone($tbl);
224         $tbl->$fld = $image->id;
225         $tbl->update($old);
226          
227     }
228     
229     // direct via roo...
230     /// ctrl not used??
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     
292     /**
293      * return a list of images for an object, optionally with a mime regex.
294      * eg. '%/pdf' or 'image/%'
295      *
296      * usage:
297      *
298      * $i = DB_DataObject::factory('Images');
299      * $i->imgtype = 'LOGO';
300      * $ar = $i->gather($somedataobject, 'image/%');
301      * 
302      * @param {DB_DataObject} dataobject  = the object to gather data on.
303      * @param {String} mimelike  LIKE query to use for search
304      
305      */
306     function gather($obj, $mime_like='', $opts=array())
307     {
308         //DB_DataObject::debugLevel(1);
309         if (empty($obj->id)) {
310             return array();
311         }
312         
313         $c = clone($this);
314         $c->ontable = $obj->tableName();
315         $c->onid = $obj->id;
316         $c->autoJoin();
317         if (!empty($mime_like)) {
318             $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
319         }
320
321         return $c->fetchAll();
322     }
323      
324     
325     /**
326     * set or get the dataobject this image is associated with
327     * @param DB_DataObject $obj An object to associate this image with
328     *        (does not store it - you need to call update() to do that)
329     * @return DB_DataObject the dataobject this image is attached to.
330     */
331     function object($obj=false)
332     {
333         if ($obj === false) {
334             if (empty($this->ontable) || empty($this->onid)) {
335                 return false;
336             }
337             $ret = DB_DataObject::factory($this->ontable);
338             $ret->get($this->onid);
339             return $ret;
340         }
341         
342         
343         $this->ontable = $obj->tableName();
344         $this->onid = $obj->id; /// assumes our nice standard of using ids..
345         return $obj;
346     }
347     
348      
349     function toRooArray($req = array()) {
350       //  echo '<PRE>';print_r($req);exit;
351         $ret= $this->toArray();
352       
353         static $ff = false;
354         if (!$ff) {
355             $ff = HTML_FlexyFramework::get();
356         }
357         
358         $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
359                     $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
360         
361         if (!empty($req['query']['imagesize'])) {
362              $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : false;
363             
364             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
365             
366             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
367             
368             if (!empty($req['query']['imagesize'])) {
369                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
370             }
371         }
372         
373          
374          
375         return $ret;
376     }
377     
378     /**
379      * URL - create  a url for the image.
380      * size - use -1 to show full size.
381      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
382      * 
383      * 
384      */
385     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
386     {
387         if (!$this->id) {
388             return 'about:blank';
389             
390         }
391
392         $ff = HTML_FlexyFramework::get();
393         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
394         if (preg_match('#^http[s]*://#', $provider)) {
395             $baseURL = '';
396         }
397        
398         if ($size < 0) {
399             $provider = preg_replace('#/Thumb$#', '', $provider);
400             
401             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
402         }
403         //-- max?
404         //$size = max(100, (int) $size);
405         //$size = min(1024, (int) $size);
406         
407         
408         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
409     }
410     /**
411      * size could be 123x345
412      * 
413      * 
414      */
415     function toHTML($size, $provider = '/Images/Thumb') 
416     {
417         
418         
419         
420         $sz = explode('x', $size);
421         $sx = $sz[0];
422         //var_dump($sz);
423         if (!$this->id || empty($this->width)) {
424             $this->height = $sx;
425             $this->width = empty($sz[1]) ? $sx : $sz[1];
426             $sy = $this->width ;
427         }
428         if (empty($sz[1])) {
429             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
430             $sy = $ratio * $sx;
431         } else {
432             $sy = $sz[1];
433         }
434         // create it?
435          
436         return '<img src="' . $this->URL($size, $provider) . '" width="'. $sx . '" height="'. $sy . '">';
437         
438         
439     }
440      
441     /**
442      * to Fileconvert object..
443      *
444      *
445      *
446      */
447     function toFileConvert()
448     {
449         require_once 'File/Convert.php';
450         $fc = new File_Convert($this->getStoreName(), $this->mimetype);
451         return $fc;
452         
453     }
454     /**
455      *
456      *
457      *
458      */
459     
460     
461     function setFromRoo($ar, $roo)
462     {
463         // not sure why we do this.. 
464         
465         
466         
467         
468         
469         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
470         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
471             $this->setFrom($ar);
472             $this->limit(1);
473             if ($this->find(true)) {
474                 $roo->old = clone($this);
475             }
476         }   
477             
478         
479         if (!empty($ar['_copy_from'])) {
480             
481             if (!$this->checkPerm( 'A' , $roo->authUser))  {
482                 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
483             }
484             
485             $copy = DB_DataObject::factory('Images');
486             $copy->get($ar['_copy_from']);
487             $this->setFrom($copy->toArray());
488             $this->setFrom($ar);
489             $this->createFrom($copy->getStoreName());
490             
491             $roo->addEvent("ADD", $this, $this->toEventString());
492             
493             $r = DB_DataObject::factory($this->tableName());
494             $r->id = $this->id;
495             $roo->loadMap($r);
496             $r->limit(1);
497             $r->find(true);
498             $roo->jok($r->toArray());
499             
500             
501         }
502         
503          
504         
505         // FIXME - we should be checking perms here...
506        
507         // this should be doign update
508         $this->setFrom($ar);
509          
510         if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser))  {
511             $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
512         }
513         
514         if (!isset($_FILES['imageUpload'])) {
515             return; // standard update...
516         }
517         
518         if ( !$this->onUpload($this)) {
519             $roo->jerr("File upload failed : ". $this->err);
520         }
521         
522         $roo->addEvent("ADD", $this, $this->toEventString());
523         
524         $r = DB_DataObject::factory($this->tableName());
525         $r->id = $this->id;
526         $roo->loadMap($r);
527         $r->limit(1);
528         $r->find(true);
529         $roo->jok($r->toArray());
530          
531     }
532     
533     function toEventString()
534     {
535         
536         //$p = DB_DataObject::factory($this->ontable);
537         //if (!is_$p) {
538         //    return "ERROR unknown table? {$this->ontable}";
539        // }
540         //$p->get($p->onid);
541         
542         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
543         //$p->toEventString();
544     }
545  }