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