JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
silence more warnings
[wfpl-cms.git] / cms_images_autoresize.php
1 <?php
2
3 require_once(__DIR__.'/'.'config.php');
4 require_once(__DIR__.'/'.'inc/wfpl/upload.php');
5
6 function cms_images_autoresize_main_abort_404() {
7     http_response_code('404');
8     header('HTTP/1.0 404 File Not Found');
9     header('Content-Type: text/plain');
10     print('404: File not found');
11     exit();
12 }
13
14 function cms_images_autoresize_main() {
15     # figure out what file was requested
16     $out_fn = $_SERVER['REDIRECT_URL'];
17     $out_fn = preg_replace('|[?].*|', '', $out_fn); # apache 2.4.17
18     $out_fn = preg_replace('|.*/|', '', $out_fn);
19     $matches = array();
20     if (!preg_match('/^([0-9a-f]+)w([0-9]+)[.](png|jpg)$/', $out_fn, $matches)) {
21         cms_images_autoresize_main_abort_404();
22     }
23
24     $basename = $matches[1];
25     $width = (int)$matches[2];
26     $ext = $matches[3];
27     $in_fn = "$basename.$ext";
28     $in_path = __DIR__.'/'.'cms_images/' . $in_fn;
29     $out_path = __DIR__.'/'.'cms_images/' . $out_fn;
30     $lock_path = $out_path . '.lock';
31
32     if (!in_array($width, $GLOBALS['wfpl_image_widths'], true)) {
33         cms_images_autoresize_main_abort_404();
34     }
35
36     if (!file_exists($in_path)) {
37         cms_images_autoresize_main_abort_404();
38     }
39
40     @$lock = fopen($lock_path, 'x');
41     if (!$lock) {
42         # delete lock file if it's stale
43         $s = stat($lock_path);
44         if ($s && $s['mtime'] + 3 < time()) {
45             unlink($lock_path);
46         } else {
47             # if it's fresh, exit with temporary error
48             header('HTTP/1.0 503 Service Unavailable');
49             header('Content-Type: text/plain');
50             header('Retry-After: 4');
51             print("503 Service Unavailable (try again soon)\n");
52             var_dump($s);
53             var_dump(time());
54             exit();
55         }
56     }
57
58     imagemagick_convert($in_path, $out_path,
59         '-geometry '
60         . $width
61         . 'x'
62         . ($width * 2)
63         . "'>'"
64     );
65
66     # done! kill the lock
67     fclose($lock);
68     unlink($lock_path);
69
70     if (!headers_sent()) {
71         header('Content-Type: ' . ($ext = 'jpg' ? 'image/jpeg' : 'image/png'));
72         readfile($out_path);
73     }
74 }
75 cms_images_autoresize_main();