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