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