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