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;
82 function get($s, $opts=array()) // determin what to serve!!!!
85 //if (!empty($_GET['_post'])) {
86 // return $this->post();
89 //DB_DataObject::debugLevel(1);
91 $this->is_local = (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') ? true : false;
93 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
95 $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
97 $bits= explode('/', $s);
99 // var_dump($bits);die('in');
100 // without id as first part...
101 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
103 $this->as_mimetype = 'image/jpeg';
104 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
105 $id = empty($bits[2]) ? 0 : $bits[2];
107 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
108 $this->method = 'attachment';
109 $id = empty($bits[1]) ? 0 : $bits[1];
111 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
113 $this->as_mimetype = 'image/jpeg';
114 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
115 $id = empty($bits[3]) ? 0 : $bits[3];
117 } else if (!empty($bits[0]) && $bits[0] == 'events') {
118 if (!$this->authUser) {
119 $this->imgErr("no-authentication-events",$s);
121 $this->downloadEvent($bits);
122 $this->imgErr("unknown file",$s);
127 $id = empty($bits[0]) ? 0 : $bits[0];
130 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
131 //DB_DataObject::debugLevel(1);
132 if (!$this->authUser) {
133 $this->imgErr("not-authenticated-using-colon-format",$s);
137 $onbits = explode(':', $id);
138 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
139 $this->imgErr("bad-url",$s);
142 //DB_DataObject::debugLevel(1);
143 $img = DB_DataObject::factory('Images');
144 $img->ontable = $onbits[0];
145 $img->onid = $onbits[1];
146 if (empty($_REQUEST['anytype'])) {
147 $img->whereAdd("mimetype like 'image/%'");
149 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
150 if (isset($onbits[2])) {
151 $img->imgtype = $onbits[2];
154 if (!$img->find(true)) {
156 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
166 // depreciated - should use ontable:onid:type here...
167 if (!empty($_REQUEST['ontable'])) {
169 if (!$this->authUser) {
170 die("authentication required");
173 //DB_DataObjecT::debugLevel(1);
174 $img = DB_DataObject::factory('Images');
175 $img->setFrom($_REQUEST);
180 if (!$img->find(true)) {
181 $this->imgErr("No file exists",$s);
187 $img = DB_DataObjecT::factory('Images');
189 if (!$id || !$img->get($id) || !$img->exists()) {
190 $this->imgErr("image has been removed or deleted.",$s);
193 if($this->is_local) {
194 return $this->serve($img);
197 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
199 if ($img->ontable != 'core_company') {
200 $this->imgErr("not-authenticated {$img->ontable}",$s);
202 if ($img->imgtype != 'LOGO') {
203 $this->imgErr("not-logo",$s);
205 $comp = $img->object();
206 if ($comp->comptype != 'OWNER') {
207 $this->imgErr("not-owner-company",$s);
210 return $this->serve($img);
214 if(!$this->hasPermission($img)){
215 $this->imgErr("access to this image/file has been denied.",$s);
222 function imgErr($reason,$path) {
224 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
225 urlencode($reason) .'&path='.urlencode($path));
229 function hasPermission($img)
236 if (!empty($_REQUEST['_get'])) {
237 return $this->get($v);
240 if (!$this->authUser) {
241 $this->jerr("image conversion only allowed by registered users");
243 // converts a posted string (eg.svg)
244 // into another type..
245 if (empty($_REQUEST['as'])) {
246 $this->jerr("missing target type");
248 if (empty($_REQUEST['mimetype'])) {
249 $this->jerr("missing mimetype");
251 if (empty($_REQUEST['data'])) {
252 $this->jerr("missing data");
256 $this->as_mimetype = $_REQUEST['as'];
257 $this->mimetype = $_REQUEST['mimetype'];
258 require_once 'File/MimeType.php';
259 $y = new File_MimeType();
260 $src_ext = $y->toExt( $this->mimetype );
263 $tmp = $this->tempName($src_ext);
264 file_put_contents($tmp, $_REQUEST['data']);
266 require_once 'File/Convert.php';
267 $cv = new File_Convert($tmp, $this->mimetype);
271 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
272 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
274 if (!empty($_REQUEST['as_data'])) {
275 $this->jok(base64_encode(file_get_contents($fn)));
278 $cv->serve('attachment');
289 $this->sessionState(0); // turn off session... - locking...
290 require_once 'File/Convert.php';
291 if (!file_exists($img->getStoreName())) {
292 // print_r($img);exit;
293 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
294 urlencode("Original file was missing : " . $img->getStoreName()));
297 // print_r($img);exit;
298 $x = $img->toFileConvert();
299 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
300 $this->as_mimetype = $img->mimetype;
303 if ($x->mimetype == $this->as_mimetype) {
304 $x->serveOnly($this->method);
309 $x->convert( $this->as_mimetype);
310 $x->serve($this->method);
313 //echo "SKALING? $this->size";
314 // acutally if we generated the image, then we do not need to validate the size..
316 // if the mimetype is not converted..
317 // then the filename should be original.{size}.jpeg
318 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
320 if($img->mimetype == 'image/gif'){
321 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
324 if (!file_exists($fn)) {
325 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
326 // if it's an image, convert into the same type for thumbnail..
327 if (preg_match('#^image/#', $img->mimetype)) {
328 $this->as_mimetype = $img->mimetype;
332 if (!file_exists($fn)) {
333 $this->validateSize();
336 if(!empty($this->page) && !is_nan($this->page * 1)){
337 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
339 $x->convert( $this->as_mimetype, $this->size);
349 function validateSize()
351 if($this->is_local) {
355 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
356 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
361 $ff = HTML_FlexyFramework::get();
363 $sizes= $this->sizes;
365 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
366 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
368 if (!empty($cfg['sizes'])) {
369 $sizes = array_merge($sizes , $cfg['sizes']);
372 $project = $ff->project;
374 require_once $ff->project . '.php';
376 $project = str_replace('/', '_', $project);
378 $pr_obj = new $project;
380 // var_dump($pr_obj->Pman_Core_Images_Size);
381 if(isset($pr_obj->Pman_Core_Images_Size)){
382 $sizes = $pr_obj->Pman_Core_Images_Size;
387 if (!in_array($this->size, $sizes)) {
388 die("invalid scale - ".$this->size);
394 * The idea of this code was to replace urls for images when you have an admin
395 * and a distribution page. with different urls.
397 * it may be usefull later if things like embedded images in emails. but
398 * I think it's proably better not to use this.
400 * The key problem being how to determine if we are replacing 'our' images or some external one..
406 static function replaceImageURLS($html, $obj = false)
409 $ff = HTML_FlexyFramework::get();
410 if (!isset($ff->Pman_Images['public_baseURL'])) {
413 //var_dump($ff->Pman_Images['public_baseURL']);
414 $baseURL = $ff->Pman_Images['public_baseURL'];
416 libxml_use_internal_errors(true);
417 $dom = new DOMDocument();
418 $dom->loadHTML("<?xml encoding='utf-8'?> <div id='tmp_dom_wrapper'>{$html}</div>");
419 $imgs = $dom->getElementsByTagName('img');
422 foreach($imgs as $img) {
423 $src = $img->getAttribute('src');
424 if (!$src|| !strlen(trim($src))) {
428 if (0 === strpos($src, 'data:')) {
430 HTML_FlexyFramework::get()->page->jerr("no object to attach data url");
433 self::replaceDataUrl($baseURL, $img, $obj);
438 if (false !== strpos($src, '//') && false === strpos($src, $baseURL)) {
439 // contains an absolute path.. and not our baseURL.
443 $img->setAttribute('src', self::domImgUrl($baseURL, $img));
445 // what about mailto or data... - just ignore?? for images...
450 $anchors = $dom->getElementsByTagName('a');
452 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
454 $matches = array_unique($result[0]);
455 foreach($anchors as $anc) {
456 $href = $anc->getAttribute('href');
457 if (!empty($href) || 0 !== strpos($href, $baseURL)) {
460 $anc->setAttribute('href', self::domImgUrl($baseURL, $href));
464 $inner = $dom->getElementById("tmp_dom_wrapper");
466 foreach ($inner->childNodes as $child) {
467 $html .= ($dom->saveHTML($child));
472 static function domImgUrl($baseURL, $dom)
475 if (!is_string($url)) {
476 $url = $dom->getAttribute('src');
479 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $url, $umatch)) {
485 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
486 $hh = explode('#',$umatch[3]);
487 $hash = '#'. array_pop($hh);
491 $img = DB_DataObject::factory('Images');
492 if (!$img->get($id)) {
495 $type = explode('/', $umatch[1]);
498 if (count($type) > 2 && $type[1] == 'Thumb') {
499 $thumbsize = $type[2];
500 $provider = '/Images/Thumb';
502 $provider = '/'.$umatch[1];
505 $w = is_string($dom) ? false : $dom->getAttribute('width');
506 $h = is_string($dom) ? false : $dom->getAttribute('width');
508 if (!is_string($dom) && (!empty($w) || !empty($h)) )
510 // no support for %...
512 (empty($w) ? '0' : $w * 1) .
514 (empty($h) ? '0' : $h * 1);
515 $provider = '/Images/Thumb';
519 if ($thumbsize !== -1) {
521 // need to regenerate it..
523 $type = array('Images', 'Thumb', $thumbsize);
525 $fc = $img->toFileConvert();
526 // make sure it's available..
527 $fc->convert($img->mimetype, $thumbsize);
531 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
535 // finally replace the original TAG with the new version..
537 return $img->URL($thumbsize, $provider, $baseURL) . $hash ;
542 static function replaceDataUrl($baseURL, $img, $obj)
544 $d = DB_DataObject::Factory('Images');
548 $d->createFromData($img->getAttribute('src'));
549 $img->setAttribute('src', $d->URL(-1, '/Images' , $baseURL));
552 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
556 // see if it's an image url..
557 // Images/{ID}/fullname.xxxx
558 // Images/Thumb/200/{ID}/fullname.xxxx
559 // Images/Download/{ID}/fullname.xxxx
561 $attr_url = $attr[$attr_name];
563 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
569 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
570 $hh = explode('#',$umatch[3]);
571 $hash = '#'. array_pop($hh);
575 $img = DB_DataObject::factory('Images');
576 if (!$img->get($id)) {
579 $type = explode('/', $umatch[1]);
582 if (count($type) > 2 && $type[1] == 'Thumb') {
583 $thumbsize = $type[2];
584 $provider = '/Images/Thumb';
586 $provider = '/'.$umatch[1];
589 if (!empty($attr['width']) || !empty($attr['height']) )
591 // no support for %...
593 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
595 (empty($attr['height']) ? '0' : $attr['height'] * 1);
596 $provider = '/Images/Thumb';
600 if ($thumbsize !== -1) {
602 // need to regenerate it..
604 $type = array('Images', 'Thumb', $thumbsize);
606 $fc = $img->toFileConvert();
607 // make sure it's available..
608 $fc->convert($img->mimetype, $thumbsize);
612 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
616 // finally replace the original TAG with the new version..
618 $new_tag = str_replace(
619 $attr_name. '="'. $attr_url . '"',
620 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
625 return str_replace($tag, $new_tag, $html);
629 function downloadEvent($bits)
631 $ev = DB_DAtaObject::Factory('events');
632 if (!$ev->get($bits[1])) {
633 die("could not find event id");
635 // technically same user only.. -- normally www-data..
636 if (function_exists('posix_getpwuid')) {
637 $uinfo = posix_getpwuid( posix_getuid () );
638 $user = $uinfo['name'];
640 $user = getenv('USERNAME'); // windows.
642 $ff = HTML_FlexyFramework::get();
644 $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
646 if(!$file || !file_exists($file)){
647 die("file was not saved");
650 $filesJ = json_decode(file_get_contents($file));
652 foreach($filesJ->FILES as $k=>$f){
653 if ($f->tmp_name != $bits[2]) {
657 $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
659 if (!$src || !file_exists($src)) {
660 die("file was not saved");
662 header ('Content-Type: ' . $f->type);
664 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );