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();
46 // die("Access denied");
48 $this->authUser = $au;
53 var $as_mimetype = false;
54 var $method = 'inline';
56 function get($s) // determin what to serve!!!!
59 //if (!empty($_GET['_post'])) {
60 // return $this->post();
63 $this->as_mimetype = empty($_REQUEST['as']) ? '' : $_REQUEST['as'];
65 $bits= explode('/', $s);
67 // var_dump($bits);die('in');
68 // without id as first part...
69 if (!empty($bits[0]) && $bits[0] == 'Thumb') {
71 $this->as_mimetype = 'image/jpeg';
72 $this->size = empty($bits[1]) ? '0x0' : $bits[1];
73 $id = empty($bits[2]) ? 0 : $bits[2];
75 } else if (!empty($bits[0]) && $bits[0] == 'Download') {
76 $this->method = 'attachment';
77 $id = empty($bits[1]) ? 0 : $bits[1];
79 } else if (!empty($bits[1]) && $bits[1] == 'Thumb') { // with id as first part.
81 $this->as_mimetype = 'image/jpeg';
82 $this->size = empty($bits[2]) ? '0x0' : $bits[2];
83 $id = empty($bits[3]) ? 0 : $bits[3];
85 } else if (!empty($bits[0]) && $bits[0] == 'events') {
87 $this->downloadEvent($bits);
89 die ("unknown file?");
93 $id = empty($bits[0]) ? 0 : $bits[0];
96 if (strpos($id,':') > 0) { // id format tablename:id:-imgtype
97 $onbits = explode(':', $id);
98 if ((count($onbits) < 2) || empty($onbits[1]) || !is_numeric($onbits[1]) || !strlen($onbits[0])) {
101 //DB_DataObject::debugLevel(1);
102 $img = DB_DataObject::factory('Images');
103 $img->ontable = $onbits[0];
104 $img->onid = $onbits[1];
105 if (empty($_REQUEST['anytype'])) {
106 $img->whereAdd("mimetype like 'image/%'");
109 if (isset($onbits[2])) {
110 $img->imgtype = $onbits[2];
113 if (!$img->find(true)) {
114 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
115 urlencode("no images for that item: " . htmlspecialchars($id)));
124 // depreciated - should use ontable:onid:type here...
125 if (!empty($_REQUEST['ontable'])) {
127 //DB_DataObjecT::debugLevel(1);
128 $img = DB_DataObjecT::factory('Images');
129 $img->setFrom($_REQUEST);
130 // use imgtype now...
131 // if (!empty($_REQUEST['query']['filename'])){
132 // $img->whereAdd("filename LIKE '". $img->escape($_REQUEST['query']['filename']).".%'");
137 if (!$img->find(true)) {
138 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason='.
139 urlencode("No file exists"));
147 $img = DB_DataObjecT::factory('Images');
149 if (!$id || !$img->get($id)) {
151 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
152 urlencode("image has been removed or deleted."));
156 if(!$this->hasPermission($img)){
157 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
158 urlencode("image has been removed or deleted."));
165 function hasPermission($img) {
172 if (!$this->authUser) {
173 $this->jerr("image conversion only allowed by registered users");
175 // converts a posted string (eg.svg)
176 // into another type..
177 if (empty($_REQUEST['as'])) {
178 $this->jerr("missing target type");
180 if (empty($_REQUEST['mimetype'])) {
181 $this->jerr("missing mimetype");
183 if (empty($_REQUEST['data'])) {
184 $this->jerr("missing data");
188 $this->as_mimetype = $_REQUEST['as'];
189 $this->mimetype = $_REQUEST['mimetype'];
190 require_once 'File/MimeType.php';
191 $y = new File_MimeType();
192 $src_ext = $y->toExt( $this->mimetype );
195 $tmp = $this->tempName($src_ext);
196 file_put_contents($tmp, $_REQUEST['data']);
198 require_once 'File/Convert.php';
199 $cv = new File_Convert($tmp, $this->mimetype);
203 empty($_REQUEST['width']) ? 0 : $_REQUEST['width'],
204 empty($_REQUEST['height']) ? 0 : $_REQUEST['height']
206 if (!empty($_REQUEST['as_data'])) {
207 $this->jok(base64_encode(file_get_contents($fn)));
210 $cv->serve('attachment');
221 $this->sessionState(0); // turn off session... - locking...
223 require_once 'File/Convert.php';
224 if (!file_exists($img->getStoreName())) {
225 // print_r($img);exit;
226 header('Location: ' . $this->rootURL . '/Pman/templates/images/file-broken.png?reason=' .
227 urlencode("Original file was missing : " . $img->getStoreName()));
230 // print_r($img);exit;
231 $x = $img->toFileConvert();
232 if (empty($this->as_mimetype)) {
233 $this->as_mimetype = $img->mimetype;
236 $x->convert( $this->as_mimetype);
237 $x->serve($this->method);
240 //echo "SKALING? $this->size";
241 // acutally if we generated the image, then we do not need to validate the size..
245 // if the mimetype is not converted..
246 // then the filename should be original.{size}.jpeg
247 $fn = $img->getStoreName() . '.'. $this->size . '.jpeg'; // thumbs are currenly all jpeg.!???
249 if (!file_exists($fn)) {
250 $fn = $img->getStoreName() . '.'. $this->size . '.'. $img->fileExt();
251 // if it's an image, convert into the same type for thumbnail..
252 if (preg_match('#^image/#', $img->mimetype)) {
253 $this->as_mimetype = $img->mimetype;
257 if (!file_exists($fn)) {
259 $this->validateSize();
262 $x->convert( $this->as_mimetype, $this->size);
270 function validateSize()
272 if (($this->authUser && $this->authUser->company_id && $this->authUser->company()->comptype=='OWNER') || $_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
276 // DEFAULT allowed - override with $cfg['sizes'];
287 '300x100', // logo on login.
291 // this should be configurable...
292 $ff = HTML_FlexyFramework::get();
293 $cfg = isset($ff->Pman_Images) ? $ff->Pman_Images :
294 (isset($ff->Pman_Core_Images) ? $ff->Pman_Core_Images : array());
298 if (!empty($cfg['sizes'])) {
299 $sizes = array_merge($sizes , $cfg['sizes']);
303 if (!in_array($this->size, $sizes)) {
304 die("invalid scale - ".$this->size);
310 * The idea of this code was to replace urls for images when you have an admin
311 * and a distribution page. with different urls.
313 * it may be usefull later if things like embedded images in emails. but
314 * I think it's proably better not to use this.
316 * The key problem being how to determine if we are replacing 'our' images or some external one..
322 static function replaceImageURLS($html)
325 $ff = HTML_FlexyFramework::get();
326 if (!isset($ff->Pman_Images['public_baseURL'])) {
329 //var_dump($ff->Pman_Images['public_baseURL']);
330 $baseURL = $ff->Pman_Images['public_baseURL'];
332 preg_match_all('/<img\s+[^>]+>/i',$html, $result);
334 $matches = array_unique($result[0]);
335 foreach($matches as $img) {
337 preg_match_all('/(width|height|src)="([^"]*)"/i',$img, $imatch);
341 foreach($imatch[1] as $i=>$key) {
342 $attr[$key] = $imatch[2][$i];
344 if (!isset($attr['src']) || 0 !== strpos($attr['src'], $baseURL)) {
347 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'src' );
351 preg_match_all('/<a\s+[^>]+>/i',$html, $result);
353 $matches = array_unique($result[0]);
354 foreach($matches as $img) {
356 preg_match_all('/(href)="([^"]*)"/i',$img, $imatch);
360 foreach($imatch[1] as $i=>$key) {
361 $attr[$key] = $imatch[2][$i];
363 if (!isset($attr['href']) || 0 !== strpos($attr['href'], $baseURL)) {
366 $html = self::replaceImgUrl($html, $baseURL, $img, $attr, 'href' );
371 static function replaceImgUrl($html, $baseURL, $tag, $attr, $attr_name)
375 // see if it's an image url..
376 // Images/{ID}/fullname.xxxx
377 // Images/Thumb/200/{ID}/fullname.xxxx
378 // Images/Download/{ID}/fullname.xxxx
380 $attr_url = $attr[$attr_name];
382 if(!preg_match('#/(Images|Images/Thumb/[a-z0-9]+|Images/Download)/([0-9]+)/(.*)$#', $attr_url, $umatch)) {
386 $img = DB_DataObject::factory('Images');
387 if (!$img->get($id)) {
390 $type = explode('/', $umatch[1]);
393 if (count($type) > 2 && $type[1] == 'Thumb') {
394 $thumbsize = $type[2];
395 $provider = '/Images/Thumb';
397 $provider = '/'.$umatch[1];
400 if (!empty($attr['width']) || !empty($attr['height']) )
402 // no support for %...
404 (empty($attr['width']) ? '0' : $attr['width'] * 1) .
406 (empty($attr['height']) ? '0' : $attr['height'] * 1);
407 $provider = '/Images/Thumb';
411 if ($thumbsize !== -1) {
413 // need to regenerate it..
415 $type = array('Images', 'Thumb', $thumbsize);
417 $fc = $img->toFileConvert();
418 // make sure it's available..
419 $fc->convert($img->mimetype, $thumbsize);
423 $provider = $provider == 'Images/Thumb' ? 'Images' : $provider;
427 // finally replace the original TAG with the new version..
429 $new_tag = str_replace(
430 $attr_name. '="'. $attr_url . '"',
431 $attr_name .'="'. htmlspecialchars($img->URL($thumbsize, $provider, $baseURL)) . '"',
436 return str_replace($tag, $new_tag, $html);
440 function downloadEvent($bits)
442 $popts = PEAR::getStaticProperty('Pman','options');
443 $ev = DB_DAtaObject::Factory('events');
444 if (!$ev->get($bits[1])) {
445 die("could not find event id");
447 // technically same user only.. -- normally www-data..
448 if (function_exists('posix_getpwuid')) {
449 $uinfo = posix_getpwuid( posix_getuid () );
450 $user = $uinfo['name'];
452 $user = getenv('USERNAME'); // windows.
454 $ff = HTML_FlexyFramework::get();
455 $file = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/',strtotime($ev->event_when)). $ev->id . ".json";
456 $filesJ = json_decode(file_get_contents($file));
460 foreach($filesJ->FILES as $k=>$f){
461 if ($f->tmp_name != $bits[2]) {
465 $src = $ff->Pman['event_log_dir']. '/'. $user. date('/Y/m/d/', strtotime($ev->event_when)). $f->tmp_name ;
466 if (!file_exists($src)) {
467 die("file was not saved");
469 header ('Content-Type: ' . $f->type);
471 header("Content-Disposition: attachment; filename=\"".basename($f->name)."\";" );