Images.php
[Pman.Core] / Images.php
1 <?php
2 /**
3  * Deal with image delivery and HTML replacement of image links in body text.
4  *
5  * $str = Pman_Core_Images::replaceImg($str); // < use with HTML
6  *
7  * or
8  *
9  * Deliver image /file etc..
10  * 
11  * Use Cases:
12  * 
13  * args: ontable request
14  *      ontable (req) tablename.
15  *      filename
16  *      (other table args)
17  *      as (serve as a type) = eg. ?as=audio/mpeg 
18  * 
19  * args: generic
20  *     as :(serve as a type) = eg. mimetype.
21  * 
22  * Images/{ID}/fullname.xxxx
23  * 
24  * (valid thumbs 200, 400)...?
25  * Images/Thumb/200/{ID}/fullname.xxxx
26  * Images/Download/{ID}/fullname.xxxx
27  *
28  *
29  *
30  * 
31  * Used to be in Base... now in core..
32  *
33  * 
34  * view permission should be required on the underlying object...
35  * 
36  */
37 require_once  'Pman.php';
38 class Pman_Core_Images extends Pman
39 {
40     
41     // tables that do not need authentication checks before serving.
42     var $public_image_tables = array();
43     
44     
45     function getAuth()
46     {
47         parent::getAuth(); // load company!
48         //return true;
49         $au = $this->getAuthUser();
50         
51         if (!$au) {
52             $this->authUser = false;
53             return true;//die("Access denied");
54         }
55         
56         $this->authUser = $au;
57         
58         return true;
59     }
60     var $thumb = false;
61     var $as_mimetype = false;
62     var $method = 'inline';
63     var $page = false;
64     
65     function get($s, $opts=array()) // determin what to serve!!!!
66     {
67         // for testing only.
68         //if (!empty($_GET['_post'])) {
69         //   return $this->post();
70         //}
71         
72         $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
73         
74         $bits= explode('/', $s);
75         $id = 0;
76 //        var_dump($bits);die('in');
77         // without id as first part...
78         if (!empty($bits[0]) && $bits[0] == 'Thumb') {
79             $this->thumb = true;
80             $this->as_mimetype = 'image/jpeg';
81             $this->size = empty($bits[1]) ? '0x0' : $bits[1];
82             $id = empty($bits[2]) ? 0 :   $bits[2];
83             
84         } else if (!empty($bits[0]) && $bits[0] == 'Download') {
85             $this->method = 'attachment';
86             $id = empty($bits[1]) ? 0 :   $bits[1];
87             
88         } else  if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
89             $this->thumb = true;
90             $this->as_mimetype = 'image/jpeg';
91             $this->size = empty($bits[2]) ? '0x0' : $bits[2];
92             $id = empty($bits[3]) ? 0 :   $bits[3];
93             
94         } else if (!empty($bits[0]) && $bits[0] == 'events') {
95             if (!$this->authUser) {
96                 $this->imgErr("no-authentication-events",$s);
97             }
98             $this->downloadEvent($bits);
99             $this->imgErr("unknown file",$s);
100             
101             
102         } else {
103         
104             $id = empty($bits[0]) ? 0 :  $bits[0];
105         }
106         
107         if (strpos($id,':') > 0) {  // id format  tablename:id:-imgtype
108             
109             if (!$this->authUser) {
110                 $this->imgErr("not-authenticated-using-colon-format",$s);
111                 
112             }
113             
114             $onbits = explode(':', $id);
115             if ((count($onbits) < 2)   || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
116                 $this->imgErr("bad-url",$s);
117                 
118             }
119             //DB_DataObject::debugLevel(1);
120             $img = DB_DataObject::factory('Images');
121             $img->ontable = $onbits[0];
122             $img->onid = $onbits[1];
123             if (empty($_REQUEST['anytype'])) {
124                 $img->whereAdd("mimetype like 'image/%'");
125             }
126             $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
127             if (isset($onbits[2])) {
128                 $img->imgtype = $onbits[2];
129             }
130             $img->limit(1);
131             if (!$img->find(true)) {
132                 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
133                 
134             }
135             
136             $id = $img->id;
137             
138             
139         }
140         $id = (int) $id;
141         
142         // depreciated - should use ontable:onid:type here...
143         if (!empty($_REQUEST['ontable'])) {
144             
145             if (!$this->authUser) {
146                 die("authentication required");
147             }
148             
149             //DB_DataObjecT::debugLevel(1);
150             $img = DB_DataObject::factory('Images');
151             $img->setFrom($_REQUEST);
152            
153             
154             
155             $img->limit(1);
156             if (!$img->find(true)) {
157                 $this->imgErr("No file exists",$s);
158             } 
159             $id = $img->id;
160             
161         }
162         
163         
164        
165         $img = DB_DataObjecT::factory('Images');
166          
167         if (!$id || !$img->get($id)) {
168              $this->imgErr("image has been removed or deleted.",$s);
169         }
170         
171         if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
172            
173             if ($img->ontable != 'core_company') {
174                 $this->imgErr("not-authenticated {$img->ontable}",$s);
175             }
176             if ($img->imgtype != 'LOGO') {
177                 $this->imgErr("not-logo",$s);
178             }
179             $comp  = $img->object();
180             if ($comp->comptype != 'OWNER') {
181                 $this->imgErr("not-owner-company",$s);
182             }
183             return $this->serve($img);
184         
185             
186         }
187         
188         
189         if(!$this->hasPermission($img)){
190             $this->imgErr("access to this image/file has been denied.",$s);
191             
192         }
193         
194         $this->serve($img);
195         exit;
196     }
197     
198     function imgErr($reason,$path) {
199         header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
200             urlencode($reason) .'&path='.urlencode($path));
201         exit;
202     }
203     
204     function hasPermission($img) 
205     {
206         return true;
207     }
208     
209     function post($v)
210     {
211         
212         if (!$this->authUser) {
213             $this->jerr("image conversion only allowed by registered users");
214         }
215         // converts a posted string (eg.svg)
216         // into another type..
217         if (empty($_REQUEST['as'])) {
218            $this->jerr("missing target type");
219         }
220         if (empty($_REQUEST['mimetype'])) {
221             $this->jerr("missing mimetype");
222         }
223         if (empty($_REQUEST['data'])) {
224             $this->jerr("missing data");
225         }
226         
227         
228         $this->as_mimetype = $_REQUEST['as'];
229         $this->mimetype = $_REQUEST['mimetype'];
230         require_once 'File/MimeType.php';
231         $y = new File_MimeType();
232         $src_ext = $y->toExt( $this->mimetype );
233         
234         
235         $tmp = $this->tempName($src_ext);
236         file_put_contents($tmp, $_REQUEST['data']);
237         
238         require_once 'File/Convert.php';
239         $cv = new File_Convert($tmp, $this->mimetype);
240         
241         $fn = $cv->convert(
242                 $this->as_mimetype ,
243                 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
244                 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
245         );
246         if (!empty($_REQUEST['as_data'])) {
247             $this->jok(base64_encode(file_get_contents($fn)));
248         }
249         
250         $cv->serve('attachment');
251         exit;
252         
253         
254         
255     }
256     
257     
258  
259     function serve($img)
260     {
261         $this->sessionState(0); // turn off session... - locking...
262         
263         require_once 'File/Convert.php';
264         if (!file_exists($img->getStoreName())) {
265 //            print_r($img);exit;
266             header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
267                 urlencode("Original file was missing : " . $img->getStoreName()));
268     
269         }
270 //        print_r($img);exit;
271         $x = $img->toFileConvert();
272         if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
273             $this->as_mimetype  = $img->mimetype;
274         }
275         if (!$this->thumb) {
276             $x->convert( $this->as_mimetype);
277             $x->serve($this->method);
278             exit;
279         }
280         //echo "SKALING?  $this->size";
281         // acutally if we generated the image, then we do not need to validate the size..
282         
283         // if the mimetype is not converted..
284         // then the filename should be original.{size}.jpeg
285         $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
286         
287         if($img->mimetype == 'image/gif'){
288             $fn = $img->getStoreName() . '.'. $this->size . '.gif';
289         }
290         
291         if (!file_exists($fn)) {
292             $fn = $img->getStoreName()  . '.'. $this->size . '.'. $img->fileExt();
293             // if it's an image, convert into the same type for thumbnail..
294             if (preg_match('#^image/#', $img->mimetype)) {
295                $this->as_mimetype = $img->mimetype;
296             }
297         }
298         
299         if (!file_exists($fn)) {    
300             $this->validateSize();
301         }
302         
303         $x->convert( $this->as_mimetype, $this->size);
304         $x->serve();
305         exit;
306         
307         
308         
309         
310     }
311     function validateSize()
312     {
313         if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
314             || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
315             return true;
316         }
317         
318         
319         $ff = HTML_FlexyFramework::get();
320         
321         $sizes = array(
322                 '100', 
323                 '100x100', 
324                 '150', 
325                 '150x150', 
326                 '200', 
327                 '200x0',
328                 '200x200',  
329                 '400x0',
330                 '300x100',
331                 '500'
332             );
333         
334         $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
335                 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
336         
337         if (!empty($cfg['sizes'])) {
338             $sizes = array_merge($sizes , $cfg['sizes']);
339         }
340         
341         $project = $ff->project;
342         
343         require_once $ff->project . '.php';
344         
345         $project = str_replace('/', '_', $project);
346          
347         $pr_obj = new $project;
348          
349        // var_dump($pr_obj->Pman_Core_Images_Size);
350         if(isset($pr_obj->Pman_Core_Images_Size)){
351             $sizes = $pr_obj->Pman_Core_Images_Size;
352             
353             
354         }
355         
356         if (!in_array($this->size, $sizes)) {
357             die("invalid scale - ".$this->size);
358         }
359     }
360     /**
361      * replace image urls
362      *
363      * The idea of this code was to replace urls for images when you have an admin
364      * and a distribution page. with different urls.
365      *
366      * it may be usefull later if things like embedded images in emails. but
367      * I think it's proably better not to use this.
368      *
369      * The key problem being how to determine if we are replacing 'our' images or some external one..
370      * 
371      *
372      */
373     
374     
375     static function replaceImageURLS($html)
376     {
377         
378         $ff = HTML_FlexyFramework::get();
379         if (!isset($ff->Pman_Images['public_baseURL'])) {
380             return $html;
381         }
382         //var_dump($ff->Pman_Images['public_baseURL']);
383         $baseURL = $ff->Pman_Images['public_baseURL'];
384         
385         preg_match_all('/<img\s+[^>]+>/i',$html, $result); 
386         //print_r($result);
387         $matches = array_unique($result[0]);
388         foreach($matches as $img) {
389             $imatch = array();
390             preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
391             // build a keymap
392             $attr =  array();
393             
394             foreach($imatch[1] as $i=>$key) {
395                 $attr[$key] = $imatch[2][$i];
396             }
397             // does it contain baseURL??? --- well what about relative paths...
398             //print_R($attr);
399             
400             if (empty($attr['src'])) {
401                 continue;
402             }
403             if (0 !== strpos($attr['src'], $baseURL)) {
404                 // it starts with our 'new' baseURL?
405                 $html = self::replaceImgUrl($html, $baseURL, $img, $attr,  'src' );
406                 continue;
407             }
408             if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
409                 // contains an absolute path.. that is probably not us...
410                 continue;
411             }
412             // what about mailto or data... - just ignore?? for images...
413             
414             $html = self::replaceImgUrl($html, $baseURL, $img, $attr,  'src' );
415             
416         }
417         
418         
419         $result = array();
420         preg_match_all('/<a\s+[^>]+>/i',$html, $result); 
421
422         $matches = array_unique($result[0]);
423         foreach($matches as $img) {
424             $imatch = array();
425             preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
426             // build a keymap
427             $attr =  array();
428             
429             foreach($imatch[1] as $i=>$key) {
430                 $attr[$key] = $imatch[2][$i];
431             }
432             if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) { 
433                 continue;
434             }
435             $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
436         }
437         
438         return $html;
439     }
440     static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name) 
441     {
442         
443         //print_R($attr);
444         // see if it's an image url..
445         // Images/{ID}/fullname.xxxx
446         // Images/Thumb/200/{ID}/fullname.xxxx
447         // Images/Download/{ID}/fullname.xxxx
448         
449         $attr_url = $attr[$attr_name];
450         $umatch  = false;
451         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch))  {
452             return $html;
453         }
454         
455         $id = $umatch[2];
456         $hash = '';
457         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
458             $hash = '#'. array_pop(explode('#',$umatch[3]));
459         }
460         
461         
462         $img = DB_DataObject::factory('Images');
463         if (!$img->get($id)) {
464             return $html;
465         }
466         $type = explode('/', $umatch[1]);
467         $thumbsize = -1;
468          
469         if (count($type) > 2 && $type[1] == 'Thumb') {
470             $thumbsize = $type[2];
471             $provider = '/Images/Thumb';
472         } else {
473             $provider = '/'.$umatch[1];
474         }
475         
476         if (!empty($attr['width']) || !empty($attr['height']) )
477         {
478             // no support for %...
479             $thumbsize =
480                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
481                 'x' .
482                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
483              $provider = '/Images/Thumb';
484             
485         }
486         
487         if ($thumbsize !== -1) {
488             // change in size..
489             // need to regenerate it..
490             
491             $type = array('Images', 'Thumb', $thumbsize);
492                 
493             $fc = $img->toFileConvert();
494             // make sure it's available..
495             $fc->convert($img->mimetype, $thumbsize);
496             
497             
498         } else {
499             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
500         }
501         
502         
503         // finally replace the original TAG with the new version..
504         
505         $new_tag = str_replace(
506             $attr_name. '="'. $attr_url . '"',
507             $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
508             $tag
509         );
510         
511         
512         return str_replace($tag, $new_tag, $html);
513          
514     }
515     
516     function downloadEvent($bits)
517     {
518         $popts = PEAR::getStaticProperty('Pman','options');
519         $ev = DB_DAtaObject::Factory('events');
520         if (!$ev->get($bits[1])) {
521             die("could not find event id");
522         }
523         // technically same user only.. -- normally www-data..
524         if (function_exists('posix_getpwuid')) {
525             $uinfo = posix_getpwuid( posix_getuid () ); 
526             $user = $uinfo['name'];
527         } else {
528             $user = getenv('USERNAME'); // windows.
529         }
530         $ff = HTML_FlexyFramework::get();
531         $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
532         $filesJ = json_decode(file_get_contents($file));
533
534         //print_r($filesJ);
535
536         foreach($filesJ->FILES as $k=>$f){
537             if ($f->tmp_name != $bits[2]) {
538                 continue;
539             }
540
541             $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)).  $f->tmp_name ;
542             if (!file_exists($src)) {
543                 die("file was not saved");
544             }
545             header ('Content-Type: ' . $f->type);
546
547             header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );
548             @ob_clean();
549             flush();
550             readfile($src);
551             exit;
552         }
553     }
554     
555 }