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