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 $this->is_local = (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') ? true : false;
91 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
93 $this->page = empty($_REQUEST['page']) ? false : (int) $_REQUEST['page'];
95 $bits= explode('/', $s);
97 // var_dump($bits);die('in');
98 // without id as first part...
99 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
101 $this->as_mimetype = 'image/jpeg';
102 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
103 $id = empty($bits[2]) ? 0 : $bits[2];
105 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
106 $this->method = 'attachment';
107 $id = empty($bits[1]) ? 0 : $bits[1];
109 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
111 $this->as_mimetype = 'image/jpeg';
112 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
113 $id = empty($bits[3]) ? 0 : $bits[3];
115 } else if (!empty($bits[0]) && $bits[0] == 'events') {
116 if (!$this->authUser) {
117 $this->imgErr("no-authentication-events",$s);
119 $this->downloadEvent($bits);
120 $this->imgErr("unknown file",$s);
125 $id = empty($bits[0]) ? 0 : $bits[0];
128 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
130 if (!$this->authUser) {
131 $this->imgErr("not-authenticated-using-colon-format",$s);
135 $onbits = explode(':', $id);
136 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
137 $this->imgErr("bad-url",$s);
140 //DB_DataObject::debugLevel(1);
141 $img = DB_DataObject::factory('Images');
142 $img->ontable = $onbits[0];
143 $img->onid = $onbits[1];
144 if (empty($_REQUEST['anytype'])) {
145 $img->whereAdd("mimetype like 'image/%'");
147 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
148 if (isset($onbits[2])) {
149 $img->imgtype = $onbits[2];
152 if (!$img->find(true)) {
153 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
163 // depreciated - should use ontable:onid:type here...
164 if (!empty($_REQUEST['ontable'])) {
166 if (!$this->authUser) {
167 die("authentication required");
170 //DB_DataObjecT::debugLevel(1);
171 $img = DB_DataObject::factory('Images');
172 $img->setFrom($_REQUEST);
177 if (!$img->find(true)) {
178 $this->imgErr("No file exists",$s);
184 $img = DB_DataObjecT::factory('Images');
186 if (!$id || !$img->get($id)) {
187 $this->imgErr("image has been removed or deleted.",$s);
190 if($this->is_local) {
191 return $this->serve($img);
194 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
196 if ($img->ontable != 'core_company') {
197 $this->imgErr("not-authenticated {$img->ontable}",$s);
199 if ($img->imgtype != 'LOGO') {
200 $this->imgErr("not-logo",$s);
202 $comp = $img->object();
203 if ($comp->comptype != 'OWNER') {
204 $this->imgErr("not-owner-company",$s);
207 return $this->serve($img);
211 if(!$this->hasPermission($img)){
212 $this->imgErr("access to this image/file has been denied.",$s);
219 function imgErr($reason,$path) {
220 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
221 urlencode($reason) .'&path='.urlencode($path));
225 function hasPermission($img)
232 if (!empty($_REQUEST['_get'])) {
233 return $this->get($v);
236 if (!$this->authUser) {
237 $this->jerr("image conversion only allowed by registered users");
239 // converts a posted string (eg.svg)
240 // into another type..
241 if (empty($_REQUEST['as'])) {
242 $this->jerr("missing target type");
244 if (empty($_REQUEST['mimetype'])) {
245 $this->jerr("missing mimetype");
247 if (empty($_REQUEST['data'])) {
248 $this->jerr("missing data");
252 $this->as_mimetype = $_REQUEST['as'];
253 $this->mimetype = $_REQUEST['mimetype'];
254 require_once 'File/MimeType.php';
255 $y = new File_MimeType();
256 $src_ext = $y->toExt( $this->mimetype );
259 $tmp = $this->tempName($src_ext);
260 file_put_contents($tmp, $_REQUEST['data']);
262 require_once 'File/Convert.php';
263 $cv = new File_Convert($tmp, $this->mimetype);
267 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
268 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
270 if (!empty($_REQUEST['as_data'])) {
271 $this->jok(base64_encode(file_get_contents($fn)));
274 $cv->serve('attachment');
285 $this->sessionState(0); // turn off session... - locking...
287 require_once 'File/Convert.php';
288 if (!file_exists($img->getStoreName())) {
289 // print_r($img);exit;
290 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
291 urlencode("Original file was missing : " . $img->getStoreName()));
294 // print_r($img);exit;
295 $x = $img->toFileConvert();
296 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
297 $this->as_mimetype = $img->mimetype;
300 if ($x->mimetype == $this->as_mimetype) {
301 $x->serveOnly($this->method);
304 $x->convert( $this->as_mimetype);
305 $x->serve($this->method);
308 //echo "SKALING? $this->size";
309 // acutally if we generated the image, then we do not need to validate the size..
311 // if the mimetype is not converted..
312 // then the filename should be original.{size}.jpeg
313 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
315 if($img->mimetype == 'image/gif'){
316 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
319 if (!file_exists($fn)) {
320 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
321 // if it's an image, convert into the same type for thumbnail..
322 if (preg_match('#^image/#', $img->mimetype)) {
323 $this->as_mimetype = $img->mimetype;
327 if (!file_exists($fn)) {
328 $this->validateSize();
331 if(!empty($this->page) && !is_nan($this->page * 1)){
332 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
334 $x->convert( $this->as_mimetype, $this->size);
344 function validateSize()
346 if($this->is_local) {
350 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
351 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
356 $ff = HTML_FlexyFramework::get();
358 $sizes= $this->sizes;
360 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
361 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
363 if (!empty($cfg['sizes'])) {
364 $sizes = array_merge($sizes , $cfg['sizes']);
367 $project = $ff->project;
369 require_once $ff->project . '.php';
371 $project = str_replace('/', '_', $project);
373 $pr_obj = new $project;
375 // var_dump($pr_obj->Pman_Core_Images_Size);
376 if(isset($pr_obj->Pman_Core_Images_Size)){
377 $sizes = $pr_obj->Pman_Core_Images_Size;
382 if (!in_array($this->size, $sizes)) {
383 die("invalid scale - ".$this->size);
389 * The idea of this code was to replace urls for images when you have an admin
390 * and a distribution page. with different urls.
392 * it may be usefull later if things like embedded images in emails. but
393 * I think it's proably better not to use this.
395 * The key problem being how to determine if we are replacing 'our' images or some external one..
401 static function replaceImageURLS($html, $obj = false)
404 $ff = HTML_FlexyFramework::get();
405 if (!isset($ff->Pman_Images['public_baseURL'])) {
408 //var_dump($ff->Pman_Images['public_baseURL']);
409 $baseURL = $ff->Pman_Images['public_baseURL'];
411 libxml_use_internal_errors(true);
412 $dom = new DOMDocument();
413 $dom->loadHTML("<?xml encoding='utf-8'?> <div id='tmp_dom_wrapper'>{$html}</div>");
414 $imgs = $dom->getElementsByTagName('img');
417 foreach($imgs as $img) {
418 $src = $img->getAttribute('src');
419 if (!$src|| !strlen(trim($src))) {
423 if (0 === strpos($src, 'data:')) {
425 HTML_FlexyFramework::get()->page->jerr("no object to attach data url");
428 self::replaceDataUrl($baseURL, $img, $obj);
433 if (false !== strpos($src, '//') && false === strpos($src, $baseURL)) {
434 // contains an absolute path.. and not our baseURL.
438 $img->setAttribute('src', self::domImgUrl($baseURL, $img));
440 // what about mailto or data... - just ignore?? for images...
445 $anchors = $dom->getElementsByTagName('a');
447 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
449 $matches = array_unique($result[0]);
450 foreach($anchors as $anc) {
451 $href = $anc->getAttribute('href');
452 if (!empty($href) || 0 !== strpos($href, $baseURL)) {
455 $anc->setAttribute('href', self::domImgUrl($baseURL, $href));
459 $inner = $dom->getElementById("tmp_dom_wrapper");
461 foreach ($inner->childNodes as $child) {
462 $html .= ($dom->saveHTML($child));
467 static function domImgUrl($baseURL, $dom)
470 if (!is_string($url)) {
471 $url = $dom->getAttribute('src');
474 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $url, $umatch)) {
480 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
481 $hh = explode('#',$umatch[3]);
482 $hash = '#'. array_pop($hh);
486 $img = DB_DataObject::factory('Images');
487 if (!$img->get($id)) {
490 $type = explode('/', $umatch[1]);
493 if (count($type) > 2 && $type[1] == 'Thumb') {
494 $thumbsize = $type[2];
495 $provider = '/Images/Thumb';
497 $provider = '/'.$umatch[1];
500 $w = is_string($dom) ? false : $dom->getAttribute('width');
501 $h = is_string($dom) ? false : $dom->getAttribute('width');
503 if (!is_string($dom) && (!empty($w) || !empty($h)) )
505 // no support for %...
507 (empty($w) ? '0' : $w * 1) .
509 (empty($h) ? '0' : $h * 1);
510 $provider = '/Images/Thumb';
514 if ($thumbsize !== -1) {
516 // need to regenerate it..
518 $type = array('Images', 'Thumb', $thumbsize);
520 $fc = $img->toFileConvert();
521 // make sure it's available..
522 $fc->convert($img->mimetype, $thumbsize);
526 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
530 // finally replace the original TAG with the new version..
532 return $img->URL($thumbsize, $provider, $baseURL) . $hash ;
537 static function replaceDataUrl($baseURL, $img, $obj)
539 $d = DB_DataObject::Factory('Images');
543 $d->createFromData($img->getAttribute('src'));
544 $img->setAttribute('src', $d->URL(-1, '/Images' , $baseURL));
547 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
551 // see if it's an image url..
552 // Images/{ID}/fullname.xxxx
553 // Images/Thumb/200/{ID}/fullname.xxxx
554 // Images/Download/{ID}/fullname.xxxx
556 $attr_url = $attr[$attr_name];
558 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
564 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
565 $hh = explode('#',$umatch[3]);
566 $hash = '#'. array_pop($hh);
570 $img = DB_DataObject::factory('Images');
571 if (!$img->get($id)) {
574 $type = explode('/', $umatch[1]);
577 if (count($type) > 2 && $type[1] == 'Thumb') {
578 $thumbsize = $type[2];
579 $provider = '/Images/Thumb';
581 $provider = '/'.$umatch[1];
584 if (!empty($attr['width']) || !empty($attr['height']) )
586 // no support for %...
588 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
590 (empty($attr['height']) ? '0' : $attr['height'] * 1);
591 $provider = '/Images/Thumb';
595 if ($thumbsize !== -1) {
597 // need to regenerate it..
599 $type = array('Images', 'Thumb', $thumbsize);
601 $fc = $img->toFileConvert();
602 // make sure it's available..
603 $fc->convert($img->mimetype, $thumbsize);
607 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
611 // finally replace the original TAG with the new version..
613 $new_tag = str_replace(
614 $attr_name. '="'. $attr_url . '"',
615 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
620 return str_replace($tag, $new_tag, $html);
624 function downloadEvent($bits)
626 $ev = DB_DAtaObject::Factory('events');
627 if (!$ev->get($bits[1])) {
628 die("could not find event id");
630 // technically same user only.. -- normally www-data..
631 if (function_exists('posix_getpwuid')) {
632 $uinfo = posix_getpwuid( posix_getuid () );
633 $user = $uinfo['name'];
635 $user = getenv('USERNAME'); // windows.
637 $ff = HTML_FlexyFramework::get();
639 $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
641 if(!$file || !file_exists($file)){
642 die("file was not saved");
645 $filesJ = json_decode(file_get_contents($file));
647 foreach($filesJ->FILES as $k=>$f){
648 if ($f->tmp_name != $bits[2]) {
652 $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
654 if (!$src || !file_exists($src)) {
655 die("file was not saved");
657 header ('Content-Type: ' . $f->type);
659 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );