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