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();
47 var $is_email = false;
63 parent::getAuth(); // load company!
65 $au = $this->getAuthUser();
68 $this->authUser = false;
69 return true;//die("Access denied");
72 $this->authUser = $au;
77 var $as_mimetype = false;
78 var $method = 'inline';
81 function get($s, $opts=array()) // determin what to serve!!!!
84 //if (!empty($_GET['_post'])) {
85 // return $this->post();
88 if(!empty($_REQUEST['is_email'])) {
89 $this->is_email = true;
92 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
94 $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
96 $bits= explode('/', $s);
98 // var_dump($bits);die('in');
99 // without id as first part...
100 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
102 $this->as_mimetype = 'image/jpeg';
103 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
104 $id = empty($bits[2]) ? 0 : $bits[2];
106 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
107 $this->method = 'attachment';
108 $id = empty($bits[1]) ? 0 : $bits[1];
110 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
112 $this->as_mimetype = 'image/jpeg';
113 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
114 $id = empty($bits[3]) ? 0 : $bits[3];
116 } else if (!empty($bits[0]) && $bits[0] == 'events') {
117 if (!$this->authUser) {
118 $this->imgErr("no-authentication-events",$s);
120 $this->downloadEvent($bits);
121 $this->imgErr("unknown file",$s);
126 $id = empty($bits[0]) ? 0 : $bits[0];
129 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
131 if (!$this->authUser) {
132 $this->imgErr("not-authenticated-using-colon-format",$s);
136 $onbits = explode(':', $id);
137 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
138 $this->imgErr("bad-url",$s);
141 //DB_DataObject::debugLevel(1);
142 $img = DB_DataObject::factory('Images');
143 $img->ontable = $onbits[0];
144 $img->onid = $onbits[1];
145 if (empty($_REQUEST['anytype'])) {
146 $img->whereAdd("mimetype like 'image/%'");
148 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
149 if (isset($onbits[2])) {
150 $img->imgtype = $onbits[2];
153 if (!$img->find(true)) {
154 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
164 // depreciated - should use ontable:onid:type here...
165 if (!empty($_REQUEST['ontable'])) {
167 if (!$this->authUser) {
168 die("authentication required");
171 //DB_DataObjecT::debugLevel(1);
172 $img = DB_DataObject::factory('Images');
173 $img->setFrom($_REQUEST);
178 if (!$img->find(true)) {
179 $this->imgErr("No file exists",$s);
185 $img = DB_DataObjecT::factory('Images');
187 if (!$id || !$img->get($id)) {
188 $this->imgErr("image has been removed or deleted.",$s);
190 print_R('test???');exit;
191 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
193 if($this->is_email) {
194 return $this->serve($img);
197 if ($img->ontable != 'core_company') {
198 $this->imgErr("not-authenticated {$img->ontable}",$s);
200 if ($img->imgtype != 'LOGO') {
201 $this->imgErr("not-logo",$s);
203 $comp = $img->object();
204 if ($comp->comptype != 'OWNER') {
205 $this->imgErr("not-owner-company",$s);
208 return $this->serve($img);
212 if(!$this->hasPermission($img)){
213 $this->imgErr("access to this image/file has been denied.",$s);
220 function imgErr($reason,$path) {
221 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
222 urlencode($reason) .'&path='.urlencode($path));
226 function hasPermission($img)
234 if (!$this->authUser) {
235 $this->jerr("image conversion only allowed by registered users");
237 // converts a posted string (eg.svg)
238 // into another type..
239 if (empty($_REQUEST['as'])) {
240 $this->jerr("missing target type");
242 if (empty($_REQUEST['mimetype'])) {
243 $this->jerr("missing mimetype");
245 if (empty($_REQUEST['data'])) {
246 $this->jerr("missing data");
250 $this->as_mimetype = $_REQUEST['as'];
251 $this->mimetype = $_REQUEST['mimetype'];
252 require_once 'File/MimeType.php';
253 $y = new File_MimeType();
254 $src_ext = $y->toExt( $this->mimetype );
257 $tmp = $this->tempName($src_ext);
258 file_put_contents($tmp, $_REQUEST['data']);
260 require_once 'File/Convert.php';
261 $cv = new File_Convert($tmp, $this->mimetype);
265 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
266 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
268 if (!empty($_REQUEST['as_data'])) {
269 $this->jok(base64_encode(file_get_contents($fn)));
272 $cv->serve('attachment');
283 $this->sessionState(0); // turn off session... - locking...
285 require_once 'File/Convert.php';
286 if (!file_exists($img->getStoreName())) {
287 // print_r($img);exit;
288 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
289 urlencode("Original file was missing : " . $img->getStoreName()));
292 // print_r($img);exit;
293 $x = $img->toFileConvert();
294 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
295 $this->as_mimetype = $img->mimetype;
298 $x->convert( $this->as_mimetype);
299 $x->serve($this->method);
302 //echo "SKALING? $this->size";
303 // acutally if we generated the image, then we do not need to validate the size..
305 // if the mimetype is not converted..
306 // then the filename should be original.{size}.jpeg
307 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
309 if($img->mimetype == 'image/gif'){
310 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
313 if (!file_exists($fn)) {
314 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
315 // if it's an image, convert into the same type for thumbnail..
316 if (preg_match('#^image/#', $img->mimetype)) {
317 $this->as_mimetype = $img->mimetype;
321 if (!file_exists($fn)) {
322 $this->validateSize();
325 if(!empty($this->page) && !is_nan($this->page * 1)){
326 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
328 $x->convert( $this->as_mimetype, $this->size);
338 function validateSize()
340 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
341 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
346 $ff = HTML_FlexyFramework::get();
348 $sizes= $this->sizes;
350 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
351 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
353 if (!empty($cfg['sizes'])) {
354 $sizes = array_merge($sizes , $cfg['sizes']);
357 $project = $ff->project;
359 require_once $ff->project . '.php';
361 $project = str_replace('/', '_', $project);
363 $pr_obj = new $project;
365 // var_dump($pr_obj->Pman_Core_Images_Size);
366 if(isset($pr_obj->Pman_Core_Images_Size)){
367 $sizes = $pr_obj->Pman_Core_Images_Size;
372 if (!in_array($this->size, $sizes)) {
373 die("invalid scale - ".$this->size);
379 * The idea of this code was to replace urls for images when you have an admin
380 * and a distribution page. with different urls.
382 * it may be usefull later if things like embedded images in emails. but
383 * I think it's proably better not to use this.
385 * The key problem being how to determine if we are replacing 'our' images or some external one..
391 static function replaceImageURLS($html)
394 $ff = HTML_FlexyFramework::get();
395 if (!isset($ff->Pman_Images['public_baseURL'])) {
398 //var_dump($ff->Pman_Images['public_baseURL']);
399 $baseURL = $ff->Pman_Images['public_baseURL'];
401 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
403 $matches = array_unique($result[0]);
404 foreach($matches as $img) {
406 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
410 foreach($imatch[1] as $i=>$key) {
411 $attr[$key] = $imatch[2][$i];
413 // does it contain baseURL??? --- well what about relative paths...
416 if (empty($attr['src'])) {
419 if (0 !== strpos($attr['src'], $baseURL)) {
420 // it starts with our 'new' baseURL?
421 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
424 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
425 // contains an absolute path.. that is probably not us...
428 // what about mailto or data... - just ignore?? for images...
430 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
436 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
438 $matches = array_unique($result[0]);
439 foreach($matches as $img) {
441 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
445 foreach($imatch[1] as $i=>$key) {
446 $attr[$key] = $imatch[2][$i];
448 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
451 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
456 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
460 // see if it's an image url..
461 // Images/{ID}/fullname.xxxx
462 // Images/Thumb/200/{ID}/fullname.xxxx
463 // Images/Download/{ID}/fullname.xxxx
465 $attr_url = $attr[$attr_name];
467 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
473 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
474 $hh = explode('#',$umatch[3]);
475 $hash = '#'. array_pop($hh);
479 $img = DB_DataObject::factory('Images');
480 if (!$img->get($id)) {
483 $type = explode('/', $umatch[1]);
486 if (count($type) > 2 && $type[1] == 'Thumb') {
487 $thumbsize = $type[2];
488 $provider = '/Images/Thumb';
490 $provider = '/'.$umatch[1];
493 if (!empty($attr['width']) || !empty($attr['height']) )
495 // no support for %...
497 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
499 (empty($attr['height']) ? '0' : $attr['height'] * 1);
500 $provider = '/Images/Thumb';
504 if ($thumbsize !== -1) {
506 // need to regenerate it..
508 $type = array('Images', 'Thumb', $thumbsize);
510 $fc = $img->toFileConvert();
511 // make sure it's available..
512 $fc->convert($img->mimetype, $thumbsize);
516 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
520 // finally replace the original TAG with the new version..
522 $new_tag = str_replace(
523 $attr_name. '="'. $attr_url . '"',
524 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
529 return str_replace($tag, $new_tag, $html);
533 function downloadEvent($bits)
535 $ev = DB_DAtaObject::Factory('events');
536 if (!$ev->get($bits[1])) {
537 die("could not find event id");
539 // technically same user only.. -- normally www-data..
540 if (function_exists('posix_getpwuid')) {
541 $uinfo = posix_getpwuid( posix_getuid () );
542 $user = $uinfo['name'];
544 $user = getenv('USERNAME'); // windows.
546 $ff = HTML_FlexyFramework::get();
548 $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
550 if(!$file || !file_exists($file)){
551 die("file was not saved");
554 $filesJ = json_decode(file_get_contents($file));
556 foreach($filesJ->FILES as $k=>$f){
557 if ($f->tmp_name != $bits[2]) {
561 $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
563 if (!$src || !file_exists($src)) {
564 die("file was not saved");
566 header ('Content-Type: ' . $f->type);
568 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );