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