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