2 if ($Page->api) return;
3 $imgpath = ltrim($Page->path, '/');
4 if (!preg_match('{^[0-9x]+/}', $imgpath)) {
7 list ($size, $imgpath) = explode('/', $imgpath, 2);
8 $imgpath = preg_replace('{^(?=[0-9]+/)}', 'data/', $imgpath, 1);
9 $ext = ''; # explicit file type request
11 if (preg_match('/(.*)(\.jpg)$/', $imgpath, $imgpart) and file_exists($imgpart[1])) {
12 # source file without requested thumb extension
13 list (, $imgpath, $ext) = $imgpart;
15 elseif (!file_exists($imgpath)) {
16 http_response_code(404);
18 if (!file_exists($imgpath)) {
22 $target = "thumb/$size/$imgpath$ext";
25 mkthumb($imgpath, $size, $target);
27 catch (Throwable $e) {
28 http_response_code($e->getCode() ?: 500);
29 header("X-Error: ".explode("\n", $e->getMessage())[0], FALSE);
31 if (file_exists($target)) {
32 header('Content-type: '.mime_content_type($target));
36 trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
40 header('Cache-Control: max-age=2628000');
41 header('Content-Type: '.mime_content_type($target));
42 header('Content-Length: '.filesize($target));
46 function mkthumb($source, $size, $target)
48 if (strpos($size, 'x') !== FALSE) {
49 list ($width, $height) = explode('x', $size);
61 if (isset($_GET['backend'])) {
62 $backend = $_GET['backend'];
64 elseif (file_exists($target)) {
67 elseif (extension_loaded('gd')) {
73 $backend = "mkthumb_$backend";
75 @mkdir(dirname($target), 0777, TRUE);
76 $backend($source, $target, $width, $height);
80 function mkthumb_gd($source, $target, $width, $height)
82 $data = imagecreatefromstring(file_get_contents($source));
83 if (!$data) throw new Exception("error reading $source");
84 $orgwidth = imagesx($data);
85 $orgheight = imagesy($data);
86 $width = min($width, $orgwidth * $height / $orgheight);
87 $gd = imagecreatetruecolor($width, $height);
89 imagecopyresampled($gd, $data, 0, 0, 0, 0,
90 $width, $height, $orgwidth, $orgheight);
91 imagejpeg($gd, $target, 90);
94 function mkthumb_exec($source, $target, $width, $height)
96 if (!function_exists('popen')) {
97 throw new Exception("exec disallowed on this server", 501);
99 $cmd = implode(' ', array_map('escapeshellarg', [
101 '-delete', '1--1', # static
103 '-background', 'white', '-layers', 'flatten', # opaque
104 '-auto-orient', # apply exif rotation
105 '-interlace', 'plane', # progressive
106 '-strip', '-taint', # omit metadata
107 '-sampling-factor', '4:2:0', '-colorspace', 'sRGB', # half chroma
108 '-resize', "${width}x${height}>",
110 $source, "jpg:$target"
112 $return = shell_exec("$cmd 2>&1");
114 throw new Exception($return);