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