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             $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
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         $this->serve($img);
164         exit;
165     }
166     
167     function hasPermission($img) 
168     {
169         return true;
170     }
171     
172     function post()
173     {
174         
175         if (!$this->authUser) {
176             $this->jerr("image conversion only allowed by registered users");
177         }
178         // converts a posted string (eg.svg)
179         // into another type..
180         if (empty($_REQUEST['as'])) {
181            $this->jerr("missing target type");
182         }
183         if (empty($_REQUEST['mimetype'])) {
184             $this->jerr("missing mimetype");
185         }
186         if (empty($_REQUEST['data'])) {
187             $this->jerr("missing data");
188         }
189         
190         
191         $this->as_mimetype = $_REQUEST['as'];
192         $this->mimetype = $_REQUEST['mimetype'];
193         require_once 'File/MimeType.php';
194         $y = new File_MimeType();
195         $src_ext = $y->toExt( $this->mimetype );
196         
197         
198         $tmp = $this->tempName($src_ext);
199         file_put_contents($tmp, $_REQUEST['data']);
200         
201         require_once 'File/Convert.php';
202         $cv = new File_Convert($tmp, $this->mimetype);
203         
204         $fn = $cv->convert(
205                 $this->as_mimetype ,
206                 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
207                 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
208         );
209         if (!empty($_REQUEST['as_data'])) {
210             $this->jok(base64_encode(file_get_contents($fn)));
211         }
212         
213         $cv->serve('attachment');
214         exit;
215         
216         
217         
218     }
219     
220     
221  
222     function serve($img)
223     {
224         $this->sessionState(0); // turn off session... - locking...
225         
226         require_once 'File/Convert.php';
227         if (!file_exists($img->getStoreName())) {
228 //            print_r($img);exit;
229             header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
230                 urlencode("Original file was missing : " . $img->getStoreName()));
231     
232         }
233 //        print_r($img);exit;
234         $x = $img->toFileConvert();
235         if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
236             $this->as_mimetype  = $img->mimetype;
237         }
238         if (!$this->thumb) {
239             $x->convert( $this->as_mimetype);
240             $x->serve($this->method);
241             exit;
242         }
243         //echo "SKALING?  $this->size";
244         // acutally if we generated the image, then we do not need to validate the size..
245         
246         require_once 'File/MimeType.php';
247         $y = new File_MimeType();
248         $ext = $y->toExt(trim((string) $this->as_mimetype ));
249         
250         print_r($ext);exit;
251         
252         
253         // if the mimetype is not converted..
254         // then the filename should be original.{size}.jpeg
255         $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
256         
257         if (!file_exists($fn)) {
258             $fn = $img->getStoreName()  . '.'. $this->size . '.'. $img->fileExt();
259             // if it's an image, convert into the same type for thumbnail..
260             if (preg_match('#^image/#', $img->mimetype)) {
261                $this->as_mimetype = $img->mimetype;
262             }
263         }
264         
265         if (!file_exists($fn)) {    
266             $this->validateSize();
267         }
268         
269         $x->convert( $this->as_mimetype, $this->size);
270         $x->serve();
271         exit;
272         
273         
274         
275         
276     }
277     function validateSize()
278     {
279         if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER') || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
280             return true;
281         }
282         
283         
284         $ff = HTML_FlexyFramework::get();
285         
286         $sizes = array(
287                 '100', 
288                 '100x100', 
289                 '150', 
290                 '150x150', 
291                 '200', 
292                 '200x0',
293                 '200x200',  
294                 '400x0',
295                 '300x100',
296                 '500'
297             );
298         
299         $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
300                 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
301         
302         if (!empty($cfg['sizes'])) {
303             $sizes = array_merge($sizes , $cfg['sizes']);
304         }
305         
306         $project = $ff->project;
307         
308         require_once $ff->project . '.php';
309         
310         $project = new $ff->project();
311         
312         if(isset($project::$Pman_Core_Images_Size)){
313             $sizes = $project::$Pman_Core_Images_Size;
314         }
315         
316         if (!in_array($this->size, $sizes)) {
317             die("invalid scale - ".$this->size);
318         }
319     }
320     /**
321      * replace image urls
322      *
323      * The idea of this code was to replace urls for images when you have an admin
324      * and a distribution page. with different urls.
325      *
326      * it may be usefull later if things like embedded images in emails. but
327      * I think it's proably better not to use this.
328      *
329      * The key problem being how to determine if we are replacing 'our' images or some external one..
330      * 
331      *
332      */
333     
334     
335     static function replaceImageURLS($html)
336     {
337         
338         $ff = HTML_FlexyFramework::get();
339         if (!isset($ff->Pman_Images['public_baseURL'])) {
340             return $html;
341         }
342         //var_dump($ff->Pman_Images['public_baseURL']);
343         $baseURL = $ff->Pman_Images['public_baseURL'];
344         
345         preg_match_all('/<img\s+[^>]+>/i',$html, $result); 
346         //print_r($result);
347         $matches = array_unique($result[0]);
348         foreach($matches as $img) {
349             $imatch = array();
350             preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
351             // build a keymap
352             $attr =  array();
353             
354             foreach($imatch[1] as $i=>$key) {
355                 $attr[$key] = $imatch[2][$i];
356             }
357             // does it contain baseURL??? --- well what about relative paths...
358             //print_R($attr);
359             
360             if (empty($attr['src'])) {
361                 continue;
362             }
363             if (0 !== strpos($attr['src'], $baseURL)) {
364                 // it starts with our 'new' baseURL?
365                 $html = self::replaceImgUrl($html, $baseURL, $img, $attr,  'src' );
366                 continue;
367             }
368             if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
369                 // contains an absolute path.. that is probably not us...
370                 continue;
371             }
372             // what about mailto or data... - just ignore?? for images...
373             
374             $html = self::replaceImgUrl($html, $baseURL, $img, $attr,  'src' );
375             
376         }
377         
378         
379         $result = array();
380         preg_match_all('/<a\s+[^>]+>/i',$html, $result); 
381
382         $matches = array_unique($result[0]);
383         foreach($matches as $img) {
384             $imatch = array();
385             preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
386             // build a keymap
387             $attr =  array();
388             
389             foreach($imatch[1] as $i=>$key) {
390                 $attr[$key] = $imatch[2][$i];
391             }
392             if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) { 
393                 continue;
394             }
395             $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
396         }
397         
398         return $html;
399     }
400     static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name) 
401     {
402         
403         //print_R($attr);
404         // see if it's an image url..
405         // Images/{ID}/fullname.xxxx
406         // Images/Thumb/200/{ID}/fullname.xxxx
407         // Images/Download/{ID}/fullname.xxxx
408         
409         $attr_url = $attr[$attr_name];
410         $umatch  = false;
411         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch))  {
412             return $html;
413         }
414         
415         $id = $umatch[2];
416         $hash = '';
417         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
418             $hash = '#'. array_pop(explode('#',$umatch[3]));
419         }
420         
421         
422         $img = DB_DataObject::factory('Images');
423         if (!$img->get($id)) {
424             return $html;
425         }
426         $type = explode('/', $umatch[1]);
427         $thumbsize = -1;
428          
429         if (count($type) > 2 && $type[1] == 'Thumb') {
430             $thumbsize = $type[2];
431             $provider = '/Images/Thumb';
432         } else {
433             $provider = '/'.$umatch[1];
434         }
435         
436         if (!empty($attr['width']) || !empty($attr['height']) )
437         {
438             // no support for %...
439             $thumbsize =
440                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
441                 'x' .
442                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
443              $provider = '/Images/Thumb';
444             
445         }
446         
447         if ($thumbsize !== -1) {
448             // change in size..
449             // need to regenerate it..
450             
451             $type = array('Images', 'Thumb', $thumbsize);
452                 
453             $fc = $img->toFileConvert();
454             // make sure it's available..
455             $fc->convert($img->mimetype, $thumbsize);
456             
457             
458         } else {
459             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
460         }
461         
462         
463         // finally replace the original TAG with the new version..
464         
465         $new_tag = str_replace(
466             $attr_name. '="'. $attr_url . '"',
467             $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
468             $tag
469         );
470         
471         
472         return str_replace($tag, $new_tag, $html);
473          
474     }
475     
476     function downloadEvent($bits)
477     {
478         $popts = PEAR::getStaticProperty('Pman','options');
479         $ev = DB_DAtaObject::Factory('events');
480         if (!$ev->get($bits[1])) {
481             die("could not find event id");
482         }
483         // technically same user only.. -- normally www-data..
484         if (function_exists('posix_getpwuid')) {
485             $uinfo = posix_getpwuid( posix_getuid () ); 
486             $user = $uinfo['name'];
487         } else {
488             $user = getenv('USERNAME'); // windows.
489         }
490         $ff = HTML_FlexyFramework::get();
491         $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
492         $filesJ = json_decode(file_get_contents($file));
493
494         //print_r($filesJ);
495
496         foreach($filesJ->FILES as $k=>$f){
497             if ($f->tmp_name != $bits[2]) {
498                 continue;
499             }
500
501             $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)).  $f->tmp_name ;
502             if (!file_exists($src)) {
503                 die("file was not saved");
504             }
505             header ('Content-Type: ' . $f->type);
506
507             header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );
508             @ob_clean();
509             flush();
510             readfile($src);
511             exit;
512         }
513     }
514     
515 }