fix #8131 - chinese translations
[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         
418         libxml_use_internal_errors(true);
419         $dom = new DOMDocument();
420         $dom->loadHTML("<?xml encoding='utf-8'?> <div id='tmp_dom_wrapper'>{$html}</div>");
421         $imgs = $dom->getElementsByTagName('img');
422        
423         
424         foreach($imgs as $img) {
425             $src = $img->getAttribute('src');
426             if (!$src|| !strlen(trim($src))) {
427                 continue;
428             }
429              
430             if (0 === strpos($src, 'data:')) {
431                 if (!$obj) {
432                     HTML_FlexyFramework::get()->page->jerr("no object to attach data url");
433                 }
434                 
435                 self::replaceDataUrl($baseURL, $img, $obj);
436                 continue;
437             }
438             
439             
440             if (false !== strpos($src, '//') && false === strpos($src, $baseURL)) {
441                 // contains an absolute path.. and not our baseURL.
442                 continue;
443             }
444              
445             $img->setAttribute('src', self::domImgUrl($baseURL, $img));
446               
447             // what about mailto or data... - just ignore?? for images...
448             
449             
450         }
451         
452         $anchors = $dom->getElementsByTagName('a');
453         $result = array();
454         preg_match_all('/<a\s+[^>]+>/i',$html, $result); 
455
456         $matches = array_unique($result[0]);
457         foreach($anchors as $anc) {
458             $href = $anc->getAttribute('href');
459             if (!empty($href) || 0 !== strpos($href, $baseURL)) { 
460                 continue;
461             }
462             $anc->setAttribute('href', self::domImgUrl($baseURL, $href));
463         }
464         
465         
466         $inner = $dom->getElementById("tmp_dom_wrapper");
467         $html = '';
468         foreach ($inner->childNodes as $child) {
469             $html .= ($dom->saveHTML($child));
470         }
471         return $html;
472     }
473     
474     static function domImgUrl($baseURL, $dom) 
475     {
476         $url = $dom;
477         if (!is_string($url)) {
478             $url = $dom->getAttribute('src');
479         }
480          $umatch  = false;
481         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $url, $umatch))  {
482             return $url;
483         }
484         $id = $umatch[2];
485         $hash = '';
486         
487         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
488             $hh = explode('#',$umatch[3]);
489             $hash = '#'. array_pop($hh);
490         }
491         
492         
493         $img = DB_DataObject::factory('Images');
494         if (!$img->get($id)) {
495             return $url;
496         }
497         $type = explode('/', $umatch[1]);
498         $thumbsize = -1;
499          
500         if (count($type) > 2 && $type[1] == 'Thumb') {
501             $thumbsize = $type[2];
502             $provider = '/Images/Thumb';
503         } else {
504             $provider = '/'.$umatch[1];
505         }
506         
507         $w =  is_string($dom) ? false : $dom->getAttribute('width');
508         $h =  is_string($dom) ? false : $dom->getAttribute('height');
509         
510         if (!is_string($dom) && (!empty($w) || !empty($h) ) && is_numeric($w) && is_numeric($h))
511         {
512             // no support for %...
513             $thumbsize =
514                 (empty($w) ? '0' : intval($w) * 1) .
515                 'x' .
516                 (empty($h) ? '0' : intval($h) * 1);
517              $provider = '/Images/Thumb';
518             
519         }
520         
521         if ($thumbsize !== -1) {
522             // change in size..
523             // need to regenerate it..
524             
525             $type = array('Images', 'Thumb', $thumbsize);
526                 
527             $fc = $img->toFileConvert();
528             // make sure it's available..
529             $fc->convert($img->mimetype, $thumbsize);
530             
531             
532         } else {
533             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
534         }
535         
536         
537         // finally replace the original TAG with the new version..
538         
539         return $img->URL($thumbsize, $provider, $baseURL) . $hash ;
540         
541          
542     }
543     
544     static function replaceDataUrl($baseURL, $img, $obj)
545     {
546         $d = DB_DataObject::Factory('Images');
547         $d->object($obj);
548         
549         
550         $d->createFromData($img->getAttribute('src'));
551         $img->setAttribute('src', $d->URL(-1, '/Images' , $baseURL));
552     }
553     
554     static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name) 
555     {
556         
557         //print_R($attr);
558         // see if it's an image url..
559         // Images/{ID}/fullname.xxxx
560         // Images/Thumb/200/{ID}/fullname.xxxx
561         // Images/Download/{ID}/fullname.xxxx
562         
563         $attr_url = $attr[$attr_name];
564         $umatch  = false;
565         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch))  {
566             return $html;
567         }
568         
569         $id = $umatch[2];
570         $hash = '';
571         if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
572             $hh = explode('#',$umatch[3]);
573             $hash = '#'. array_pop($hh);
574         }
575         
576         
577         $img = DB_DataObject::factory('Images');
578         if (!$img->get($id)) {
579             return $html;
580         }
581         $type = explode('/', $umatch[1]);
582         $thumbsize = -1;
583          
584         if (count($type) > 2 && $type[1] == 'Thumb') {
585             $thumbsize = $type[2];
586             $provider = '/Images/Thumb';
587         } else {
588             $provider = '/'.$umatch[1];
589         }
590         
591         if (!empty($attr['width']) || !empty($attr['height']) )
592         {
593             // no support for %...
594             $thumbsize =
595                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
596                 'x' .
597                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
598              $provider = '/Images/Thumb';
599             
600         }
601         
602         if ($thumbsize !== -1) {
603             // change in size..
604             // need to regenerate it..
605             
606             $type = array('Images', 'Thumb', $thumbsize);
607                 
608             $fc = $img->toFileConvert();
609             // make sure it's available..
610             $fc->convert($img->mimetype, $thumbsize);
611             
612             
613         } else {
614             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
615         }
616         
617         
618         // finally replace the original TAG with the new version..
619         
620         $new_tag = str_replace(
621             $attr_name. '="'. $attr_url . '"',
622             $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
623             $tag
624         );
625         
626         
627         return str_replace($tag, $new_tag, $html);
628          
629     }
630     
631     function downloadEvent($bits)
632     {
633         $ev = DB_DAtaObject::Factory('events');
634         if (!$ev->get($bits[1])) {
635             die("could not find event id");
636         }
637         // technically same user only.. -- normally www-data..
638         if (function_exists('posix_getpwuid')) {
639             $uinfo = posix_getpwuid( posix_getuid () ); 
640             $user = $uinfo['name'];
641         } else {
642             $user = getenv('USERNAME'); // windows.
643         }
644         $ff = HTML_FlexyFramework::get();
645         
646         $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
647         
648         if(!$file || !file_exists($file)){
649             die("file was not saved");
650         }
651         
652         $filesJ = json_decode(file_get_contents($file));
653
654         foreach($filesJ->FILES as $k=>$f){
655             if ($f->tmp_name != $bits[2]) {
656                 continue;
657             }
658
659             $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)).  $f->tmp_name ;
660             
661             if (!$src || !file_exists($src)) {
662                 die("file was not saved");
663             }
664             header ('Content-Type: ' . $f->type);
665
666             header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );
667             @ob_clean();
668             flush();
669             readfile($src);
670             exit;
671         }
672     }
673     
674      
675         
676         
677          
678 }