Changed 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     var $size;
82     
83     
84     function get($s, $opts=array()) // determin what to serve!!!!
85     {
86         // for testing only.
87         //if (!empty($_GET['_post'])) {
88         //   return $this->post();
89         //}
90      
91         
92         
93         $this->is_local = (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') ? true : false;
94         
95         $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
96         
97         $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
98         
99         $bits= explode('/', $s);
100         $id = 0;
101 //        var_dump($bits);die('in');
102         // without id as first part...
103         if (!empty($bits[0]) && $bits[0] == 'Thumb') {
104             $this->thumb = true;
105             $this->as_mimetype = 'image/jpeg';
106             $this->size = empty($bits[1]) ? '0x0' : $bits[1];
107             $id = empty($bits[2]) ? 0 :   $bits[2];
108             
109         } else if (!empty($bits[0]) && $bits[0] == 'Download') {
110             $this->method = 'attachment';
111             $id = empty($bits[1]) ? 0 :   $bits[1];
112             
113         } else  if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
114             $this->thumb = true;
115             $this->as_mimetype = 'image/jpeg';
116             $this->size = empty($bits[2]) ? '0x0' : $bits[2];
117             $id = empty($bits[3]) ? 0 :   $bits[3];
118             
119         } else if (!empty($bits[0]) && $bits[0] == 'events') {
120             if (!$this->authUser) {
121                 $this->imgErr("no-authentication-events",$s);
122             }
123             $this->downloadEvent($bits);
124             $this->imgErr("unknown file",$s);
125             
126             
127         } else {
128         
129             $id = empty($bits[0]) ? 0 :  $bits[0];
130         }
131         
132         if (strpos($id,':') > 0) {  // id format  tablename:id:-imgtype
133             //DB_DataObject::debugLevel(1);
134             if (!$this->authUser) {
135                 $this->imgErr("not-authenticated-using-colon-format",$s);
136                 
137             }
138             
139             $onbits = explode(':', $id);
140             if ((count($onbits) < 2)   || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
141                 $this->imgErr("bad-url",$s);
142                 
143             }
144             //DB_DataObject::debugLevel(1);
145             $img = DB_DataObject::factory('Images');
146             $img->ontable = $onbits[0];
147             $img->onid = $onbits[1];
148             if (empty($_REQUEST['anytype'])) {
149                 $img->whereAdd("mimetype like 'image/%'");
150             }
151             $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
152             if (isset($onbits[2])) {
153                 $img->imgtype = $onbits[2];
154             }
155             $img->limit(1);
156             if (!$img->find(true)) {
157                 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
158                 
159             }
160             
161             $id = $img->id;
162             
163             
164         }
165         $id = (int) $id;
166         
167         // depreciated - should use ontable:onid:type here...
168         if (!empty($_REQUEST['ontable'])) {
169             
170             if (!$this->authUser) {
171                 die("authentication required");
172             }
173             
174             //DB_DataObjecT::debugLevel(1);
175             $img = DB_DataObject::factory('Images');
176             $img->setFrom($_REQUEST);
177            
178             
179             
180             $img->limit(1);
181             if (!$img->find(true)) {
182                 $this->imgErr("No file exists",$s);
183             } 
184             $id = $img->id;
185             
186         }
187         
188         $img = DB_DataObjecT::factory('Images');
189          
190         if (!$id || !$img->get($id) || !$img->exists()) {
191            //print_r($img);           die("HERE");
192             $this->imgErr("image has been removed or deleted.",$s);
193         }
194         
195         if($this->is_local) {
196             return $this->serve($img);
197         }
198         
199         if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
200             
201             if ($img->ontable != 'core_company') {
202                 $this->imgErr("not-authenticated {$img->ontable}",$s);
203             }
204             if ($img->imgtype != 'LOGO') {
205                 $this->imgErr("not-logo",$s);
206             }
207             $comp  = $img->object();
208             if ($comp->comptype != 'OWNER') {
209                 $this->imgErr("not-owner-company",$s);
210             }
211             
212             return $this->serve($img);
213             
214         }
215         
216         if(!$this->hasPermission($img)){
217             $this->imgErr("access to this image/file has been denied.",$s);
218         }
219         
220         $this->serve($img);
221         exit;
222     }
223     
224     function imgErr($reason,$path) {
225         header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' . urlencode($reason) );
226         header('X-Error: ' . $reason . ':' . $path);
227         echo $reason . ':' . $path;
228         exit;
229     }
230     
231     function hasPermission($img) 
232     {
233         return true;
234     }
235     
236     function post($v)
237     {
238         if (!empty($_REQUEST['_get'])) {
239             return $this->get($v);
240         }
241         
242         if (!$this->authUser) {
243             $this->jerr("image conversion only allowed by registered users");
244         }
245         // converts a posted string (eg.svg)
246         // into another type..
247         if (empty($_REQUEST['as'])) {
248            $this->jerr("missing target type");
249         }
250         if (empty($_REQUEST['mimetype'])) {
251             $this->jerr("missing mimetype");
252         }
253         if (empty($_REQUEST['data'])) {
254             $this->jerr("missing data");
255         }
256         
257         
258         $this->as_mimetype = $_REQUEST['as'];
259         $this->mimetype = $_REQUEST['mimetype'];
260         require_once 'File/MimeType.php';
261         $y = new File_MimeType();
262         $src_ext = $y->toExt( $this->mimetype );
263         
264         
265         $tmp = $this->tempName($src_ext);
266         file_put_contents($tmp, $_REQUEST['data']);
267         
268         require_once 'File/Convert.php';
269         $cv = new File_Convert($tmp, $this->mimetype);
270         
271         $fn = $cv->convert(
272                 $this->as_mimetype ,
273                 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
274                 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
275         );
276         if (!empty($_REQUEST['as_data'])) {
277             $this->jok(base64_encode(file_get_contents($fn)));
278         }
279         
280         $cv->serve('attachment');
281         exit;
282         
283         
284         
285     }
286     
287     
288  
289     function serve($img)
290     {
291         
292         $this->sessionState(0); // turn off session... - locking...
293         require_once 'File/Convert.php';
294         if (!$img->exists()) {
295             $this->imgErr("serve = missing-image", $img->getStoreName());
296              
297         }
298 //        print_r($img);exit;
299         $x = $img->toFileConvert();
300         if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
301             $this->as_mimetype  = $img->mimetype;
302         }
303         
304         
305         if (!$this->thumb) {
306             if ($x->mimetype == $this->as_mimetype) {
307                 $x->serveOnly($this->method, $img->filename);
308                 exit;
309             }
310             $x->convert( $this->as_mimetype);
311             $x->serve($this->method, $img->filename);
312             exit;
313         }
314         //echo "SKALING?  $this->size";
315         // acutally if we generated the image, then we do not need to validate the size..
316         
317         // if the mimetype is not converted..
318         // then the filename should be original.{size}.jpeg
319         $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
320         
321         if($img->mimetype == 'image/gif'){
322             $fn = $img->getStoreName() . '.'. $this->size . '.gif';
323         }
324         
325         if (!file_exists($fn)) {
326             $fn = $img->getStoreName()  . '.'. $this->size . '.'. $img->fileExt();
327             // if it's an image, convert into the same type for thumbnail..
328             if (preg_match('#^image/#', $img->mimetype)) {
329                $this->as_mimetype = $img->mimetype;
330             }
331         }
332         
333         if (!file_exists($fn)) {    
334             $this->validateSize();
335         }
336        
337         
338         if(!empty($this->page) && !is_nan($this->page * 1)){
339             $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
340         } else {
341             $x->convert( $this->as_mimetype, $this->size);
342         }
343         
344         $x->serve();
345         exit;
346         
347         
348         
349         
350     }
351     function validateSize()
352     {
353         if($this->is_local) {
354             return true;
355         }
356         
357         if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
358             || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
359             return true;
360         }
361         
362         
363         $ff = HTML_FlexyFramework::get();
364         
365         $sizes= $this->sizes;
366         
367         $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
368                 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
369         
370         if (!empty($cfg['sizes'])) {
371             $sizes = array_merge($sizes , $cfg['sizes']);
372         }
373         
374         $project = $ff->project;
375         
376         require_once $ff->project . '.php';
377         
378         $project = str_replace('/', '_', $project);
379          
380         $pr_obj = new $project;
381          
382        // var_dump($pr_obj->Pman_Core_Images_Size);
383         if(isset($pr_obj->Pman_Core_Images_Size)){
384             $sizes = $pr_obj->Pman_Core_Images_Size;
385             
386             
387         }
388         
389         if (!in_array($this->size, $sizes)) {
390             die("invalid scale - ".$this->size);
391         }
392     }
393     /**
394      * replace image urls
395      *
396      * The idea of this code was to replace urls for images when you have an admin
397      * and a distribution page. with different urls.
398      *
399      * it may be usefull later if things like embedded images in emails. but
400      * I think it's proably better not to use this.
401      *
402      * The key problem being how to determine if we are replacing 'our' images or some external one..
403      * 
404      *
405      */
406     
407     
408     static function replaceImageURLS($html, $obj = false)
409     {
410         
411         $ff = HTML_FlexyFramework::get();
412         if (!isset($ff->Pman_Images['public_baseURL'])) {
413             return $html;
414         }
415         //var_dump($ff->Pman_Images['public_baseURL']);
416         $baseURL = $ff->Pman_Images['public_baseURL'];
417         var_dumP($baseURL);
418         die('test');
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 }