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