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(
46 'crm_mailing_list_message' // we know these are ok...
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';
80 var $is_local = false;
84 function get($s, $opts=array()) // determin what to serve!!!!
87 //if (!empty($_GET['_post'])) {
88 // return $this->post();
93 $this->is_local = (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') ? true : false;
95 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
97 $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
99 $bits= explode('/', $s);
101 // var_dump($bits);die('in');
102 // without id as first part...
103 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
105 $this->as_mimetype = 'image/jpeg';
106 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
107 $id = empty($bits[2]) ? 0 : $bits[2];
109 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
110 $this->method = 'attachment';
111 $id = empty($bits[1]) ? 0 : $bits[1];
113 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
115 $this->as_mimetype = 'image/jpeg';
116 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
117 $id = empty($bits[3]) ? 0 : $bits[3];
119 } else if (!empty($bits[0]) && $bits[0] == 'events') {
120 if (!$this->authUser) {
121 $this->imgErr("no-authentication-events",$s);
123 $this->downloadEvent($bits);
124 $this->imgErr("unknown file",$s);
129 $id = empty($bits[0]) ? 0 : $bits[0];
132 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
133 //DB_DataObject::debugLevel(1);
134 if (!$this->authUser) {
135 $this->imgErr("not-authenticated-using-colon-format",$s);
139 $onbits = explode(':', $id);
140 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
141 $this->imgErr("bad-url",$s);
144 //DB_DataObject::debugLevel(1);
145 $img = DB_DataObject::factory('Images');
146 $img->ontable = $onbits[0];
147 $img->onid = $onbits[1];
148 if (empty($_REQUEST['anytype'])) {
149 $img->whereAdd("mimetype like 'image/%'");
151 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
152 if (isset($onbits[2])) {
153 $img->imgtype = $onbits[2];
156 if (!$img->find(true)) {
157 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
167 // depreciated - should use ontable:onid:type here...
168 if (!empty($_REQUEST['ontable'])) {
170 if (!$this->authUser) {
171 die("authentication required");
174 //DB_DataObjecT::debugLevel(1);
175 $img = DB_DataObject::factory('Images');
176 $img->setFrom($_REQUEST);
181 if (!$img->find(true)) {
182 $this->imgErr("No file exists",$s);
188 $img = DB_DataObjecT::factory('Images');
190 if (!$id || !$img->get($id) || !$img->exists()) {
191 //print_r($img); die("HERE");
192 $this->imgErr("image has been removed or deleted.",$s);
195 if($this->is_local) {
196 return $this->serve($img);
199 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
201 if ($img->ontable != 'core_company') {
202 $this->imgErr("not-authenticated {$img->ontable}",$s);
204 if ($img->imgtype != 'LOGO') {
205 $this->imgErr("not-logo",$s);
207 $comp = $img->object();
208 if ($comp->comptype != 'OWNER') {
209 $this->imgErr("not-owner-company",$s);
212 return $this->serve($img);
216 if(!$this->hasPermission($img)){
217 $this->imgErr("access to this image/file has been denied.",$s);
224 function imgErr($reason,$path) {
225 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' . urlencode($reason) );
226 header('X-Error: ' . $reason . ':' . $path);
227 echo $reason . ':' . $path;
231 function hasPermission($img)
238 if (!empty($_REQUEST['_get'])) {
239 return $this->get($v);
242 if (!$this->authUser) {
243 $this->jerr("image conversion only allowed by registered users");
245 // converts a posted string (eg.svg)
246 // into another type..
247 if (empty($_REQUEST['as'])) {
248 $this->jerr("missing target type");
250 if (empty($_REQUEST['mimetype'])) {
251 $this->jerr("missing mimetype");
253 if (empty($_REQUEST['data'])) {
254 $this->jerr("missing data");
258 $this->as_mimetype = $_REQUEST['as'];
259 $this->mimetype = $_REQUEST['mimetype'];
260 require_once 'File/MimeType.php';
261 $y = new File_MimeType();
262 $src_ext = $y->toExt( $this->mimetype );
265 $tmp = $this->tempName($src_ext);
266 file_put_contents($tmp, $_REQUEST['data']);
268 require_once 'File/Convert.php';
269 $cv = new File_Convert($tmp, $this->mimetype);
273 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
274 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
276 if (!empty($_REQUEST['as_data'])) {
277 $this->jok(base64_encode(file_get_contents($fn)));
280 $cv->serve('attachment');
292 $this->sessionState(0); // turn off session... - locking...
293 require_once 'File/Convert.php';
294 if (!$img->exists()) {
295 $this->imgErr("serve = missing-image", $img->getStoreName());
298 // print_r($img);exit;
299 $x = $img->toFileConvert();
300 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
301 $this->as_mimetype = $img->mimetype;
306 if ($x->mimetype == $this->as_mimetype) {
307 $x->serveOnly($this->method, $img->filename);
310 $x->convert( $this->as_mimetype);
311 $x->serve($this->method, $img->filename);
314 //echo "SKALING? $this->size";
315 // acutally if we generated the image, then we do not need to validate the size..
317 // if the mimetype is not converted..
318 // then the filename should be original.{size}.jpeg
319 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
321 if($img->mimetype == 'image/gif'){
322 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
325 if (!file_exists($fn)) {
326 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
327 // if it's an image, convert into the same type for thumbnail..
328 if (preg_match('#^image/#', $img->mimetype)) {
329 $this->as_mimetype = $img->mimetype;
333 if (!file_exists($fn)) {
334 $this->validateSize();
338 if(!empty($this->page) && !is_nan($this->page * 1)){
339 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
341 $x->convert( $this->as_mimetype, $this->size);
351 function validateSize()
353 if($this->is_local) {
357 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
358 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
363 $ff = HTML_FlexyFramework::get();
365 $sizes= $this->sizes;
367 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
368 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
370 if (!empty($cfg['sizes'])) {
371 $sizes = array_merge($sizes , $cfg['sizes']);
374 $project = $ff->project;
376 require_once $ff->project . '.php';
378 $project = str_replace('/', '_', $project);
380 $pr_obj = new $project;
382 // var_dump($pr_obj->Pman_Core_Images_Size);
383 if(isset($pr_obj->Pman_Core_Images_Size)){
384 $sizes = $pr_obj->Pman_Core_Images_Size;
389 if (!in_array($this->size, $sizes)) {
390 die("invalid scale - ".$this->size);
396 * The idea of this code was to replace urls for images when you have an admin
397 * and a distribution page. with different urls.
399 * it may be usefull later if things like embedded images in emails. but
400 * I think it's proably better not to use this.
402 * The key problem being how to determine if we are replacing 'our' images or some external one..
408 static function replaceImageURLS($html, $obj = false)
411 $ff = HTML_FlexyFramework::get();
412 if (!isset($ff->Pman_Images['public_baseURL'])) {
415 //var_dump($ff->Pman_Images['public_baseURL']);
416 $baseURL = $ff->Pman_Images['public_baseURL'];
418 libxml_use_internal_errors(true);
419 $dom = new DOMDocument();
420 $dom->loadHTML("<?xml encoding='utf-8'?> <div id='tmp_dom_wrapper'>{$html}</div>");
421 $imgs = $dom->getElementsByTagName('img');
424 foreach($imgs as $img) {
425 $src = $img->getAttribute('src');
426 if (!$src|| !strlen(trim($src))) {
430 if (0 === strpos($src, 'data:')) {
432 HTML_FlexyFramework::get()->page->jerr("no object to attach data url");
435 self::replaceDataUrl($baseURL, $img, $obj);
440 if (false !== strpos($src, '//') && false === strpos($src, $baseURL)) {
441 // contains an absolute path.. and not our baseURL.
445 $img->setAttribute('src', self::domImgUrl($baseURL, $img));
447 // what about mailto or data... - just ignore?? for images...
452 $anchors = $dom->getElementsByTagName('a');
454 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
456 $matches = array_unique($result[0]);
457 foreach($anchors as $anc) {
458 $href = $anc->getAttribute('href');
459 if (!empty($href) || 0 !== strpos($href, $baseURL)) {
462 $anc->setAttribute('href', self::domImgUrl($baseURL, $href));
466 $inner = $dom->getElementById("tmp_dom_wrapper");
468 foreach ($inner->childNodes as $child) {
469 $html .= ($dom->saveHTML($child));
474 static function domImgUrl($baseURL, $dom)
477 if (!is_string($url)) {
478 $url = $dom->getAttribute('src');
481 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $url, $umatch)) {
487 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
488 $hh = explode('#',$umatch[3]);
489 $hash = '#'. array_pop($hh);
493 $img = DB_DataObject::factory('Images');
494 if (!$img->get($id)) {
497 $type = explode('/', $umatch[1]);
500 if (count($type) > 2 && $type[1] == 'Thumb') {
501 $thumbsize = $type[2];
502 $provider = '/Images/Thumb';
504 $provider = '/'.$umatch[1];
507 $w = is_string($dom) ? false : $dom->getAttribute('width');
508 $h = is_string($dom) ? false : $dom->getAttribute('width');
510 if (!is_string($dom) && (!empty($w) || !empty($h)) )
512 // no support for %...
514 (empty($w) ? '0' : $w * 1) .
516 (empty($h) ? '0' : $h * 1);
517 $provider = '/Images/Thumb';
521 if ($thumbsize !== -1) {
523 // need to regenerate it..
525 $type = array('Images', 'Thumb', $thumbsize);
527 $fc = $img->toFileConvert();
528 // make sure it's available..
529 $fc->convert($img->mimetype, $thumbsize);
533 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
537 // finally replace the original TAG with the new version..
539 return $img->URL($thumbsize, $provider, $baseURL) . $hash ;
544 static function replaceDataUrl($baseURL, $img, $obj)
546 $d = DB_DataObject::Factory('Images');
550 $d->createFromData($img->getAttribute('src'));
551 $img->setAttribute('src', $d->URL(-1, '/Images' , $baseURL));
554 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
558 // see if it's an image url..
559 // Images/{ID}/fullname.xxxx
560 // Images/Thumb/200/{ID}/fullname.xxxx
561 // Images/Download/{ID}/fullname.xxxx
563 $attr_url = $attr[$attr_name];
565 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
571 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
572 $hh = explode('#',$umatch[3]);
573 $hash = '#'. array_pop($hh);
577 $img = DB_DataObject::factory('Images');
578 if (!$img->get($id)) {
581 $type = explode('/', $umatch[1]);
584 if (count($type) > 2 && $type[1] == 'Thumb') {
585 $thumbsize = $type[2];
586 $provider = '/Images/Thumb';
588 $provider = '/'.$umatch[1];
591 if (!empty($attr['width']) || !empty($attr['height']) )
593 // no support for %...
595 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
597 (empty($attr['height']) ? '0' : $attr['height'] * 1);
598 $provider = '/Images/Thumb';
602 if ($thumbsize !== -1) {
604 // need to regenerate it..
606 $type = array('Images', 'Thumb', $thumbsize);
608 $fc = $img->toFileConvert();
609 // make sure it's available..
610 $fc->convert($img->mimetype, $thumbsize);
614 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
618 // finally replace the original TAG with the new version..
620 $new_tag = str_replace(
621 $attr_name. '="'. $attr_url . '"',
622 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
627 return str_replace($tag, $new_tag, $html);
631 function downloadEvent($bits)
633 $ev = DB_DAtaObject::Factory('events');
634 if (!$ev->get($bits[1])) {
635 die("could not find event id");
637 // technically same user only.. -- normally www-data..
638 if (function_exists('posix_getpwuid')) {
639 $uinfo = posix_getpwuid( posix_getuid () );
640 $user = $uinfo['name'];
642 $user = getenv('USERNAME'); // windows.
644 $ff = HTML_FlexyFramework::get();
646 $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
648 if(!$file || !file_exists($file)){
649 die("file was not saved");
652 $filesJ = json_decode(file_get_contents($file));
654 foreach($filesJ->FILES as $k=>$f){
655 if ($f->tmp_name != $bits[2]) {
659 $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
661 if (!$src || !file_exists($src)) {
662 die("file was not saved");
664 header ('Content-Type: ' . $f->type);
666 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );