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