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