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