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