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