Fix #5784 - COVERAGE BY REGION: Others
[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         
231         if (!$this->authUser) {
232             $this->jerr("image conversion only allowed by registered users");
233         }
234         // converts a posted string (eg.svg)
235         // into another type..
236         if (empty($_REQUEST['as'])) {
237            $this->jerr("missing target type");
238         }
239         if (empty($_REQUEST['mimetype'])) {
240             $this->jerr("missing mimetype");
241         }
242         if (empty($_REQUEST['data'])) {
243             $this->jerr("missing data");
244         }
245         
246         
247         $this->as_mimetype = $_REQUEST['as'];
248         $this->mimetype = $_REQUEST['mimetype'];
249         require_once 'File/MimeType.php';
250         $y = new File_MimeType();
251         $src_ext = $y->toExt( $this->mimetype );
252         
253         
254         $tmp = $this->tempName($src_ext);
255         file_put_contents($tmp, $_REQUEST['data']);
256         
257         require_once 'File/Convert.php';
258         $cv = new File_Convert($tmp, $this->mimetype);
259         
260         $fn = $cv->convert(
261                 $this->as_mimetype ,
262                 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
263                 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
264         );
265         if (!empty($_REQUEST['as_data'])) {
266             $this->jok(base64_encode(file_get_contents($fn)));
267         }
268         
269         $cv->serve('attachment');
270         exit;
271         
272         
273         
274     }
275     
276     
277  
278     function serve($img)
279     {
280         $this->sessionState(0); // turn off session... - locking...
281         
282         require_once 'File/Convert.php';
283         if (!file_exists($img->getStoreName())) {
284 //            print_r($img);exit;
285             header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
286                 urlencode("Original file was missing : " . $img->getStoreName()));
287     
288         }
289 //        print_r($img);exit;
290         $x = $img->toFileConvert();
291         if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
292             $this->as_mimetype  = $img->mimetype;
293         }
294         if (!$this->thumb) {
295             $x->convert( $this->as_mimetype);
296             $x->serve($this->method);
297             exit;
298         }
299         //echo "SKALING?  $this->size";
300         // acutally if we generated the image, then we do not need to validate the size..
301         
302         // if the mimetype is not converted..
303         // then the filename should be original.{size}.jpeg
304         $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
305         
306         if($img->mimetype == 'image/gif'){
307             $fn = $img->getStoreName() . '.'. $this->size . '.gif';
308         }
309         
310         if (!file_exists($fn)) {
311             $fn = $img->getStoreName()  . '.'. $this->size . '.'. $img->fileExt();
312             // if it's an image, convert into the same type for thumbnail..
313             if (preg_match('#^image/#', $img->mimetype)) {
314                $this->as_mimetype = $img->mimetype;
315             }
316         }
317         
318         if (!file_exists($fn)) {    
319             $this->validateSize();
320         }
321         
322         if(!empty($this->page) && !is_nan($this->page * 1)){
323             $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
324         } else {
325             $x->convert( $this->as_mimetype, $this->size);
326         }
327         
328         $x->serve();
329         exit;
330         
331         
332         
333         
334     }
335     function validateSize()
336     {
337         if($this->is_local) {
338             return true;
339         }
340         
341         if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
342             || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
343             return true;
344         }
345         
346         
347         $ff = HTML_FlexyFramework::get();
348         
349         $sizes= $this->sizes;
350         
351         $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
352                 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
353         
354         if (!empty($cfg['sizes'])) {
355             $sizes = array_merge($sizes , $cfg['sizes']);
356         }
357         
358         $project = $ff->project;
359         
360         require_once $ff->project . '.php';
361         
362         $project = str_replace('/', '_', $project);
363          
364         $pr_obj = new $project;
365          
366        // var_dump($pr_obj->Pman_Core_Images_Size);
367         if(isset($pr_obj->Pman_Core_Images_Size)){
368             $sizes = $pr_obj->Pman_Core_Images_Size;
369             
370             
371         }
372         
373         if (!in_array($this->size, $sizes)) {
374             die("invalid scale - ".$this->size);
375         }
376     }
377     /**
378      * replace image urls
379      *
380      * The idea of this code was to replace urls for images when you have an admin
381      * and a distribution page. with different urls.
382      *
383      * it may be usefull later if things like embedded images in emails. but
384      * I think it's proably better not to use this.
385      *
386      * The key problem being how to determine if we are replacing 'our' images or some external one..
387      * 
388      *
389      */
390     
391     
392     static function replaceImageURLS($html)
393     {
394         
395         $ff = HTML_FlexyFramework::get();
396         if (!isset($ff->Pman_Images['public_baseURL'])) {
397             return $html;
398         }
399         //var_dump($ff->Pman_Images['public_baseURL']);
400         $baseURL = $ff->Pman_Images['public_baseURL'];
401         
402         preg_match_all('/<img\s+[^>]+>/i',$html, $result); 
403         //print_r($result);
404         $matches = array_unique($result[0]);
405         foreach($matches as $img) {
406             $imatch = array();
407             preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
408             // build a keymap
409             $attr =  array();
410             
411             foreach($imatch[1] as $i=>$key) {
412                 $attr[$key] = $imatch[2][$i];
413             }
414             // does it contain baseURL??? --- well what about relative paths...
415             //print_R($attr);
416             
417             if (empty($attr['src'])) {
418                 continue;
419             }
420             if (0 !== strpos($attr['src'], $baseURL)) {
421                 // it starts with our 'new' baseURL?
422                 $html = self::replaceImgUrl($html, $baseURL, $img, $attr,  'src' );
423                 continue;
424             }
425             if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
426                 // contains an absolute path.. that is probably not us...
427                 continue;
428             }
429             // what about mailto or data... - just ignore?? for images...
430             
431             $html = self::replaceImgUrl($html, $baseURL, $img, $attr,  'src' );
432             
433         }
434         
435         
436         $result = array();
437         preg_match_all('/<a\s+[^>]+>/i',$html, $result); 
438
439         $matches = array_unique($result[0]);
440         foreach($matches as $img) {
441             $imatch = array();
442             preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
443             // build a keymap
444             $attr =  array();
445             
446             foreach($imatch[1] as $i=>$key) {
447                 $attr[$key] = $imatch[2][$i];
448             }
449             if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) { 
450                 continue;
451             }
452             $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
453         }
454         
455         return $html;
456     }
457     static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name) 
458     {
459         
460         //print_R($attr);
461         // see if it's an image url..
462         // Images/{ID}/fullname.xxxx
463         // Images/Thumb/200/{ID}/fullname.xxxx
464         // Images/Download/{ID}/fullname.xxxx
465         
466         $attr_url = $attr[$attr_name];
467         $umatch  = false;
468         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch))  {
469             return $html;
470         }
471         
472         $id = $umatch[2];
473         $hash = '';
474         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
475             $hh = explode('#',$umatch[3]);
476             $hash = '#'. array_pop($hh);
477         }
478         
479         
480         $img = DB_DataObject::factory('Images');
481         if (!$img->get($id)) {
482             return $html;
483         }
484         $type = explode('/', $umatch[1]);
485         $thumbsize = -1;
486          
487         if (count($type) > 2 && $type[1] == 'Thumb') {
488             $thumbsize = $type[2];
489             $provider = '/Images/Thumb';
490         } else {
491             $provider = '/'.$umatch[1];
492         }
493         
494         if (!empty($attr['width']) || !empty($attr['height']) )
495         {
496             // no support for %...
497             $thumbsize =
498                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
499                 'x' .
500                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
501              $provider = '/Images/Thumb';
502             
503         }
504         
505         if ($thumbsize !== -1) {
506             // change in size..
507             // need to regenerate it..
508             
509             $type = array('Images', 'Thumb', $thumbsize);
510                 
511             $fc = $img->toFileConvert();
512             // make sure it's available..
513             $fc->convert($img->mimetype, $thumbsize);
514             
515             
516         } else {
517             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
518         }
519         
520         
521         // finally replace the original TAG with the new version..
522         
523         $new_tag = str_replace(
524             $attr_name. '="'. $attr_url . '"',
525             $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
526             $tag
527         );
528         
529         
530         return str_replace($tag, $new_tag, $html);
531          
532     }
533     
534     function downloadEvent($bits)
535     {
536         $ev = DB_DAtaObject::Factory('events');
537         if (!$ev->get($bits[1])) {
538             die("could not find event id");
539         }
540         // technically same user only.. -- normally www-data..
541         if (function_exists('posix_getpwuid')) {
542             $uinfo = posix_getpwuid( posix_getuid () ); 
543             $user = $uinfo['name'];
544         } else {
545             $user = getenv('USERNAME'); // windows.
546         }
547         $ff = HTML_FlexyFramework::get();
548         
549         $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
550         
551         if(!$file || !file_exists($file)){
552             die("file was not saved");
553         }
554         
555         $filesJ = json_decode(file_get_contents($file));
556
557         foreach($filesJ->FILES as $k=>$f){
558             if ($f->tmp_name != $bits[2]) {
559                 continue;
560             }
561
562             $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)).  $f->tmp_name ;
563             
564             if (!$src || !file_exists($src)) {
565                 die("file was not saved");
566             }
567             header ('Content-Type: ' . $f->type);
568
569             header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );
570             @ob_clean();
571             flush();
572             readfile($src);
573             exit;
574         }
575     }
576     
577 }