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();
58 parent::getAuth(); // load company!
60 $au = $this->getAuthUser();
63 $this->authUser = false;
64 return true;//die("Access denied");
67 $this->authUser = $au;
72 var $as_mimetype = false;
73 var $method = 'inline';
76 function get($s, $opts=array()) // determin what to serve!!!!
79 //if (!empty($_GET['_post'])) {
80 // return $this->post();
83 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
85 $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
87 $bits= explode('/', $s);
89 // var_dump($bits);die('in');
90 // without id as first part...
91 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
93 $this->as_mimetype = 'image/jpeg';
94 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
95 $id = empty($bits[2]) ? 0 : $bits[2];
97 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
98 $this->method = 'attachment';
99 $id = empty($bits[1]) ? 0 : $bits[1];
101 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
103 $this->as_mimetype = 'image/jpeg';
104 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
105 $id = empty($bits[3]) ? 0 : $bits[3];
107 } else if (!empty($bits[0]) && $bits[0] == 'events') {
108 if (!$this->authUser) {
109 $this->imgErr("no-authentication-events",$s);
111 $this->downloadEvent($bits);
112 $this->imgErr("unknown file",$s);
117 $id = empty($bits[0]) ? 0 : $bits[0];
120 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
122 if (!$this->authUser) {
123 $this->imgErr("not-authenticated-using-colon-format",$s);
127 $onbits = explode(':', $id);
128 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
129 $this->imgErr("bad-url",$s);
132 //DB_DataObject::debugLevel(1);
133 $img = DB_DataObject::factory('Images');
134 $img->ontable = $onbits[0];
135 $img->onid = $onbits[1];
136 if (empty($_REQUEST['anytype'])) {
137 $img->whereAdd("mimetype like 'image/%'");
139 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
140 if (isset($onbits[2])) {
141 $img->imgtype = $onbits[2];
144 if (!$img->find(true)) {
145 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
155 // depreciated - should use ontable:onid:type here...
156 if (!empty($_REQUEST['ontable'])) {
158 if (!$this->authUser) {
159 die("authentication required");
162 //DB_DataObjecT::debugLevel(1);
163 $img = DB_DataObject::factory('Images');
164 $img->setFrom($_REQUEST);
169 if (!$img->find(true)) {
170 $this->imgErr("No file exists",$s);
178 $img = DB_DataObjecT::factory('Images');
180 if (!$id || !$img->get($id)) {
181 $this->imgErr("image has been removed or deleted.",$s);
184 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
186 if ($img->ontable != 'core_company') {
187 $this->imgErr("not-authenticated {$img->ontable}",$s);
189 if ($img->imgtype != 'LOGO') {
190 $this->imgErr("not-logo",$s);
192 $comp = $img->object();
193 if ($comp->comptype != 'OWNER') {
194 $this->imgErr("not-owner-company",$s);
196 return $this->serve($img);
202 if(!$this->hasPermission($img)){
203 $this->imgErr("access to this image/file has been denied.",$s);
211 function imgErr($reason,$path) {
212 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
213 urlencode($reason) .'&path='.urlencode($path));
217 function hasPermission($img)
225 if (!$this->authUser) {
226 $this->jerr("image conversion only allowed by registered users");
228 // converts a posted string (eg.svg)
229 // into another type..
230 if (empty($_REQUEST['as'])) {
231 $this->jerr("missing target type");
233 if (empty($_REQUEST['mimetype'])) {
234 $this->jerr("missing mimetype");
236 if (empty($_REQUEST['data'])) {
237 $this->jerr("missing data");
241 $this->as_mimetype = $_REQUEST['as'];
242 $this->mimetype = $_REQUEST['mimetype'];
243 require_once 'File/MimeType.php';
244 $y = new File_MimeType();
245 $src_ext = $y->toExt( $this->mimetype );
248 $tmp = $this->tempName($src_ext);
249 file_put_contents($tmp, $_REQUEST['data']);
251 require_once 'File/Convert.php';
252 $cv = new File_Convert($tmp, $this->mimetype);
256 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
257 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
259 if (!empty($_REQUEST['as_data'])) {
260 $this->jok(base64_encode(file_get_contents($fn)));
263 $cv->serve('attachment');
274 $this->sessionState(0); // turn off session... - locking...
276 require_once 'File/Convert.php';
277 if (!file_exists($img->getStoreName())) {
278 // print_r($img);exit;
279 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
280 urlencode("Original file was missing : " . $img->getStoreName()));
283 // print_r($img);exit;
284 $x = $img->toFileConvert();
285 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
286 $this->as_mimetype = $img->mimetype;
289 $x->convert( $this->as_mimetype);
290 $x->serve($this->method);
293 //echo "SKALING? $this->size";
294 // acutally if we generated the image, then we do not need to validate the size..
296 // if the mimetype is not converted..
297 // then the filename should be original.{size}.jpeg
298 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
300 if($img->mimetype == 'image/gif'){
301 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
304 if (!file_exists($fn)) {
305 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
306 // if it's an image, convert into the same type for thumbnail..
307 if (preg_match('#^image/#', $img->mimetype)) {
308 $this->as_mimetype = $img->mimetype;
312 if (!file_exists($fn)) {
313 $this->validateSize();
316 if(!empty($this->page) && !is_nan($this->page * 1)){
317 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
319 $x->convert( $this->as_mimetype, $this->size);
329 function validateSize()
331 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
332 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
337 $ff = HTML_FlexyFramework::get();
339 $sizes= $this->sizes;
341 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
342 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
344 if (!empty($cfg['sizes'])) {
345 $sizes = array_merge($sizes , $cfg['sizes']);
348 $project = $ff->project;
350 require_once $ff->project . '.php';
352 $project = str_replace('/', '_', $project);
354 $pr_obj = new $project;
356 // var_dump($pr_obj->Pman_Core_Images_Size);
357 if(isset($pr_obj->Pman_Core_Images_Size)){
358 $sizes = $pr_obj->Pman_Core_Images_Size;
363 if (!in_array($this->size, $sizes)) {
364 die("invalid scale - ".$this->size);
370 * The idea of this code was to replace urls for images when you have an admin
371 * and a distribution page. with different urls.
373 * it may be usefull later if things like embedded images in emails. but
374 * I think it's proably better not to use this.
376 * The key problem being how to determine if we are replacing 'our' images or some external one..
382 static function replaceImageURLS($html)
385 $ff = HTML_FlexyFramework::get();
386 if (!isset($ff->Pman_Images['public_baseURL'])) {
389 //var_dump($ff->Pman_Images['public_baseURL']);
390 $baseURL = $ff->Pman_Images['public_baseURL'];
392 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
394 $matches = array_unique($result[0]);
395 foreach($matches as $img) {
397 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
401 foreach($imatch[1] as $i=>$key) {
402 $attr[$key] = $imatch[2][$i];
404 // does it contain baseURL??? --- well what about relative paths...
407 if (empty($attr['src'])) {
410 if (0 !== strpos($attr['src'], $baseURL)) {
411 // it starts with our 'new' baseURL?
412 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
415 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
416 // contains an absolute path.. that is probably not us...
419 // what about mailto or data... - just ignore?? for images...
421 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
427 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
429 $matches = array_unique($result[0]);
430 foreach($matches as $img) {
432 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
436 foreach($imatch[1] as $i=>$key) {
437 $attr[$key] = $imatch[2][$i];
439 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
442 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
447 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
451 // see if it's an image url..
452 // Images/{ID}/fullname.xxxx
453 // Images/Thumb/200/{ID}/fullname.xxxx
454 // Images/Download/{ID}/fullname.xxxx
456 $attr_url = $attr[$attr_name];
458 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
464 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
465 $hash = '#'. array_pop(explode('#',$umatch[3]));
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 $popts = PEAR::getStaticProperty('Pman','options');
526 $ev = DB_DAtaObject::Factory('events');
527 if (!$ev->get($bits[1])) {
528 die("could not find event id");
530 // technically same user only.. -- normally www-data..
531 if (function_exists('posix_getpwuid')) {
532 $uinfo = posix_getpwuid( posix_getuid () );
533 $user = $uinfo['name'];
535 $user = getenv('USERNAME'); // windows.
537 $ff = HTML_FlexyFramework::get();
538 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
539 $filesJ = json_decode(file_get_contents($file));
543 foreach($filesJ->FILES as $k=>$f){
544 if ($f->tmp_name != $bits[2]) {
548 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
549 if (!file_exists($src)) {
550 die("file was not saved");
552 header ('Content-Type: ' . $f->type);
554 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );