From 9942d1dc860f538a47661d905a9819ab47b17883 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Wed, 21 Jan 2015 00:38:09 -0800 Subject: [PATCH] Allow caching of profile images I considered refactoring CRM_Utils_System::download() to work with this, but there are just so many things that need to be done differently or explained -- it's just not worth it. Calling header() directly winds up being clearer/simpler. --- CRM/Contact/Page/ImageFile.php | 42 ++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/CRM/Contact/Page/ImageFile.php b/CRM/Contact/Page/ImageFile.php index 40731b6320..7e5a59a61b 100644 --- a/CRM/Contact/Page/ImageFile.php +++ b/CRM/Contact/Page/ImageFile.php @@ -33,6 +33,14 @@ * */ class CRM_Contact_Page_ImageFile extends CRM_Core_Page { + + /** + * @var int Time to live (seconds). + * + * 12 hours: 12 * 60 * 60 = 43200 + */ + private $ttl = 43200; + function run() { if (!preg_match('/^[^\/]+\.(jpg|jpeg|png|gif)$/i', $_GET['photo'])) { CRM_Core_Error::fatal('Malformed photo name'); @@ -49,12 +57,10 @@ class CRM_Contact_Page_ImageFile extends CRM_Core_Page { } if ($cid) { $config = CRM_Core_Config::singleton(); - $buffer = file_get_contents($config->customFileUploadDir . $_GET['photo']); - $mimeType = 'image/' . pathinfo($_GET['photo'], PATHINFO_EXTENSION); - CRM_Utils_System::download($_GET['photo'], $mimeType, $buffer, - NULL, - TRUE, - 'inline' + $this->download( + $config->customFileUploadDir . $_GET['photo'], + 'image/' . pathinfo($_GET['photo'], PATHINFO_EXTENSION), + $this->ttl ); CRM_Utils_System::civiExit(); } @@ -62,6 +68,28 @@ class CRM_Contact_Page_ImageFile extends CRM_Core_Page { CRM_Core_Error::fatal('Photo does not exist'); } } -} + /** + * @param string $file + * Local file path. + * @param string $mimeType + * @param int $ttl + * Time to live (seconds). + */ + protected function download($file, $mimeType, $ttl) { + if (!file_exists($file)) { + header("HTTP/1.0 404 Not Found"); + return; + } elseif (!is_readable($file)) { + header('HTTP/1.0 403 Forbidden'); + return; + } + header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', CRM_Utils_Time::getTimeRaw() + $ttl)); + header("Content-Type: $mimeType"); + header("Content-Disposition: inline; filename=\"" . basename($file) . "\""); + header("Cache-Control: max-age=$ttl, public"); + header('Pragma: public'); + readfile($file); + } +} -- 2.25.1