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