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