9db0912e8b9f61d1c98058b49303469294f4eff1
[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 $is_email = false;
48     
49     var  $sizes = array(
50                 '100', 
51                 '100x100', 
52                 '150', 
53                 '150x150', 
54                 '200', 
55                 '200x0',
56                 '200x200',  
57                 '400x0',
58                 '300x100',
59                 '500'
60             );
61     function getAuth()
62     {
63         parent::getAuth(); // load company!
64         //return true;
65         $au = $this->getAuthUser();
66         
67         if (!$au) {
68             $this->authUser = false;
69             return true;//die("Access denied");
70         }
71         
72         $this->authUser = $au;
73         
74         return true;
75     }
76     var $thumb = false;
77     var $as_mimetype = false;
78     var $method = 'inline';
79     var $page = false;
80     
81     function get($s, $opts=array()) // determin what to serve!!!!
82     {
83         // for testing only.
84         //if (!empty($_GET['_post'])) {
85         //   return $this->post();
86         //}
87         
88         $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
89         
90         $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
91         
92         $bits= explode('/', $s);
93         $id = 0;
94 //        var_dump($bits);die('in');
95         // without id as first part...
96         if (!empty($bits[0]) && $bits[0] == 'Thumb') {
97             $this->thumb = true;
98             $this->as_mimetype = 'image/jpeg';
99             $this->size = empty($bits[1]) ? '0x0' : $bits[1];
100             $id = empty($bits[2]) ? 0 :   $bits[2];
101             
102         } else if (!empty($bits[0]) && $bits[0] == 'Download') {
103             $this->method = 'attachment';
104             $id = empty($bits[1]) ? 0 :   $bits[1];
105             
106         } else  if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
107             $this->thumb = true;
108             $this->as_mimetype = 'image/jpeg';
109             $this->size = empty($bits[2]) ? '0x0' : $bits[2];
110             $id = empty($bits[3]) ? 0 :   $bits[3];
111             
112         } else if (!empty($bits[0]) && $bits[0] == 'events') {
113             if (!$this->authUser) {
114                 $this->imgErr("no-authentication-events",$s);
115             }
116             $this->downloadEvent($bits);
117             $this->imgErr("unknown file",$s);
118             
119             
120         } else {
121         
122             $id = empty($bits[0]) ? 0 :  $bits[0];
123         }
124         
125         if (strpos($id,':') > 0) {  // id format  tablename:id:-imgtype
126             
127             if (!$this->authUser) {
128                 $this->imgErr("not-authenticated-using-colon-format",$s);
129                 
130             }
131             
132             $onbits = explode(':', $id);
133             if ((count($onbits) < 2)   || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
134                 $this->imgErr("bad-url",$s);
135                 
136             }
137             //DB_DataObject::debugLevel(1);
138             $img = DB_DataObject::factory('Images');
139             $img->ontable = $onbits[0];
140             $img->onid = $onbits[1];
141             if (empty($_REQUEST['anytype'])) {
142                 $img->whereAdd("mimetype like 'image/%'");
143             }
144             $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
145             if (isset($onbits[2])) {
146                 $img->imgtype = $onbits[2];
147             }
148             $img->limit(1);
149             if (!$img->find(true)) {
150                 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
151                 
152             }
153             
154             $id = $img->id;
155             
156             
157         }
158         $id = (int) $id;
159         
160         // depreciated - should use ontable:onid:type here...
161         if (!empty($_REQUEST['ontable'])) {
162             
163             if (!$this->authUser) {
164                 die("authentication required");
165             }
166             
167             //DB_DataObjecT::debugLevel(1);
168             $img = DB_DataObject::factory('Images');
169             $img->setFrom($_REQUEST);
170            
171             
172             
173             $img->limit(1);
174             if (!$img->find(true)) {
175                 $this->imgErr("No file exists",$s);
176             } 
177             $id = $img->id;
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             
200             return $this->serve($img);
201             
202         }
203         
204         if(!$this->hasPermission($img)){
205             $this->imgErr("access to this image/file has been denied.",$s);
206         }
207         
208         $this->serve($img);
209         exit;
210     }
211     
212     function imgErr($reason,$path) {
213         header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
214             urlencode($reason) .'&path='.urlencode($path));
215         exit;
216     }
217     
218     function hasPermission($img) 
219     {
220         return true;
221     }
222     
223     function post($v)
224     {
225         
226         if (!$this->authUser) {
227             $this->jerr("image conversion only allowed by registered users");
228         }
229         // converts a posted string (eg.svg)
230         // into another type..
231         if (empty($_REQUEST['as'])) {
232            $this->jerr("missing target type");
233         }
234         if (empty($_REQUEST['mimetype'])) {
235             $this->jerr("missing mimetype");
236         }
237         if (empty($_REQUEST['data'])) {
238             $this->jerr("missing data");
239         }
240         
241         
242         $this->as_mimetype = $_REQUEST['as'];
243         $this->mimetype = $_REQUEST['mimetype'];
244         require_once 'File/MimeType.php';
245         $y = new File_MimeType();
246         $src_ext = $y->toExt( $this->mimetype );
247         
248         
249         $tmp = $this->tempName($src_ext);
250         file_put_contents($tmp, $_REQUEST['data']);
251         
252         require_once 'File/Convert.php';
253         $cv = new File_Convert($tmp, $this->mimetype);
254         
255         $fn = $cv->convert(
256                 $this->as_mimetype ,
257                 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
258                 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
259         );
260         if (!empty($_REQUEST['as_data'])) {
261             $this->jok(base64_encode(file_get_contents($fn)));
262         }
263         
264         $cv->serve('attachment');
265         exit;
266         
267         
268         
269     }
270     
271     
272  
273     function serve($img)
274     {
275         $this->sessionState(0); // turn off session... - locking...
276         
277         require_once 'File/Convert.php';
278         if (!file_exists($img->getStoreName())) {
279 //            print_r($img);exit;
280             header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
281                 urlencode("Original file was missing : " . $img->getStoreName()));
282     
283         }
284 //        print_r($img);exit;
285         $x = $img->toFileConvert();
286         if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
287             $this->as_mimetype  = $img->mimetype;
288         }
289         if (!$this->thumb) {
290             $x->convert( $this->as_mimetype);
291             $x->serve($this->method);
292             exit;
293         }
294         //echo "SKALING?  $this->size";
295         // acutally if we generated the image, then we do not need to validate the size..
296         
297         // if the mimetype is not converted..
298         // then the filename should be original.{size}.jpeg
299         $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
300         
301         if($img->mimetype == 'image/gif'){
302             $fn = $img->getStoreName() . '.'. $this->size . '.gif';
303         }
304         
305         if (!file_exists($fn)) {
306             $fn = $img->getStoreName()  . '.'. $this->size . '.'. $img->fileExt();
307             // if it's an image, convert into the same type for thumbnail..
308             if (preg_match('#^image/#', $img->mimetype)) {
309                $this->as_mimetype = $img->mimetype;
310             }
311         }
312         
313         if (!file_exists($fn)) {    
314             $this->validateSize();
315         }
316         
317         if(!empty($this->page) && !is_nan($this->page * 1)){
318             $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
319         } else {
320             $x->convert( $this->as_mimetype, $this->size);
321         }
322         
323         $x->serve();
324         exit;
325         
326         
327         
328         
329     }
330     function validateSize()
331     {
332         if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
333             || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
334             return true;
335         }
336         
337         
338         $ff = HTML_FlexyFramework::get();
339         
340         $sizes= $this->sizes;
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             $hh = explode('#',$umatch[3]);
467             $hash = '#'. array_pop($hh);
468         }
469         
470         
471         $img = DB_DataObject::factory('Images');
472         if (!$img->get($id)) {
473             return $html;
474         }
475         $type = explode('/', $umatch[1]);
476         $thumbsize = -1;
477          
478         if (count($type) > 2 && $type[1] == 'Thumb') {
479             $thumbsize = $type[2];
480             $provider = '/Images/Thumb';
481         } else {
482             $provider = '/'.$umatch[1];
483         }
484         
485         if (!empty($attr['width']) || !empty($attr['height']) )
486         {
487             // no support for %...
488             $thumbsize =
489                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
490                 'x' .
491                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
492              $provider = '/Images/Thumb';
493             
494         }
495         
496         if ($thumbsize !== -1) {
497             // change in size..
498             // need to regenerate it..
499             
500             $type = array('Images', 'Thumb', $thumbsize);
501                 
502             $fc = $img->toFileConvert();
503             // make sure it's available..
504             $fc->convert($img->mimetype, $thumbsize);
505             
506             
507         } else {
508             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
509         }
510         
511         
512         // finally replace the original TAG with the new version..
513         
514         $new_tag = str_replace(
515             $attr_name. '="'. $attr_url . '"',
516             $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
517             $tag
518         );
519         
520         
521         return str_replace($tag, $new_tag, $html);
522          
523     }
524     
525     function downloadEvent($bits)
526     {
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         
540         $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
541         
542         if(!$file || !file_exists($file)){
543             die("file was not saved");
544         }
545         
546         $filesJ = json_decode(file_get_contents($file));
547
548         foreach($filesJ->FILES as $k=>$f){
549             if ($f->tmp_name != $bits[2]) {
550                 continue;
551             }
552
553             $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)).  $f->tmp_name ;
554             
555             if (!$src || !file_exists($src)) {
556                 die("file was not saved");
557             }
558             header ('Content-Type: ' . $f->type);
559
560             header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );
561             @ob_clean();
562             flush();
563             readfile($src);
564             exit;
565         }
566     }
567     
568 }