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