3 * Deal with image delivery and HTML replacement of image links in body text.
5 * $str = Pman_Core_Images::replaceImg($str); // < use with HTML
9 * Deliver image /file etc..
13 * args: ontable request
14 * ontable (req) tablename.
17 * as (serve as a type) = eg. ?as=audio/mpeg
20 * as :(serve as a type) = eg. mimetype.
22 * Images/{ID}/fullname.xxxx
24 * (valid thumbs 200, 400)...?
25 * Images/Thumb/200/{ID}/fullname.xxxx
26 * Images/Download/{ID}/fullname.xxxx
31 * Used to be in Base... now in core..
34 * view permission should be required on the underlying object...
37 require_once 'Pman.php';
38 class Pman_Core_Images extends Pman
42 parent::getAuth(); // load company!
44 $au = $this->getAuthUser();
50 $this->authUser = $au;
55 var $as_mimetype = false;
56 var $method = 'inline';
58 function get($s) // determin what to serve!!!!
61 //if (!empty($_GET['_post'])) {
62 // return $this->post();
65 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
67 $bits= explode('/', $s);
69 // var_dump($bits);die('in');
70 // without id as first part...
71 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
73 $this->as_mimetype = 'image/jpeg';
74 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
75 $id = empty($bits[2]) ? 0 : $bits[2];
77 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
78 $this->method = 'attachment';
79 $id = empty($bits[1]) ? 0 : $bits[1];
81 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
83 $this->as_mimetype = 'image/jpeg';
84 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
85 $id = empty($bits[3]) ? 0 : $bits[3];
87 } else if (!empty($bits[0]) && $bits[0] == 'events') {
89 $this->downloadEvent($bits);
91 die ("unknown file?");
95 $id = empty($bits[0]) ? 0 : $bits[0];
98 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
99 $onbits = explode(':', $id);
100 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
103 //DB_DataObject::debugLevel(1);
104 $img = DB_DataObject::factory('Images');
105 $img->ontable = $onbits[0];
106 $img->onid = $onbits[1];
107 if (empty($_REQUEST['anytype'])) {
108 $img->whereAdd("mimetype like 'image/%'");
111 if (isset($onbits[2])) {
112 $img->imgtype = $onbits[2];
115 if (!$img->find(true)) {
116 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
117 urlencode("no images for that item: " . htmlspecialchars($id)));
126 // depreciated - should use ontable:onid:type here...
127 if (!empty($_REQUEST['ontable'])) {
129 //DB_DataObjecT::debugLevel(1);
130 $img = DB_DataObjecT::factory('Images');
131 $img->setFrom($_REQUEST);
132 // use imgtype now...
133 // if (!empty($_REQUEST['query']['filename'])){
134 // $img->whereAdd("filename LIKE '". $img->escape($_REQUEST['query']['filename']).".%'");
139 if (!$img->find(true)) {
140 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason='.
141 urlencode("No file exists"));
149 $img = DB_DataObjecT::factory('Images');
151 if (!$id || !$img->get($id)) {
153 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
154 urlencode("image has been removed or deleted."));
158 if(!$this->hasPermission($img)){
159 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
160 urlencode("access to this image/file has been denied."));
167 function hasPermission($img)
175 if (!$this->authUser) {
176 $this->jerr("image conversion only allowed by registered users");
178 // converts a posted string (eg.svg)
179 // into another type..
180 if (empty($_REQUEST['as'])) {
181 $this->jerr("missing target type");
183 if (empty($_REQUEST['mimetype'])) {
184 $this->jerr("missing mimetype");
186 if (empty($_REQUEST['data'])) {
187 $this->jerr("missing data");
191 $this->as_mimetype = $_REQUEST['as'];
192 $this->mimetype = $_REQUEST['mimetype'];
193 require_once 'File/MimeType.php';
194 $y = new File_MimeType();
195 $src_ext = $y->toExt( $this->mimetype );
198 $tmp = $this->tempName($src_ext);
199 file_put_contents($tmp, $_REQUEST['data']);
201 require_once 'File/Convert.php';
202 $cv = new File_Convert($tmp, $this->mimetype);
206 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
207 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
209 if (!empty($_REQUEST['as_data'])) {
210 $this->jok(base64_encode(file_get_contents($fn)));
213 $cv->serve('attachment');
224 $this->sessionState(0); // turn off session... - locking...
226 require_once 'File/Convert.php';
227 if (!file_exists($img->getStoreName())) {
228 // print_r($img);exit;
229 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
230 urlencode("Original file was missing : " . $img->getStoreName()));
233 // print_r($img);exit;
234 $x = $img->toFileConvert();
235 if (empty($this->as_mimetype)) {
236 $this->as_mimetype = $img->mimetype;
239 $x->convert( $this->as_mimetype);
240 $x->serve($this->method);
243 //echo "SKALING? $this->size";
244 // acutally if we generated the image, then we do not need to validate the size..
248 // if the mimetype is not converted..
249 // then the filename should be original.{size}.jpeg
250 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
252 if (!file_exists($fn)) {
253 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
254 // if it's an image, convert into the same type for thumbnail..
255 if (preg_match('#^image/#', $img->mimetype)) {
256 $this->as_mimetype = $img->mimetype;
260 if (!file_exists($fn)) {
262 $this->validateSize();
265 $x->convert( $this->as_mimetype, $this->size);
273 function validateSize()
275 if (($this->authUser && $this->authUser->company_id && $this->authUser->company()->comptype=='OWNER') || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
279 // DEFAULT allowed - override with Pman_Core_Images[sizes] => array();
290 '300x100', // logo on login.
294 // this should be configurable...
295 $ff = HTML_FlexyFramework::get();
298 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
299 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
303 if (!empty($cfg['sizes'])) {
304 $sizes = array_merge($sizes , $cfg['sizes']);
308 if (!in_array($this->size, $sizes)) {
310 die("invalid scale - ".$this->size);
316 * The idea of this code was to replace urls for images when you have an admin
317 * and a distribution page. with different urls.
319 * it may be usefull later if things like embedded images in emails. but
320 * I think it's proably better not to use this.
322 * The key problem being how to determine if we are replacing 'our' images or some external one..
328 static function replaceImageURLS($html)
331 $ff = HTML_FlexyFramework::get();
332 if (!isset($ff->Pman_Images['public_baseURL'])) {
335 //var_dump($ff->Pman_Images['public_baseURL']);
336 $baseURL = $ff->Pman_Images['public_baseURL'];
338 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
340 $matches = array_unique($result[0]);
341 foreach($matches as $img) {
343 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
347 foreach($imatch[1] as $i=>$key) {
348 $attr[$key] = $imatch[2][$i];
350 if (!isset($attr['src']) || 0 !== strpos($attr['src'], $baseURL)) {
353 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
357 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
359 $matches = array_unique($result[0]);
360 foreach($matches as $img) {
362 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
366 foreach($imatch[1] as $i=>$key) {
367 $attr[$key] = $imatch[2][$i];
369 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
372 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
377 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
381 // see if it's an image url..
382 // Images/{ID}/fullname.xxxx
383 // Images/Thumb/200/{ID}/fullname.xxxx
384 // Images/Download/{ID}/fullname.xxxx
386 $attr_url = $attr[$attr_name];
388 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
392 $img = DB_DataObject::factory('Images');
393 if (!$img->get($id)) {
396 $type = explode('/', $umatch[1]);
399 if (count($type) > 2 && $type[1] == 'Thumb') {
400 $thumbsize = $type[2];
401 $provider = '/Images/Thumb';
403 $provider = '/'.$umatch[1];
406 if (!empty($attr['width']) || !empty($attr['height']) )
408 // no support for %...
410 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
412 (empty($attr['height']) ? '0' : $attr['height'] * 1);
413 $provider = '/Images/Thumb';
417 if ($thumbsize !== -1) {
419 // need to regenerate it..
421 $type = array('Images', 'Thumb', $thumbsize);
423 $fc = $img->toFileConvert();
424 // make sure it's available..
425 $fc->convert($img->mimetype, $thumbsize);
429 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
433 // finally replace the original TAG with the new version..
435 $new_tag = str_replace(
436 $attr_name. '="'. $attr_url . '"',
437 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . '"',
442 return str_replace($tag, $new_tag, $html);
446 function downloadEvent($bits)
448 $popts = PEAR::getStaticProperty('Pman','options');
449 $ev = DB_DAtaObject::Factory('events');
450 if (!$ev->get($bits[1])) {
451 die("could not find event id");
453 // technically same user only.. -- normally www-data..
454 if (function_exists('posix_getpwuid')) {
455 $uinfo = posix_getpwuid( posix_getuid () );
456 $user = $uinfo['name'];
458 $user = getenv('USERNAME'); // windows.
460 $ff = HTML_FlexyFramework::get();
461 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
462 $filesJ = json_decode(file_get_contents($file));
466 foreach($filesJ->FILES as $k=>$f){
467 if ($f->tmp_name != $bits[2]) {
471 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
472 if (!file_exists($src)) {
473 die("file was not saved");
475 header ('Content-Type: ' . $f->type);
477 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );