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