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         
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          
308             $x->convert( $this->as_mimetype);
309             $x->serve($this->method);
310             exit;
311         }
312         //echo "SKALING?  $this->size";
313         // acutally if we generated the image, then we do not need to validate the size..
314         
315         // if the mimetype is not converted..
316         // then the filename should be original.{size}.jpeg
317         $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
318         
319         if($img->mimetype == 'image/gif'){
320             $fn = $img->getStoreName() . '.'. $this->size . '.gif';
321         }
322         
323         if (!file_exists($fn)) {
324             $fn = $img->getStoreName()  . '.'. $this->size . '.'. $img->fileExt();
325             // if it's an image, convert into the same type for thumbnail..
326             if (preg_match('#^image/#', $img->mimetype)) {
327                $this->as_mimetype = $img->mimetype;
328             }
329         }
330         
331         if (!file_exists($fn)) {    
332             $this->validateSize();
333         }
334         
335         if(!empty($this->page) && !is_nan($this->page * 1)){
336             $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
337         } else {
338             $x->convert( $this->as_mimetype, $this->size);
339         }
340         
341         $x->serve();
342         exit;
343         
344         
345         
346         
347     }
348     function validateSize()
349     {
350         if($this->is_local) {
351             return true;
352         }
353         
354         if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
355             || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
356             return true;
357         }
358         
359         
360         $ff = HTML_FlexyFramework::get();
361         
362         $sizes= $this->sizes;
363         
364         $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
365                 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
366         
367         if (!empty($cfg['sizes'])) {
368             $sizes = array_merge($sizes , $cfg['sizes']);
369         }
370         
371         $project = $ff->project;
372         
373         require_once $ff->project . '.php';
374         
375         $project = str_replace('/', '_', $project);
376          
377         $pr_obj = new $project;
378          
379        // var_dump($pr_obj->Pman_Core_Images_Size);
380         if(isset($pr_obj->Pman_Core_Images_Size)){
381             $sizes = $pr_obj->Pman_Core_Images_Size;
382             
383             
384         }
385         
386         if (!in_array($this->size, $sizes)) {
387             die("invalid scale - ".$this->size);
388         }
389     }
390     /**
391      * replace image urls
392      *
393      * The idea of this code was to replace urls for images when you have an admin
394      * and a distribution page. with different urls.
395      *
396      * it may be usefull later if things like embedded images in emails. but
397      * I think it's proably better not to use this.
398      *
399      * The key problem being how to determine if we are replacing 'our' images or some external one..
400      * 
401      *
402      */
403     
404     
405     static function replaceImageURLS($html, $obj = false)
406     {
407         
408         $ff = HTML_FlexyFramework::get();
409         if (!isset($ff->Pman_Images['public_baseURL'])) {
410             return $html;
411         }
412         //var_dump($ff->Pman_Images['public_baseURL']);
413         $baseURL = $ff->Pman_Images['public_baseURL'];
414         
415         libxml_use_internal_errors(true);
416         $dom = new DOMDocument();
417         $dom->loadHTML("<?xml encoding='utf-8'?> <div id='tmp_dom_wrapper'>{$html}</div>");
418         $imgs = $dom->getElementsByTagName('img');
419        
420         
421         foreach($imgs as $img) {
422             $src = $img->getAttribute('src');
423             if (!$src|| !strlen(trim($src))) {
424                 continue;
425             }
426              
427             if (0 === strpos($src, 'data:')) {
428                 if (!$obj) {
429                     HTML_FlexyFramework::get()->page->jerr("no object to attach data url");
430                 }
431                 
432                 self::replaceDataUrl($baseURL, $img, $obj);
433                 continue;
434             }
435             
436             
437             if (false !== strpos($src, '//') && false === strpos($src, $baseURL)) {
438                 // contains an absolute path.. and not our baseURL.
439                 continue;
440             }
441              
442             $img->setAttribute('src', self::domImgUrl($baseURL, $img));
443               
444             // what about mailto or data... - just ignore?? for images...
445             
446             
447         }
448         
449         $anchors = $dom->getElementsByTagName('a');
450         $result = array();
451         preg_match_all('/<a\s+[^>]+>/i',$html, $result); 
452
453         $matches = array_unique($result[0]);
454         foreach($anchors as $anc) {
455             $href = $anc->getAttribute('href');
456             if (!empty($href) || 0 !== strpos($href, $baseURL)) { 
457                 continue;
458             }
459             $anc->setAttribute('href', self::domImgUrl($baseURL, $href));
460         }
461         
462         
463         $inner = $dom->getElementById("tmp_dom_wrapper");
464         $html = '';
465         foreach ($inner->childNodes as $child) {
466             $html .= ($dom->saveHTML($child));
467         }
468         return $html;
469     }
470     
471     static function domImgUrl($baseURL, $dom) 
472     {
473         $url = $dom;
474         if (!is_string($url)) {
475             $url = $dom->getAttribute('src');
476         }
477          $umatch  = false;
478         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $url, $umatch))  {
479             return $url;
480         }
481         $id = $umatch[2];
482         $hash = '';
483         
484         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
485             $hh = explode('#',$umatch[3]);
486             $hash = '#'. array_pop($hh);
487         }
488         
489         
490         $img = DB_DataObject::factory('Images');
491         if (!$img->get($id)) {
492             return $url;
493         }
494         $type = explode('/', $umatch[1]);
495         $thumbsize = -1;
496          
497         if (count($type) > 2 && $type[1] == 'Thumb') {
498             $thumbsize = $type[2];
499             $provider = '/Images/Thumb';
500         } else {
501             $provider = '/'.$umatch[1];
502         }
503         
504         $w =  is_string($dom) ? false : $dom->getAttribute('width');
505         $h =  is_string($dom) ? false : $dom->getAttribute('width');
506         
507         if (!is_string($dom) && (!empty($w) || !empty($h)) )
508         {
509             // no support for %...
510             $thumbsize =
511                 (empty($w) ? '0' : $w * 1) .
512                 'x' .
513                 (empty($h) ? '0' : $h * 1);
514              $provider = '/Images/Thumb';
515             
516         }
517         
518         if ($thumbsize !== -1) {
519             // change in size..
520             // need to regenerate it..
521             
522             $type = array('Images', 'Thumb', $thumbsize);
523                 
524             $fc = $img->toFileConvert();
525             // make sure it's available..
526             $fc->convert($img->mimetype, $thumbsize);
527             
528             
529         } else {
530             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
531         }
532         
533         
534         // finally replace the original TAG with the new version..
535         
536         return $img->URL($thumbsize, $provider, $baseURL) . $hash ;
537         
538          
539     }
540     
541     static function replaceDataUrl($baseURL, $img, $obj)
542     {
543         $d = DB_DataObject::Factory('Images');
544         $d->object($obj);
545         
546         
547         $d->createFromData($img->getAttribute('src'));
548         $img->setAttribute('src', $d->URL(-1, '/Images' , $baseURL));
549     }
550     
551     static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name) 
552     {
553         
554         //print_R($attr);
555         // see if it's an image url..
556         // Images/{ID}/fullname.xxxx
557         // Images/Thumb/200/{ID}/fullname.xxxx
558         // Images/Download/{ID}/fullname.xxxx
559         
560         $attr_url = $attr[$attr_name];
561         $umatch  = false;
562         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch))  {
563             return $html;
564         }
565         
566         $id = $umatch[2];
567         $hash = '';
568         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
569             $hh = explode('#',$umatch[3]);
570             $hash = '#'. array_pop($hh);
571         }
572         
573         
574         $img = DB_DataObject::factory('Images');
575         if (!$img->get($id)) {
576             return $html;
577         }
578         $type = explode('/', $umatch[1]);
579         $thumbsize = -1;
580          
581         if (count($type) > 2 && $type[1] == 'Thumb') {
582             $thumbsize = $type[2];
583             $provider = '/Images/Thumb';
584         } else {
585             $provider = '/'.$umatch[1];
586         }
587         
588         if (!empty($attr['width']) || !empty($attr['height']) )
589         {
590             // no support for %...
591             $thumbsize =
592                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
593                 'x' .
594                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
595              $provider = '/Images/Thumb';
596             
597         }
598         
599         if ($thumbsize !== -1) {
600             // change in size..
601             // need to regenerate it..
602             
603             $type = array('Images', 'Thumb', $thumbsize);
604                 
605             $fc = $img->toFileConvert();
606             // make sure it's available..
607             $fc->convert($img->mimetype, $thumbsize);
608             
609             
610         } else {
611             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
612         }
613         
614         
615         // finally replace the original TAG with the new version..
616         
617         $new_tag = str_replace(
618             $attr_name. '="'. $attr_url . '"',
619             $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
620             $tag
621         );
622         
623         
624         return str_replace($tag, $new_tag, $html);
625          
626     }
627     
628     function downloadEvent($bits)
629     {
630         $ev = DB_DAtaObject::Factory('events');
631         if (!$ev->get($bits[1])) {
632             die("could not find event id");
633         }
634         // technically same user only.. -- normally www-data..
635         if (function_exists('posix_getpwuid')) {
636             $uinfo = posix_getpwuid( posix_getuid () ); 
637             $user = $uinfo['name'];
638         } else {
639             $user = getenv('USERNAME'); // windows.
640         }
641         $ff = HTML_FlexyFramework::get();
642         
643         $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
644         
645         if(!$file || !file_exists($file)){
646             die("file was not saved");
647         }
648         
649         $filesJ = json_decode(file_get_contents($file));
650
651         foreach($filesJ->FILES as $k=>$f){
652             if ($f->tmp_name != $bits[2]) {
653                 continue;
654             }
655
656             $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)).  $f->tmp_name ;
657             
658             if (!$src || !file_exists($src)) {
659                 die("file was not saved");
660             }
661             header ('Content-Type: ' . $f->type);
662
663             header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );
664             @ob_clean();
665             flush();
666             readfile($src);
667             exit;
668         }
669     }
670     
671 }