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