thumb: error image also on unexpected exceptions
[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         exit;
11 }
12
13 $target = "thumb/$height/$imgpath";
14 if (!file_exists($target)) {
15         try {
16                 mkthumb($imgpath, $target, $width, $height);
17         }
18         catch (Exception $e) {
19                 http_response_code($e->getCode() ?: 500);
20                 $target = '500.png';
21                 if (file_exists($target)) {
22                         header("X-Error: ".$e->getMessage());
23                         header('Content-type: '.mime_content_type($target));
24                         readfile($target);
25                         exit;
26                 }
27                 trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
28                 exit;
29         }
30 }
31
32 header('Content-type: '.mime_content_type($target));
33 readfile($target);
34 exit;
35
36 function mkthumb($source, $target, $width, $height)
37 {
38         @mkdir(dirname($target), 0777, TRUE);
39         return mkthumb_exec($source, $target, $width, $height);
40 }
41
42 function mkthumb_exec($source, $target, $width, $height)
43 {
44         if (!function_exists('popen')) {
45                 throw new Exception("exec disallowed on this server", 501);
46         }
47         $cmd = implode(' ', array_map('escapeshellarg', [
48                 'convert',
49                 '-trim',
50                 '-resize', "${width}x${height}",
51                 '-quality', '90%',
52                 $source, $target
53         ]));
54         $return = shell_exec("$cmd 2>&1");
55         if ($return) {
56                 throw new Exception($return);
57         }
58 }