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  *
6  * NOTE THIS WAS NEVER INTENDED FOR PUBLIC IMAGE DISTRIBUTION - we need to create a seperate file for that...
7  *
8  * $str = Pman_Core_Images::replaceImg($str); // < use with HTML
9  *
10  * or
11  *
12  * Deliver image /file etc..
13  * 
14  * Use Cases:
15  * 
16  * args: ontable request
17  *      ontable (req) tablename.
18  *      filename
19  *      (other table args)
20  *      as (serve as a type) = eg. ?as=audio/mpeg 
21  * 
22  * args: generic
23  *     as :(serve as a type) = eg. mimetype.
24  * 
25  * Images/{ID}/fullname.xxxx
26  * 
27  * (valid thumbs 200, 400)...?
28  * Images/Thumb/200/{ID}/fullname.xxxx
29  * Images/Download/{ID}/fullname.xxxx
30  *
31  *
32  *
33  * 
34  * Used to be in Base... now in core..
35  *
36  * 
37  * view permission should be required on the underlying object...
38  * 
39  */
40 require_once  'Pman.php';
41 class Pman_Core_Images extends Pman
42 {
43     
44     // tables that do not need authentication checks before serving.
45     var $public_image_tables = array(
46         'crm_mailing_list_message'   // we know these are ok...
47     );
48     
49     var  $sizes = array(
50                 '100', 
51                 '100x100', 
52                 '150', 
53                 '150x150', 
54                 '200', 
55                 '200x0',
56                 '200x200',  
57                 '400x0',
58                 '300x100',
59                 '500'
60             );
61     function getAuth()
62     {
63         parent::getAuth(); // load company!
64         //return true;
65         $au = $this->getAuthUser();
66         var_dump($au);
67         die('b');
68         
69         if (!$au) {
70             $this->authUser = false;
71             return true;//die("Access denied");
72         }
73         
74         $this->authUser = $au;
75         
76         return true;
77     }
78     var $thumb = false;
79     var $as_mimetype = false;
80     var $method = 'inline';
81     var $page = false;
82     var $is_local = false;
83     var $size;
84     
85     
86     function get($s, $opts=array()) // determin what to serve!!!!
87     {
88         // for testing only.
89         //if (!empty($_GET['_post'])) {
90         //   return $this->post();
91         //}
92      
93         
94         
95         $this->is_local = (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') ? true : false;
96         
97         $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
98         
99         $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
100         
101         $bits= explode('/', $s);
102         $id = 0;
103 //        var_dump($bits);die('in');
104         // without id as first part...
105         if (!empty($bits[0]) && $bits[0] == 'Thumb') {
106             $this->thumb = true;
107             $this->as_mimetype = 'image/jpeg';
108             $this->size = empty($bits[1]) ? '0x0' : $bits[1];
109             $id = empty($bits[2]) ? 0 :   $bits[2];
110             
111         } else if (!empty($bits[0]) && $bits[0] == 'Download') {
112             $this->method = 'attachment';
113             $id = empty($bits[1]) ? 0 :   $bits[1];
114             
115         } else  if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
116             $this->thumb = true;
117             $this->as_mimetype = 'image/jpeg';
118             $this->size = empty($bits[2]) ? '0x0' : $bits[2];
119             $id = empty($bits[3]) ? 0 :   $bits[3];
120             
121         } else if (!empty($bits[0]) && $bits[0] == 'events') {
122             if (!$this->authUser) {
123                 $this->imgErr("no-authentication-events",$s);
124             }
125             $this->downloadEvent($bits);
126             $this->imgErr("unknown file",$s);
127             
128             
129         } else {
130         
131             $id = empty($bits[0]) ? 0 :  $bits[0];
132         }
133         
134         if (strpos($id,':') > 0) {  // id format  tablename:id:-imgtype
135             //DB_DataObject::debugLevel(1);
136             if (!$this->authUser) {
137                 $this->imgErr("not-authenticated-using-colon-format",$s);
138                 
139             }
140             
141             $onbits = explode(':', $id);
142             if ((count($onbits) < 2)   || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
143                 $this->imgErr("bad-url",$s);
144                 
145             }
146             //DB_DataObject::debugLevel(1);
147             $img = DB_DataObject::factory('Images');
148             $img->ontable = $onbits[0];
149             $img->onid = $onbits[1];
150             if (empty($_REQUEST['anytype'])) {
151                 $img->whereAdd("mimetype like 'image/%'");
152             }
153             $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
154             if (isset($onbits[2])) {
155                 $img->imgtype = $onbits[2];
156             }
157             $img->limit(1);
158             if (!$img->find(true)) {
159                 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
160                 
161             }
162             
163             $id = $img->id;
164             
165             
166         }
167         $id = (int) $id;
168         
169         // depreciated - should use ontable:onid:type here...
170         if (!empty($_REQUEST['ontable'])) {
171             
172             if (!$this->authUser) {
173                 die("authentication required");
174             }
175             
176             //DB_DataObjecT::debugLevel(1);
177             $img = DB_DataObject::factory('Images');
178             $img->setFrom($_REQUEST);
179            
180             
181             
182             $img->limit(1);
183             if (!$img->find(true)) {
184                 $this->imgErr("No file exists",$s);
185             } 
186             $id = $img->id;
187             
188         }
189         
190         $img = DB_DataObjecT::factory('Images');
191          
192         if (!$id || !$img->get($id) || !$img->exists()) {
193            //print_r($img);           die("HERE");
194             $this->imgErr("image has been removed or deleted.",$s);
195         }
196         
197         if($this->is_local) {
198             return $this->serve($img);
199         }
200         
201         if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
202             
203             if ($img->ontable != 'core_company') {
204                 $this->imgErr("not-authenticated {$img->ontable}",$s);
205             }
206             if ($img->imgtype != 'LOGO') {
207                 $this->imgErr("not-logo",$s);
208             }
209             $comp  = $img->object();
210             if ($comp->comptype != 'OWNER') {
211                 $this->imgErr("not-owner-company",$s);
212             }
213             
214             return $this->serve($img);
215             
216         }
217         
218         if(!$this->hasPermission($img)){
219             $this->imgErr("access to this image/file has been denied.",$s);
220         }
221         
222         $this->serve($img);
223         exit;
224     }
225     
226     function imgErr($reason,$path) {
227         header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' . urlencode($reason) );
228         header('X-Error: ' . $reason . ':' . $path);
229         echo $reason . ':' . $path;
230         exit;
231     }
232     
233     function hasPermission($img) 
234     {
235         return true;
236     }
237     
238     function post($v)
239     {
240         if (!empty($_REQUEST['_get'])) {
241             return $this->get($v);
242         }
243         
244         if (!$this->authUser) {
245             $this->jerr("image conversion only allowed by registered users");
246         }
247         // converts a posted string (eg.svg)
248         // into another type..
249         if (empty($_REQUEST['as'])) {
250            $this->jerr("missing target type");
251         }
252         if (empty($_REQUEST['mimetype'])) {
253             $this->jerr("missing mimetype");
254         }
255         if (empty($_REQUEST['data'])) {
256             $this->jerr("missing data");
257         }
258         
259         
260         $this->as_mimetype = $_REQUEST['as'];
261         $this->mimetype = $_REQUEST['mimetype'];
262         require_once 'File/MimeType.php';
263         $y = new File_MimeType();
264         $src_ext = $y->toExt( $this->mimetype );
265         
266         
267         $tmp = $this->tempName($src_ext);
268         file_put_contents($tmp, $_REQUEST['data']);
269         
270         require_once 'File/Convert.php';
271         $cv = new File_Convert($tmp, $this->mimetype);
272         
273         $fn = $cv->convert(
274                 $this->as_mimetype ,
275                 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
276                 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
277         );
278         if (!empty($_REQUEST['as_data'])) {
279             $this->jok(base64_encode(file_get_contents($fn)));
280         }
281         
282         $cv->serve('attachment');
283         exit;
284         
285         
286         
287     }
288     
289     
290  
291     function serve($img)
292     {
293         
294         $this->sessionState(0); // turn off session... - locking...
295         require_once 'File/Convert.php';
296         if (!$img->exists()) {
297             $this->imgErr("serve = missing-image", $img->getStoreName());
298              
299         }
300 //        print_r($img);exit;
301         $x = $img->toFileConvert();
302         if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
303             $this->as_mimetype  = $img->mimetype;
304         }
305         
306         
307         if (!$this->thumb) {
308             if ($x->mimetype == $this->as_mimetype) {
309                 $x->serveOnly($this->method, $img->filename);
310                 exit;
311             }
312             $x->convert( $this->as_mimetype);
313             $x->serve($this->method, $img->filename);
314             exit;
315         }
316         //echo "SKALING?  $this->size";
317         // acutally if we generated the image, then we do not need to validate the size..
318         
319         // if the mimetype is not converted..
320         // then the filename should be original.{size}.jpeg
321         $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
322         
323         if($img->mimetype == 'image/gif'){
324             $fn = $img->getStoreName() . '.'. $this->size . '.gif';
325         }
326         
327         if (!file_exists($fn)) {
328             $fn = $img->getStoreName()  . '.'. $this->size . '.'. $img->fileExt();
329             // if it's an image, convert into the same type for thumbnail..
330             if (preg_match('#^image/#', $img->mimetype)) {
331                $this->as_mimetype = $img->mimetype;
332             }
333         }
334         
335         if (!file_exists($fn)) {    
336             $this->validateSize();
337         }
338        
339         
340         if(!empty($this->page) && !is_nan($this->page * 1)){
341             $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
342         } else {
343             $x->convert( $this->as_mimetype, $this->size);
344         }
345         
346         $x->serve();
347         exit;
348         
349         
350         
351         
352     }
353     function validateSize()
354     {
355         if($this->is_local) {
356             return true;
357         }
358         
359         if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
360             || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
361             return true;
362         }
363         
364         
365         $ff = HTML_FlexyFramework::get();
366         
367         $sizes= $this->sizes;
368         
369         $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
370                 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
371         
372         if (!empty($cfg['sizes'])) {
373             $sizes = array_merge($sizes , $cfg['sizes']);
374         }
375         
376         $project = $ff->project;
377         
378         require_once $ff->project . '.php';
379         
380         $project = str_replace('/', '_', $project);
381          
382         $pr_obj = new $project;
383          
384        // var_dump($pr_obj->Pman_Core_Images_Size);
385         if(isset($pr_obj->Pman_Core_Images_Size)){
386             $sizes = $pr_obj->Pman_Core_Images_Size;
387             
388             
389         }
390         
391         if (!in_array($this->size, $sizes)) {
392             die("invalid scale - ".$this->size);
393         }
394     }
395     /**
396      * replace image urls
397      *
398      * The idea of this code was to replace urls for images when you have an admin
399      * and a distribution page. with different urls.
400      *
401      * it may be usefull later if things like embedded images in emails. but
402      * I think it's proably better not to use this.
403      *
404      * The key problem being how to determine if we are replacing 'our' images or some external one..
405      * 
406      *
407      */
408     
409     
410     static function replaceImageURLS($html, $obj = false)
411     {
412         
413         $ff = HTML_FlexyFramework::get();
414         if (!isset($ff->Pman_Images['public_baseURL'])) {
415             return $html;
416         }
417         //var_dump($ff->Pman_Images['public_baseURL']);
418         $baseURL = $ff->Pman_Images['public_baseURL'];
419         
420         libxml_use_internal_errors(true);
421         $dom = new DOMDocument();
422         $dom->loadHTML("<?xml encoding='utf-8'?> <div id='tmp_dom_wrapper'>{$html}</div>");
423         $imgs = $dom->getElementsByTagName('img');
424        
425         
426         foreach($imgs as $img) {
427             $src = $img->getAttribute('src');
428             if (!$src|| !strlen(trim($src))) {
429                 continue;
430             }
431              
432             if (0 === strpos($src, 'data:')) {
433                 if (!$obj) {
434                     HTML_FlexyFramework::get()->page->jerr("no object to attach data url");
435                 }
436                 
437                 self::replaceDataUrl($baseURL, $img, $obj);
438                 continue;
439             }
440             
441             
442             if (false !== strpos($src, '//') && false === strpos($src, $baseURL)) {
443                 // contains an absolute path.. and not our baseURL.
444                 continue;
445             }
446              
447             $img->setAttribute('src', self::domImgUrl($baseURL, $img));
448               
449             // what about mailto or data... - just ignore?? for images...
450             
451             
452         }
453         
454         $anchors = $dom->getElementsByTagName('a');
455         $result = array();
456         preg_match_all('/<a\s+[^>]+>/i',$html, $result); 
457
458         $matches = array_unique($result[0]);
459         foreach($anchors as $anc) {
460             $href = $anc->getAttribute('href');
461             if (!empty($href) || 0 !== strpos($href, $baseURL)) { 
462                 continue;
463             }
464             $anc->setAttribute('href', self::domImgUrl($baseURL, $href));
465         }
466         
467         
468         $inner = $dom->getElementById("tmp_dom_wrapper");
469         $html = '';
470         foreach ($inner->childNodes as $child) {
471             $html .= ($dom->saveHTML($child));
472         }
473         return $html;
474     }
475     
476     static function domImgUrl($baseURL, $dom) 
477     {
478         $url = $dom;
479         if (!is_string($url)) {
480             $url = $dom->getAttribute('src');
481         }
482          $umatch  = false;
483         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $url, $umatch))  {
484             return $url;
485         }
486         $id = $umatch[2];
487         $hash = '';
488         
489         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
490             $hh = explode('#',$umatch[3]);
491             $hash = '#'. array_pop($hh);
492         }
493         
494         
495         $img = DB_DataObject::factory('Images');
496         if (!$img->get($id)) {
497             return $url;
498         }
499         $type = explode('/', $umatch[1]);
500         $thumbsize = -1;
501          
502         if (count($type) > 2 && $type[1] == 'Thumb') {
503             $thumbsize = $type[2];
504             $provider = '/Images/Thumb';
505         } else {
506             $provider = '/'.$umatch[1];
507         }
508         
509         $w =  is_string($dom) ? false : $dom->getAttribute('width');
510         $h =  is_string($dom) ? false : $dom->getAttribute('width');
511         
512         if (!is_string($dom) && (!empty($w) || !empty($h)) )
513         {
514             // no support for %...
515             $thumbsize =
516                 (empty($w) ? '0' : $w * 1) .
517                 'x' .
518                 (empty($h) ? '0' : $h * 1);
519              $provider = '/Images/Thumb';
520             
521         }
522         
523         if ($thumbsize !== -1) {
524             // change in size..
525             // need to regenerate it..
526             
527             $type = array('Images', 'Thumb', $thumbsize);
528                 
529             $fc = $img->toFileConvert();
530             // make sure it's available..
531             $fc->convert($img->mimetype, $thumbsize);
532             
533             
534         } else {
535             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
536         }
537         
538         
539         // finally replace the original TAG with the new version..
540         
541         return $img->URL($thumbsize, $provider, $baseURL) . $hash ;
542         
543          
544     }
545     
546     static function replaceDataUrl($baseURL, $img, $obj)
547     {
548         $d = DB_DataObject::Factory('Images');
549         $d->object($obj);
550         
551         
552         $d->createFromData($img->getAttribute('src'));
553         $img->setAttribute('src', $d->URL(-1, '/Images' , $baseURL));
554     }
555     
556     static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name) 
557     {
558         
559         //print_R($attr);
560         // see if it's an image url..
561         // Images/{ID}/fullname.xxxx
562         // Images/Thumb/200/{ID}/fullname.xxxx
563         // Images/Download/{ID}/fullname.xxxx
564         
565         $attr_url = $attr[$attr_name];
566         $umatch  = false;
567         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch))  {
568             return $html;
569         }
570         
571         $id = $umatch[2];
572         $hash = '';
573         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
574             $hh = explode('#',$umatch[3]);
575             $hash = '#'. array_pop($hh);
576         }
577         
578         
579         $img = DB_DataObject::factory('Images');
580         if (!$img->get($id)) {
581             return $html;
582         }
583         $type = explode('/', $umatch[1]);
584         $thumbsize = -1;
585          
586         if (count($type) > 2 && $type[1] == 'Thumb') {
587             $thumbsize = $type[2];
588             $provider = '/Images/Thumb';
589         } else {
590             $provider = '/'.$umatch[1];
591         }
592         
593         if (!empty($attr['width']) || !empty($attr['height']) )
594         {
595             // no support for %...
596             $thumbsize =
597                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
598                 'x' .
599                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
600              $provider = '/Images/Thumb';
601             
602         }
603         
604         if ($thumbsize !== -1) {
605             // change in size..
606             // need to regenerate it..
607             
608             $type = array('Images', 'Thumb', $thumbsize);
609                 
610             $fc = $img->toFileConvert();
611             // make sure it's available..
612             $fc->convert($img->mimetype, $thumbsize);
613             
614             
615         } else {
616             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
617         }
618         
619         
620         // finally replace the original TAG with the new version..
621         
622         $new_tag = str_replace(
623             $attr_name. '="'. $attr_url . '"',
624             $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
625             $tag
626         );
627         
628         
629         return str_replace($tag, $new_tag, $html);
630          
631     }
632     
633     function downloadEvent($bits)
634     {
635         $ev = DB_DAtaObject::Factory('events');
636         if (!$ev->get($bits[1])) {
637             die("could not find event id");
638         }
639         // technically same user only.. -- normally www-data..
640         if (function_exists('posix_getpwuid')) {
641             $uinfo = posix_getpwuid( posix_getuid () ); 
642             $user = $uinfo['name'];
643         } else {
644             $user = getenv('USERNAME'); // windows.
645         }
646         $ff = HTML_FlexyFramework::get();
647         
648         $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
649         
650         if(!$file || !file_exists($file)){
651             die("file was not saved");
652         }
653         
654         $filesJ = json_decode(file_get_contents($file));
655
656         foreach($filesJ->FILES as $k=>$f){
657             if ($f->tmp_name != $bits[2]) {
658                 continue;
659             }
660
661             $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)).  $f->tmp_name ;
662             
663             if (!$src || !file_exists($src)) {
664                 die("file was not saved");
665             }
666             header ('Content-Type: ' . $f->type);
667
668             header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );
669             @ob_clean();
670             flush();
671             readfile($src);
672             exit;
673         }
674     }
675     
676      
677         
678         
679          
680 }