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