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