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