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. mimetype.
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         // without id as first part...
63         if (!empty($bits[0]) && $bits[0] == 'Thumb') {
64             $this->thumb = true;
65             $this->as_mimetype = 'image/jpeg';
66             $this->size = empty($bits[1]) ? '0x0' : $bits[1];
67             $id = empty($bits[2]) ? 0 :   $bits[2];
68             
69         } else if (!empty($bits[0]) && $bits[0] == 'Download') {
70             $this->method = 'attachment';
71             $id = empty($bits[1]) ? 0 :   $bits[1];
72             
73         } else  if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
74             $this->thumb = true;
75             $this->as_mimetype = 'image/jpeg';
76             $this->size = empty($bits[2]) ? '0x0' : $bits[2];
77             $id = empty($bits[3]) ? 0 :   $bits[3];
78             
79         } else {
80             $id = empty($bits[0]) ? 0 :  $bits[0];
81         }
82         
83         if (strpos($id,':') > 0) {  // id format  tablename:id:-imgtype
84             $onbits = explode(':', $id);
85             if ((count($onbits) < 2)   || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
86                 die("Bad url");
87             }
88             //DB_DataObject::debugLevel(1);
89             $img = DB_DataObject::factory('Images');
90             $img->ontable = $onbits[0];
91             $img->onid = $onbits[1];
92             if (empty($_REQUEST['anytype'])) {
93                 $img->whereAdd("mimetype like 'image/%'");
94             }
95             
96             if (isset($onbits[2])) {
97                 $img->imgtype = $onbits[2];
98             }
99             $img->limit(1);
100             if (!$img->find(true)) {
101                 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
102                 urlencode("no images for that item: " . htmlspecialchars($id)));
103             }
104             
105             $id = $img->id;
106             
107             
108         }
109         $id = (int) $id;
110         
111         // depreciated - should use ontable:onid:type here...
112         if (!empty($_REQUEST['ontable'])) {
113
114             //DB_DataObjecT::debugLevel(1);
115             $img = DB_DataObjecT::factory('Images');
116             $img->setFrom($_REQUEST);
117             // use imgtype now...
118            // if (!empty($_REQUEST['query']['filename'])){
119            //     $img->whereAdd("filename LIKE '". $img->escape($_REQUEST['query']['filename']).".%'");
120            // }
121             
122             
123             $img->limit(1);
124             if (!$img->find(true)) {
125                 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason='. 
126                     urlencode("No file exists"));
127             } 
128             $id = $img->id;
129             
130         }
131         
132         
133        
134         $img = DB_DataObjecT::factory('Images');
135         if (!$id || !$img->get($id)) {
136              
137             header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
138                 urlencode("image has been removed or deleted."));
139         }
140         $this->serve($img);
141         exit;
142     }
143  
144     function serve($img)
145     {
146         require_once 'File/Convert.php';
147         if (!file_exists($img->getStoreName())) {
148             //print_r($img);exit;
149             header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
150                 urlencode("Original file was missing : " . $img->getStoreName()));
151     
152         }
153         
154         $x = $img->toFileConvert();
155         if (empty($this->as_mimetype)) {
156             $this->as_mimetype  = $img->mimetype;
157         }
158         if (!$this->thumb) {
159             $x->convert( $this->as_mimetype);
160             $x->serve($this->method);
161             exit;
162         }
163         //echo "SKALING?  $this->size";
164         // acutally if we generated the image, then we do not need to validate the size..
165         $this->validateSize();
166         
167         $x->convert( $this->as_mimetype, $this->size);
168         $x->serve();
169         exit;
170         
171         
172         
173         
174     }
175     function validateSize()
176     {
177         
178         // DEFAULT allowed - override with $cfg['sizes'];
179         
180         $sizes = array(
181                 '100', 
182                 '100x100', 
183                 '150', 
184                 '150x150', 
185                 '200', 
186                 '200x0',
187                 '200x200',  
188                 '400x0',
189                 '300x100', // logo on login.
190                 '500'
191             );
192         
193         // this should be configurable...
194         $ff = HTML_FlexyFramework::get();
195         $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
196                 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
197         
198         
199         
200         if (!empty($cfg['sizes'])) {
201             $sizes = array_merge($sizes , $cfg['sizes']);
202         }
203         
204         
205         if (!in_array($this->size, $sizes)) {
206             die("invalid scale - ".$this->size);
207         }
208     }
209     
210     
211     
212     static function replaceImg($html, $baseURL)
213     {
214         preg_match_all('/<img[^>]+>/i',$html, $result); 
215
216         $matches = array_unique($result[0]);
217         foreach($matches as $img) {
218             $imatch = array();
219             preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
220             // build a keymap
221             $attr =  array();
222             
223             foreach($imatch[1] as $i=>$key) {
224                 $attr[$key] = $imatch[2][$i];
225             }
226             if (!isset($attr['src'])) {
227                 continue;
228             }
229             $html = self::replaceImgUrl($html, $baseURL, $img, $attr, $attr['src'] );
230         }
231         return $html;
232     }
233     static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_url) 
234     {
235         
236         //print_R($attr);
237         // see if it's an image url..
238         // Images/{ID}/fullname.xxxx
239         // Images/Thumb/200/{ID}/fullname.xxxx
240         // Images/Download/{ID}/fullname.xxxx
241         $umatch  = false;
242         if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch))  {
243             continue;
244         }
245         $id = $umatch[2];
246         $img = DB_DataObject::factory('Images');
247         if (!$img->get($id)) {
248             return $html;
249         }
250         $type = explode('/', $umatch[1]);
251         $thumbsize = -1;
252         $new_thumbsize = -1;
253         
254         if (count($type) > 2 && $type[1] == 'Thumb') {
255             $thumbsize = $type[2];
256             $provider = 'Images/Thumb';
257         } else {
258             $provider = $umatch[1];
259         }
260         
261         if (!empty($attr['width']) || !empty($attr['height']) )
262         {
263             // no support for %...
264             $new_thumbsize =
265                 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
266                 'x' .
267                 (empty($attr['height']) ? '0' : $attr['height'] * 1);
268             
269             
270         }
271         if ($new_thumbsize != $thumbsize) {
272             // change in size..
273             // need to regenerate it..
274             if (!$new_thumbsize) {
275                 $type = array('Image');
276             } else {
277                 
278                 $type = array('Image', 'Thumb', $new_thumbsize);
279                 
280                 $fc = $img->toFileConvert();
281                 // make sure it's available..
282                 $fc->convert($img->mimetype, $new_thumbsize);
283                 
284             }
285             
286         }
287         
288         
289         // finally replace the original TAG with the new version..
290         
291         $new_tag = str_replace(
292             'src="'. $attr['src'] . '"',
293             'src="'. htmlspecialchars($img->URL($new_thumbsize , $provider, $baseURL)) . '"',
294             $tag
295         );
296         
297         
298         return str_replace($tag, $new_tag, $html);
299          
300     }
301     
302 }