3 * Deal with image delivery and HTML replacement of image links in body text.
5 * $str = Pman_Core_Images::replaceImg($str); // < use with HTML
9 * Deliver image /file etc..
13 * args: ontable request
14 * ontable (req) tablename.
17 * as (serve as a type) = eg. ?as=audio/mpeg
20 * as :(serve as a type) = eg. mimetype.
22 * Images/{ID}/fullname.xxxx
24 * (valid thumbs 200, 400)...?
25 * Images/Thumb/200/{ID}/fullname.xxxx
26 * Images/Download/{ID}/fullname.xxxx
31 * Used to be in Base... now in core..
34 * view permission should be required on the underlying object...
37 require_once 'Pman.php';
38 class Pman_Core_Images extends Pman
41 var $public_image_table = array();
45 parent::getAuth(); // load company!
47 $au = $this->getAuthUser();
50 $this->authUser = false;
51 return true;//die("Access denied");
54 $this->authUser = $au;
59 var $as_mimetype = false;
60 var $method = 'inline';
62 function get($s, $opts=array()) // determin what to serve!!!!
65 //if (!empty($_GET['_post'])) {
66 // return $this->post();
69 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
71 $bits= explode('/', $s);
73 // var_dump($bits);die('in');
74 // without id as first part...
75 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
77 $this->as_mimetype = 'image/jpeg';
78 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
79 $id = empty($bits[2]) ? 0 : $bits[2];
81 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
82 $this->method = 'attachment';
83 $id = empty($bits[1]) ? 0 : $bits[1];
85 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
87 $this->as_mimetype = 'image/jpeg';
88 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
89 $id = empty($bits[3]) ? 0 : $bits[3];
91 } else if (!empty($bits[0]) && $bits[0] == 'events') {
92 if (!$this->authUser) {
93 $this->imgErr("no-authentication-events",$s);
95 $this->downloadEvent($bits);
96 $this->imgErr("unknown file",$s);
101 $id = empty($bits[0]) ? 0 : $bits[0];
104 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
106 if (!$this->authUser) {
107 $this->imgErr("not-authenticated-using-colon-format",$s);
111 $onbits = explode(':', $id);
112 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
113 $this->imgErr("bad-url",$s);
116 //DB_DataObject::debugLevel(1);
117 $img = DB_DataObject::factory('Images');
118 $img->ontable = $onbits[0];
119 $img->onid = $onbits[1];
120 if (empty($_REQUEST['anytype'])) {
121 $img->whereAdd("mimetype like 'image/%'");
123 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
124 if (isset($onbits[2])) {
125 $img->imgtype = $onbits[2];
128 if (!$img->find(true)) {
129 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
139 // depreciated - should use ontable:onid:type here...
140 if (!empty($_REQUEST['ontable'])) {
142 if (!$this->authUser) {
143 die("authentication required");
146 //DB_DataObjecT::debugLevel(1);
147 $img = DB_DataObject::factory('Images');
148 $img->setFrom($_REQUEST);
153 if (!$img->find(true)) {
154 $this->imgErr("No file exists",$s);
162 $img = DB_DataObjecT::factory('Images');
164 if (!$id || !$img->get($id)) {
165 $this->imgErr("image has been removed or deleted.",$s);
168 if (!$this->authUser && !in_array($img->ontable,$this->public_image_tables)) {
170 if ($img->ontable != 'core_company') {
171 $this->imgErr("not-authenticated {$img->ontable}",$s);
173 if ($img->imgtype != 'LOGO') {
174 $this->imgErr("not-logo",$s);
176 $comp = $img->object();
177 if ($comp->comptype != 'OWNER') {
178 $this->imgErr("not-owner-company",$s);
180 return $this->serve($img);
186 if(!$this->hasPermission($img)){
187 $this->imgErr("access to this image/file has been denied.",$s);
195 function imgErr($reason,$path) {
196 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
197 urlencode($reason) .'&path='.urlencode($path));
201 function hasPermission($img)
209 if (!$this->authUser) {
210 $this->jerr("image conversion only allowed by registered users");
212 // converts a posted string (eg.svg)
213 // into another type..
214 if (empty($_REQUEST['as'])) {
215 $this->jerr("missing target type");
217 if (empty($_REQUEST['mimetype'])) {
218 $this->jerr("missing mimetype");
220 if (empty($_REQUEST['data'])) {
221 $this->jerr("missing data");
225 $this->as_mimetype = $_REQUEST['as'];
226 $this->mimetype = $_REQUEST['mimetype'];
227 require_once 'File/MimeType.php';
228 $y = new File_MimeType();
229 $src_ext = $y->toExt( $this->mimetype );
232 $tmp = $this->tempName($src_ext);
233 file_put_contents($tmp, $_REQUEST['data']);
235 require_once 'File/Convert.php';
236 $cv = new File_Convert($tmp, $this->mimetype);
240 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
241 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
243 if (!empty($_REQUEST['as_data'])) {
244 $this->jok(base64_encode(file_get_contents($fn)));
247 $cv->serve('attachment');
258 $this->sessionState(0); // turn off session... - locking...
260 require_once 'File/Convert.php';
261 if (!file_exists($img->getStoreName())) {
262 // print_r($img);exit;
263 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
264 urlencode("Original file was missing : " . $img->getStoreName()));
267 // print_r($img);exit;
268 $x = $img->toFileConvert();
269 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
270 $this->as_mimetype = $img->mimetype;
273 $x->convert( $this->as_mimetype);
274 $x->serve($this->method);
277 //echo "SKALING? $this->size";
278 // acutally if we generated the image, then we do not need to validate the size..
280 // if the mimetype is not converted..
281 // then the filename should be original.{size}.jpeg
282 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
284 if($img->mimetype == 'image/gif'){
285 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
288 if (!file_exists($fn)) {
289 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
290 // if it's an image, convert into the same type for thumbnail..
291 if (preg_match('#^image/#', $img->mimetype)) {
292 $this->as_mimetype = $img->mimetype;
296 if (!file_exists($fn)) {
297 $this->validateSize();
300 $x->convert( $this->as_mimetype, $this->size);
308 function validateSize()
310 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
311 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
316 $ff = HTML_FlexyFramework::get();
331 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
332 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
334 if (!empty($cfg['sizes'])) {
335 $sizes = array_merge($sizes , $cfg['sizes']);
338 $project = $ff->project;
340 require_once $ff->project . '.php';
342 $project = str_replace('/', '_', $project);
344 $pr_obj = new $project;
346 // var_dump($pr_obj->Pman_Core_Images_Size);
347 if(isset($pr_obj->Pman_Core_Images_Size)){
348 $sizes = $pr_obj->Pman_Core_Images_Size;
353 if (!in_array($this->size, $sizes)) {
354 die("invalid scale - ".$this->size);
360 * The idea of this code was to replace urls for images when you have an admin
361 * and a distribution page. with different urls.
363 * it may be usefull later if things like embedded images in emails. but
364 * I think it's proably better not to use this.
366 * The key problem being how to determine if we are replacing 'our' images or some external one..
372 static function replaceImageURLS($html)
375 $ff = HTML_FlexyFramework::get();
376 if (!isset($ff->Pman_Images['public_baseURL'])) {
379 //var_dump($ff->Pman_Images['public_baseURL']);
380 $baseURL = $ff->Pman_Images['public_baseURL'];
382 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
384 $matches = array_unique($result[0]);
385 foreach($matches as $img) {
387 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
391 foreach($imatch[1] as $i=>$key) {
392 $attr[$key] = $imatch[2][$i];
394 // does it contain baseURL??? --- well what about relative paths...
397 if (empty($attr['src'])) {
400 if (0 !== strpos($attr['src'], $baseURL)) {
401 // it starts with our 'new' baseURL?
402 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
405 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
406 // contains an absolute path.. that is probably not us...
409 // what about mailto or data... - just ignore?? for images...
411 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
417 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
419 $matches = array_unique($result[0]);
420 foreach($matches as $img) {
422 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
426 foreach($imatch[1] as $i=>$key) {
427 $attr[$key] = $imatch[2][$i];
429 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
432 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
437 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
441 // see if it's an image url..
442 // Images/{ID}/fullname.xxxx
443 // Images/Thumb/200/{ID}/fullname.xxxx
444 // Images/Download/{ID}/fullname.xxxx
446 $attr_url = $attr[$attr_name];
448 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
454 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
455 $hash = '#'. array_pop(explode('#',$umatch[3]));
459 $img = DB_DataObject::factory('Images');
460 if (!$img->get($id)) {
463 $type = explode('/', $umatch[1]);
466 if (count($type) > 2 && $type[1] == 'Thumb') {
467 $thumbsize = $type[2];
468 $provider = '/Images/Thumb';
470 $provider = '/'.$umatch[1];
473 if (!empty($attr['width']) || !empty($attr['height']) )
475 // no support for %...
477 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
479 (empty($attr['height']) ? '0' : $attr['height'] * 1);
480 $provider = '/Images/Thumb';
484 if ($thumbsize !== -1) {
486 // need to regenerate it..
488 $type = array('Images', 'Thumb', $thumbsize);
490 $fc = $img->toFileConvert();
491 // make sure it's available..
492 $fc->convert($img->mimetype, $thumbsize);
496 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
500 // finally replace the original TAG with the new version..
502 $new_tag = str_replace(
503 $attr_name. '="'. $attr_url . '"',
504 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
509 return str_replace($tag, $new_tag, $html);
513 function downloadEvent($bits)
515 $popts = PEAR::getStaticProperty('Pman','options');
516 $ev = DB_DAtaObject::Factory('events');
517 if (!$ev->get($bits[1])) {
518 die("could not find event id");
520 // technically same user only.. -- normally www-data..
521 if (function_exists('posix_getpwuid')) {
522 $uinfo = posix_getpwuid( posix_getuid () );
523 $user = $uinfo['name'];
525 $user = getenv('USERNAME'); // windows.
527 $ff = HTML_FlexyFramework::get();
528 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
529 $filesJ = json_decode(file_get_contents($file));
533 foreach($filesJ->FILES as $k=>$f){
534 if ($f->tmp_name != $bits[2]) {
538 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
539 if (!file_exists($src)) {
540 die("file was not saved");
542 header ('Content-Type: ' . $f->type);
544 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );