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