From 255bd9ef9c2875f1de2759f653e06b7366ab8699 Mon Sep 17 00:00:00 2001 From: ericLemanissier <ericLemanissier@users.noreply.github.com> Date: Fri, 28 Aug 2015 19:23:09 +0200 Subject: [PATCH] reduce memory usage when decoding files When decoding attached files, passing the whole content of the file to imap_base64 or base64_decode leads to allocating the memory for the whole base 64 decoded file while the binary content of the file is still in memory. This leads easily to Out of memory error on limited resources servers. Using .stream_filter_append to decode the file while writing it in a temporary file uses much less memory. The content of the decoded file is then simply read from the file --- include/class.mailfetch.php | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/include/class.mailfetch.php b/include/class.mailfetch.php index 024f80ce5..8ab686906 100644 --- a/include/class.mailfetch.php +++ b/include/class.mailfetch.php @@ -193,9 +193,34 @@ class MailFetcher { $text=imap_binary($text); break; case 3: - // imap_base64 implies strict mode. If it refuses to decode the - // data, then fallback to base64_decode in non-strict mode - $text = (($conv=imap_base64($text))) ? $conv : base64_decode($text); + if(10000000 > strlen($text)) + { + // imap_base64 implies strict mode. If it refuses to decode the + // data, then fallback to base64_decode in non-strict mode + $text = (($conv=imap_base64($text))) ? $conv : base64_decode($text); + } + else + { + $temp = tempnam(sys_get_temp_dir(), 'attachments'); + if(!$temp) + break; + $f = fopen($temp, 'w'); + if(!$f) + break; + $s_filter = stream_filter_append($f, 'convert.base64-decode',STREAM_FILTER_WRITE); + if(!fwrite($f, $text)) + break; + stream_filter_remove($s_filter); + fclose($f); + $f = fopen($temp, 'r'); + if(!$f) + break; + $text = fread($f,filesize($temp)); + if(!$text) + break; + fclose($f); + unlink($temp); + } break; case 4: $text=imap_qprint($text); -- GitLab