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