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();
50 $this->authUser = $au;
55 var $as_mimetype = false;
56 var $method = 'inline';
58 function get($s) // 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') {
90 $this->downloadEvent($bits);
92 die ("unknown file?");
96 $id = empty($bits[0]) ? 0 : $bits[0];
99 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
100 $onbits = explode(':', $id);
101 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
104 //DB_DataObject::debugLevel(1);
105 $img = DB_DataObject::factory('Images');
106 $img->ontable = $onbits[0];
107 $img->onid = $onbits[1];
108 if (empty($_REQUEST['anytype'])) {
109 $img->whereAdd("mimetype like 'image/%'");
111 $img->orderBy('title ASC'); /// spurious ordering... (curretnly used by shipping project)
112 if (isset($onbits[2])) {
113 $img->imgtype = $onbits[2];
116 if (!$img->find(true)) {
117 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
118 urlencode("no images for that item: " . htmlspecialchars($id)));
127 // depreciated - should use ontable:onid:type here...
128 if (!empty($_REQUEST['ontable'])) {
130 //DB_DataObjecT::debugLevel(1);
131 $img = DB_DataObjecT::factory('Images');
132 $img->setFrom($_REQUEST);
133 // use imgtype now...
134 // if (!empty($_REQUEST['query']['filename'])){
135 // $img->whereAdd("filename LIKE '". $img->escape($_REQUEST['query']['filename']).".%'");
140 if (!$img->find(true)) {
141 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason='.
142 urlencode("No file exists"));
150 $img = DB_DataObjecT::factory('Images');
152 if (!$id || !$img->get($id)) {
154 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
155 urlencode("image has been removed or deleted."));
159 if(!$this->hasPermission($img)){
160 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
161 urlencode("access to this image/file has been denied."));
168 function hasPermission($img)
176 if (!$this->authUser) {
177 $this->jerr("image conversion only allowed by registered users");
179 // converts a posted string (eg.svg)
180 // into another type..
181 if (empty($_REQUEST['as'])) {
182 $this->jerr("missing target type");
184 if (empty($_REQUEST['mimetype'])) {
185 $this->jerr("missing mimetype");
187 if (empty($_REQUEST['data'])) {
188 $this->jerr("missing data");
192 $this->as_mimetype = $_REQUEST['as'];
193 $this->mimetype = $_REQUEST['mimetype'];
194 require_once 'File/MimeType.php';
195 $y = new File_MimeType();
196 $src_ext = $y->toExt( $this->mimetype );
199 $tmp = $this->tempName($src_ext);
200 file_put_contents($tmp, $_REQUEST['data']);
202 require_once 'File/Convert.php';
203 $cv = new File_Convert($tmp, $this->mimetype);
207 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
208 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
210 if (!empty($_REQUEST['as_data'])) {
211 $this->jok(base64_encode(file_get_contents($fn)));
214 $cv->serve('attachment');
225 print_f("test??");exit;
226 $this->sessionState(0); // turn off session... - locking...
228 require_once 'File/Convert.php';
229 if (!file_exists($img->getStoreName())) {
230 // print_r($img);exit;
231 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
232 urlencode("Original file was missing : " . $img->getStoreName()));
235 // print_r($img);exit;
236 $x = $img->toFileConvert();
237 if (empty($this->as_mimetype) || $img->mimetype == 'image/gif') {
238 $this->as_mimetype = $img->mimetype;
242 $x->convert( $this->as_mimetype);
243 $x->serve($this->method);
246 //echo "SKALING? $this->size";
247 // acutally if we generated the image, then we do not need to validate the size..
249 require_once 'File/MimeType.php';
250 $y = new File_MimeType();
251 $ext = $y->toExt(trim((string) $this->as_mimetype ));
255 // if the mimetype is not converted..
256 // then the filename should be original.{size}.jpeg
257 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
259 if (!file_exists($fn)) {
260 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
261 // if it's an image, convert into the same type for thumbnail..
262 if (preg_match('#^image/#', $img->mimetype)) {
263 $this->as_mimetype = $img->mimetype;
267 if (!file_exists($fn)) {
268 $this->validateSize();
271 $x->convert( $this->as_mimetype, $this->size);
279 function validateSize()
281 if (($this->authUser && !empty($this->authUser->company_id) && $this->authUser->company()->comptype=='OWNER') || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
286 $ff = HTML_FlexyFramework::get();
301 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
302 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
304 if (!empty($cfg['sizes'])) {
305 $sizes = array_merge($sizes , $cfg['sizes']);
308 $project = $ff->project;
310 require_once $ff->project . '.php';
312 $project = new $ff->project();
314 if(isset($project::$Pman_Core_Images_Size)){
315 $sizes = $project::$Pman_Core_Images_Size;
318 if (!in_array($this->size, $sizes)) {
319 die("invalid scale - ".$this->size);
325 * The idea of this code was to replace urls for images when you have an admin
326 * and a distribution page. with different urls.
328 * it may be usefull later if things like embedded images in emails. but
329 * I think it's proably better not to use this.
331 * The key problem being how to determine if we are replacing 'our' images or some external one..
337 static function replaceImageURLS($html)
340 $ff = HTML_FlexyFramework::get();
341 if (!isset($ff->Pman_Images['public_baseURL'])) {
344 //var_dump($ff->Pman_Images['public_baseURL']);
345 $baseURL = $ff->Pman_Images['public_baseURL'];
347 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
349 $matches = array_unique($result[0]);
350 foreach($matches as $img) {
352 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
356 foreach($imatch[1] as $i=>$key) {
357 $attr[$key] = $imatch[2][$i];
359 // does it contain baseURL??? --- well what about relative paths...
362 if (empty($attr['src'])) {
365 if (0 !== strpos($attr['src'], $baseURL)) {
366 // it starts with our 'new' baseURL?
367 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
370 if (false !== strpos($attr['src'], '//') && false === strpos($attr['src'], $baseURL)) {
371 // contains an absolute path.. that is probably not us...
374 // what about mailto or data... - just ignore?? for images...
376 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
382 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
384 $matches = array_unique($result[0]);
385 foreach($matches as $img) {
387 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
391 foreach($imatch[1] as $i=>$key) {
392 $attr[$key] = $imatch[2][$i];
394 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
397 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
402 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
406 // see if it's an image url..
407 // Images/{ID}/fullname.xxxx
408 // Images/Thumb/200/{ID}/fullname.xxxx
409 // Images/Download/{ID}/fullname.xxxx
411 $attr_url = $attr[$attr_name];
413 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
419 if (!empty($umatch[3]) && strpos($umatch[3],'#')) {
420 $hash = '#'. array_pop(explode('#',$umatch[3]));
424 $img = DB_DataObject::factory('Images');
425 if (!$img->get($id)) {
428 $type = explode('/', $umatch[1]);
431 if (count($type) > 2 && $type[1] == 'Thumb') {
432 $thumbsize = $type[2];
433 $provider = '/Images/Thumb';
435 $provider = '/'.$umatch[1];
438 if (!empty($attr['width']) || !empty($attr['height']) )
440 // no support for %...
442 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
444 (empty($attr['height']) ? '0' : $attr['height'] * 1);
445 $provider = '/Images/Thumb';
449 if ($thumbsize !== -1) {
451 // need to regenerate it..
453 $type = array('Images', 'Thumb', $thumbsize);
455 $fc = $img->toFileConvert();
456 // make sure it's available..
457 $fc->convert($img->mimetype, $thumbsize);
461 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
465 // finally replace the original TAG with the new version..
467 $new_tag = str_replace(
468 $attr_name. '="'. $attr_url . '"',
469 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . $hash .'"',
474 return str_replace($tag, $new_tag, $html);
478 function downloadEvent($bits)
480 $popts = PEAR::getStaticProperty('Pman','options');
481 $ev = DB_DAtaObject::Factory('events');
482 if (!$ev->get($bits[1])) {
483 die("could not find event id");
485 // technically same user only.. -- normally www-data..
486 if (function_exists('posix_getpwuid')) {
487 $uinfo = posix_getpwuid( posix_getuid () );
488 $user = $uinfo['name'];
490 $user = getenv('USERNAME'); // windows.
492 $ff = HTML_FlexyFramework::get();
493 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
494 $filesJ = json_decode(file_get_contents($file));
498 foreach($filesJ->FILES as $k=>$f){
499 if ($f->tmp_name != $bits[2]) {
503 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
504 if (!file_exists($src)) {
505 die("file was not saved");
507 header ('Content-Type: ' . $f->type);
509 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );