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