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         return implode( '/', array(
189             $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
190         ));
191           
192     }
193      
194     /**
195      * deletes all the image instances of it...
196      * 
197      * 
198      */
199     function beforeDelete()
200     {
201         $fn = $this->getStoreName();
202         if (file_exists($fn)) {
203             unlink($fn);
204         }
205         // delete thumbs..
206         $b = basename($fn);
207         $d = dirname($fn);
208         if (file_exists($d)) {
209                 
210             $dh = opendir($d);
211             while (false !== ($fn = readdir($dh))) {
212                 if (substr($fn, 0, strlen($b)) == $b) {
213                     unlink($d. '/'. $fn);
214                 }
215             }
216         }
217         
218     }
219     /**
220      * check mimetype against type
221      * - eg. img.is(#image#)
222      *
223      */
224     function is($type)
225     {
226         if (empty($this->mimetype)) {
227             return false;
228         }
229         return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
230     }
231   
232     /**
233      * onUpload (singlely attached image to a table)
234      */
235     
236     function onUploadWithTbl($tbl,  $fld)
237     {
238         if ( $tbl->__table == 'Images') {
239             return; // not upload to self...
240         }
241         if (empty($_FILES['imageUpload']['tmp_name']) || 
242             empty($_FILES['imageUpload']['name']) || 
243             empty($_FILES['imageUpload']['type'])
244         ) {
245             return false;
246         }
247         if ($tbl->$fld) {
248             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
249             exit;
250             $image = DB_DataObject::factory('Images');
251             $image->get($tbl->$fld);
252             $image->beforeDelete();
253             $image->delete();
254         }
255         
256         $image = DB_DataObject::factory('Images');
257         $image->onid = $tbl->id;
258         $image->ontable = $tbl->__table;
259         $image->filename = $_FILES['imageUpload']['name']; 
260         $image->mimetype = $_FILES['imageUpload']['type'];
261        
262         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
263             return false;
264         }
265         $old = clone($tbl);
266         $tbl->$fld = $image->id;
267         $tbl->update($old);
268          
269     }
270     
271     // direct via roo...
272     /// ctrl not used??
273     function onUpload($roo)
274     {
275         //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
276         if (empty($_FILES['imageUpload']['tmp_name']) || 
277             empty($_FILES['imageUpload']['name']) || 
278             empty($_FILES['imageUpload']['type'])
279         ) {
280             
281             $emap = array( 
282                 0=>"There is no error, the file uploaded with success", 
283                 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
284                 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
285                 3=>"The uploaded file was only partially uploaded",
286                 4=>"No file was uploaded",
287                 6=>"Missing a temporary folder" 
288             ); 
289             $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
290             $this->err = "Missing file details : Error=". $estr;
291             return false;
292         }
293         
294         if ($this->id) {
295             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
296             exit;
297             $this->beforeDelete();
298         }
299         if ( empty($this->ontable)) {
300             $this->err = "Missing  ontable";
301             return false;
302         }
303         
304         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
305             // then its an upload 
306             $img  = DB_DataObject::factory('Images');
307             $img->onid = $this->onid;
308             $img->ontable = $this->ontable;
309             $img->imgtype = $this->imgtype;
310             
311             $img->find();
312             while ($img->fetch()) {
313                 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
314                 exit;
315                 $img->beforeDelete();
316                 $img->delete();
317             }
318             
319         }
320         
321         
322         
323         require_once 'File/MimeType.php';
324         $y = new File_MimeType();
325         $this->mimetype = $_FILES['imageUpload']['type'];
326         if (in_array($this->mimetype, array(
327                         'text/application',
328                         'application/octet-stream',
329                         'image/x-png',  // WTF does this?
330                         'image/pjpeg',  // WTF does this?
331                         'application/x-apple-msg-attachment', /// apple doing it's magic...
332                         'application/vnd.ms-excel',   /// sometimes windows reports csv as excel???
333                         'application/csv-tab-delimited-table', // windows again!!?
334                 ))) { // weird tyeps..
335             $inf = pathinfo($_FILES['imageUpload']['name']);
336             $this->mimetype  = $y->fromExt($inf['extension']);
337         }
338         
339         
340         $ext = $y->toExt(trim((string) $this->mimetype ));
341         
342         $this->filename = empty($this->filename) ? 
343             $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext); 
344         
345         
346         
347         if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
348             $this->err  =  isset($this->err)  ?  $this->err  : "createFrom Image failed";
349             return false;
350         }
351         return true;
352          
353     }
354      
355     
356     
357     /**
358      * return a list of images for an object, optionally with a mime regex.
359      * eg. '%/pdf' or 'image/%'
360      *
361      * usage:
362      *
363      * $i = DB_DataObject::factory('Images');
364      * $i->imgtype = 'LOGO';
365      * $ar = $i->gather($somedataobject, 'image/%');
366      * 
367      * @param {DB_DataObject} dataobject  = the object to gather data on.
368      * @param {String} mimelike  LIKE query to use for search
369      
370      */
371     function gather($obj, $mime_like='', $opts=array())
372     {
373         //DB_DataObject::debugLevel(1);
374         if (empty($obj->id)) {
375             return array();
376         }
377         
378         $c = clone($this);
379         $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
380         $c->onid = $obj->id;
381         $c->autoJoin();
382         if (!empty($mime_like)) {
383             $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
384         }
385         $c->orderBy('created DESC');
386
387         return $c->fetchAll();
388     }
389      
390     
391     /**
392     * set or get the dataobject this image is associated with
393     * @param DB_DataObject $obj An object to associate this image with
394     *        (does not store it - you need to call update() to do that)
395     * @return DB_DataObject the dataobject this image is attached to.
396     */
397     function object($obj=false)
398     {
399         if ($obj === false) {
400             if (empty($this->ontable) || empty($this->onid)) {
401                 return false;
402             }
403             $ret = DB_DataObject::factory($this->ontable);
404             $ret->get($this->onid);
405             return $ret;
406         }
407         
408         
409         $this->ontable = $obj->tableName();
410         $this->onid = $obj->id; /// assumes our nice standard of using ids..
411         return $obj;
412     }
413     
414      
415     function toRooArray($req) {
416         
417         $ret= $this->toArray();
418       
419         static $ff = false;
420         if (!$ff) {
421             $ff = HTML_FlexyFramework::get();
422         }
423         
424         $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
425                     $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
426         
427         if (!empty($req['query']['imagesize'])) {
428             // query/imageBaseURL ... depricated...? -- set it in config?
429             
430             $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
431             
432             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
433             
434             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
435             
436             if (!empty($req['query']['imagesize'])) {
437                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
438             }
439         }
440         
441          
442          
443         return $ret;
444     }
445     
446     /**
447      * URL - create  a url for the image.
448      * size - use -1 to show full size.
449      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
450      * 
451      * 
452      */
453     function URL($size , $provider = '/Images/Thumb', $baseURL=false)
454     {
455         if (!$this->id) {
456             return 'about:blank';
457             
458         }
459
460         $ff = HTML_FlexyFramework::get();
461         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
462         if (preg_match('#^http[s]*://#', $provider)) {
463             $baseURL = '';
464         }
465        
466         if ($size < 0) {
467             $provider = preg_replace('#/Thumb$#', '', $provider);
468             
469             return $baseURL . $provider . "/{$this->id}/{$this->filename}";
470         }
471         //-- max?
472         //$size = max(100, (int) $size);
473         //$size = min(1024, (int) $size);
474         // the size should 200x150 to convert
475         $sizear = preg_split('/(x|c)/', $size);
476         if(empty($sizear[1])){
477             $sizear[1] = 0;
478         }
479         $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
480 //        print_r($size);
481         $fc = $this->toFileConvert();
482 //        print_r($size);
483 //        exit;
484         $mt = $this->mimetype;
485         if (!preg_match('#^image/#i',$mt)) {
486             $mt = 'image/jpeg';
487         }
488         
489         $fc->convert($mt, $size);
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 : error = ". (!empty($this->err) ? $this->err : ''));
640         }
641         
642         $this->addEvent($ar, $roo);
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 addEvent($ar, $roo)
654     {
655         $roo->addEvent("ADD", $this, $this->toEventString());
656     }
657     
658     function toEventString()
659     {
660         
661         //$p = DB_DataObject::factory($this->ontable);
662         //if (!is_$p) {
663         //    return "ERROR unknown table? {$this->ontable}";
664        // }
665         //$p->get($p->onid);
666         
667         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
668         //$p->toEventString();
669     }
670     
671     function onUploadFromData($data, $roo)
672     {
673         if (empty($data)) {
674             $this->err = "Missing file details";
675             return false;
676         }
677         
678         if ($this->id) {
679             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
680             exit;
681             $this->beforeDelete();
682         }
683         
684         if (empty($this->ontable)) {
685             $this->err = "Missing  ontable";
686             return false;
687         }
688         
689         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
690             // then its an upload 
691             $img  = DB_DataObject::factory('Images');
692             $img->onid = $this->onid;
693             $img->ontable = $this->ontable;
694             $img->imgtype = $this->imgtype;
695             
696             $img->find();
697             while ($img->fetch()) {
698                 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
699                 exit;
700                 $img->beforeDelete();
701                 $img->delete();
702             }
703             
704         }
705         
706         require_once 'File/MimeType.php';
707         $y = new File_MimeType();
708         
709         if (in_array($this->mimetype, array(
710                         'text/application',
711                         'application/octet-stream',
712                         'image/x-png',  // WTF does this?
713                         'image/pjpeg',  // WTF does this?
714                         'application/x-apple-msg-attachment', /// apple doing it's magic...
715                         'application/vnd.ms-excel',   /// sometimes windows reports csv as excel???
716                         'application/csv-tab-delimited-table', // windows again!!?
717                 ))) { // weird tyeps..
718             $inf = pathinfo($this->filename);
719             $this->mimetype  = $y->fromExt($inf['extension']);
720         }
721         
722         $ext = $y->toExt(trim((string) $this->mimetype ));
723         
724         if(array_pop(explode('.', $this->filename)) != $ext){
725             $this->filename = $this->filename .'.'. $ext; 
726         }
727         
728         if (!$this->createFromData($data)) {
729             return false;
730         }
731         
732         return true;
733          
734     }
735     
736     function createFromData($data)
737     {   
738         
739         $this->mimetype= strtolower($this->mimetype);
740         
741         if (array_shift(explode('/', $this->mimetype)) == 'image') { 
742         
743             $imgs = @getimagesize($data);
744             
745             if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
746                 list($this->width , $this->height)  = $imgs;
747             }
748         }
749         
750         $this->created = date('Y-m-d H:i:s');
751         
752         if (!$this->id) {
753             $this->insert();
754         } else {
755             $this->update();
756         }
757         
758         $f = $this->getStoreName();
759         $dest = dirname($f);
760         if (!file_exists($dest)) {
761             $oldumask = umask(0);
762             mkdir($dest, 0775, true);
763             umask($oldumask);  
764         }
765         
766         file_put_contents($f, file_get_contents("data://" . $data));
767         
768         $o = clone($this);
769         
770         $this->filesize = filesize($f);
771         
772         if($this->mimetype == 'application/pdf'){
773             $this->no_of_pages = $this->getPdfPages($f);
774         }
775         
776         $this->update($o);
777         
778         return true;
779         
780     }
781     
782     function toBase64()
783     {
784         if(!preg_match('/^image\//', $this->mimetype)){
785             return false;
786         }
787         
788         $file = $this->getStoreName();
789         
790         if(!file_exists($file)){
791             return false;
792         }
793         
794         $data = file_get_contents($file);
795         
796         $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
797         
798         return $base64;
799     }
800     
801     function getPdfPages($file)
802     {
803         require_once 'System.php';
804         
805         $page = 0;
806
807         $pdfinfo = System::which('pdfinfo');
808
809         if (!file_exists($file) || empty($pdfinfo)) {
810             return $page;
811         }
812         
813         $cmd = "{$pdfinfo} {$file}";
814
815         $ret = `$cmd`;
816
817         $info = explode("\n", $ret);
818
819         foreach ($info as $i){
820
821             if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
822                 continue;
823             }
824             
825             $page = (empty($matches[1])) ? 0 : $matches[1];
826         }
827         
828         return $page;
829     }
830     
831  }