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