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