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