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