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
42 parent::getAuth(); // load company!
44 $au = $this->getAuthUser();
47 $this->authUser = false;
48 return true;//die("Access denied");
51 $this->authUser = $au;
56 var $as_mimetype = false;
57 var $method = 'inline';
59 function get($s, $opts=array()) // determin what to serve!!!!
62 //if (!empty($_GET['_post'])) {
63 // return $this->post();
66 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
68 $bits= explode('/', $s);
70 // var_dump($bits);die('in');
71 // without id as first part...
72 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
74 $this->as_mimetype = 'image/jpeg';
75 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
76 $id = empty($bits[2]) ? 0 : $bits[2];
78 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
79 $this->method = 'attachment';
80 $id = empty($bits[1]) ? 0 : $bits[1];
82 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
84 $this->as_mimetype = 'image/jpeg';
85 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
86 $id = empty($bits[3]) ? 0 : $bits[3];
88 } else if (!empty($bits[0]) && $bits[0] == 'events') {
89 if (!$this->authUser) {
90 $this->imgErr("no-authentication-events",$s);
92 $this->downloadEvent($bits);
93 $this->imgErr("unknown file",$s);
98 $id = empty($bits[0]) ? 0 : $bits[0];
101 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
103 if (!$this->authUser) {
104 $this->imgErr("not-authenticated-using-colon-format",$s);
108 $onbits = explode(':', $id);
109 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
110 $this->imgErr("bad-url",$s);
113 //DB_DataObject::debugLevel(1);
114 $img = DB_DataObject::factory('Images');
115 $img->ontable = $onbits[0];
116 $img->onid = $onbits[1];
117 if (empty($_REQUEST['anytype'])) {
118 $img->whereAdd("mimetype like 'image/%'");
120 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
121 if (isset($onbits[2])) {
122 $img->imgtype = $onbits[2];
125 if (!$img->find(true)) {
126 $this->imgErr("no images for that item: " . htmlspecialchars($id),$s);
136 // depreciated - should use ontable:onid:type here...
137 if (!empty($_REQUEST['ontable'])) {
139 if (!$this->authUser) {
140 die("authentication required");
143 //DB_DataObjecT::debugLevel(1);
144 $img = DB_DataObject::factory('Images');
145 $img->setFrom($_REQUEST);
150 if (!$img->find(true)) {
151 $this->imgErr("No file exists",$s);
159 $img = DB_DataObjecT::factory('Images');
161 if (!$id || !$img->get($id)) {
162 $this->imgErr("image has been removed or deleted.",$s);
165 if (!$this->authUser) {
167 if ($img->ontable != 'core_company') {
168 $this->imgErr("not-authenticated",$s);
170 if ($img->imgtype != 'LOGO') {
171 $this->imgErr("not-logo",$s);
173 $comp = $img->object();
174 if ($comp->comptype != 'OWNER') {
175 $this->imgErr("not-owner-company",$s);
177 return $this->serve($img);
183 if(!$this->hasPermission($img)){
184 $this->imgErr("access to this image/file has been denied.",$s);
192 function imgErr($reason,$path) {
193 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
194 urlencode($reason) .'&path='.urlencode($path));
198 function hasPermission($img)
206 if (!$this->authUser) {
207 $this->jerr("image conversion only allowed by registered users");
209 // converts a posted string (eg.svg)
210 // into another type..
211 if (empty($_REQUEST['as'])) {
212 $this->jerr("missing target type");
214 if (empty($_REQUEST['mimetype'])) {
215 $this->jerr("missing mimetype");
217 if (empty($_REQUEST['data'])) {
218 $this->jerr("missing data");
222 $this->as_mimetype = $_REQUEST['as'];
223 $this->mimetype = $_REQUEST['mimetype'];
224 require_once 'File/MimeType.php';
225 $y = new File_MimeType();
226 $src_ext = $y->toExt( $this->mimetype );
229 $tmp = $this->tempName($src_ext);
230 file_put_contents($tmp, $_REQUEST['data']);
232 require_once 'File/Convert.php';
233 $cv = new File_Convert($tmp, $this->mimetype);
237 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
238 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
240 if (!empty($_REQUEST['as_data'])) {
241 $this->jok(base64_encode(file_get_contents($fn)));
244 $cv->serve('attachment');
255 $this->sessionState(0); // turn off session... - locking...
257 require_once 'File/Convert.php';
258 if (!file_exists($img->getStoreName())) {
259 // print_r($img);exit;
260 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
261 urlencode("Original file was missing : " . $img->getStoreName()));
264 // print_r($img);exit;
265 $x = $img->toFileConvert();
266 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
267 $this->as_mimetype = $img->mimetype;
270 $x->convert( $this->as_mimetype);
271 $x->serve($this->method);
274 //echo "SKALING? $this->size";
275 // acutally if we generated the image, then we do not need to validate the size..
277 // if the mimetype is not converted..
278 // then the filename should be original.{size}.jpeg
279 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
281 if($img->mimetype == 'image/gif'){
282 $fn = $img->getStoreName() . '.'. $this->size . '.gif';
285 if (!file_exists($fn)) {
286 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
287 // if it's an image, convert into the same type for thumbnail..
288 if (preg_match('#^image/#', $img->mimetype)) {
289 $this->as_mimetype = $img->mimetype;
293 if (!file_exists($fn)) {
294 $this->validateSize();
297 $x->convert( $this->as_mimetype, $this->size);
305 function validateSize()
307 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER')
308 || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
313 $ff = HTML_FlexyFramework::get();
328 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
329 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
331 if (!empty($cfg['sizes'])) {
332 $sizes = array_merge($sizes , $cfg['sizes']);
335 $project = $ff->project;
337 require_once $ff->project . '.php';
339 $project = str_replace('/', '_', $project);
341 $pr_obj = new $project;
343 // var_dump($pr_obj->Pman_Core_Images_Size);
344 if(isset($pr_obj->Pman_Core_Images_Size)){
345 $sizes = $pr_obj->Pman_Core_Images_Size;
350 if (!in_array($this->size, $sizes)) {
351 die("invalid scale - ".$this->size);
357 * The idea of this code was to replace urls for images when you have an admin
358 * and a distribution page. with different urls.
360 * it may be usefull later if things like embedded images in emails. but
361 * I think it's proably better not to use this.
363 * The key problem being how to determine if we are replacing 'our' images or some external one..
369 static function replaceImageURLS($html)
372 $ff = HTML_FlexyFramework::get();
373 if (!isset($ff->Pman_Images['public_baseURL'])) {
376 //var_dump($ff->Pman_Images['public_baseURL']);
377 $baseURL = $ff->Pman_Images['public_baseURL'];
379 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
381 $matches = array_unique($result[0]);
382 foreach($matches as $img) {
384 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
388 foreach($imatch[1] as $i=>$key) {
389 $attr[$key] = $imatch[2][$i];
391 // does it contain baseURL??? --- well what about relative paths...
394 if (empty($attr['src'])) {
397 if (0 !== strpos($attr['src'], $baseURL)) {
398 // it starts with our 'new' baseURL?
399 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
402 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
403 // contains an absolute path.. that is probably not us...
406 // what about mailto or data... - just ignore?? for images...
408 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
414 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
416 $matches = array_unique($result[0]);
417 foreach($matches as $img) {
419 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
423 foreach($imatch[1] as $i=>$key) {
424 $attr[$key] = $imatch[2][$i];
426 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
429 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
434 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
438 // see if it's an image url..
439 // Images/{ID}/fullname.xxxx
440 // Images/Thumb/200/{ID}/fullname.xxxx
441 // Images/Download/{ID}/fullname.xxxx
443 $attr_url = $attr[$attr_name];
445 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
451 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
452 $hash = '#'. array_pop(explode('#',$umatch[3]));
456 $img = DB_DataObject::factory('Images');
457 if (!$img->get($id)) {
460 $type = explode('/', $umatch[1]);
463 if (count($type) > 2 && $type[1] == 'Thumb') {
464 $thumbsize = $type[2];
465 $provider = '/Images/Thumb';
467 $provider = '/'.$umatch[1];
470 if (!empty($attr['width']) || !empty($attr['height']) )
472 // no support for %...
474 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
476 (empty($attr['height']) ? '0' : $attr['height'] * 1);
477 $provider = '/Images/Thumb';
481 if ($thumbsize !== -1) {
483 // need to regenerate it..
485 $type = array('Images', 'Thumb', $thumbsize);
487 $fc = $img->toFileConvert();
488 // make sure it's available..
489 $fc->convert($img->mimetype, $thumbsize);
493 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
497 // finally replace the original TAG with the new version..
499 $new_tag = str_replace(
500 $attr_name. '="'. $attr_url . '"',
501 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
506 return str_replace($tag, $new_tag, $html);
510 function downloadEvent($bits)
512 $popts = PEAR::getStaticProperty('Pman','options');
513 $ev = DB_DAtaObject::Factory('events');
514 if (!$ev->get($bits[1])) {
515 die("could not find event id");
517 // technically same user only.. -- normally www-data..
518 if (function_exists('posix_getpwuid')) {
519 $uinfo = posix_getpwuid( posix_getuid () );
520 $user = $uinfo['name'];
522 $user = getenv('USERNAME'); // windows.
524 $ff = HTML_FlexyFramework::get();
525 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
526 $filesJ = json_decode(file_get_contents($file));
530 foreach($filesJ->FILES as $k=>$f){
531 if ($f->tmp_name != $bits[2]) {
535 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
536 if (!file_exists($src)) {
537 die("file was not saved");
539 header ('Content-Type: ' . $f->type);
541 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );