thumb: show 404.png for missing requests
[minimedit.git] / thumb / index.php
1 <?php
2 ob_clean();
3
4 list ($height, $imgpath) = explode('/', ltrim($Args, '/'), 2);
5 $width= 1000;
6 $imgpath = preg_replace('{^(?=[0-9]+/)}', 'data/', $imgpath, 1);
7
8 if (!file_exists($imgpath)) {
9         http_response_code(404);
10         $imgpath = '404.png';
11         if (!file_exists($imgpath)) {
12                 exit;
13         }
14 }
15
16 $target = "thumb/$height/$imgpath";
17 if (!file_exists($target)) {
18         try {
19                 mkthumb($imgpath, $target, $width, $height);
20         }
21         catch (Exception $e) {
22                 http_response_code($e->getCode() ?: 500);
23                 $target = '500.png';
24                 if (file_exists($target)) {
25                         header("X-Error: ".$e->getMessage());
26                         header('Content-type: '.mime_content_type($target));
27                         readfile($target);
28                         exit;
29                 }
30                 trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
31                 exit;
32         }
33 }
34
35 header('Content-type: '.mime_content_type($target));
36 readfile($target);
37 exit;
38
39 function mkthumb($source, $target, $width, $height)
40 {
41         @mkdir(dirname($target), 0777, TRUE);
42         return mkthumb_exec($source, $target, $width, $height);
43 }
44
45 function mkthumb_exec($source, $target, $width, $height)
46 {
47         if (!function_exists('popen')) {
48                 throw new Exception("exec disallowed on this server", 501);
49         }
50         $cmd = implode(' ', array_map('escapeshellarg', [
51                 'convert',
52                 '-trim',
53                 '-resize', "${width}x${height}",
54                 '-quality', '90%',
55                 $source, $target
56         ]));
57         $return = shell_exec("$cmd 2>&1");
58         if ($return) {
59                 throw new Exception($return);
60         }
61 }