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);
308 $x->convert( $this->as_mimetype);
309 $x->serve($this->method);
312 //echo "SKALING? $this->size";
313 // acutally if we generated the image, then we do not need to validate the size..
315 // if the mimetype is not converted..
316 // then the filename should be original.{size}.jpeg
317 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
319 if($img->mimetype == 'image/gif'){
320 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
323 if (!file_exists($fn)) {
324 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
325 // if it's an image, convert into the same type for thumbnail..
326 if (preg_match('#^image/#', $img->mimetype)) {
327 $this->as_mimetype = $img->mimetype;
331 if (!file_exists($fn)) {
332 $this->validateSize();
335 if(!empty($this->page) && !is_nan($this->page * 1)){
336 $x->convert( $this->as_mimetype, $this->size, 0, $this->page);
338 $x->convert( $this->as_mimetype, $this->size);
348 function validateSize()
350 if($this->is_local) {
354 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
355 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
360 $ff = HTML_FlexyFramework::get();
362 $sizes= $this->sizes;
364 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
365 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
367 if (!empty($cfg['sizes'])) {
368 $sizes = array_merge($sizes , $cfg['sizes']);
371 $project = $ff->project;
373 require_once $ff->project . '.php';
375 $project = str_replace('/', '_', $project);
377 $pr_obj = new $project;
379 // var_dump($pr_obj->Pman_Core_Images_Size);
380 if(isset($pr_obj->Pman_Core_Images_Size)){
381 $sizes = $pr_obj->Pman_Core_Images_Size;
386 if (!in_array($this->size, $sizes)) {
387 die("invalid scale - ".$this->size);
393 * The idea of this code was to replace urls for images when you have an admin
394 * and a distribution page. with different urls.
396 * it may be usefull later if things like embedded images in emails. but
397 * I think it's proably better not to use this.
399 * The key problem being how to determine if we are replacing 'our' images or some external one..
405 static function replaceImageURLS($html, $obj = false)
408 $ff = HTML_FlexyFramework::get();
409 if (!isset($ff->Pman_Images['public_baseURL'])) {
412 //var_dump($ff->Pman_Images['public_baseURL']);
413 $baseURL = $ff->Pman_Images['public_baseURL'];
415 libxml_use_internal_errors(true);
416 $dom = new DOMDocument();
417 $dom->loadHTML("<?xml encoding='utf-8'?> <div id='tmp_dom_wrapper'>{$html}</div>");
418 $imgs = $dom->getElementsByTagName('img');
421 foreach($imgs as $img) {
422 $src = $img->getAttribute('src');
423 if (!$src|| !strlen(trim($src))) {
427 if (0 === strpos($src, 'data:')) {
429 HTML_FlexyFramework::get()->page->jerr("no object to attach data url");
432 self::replaceDataUrl($baseURL, $img, $obj);
437 if (false !== strpos($src, '//') && false === strpos($src, $baseURL)) {
438 // contains an absolute path.. and not our baseURL.
442 $img->setAttribute('src', self::domImgUrl($baseURL, $img));
444 // what about mailto or data... - just ignore?? for images...
449 $anchors = $dom->getElementsByTagName('a');
451 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
453 $matches = array_unique($result[0]);
454 foreach($anchors as $anc) {
455 $href = $anc->getAttribute('href');
456 if (!empty($href) || 0 !== strpos($href, $baseURL)) {
459 $anc->setAttribute('href', self::domImgUrl($baseURL, $href));
463 $inner = $dom->getElementById("tmp_dom_wrapper");
465 foreach ($inner->childNodes as $child) {
466 $html .= ($dom->saveHTML($child));
471 static function domImgUrl($baseURL, $dom)
474 if (!is_string($url)) {
475 $url = $dom->getAttribute('src');
478 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $url, $umatch)) {
484 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
485 $hh = explode('#',$umatch[3]);
486 $hash = '#'. array_pop($hh);
490 $img = DB_DataObject::factory('Images');
491 if (!$img->get($id)) {
494 $type = explode('/', $umatch[1]);
497 if (count($type) > 2 && $type[1] == 'Thumb') {
498 $thumbsize = $type[2];
499 $provider = '/Images/Thumb';
501 $provider = '/'.$umatch[1];
504 $w = is_string($dom) ? false : $dom->getAttribute('width');
505 $h = is_string($dom) ? false : $dom->getAttribute('width');
507 if (!is_string($dom) && (!empty($w) || !empty($h)) )
509 // no support for %...
511 (empty($w) ? '0' : $w * 1) .
513 (empty($h) ? '0' : $h * 1);
514 $provider = '/Images/Thumb';
518 if ($thumbsize !== -1) {
520 // need to regenerate it..
522 $type = array('Images', 'Thumb', $thumbsize);
524 $fc = $img->toFileConvert();
525 // make sure it's available..
526 $fc->convert($img->mimetype, $thumbsize);
530 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
534 // finally replace the original TAG with the new version..
536 return $img->URL($thumbsize, $provider, $baseURL) . $hash ;
541 static function replaceDataUrl($baseURL, $img, $obj)
543 $d = DB_DataObject::Factory('Images');
547 $d->createFromData($img->getAttribute('src'));
548 $img->setAttribute('src', $d->URL(-1, '/Images' , $baseURL));
551 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
555 // see if it's an image url..
556 // Images/{ID}/fullname.xxxx
557 // Images/Thumb/200/{ID}/fullname.xxxx
558 // Images/Download/{ID}/fullname.xxxx
560 $attr_url = $attr[$attr_name];
562 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
568 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
569 $hh = explode('#',$umatch[3]);
570 $hash = '#'. array_pop($hh);
574 $img = DB_DataObject::factory('Images');
575 if (!$img->get($id)) {
578 $type = explode('/', $umatch[1]);
581 if (count($type) > 2 && $type[1] == 'Thumb') {
582 $thumbsize = $type[2];
583 $provider = '/Images/Thumb';
585 $provider = '/'.$umatch[1];
588 if (!empty($attr['width']) || !empty($attr['height']) )
590 // no support for %...
592 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
594 (empty($attr['height']) ? '0' : $attr['height'] * 1);
595 $provider = '/Images/Thumb';
599 if ($thumbsize !== -1) {
601 // need to regenerate it..
603 $type = array('Images', 'Thumb', $thumbsize);
605 $fc = $img->toFileConvert();
606 // make sure it's available..
607 $fc->convert($img->mimetype, $thumbsize);
611 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
615 // finally replace the original TAG with the new version..
617 $new_tag = str_replace(
618 $attr_name. '="'. $attr_url . '"',
619 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
624 return str_replace($tag, $new_tag, $html);
628 function downloadEvent($bits)
630 $ev = DB_DAtaObject::Factory('events');
631 if (!$ev->get($bits[1])) {
632 die("could not find event id");
634 // technically same user only.. -- normally www-data..
635 if (function_exists('posix_getpwuid')) {
636 $uinfo = posix_getpwuid( posix_getuid () );
637 $user = $uinfo['name'];
639 $user = getenv('USERNAME'); // windows.
641 $ff = HTML_FlexyFramework::get();
643 $file = $ev->logDir() . date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
645 if(!$file || !file_exists($file)){
646 die("file was not saved");
649 $filesJ = json_decode(file_get_contents($file));
651 foreach($filesJ->FILES as $k=>$f){
652 if ($f->tmp_name != $bits[2]) {
656 $src = $file = $ev->logDir() . date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
658 if (!$src || !file_exists($src)) {
659 die("file was not saved");
661 header ('Content-Type: ' . $f->type);
663 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );