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