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