fix #7937 - image upload filename issue
[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     function applyFilters($q, $au, $roo)
33     {
34         $tn = $this->tableName();
35         
36         if(!empty($q['search']['filename'])){
37             $this->whereAdd("
38                 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%' OR $tn.title LIKE '%{$this->escape($q['search']['filename'])}%'
39             ");
40         }
41
42         if(!empty($q['_to_base64']) && !empty($q['image_id'])) {
43             $i = DB_DataObject::factory("Images");
44             $i->get($q['image_id']);
45             $roo->jok($i->toBase64());
46         }
47         
48
49     }
50     
51     function checkPerm($lvl, $au)
52     {
53         // default permissons are to
54         // allow create / edit / if the user has
55         
56         if (!$au) {
57             return false;
58         }
59         
60         $o = $this->object();
61         //print_r($o);
62         if ($o &&  method_exists($o, 'checkPerm')) {
63             // edit permissions on related object needed...
64             return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
65             
66         }
67         
68         return true; //// ??? not really that safe...
69         
70     }
71     
72     function beforeInsert($q, $roo) 
73     {
74         if (isset($q['_remote_upload'])) {
75             require_once 'System.php';
76             
77             $tmpdir  = System::mktemp("-d remote_upload");
78             
79             $path = $tmpdir . '/' . basename($q['_remote_upload']);
80             
81             if(!file_exists($path)){
82                file_put_contents($path, file_get_contents($q['_remote_upload'])); 
83             }
84             
85             $imageInfo = getimagesize($path);
86             
87             require_once 'File/MimeType.php';
88             $y = new File_MimeType();
89             $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
90             
91             if (!preg_match("/\." . $ext."$/", $path, $matches)) {
92                 rename($path,$path.".".$ext);
93                 $path.= ".".$ext;
94             }
95             
96             if (!$this->createFrom($path)) {
97                 $roo->jerr("erro making image" . $q['_remote_upload']);
98             }
99             
100             if(!empty($q['_return_after_create'])){
101                 return;
102             }
103             
104             $roo->addEvent("ADD", $this, $this->toEventString());
105         
106             $r = DB_DataObject::factory($this->tableName());
107             $r->id = $this->id;
108             $roo->loadMap($r);
109             $r->limit(1);
110             $r->find(true);
111             $roo->jok($r->URL(-1,'/Images') . '#attachment-'.  $r->id);
112         }
113         
114     }
115     
116      
117     /**
118      * create an email from file.
119      * these must have been set first.
120      * ontable / onid.
121      * 
122      */
123     function createFrom($file, $filename=false)
124     {
125         // copy the file into the storage area..
126         if (!file_exists($file) || !filesize($file)) {
127             $this->err = "File $file did not exist or is 0 size";
128             return false;
129         }
130         
131         $filename = empty($filename) ? $file : $filename;
132         
133         if (empty($this->mimetype)) {
134             require_once 'File/MimeType.php';
135             $y = new File_MimeType();
136             $this->mimetype = $y->fromFilename($filename);
137         }
138         
139         $this->mimetype = strtolower($this->mimetype);
140         
141         $mta = explode('/', $this->mimetype);
142         if (array_shift($mta) == 'image') { 
143         
144             $imgs = @getimagesize($file);
145             
146             if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
147                 // it's a file!!!!
148             } else {
149                 list($this->width , $this->height)  = $imgs;
150             }
151         }
152         
153         if($this->mimetype == 'application/pdf'){
154             $this->no_of_pages = $this->getPdfPages($file);
155         }
156         
157         $this->filesize = filesize($file);
158         $this->created = date('Y-m-d H:i:s');
159          
160         
161         if (empty($this->filename)) {
162             $this->filename = basename($filename);
163         }
164         
165         //DB_DataObject::debugLevel(1);
166         if (!$this->id) {
167             $this->insert();
168         } else {
169             $this->update();
170         }
171         
172         
173         
174         $f = $this->getStoreName();
175         $dest = dirname($f);
176         if (!file_exists($dest)) {
177             // currently this is 0775 due to problems using shared hosing (FTP)
178             // it makes all the files unaccessable..
179             // you can normally solve this by giving the storedirectory better perms
180             // if needed on a dedicated server..
181             $oldumask = umask(0);
182             mkdir($dest, 0775, true);
183             umask($oldumask);  
184         }
185         
186         copy($file,$f);
187         
188         // fill in details..
189         
190         /* thumbnails */
191         
192      
193        // $this->createThumbnail(0,50);
194         return true;
195         
196     }
197
198     /**
199      * Calculate target file name
200      *
201      * @return - target file name
202      */
203     function getStoreName() 
204     {
205         return self::staticGetStoreName($this);
206           
207     }
208
209     static function staticGetStoreName($o)
210     {
211         $opts = HTML_FlexyFramework::get()->Pman;
212         $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $o->filename);
213         return implode( '/', array(
214             $opts['storedir'], '_images_', date('Y/m', strtotime($o->created)), $o->id . '-'. $fn
215         ));
216     }
217     
218     /**
219      * does the files exist?
220      */
221     function exists()
222     {
223         return self::staticExists($this);
224     }
225
226     static function staticExists($o)
227     {
228         clearstatcache();
229         $ret =  file_exists(self::staticGetStoreName($o));
230         if (!$ret) {
231             return self::staticCanFix($o);
232         }
233         return $ret;
234     }
235
236     /**
237      * the getStorename code got changed, and some old files may not end up with the correct name anymore.
238      * this tries to fix it.
239      *
240      */
241     function canFix() 
242     {
243         return self::staticCanFix($this);
244     }
245
246     static function staticCanFix($o)
247     {
248         // look for the image in the folder, with matching id.
249         // this is problematic..
250         $fn = self::staticGetStoreName($o);
251         if (file_exists($fn . '-really-missing')) {
252             return false;
253         }
254         if (!file_exists(dirname($fn))) {
255             return false;
256         }
257         foreach( scandir(dirname($fn)) as $n) {
258             if (empty($n) || $n[0] == '.') {
259                 continue;
260             }
261             $bits = explode('-', $n);
262             if ($bits[0] != $o->id) {
263                 continue;
264             }
265             if (preg_match('/\.[0-9]+x[0-9]]+\.jpeg$/', $n)) {
266                 continue;
267             }
268             copy(dirname($fn). '/'.  $n, $fn);
269             clearstatcache();
270             return true;
271         }
272         // fixme - flag it as bad
273         touch($fn . '-really-missing');
274     }
275     
276     
277     /**
278      * deletes all the image instances of it...
279      * 
280      * 
281      */
282     function beforeDelete($dependants_array, $roo)
283     {
284         
285         if (!empty($dependants_array)) {
286             return;
287         }
288         
289         $opts = HTML_FlexyFramework::get()->Pman;
290         $deldir = $opts['storedir']. '/_deleted_images_';
291         clearstatcache();
292         if (!file_exists( $deldir )) {
293             @mkdir($deldir, 0755); // not sure why we are erroring here.. after checking - maybe permissions?
294         }
295             
296         $fn = $this->getStoreName();
297         $b = basename($fn);
298         clearstatcache();
299         if (file_exists($fn)) {
300             
301             if (file_exists($deldir . '/'. $b)) {
302                 unlink($fn);
303             } else {
304                 rename($fn, $deldir .'/'. $b);
305             }
306             
307             
308         }
309         // delete thumbs..
310         
311         $d = dirname($fn);
312         if (file_exists($d)) {
313                 
314             $dh = opendir($d);
315             while (false !== ($fn = readdir($dh))) {
316                 if (substr($fn, 0, strlen($b)) == $b) {
317                     clearstatcache();
318                     if (file_exists($deldir . '/'. $fn)) {
319                         unlink($d. '/'. $fn);
320                         continue;
321                     }
322                     if (file_exists($d. '/'. $fn)) {
323                         rename($d. '/'. $fn, $deldir .'/'. $fn);
324                     }
325                     
326                 }
327             }
328         }
329         
330     }
331     /**
332      * check mimetype against type
333      * - eg. img.is(#image#)
334      *
335      */
336     function is($type)
337     {
338         if (empty($this->mimetype)) {
339             return false;
340         }
341         return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
342     }
343   
344     /**
345      * onUpload (singlely attached image to a table)
346      */
347     
348     function onUploadWithTbl($tbl,  $fld)
349     {
350         if ( $tbl->__table == 'Images') {
351             return; // not upload to self...
352         }
353         if (empty($_FILES['imageUpload']['tmp_name']) || 
354             empty($_FILES['imageUpload']['name']) || 
355             empty($_FILES['imageUpload']['type'])
356         ) {
357             return false;
358         }
359         if ($tbl->$fld) {
360             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
361             exit;
362             $image = DB_DataObject::factory('Images');
363             $image->get($tbl->$fld);
364             $image->beforeDelete();
365             $image->delete();
366         }
367         
368         $image = DB_DataObject::factory('Images');
369         $image->onid = $tbl->id;
370         $image->ontable = $tbl->__table;
371         $image->filename = $_FILES['imageUpload']['name']; 
372         $image->mimetype = $_FILES['imageUpload']['type'];
373        
374         if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
375             return false;
376         }
377         $old = clone($tbl);
378         $tbl->$fld = $image->id;
379         $tbl->update($old);
380          
381     }
382     
383     // direct via roo...
384     /// ctrl not used??
385     function onUpload($roo, $table = false, $file = false)
386     {
387         
388         if ($table !== false) {
389             $this->ontable = $table->tableName();
390             $this->onid = $table->pid();
391         }
392         
393         if ($file === false) {
394             $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
395         }
396         
397         //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
398         if (empty($file['tmp_name']) || 
399             empty($file['name']) || 
400             empty($file['type'])
401         ) {
402             
403             $emap = array( 
404                 0=>"There is no error, the file uploaded with success", 
405                 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
406                 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
407                 3=>"The uploaded file was only partially uploaded",
408                 4=>"No file was uploaded",
409                 6=>"Missing a temporary folder" 
410             ); 
411             $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
412             $this->err = "Missing file details : Error=". $estr;
413             return false;
414         }
415         
416         if ($this->id) {
417             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
418             exit;
419             $this->beforeDelete();
420         }
421         if ( empty($this->ontable)) {
422             $this->err = "Missing  ontable";
423             return false;
424         }
425         
426         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
427             // then its an upload 
428             $img  = DB_DataObject::factory('Images');
429             $img->onid = $this->onid;
430             $img->ontable = $this->ontable;
431             $img->imgtype = $this->imgtype;
432             
433             $img->find();
434             while ($img->fetch()) {
435                 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
436                 exit;
437                 $img->beforeDelete();
438                 $img->delete();
439             }
440             
441         }
442         
443         
444         
445         require_once 'File/MimeType.php';
446         $y = new File_MimeType();
447         $this->mimetype = $file['type'];
448         if (in_array($this->mimetype, array(
449                         'text/application',
450                         'application/octet-stream',
451                         'image/x-png',  // WTF does this?
452                         'image/pjpeg',  // WTF does this?
453                         'application/x-apple-msg-attachment', /// apple doing it's magic...
454                         'application/vnd.ms-excel',   /// sometimes windows reports csv as excel???
455                         'application/csv-tab-delimited-table', // windows again!!?
456                 ))) { // weird tyeps..
457             $inf = pathinfo($file['name']);
458             $this->mimetype  = $y->fromExt($inf['extension']);
459         }
460         
461         
462         $ext = $y->toExt(trim((string) $this->mimetype ));
463         
464         $this->filename = empty($this->filename) ? 
465             $file['name'] : ($this->filename .'.'. $ext); 
466         
467         
468         
469         if (!$this->createFrom($file['tmp_name'])) {
470             $this->err  =  isset($this->err)  ?  $this->err  : "createFrom Image failed";
471             return false;
472         }
473         return true;
474          
475     }
476      
477     
478     
479     /**
480      * return a list of images for an object, optionally with a mime regex.
481      * eg. '%/pdf' or 'image/%'
482      *
483      * usage:
484      *
485      * $i = DB_DataObject::factory('Images');
486      * $i->imgtype = 'LOGO';
487      * $ar = $i->gather($somedataobject, 'image/%');
488      * 
489      * @param {DB_DataObject} dataobject  = the object to gather data on.
490      * @param {String} mimelike  LIKE query to use for search
491      
492      */
493     function gather($obj, $mime_like='', $opts=array())
494     {
495         //DB_DataObject::debugLevel(1);
496         if (empty($obj->id)) {
497             return array();
498         }
499         
500         $c = clone($this);
501         $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
502         $c->onid = $obj->id;
503         $c->autoJoin();
504         if (!empty($mime_like)) {
505             $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
506         }
507         $c->orderBy('created DESC');
508
509         return $c->fetchAll();
510     }
511      
512     
513     /**
514     * set or get the dataobject this image is associated with
515     * @param DB_DataObject $obj An object to associate this image with
516     *        (does not store it - you need to call update() to do that)
517     * @return DB_DataObject the dataobject this image is attached to.
518     */
519     function object($obj=false)
520     {
521         if ($obj === false) {
522             if (empty($this->ontable) || empty($this->onid)) {
523                 return false;
524             }
525             $ret = DB_DataObject::factory($this->ontable);
526             $ret->get($this->onid);
527             return $ret;
528         }
529         
530         
531         $this->ontable = $obj->tableName();
532         $this->onid = $obj->id; /// assumes our nice standard of using ids..
533         return $obj;
534     }
535     
536      
537     function toRooArray($req)
538     {
539         
540         $ret= $this->toArray();
541       
542          
543         $ff = HTML_FlexyFramework::get();
544         
545         
546         $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
547                     $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
548         
549         if (!empty($req['query']['imagesize'])) {
550             // query/imageBaseURL ... depricated...? -- set it in config?
551             
552             $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
553             
554             $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
555             
556             $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);    
557             
558             if (!empty($req['query']['imagesize'])) {
559                 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
560             }
561             
562             
563         }
564         $ret['shorten_name']   = $this->shorten_name();
565         
566         return $ret;
567     }
568     
569     /**
570      * URL - create  a url for the image.
571      * size - use -1 to show full size.
572      * provier = baseURL + /Images/Thumb ... use '/Images/' for full
573      * 
574      * 
575      */
576     function URL($size , $provider = '/Images/Thumb', $baseURL=false, $to_type=false)
577     {
578         if (!$this->id) {
579             return 'about:blank';
580         }
581         if (!$this->exists()) {
582             return 'about:missing';
583         }
584         
585         $shorten_name = $this->shorten_name();
586         
587         $ff = HTML_FlexyFramework::get();
588         $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
589         if (preg_match('#^http[s]*://#', $provider)) {
590             $baseURL = '';
591         }
592        
593         if ($size < 0) {
594             $provider = preg_replace('#/Thumb$#', '', $provider);
595             
596             return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
597         }
598         //-- max?
599         //$size = max(100, (int) $size);
600         //$size = min(1024, (int) $size);
601         // the size should 200x150 to convert
602         $sizear = preg_split('/(x|c)/', $size);
603         if(!isset($sizear[1])){
604             $sizear[1] =   0; // 0x with '0' is a box? why
605         }
606         
607         $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
608 //        print_r($size);
609         $fc = $this->toFileConvert();
610 //        print_r($size);
611 //        exit;
612         $mt = $to_type === false ? $this->mimetype : $to_type;
613         if (!preg_match('#^image/#i',$mt)) {
614             $mt = 'image/jpeg';
615         }
616         
617         $cn = $fc->convert($mt, $size);
618         $shorten_name = $this->shorten_name(basename($cn));
619         
620         return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
621     }
622     /**
623      *
624      * tries to get an image from then URL - not always has based... - also from the normal url
625      */
626     function getFromHashURL($url)
627     {
628         $id = false;
629         if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
630             $id = $matches[1];
631         } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
632             $id = $matches[1];
633         } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
634             $id = $matches[1];
635         } else if (preg_match('#images[^/]+/([0-9]+)/#i', $url, $matches)) {
636             // supports images.xxxxx.com/{number}/name...
637             $id = $matches[1];
638         }
639         if ($id === false ||  $id < 1) {
640             return false;
641         }
642         
643         $img = DB_DAtaObject::Factory('images');
644         if ($img->get($id)) {
645             return $img;
646         }
647         return false;
648     }
649     
650     
651     function shorten_name($fn = false)
652     {
653         if(empty($this->filename)) {
654             return;
655         }
656         $fn = $fn === false ? $this->filename : $fn;
657         
658         $filename = explode('.', $fn);
659         $ext = array_pop($filename);
660         $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
661         
662         if(strlen($name) > 32) {
663             $name = substr($name, 0, 32);
664         }
665         
666         $shorten_name = "{$name}.{$ext}";
667         
668         return $shorten_name;
669     }
670     /**
671      * size could be 123x345
672      * 
673      * 
674      */
675     function toHTML($size, $provider = '/Images/Thumb', $extra = '') 
676     {
677         
678         
679         
680         $sz = explode('x', $size);
681         $sx = $sz[0];
682         //var_dump($sz);
683         if (!$this->id || empty($this->width)) {
684             $this->height = $sx;
685             $this->width = empty($sz[1]) ? $sx : $sz[1];
686             $sy = $this->width ;
687         }
688         if (empty($sz[1])) {
689             $ratio =  empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
690             $sy = intval($ratio * $sx);
691         } else {
692             $sy = $sz[1];
693         }
694         // create it?
695        
696         if (strlen($this->title)) {
697             $extra = ' title="'. htmlspecialchars($this->title) . '"';
698         }
699         
700         return '<img src="' . $this->URL($size, $provider) . '"' .
701                 $extra .
702                 ' width="'. $sx . '"' .
703                 ' height="'. $sy . '">';
704         
705         
706     }
707     
708     /**
709      * 
710      * #2142 [new] CMS - image link urls
711      * 
712      * 
713      * 
714      */
715     function toLinkHTML($size, $provider = '/Images/Thumb')
716     {
717         if(empty($this->linkurl)){
718             return $this->toHTML($size, $provider = '/Images/Thumb');
719         }
720         
721         return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
722         
723     }
724     
725     
726     /**
727      * to Fileconvert object..
728      *
729      *
730      *
731      */
732     function toFileConvert()
733     {
734         $fn = $this->getStoreName();
735         
736         require_once 'File/Convert.php';
737         $fc = new File_Convert($this->getStoreName(), $this->mimetype);
738         return $fc;
739         
740     }
741     
742     function fileExt()
743     {
744         require_once 'File/MimeType.php';
745         
746         $y = new File_MimeType();
747         return  $y->toExt($this->mimetype);
748         
749         
750     }
751     
752     /**
753      *
754      *
755      *
756      */
757     
758     
759     function setFromRoo($ar, $roo)
760     {
761         // not sure why we do this.. 
762         
763         // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
764         if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
765             $this->setFrom($ar);
766             $this->limit(1);
767             if ($this->find(true)) {
768                 $roo->old = clone($this);
769             }
770         }   
771             
772         
773         if (!empty($ar['_copy_from'])) {
774             
775             if (!$this->checkPerm( 'A' , $roo->authUser))  {
776                 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
777             }
778             
779             $copy = DB_DataObject::factory('Images');
780             $copy->get($ar['_copy_from']);
781             $this->setFrom($copy->toArray());
782             $this->setFrom($ar);
783             $this->createFrom($copy->getStoreName());
784             
785             $roo->addEvent("ADD", $this, $this->toEventString());
786             
787             $r = DB_DataObject::factory($this->tableName());
788             
789             $r->id = $this->id;
790             $roo->loadMap($r);
791             $r->limit(1);
792             $r->find(true);
793             $roo->jok($r->toRooArray($ar));
794             
795             
796         }
797         
798          
799         
800         // FIXME - we should be checking perms here...
801        
802         // this should be doign update
803         $this->setFrom($ar);
804          
805         if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser))  {
806             $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
807         }
808          
809         
810         if (!isset($_FILES['imageUpload'])) {
811             return; // standard update...
812         }
813         
814         
815 //        print_r(!$this->onUpload($this));
816         
817         if ( !$this->onUpload($this)) { 
818             $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
819         }
820         
821         $this->addEvent($ar, $roo);
822         
823         $r = DB_DataObject::factory($this->tableName());
824         $r->id = $this->id;
825         $roo->loadMap($r);
826         $r->limit(1);
827         $r->find(true);
828         $roo->jok($r->toRooArray($ar));
829          
830     }
831     
832     function addEvent($ar, $roo)
833     {
834         $roo->addEvent("ADD", $this, $this->toEventString());
835     }
836     
837     function toEventString()
838     {
839         
840         //$p = DB_DataObject::factory($this->ontable);
841         //if (!is_$p) {
842         //    return "ERROR unknown table? {$this->ontable}";
843        // }
844         //$p->get($p->onid);
845         
846         return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
847         //$p->toEventString();
848     }
849     
850     function onUploadFromData($data, $roo)
851     {
852         if (empty($data)) {
853             $this->err = "Missing file details";
854             return false;
855         }
856         
857         if ($this->id) {
858             HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
859             exit;
860             $this->beforeDelete();
861         }
862         
863         if (empty($this->ontable)) {
864             $this->err = "Missing  ontable";
865             return false;
866         }
867         
868         if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
869             // then its an upload 
870             $img  = DB_DataObject::factory('Images');
871             $img->onid = $this->onid;
872             $img->ontable = $this->ontable;
873             $img->imgtype = $this->imgtype;
874             
875             $img->find();
876             while ($img->fetch()) {
877                 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
878                 exit;
879                 $img->beforeDelete();
880                 $img->delete();
881             }
882             
883         }
884         
885         require_once 'File/MimeType.php';
886         $y = new File_MimeType();
887         
888         if (in_array($this->mimetype, array(
889                         'text/application',
890                         'application/octet-stream',
891                         'image/x-png',  // WTF does this?
892                         'image/pjpeg',  // WTF does this?
893                         'application/x-apple-msg-attachment', /// apple doing it's magic...
894                         'application/vnd.ms-excel',   /// sometimes windows reports csv as excel???
895                         'application/csv-tab-delimited-table', // windows again!!?
896                 ))) { // weird tyeps..
897             $inf = pathinfo($this->filename);
898             $this->mimetype  = $y->fromExt($inf['extension']);
899         }
900         
901         $ext = $y->toExt(trim((string) $this->mimetype ));
902         
903         $explode_filename = explode('.', $this->filename);
904         if(array_pop($explode_filename) != $ext){
905             $this->filename = $this->filename .'.'. $ext; 
906         }
907         
908         if (!$this->createFromData($data)) {
909             return false;
910         }
911         
912         return true;
913          
914     }
915     
916     function createFromData($data)
917     {   
918         
919         if (0 === strpos($data, "data:")) {
920             // data:image/png;base64, 
921             $data = substr($data,5);
922             $bits = explode(";", $data);
923             $this->mimetype = $bits[0];
924         }
925         static $imgid = 1;
926         if (empty($this->filename)) {
927             require_once 'File/MimeType.php';
928             $y = new File_MimeType();
929             $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
930         }
931         
932         
933         $this->mimetype = strtolower($this->mimetype);
934         if ($this->mimetype == 'image/jpg') {
935             $this->mimetype = 'image/jpeg';
936         }
937         
938         
939         $explode_mimetype = explode('/', $this->mimetype);
940         
941         if (array_shift($explode_mimetype) == 'image') { 
942         
943             $imgs = @getimagesize('data://'. $data);
944             
945             if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
946                 list($this->width , $this->height)  = $imgs;
947             }
948         }
949         
950         $this->created = date('Y-m-d H:i:s');
951         
952         if (!$this->id) {
953             $this->insert();
954         } else {
955             $this->update();
956         }
957         
958         $f = $this->getStoreName();
959         $dest = dirname($f);
960         if (!file_exists($dest)) {
961             $oldumask = umask(0);
962             mkdir($dest, 0775, true);
963             umask($oldumask);  
964         }
965         
966         file_put_contents($f, file_get_contents("data://" . $data));
967         //var_dump($f);exit;
968         $o = clone($this);
969         
970         $this->filesize = filesize($f);
971         
972         if($this->mimetype == 'application/pdf'){
973             $this->no_of_pages = $this->getPdfPages($f);
974         }
975         
976         $this->update($o);
977         
978         return true;
979         
980     }
981     
982     function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
983     {
984         if(!preg_match('/^image\//', $this->mimetype)){
985             return false;
986         }
987         
988         $file = $this->getStoreName();
989
990         if(!file_exists($file)){
991             return false;
992         }
993         
994         $data = file_get_contents($file);
995         
996         if(!empty($scaleWidth) || !empty($scaleHeight)){
997             $data = $this->scale(false, $scaleWidth, $scaleHeight);
998         }
999         
1000         if($rotate){
1001             $data = $this->rotate($data);
1002         }
1003         
1004         $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
1005         
1006         return $base64;
1007     }
1008     
1009     function getPdfPages($file)
1010     {
1011         require_once 'System.php';
1012         
1013         $page = 0;
1014
1015         $pdfinfo = System::which('pdfinfo');
1016
1017         if (!file_exists($file) || empty($pdfinfo)) {
1018             return $page;
1019         }
1020         
1021         $cmd = "{$pdfinfo} {$file}";
1022
1023         $ret = `$cmd`;
1024
1025         $info = explode("\n", $ret);
1026
1027         foreach ($info as $i){
1028
1029             if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
1030                 continue;
1031             }
1032             
1033             $page = (empty($matches[1])) ? 0 : $matches[1];
1034         }
1035         
1036         return $page;
1037     }
1038     
1039     function rotate($imageBlob = false)
1040     {
1041         if(empty($imageBlob)){
1042             $imagick = new Imagick($this->getStoreName());
1043         } else {
1044             $imagick = new Imagick();
1045             $imagick->readImageBlob($imageBlob);
1046         }
1047         
1048         $orientation = $imagick->getImageOrientation(); 
1049         
1050         switch($orientation) { 
1051             case Imagick::ORIENTATION_BOTTOMRIGHT: 
1052                 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees 
1053             break; 
1054
1055             case Imagick::ORIENTATION_RIGHTTOP: 
1056                 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW 
1057             break; 
1058
1059             case Imagick::ORIENTATION_LEFTBOTTOM: 
1060                 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW 
1061             break; 
1062         }
1063         
1064         return $imagick->getImageBlob();
1065     }
1066     
1067     function scale($imageBlob = false, $width = 0, $height = 0)
1068     {
1069         if(empty($imageBlob)){
1070             $imagick = new Imagick($this->getStoreName());
1071         } else {
1072             $imagick = new Imagick();
1073             $imagick->readImageBlob($imageBlob);
1074         }
1075         
1076         $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
1077         
1078         return $imagick->getImageBlob();
1079         
1080     }
1081     
1082  }