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