|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace dokuwiki\File; |
| 4 | + |
| 5 | +/** |
| 6 | + * Access a static file from lib/images with optinal override in conf/images |
| 7 | + */ |
| 8 | +class StaticImage |
| 9 | +{ |
| 10 | + |
| 11 | + protected string $path; |
| 12 | + |
| 13 | + /** |
| 14 | + * @param string $path the path relative to lib/images |
| 15 | + */ |
| 16 | + public function __construct(string $path) |
| 17 | + { |
| 18 | + require_once(DOKU_INC . 'inc/fetch.functions.php'); // late load when needed |
| 19 | + |
| 20 | + $path = preg_replace('/\.\.+/', '.', $path); |
| 21 | + $path = preg_replace('/\/\/+/', '/', $path); |
| 22 | + $path = trim($path, '/'); |
| 23 | + $this->path = $path; |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Static convenience method to get the real path to an image |
| 28 | + * |
| 29 | + * @param string $path |
| 30 | + * @return string |
| 31 | + */ |
| 32 | + public static function path(string $path): string |
| 33 | + { |
| 34 | + return (new self($path))->getRealPath(); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Static convenience method to get the URL to an image |
| 39 | + * |
| 40 | + * @param string $path |
| 41 | + * @return string |
| 42 | + */ |
| 43 | + public static function url(string $path): string |
| 44 | + { |
| 45 | + return (new self($path))->getURL(); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * @return string the mime type of the image |
| 50 | + */ |
| 51 | + public function getMimeType() |
| 52 | + { |
| 53 | + [/*ext*/, $mime] = mimetype($this->path, false); |
| 54 | + if ($mime === false) throw new \RuntimeException('Unknown mime type'); |
| 55 | + return $mime; |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * @return string the real path to the image |
| 60 | + */ |
| 61 | + public function getRealPath() |
| 62 | + { |
| 63 | + // overridden image |
| 64 | + $path = DOKU_CONF . 'images/' . $this->path; |
| 65 | + if (file_exists($path)) return $path; |
| 66 | + |
| 67 | + // default image |
| 68 | + $path = DOKU_INC . 'lib/images/' . $this->path; |
| 69 | + if (file_exists($path)) return $path; |
| 70 | + |
| 71 | + throw new \RuntimeException('Image not found'); |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * @return string the URL to the image |
| 76 | + */ |
| 77 | + public function getURL() |
| 78 | + { |
| 79 | + return DOKU_BASE . 'lib/exe/image.php/' . $this->path; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Serve the image to the client |
| 84 | + */ |
| 85 | + public function serve() |
| 86 | + { |
| 87 | + $path = $this->getRealPath(); |
| 88 | + $mime = $this->getMimeType(); |
| 89 | + sendFile($path, $mime, false, -1, true); |
| 90 | + } |
| 91 | +} |
0 commit comments