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