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