+<?php
+
+define('DOCROOT', __DIR__ .'/');
+require_once(DOCROOT . 'config.php');
+require_once(DOCROOT . 'inc/wfpl/upload.php');
+
+function cms_images_autoresize_main_abort_404() {
+ http_response_code('404');
+ header('HTTP/1.0 404 File Not Found');
+ header('Content-Type: text/plain');
+ print('404: File not found');
+ exit();
+}
+
+function cms_images_autoresize_main() {
+ # figure out what file was requested
+ $out_fn = $_SERVER['REDIRECT_URL'];
+ $out_fn = preg_replace('|[?].*|', '', $out_fn); # apache 2.4.17
+ $out_fn = preg_replace('|.*/|', '', $out_fn);
+ $matches = array();
+ if (!preg_match('/^([0-9a-f]+)w([0-9]+)[.](png|jpg)$/', $out_fn, $matches)) {
+ cms_images_autoresize_main_abort_404();
+ }
+
+ $basename = $matches[1];
+ $width = (int)$matches[2];
+ $ext = $matches[3];
+ $in_fn = "$basename.$ext";
+ $in_path = DOCROOT . 'cms_images/' . $in_fn;
+ $out_path = DOCROOT . 'cms_images/' . $out_fn;
+ $lock_path = $out_path . '.lock';
+
+ if (!in_array($width, $GLOBALS['wfpl_image_widths'], true)) {
+ cms_images_autoresize_main_abort_404();
+ }
+
+ if (!file_exists($in_path)) {
+ cms_images_autoresize_main_abort_404();
+ }
+
+ @$lock = fopen($lock_path, 'x');
+ if (!$lock) {
+ # delete lock file if it's stale
+ $s = stat($lock_path);
+ if ($s && $s['mtime'] + 3 < time()) {
+ unlink($lock_path);
+ } else {
+ # if it's fresh, exit with temporary error
+ header('HTTP/1.0 503 Service Unavailable');
+ header('Content-Type: text/plain');
+ header('Retry-After: 4');
+ print("503 Service Unavailable (try again soon)\n");
+ var_dump($s);
+ var_dump(time());
+ exit();
+ }
+ }
+
+ imagemagick_convert($in_path, $out_path,
+ '-geometry '
+ . $width
+ . 'x'
+ . ($width * 2)
+ . "'>'"
+ );
+
+ # done! kill the lock
+ fclose($lock);
+ unlink($lock_path);
+
+ if (!headers_sent()) {
+ header('Content-Type: ' . ($ext = 'jpg' ? 'image/jpeg' : 'image/png'));
+ readfile($out_path);
+ }
+}
+cms_images_autoresize_main();