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