DataObjects/core.sql
[Pman.Core] / Images.php
1 <?php
2 /**
3  * Deal with image delivery and HTML replacement of image links in body text.
4  *
5  * $str = Pman_Core_Images::replaceImg($str); // < use with HTML
6  *
7  * or
8  *
9  * Deliver image /file etc..
10  * 
11  * Use Cases:
12  * 
13  * args: ontable request
14  *      ontable (req) tablename.
15  *      filename
16  *      (other table args)
17  *      as (serve as a type) = eg. ?as=audio/mpeg 
18  * 
19  * args: generic
20  *     as :(serve as a type) = eg. mimetype.
21  * 
22  * Images/{ID}/fullname.xxxx
23  * 
24  * (valid thumbs 200, 400)...?
25  * Images/Thumb/200/{ID}/fullname.xxxx
26  * Images/Download/{ID}/fullname.xxxx
27  *
28  *
29  *
30  * 
31  * Used to be in Base... now in core..
32  *
33  * 
34  * view permission should be required on the underlying object...
35  * 
36  */
37 require_once  'Pman.php';
38 class Pman_Core_Images extends Pman
39 {
40     function getAuth()
41     {
42         parent::getAuth(); // load company!
43         //return true;
44         $au = $this->getAuthUser();
45         //if (!$au) {
46         //    die("Access denied");
47        // }
48         $this->authUser = $au;
49         
50         return true;
51     }
52     var $thumb = false;
53     var $as_mimetype = false;
54     var $method = 'inline';
55     
56     function get($s) // determin what to serve!!!!
57     {
58         $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
59         
60         $bits= explode('/', $s);
61         $id = 0;
62         
63         // without id as first part...
64         if (!empty($bits[0]) && $bits[0] == 'Thumb') {
65             $this->thumb = true;
66             $this->as_mimetype = 'image/jpeg';
67             $this->size = empty($bits[1]) ? '0x0' : $bits[1];
68             $id = empty($bits[2]) ? 0 :   $bits[2];
69             
70         } else if (!empty($bits[0]) && $bits[0] == 'Download') {
71             $this->method = 'attachment';
72             $id = empty($bits[1]) ? 0 :   $bits[1];
73             
74         } else  if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
75             $this->thumb = true;
76             $this->as_mimetype = 'image/jpeg';
77             $this->size = empty($bits[2]) ? '0x0' : $bits[2];
78             $id = empty($bits[3]) ? 0 :   $bits[3];
79             
80         } else if (!empty($bits[0]) && $bits[0] == 'events') {
81             $popts = PEAR::getStaticProperty('Pman','options');
82             $ev = DB_DAtaObject::Factory('events');
83             if (!$ev->get($bits[1])) {
84                 die("could not find event id");
85             }
86             // technically same user only.. -- normally www-data..
87             if (function_exists('posix_getpwuid')) {
88                 $uinfo = posix_getpwuid( posix_getuid () ); 
89              
90                 $user = $uinfo['name'];
91             } else {
92                 $user = getenv('USERNAME'); // windows.
93             }
94             $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/'). $this->id . ".json";
95             $filesJ = json_decode(file_get_contents($file));
96          
97          
98          
99             foreach($filesJ->FILES as $k=>$f){
100                 if ($f->tmp_name == $bits[2]) {
101                     continue;
102                 }
103                 
104                 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/').  $f->tmp_name ;
105                 if (!file_exists($src)) {
106                     die("file was not saved");
107                 }
108                 header ('Content-Type: ' . $f->mimetype);
109             
110                 header("Content-Disposition: attachment; filename=\"".basename($f->filename)."\";" );
111                 ob_clean();
112                 flush();
113                 readfile($src);
114                 exit;
115             }
116             die ("unknown file?"); 
117         } else {
118         
119             $id = empty($bits[0]) ? 0 :  $bits[0];
120         }
121         
122         if (strpos($id,':') > 0) {  // id format  tablename:id:-imgtype
123             $onbits = explode(':', $id);
124             if ((count($onbits) < 2)   || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
125                 die("Bad url");
126             }
127             //DB_DataObject::debugLevel(1);
128             $img = DB_DataObject::factory('Images');
129             $img->ontable = $onbits[0];
130             $img->onid = $onbits[1];
131             if (empty($_REQUEST['anytype'])) {
132                 $img->whereAdd("mimetype like 'image/%'");
133             }
134             
135             if (isset($onbits[2])) {
136                 $img->imgtype = $onbits[2];
137             }
138             $img->limit(1);
139             if (!$img->find(true)) {
140                 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
141                 urlencode("no images for that item: " . htmlspecialchars($id)));
142             }
143             
144             $id = $img->id;
145             
146             
147         }
148         $id = (int) $id;
149         
150         // depreciated - should use ontable:onid:type here...
151         if (!empty($_REQUEST['ontable'])) {
152
153             //DB_DataObjecT::debugLevel(1);
154             $img = DB_DataObjecT::factory('Images');
155             $img->setFrom($_REQUEST);
156             // use imgtype now...
157            // if (!empty($_REQUEST['query']['filename'])){
158            //     $img->whereAdd("filename LIKE '". $img->escape($_REQUEST['query']['filename']).".%'");
159            // }
160             
161             
162             $img->limit(1);
163             if (!$img->find(true)) {
164                 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason='. 
165                     urlencode("No file exists"));
166             } 
167             $id = $img->id;
168             
169         }
170         
171         
172        
173         $img = DB_DataObjecT::factory('Images');
174         if (!$id || !$img->get($id)) {
175              
176             header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
177                 urlencode("image has been removed or deleted."));
178         }
179         $this->serve($img);
180         exit;
181     }
182     
183     
184     function post()
185     {
186         
187         if (!$this->authUser) {
188             $this->jerr("image conversion only allowed by registered users");
189         }
190         // converts a posted string (eg.svg)
191         // into another type..
192         if (empty($_REQUEST['as'])) {
193            $this->jerr("missing target type");
194         }
195         if (empty($_REQUEST['mimetype'])) {
196             $this->jerr("missing mimetype");
197         }
198         if (empty($_REQUEST['data'])) {
199             $this->jerr("missing data");
200         }
201         
202         
203         $this->as_mimetype = $_REQUEST['as'];
204         $this->mimetype = $_REQUEST['mimetype'];
205         require_once 'File/MimeType.php';
206         $y = new File_MimeType();
207         $src_ext = $y->toExt( $this->mimetype );
208         
209         
210         $tmp = $this->tempName($src_ext);
211         file_put_contents($tmp, $_REQUEST['data']);
212         
213         require_once 'File/Convert.php';
214         $cv = new File_Convert($tmp, $this->mimetype);
215         
216         $fn = $cv->convert(
217                 $this->as_mimetype ,
218                 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
219                 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
220         );
221         if (!empty($_REQUEST['as_data'])) {
222             $this->jok(base64_encode(file_get_contents($fn)));
223         }
224         
225         $cv->serve('attachment');
226         exit;
227         
228         
229         
230     }
231     
232     
233  
234     function serve($img)
235     {
236         require_once 'File/Convert.php';
237         if (!file_exists($img->getStoreName())) {
238             //print_r($img);exit;
239             header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
240                 urlencode("Original file was missing : " . $img->getStoreName()));
241     
242         }
243         
244         $x = $img->toFileConvert();
245         if (empty($this->as_mimetype)) {
246             $this->as_mimetype  = $img->mimetype;
247         }
248         if (!$this->thumb) {
249             $x->convert( $this->as_mimetype);
250             $x->serve($this->method);
251             exit;
252         }
253         //echo "SKALING?  $this->size";
254         // acutally if we generated the image, then we do not need to validate the size..
255         
256         
257         
258         // if the mimetype is not converted..
259         // then the filename should be original.{size}.jpeg
260         $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
261         
262         if (!file_exists($fn)) {
263             $fn = $img->getStoreName()  . '.'. $this->size . '.'. $img->fileExt();
264             // if it's an image, convert into the same type for thumbnail..
265             if (preg_match('#^image/#', $img->mimetype)) {
266                $this->as_mimetype = $img->mimetype;
267             }
268         }
269         
270         if (!file_exists($fn)) {            
271             
272             $this->validateSize();
273         }
274         
275         $x->convert( $this->as_mimetype, $this->size);
276         $x->serve();
277         exit;
278         
279         
280         
281         
282     }
283     function validateSize()
284     {
285         
286         // DEFAULT allowed - override with $cfg['sizes'];
287         
288         $sizes = array(
289                 '100', 
290                 '100x100', 
291                 '150', 
292                 '150x150', 
293                 '200', 
294                 '200x0',
295                 '200x200',  
296                 '400x0',
297                 '300x100', // logo on login.
298                 '500'
299             );
300         
301         // this should be configurable...
302         $ff = HTML_FlexyFramework::get();
303         $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
304                 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
305         
306         
307         
308         if (!empty($cfg['sizes'])) {
309             $sizes = array_merge($sizes , $cfg['sizes']);
310         }
311         
312         
313         if (!in_array($this->size, $sizes)) {
314             die("invalid scale - ".$this->size);
315         }
316     }
317     /**
318      * replace image urls
319      *
320      * The idea of this code was to replace urls for images when you have an admin
321      * and a distribution page. with different urls.
322      *
323      * it may be usefull later if things like embedded images in emails. but
324      * I think it's proably better not to use this.
325      *
326      * The key problem being how to determine if we are replacing 'our' images or some external one..
327      * 
328      *
329      */
330     
331     
332     static function replaceImageURLS($html)
333     {
334         
335         $ff = HTML_FlexyFramework::get();
336         if (!isset($ff->Pman_Images['public_baseURL'])) {
337             return $html;
338         }
339         //var_dump($ff->Pman_Images['public_baseURL']);
340         $baseURL = $ff->Pman_Images['public_baseURL'];
341         
342         preg_match_all('/<img\s+[^>]+>/i',$html, $result); 
343         //print_r($result);
344         $matches = array_unique($result[0]);
345         foreach($matches as $img) {
346             $imatch = array();
347             preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
348             // build a keymap
349             $attr =  array();
350             
351             foreach($imatch[1] as $i=>$key) {
352                 $attr[$key] = $imatch[2][$i];
353             }
354             if (!isset($attr['src']) || 0 !== strpos($attr['src'], $baseURL)) {
355                 continue;
356             }
357             $html = self::replaceImgUrl($html, $baseURL, $img, $attr,  'src' );
358         }
359         
360         $result = array();
361         preg_match_all('/<a\s+[^>]+>/i',$html, $result); 
362
363         $matches = array_unique($result[0]);
364         foreach($matches as $img) {
365             $imatch = array();
366             preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
367             // build a keymap
368             $attr =  array();
369             
370             foreach($imatch[1] as $i=>$key) {
371                 $attr[$key] = $imatch[2][$i];
372             }
373             if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) { 
374                 continue;
375             }
376             $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
377         }
378         
379         return $html;
380     }
381     static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name) 
382     {
383         
384         //print_R($attr);
385         // see if it's an image url..
386         // Images/{ID}/fullname.xxxx
387         // Images/Thumb/200/{ID}/fullname.xxxx
388         // Images/Download/{ID}/fullname.xxxx
389         
390         $attr_url = $attr[$attr_name];
391         $umatch  = false;
392         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch))  {
393             return $html;
394         }
395         $id = $umatch[2];
396         $img = DB_DataObject::factory('Images');
397         if (!$img->get($id)) {
398             return $html;
399         }
400         $type = explode('/', $umatch[1]);
401         $thumbsize = -1;
402          
403         if (count($type) > 2 && $type[1] == 'Thumb') {
404             $thumbsize = $type[2];
405             $provider = '/Images/Thumb';
406         } else {
407             $provider = '/'.$umatch[1];
408         }
409         
410         if (!empty($attr['width']) || !empty($attr['height']) )
411         {
412             // no support for %...
413             $thumbsize =
414                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
415                 'x' .
416                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
417              $provider = '/Images/Thumb';
418             
419         }
420         
421         if ($thumbsize !== -1) {
422             // change in size..
423             // need to regenerate it..
424             
425             $type = array('Images', 'Thumb', $thumbsize);
426                 
427             $fc = $img->toFileConvert();
428             // make sure it's available..
429             $fc->convert($img->mimetype, $thumbsize);
430             
431             
432         } else {
433             $provider = $provider == 'Images/Thumb' ? 'Images' : $provider; 
434         }
435         
436         
437         // finally replace the original TAG with the new version..
438         
439         $new_tag = str_replace(
440             $attr_name. '="'. $attr_url . '"',
441             $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . '"',
442             $tag
443         );
444         
445         
446         return str_replace($tag, $new_tag, $html);
447          
448     }
449     
450 }