thumb: force reload with specified ?backend
[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 try {
18         mkthumb($imgpath, $target, $width, $height);
19 }
20 catch (Exception $e) {
21         http_response_code($e->getCode() ?: 500);
22         $target = '500.png';
23         if (file_exists($target)) {
24                 header("X-Error: ".$e->getMessage());
25                 header('Content-type: '.mime_content_type($target));
26                 readfile($target);
27                 exit;
28         }
29         trigger_error("thumbnail creation failed: ".$e->getMessage(), E_USER_WARNING);
30         exit;
31 }
32
33 header('Content-type: '.mime_content_type($target));
34 readfile($target);
35 exit;
36
37 function mkthumb($source, $target, $width, $height)
38 {
39         if (isset($_GET['backend'])) {
40                 $backend = $_GET['backend'];
41         }
42         elseif (file_exists($target)) {
43                 return;
44         }
45         else {
46                 $backend = 'exec';
47         }
48         $backend = "mkthumb_$backend";
49
50         @mkdir(dirname($target), 0777, TRUE);
51         $backend($source, $target, $width, $height);
52 }
53
54 function mkthumb_exec($source, $target, $width, $height)
55 {
56         if (!function_exists('popen')) {
57                 throw new Exception("exec disallowed on this server", 501);
58         }
59         $cmd = implode(' ', array_map('escapeshellarg', [
60                 'convert',
61                 '-trim',
62                 '-resize', "${width}x${height}",
63                 '-quality', '90%',
64                 $source, $target
65         ]));
66         $return = shell_exec("$cmd 2>&1");
67         if ($return) {
68                 throw new Exception($return);
69         }
70 }