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