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';
79 function get($s, $opts=array()) // determin what to serve!!!!
82 //if (!empty($_GET['_post'])) {
83 // return $this->post();
86 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
88 $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
90 $bits= explode('/', $s);
92 // var_dump($bits);die('in');
93 // without id as first part...
94 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
96 $this->as_mimetype = 'image/jpeg';
97 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
98 $id = empty($bits[2]) ? 0 : $bits[2];
100 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
101 $this->method = 'attachment';
102 $id = empty($bits[1]) ? 0 : $bits[1];
104 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
106 $this->as_mimetype = 'image/jpeg';
107 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
108 $id = empty($bits[3]) ? 0 : $bits[3];
110 } else if (!empty($bits[0]) && $bits[0] == 'events') {
111 if (!$this->authUser) {
112 $this->imgErr("no-authentication-events",$s);
114 $this->downloadEvent($bits);
115 $this->imgErr("unknown file",$s);
120 $id = empty($bits[0]) ? 0 : $bits[0];
123 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
125 if (!$this->authUser) {
126 $this->imgErr("not-authenticated-using-colon-format",$s);
130 $onbits = explode(':', $id);
131 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
132 $this->imgErr("bad-url",$s);
135 //DB_DataObject::debugLevel(1);
136 $img = DB_DataObject::factory('Images');
137 $img->ontable = $onbits[0];
138 $img->onid = $onbits[1];
139 if (empty($_REQUEST['anytype'])) {
140 $img->whereAdd("mimetype like 'image/%'");
142 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
143 if (isset($onbits[2])) {
144 $img->imgtype = $onbits[2];
147 if (!$img->find(true)) {
148 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
158 // depreciated - should use ontable:onid:type here...
159 if (!empty($_REQUEST['ontable'])) {
161 if (!$this->authUser) {
162 die("authentication required");
165 //DB_DataObjecT::debugLevel(1);
166 $img = DB_DataObject::factory('Images');
167 $img->setFrom($_REQUEST);
172 if (!$img->find(true)) {
173 $this->imgErr("No file exists",$s);
181 $img = DB_DataObjecT::factory('Images');
183 if (!$id || !$img->get($id)) {
184 $this->imgErr("image has been removed or deleted.",$s);
187 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
189 if ($img->ontable != 'core_company') {
190 $this->imgErr("not-authenticated {$img->ontable}",$s);
192 if ($img->imgtype != 'LOGO') {
193 $this->imgErr("not-logo",$s);
195 $comp = $img->object();
196 if ($comp->comptype != 'OWNER') {
197 $this->imgErr("not-owner-company",$s);
199 return $this->serve($img);
205 if(!$this->hasPermission($img)){
206 $this->imgErr("access to this image/file has been denied.",$s);
214 function imgErr($reason,$path) {
215 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
216 urlencode($reason) .'&path='.urlencode($path));
220 function hasPermission($img)
228 if (!$this->authUser) {
229 $this->jerr("image conversion only allowed by registered users");
231 // converts a posted string (eg.svg)
232 // into another type..
233 if (empty($_REQUEST['as'])) {
234 $this->jerr("missing target type");
236 if (empty($_REQUEST['mimetype'])) {
237 $this->jerr("missing mimetype");
239 if (empty($_REQUEST['data'])) {
240 $this->jerr("missing data");
244 $this->as_mimetype = $_REQUEST['as'];
245 $this->mimetype = $_REQUEST['mimetype'];
246 require_once 'File/MimeType.php';
247 $y = new File_MimeType();
248 $src_ext = $y->toExt( $this->mimetype );
251 $tmp = $this->tempName($src_ext);
252 file_put_contents($tmp, $_REQUEST['data']);
254 require_once 'File/Convert.php';
255 $cv = new File_Convert($tmp, $this->mimetype);
259 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
260 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
262 if (!empty($_REQUEST['as_data'])) {
263 $this->jok(base64_encode(file_get_contents($fn)));
266 $cv->serve('attachment');
277 $this->sessionState(0); // turn off session... - locking...
279 require_once 'File/Convert.php';
280 if (!file_exists($img->getStoreName())) {
281 // print_r($img);exit;
282 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
283 urlencode("Original file was missing : " . $img->getStoreName()));
286 // print_r($img);exit;
287 $x = $img->toFileConvert();
288 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
289 $this->as_mimetype = $img->mimetype;
292 $x->convert( $this->as_mimetype);
293 $x->serve($this->method);
296 //echo "SKALING? $this->size";
297 // acutally if we generated the image, then we do not need to validate the size..
299 // if the mimetype is not converted..
300 // then the filename should be original.{size}.jpeg
301 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
303 if($img->mimetype == 'image/gif'){
304 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
307 if (!file_exists($fn)) {
308 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
309 // if it's an image, convert into the same type for thumbnail..
310 if (preg_match('#^image/#', $img->mimetype)) {
311 $this->as_mimetype = $img->mimetype;
315 if (!file_exists($fn)) {
316 $this->validateSize();
319 if(!empty($this->page) && !is_nan($this->page * 1)){
320 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
322 $x->convert( $this->as_mimetype, $this->size);
332 function validateSize()
334 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
335 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
340 $ff = HTML_FlexyFramework::get();
342 $sizes= $this->sizes;
344 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
345 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
347 if (!empty($cfg['sizes'])) {
348 $sizes = array_merge($sizes , $cfg['sizes']);
351 $project = $ff->project;
353 require_once $ff->project . '.php';
355 $project = str_replace('/', '_', $project);
357 $pr_obj = new $project;
359 // var_dump($pr_obj->Pman_Core_Images_Size);
360 if(isset($pr_obj->Pman_Core_Images_Size)){
361 $sizes = $pr_obj->Pman_Core_Images_Size;
366 if (!in_array($this->size, $sizes)) {
367 die("invalid scale - ".$this->size);
373 * The idea of this code was to replace urls for images when you have an admin
374 * and a distribution page. with different urls.
376 * it may be usefull later if things like embedded images in emails. but
377 * I think it's proably better not to use this.
379 * The key problem being how to determine if we are replacing 'our' images or some external one..
385 static function replaceImageURLS($html)
388 $ff = HTML_FlexyFramework::get();
389 if (!isset($ff->Pman_Images['public_baseURL'])) {
392 //var_dump($ff->Pman_Images['public_baseURL']);
393 $baseURL = $ff->Pman_Images['public_baseURL'];
395 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
397 $matches = array_unique($result[0]);
398 foreach($matches as $img) {
400 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
404 foreach($imatch[1] as $i=>$key) {
405 $attr[$key] = $imatch[2][$i];
407 // does it contain baseURL??? --- well what about relative paths...
410 if (empty($attr['src'])) {
413 if (0 !== strpos($attr['src'], $baseURL)) {
414 // it starts with our 'new' baseURL?
415 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
418 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
419 // contains an absolute path.. that is probably not us...
422 // what about mailto or data... - just ignore?? for images...
424 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
430 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
432 $matches = array_unique($result[0]);
433 foreach($matches as $img) {
435 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
439 foreach($imatch[1] as $i=>$key) {
440 $attr[$key] = $imatch[2][$i];
442 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
445 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
450 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
454 // see if it's an image url..
455 // Images/{ID}/fullname.xxxx
456 // Images/Thumb/200/{ID}/fullname.xxxx
457 // Images/Download/{ID}/fullname.xxxx
459 $attr_url = $attr[$attr_name];
461 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
467 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
468 $hash = '#'. array_pop(explode('#',$umatch[3]));
472 $img = DB_DataObject::factory('Images');
473 if (!$img->get($id)) {
476 $type = explode('/', $umatch[1]);
479 if (count($type) > 2 && $type[1] == 'Thumb') {
480 $thumbsize = $type[2];
481 $provider = '/Images/Thumb';
483 $provider = '/'.$umatch[1];
486 if (!empty($attr['width']) || !empty($attr['height']) )
488 // no support for %...
490 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
492 (empty($attr['height']) ? '0' : $attr['height'] * 1);
493 $provider = '/Images/Thumb';
497 if ($thumbsize !== -1) {
499 // need to regenerate it..
501 $type = array('Images', 'Thumb', $thumbsize);
503 $fc = $img->toFileConvert();
504 // make sure it's available..
505 $fc->convert($img->mimetype, $thumbsize);
509 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
513 // finally replace the original TAG with the new version..
515 $new_tag = str_replace(
516 $attr_name. '="'. $attr_url . '"',
517 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
522 return str_replace($tag, $new_tag, $html);
526 function downloadEvent($bits)
528 // $popts = PEAR::getStaticProperty('Pman','options');
529 $ev = DB_DAtaObject::Factory('events');
530 if (!$ev->get($bits[1])) {
531 die("could not find event id");
533 // technically same user only.. -- normally www-data..
534 if (function_exists('posix_getpwuid')) {
535 $uinfo = posix_getpwuid( posix_getuid () );
536 $user = $uinfo['name'];
538 $user = getenv('USERNAME'); // windows.
540 $ff = HTML_FlexyFramework::get();
544 if (!empty($ff->Pman['storedir'])) {
545 $file = $ff->Pman['storedir']. '/Events/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
548 if (!empty($ff->Pman['event_log_dir'])) {
549 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
552 if(!$file || !file_exists($file)){
553 die("file was not saved");
556 $filesJ = json_decode(file_get_contents($file));
558 foreach($filesJ->FILES as $k=>$f){
559 if ($f->tmp_name != $bits[2]) {
565 if (!empty($ff->Pman['storedir'])) {
566 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
569 if (!empty($ff->Pman['event_log_dir'])) {
570 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
573 if (!$src || !file_exists($src)) {
574 die("file was not saved");
576 header ('Content-Type: ' . $f->type);
578 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );