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