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