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
41 // tables that do not need authentication checks before serving.
42 var $public_image_tables = array();
47 parent::getAuth(); // load company!
49 $au = $this->getAuthUser();
52 $this->authUser = false;
53 return true;//die("Access denied");
56 $this->authUser = $au;
61 var $as_mimetype = false;
62 var $method = 'inline';
64 function get($s, $opts=array()) // determin what to serve!!!!
67 //if (!empty($_GET['_post'])) {
68 // return $this->post();
71 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
73 $bits= explode('/', $s);
75 // var_dump($bits);die('in');
76 // without id as first part...
77 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
79 $this->as_mimetype = 'image/jpeg';
80 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
81 $id = empty($bits[2]) ? 0 : $bits[2];
83 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
84 $this->method = 'attachment';
85 $id = empty($bits[1]) ? 0 : $bits[1];
87 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
89 $this->as_mimetype = 'image/jpeg';
90 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
91 $id = empty($bits[3]) ? 0 : $bits[3];
93 } else if (!empty($bits[0]) && $bits[0] == 'events') {
94 if (!$this->authUser) {
95 $this->imgErr("no-authentication-events",$s);
97 $this->downloadEvent($bits);
98 $this->imgErr("unknown file",$s);
103 $id = empty($bits[0]) ? 0 : $bits[0];
106 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
108 if (!$this->authUser) {
109 $this->imgErr("not-authenticated-using-colon-format",$s);
113 $onbits = explode(':', $id);
114 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
115 $this->imgErr("bad-url",$s);
118 //DB_DataObject::debugLevel(1);
119 $img = DB_DataObject::factory('Images');
120 $img->ontable = $onbits[0];
121 $img->onid = $onbits[1];
122 if (empty($_REQUEST['anytype'])) {
123 $img->whereAdd("mimetype like 'image/%'");
125 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
126 if (isset($onbits[2])) {
127 $img->imgtype = $onbits[2];
130 if (!$img->find(true)) {
131 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
141 // depreciated - should use ontable:onid:type here...
142 if (!empty($_REQUEST['ontable'])) {
144 if (!$this->authUser) {
145 die("authentication required");
148 //DB_DataObjecT::debugLevel(1);
149 $img = DB_DataObject::factory('Images');
150 $img->setFrom($_REQUEST);
155 if (!$img->find(true)) {
156 $this->imgErr("No file exists",$s);
164 $img = DB_DataObjecT::factory('Images');
166 if (!$id || !$img->get($id)) {
167 $this->imgErr("image has been removed or deleted.",$s);
170 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
172 if ($img->ontable != 'core_company') {
173 $this->imgErr("not-authenticated {$img->ontable}",$s);
175 if ($img->imgtype != 'LOGO') {
176 $this->imgErr("not-logo",$s);
178 $comp = $img->object();
179 if ($comp->comptype != 'OWNER') {
180 $this->imgErr("not-owner-company",$s);
182 return $this->serve($img);
188 if(!$this->hasPermission($img)){
189 $this->imgErr("access to this image/file has been denied.",$s);
197 function imgErr($reason,$path) {
198 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
199 urlencode($reason) .'&path='.urlencode($path));
203 function hasPermission($img)
211 if (!$this->authUser) {
212 $this->jerr("image conversion only allowed by registered users");
214 // converts a posted string (eg.svg)
215 // into another type..
216 if (empty($_REQUEST['as'])) {
217 $this->jerr("missing target type");
219 if (empty($_REQUEST['mimetype'])) {
220 $this->jerr("missing mimetype");
222 if (empty($_REQUEST['data'])) {
223 $this->jerr("missing data");
227 $this->as_mimetype = $_REQUEST['as'];
228 $this->mimetype = $_REQUEST['mimetype'];
229 require_once 'File/MimeType.php';
230 $y = new File_MimeType();
231 $src_ext = $y->toExt( $this->mimetype );
234 $tmp = $this->tempName($src_ext);
235 file_put_contents($tmp, $_REQUEST['data']);
237 require_once 'File/Convert.php';
238 $cv = new File_Convert($tmp, $this->mimetype);
242 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
243 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
245 if (!empty($_REQUEST['as_data'])) {
246 $this->jok(base64_encode(file_get_contents($fn)));
249 $cv->serve('attachment');
260 $this->sessionState(0); // turn off session... - locking...
262 require_once 'File/Convert.php';
263 if (!file_exists($img->getStoreName())) {
264 // print_r($img);exit;
265 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
266 urlencode("Original file was missing : " . $img->getStoreName()));
269 // print_r($img);exit;
270 $x = $img->toFileConvert();
271 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
272 $this->as_mimetype = $img->mimetype;
275 $x->convert( $this->as_mimetype);
276 $x->serve($this->method);
279 //echo "SKALING? $this->size";
280 // acutally if we generated the image, then we do not need to validate the size..
282 // if the mimetype is not converted..
283 // then the filename should be original.{size}.jpeg
284 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
286 if($img->mimetype == 'image/gif'){
287 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
290 if (!file_exists($fn)) {
291 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
292 // if it's an image, convert into the same type for thumbnail..
293 if (preg_match('#^image/#', $img->mimetype)) {
294 $this->as_mimetype = $img->mimetype;
298 if (!file_exists($fn)) {
299 $this->validateSize();
302 $x->convert( $this->as_mimetype, $this->size);
310 function validateSize()
312 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
313 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
318 $ff = HTML_FlexyFramework::get();
333 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
334 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
336 if (!empty($cfg['sizes'])) {
337 $sizes = array_merge($sizes , $cfg['sizes']);
340 $project = $ff->project;
342 require_once $ff->project . '.php';
344 $project = str_replace('/', '_', $project);
346 $pr_obj = new $project;
348 // var_dump($pr_obj->Pman_Core_Images_Size);
349 if(isset($pr_obj->Pman_Core_Images_Size)){
350 $sizes = $pr_obj->Pman_Core_Images_Size;
355 if (!in_array($this->size, $sizes)) {
356 die("invalid scale - ".$this->size);
362 * The idea of this code was to replace urls for images when you have an admin
363 * and a distribution page. with different urls.
365 * it may be usefull later if things like embedded images in emails. but
366 * I think it's proably better not to use this.
368 * The key problem being how to determine if we are replacing 'our' images or some external one..
374 static function replaceImageURLS($html)
377 $ff = HTML_FlexyFramework::get();
378 if (!isset($ff->Pman_Images['public_baseURL'])) {
381 //var_dump($ff->Pman_Images['public_baseURL']);
382 $baseURL = $ff->Pman_Images['public_baseURL'];
384 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
386 $matches = array_unique($result[0]);
387 foreach($matches as $img) {
389 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
393 foreach($imatch[1] as $i=>$key) {
394 $attr[$key] = $imatch[2][$i];
396 // does it contain baseURL??? --- well what about relative paths...
399 if (empty($attr['src'])) {
402 if (0 !== strpos($attr['src'], $baseURL)) {
403 // it starts with our 'new' baseURL?
404 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
407 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
408 // contains an absolute path.. that is probably not us...
411 // what about mailto or data... - just ignore?? for images...
413 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
419 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
421 $matches = array_unique($result[0]);
422 foreach($matches as $img) {
424 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
428 foreach($imatch[1] as $i=>$key) {
429 $attr[$key] = $imatch[2][$i];
431 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
434 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
439 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
443 // see if it's an image url..
444 // Images/{ID}/fullname.xxxx
445 // Images/Thumb/200/{ID}/fullname.xxxx
446 // Images/Download/{ID}/fullname.xxxx
448 $attr_url = $attr[$attr_name];
450 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
456 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
457 $hash = '#'. array_pop(explode('#',$umatch[3]));
461 $img = DB_DataObject::factory('Images');
462 if (!$img->get($id)) {
465 $type = explode('/', $umatch[1]);
468 if (count($type) > 2 && $type[1] == 'Thumb') {
469 $thumbsize = $type[2];
470 $provider = '/Images/Thumb';
472 $provider = '/'.$umatch[1];
475 if (!empty($attr['width']) || !empty($attr['height']) )
477 // no support for %...
479 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
481 (empty($attr['height']) ? '0' : $attr['height'] * 1);
482 $provider = '/Images/Thumb';
486 if ($thumbsize !== -1) {
488 // need to regenerate it..
490 $type = array('Images', 'Thumb', $thumbsize);
492 $fc = $img->toFileConvert();
493 // make sure it's available..
494 $fc->convert($img->mimetype, $thumbsize);
498 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
502 // finally replace the original TAG with the new version..
504 $new_tag = str_replace(
505 $attr_name. '="'. $attr_url . '"',
506 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
511 return str_replace($tag, $new_tag, $html);
515 function downloadEvent($bits)
517 $popts = PEAR::getStaticProperty('Pman','options');
518 $ev = DB_DAtaObject::Factory('events');
519 if (!$ev->get($bits[1])) {
520 die("could not find event id");
522 // technically same user only.. -- normally www-data..
523 if (function_exists('posix_getpwuid')) {
524 $uinfo = posix_getpwuid( posix_getuid () );
525 $user = $uinfo['name'];
527 $user = getenv('USERNAME'); // windows.
529 $ff = HTML_FlexyFramework::get();
530 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
531 $filesJ = json_decode(file_get_contents($file));
535 foreach($filesJ->FILES as $k=>$f){
536 if ($f->tmp_name != $bits[2]) {
540 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
541 if (!file_exists($src)) {
542 die("file was not saved");
544 header ('Content-Type: ' . $f->type);
546 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );