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 var $public_image_tables = array();
46 parent::getAuth(); // load company!
48 $au = $this->getAuthUser();
51 $this->authUser = false;
52 return true;//die("Access denied");
55 $this->authUser = $au;
60 var $as_mimetype = false;
61 var $method = 'inline';
63 function get($s, $opts=array()) // determin what to serve!!!!
66 //if (!empty($_GET['_post'])) {
67 // return $this->post();
70 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
72 $bits= explode('/', $s);
74 // var_dump($bits);die('in');
75 // without id as first part...
76 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
78 $this->as_mimetype = 'image/jpeg';
79 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
80 $id = empty($bits[2]) ? 0 : $bits[2];
82 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
83 $this->method = 'attachment';
84 $id = empty($bits[1]) ? 0 : $bits[1];
86 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
88 $this->as_mimetype = 'image/jpeg';
89 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
90 $id = empty($bits[3]) ? 0 : $bits[3];
92 } else if (!empty($bits[0]) && $bits[0] == 'events') {
93 if (!$this->authUser) {
94 $this->imgErr("no-authentication-events",$s);
96 $this->downloadEvent($bits);
97 $this->imgErr("unknown file",$s);
102 $id = empty($bits[0]) ? 0 : $bits[0];
105 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
107 if (!$this->authUser) {
108 $this->imgErr("not-authenticated-using-colon-format",$s);
112 $onbits = explode(':', $id);
113 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
114 $this->imgErr("bad-url",$s);
117 //DB_DataObject::debugLevel(1);
118 $img = DB_DataObject::factory('Images');
119 $img->ontable = $onbits[0];
120 $img->onid = $onbits[1];
121 if (empty($_REQUEST['anytype'])) {
122 $img->whereAdd("mimetype like 'image/%'");
124 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
125 if (isset($onbits[2])) {
126 $img->imgtype = $onbits[2];
129 if (!$img->find(true)) {
130 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
140 // depreciated - should use ontable:onid:type here...
141 if (!empty($_REQUEST['ontable'])) {
143 if (!$this->authUser) {
144 die("authentication required");
147 //DB_DataObjecT::debugLevel(1);
148 $img = DB_DataObject::factory('Images');
149 $img->setFrom($_REQUEST);
154 if (!$img->find(true)) {
155 $this->imgErr("No file exists",$s);
163 $img = DB_DataObjecT::factory('Images');
165 if (!$id || !$img->get($id)) {
166 $this->imgErr("image has been removed or deleted.",$s);
169 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
171 if ($img->ontable != 'core_company') {
172 $this->imgErr("not-authenticated {$img->ontable}",$s);
174 if ($img->imgtype != 'LOGO') {
175 $this->imgErr("not-logo",$s);
177 $comp = $img->object();
178 if ($comp->comptype != 'OWNER') {
179 $this->imgErr("not-owner-company",$s);
181 return $this->serve($img);
187 if(!$this->hasPermission($img)){
188 $this->imgErr("access to this image/file has been denied.",$s);
196 function imgErr($reason,$path) {
197 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
198 urlencode($reason) .'&path='.urlencode($path));
202 function hasPermission($img)
210 if (!$this->authUser) {
211 $this->jerr("image conversion only allowed by registered users");
213 // converts a posted string (eg.svg)
214 // into another type..
215 if (empty($_REQUEST['as'])) {
216 $this->jerr("missing target type");
218 if (empty($_REQUEST['mimetype'])) {
219 $this->jerr("missing mimetype");
221 if (empty($_REQUEST['data'])) {
222 $this->jerr("missing data");
226 $this->as_mimetype = $_REQUEST['as'];
227 $this->mimetype = $_REQUEST['mimetype'];
228 require_once 'File/MimeType.php';
229 $y = new File_MimeType();
230 $src_ext = $y->toExt( $this->mimetype );
233 $tmp = $this->tempName($src_ext);
234 file_put_contents($tmp, $_REQUEST['data']);
236 require_once 'File/Convert.php';
237 $cv = new File_Convert($tmp, $this->mimetype);
241 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
242 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
244 if (!empty($_REQUEST['as_data'])) {
245 $this->jok(base64_encode(file_get_contents($fn)));
248 $cv->serve('attachment');
259 $this->sessionState(0); // turn off session... - locking...
261 require_once 'File/Convert.php';
262 if (!file_exists($img->getStoreName())) {
263 // print_r($img);exit;
264 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
265 urlencode("Original file was missing : " . $img->getStoreName()));
268 // print_r($img);exit;
269 $x = $img->toFileConvert();
270 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
271 $this->as_mimetype = $img->mimetype;
274 $x->convert( $this->as_mimetype);
275 $x->serve($this->method);
278 //echo "SKALING? $this->size";
279 // acutally if we generated the image, then we do not need to validate the size..
281 // if the mimetype is not converted..
282 // then the filename should be original.{size}.jpeg
283 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
285 if($img->mimetype == 'image/gif'){
286 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
289 if (!file_exists($fn)) {
290 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
291 // if it's an image, convert into the same type for thumbnail..
292 if (preg_match('#^image/#', $img->mimetype)) {
293 $this->as_mimetype = $img->mimetype;
297 if (!file_exists($fn)) {
298 $this->validateSize();
301 $x->convert( $this->as_mimetype, $this->size);
309 function validateSize()
311 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
312 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
317 $ff = HTML_FlexyFramework::get();
332 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
333 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
335 if (!empty($cfg['sizes'])) {
336 $sizes = array_merge($sizes , $cfg['sizes']);
339 $project = $ff->project;
341 require_once $ff->project . '.php';
343 $project = str_replace('/', '_', $project);
345 $pr_obj = new $project;
347 // var_dump($pr_obj->Pman_Core_Images_Size);
348 if(isset($pr_obj->Pman_Core_Images_Size)){
349 $sizes = $pr_obj->Pman_Core_Images_Size;
354 if (!in_array($this->size, $sizes)) {
355 die("invalid scale - ".$this->size);
361 * The idea of this code was to replace urls for images when you have an admin
362 * and a distribution page. with different urls.
364 * it may be usefull later if things like embedded images in emails. but
365 * I think it's proably better not to use this.
367 * The key problem being how to determine if we are replacing 'our' images or some external one..
373 static function replaceImageURLS($html)
376 $ff = HTML_FlexyFramework::get();
377 if (!isset($ff->Pman_Images['public_baseURL'])) {
380 //var_dump($ff->Pman_Images['public_baseURL']);
381 $baseURL = $ff->Pman_Images['public_baseURL'];
383 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
385 $matches = array_unique($result[0]);
386 foreach($matches as $img) {
388 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
392 foreach($imatch[1] as $i=>$key) {
393 $attr[$key] = $imatch[2][$i];
395 // does it contain baseURL??? --- well what about relative paths...
398 if (empty($attr['src'])) {
401 if (0 !== strpos($attr['src'], $baseURL)) {
402 // it starts with our 'new' baseURL?
403 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
406 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
407 // contains an absolute path.. that is probably not us...
410 // what about mailto or data... - just ignore?? for images...
412 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
418 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
420 $matches = array_unique($result[0]);
421 foreach($matches as $img) {
423 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
427 foreach($imatch[1] as $i=>$key) {
428 $attr[$key] = $imatch[2][$i];
430 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
433 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
438 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
442 // see if it's an image url..
443 // Images/{ID}/fullname.xxxx
444 // Images/Thumb/200/{ID}/fullname.xxxx
445 // Images/Download/{ID}/fullname.xxxx
447 $attr_url = $attr[$attr_name];
449 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
455 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
456 $hash = '#'. array_pop(explode('#',$umatch[3]));
460 $img = DB_DataObject::factory('Images');
461 if (!$img->get($id)) {
464 $type = explode('/', $umatch[1]);
467 if (count($type) > 2 && $type[1] == 'Thumb') {
468 $thumbsize = $type[2];
469 $provider = '/Images/Thumb';
471 $provider = '/'.$umatch[1];
474 if (!empty($attr['width']) || !empty($attr['height']) )
476 // no support for %...
478 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
480 (empty($attr['height']) ? '0' : $attr['height'] * 1);
481 $provider = '/Images/Thumb';
485 if ($thumbsize !== -1) {
487 // need to regenerate it..
489 $type = array('Images', 'Thumb', $thumbsize);
491 $fc = $img->toFileConvert();
492 // make sure it's available..
493 $fc->convert($img->mimetype, $thumbsize);
497 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
501 // finally replace the original TAG with the new version..
503 $new_tag = str_replace(
504 $attr_name. '="'. $attr_url . '"',
505 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
510 return str_replace($tag, $new_tag, $html);
514 function downloadEvent($bits)
516 $popts = PEAR::getStaticProperty('Pman','options');
517 $ev = DB_DAtaObject::Factory('events');
518 if (!$ev->get($bits[1])) {
519 die("could not find event id");
521 // technically same user only.. -- normally www-data..
522 if (function_exists('posix_getpwuid')) {
523 $uinfo = posix_getpwuid( posix_getuid () );
524 $user = $uinfo['name'];
526 $user = getenv('USERNAME'); // windows.
528 $ff = HTML_FlexyFramework::get();
529 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
530 $filesJ = json_decode(file_get_contents($file));
534 foreach($filesJ->FILES as $k=>$f){
535 if ($f->tmp_name != $bits[2]) {
539 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
540 if (!file_exists($src)) {
541 die("file was not saved");
543 header ('Content-Type: ' . $f->type);
545 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );