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