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