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