Skip to content

Commit

Permalink
Set a Part filename if the part stores an attachment
Browse files Browse the repository at this point in the history
This change simplistically sets a Part's filename property if the
content disposition header is set, it's an attachment, and the filename
property is set. I've deliberately avoided any considerations about
sanitising the filename, deciding, at this stage, to leave that to the
calling code up the line.

Signed-off-by: Matthew Setter <matthew@matthewsetter.com>
  • Loading branch information
settermjd committed Nov 29, 2023
1 parent f67b0c0 commit 93c2cd6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@

namespace Laminas\Mime;

use Laminas\Mail\Header\ContentDisposition;
use Laminas\Mail\Header\ContentType;
use Laminas\Mail\Header\HeaderInterface;
use Laminas\Mail\Headers;
use Laminas\Mime\Mime;
use Laminas\Mime\Part;

use function array_keys;
use function base64_decode;
use function count;
use function current;
use function quoted_printable_decode;
use function sprintf;
use function str_starts_with;
use function strlen;
use function strpos;
use function strtolower;
Expand Down Expand Up @@ -333,6 +332,17 @@ public static function createFromMessage($message, $boundary = null, $EOL = Mime
}
} else {
$newPart = new Part($body);

if ($headers->has('content-disposition')) {
/** @var ContentDisposition $header */
$header = $headers->get('content-disposition');
if (
str_starts_with($header->getFieldValue(), 'attachment')
&& $header->getParameter('filename') !== null
) {
$newPart->setFileName($header->getParameter('filename'));
}
}
}
foreach ($properties as $key => $value) {
$newPart->$key = $value;
Expand Down
2 changes: 2 additions & 0 deletions test/MessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,8 @@ public function testDecodeMultipartMimeMessageWithMessagePartAlternatives()
);
}, ARRAY_FILTER_USE_BOTH);
$this->assertCount(1, $attachments);
$docAttachment = $attachments[1];
$this->assertSame("DockMcWordface.docx", $docAttachment->getFileName());

$nonAttachments = array_filter($parts, function ($part, $index) {
return ! str_starts_with(
Expand Down

0 comments on commit 93c2cd6

Please sign in to comment.