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