DataObjects/Images.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     /* the code above is auto generated do not remove the tag below */
31     ###END_AUTOCODE
32     
33     function checkPerm($perm, $au)
34     {
35         // default permissons are to
36         // allow create / edit / if the user has
37         
38         if (!$au) {
39             
40           
41             
42             return false;
43         }
44         
45         $o = $this->object();
46         //print_r($o);
47         if (method_exists($o, 'hasPerm')) {
48             // edit permissions on related object needed...
49             return $o->hasPerm( $perm == 'S' ? 'S' : 'E' , $au);
50             
51         }
52         
53         return true; //// ??? not really that safe...
54         
55     }
56     
57     function beforeInsert($q, $roo) 
58     {
59         if (isset($q['_remote_upload'])) {
60             require_once 'System.php';
61             
62             $tmpdir  = System::mktemp("-d remote_upload");
63             
64             $path = $tmpdir . '/' . basename($q['_remote_upload']);
65             
66             if(!file_exists($path)){
67                file_put_contents($path, file_get_contents($q['_remote_upload'])); 
68             }
69             
70             $imageInfo = getimagesize($path);
71             
72             require_once 'File/MimeType.php';
73             $y = new File_MimeType();
74             $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
75             
76             if (!preg_match("/\." . $ext."$/", $path, $matches)) {
77                 rename($path,$path.".".$ext);
78                 $path.= ".".$ext;
79             }
80             
81             if (!$this->createFrom($path)) {
82                 $roo->jerr("erro making image" . $q['_remote_upload']);
83             }
84             
85             if(!empty($q['_return_after_create'])){
86                 return;
87             }
88             
89             $roo->addEvent("ADD", $this, $this->toEventString());
90         
91             $r = DB_DataObject::factory($this->tableName());
92             $r->id = $this->id;
93             $roo->loadMap($r);
94             $r->limit(1);
95             $r->find(true);
96             $roo->jok($r->URL(-1,'/Images') . '#attachment-'.  $r->id);
97         }
98         
99         if(isset($q['_auto_save'])){
100             require_once 'System.php';
101             
102             $tmpdir  = System::mktemp("-d auto_save");
103             
104             $path = $tmpdir . '/' . time();
105             
106             $source = array(
107                 'source' => $q['_source']
108             );
109             print_r(json_encode($source));exit;
110 //            if(!file_exists($path)){
111 //               file_put_contents($path, $q['_source']); 
112 //            }
113 //            
114 //            $this->setFrom($q);
115 //            
116 //            if (!$this->createFrom($path)) {
117 //                $roo->jerr("error on auto save making image");
118 //            }
119 //            
120 //            $roo->addEvent("AUTOSAVE", $this, $this->toEventString());
121             
122             $this->jok("OK");
123         }
124         
125     }
126     
127      
128     /**
129      * create an email from file.
130      * these must have been set first.
131      * ontable / onid.
132      * 
133      */
134     function createFrom($file, $filename=false)
135     {
136         // copy the file into the storage area..
137         if (!file_exists($file) || !filesize($file)) {
138             return false;
139         }
140         
141         $filename = empty($filename) ? $file : $filename;
142         
143         if (empty($this->mimetype)) {
144             require_once 'File/MimeType.php';
145             $y = new File_MimeType();
146             $this->mimetype = $y->fromFilename($filename);
147         }
148         
149         $this->mimetype= strtolower($this->mimetype);
150         
151         if (array_shift(explode('/', $this->mimetype)) == 'image') { 
152         
153             $imgs = @getimagesize($file);
154             
155             if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
156                 // it's a file!!!!
157             } else {
158                 list($this->width , $this->height)  = $imgs;
159             }
160         }
161         
162         $this->filesize = filesize($file);
163         $this->created = date('Y-m-d H:i:s');
164          
165         
166         if (empty($this->filename)) {
167             $this->filename = basename($filename);
168         }
169         
170         //DB_DataObject::debugLevel(1);
171         if (!$this->id) {
172             $this->insert();
173         } else {
174             $this->update();
175         }
176         
177         
178         
179         $f = $this->getStoreName();
180         $dest = dirname($f);
181         if (!file_exists($dest)) {
182             // currently this is 0775 due to problems using shared hosing (FTP)
183             // it makes all the files unaccessable..
184             // you can normally solve this by giving the storedirectory better perms
185             // if needed on a dedicated server..
186             $oldumask = umask(0);
187             mkdir($dest, 0775, true);
188             umask($oldumask);  
189         }
190         
191         copy($file,$f);
192         
193         // fill in details..
194         
195         /* thumbnails */
196         
197      
198        // $this->createThumbnail(0,50);
199         return true;
200         
201     }
202
203     /**
204      * Calculate target file name
205      *
206      * @return - target file name
207      */
208     function getStoreName() 
209     {
210         $opts = HTML_FlexyFramework::get()->Pman;
211         $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
212         return implode( '/', array(
213             $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
214         ));
215           
216     }
217      
218     /**
219      * deletes all the image instances of it...
220      * 
221      * 
222      */
223     function beforeDelete()
224     {
225         $fn = $this->getStoreName();
226         if (file_exists($fn)) {
227             unlink($fn);
228         }
229         // delete thumbs..
230         $b = basename($fn);
231         $d = dirname($fn);
232         if (file_exists($d)) {
233                 
234             $dh = opendir($d);
235             while (false !== ($fn = readdir($dh))) {
236                 if (substr($fn, 0, strlen($b)) == $b) {
237                     unlink($d. '/'. $fn);
238                 }
239             }
240         }
241         
242     }
243     /**
244      * check mimetype against type
245      * - eg. img.is(#image#)
246      *
247      */
248     function is($type)
249     {
250         if (empty($this->mimetype)) {
251             return false;
252         }
253         return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
254     }
255   
256     /**
257      * onUpload (singlely attached image to a table)
258      */
259     
260     function onUploadWithTbl($tbl,  $fld)
261     {
262         if ( $tbl->__table == 'Images') {
263             return; // not upload to self...
264         }
265         if (empty($_FILES['imageUpload']['tmp_name']) || 
266             empty($_FILES['imageUpload']['name']) || 
267             empty($_FILES['imageUpload']['type'])
268         ) {
269             return false;
270         }
271         if ($tbl->$fld) {
272             $image = DB_DataObject::factory('Images');
273             $image->get($tbl->$fld);
274             $image->beforeDelete();
275             $image->delete();
276         }
277         
278         $image = DB_DataObject::factory('Images');
279         $image->onid = $tbl->id;
280         $image->ontable = $tbl->__table;
281         $image->filename = $_FILES['imageUpload']['name']; 
282         $image->mimetype = $_FILES['imageUpload']['type'];
283        
284         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
285             return false;
286         }
287         $old = clone($tbl);
288         $tbl->$fld = $image->id;
289         $tbl->update($old);
290          
291     }
292     
293     // direct via roo...
294     /// ctrl not used??
295     function onUpload($roo)
296     {
297 //        echo $_FILES['imageUpload']['type'];exit;
298         if (empty($_FILES['imageUpload']['tmp_name']) || 
299             empty($_FILES['imageUpload']['name']) || 
300             empty($_FILES['imageUpload']['type'])
301         ) {
302             $this->err = "Missing file details";
303             return false;
304         }
305         
306         if ($this->id) {
307             $this->beforeDelete();
308         }
309         if ( empty($this->ontable)) {
310             $this->err = "Missing  ontable";
311             return false;
312         }
313         
314         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
315             // then its an upload 
316             $img  = DB_DataObject::factory('Images');
317             $img->onid = $this->onid;
318             $img->ontable = $this->ontable;
319             $img->imgtype = $this->imgtype;
320             
321             $img->find();
322             while ($img->fetch()) {
323                 $img->beforeDelete();
324                 $img->delete();
325             }
326             
327         }
328         
329         
330         
331         require_once 'File/MimeType.php';
332         $y = new File_MimeType();
333         $this->mimetype = $_FILES['imageUpload']['type'];
334         if (in_array($this->mimetype, array(
335                         'text/application',
336                         'application/octet-stream',
337                         'image/x-png',  // WTF does this?
338                         'image/pjpeg',  // WTF does this?
339                         'application/x-apple-msg-attachment', /// apple doing it's magic...
340                         'application/vnd.ms-excel',   /// sometimes windows reports csv as excel???
341                         'application/csv-tab-delimited-table', // windows again!!?
342                 ))) { // weird tyeps..
343             $inf = pathinfo($_FILES['imageUpload']['name']);
344             $this->mimetype  = $y->fromExt($inf['extension']);
345         }
346         
347         
348         $ext = $y->toExt(trim((string) $this->mimetype ));
349         
350         $this->filename = empty($this->filename) ? 
351             $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext); 
352         
353         
354         
355         if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
356             return false;
357         }
358         return true;
359          
360     }
361      
362     
363     
364     /**
365      * return a list of images for an object, optionally with a mime regex.
366      * eg. '%/pdf' or 'image/%'
367      *
368      * usage:
369      *
370      * $i = DB_DataObject::factory('Images');
371      * $i->imgtype = 'LOGO';
372      * $ar = $i->gather($somedataobject, 'image/%');
373      * 
374      * @param {DB_DataObject} dataobject  = the object to gather data on.
375      * @param {String} mimelike  LIKE query to use for search
376      
377      */
378     function gather($obj, $mime_like='', $opts=array())
379     {
380         //DB_DataObject::debugLevel(1);
381         if (empty($obj->id)) {
382             return array();
383         }
384         
385         $c = clone($this);
386         $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
387         $c->onid = $obj->id;
388         $c->autoJoin();
389         if (!empty($mime_like)) {
390             $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
391         }
392
393         return $c->fetchAll();
394     }
395      
396     
397     /**
398     * set or get the dataobject this image is associated with
399     * @param DB_DataObject $obj An object to associate this image with
400     *        (does not store it - you need to call update() to do that)
401     * @return DB_DataObject the dataobject this image is attached to.
402     */
403     function object($obj=false)
404     {
405         if ($obj === false) {
406             if (empty($this->ontable) || empty($this->onid)) {
407                 return false;
408             }
409             $ret = DB_DataObject::factory($this->ontable);
410             $ret->get($this->onid);
411             return $ret;
412         }
413         
414         
415         $this->ontable = $obj->tableName();
416         $this->onid = $obj->id; /// assumes our nice standard of using ids..
417         return $obj;
418     }
419     
420      
421     function toRooArray($req = array()) {
422       //  echo '<PRE>';print_r($req);exit;
423         $ret= $this->toArray();
424       
425         static $ff = false;
426         if (!$ff) {
427             $ff = HTML_FlexyFramework::get();
428         }
429         
430         $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
431                     $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
432         
433         if (!empty($req['query']['imagesize'])) {
434              $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : false;
435             
436             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
437             
438             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
439             
440             if (!empty($req['query']['imagesize'])) {
441                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
442             }
443         }
444         
445          
446          
447         return $ret;
448     }
449     
450     /**
451      * URL - create  a url for the image.
452      * size - use -1 to show full size.
453      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
454      * 
455      * 
456      */
457     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
458     {
459         if (!$this->id) {
460             return 'about:blank';
461             
462         }
463
464         $ff = HTML_FlexyFramework::get();
465         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
466         if (preg_match('#^http[s]*://#', $provider)) {
467             $baseURL = '';
468         }
469        
470         if ($size < 0) {
471             $provider = preg_replace('#/Thumb$#', '', $provider);
472             
473             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
474         }
475         //-- max?
476         //$size = max(100, (int) $size);
477         //$size = min(1024, (int) $size);
478         // the size should 200x150 to convert
479         $sizear = preg_split('/(x|c)/', $size);
480         if(empty($sizear[1])){
481             $sizear[1] = 0;
482         }
483         $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
484 //        print_r($size);
485         $fc = $this->toFileConvert();
486 //        print_r($size);
487 //        exit;
488         $fc->convert($this->mimetype, $size);
489         
490         
491         return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
492     }
493     /**
494      * size could be 123x345
495      * 
496      * 
497      */
498     function toHTML($size, $provider = '/Images/Thumb') 
499     {
500         
501         
502         
503         $sz = explode('x', $size);
504         $sx = $sz[0];
505         //var_dump($sz);
506         if (!$this->id || empty($this->width)) {
507             $this->height = $sx;
508             $this->width = empty($sz[1]) ? $sx : $sz[1];
509             $sy = $this->width ;
510         }
511         if (empty($sz[1])) {
512             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
513             $sy = $ratio * $sx;
514         } else {
515             $sy = $sz[1];
516         }
517         // create it?
518         $extra = '';
519         if (strlen($this->title)) {
520             $extra = ' title="'. htmlspecialchars($this->title) . '"';
521         }
522         
523         return '<img src="' . $this->URL($size, $provider) . '"' .
524                 $extra .
525                 ' width="'. $sx . '"' .
526                 ' height="'. $sy . '">';
527         
528         
529     }
530     
531     /**
532      * 
533      * #2142 [new] CMS - image link urls
534      * 
535      * 
536      * 
537      */
538     function toLinkHTML($size, $provider = '/Images/Thumb')
539     {
540         if(empty($this->linkurl)){
541             return $this->toHTML($size, $provider = '/Images/Thumb');
542         }
543         
544         return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
545         
546     }
547     
548     
549     /**
550      * to Fileconvert object..
551      *
552      *
553      *
554      */
555     function toFileConvert()
556     {
557         require_once 'File/Convert.php';
558         $fc = new File_Convert($this->getStoreName(), $this->mimetype);
559         return $fc;
560         
561     }
562     
563     function fileExt()
564     {
565         require_once 'File/MimeType.php';
566         
567         $y = new File_MimeType();
568         return  $y->toExt($this->mimetype);
569         
570         
571     }
572     
573     /**
574      *
575      *
576      *
577      */
578     
579     
580     function setFromRoo($ar, $roo)
581     {
582         // not sure why we do this.. 
583         
584         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
585         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
586             $this->setFrom($ar);
587             $this->limit(1);
588             if ($this->find(true)) {
589                 $roo->old = clone($this);
590             }
591         }   
592             
593         
594         if (!empty($ar['_copy_from'])) {
595             
596             if (!$this->checkPerm( 'A' , $roo->authUser))  {
597                 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
598             }
599             
600             $copy = DB_DataObject::factory('Images');
601             $copy->get($ar['_copy_from']);
602             $this->setFrom($copy->toArray());
603             $this->setFrom($ar);
604             $this->createFrom($copy->getStoreName());
605             
606             $roo->addEvent("ADD", $this, $this->toEventString());
607             
608             $r = DB_DataObject::factory($this->tableName());
609             $r->id = $this->id;
610             $roo->loadMap($r);
611             $r->limit(1);
612             $r->find(true);
613             $roo->jok($r->toArray());
614             
615             
616         }
617         
618          
619         
620         // FIXME - we should be checking perms here...
621        
622         // this should be doign update
623         $this->setFrom($ar);
624          
625         if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser))  {
626             $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
627         }
628         
629         
630         
631         if (!isset($_FILES['imageUpload'])) {
632             return; // standard update...
633         }
634         
635         
636 //        print_r(!$this->onUpload($this));
637         
638         if ( !$this->onUpload($this)) { 
639             $roo->jerr("File upload failed : ". (!empty($this->err) ? $this->err : ''));
640         }
641         
642         $roo->addEvent("ADD", $this, $this->toEventString());
643         
644         $r = DB_DataObject::factory($this->tableName());
645         $r->id = $this->id;
646         $roo->loadMap($r);
647         $r->limit(1);
648         $r->find(true);
649         $roo->jok($r->toArray());
650          
651     }
652     
653     function toEventString()
654     {
655         
656         //$p = DB_DataObject::factory($this->ontable);
657         //if (!is_$p) {
658         //    return "ERROR unknown table? {$this->ontable}";
659        // }
660         //$p->get($p->onid);
661         
662         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
663         //$p->toEventString();
664     }
665     
666  }