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