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