3 * Deal with image delivery and HTML replacement of image links in body text.
6 * NOTE THIS WAS NEVER INTENDED FOR PUBLIC IMAGE DISTRIBUTION - we need to create a seperate file for that...
8 * $str = Pman_Core_Images::replaceImg($str); // < use with HTML
12 * Deliver image /file etc..
16 * args: ontable request
17 * ontable (req) tablename.
20 * as (serve as a type) = eg. ?as=audio/mpeg
23 * as :(serve as a type) = eg. mimetype.
25 * Images/{ID}/fullname.xxxx
27 * (valid thumbs 200, 400)...?
28 * Images/Thumb/200/{ID}/fullname.xxxx
29 * Images/Download/{ID}/fullname.xxxx
34 * Used to be in Base... now in core..
37 * view permission should be required on the underlying object...
40 require_once 'Pman.php';
41 class Pman_Core_Images extends Pman
44 // tables that do not need authentication checks before serving.
45 var $public_image_tables = array();
61 parent::getAuth(); // load company!
63 $au = $this->getAuthUser();
66 $this->authUser = false;
67 return true;//die("Access denied");
70 $this->authUser = $au;
75 var $as_mimetype = false;
76 var $method = 'inline';
79 function get($s, $opts=array()) // determin what to serve!!!!
82 //if (!empty($_GET['_post'])) {
83 // return $this->post();
86 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
88 $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
90 $bits= explode('/', $s);
92 // var_dump($bits);die('in');
93 // without id as first part...
94 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
96 $this->as_mimetype = 'image/jpeg';
97 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
98 $id = empty($bits[2]) ? 0 : $bits[2];
100 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
101 $this->method = 'attachment';
102 $id = empty($bits[1]) ? 0 : $bits[1];
104 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
106 $this->as_mimetype = 'image/jpeg';
107 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
108 $id = empty($bits[3]) ? 0 : $bits[3];
110 } else if (!empty($bits[0]) && $bits[0] == 'events') {
111 if (!$this->authUser) {
112 $this->imgErr("no-authentication-events",$s);
114 $this->downloadEvent($bits);
115 $this->imgErr("unknown file",$s);
120 $id = empty($bits[0]) ? 0 : $bits[0];
123 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
125 if (!$this->authUser) {
126 $this->imgErr("not-authenticated-using-colon-format",$s);
130 $onbits = explode(':', $id);
131 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
132 $this->imgErr("bad-url",$s);
135 //DB_DataObject::debugLevel(1);
136 $img = DB_DataObject::factory('Images');
137 $img->ontable = $onbits[0];
138 $img->onid = $onbits[1];
139 if (empty($_REQUEST['anytype'])) {
140 $img->whereAdd("mimetype like 'image/%'");
142 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
143 if (isset($onbits[2])) {
144 $img->imgtype = $onbits[2];
147 if (!$img->find(true)) {
148 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
158 // depreciated - should use ontable:onid:type here...
159 if (!empty($_REQUEST['ontable'])) {
161 if (!$this->authUser) {
162 die("authentication required");
165 //DB_DataObjecT::debugLevel(1);
166 $img = DB_DataObject::factory('Images');
167 $img->setFrom($_REQUEST);
172 if (!$img->find(true)) {
173 $this->imgErr("No file exists",$s);
179 $img = DB_DataObjecT::factory('Images');
181 if (!$id || !$img->get($id)) {
182 $this->imgErr("image has been removed or deleted.",$s);
185 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
187 if ($img->ontable != 'core_company') {
188 $this->imgErr("not-authenticated {$img->ontable}",$s);
190 if ($img->imgtype != 'LOGO') {
191 $this->imgErr("not-logo",$s);
193 $comp = $img->object();
194 if ($comp->comptype != 'OWNER') {
195 $this->imgErr("not-owner-company",$s);
198 return $this->serve($img);
202 if(!$this->hasPermission($img)){
203 $this->imgErr("access to this image/file has been denied.",$s);
210 function imgErr($reason,$path) {
211 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
212 urlencode($reason) .'&path='.urlencode($path));
216 function hasPermission($img)
224 if (!$this->authUser) {
225 $this->jerr("image conversion only allowed by registered users");
227 // converts a posted string (eg.svg)
228 // into another type..
229 if (empty($_REQUEST['as'])) {
230 $this->jerr("missing target type");
232 if (empty($_REQUEST['mimetype'])) {
233 $this->jerr("missing mimetype");
235 if (empty($_REQUEST['data'])) {
236 $this->jerr("missing data");
240 $this->as_mimetype = $_REQUEST['as'];
241 $this->mimetype = $_REQUEST['mimetype'];
242 require_once 'File/MimeType.php';
243 $y = new File_MimeType();
244 $src_ext = $y->toExt( $this->mimetype );
247 $tmp = $this->tempName($src_ext);
248 file_put_contents($tmp, $_REQUEST['data']);
250 require_once 'File/Convert.php';
251 $cv = new File_Convert($tmp, $this->mimetype);
255 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
256 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
258 if (!empty($_REQUEST['as_data'])) {
259 $this->jok(base64_encode(file_get_contents($fn)));
262 $cv->serve('attachment');
273 $this->sessionState(0); // turn off session... - locking...
275 require_once 'File/Convert.php';
276 if (!file_exists($img->getStoreName())) {
277 // print_r($img);exit;
278 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
279 urlencode("Original file was missing : " . $img->getStoreName()));
282 // print_r($img);exit;
283 $x = $img->toFileConvert();
284 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
285 $this->as_mimetype = $img->mimetype;
288 $x->convert( $this->as_mimetype);
289 $x->serve($this->method);
292 //echo "SKALING? $this->size";
293 // acutally if we generated the image, then we do not need to validate the size..
295 // if the mimetype is not converted..
296 // then the filename should be original.{size}.jpeg
297 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
299 if($img->mimetype == 'image/gif'){
300 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
303 if (!file_exists($fn)) {
304 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
305 // if it's an image, convert into the same type for thumbnail..
306 if (preg_match('#^image/#', $img->mimetype)) {
307 $this->as_mimetype = $img->mimetype;
311 if (!file_exists($fn)) {
312 $this->validateSize();
315 if(!empty($this->page) && !is_nan($this->page * 1)){
316 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
318 $x->convert( $this->as_mimetype, $this->size);
328 function validateSize()
330 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
331 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
336 $ff = HTML_FlexyFramework::get();
338 $sizes= $this->sizes;
340 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
341 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
343 if (!empty($cfg['sizes'])) {
344 $sizes = array_merge($sizes , $cfg['sizes']);
347 $project = $ff->project;
349 require_once $ff->project . '.php';
351 $project = str_replace('/', '_', $project);
353 $pr_obj = new $project;
355 // var_dump($pr_obj->Pman_Core_Images_Size);
356 if(isset($pr_obj->Pman_Core_Images_Size)){
357 $sizes = $pr_obj->Pman_Core_Images_Size;
362 if (!in_array($this->size, $sizes)) {
363 die("invalid scale - ".$this->size);
369 * The idea of this code was to replace urls for images when you have an admin
370 * and a distribution page. with different urls.
372 * it may be usefull later if things like embedded images in emails. but
373 * I think it's proably better not to use this.
375 * The key problem being how to determine if we are replacing 'our' images or some external one..
381 static function replaceImageURLS($html)
384 $ff = HTML_FlexyFramework::get();
385 if (!isset($ff->Pman_Images['public_baseURL'])) {
388 //var_dump($ff->Pman_Images['public_baseURL']);
389 $baseURL = $ff->Pman_Images['public_baseURL'];
391 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
393 $matches = array_unique($result[0]);
394 foreach($matches as $img) {
396 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
400 foreach($imatch[1] as $i=>$key) {
401 $attr[$key] = $imatch[2][$i];
403 // does it contain baseURL??? --- well what about relative paths...
406 if (empty($attr['src'])) {
409 if (0 !== strpos($attr['src'], $baseURL)) {
410 // it starts with our 'new' baseURL?
411 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
414 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
415 // contains an absolute path.. that is probably not us...
418 // what about mailto or data... - just ignore?? for images...
420 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
426 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
428 $matches = array_unique($result[0]);
429 foreach($matches as $img) {
431 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
435 foreach($imatch[1] as $i=>$key) {
436 $attr[$key] = $imatch[2][$i];
438 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
441 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
446 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
450 // see if it's an image url..
451 // Images/{ID}/fullname.xxxx
452 // Images/Thumb/200/{ID}/fullname.xxxx
453 // Images/Download/{ID}/fullname.xxxx
455 $attr_url = $attr[$attr_name];
457 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
463 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
464 $hh = explode('#',$umatch[3]);
465 $hash = '#'. array_pop($hh);
469 $img = DB_DataObject::factory('Images');
470 if (!$img->get($id)) {
473 $type = explode('/', $umatch[1]);
476 if (count($type) > 2 && $type[1] == 'Thumb') {
477 $thumbsize = $type[2];
478 $provider = '/Images/Thumb';
480 $provider = '/'.$umatch[1];
483 if (!empty($attr['width']) || !empty($attr['height']) )
485 // no support for %...
487 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
489 (empty($attr['height']) ? '0' : $attr['height'] * 1);
490 $provider = '/Images/Thumb';
494 if ($thumbsize !== -1) {
496 // need to regenerate it..
498 $type = array('Images', 'Thumb', $thumbsize);
500 $fc = $img->toFileConvert();
501 // make sure it's available..
502 $fc->convert($img->mimetype, $thumbsize);
506 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
510 // finally replace the original TAG with the new version..
512 $new_tag = str_replace(
513 $attr_name. '="'. $attr_url . '"',
514 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
519 return str_replace($tag, $new_tag, $html);
523 function downloadEvent($bits)
525 $ev = DB_DAtaObject::Factory('events');
526 if (!$ev->get($bits[1])) {
527 die("could not find event id");
529 // technically same user only.. -- normally www-data..
530 if (function_exists('posix_getpwuid')) {
531 $uinfo = posix_getpwuid( posix_getuid () );
532 $user = $uinfo['name'];
534 $user = getenv('USERNAME'); // windows.
536 $ff = HTML_FlexyFramework::get();
538 $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
540 if(!$file || !file_exists($file)){
541 die("file was not saved");
544 $filesJ = json_decode(file_get_contents($file));
546 foreach($filesJ->FILES as $k=>$f){
547 if ($f->tmp_name != $bits[2]) {
551 $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
553 if (!$src || !file_exists($src)) {
554 die("file was not saved");
556 header ('Content-Type: ' . $f->type);
558 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );