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