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