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';
65 function get($s, $opts=array()) // determin what to serve!!!!
68 //if (!empty($_GET['_post'])) {
69 // return $this->post();
72 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
74 $bits= explode('/', $s);
76 // var_dump($bits);die('in');
77 // without id as first part...
78 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
80 $this->as_mimetype = 'image/jpeg';
81 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
82 $id = empty($bits[2]) ? 0 : $bits[2];
84 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
85 $this->method = 'attachment';
86 $id = empty($bits[1]) ? 0 : $bits[1];
88 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
90 $this->as_mimetype = 'image/jpeg';
91 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
92 $id = empty($bits[3]) ? 0 : $bits[3];
94 } else if (!empty($bits[0]) && $bits[0] == 'events') {
95 if (!$this->authUser) {
96 $this->imgErr("no-authentication-events",$s);
98 $this->downloadEvent($bits);
99 $this->imgErr("unknown file",$s);
104 $id = empty($bits[0]) ? 0 : $bits[0];
107 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
109 if (!$this->authUser) {
110 $this->imgErr("not-authenticated-using-colon-format",$s);
114 $onbits = explode(':', $id);
115 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
116 $this->imgErr("bad-url",$s);
119 //DB_DataObject::debugLevel(1);
120 $img = DB_DataObject::factory('Images');
121 $img->ontable = $onbits[0];
122 $img->onid = $onbits[1];
123 if (empty($_REQUEST['anytype'])) {
124 $img->whereAdd("mimetype like 'image/%'");
126 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
127 if (isset($onbits[2])) {
128 $img->imgtype = $onbits[2];
131 if (!$img->find(true)) {
132 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
142 // depreciated - should use ontable:onid:type here...
143 if (!empty($_REQUEST['ontable'])) {
145 if (!$this->authUser) {
146 die("authentication required");
149 //DB_DataObjecT::debugLevel(1);
150 $img = DB_DataObject::factory('Images');
151 $img->setFrom($_REQUEST);
156 if (!$img->find(true)) {
157 $this->imgErr("No file exists",$s);
165 $img = DB_DataObjecT::factory('Images');
167 if (!$id || !$img->get($id)) {
168 $this->imgErr("image has been removed or deleted.",$s);
171 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
173 if ($img->ontable != 'core_company') {
174 $this->imgErr("not-authenticated {$img->ontable}",$s);
176 if ($img->imgtype != 'LOGO') {
177 $this->imgErr("not-logo",$s);
179 $comp = $img->object();
180 if ($comp->comptype != 'OWNER') {
181 $this->imgErr("not-owner-company",$s);
183 return $this->serve($img);
189 if(!$this->hasPermission($img)){
190 $this->imgErr("access to this image/file has been denied.",$s);
198 function imgErr($reason,$path) {
199 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
200 urlencode($reason) .'&path='.urlencode($path));
204 function hasPermission($img)
212 if (!$this->authUser) {
213 $this->jerr("image conversion only allowed by registered users");
215 // converts a posted string (eg.svg)
216 // into another type..
217 if (empty($_REQUEST['as'])) {
218 $this->jerr("missing target type");
220 if (empty($_REQUEST['mimetype'])) {
221 $this->jerr("missing mimetype");
223 if (empty($_REQUEST['data'])) {
224 $this->jerr("missing data");
228 $this->as_mimetype = $_REQUEST['as'];
229 $this->mimetype = $_REQUEST['mimetype'];
230 require_once 'File/MimeType.php';
231 $y = new File_MimeType();
232 $src_ext = $y->toExt( $this->mimetype );
235 $tmp = $this->tempName($src_ext);
236 file_put_contents($tmp, $_REQUEST['data']);
238 require_once 'File/Convert.php';
239 $cv = new File_Convert($tmp, $this->mimetype);
243 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
244 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
246 if (!empty($_REQUEST['as_data'])) {
247 $this->jok(base64_encode(file_get_contents($fn)));
250 $cv->serve('attachment');
261 $this->sessionState(0); // turn off session... - locking...
263 require_once 'File/Convert.php';
264 if (!file_exists($img->getStoreName())) {
265 // print_r($img);exit;
266 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
267 urlencode("Original file was missing : " . $img->getStoreName()));
270 // print_r($img);exit;
271 $x = $img->toFileConvert();
272 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
273 $this->as_mimetype = $img->mimetype;
276 $x->convert( $this->as_mimetype);
277 $x->serve($this->method);
280 //echo "SKALING? $this->size";
281 // acutally if we generated the image, then we do not need to validate the size..
283 // if the mimetype is not converted..
284 // then the filename should be original.{size}.jpeg
285 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
287 if($img->mimetype == 'image/gif'){
288 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
291 if (!file_exists($fn)) {
292 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
293 // if it's an image, convert into the same type for thumbnail..
294 if (preg_match('#^image/#', $img->mimetype)) {
295 $this->as_mimetype = $img->mimetype;
299 if (!file_exists($fn)) {
300 $this->validateSize();
303 $x->convert( $this->as_mimetype, $this->size);
311 function validateSize()
313 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
314 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
319 $ff = HTML_FlexyFramework::get();
334 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
335 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
337 if (!empty($cfg['sizes'])) {
338 $sizes = array_merge($sizes , $cfg['sizes']);
341 $project = $ff->project;
343 require_once $ff->project . '.php';
345 $project = str_replace('/', '_', $project);
347 $pr_obj = new $project;
349 // var_dump($pr_obj->Pman_Core_Images_Size);
350 if(isset($pr_obj->Pman_Core_Images_Size)){
351 $sizes = $pr_obj->Pman_Core_Images_Size;
356 if (!in_array($this->size, $sizes)) {
357 die("invalid scale - ".$this->size);
363 * The idea of this code was to replace urls for images when you have an admin
364 * and a distribution page. with different urls.
366 * it may be usefull later if things like embedded images in emails. but
367 * I think it's proably better not to use this.
369 * The key problem being how to determine if we are replacing 'our' images or some external one..
375 static function replaceImageURLS($html)
378 $ff = HTML_FlexyFramework::get();
379 if (!isset($ff->Pman_Images['public_baseURL'])) {
382 //var_dump($ff->Pman_Images['public_baseURL']);
383 $baseURL = $ff->Pman_Images['public_baseURL'];
385 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
387 $matches = array_unique($result[0]);
388 foreach($matches as $img) {
390 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
394 foreach($imatch[1] as $i=>$key) {
395 $attr[$key] = $imatch[2][$i];
397 // does it contain baseURL??? --- well what about relative paths...
400 if (empty($attr['src'])) {
403 if (0 !== strpos($attr['src'], $baseURL)) {
404 // it starts with our 'new' baseURL?
405 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
408 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
409 // contains an absolute path.. that is probably not us...
412 // what about mailto or data... - just ignore?? for images...
414 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
420 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
422 $matches = array_unique($result[0]);
423 foreach($matches as $img) {
425 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
429 foreach($imatch[1] as $i=>$key) {
430 $attr[$key] = $imatch[2][$i];
432 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
435 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
440 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
444 // see if it's an image url..
445 // Images/{ID}/fullname.xxxx
446 // Images/Thumb/200/{ID}/fullname.xxxx
447 // Images/Download/{ID}/fullname.xxxx
449 $attr_url = $attr[$attr_name];
451 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
457 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
458 $hash = '#'. array_pop(explode('#',$umatch[3]));
462 $img = DB_DataObject::factory('Images');
463 if (!$img->get($id)) {
466 $type = explode('/', $umatch[1]);
469 if (count($type) > 2 && $type[1] == 'Thumb') {
470 $thumbsize = $type[2];
471 $provider = '/Images/Thumb';
473 $provider = '/'.$umatch[1];
476 if (!empty($attr['width']) || !empty($attr['height']) )
478 // no support for %...
480 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
482 (empty($attr['height']) ? '0' : $attr['height'] * 1);
483 $provider = '/Images/Thumb';
487 if ($thumbsize !== -1) {
489 // need to regenerate it..
491 $type = array('Images', 'Thumb', $thumbsize);
493 $fc = $img->toFileConvert();
494 // make sure it's available..
495 $fc->convert($img->mimetype, $thumbsize);
499 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
503 // finally replace the original TAG with the new version..
505 $new_tag = str_replace(
506 $attr_name. '="'. $attr_url . '"',
507 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
512 return str_replace($tag, $new_tag, $html);
516 function downloadEvent($bits)
518 $popts = PEAR::getStaticProperty('Pman','options');
519 $ev = DB_DAtaObject::Factory('events');
520 if (!$ev->get($bits[1])) {
521 die("could not find event id");
523 // technically same user only.. -- normally www-data..
524 if (function_exists('posix_getpwuid')) {
525 $uinfo = posix_getpwuid( posix_getuid () );
526 $user = $uinfo['name'];
528 $user = getenv('USERNAME'); // windows.
530 $ff = HTML_FlexyFramework::get();
531 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
532 $filesJ = json_decode(file_get_contents($file));
536 foreach($filesJ->FILES as $k=>$f){
537 if ($f->tmp_name != $bits[2]) {
541 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
542 if (!file_exists($src)) {
543 die("file was not saved");
545 header ('Content-Type: ' . $f->type);
547 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );