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