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