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