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