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