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