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