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';
78 var $is_local = false;
80 function get($s, $opts=array()) // determin what to serve!!!!
83 //if (!empty($_GET['_post'])) {
84 // return $this->post();
87 $this->is_local = (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') ? true : false;
89 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
91 $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
93 $bits= explode('/', $s);
95 // var_dump($bits);die('in');
96 // without id as first part...
97 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
99 $this->as_mimetype = 'image/jpeg';
100 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
101 $id = empty($bits[2]) ? 0 : $bits[2];
103 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
104 $this->method = 'attachment';
105 $id = empty($bits[1]) ? 0 : $bits[1];
107 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
109 $this->as_mimetype = 'image/jpeg';
110 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
111 $id = empty($bits[3]) ? 0 : $bits[3];
113 } else if (!empty($bits[0]) && $bits[0] == 'events') {
114 if (!$this->authUser) {
115 $this->imgErr("no-authentication-events",$s);
117 $this->downloadEvent($bits);
118 $this->imgErr("unknown file",$s);
123 $id = empty($bits[0]) ? 0 : $bits[0];
126 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
128 if (!$this->authUser) {
129 $this->imgErr("not-authenticated-using-colon-format",$s);
133 $onbits = explode(':', $id);
134 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
135 $this->imgErr("bad-url",$s);
138 //DB_DataObject::debugLevel(1);
139 $img = DB_DataObject::factory('Images');
140 $img->ontable = $onbits[0];
141 $img->onid = $onbits[1];
142 if (empty($_REQUEST['anytype'])) {
143 $img->whereAdd("mimetype like 'image/%'");
145 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
146 if (isset($onbits[2])) {
147 $img->imgtype = $onbits[2];
150 if (!$img->find(true)) {
151 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
161 // depreciated - should use ontable:onid:type here...
162 if (!empty($_REQUEST['ontable'])) {
164 if (!$this->authUser) {
165 die("authentication required");
168 //DB_DataObjecT::debugLevel(1);
169 $img = DB_DataObject::factory('Images');
170 $img->setFrom($_REQUEST);
175 if (!$img->find(true)) {
176 $this->imgErr("No file exists",$s);
182 $img = DB_DataObjecT::factory('Images');
184 if (!$id || !$img->get($id)) {
185 $this->imgErr("image has been removed or deleted.",$s);
188 if($this->is_local) {
189 return $this->serve($img);
192 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
194 if ($img->ontable != 'core_company') {
195 $this->imgErr("not-authenticated {$img->ontable}",$s);
197 if ($img->imgtype != 'LOGO') {
198 $this->imgErr("not-logo",$s);
200 $comp = $img->object();
201 if ($comp->comptype != 'OWNER') {
202 $this->imgErr("not-owner-company",$s);
205 return $this->serve($img);
209 if(!$this->hasPermission($img)){
210 $this->imgErr("access to this image/file has been denied.",$s);
217 function imgErr($reason,$path) {
218 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
219 urlencode($reason) .'&path='.urlencode($path));
223 function hasPermission($img)
231 if (!$this->authUser) {
232 $this->jerr("image conversion only allowed by registered users");
234 // converts a posted string (eg.svg)
235 // into another type..
236 if (empty($_REQUEST['as'])) {
237 $this->jerr("missing target type");
239 if (empty($_REQUEST['mimetype'])) {
240 $this->jerr("missing mimetype");
242 if (empty($_REQUEST['data'])) {
243 $this->jerr("missing data");
247 $this->as_mimetype = $_REQUEST['as'];
248 $this->mimetype = $_REQUEST['mimetype'];
249 require_once 'File/MimeType.php';
250 $y = new File_MimeType();
251 $src_ext = $y->toExt( $this->mimetype );
254 $tmp = $this->tempName($src_ext);
255 file_put_contents($tmp, $_REQUEST['data']);
257 require_once 'File/Convert.php';
258 $cv = new File_Convert($tmp, $this->mimetype);
262 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
263 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
265 if (!empty($_REQUEST['as_data'])) {
266 $this->jok(base64_encode(file_get_contents($fn)));
269 $cv->serve('attachment');
280 $this->sessionState(0); // turn off session... - locking...
282 require_once 'File/Convert.php';
283 if (!file_exists($img->getStoreName())) {
284 // print_r($img);exit;
285 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
286 urlencode("Original file was missing : " . $img->getStoreName()));
289 // print_r($img);exit;
290 $x = $img->toFileConvert();
291 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
292 $this->as_mimetype = $img->mimetype;
295 $x->convert( $this->as_mimetype);
296 $x->serve($this->method);
299 //echo "SKALING? $this->size";
300 // acutally if we generated the image, then we do not need to validate the size..
302 // if the mimetype is not converted..
303 // then the filename should be original.{size}.jpeg
304 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
306 if($img->mimetype == 'image/gif'){
307 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
310 if (!file_exists($fn)) {
311 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
312 // if it's an image, convert into the same type for thumbnail..
313 if (preg_match('#^image/#', $img->mimetype)) {
314 $this->as_mimetype = $img->mimetype;
318 if (!file_exists($fn)) {
319 $this->validateSize();
322 if(!empty($this->page) && !is_nan($this->page * 1)){
323 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
325 $x->convert( $this->as_mimetype, $this->size);
335 function validateSize()
337 if($this->is_local) {
341 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
342 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
347 $ff = HTML_FlexyFramework::get();
349 $sizes= $this->sizes;
351 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
352 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
354 if (!empty($cfg['sizes'])) {
355 $sizes = array_merge($sizes , $cfg['sizes']);
358 $project = $ff->project;
360 require_once $ff->project . '.php';
362 $project = str_replace('/', '_', $project);
364 $pr_obj = new $project;
366 // var_dump($pr_obj->Pman_Core_Images_Size);
367 if(isset($pr_obj->Pman_Core_Images_Size)){
368 $sizes = $pr_obj->Pman_Core_Images_Size;
373 if (!in_array($this->size, $sizes)) {
374 die("invalid scale - ".$this->size);
380 * The idea of this code was to replace urls for images when you have an admin
381 * and a distribution page. with different urls.
383 * it may be usefull later if things like embedded images in emails. but
384 * I think it's proably better not to use this.
386 * The key problem being how to determine if we are replacing 'our' images or some external one..
392 static function replaceImageURLS($html)
395 $ff = HTML_FlexyFramework::get();
396 if (!isset($ff->Pman_Images['public_baseURL'])) {
399 //var_dump($ff->Pman_Images['public_baseURL']);
400 $baseURL = $ff->Pman_Images['public_baseURL'];
402 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
404 $matches = array_unique($result[0]);
405 foreach($matches as $img) {
407 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
411 foreach($imatch[1] as $i=>$key) {
412 $attr[$key] = $imatch[2][$i];
414 // does it contain baseURL??? --- well what about relative paths...
417 if (empty($attr['src'])) {
420 if (0 !== strpos($attr['src'], $baseURL)) {
421 // it starts with our 'new' baseURL?
422 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
425 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
426 // contains an absolute path.. that is probably not us...
429 // what about mailto or data... - just ignore?? for images...
431 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
437 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
439 $matches = array_unique($result[0]);
440 foreach($matches as $img) {
442 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
446 foreach($imatch[1] as $i=>$key) {
447 $attr[$key] = $imatch[2][$i];
449 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
452 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
457 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
461 // see if it's an image url..
462 // Images/{ID}/fullname.xxxx
463 // Images/Thumb/200/{ID}/fullname.xxxx
464 // Images/Download/{ID}/fullname.xxxx
466 $attr_url = $attr[$attr_name];
468 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
474 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
475 $hh = explode('#',$umatch[3]);
476 $hash = '#'. array_pop($hh);
480 $img = DB_DataObject::factory('Images');
481 if (!$img->get($id)) {
484 $type = explode('/', $umatch[1]);
487 if (count($type) > 2 && $type[1] == 'Thumb') {
488 $thumbsize = $type[2];
489 $provider = '/Images/Thumb';
491 $provider = '/'.$umatch[1];
494 if (!empty($attr['width']) || !empty($attr['height']) )
496 // no support for %...
498 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
500 (empty($attr['height']) ? '0' : $attr['height'] * 1);
501 $provider = '/Images/Thumb';
505 if ($thumbsize !== -1) {
507 // need to regenerate it..
509 $type = array('Images', 'Thumb', $thumbsize);
511 $fc = $img->toFileConvert();
512 // make sure it's available..
513 $fc->convert($img->mimetype, $thumbsize);
517 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
521 // finally replace the original TAG with the new version..
523 $new_tag = str_replace(
524 $attr_name. '="'. $attr_url . '"',
525 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
530 return str_replace($tag, $new_tag, $html);
534 function downloadEvent($bits)
536 $ev = DB_DAtaObject::Factory('events');
537 if (!$ev->get($bits[1])) {
538 die("could not find event id");
540 // technically same user only.. -- normally www-data..
541 if (function_exists('posix_getpwuid')) {
542 $uinfo = posix_getpwuid( posix_getuid () );
543 $user = $uinfo['name'];
545 $user = getenv('USERNAME'); // windows.
547 $ff = HTML_FlexyFramework::get();
549 $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
551 if(!$file || !file_exists($file)){
552 die("file was not saved");
555 $filesJ = json_decode(file_get_contents($file));
557 foreach($filesJ->FILES as $k=>$f){
558 if ($f->tmp_name != $bits[2]) {
562 $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
564 if (!$src || !file_exists($src)) {
565 die("file was not saved");
567 header ('Content-Type: ' . $f->type);
569 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );