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