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