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