1
0

first commit

This commit is contained in:
Daniel Tartavel
2021-10-14 17:58:21 +02:00
parent e5fe464cbc
commit df07673a67
327 changed files with 44407 additions and 0 deletions

View File

@ -0,0 +1,144 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An attachment, in a multipart message.
*
* @author Chris Corbyn
*/
class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
{
/** Recognized MIME types */
private $mimeTypes = [];
/**
* Create a new Attachment with $headers, $encoder and $cache.
*
* @param array $mimeTypes
*/
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = [])
{
parent::__construct($headers, $encoder, $cache, $idGenerator);
$this->setDisposition('attachment');
$this->setContentType('application/octet-stream');
$this->mimeTypes = $mimeTypes;
}
/**
* Get the nesting level used for this attachment.
*
* Always returns {@link LEVEL_MIXED}.
*
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_MIXED;
}
/**
* Get the Content-Disposition of this attachment.
*
* By default attachments have a disposition of "attachment".
*
* @return string
*/
public function getDisposition()
{
return $this->getHeaderFieldModel('Content-Disposition');
}
/**
* Set the Content-Disposition of this attachment.
*
* @param string $disposition
*
* @return $this
*/
public function setDisposition($disposition)
{
if (!$this->setHeaderFieldModel('Content-Disposition', $disposition)) {
$this->getHeaders()->addParameterizedHeader('Content-Disposition', $disposition);
}
return $this;
}
/**
* Get the filename of this attachment when downloaded.
*
* @return string
*/
public function getFilename()
{
return $this->getHeaderParameter('Content-Disposition', 'filename');
}
/**
* Set the filename of this attachment.
*
* @param string $filename
*
* @return $this
*/
public function setFilename($filename)
{
$this->setHeaderParameter('Content-Disposition', 'filename', $filename);
$this->setHeaderParameter('Content-Type', 'name', $filename);
return $this;
}
/**
* Get the file size of this attachment.
*
* @return int
*/
public function getSize()
{
return $this->getHeaderParameter('Content-Disposition', 'size');
}
/**
* Set the file size of this attachment.
*
* @param int $size
*
* @return $this
*/
public function setSize($size)
{
$this->setHeaderParameter('Content-Disposition', 'size', $size);
return $this;
}
/**
* Set the file that this attachment is for.
*
* @param string $contentType optional
*
* @return $this
*/
public function setFile(Swift_FileStream $file, $contentType = null)
{
$this->setFilename(basename($file->getPath()));
$this->setBody($file, $contentType);
if (!isset($contentType)) {
$extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1));
if (\array_key_exists($extension, $this->mimeTypes)) {
$this->setContentType($this->mimeTypes[$extension]);
}
}
return $this;
}
}

View File

@ -0,0 +1,24 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Observes changes in an Mime entity's character set.
*
* @author Chris Corbyn
*/
interface Swift_Mime_CharsetObserver
{
/**
* Notify this observer that the entity's charset has changed.
*
* @param string $charset
*/
public function charsetChanged($charset);
}

View File

@ -0,0 +1,34 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Interface for all Transfer Encoding schemes.
*
* @author Chris Corbyn
*/
interface Swift_Mime_ContentEncoder extends Swift_Encoder
{
/**
* Encode $in to $out.
*
* @param Swift_OutputByteStream $os to read from
* @param Swift_InputByteStream $is to write to
* @param int $firstLineOffset
* @param int $maxLineLength - 0 indicates the default length for this encoding
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0);
/**
* Get the MIME name of this content encoding scheme.
*
* @return string
*/
public function getName();
}

View File

@ -0,0 +1,101 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Base 64 Transfer Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_Base64ContentEncoder extends Swift_Encoder_Base64Encoder implements Swift_Mime_ContentEncoder
{
/**
* Encode stream $in to stream $out.
*
* @param int $firstLineOffset
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
if (0 >= $maxLineLength || 76 < $maxLineLength) {
$maxLineLength = 76;
}
$remainder = 0;
$base64ReadBufferRemainderBytes = null;
// To reduce memory usage, the output buffer is streamed to the input buffer like so:
// Output Stream => base64encode => wrap line length => Input Stream
// HOWEVER it's important to note that base64_encode() should only be passed whole triplets of data (except for the final chunk of data)
// otherwise it will assume the input data has *ended* and it will incorrectly pad/terminate the base64 data mid-stream.
// We use $base64ReadBufferRemainderBytes to carry over 1-2 "remainder" bytes from the each chunk from OutputStream and pre-pend those onto the
// chunk of bytes read in the next iteration.
// When the OutputStream is empty, we must flush any remainder bytes.
while (true) {
$readBytes = $os->read(8192);
$atEOF = (false === $readBytes);
if ($atEOF) {
$streamTheseBytes = $base64ReadBufferRemainderBytes;
} else {
$streamTheseBytes = $base64ReadBufferRemainderBytes.$readBytes;
}
$base64ReadBufferRemainderBytes = null;
$bytesLength = \strlen($streamTheseBytes);
if (0 === $bytesLength) { // no data left to encode
break;
}
// if we're not on the last block of the ouput stream, make sure $streamTheseBytes ends with a complete triplet of data
// and carry over remainder 1-2 bytes to the next loop iteration
if (!$atEOF) {
$excessBytes = $bytesLength % 3;
if (0 !== $excessBytes) {
$base64ReadBufferRemainderBytes = substr($streamTheseBytes, -$excessBytes);
$streamTheseBytes = substr($streamTheseBytes, 0, $bytesLength - $excessBytes);
}
}
$encoded = base64_encode($streamTheseBytes);
$encodedTransformed = '';
$thisMaxLineLength = $maxLineLength - $remainder - $firstLineOffset;
while ($thisMaxLineLength < \strlen($encoded)) {
$encodedTransformed .= substr($encoded, 0, $thisMaxLineLength)."\r\n";
$firstLineOffset = 0;
$encoded = substr($encoded, $thisMaxLineLength);
$thisMaxLineLength = $maxLineLength;
$remainder = 0;
}
if (0 < $remainingLength = \strlen($encoded)) {
$remainder += $remainingLength;
$encodedTransformed .= $encoded;
$encoded = null;
}
$is->write($encodedTransformed);
if ($atEOF) {
break;
}
}
}
/**
* Get the name of this encoding scheme.
* Returns the string 'base64'.
*
* @return string
*/
public function getName()
{
return 'base64';
}
}

View File

@ -0,0 +1,121 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer using the PHP core function.
*
* @author Lars Strojny
*/
class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_ContentEncoder
{
/**
* @var string|null
*/
private $charset;
/**
* @param string|null $charset
*/
public function __construct($charset = null)
{
$this->charset = $charset ?: 'utf-8';
}
/**
* Notify this observer that the entity's charset has changed.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->charset = $charset;
}
/**
* Encode $in to $out.
*
* @param Swift_OutputByteStream $os to read from
* @param Swift_InputByteStream $is to write to
* @param int $firstLineOffset
* @param int $maxLineLength 0 indicates the default length for this encoding
*
* @throws RuntimeException
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
if ('utf-8' !== $this->charset) {
throw new RuntimeException(sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset));
}
$string = '';
while (false !== $bytes = $os->read(8192)) {
$string .= $bytes;
}
$is->write($this->encodeString($string));
}
/**
* Get the MIME name of this content encoding scheme.
*
* @return string
*/
public function getName()
{
return 'quoted-printable';
}
/**
* Encode a given string to produce an encoded string.
*
* @param string $string
* @param int $firstLineOffset if first line needs to be shorter
* @param int $maxLineLength 0 indicates the default length for this encoding
*
* @throws RuntimeException
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
if ('utf-8' !== $this->charset) {
throw new RuntimeException(sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset));
}
return $this->standardize(quoted_printable_encode($string));
}
/**
* Make sure CRLF is correct and HT/SPACE are in valid places.
*
* @param string $string
*
* @return string
*/
protected function standardize($string)
{
// transform CR or LF to CRLF
$string = preg_replace('~=0D(?!=0A)|(?<!=0D)=0A~', '=0D=0A', $string);
// transform =0D=0A to CRLF
$string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], ["=09\r\n", "=20\r\n", "\r\n"], $string);
switch (\ord(substr($string, -1))) {
case 0x09:
$string = substr_replace($string, '=09', -1);
break;
case 0x20:
$string = substr_replace($string, '=20', -1);
break;
}
return $string;
}
}

View File

@ -0,0 +1,79 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles the case where the email body is already encoded and you just need specify the correct
* encoding without actually changing the encoding of the body.
*
* @author Jan Flora <jf@penneo.com>
*/
class Swift_Mime_ContentEncoder_NullContentEncoder implements Swift_Mime_ContentEncoder
{
/**
* The name of this encoding scheme (probably 7bit or 8bit).
*
* @var string
*/
private $name;
/**
* Creates a new NullContentEncoder with $name (probably 7bit or 8bit).
*
* @param string $name
*/
public function __construct($name)
{
$this->name = $name;
}
/**
* Encode a given string to produce an encoded string.
*
* @param string $string
* @param int $firstLineOffset ignored
* @param int $maxLineLength ignored
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
return $string;
}
/**
* Encode stream $in to stream $out.
*
* @param int $firstLineOffset ignored
* @param int $maxLineLength ignored
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
while (false !== ($bytes = $os->read(8192))) {
$is->write($bytes);
}
}
/**
* Get the name of this encoding scheme.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Not used.
*/
public function charsetChanged($charset)
{
}
}

View File

@ -0,0 +1,164 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles binary/7/8-bit Transfer Encoding in Swift Mailer.
*
* When sending 8-bit content over SMTP, you should use
* Swift_Transport_Esmtp_EightBitMimeHandler to enable the 8BITMIME SMTP
* extension.
*
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_ContentEncoder
{
/**
* The name of this encoding scheme (probably 7bit or 8bit).
*
* @var string
*/
private $name;
/**
* True if canonical transformations should be done.
*
* @var bool
*/
private $canonical;
/**
* Creates a new PlainContentEncoder with $name (probably 7bit or 8bit).
*
* @param string $name
* @param bool $canonical if canonicalization transformation should be done
*/
public function __construct($name, $canonical = false)
{
$this->name = $name;
$this->canonical = $canonical;
}
/**
* Encode a given string to produce an encoded string.
*
* @param string $string
* @param int $firstLineOffset ignored
* @param int $maxLineLength - 0 means no wrapping will occur
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
if ($this->canonical) {
$string = $this->canonicalize($string);
}
return $this->safeWordwrap($string, $maxLineLength, "\r\n");
}
/**
* Encode stream $in to stream $out.
*
* @param int $firstLineOffset ignored
* @param int $maxLineLength optional, 0 means no wrapping will occur
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
$leftOver = '';
while (false !== $bytes = $os->read(8192)) {
$toencode = $leftOver.$bytes;
if ($this->canonical) {
$toencode = $this->canonicalize($toencode);
}
$wrapped = $this->safeWordwrap($toencode, $maxLineLength, "\r\n");
$lastLinePos = strrpos($wrapped, "\r\n");
$leftOver = substr($wrapped, $lastLinePos);
$wrapped = substr($wrapped, 0, $lastLinePos);
$is->write($wrapped);
}
if (\strlen($leftOver)) {
$is->write($leftOver);
}
}
/**
* Get the name of this encoding scheme.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Not used.
*/
public function charsetChanged($charset)
{
}
/**
* A safer (but weaker) wordwrap for unicode.
*
* @param string $string
* @param int $length
* @param string $le
*
* @return string
*/
private function safeWordwrap($string, $length = 75, $le = "\r\n")
{
if (0 >= $length) {
return $string;
}
$originalLines = explode($le, $string);
$lines = [];
$lineCount = 0;
foreach ($originalLines as $originalLine) {
$lines[] = '';
$currentLine = &$lines[$lineCount++];
//$chunks = preg_split('/(?<=[\ \t,\.!\?\-&\+\/])/', $originalLine);
$chunks = preg_split('/(?<=\s)/', $originalLine);
foreach ($chunks as $chunk) {
if (0 != \strlen($currentLine)
&& \strlen($currentLine.$chunk) > $length) {
$lines[] = '';
$currentLine = &$lines[$lineCount++];
}
$currentLine .= $chunk;
}
}
return implode("\r\n", $lines);
}
/**
* Canonicalize string input (fix CRLF).
*
* @param string $string
*
* @return string
*/
private function canonicalize($string)
{
return str_replace(
["\r\n", "\r", "\n"],
["\n", "\n", "\r\n"],
$string
);
}
}

View File

@ -0,0 +1,134 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_ContentEncoder
{
protected $dotEscape;
/**
* Creates a new QpContentEncoder for the given CharacterStream.
*
* @param Swift_CharacterStream $charStream to use for reading characters
* @param Swift_StreamFilter $filter if canonicalization should occur
* @param bool $dotEscape if dot stuffing workaround must be enabled
*/
public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null, $dotEscape = false)
{
$this->dotEscape = $dotEscape;
parent::__construct($charStream, $filter);
}
public function __sleep()
{
return ['charStream', 'filter', 'dotEscape'];
}
protected function getSafeMapShareId()
{
return static::class.($this->dotEscape ? '.dotEscape' : '');
}
protected function initSafeMap()
{
parent::initSafeMap();
if ($this->dotEscape) {
/* Encode . as =2e for buggy remote servers */
unset($this->safeMap[0x2e]);
}
}
/**
* Encode stream $in to stream $out.
*
* QP encoded strings have a maximum line length of 76 characters.
* If the first line needs to be shorter, indicate the difference with
* $firstLineOffset.
*
* @param Swift_OutputByteStream $os output stream
* @param Swift_InputByteStream $is input stream
* @param int $firstLineOffset
* @param int $maxLineLength
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
if ($maxLineLength > 76 || $maxLineLength <= 0) {
$maxLineLength = 76;
}
$thisLineLength = $maxLineLength - $firstLineOffset;
$this->charStream->flushContents();
$this->charStream->importByteStream($os);
$currentLine = '';
$prepend = '';
$size = $lineLen = 0;
while (false !== $bytes = $this->nextSequence()) {
// If we're filtering the input
if (isset($this->filter)) {
// If we can't filter because we need more bytes
while ($this->filter->shouldBuffer($bytes)) {
// Then collect bytes into the buffer
if (false === $moreBytes = $this->nextSequence(1)) {
break;
}
foreach ($moreBytes as $b) {
$bytes[] = $b;
}
}
// And filter them
$bytes = $this->filter->filter($bytes);
}
$enc = $this->encodeByteSequence($bytes, $size);
$i = strpos($enc, '=0D=0A');
$newLineLength = $lineLen + (false === $i ? $size : $i);
if ($currentLine && $newLineLength >= $thisLineLength) {
$is->write($prepend.$this->standardize($currentLine));
$currentLine = '';
$prepend = "=\r\n";
$thisLineLength = $maxLineLength;
$lineLen = 0;
}
$currentLine .= $enc;
if (false === $i) {
$lineLen += $size;
} else {
// 6 is the length of '=0D=0A'.
$lineLen = $size - strrpos($enc, '=0D=0A') - 6;
}
}
if (\strlen($currentLine)) {
$is->write($prepend.$this->standardize($currentLine));
}
}
/**
* Get the name of this encoding scheme.
* Returns the string 'quoted-printable'.
*
* @return string
*/
public function getName()
{
return 'quoted-printable';
}
}

View File

@ -0,0 +1,96 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Proxy for quoted-printable content encoders.
*
* Switches on the best QP encoder implementation for current charset.
*
* @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
*/
class Swift_Mime_ContentEncoder_QpContentEncoderProxy implements Swift_Mime_ContentEncoder
{
/**
* @var Swift_Mime_ContentEncoder_QpContentEncoder
*/
private $safeEncoder;
/**
* @var Swift_Mime_ContentEncoder_NativeQpContentEncoder
*/
private $nativeEncoder;
/**
* @var string|null
*/
private $charset;
/**
* Constructor.
*
* @param string|null $charset
*/
public function __construct(Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder, Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder, $charset)
{
$this->safeEncoder = $safeEncoder;
$this->nativeEncoder = $nativeEncoder;
$this->charset = $charset;
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->safeEncoder = clone $this->safeEncoder;
$this->nativeEncoder = clone $this->nativeEncoder;
}
/**
* {@inheritdoc}
*/
public function charsetChanged($charset)
{
$this->charset = $charset;
$this->safeEncoder->charsetChanged($charset);
}
/**
* {@inheritdoc}
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
$this->getEncoder()->encodeByteStream($os, $is, $firstLineOffset, $maxLineLength);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'quoted-printable';
}
/**
* {@inheritdoc}
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
return $this->getEncoder()->encodeString($string, $firstLineOffset, $maxLineLength);
}
/**
* @return Swift_Mime_ContentEncoder
*/
private function getEncoder()
{
return 'utf-8' === $this->charset ? $this->nativeEncoder : $this->safeEncoder;
}
}

View File

@ -0,0 +1,65 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles raw Transfer Encoding in Swift Mailer.
*
* When sending 8-bit content over SMTP, you should use
* Swift_Transport_Esmtp_EightBitMimeHandler to enable the 8BITMIME SMTP
* extension.
*
* @author Sebastiaan Stok <s.stok@rollerscapes.net>
*/
class Swift_Mime_ContentEncoder_RawContentEncoder implements Swift_Mime_ContentEncoder
{
/**
* Encode a given string to produce an encoded string.
*
* @param string $string
* @param int $firstLineOffset ignored
* @param int $maxLineLength ignored
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
return $string;
}
/**
* Encode stream $in to stream $out.
*
* @param int $firstLineOffset ignored
* @param int $maxLineLength ignored
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
while (false !== ($bytes = $os->read(8192))) {
$is->write($bytes);
}
}
/**
* Get the name of this encoding scheme.
*
* @return string
*/
public function getName()
{
return 'raw';
}
/**
* Not used.
*/
public function charsetChanged($charset)
{
}
}

View File

@ -0,0 +1,41 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An embedded file, in a multipart message.
*
* @author Chris Corbyn
*/
class Swift_Mime_EmbeddedFile extends Swift_Mime_Attachment
{
/**
* Creates a new Attachment with $headers and $encoder.
*
* @param array $mimeTypes optional
*/
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = [])
{
parent::__construct($headers, $encoder, $cache, $idGenerator, $mimeTypes);
$this->setDisposition('inline');
$this->setId($this->getId());
}
/**
* Get the nesting level of this EmbeddedFile.
*
* Returns {@see LEVEL_RELATED}.
*
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_RELATED;
}
}

View File

@ -0,0 +1,22 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Observes changes for a Mime entity's ContentEncoder.
*
* @author Chris Corbyn
*/
interface Swift_Mime_EncodingObserver
{
/**
* Notify this observer that the observed entity's ContentEncoder has changed.
*/
public function encoderChanged(Swift_Mime_ContentEncoder $encoder);
}

View File

@ -0,0 +1,93 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A MIME Header.
*
* @author Chris Corbyn
*/
interface Swift_Mime_Header
{
/** Text headers */
const TYPE_TEXT = 2;
/** headers (text + params) */
const TYPE_PARAMETERIZED = 6;
/** Mailbox and address headers */
const TYPE_MAILBOX = 8;
/** Date and time headers */
const TYPE_DATE = 16;
/** Identification headers */
const TYPE_ID = 32;
/** Address path headers */
const TYPE_PATH = 64;
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType();
/**
* Set the model for the field body.
*
* The actual types needed will vary depending upon the type of Header.
*
* @param mixed $model
*/
public function setFieldBodyModel($model);
/**
* Set the charset used when rendering the Header.
*
* @param string $charset
*/
public function setCharset($charset);
/**
* Get the model for the field body.
*
* The return type depends on the specifics of the Header.
*
* @return mixed
*/
public function getFieldBodyModel();
/**
* Get the name of this header (e.g. Subject).
*
* The name is an identifier and as such will be immutable.
*
* @return string
*/
public function getFieldName();
/**
* Get the field body, prepared for folding into a final header value.
*
* @return string
*/
public function getFieldBody();
/**
* Get this Header rendered as a compliant string, including trailing CRLF.
*
* @return string
*/
public function toString();
}

View File

@ -0,0 +1,24 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Interface for all Header Encoding schemes.
*
* @author Chris Corbyn
*/
interface Swift_Mime_HeaderEncoder extends Swift_Encoder
{
/**
* Get the MIME name of this content encoding scheme.
*
* @return string
*/
public function getName();
}

View File

@ -0,0 +1,55 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Base64 (B) Header Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_HeaderEncoder_Base64HeaderEncoder extends Swift_Encoder_Base64Encoder implements Swift_Mime_HeaderEncoder
{
/**
* Get the name of this encoding scheme.
* Returns the string 'B'.
*
* @return string
*/
public function getName()
{
return 'B';
}
/**
* Takes an unencoded string and produces a Base64 encoded string from it.
*
* If the charset is iso-2022-jp, it uses mb_encode_mimeheader instead of
* default encodeString, otherwise pass to the parent method.
*
* @param string $string string to encode
* @param int $firstLineOffset
* @param int $maxLineLength optional, 0 indicates the default of 76 bytes
* @param string $charset
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0, $charset = 'utf-8')
{
if ('iso-2022-jp' === strtolower($charset)) {
$old = mb_internal_encoding();
mb_internal_encoding('utf-8');
$newstring = mb_encode_mimeheader($string, $charset, $this->getName(), "\r\n");
mb_internal_encoding($old);
return $newstring;
}
return parent::encodeString($string, $firstLineOffset, $maxLineLength);
}
}

View File

@ -0,0 +1,65 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Quoted Printable (Q) Header Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_HeaderEncoder
{
/**
* Creates a new QpHeaderEncoder for the given CharacterStream.
*
* @param Swift_CharacterStream $charStream to use for reading characters
*/
public function __construct(Swift_CharacterStream $charStream)
{
parent::__construct($charStream);
}
protected function initSafeMap()
{
foreach (array_merge(
range(0x61, 0x7A), range(0x41, 0x5A),
range(0x30, 0x39), [0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F]
) as $byte) {
$this->safeMap[$byte] = \chr($byte);
}
}
/**
* Get the name of this encoding scheme.
*
* Returns the string 'Q'.
*
* @return string
*/
public function getName()
{
return 'Q';
}
/**
* Takes an unencoded string and produces a QP encoded string from it.
*
* @param string $string string to encode
* @param int $firstLineOffset optional
* @param int $maxLineLength optional, 0 indicates the default of 76 chars
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
return str_replace([' ', '=20', "=\r\n"], ['_', '_', "\r\n"],
parent::encodeString($string, $firstLineOffset, $maxLineLength)
);
}
}

View File

@ -0,0 +1,476 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An abstract base MIME Header.
*
* @author Chris Corbyn
*/
abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
{
const PHRASE_PATTERN = '(?:(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]+(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)|(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?"((?:(?:[ \t]*(?:\r\n))?[ \t])?(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21\x23-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])))*(?:(?:[ \t]*(?:\r\n))?[ \t])?"(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?))+?)';
/**
* The name of this Header.
*
* @var string
*/
private $name;
/**
* The Encoder used to encode this Header.
*
* @var Swift_Encoder
*/
private $encoder;
/**
* The maximum length of a line in the header.
*
* @var int
*/
private $lineLength = 78;
/**
* The language used in this Header.
*
* @var string
*/
private $lang;
/**
* The character set of the text in this Header.
*
* @var string
*/
private $charset = 'utf-8';
/**
* The value of this Header, cached.
*
* @var string
*/
private $cachedValue = null;
/**
* Set the character set used in this Header.
*
* @param string $charset
*/
public function setCharset($charset)
{
$this->clearCachedValueIf($charset != $this->charset);
$this->charset = $charset;
if (isset($this->encoder)) {
$this->encoder->charsetChanged($charset);
}
}
/**
* Get the character set used in this Header.
*
* @return string
*/
public function getCharset()
{
return $this->charset;
}
/**
* Set the language used in this Header.
*
* For example, for US English, 'en-us'.
* This can be unspecified.
*
* @param string $lang
*/
public function setLanguage($lang)
{
$this->clearCachedValueIf($this->lang != $lang);
$this->lang = $lang;
}
/**
* Get the language used in this Header.
*
* @return string
*/
public function getLanguage()
{
return $this->lang;
}
/**
* Set the encoder used for encoding the header.
*/
public function setEncoder(Swift_Mime_HeaderEncoder $encoder)
{
$this->encoder = $encoder;
$this->setCachedValue(null);
}
/**
* Get the encoder used for encoding this Header.
*
* @return Swift_Mime_HeaderEncoder
*/
public function getEncoder()
{
return $this->encoder;
}
/**
* Get the name of this header (e.g. charset).
*
* @return string
*/
public function getFieldName()
{
return $this->name;
}
/**
* Set the maximum length of lines in the header (excluding EOL).
*
* @param int $lineLength
*/
public function setMaxLineLength($lineLength)
{
$this->clearCachedValueIf($this->lineLength != $lineLength);
$this->lineLength = $lineLength;
}
/**
* Get the maximum permitted length of lines in this Header.
*
* @return int
*/
public function getMaxLineLength()
{
return $this->lineLength;
}
/**
* Get this Header rendered as a RFC 2822 compliant string.
*
* @return string
*
* @throws Swift_RfcComplianceException
*/
public function toString()
{
return $this->tokensToString($this->toTokens());
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
/**
* Set the name of this Header field.
*
* @param string $name
*/
protected function setFieldName($name)
{
$this->name = $name;
}
/**
* Produces a compliant, formatted RFC 2822 'phrase' based on the string given.
*
* @param string $string as displayed
* @param string $charset of the text
* @param bool $shorten the first line to make remove for header name
*
* @return string
*/
protected function createPhrase(Swift_Mime_Header $header, $string, $charset, Swift_Mime_HeaderEncoder $encoder = null, $shorten = false)
{
// Treat token as exactly what was given
$phraseStr = $string;
// If it's not valid
if (!preg_match('/^'.self::PHRASE_PATTERN.'$/D', $phraseStr)) {
// .. but it is just ascii text, try escaping some characters
// and make it a quoted-string
if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) {
$phraseStr = $this->escapeSpecials($phraseStr, ['"']);
$phraseStr = '"'.$phraseStr.'"';
} else {
// ... otherwise it needs encoding
// Determine space remaining on line if first line
if ($shorten) {
$usedLength = \strlen($header->getFieldName().': ');
} else {
$usedLength = 0;
}
$phraseStr = $this->encodeWords($header, $string, $usedLength);
}
}
return $phraseStr;
}
/**
* Escape special characters in a string (convert to quoted-pairs).
*
* @param string $token
* @param string[] $include additional chars to escape
*
* @return string
*/
private function escapeSpecials($token, $include = [])
{
foreach (array_merge(['\\'], $include) as $char) {
$token = str_replace($char, '\\'.$char, $token);
}
return $token;
}
/**
* Encode needed word tokens within a string of input.
*
* @param string $input
* @param string $usedLength optional
*
* @return string
*/
protected function encodeWords(Swift_Mime_Header $header, $input, $usedLength = -1)
{
$value = '';
$tokens = $this->getEncodableWordTokens($input);
foreach ($tokens as $token) {
// See RFC 2822, Sect 2.2 (really 2.2 ??)
if ($this->tokenNeedsEncoding($token)) {
// Don't encode starting WSP
$firstChar = substr($token, 0, 1);
switch ($firstChar) {
case ' ':
case "\t":
$value .= $firstChar;
$token = substr($token, 1);
}
if (-1 == $usedLength) {
$usedLength = \strlen($header->getFieldName().': ') + \strlen($value);
}
$value .= $this->getTokenAsEncodedWord($token, $usedLength);
$header->setMaxLineLength(76); // Forcefully override
} else {
$value .= $token;
}
}
return $value;
}
/**
* Test if a token needs to be encoded or not.
*
* @param string $token
*
* @return bool
*/
protected function tokenNeedsEncoding($token)
{
return preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token);
}
/**
* Splits a string into tokens in blocks of words which can be encoded quickly.
*
* @param string $string
*
* @return string[]
*/
protected function getEncodableWordTokens($string)
{
$tokens = [];
$encodedToken = '';
// Split at all whitespace boundaries
foreach (preg_split('~(?=[\t ])~', $string) as $token) {
if ($this->tokenNeedsEncoding($token)) {
$encodedToken .= $token;
} else {
if (\strlen($encodedToken) > 0) {
$tokens[] = $encodedToken;
$encodedToken = '';
}
$tokens[] = $token;
}
}
if (\strlen($encodedToken)) {
$tokens[] = $encodedToken;
}
return $tokens;
}
/**
* Get a token as an encoded word for safe insertion into headers.
*
* @param string $token token to encode
* @param int $firstLineOffset optional
*
* @return string
*/
protected function getTokenAsEncodedWord($token, $firstLineOffset = 0)
{
// Adjust $firstLineOffset to account for space needed for syntax
$charsetDecl = $this->charset;
if (isset($this->lang)) {
$charsetDecl .= '*'.$this->lang;
}
$encodingWrapperLength = \strlen(
'=?'.$charsetDecl.'?'.$this->encoder->getName().'??='
);
if ($firstLineOffset >= 75) {
//Does this logic need to be here?
$firstLineOffset = 0;
}
$encodedTextLines = explode("\r\n",
$this->encoder->encodeString(
$token, $firstLineOffset, 75 - $encodingWrapperLength, $this->charset
)
);
if ('iso-2022-jp' !== strtolower($this->charset)) {
// special encoding for iso-2022-jp using mb_encode_mimeheader
foreach ($encodedTextLines as $lineNum => $line) {
$encodedTextLines[$lineNum] = '=?'.$charsetDecl.
'?'.$this->encoder->getName().
'?'.$line.'?=';
}
}
return implode("\r\n ", $encodedTextLines);
}
/**
* Generates tokens from the given string which include CRLF as individual tokens.
*
* @param string $token
*
* @return string[]
*/
protected function generateTokenLines($token)
{
return preg_split('~(\r\n)~', $token, -1, PREG_SPLIT_DELIM_CAPTURE);
}
/**
* Set a value into the cache.
*
* @param string $value
*/
protected function setCachedValue($value)
{
$this->cachedValue = $value;
}
/**
* Get the value in the cache.
*
* @return string
*/
protected function getCachedValue()
{
return $this->cachedValue;
}
/**
* Clear the cached value if $condition is met.
*
* @param bool $condition
*/
protected function clearCachedValueIf($condition)
{
if ($condition) {
$this->setCachedValue(null);
}
}
/**
* Generate a list of all tokens in the final header.
*
* @param string $string The string to tokenize
*
* @return array An array of tokens as strings
*/
protected function toTokens($string = null)
{
if (null === $string) {
$string = $this->getFieldBody();
}
$tokens = [];
// Generate atoms; split at all invisible boundaries followed by WSP
foreach (preg_split('~(?=[ \t])~', $string) as $token) {
$newTokens = $this->generateTokenLines($token);
foreach ($newTokens as $newToken) {
$tokens[] = $newToken;
}
}
return $tokens;
}
/**
* Takes an array of tokens which appear in the header and turns them into
* an RFC 2822 compliant string, adding FWSP where needed.
*
* @param string[] $tokens
*
* @return string
*/
private function tokensToString(array $tokens)
{
$lineCount = 0;
$headerLines = [];
$headerLines[] = $this->name.': ';
$currentLine = &$headerLines[$lineCount++];
// Build all tokens back into compliant header
foreach ($tokens as $i => $token) {
// Line longer than specified maximum or token was just a new line
if (("\r\n" == $token) ||
($i > 0 && \strlen($currentLine.$token) > $this->lineLength)
&& 0 < \strlen($currentLine)) {
$headerLines[] = '';
$currentLine = &$headerLines[$lineCount++];
}
// Append token to the line
if ("\r\n" != $token) {
$currentLine .= $token;
}
}
// Implode with FWS (RFC 2822, 2.2.3)
return implode("\r\n", $headerLines)."\r\n";
}
}

View File

@ -0,0 +1,113 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A Date MIME Header for Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* Date-time value of this Header.
*
* @var DateTimeImmutable
*/
private $dateTime;
/**
* Creates a new DateHeader with $name.
*
* @param string $name of Header
*/
public function __construct($name)
{
$this->setFieldName($name);
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_DATE;
}
/**
* Set the model for the field body.
*
* @param DateTimeInterface $model
*/
public function setFieldBodyModel($model)
{
$this->setDateTime($model);
}
/**
* Get the model for the field body.
*
* @return DateTimeImmutable
*/
public function getFieldBodyModel()
{
return $this->getDateTime();
}
/**
* Get the date-time representing the Date in this Header.
*
* @return DateTimeImmutable
*/
public function getDateTime()
{
return $this->dateTime;
}
/**
* Set the date-time of the Date in this Header.
*
* If a DateTime instance is provided, it is converted to DateTimeImmutable.
*/
public function setDateTime(DateTimeInterface $dateTime)
{
$this->clearCachedValueIf($this->getCachedValue() != $dateTime->format(DateTime::RFC2822));
if ($dateTime instanceof DateTime) {
$immutable = new DateTimeImmutable('@'.$dateTime->getTimestamp());
$dateTime = $immutable->setTimezone($dateTime->getTimezone());
}
$this->dateTime = $dateTime;
}
/**
* Get the string value of the body in this Header.
*
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
*
* @see toString()
*
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
if (isset($this->dateTime)) {
$this->setCachedValue($this->dateTime->format(DateTime::RFC2822));
}
}
return $this->getCachedValue();
}
}

View File

@ -0,0 +1,189 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\MessageIDValidation;
use Egulias\EmailValidator\Validation\RFCValidation;
/**
* An ID MIME Header for something like Message-ID or Content-ID.
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The IDs used in the value of this Header.
*
* This may hold multiple IDs or just a single ID.
*
* @var string[]
*/
private $ids = [];
/**
* The strict EmailValidator.
*
* @var EmailValidator
*/
private $emailValidator;
private $addressEncoder;
/**
* Creates a new IdentificationHeader with the given $name and $id.
*
* @param string $name
*/
public function __construct($name, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null)
{
$this->setFieldName($name);
$this->emailValidator = $emailValidator;
$this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_ID;
}
/**
* Set the model for the field body.
*
* This method takes a string ID, or an array of IDs.
*
* @param mixed $model
*
* @throws Swift_RfcComplianceException
*/
public function setFieldBodyModel($model)
{
$this->setId($model);
}
/**
* Get the model for the field body.
*
* This method returns an array of IDs
*
* @return array
*/
public function getFieldBodyModel()
{
return $this->getIds();
}
/**
* Set the ID used in the value of this header.
*
* @param string|array $id
*
* @throws Swift_RfcComplianceException
*/
public function setId($id)
{
$this->setIds(\is_array($id) ? $id : [$id]);
}
/**
* Get the ID used in the value of this Header.
*
* If multiple IDs are set only the first is returned.
*
* @return string
*/
public function getId()
{
if (\count($this->ids) > 0) {
return $this->ids[0];
}
}
/**
* Set a collection of IDs to use in the value of this Header.
*
* @param string[] $ids
*
* @throws Swift_RfcComplianceException
*/
public function setIds(array $ids)
{
$actualIds = [];
foreach ($ids as $id) {
$this->assertValidId($id);
$actualIds[] = $id;
}
$this->clearCachedValueIf($this->ids != $actualIds);
$this->ids = $actualIds;
}
/**
* Get the list of IDs used in this Header.
*
* @return string[]
*/
public function getIds()
{
return $this->ids;
}
/**
* Get the string value of the body in this Header.
*
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@see toString()} for that).
*
* @see toString()
*
* @throws Swift_RfcComplianceException
*
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
$angleAddrs = [];
foreach ($this->ids as $id) {
$angleAddrs[] = '<'.$this->addressEncoder->encodeString($id).'>';
}
$this->setCachedValue(implode(' ', $angleAddrs));
}
return $this->getCachedValue();
}
/**
* Throws an Exception if the id passed does not comply with RFC 2822.
*
* @param string $id
*
* @throws Swift_RfcComplianceException
*/
private function assertValidId($id)
{
$emailValidation = class_exists(MessageIDValidation::class) ? new MessageIDValidation() : new RFCValidation();
if (!$this->emailValidator->isValid($id, $emailValidation)) {
throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>');
}
}
}

View File

@ -0,0 +1,358 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
/**
* A Mailbox Address MIME Header for something like From or Sender.
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The mailboxes used in this Header.
*
* @var string[]
*/
private $mailboxes = [];
/**
* The strict EmailValidator.
*
* @var EmailValidator
*/
private $emailValidator;
private $addressEncoder;
/**
* Creates a new MailboxHeader with $name.
*
* @param string $name of Header
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null)
{
$this->setFieldName($name);
$this->setEncoder($encoder);
$this->emailValidator = $emailValidator;
$this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_MAILBOX;
}
/**
* Set the model for the field body.
*
* This method takes a string, or an array of addresses.
*
* @param mixed $model
*
* @throws Swift_RfcComplianceException
*/
public function setFieldBodyModel($model)
{
$this->setNameAddresses($model);
}
/**
* Get the model for the field body.
*
* This method returns an associative array like {@link getNameAddresses()}
*
* @throws Swift_RfcComplianceException
*
* @return array
*/
public function getFieldBodyModel()
{
return $this->getNameAddresses();
}
/**
* Set a list of mailboxes to be shown in this Header.
*
* The mailboxes can be a simple array of addresses, or an array of
* key=>value pairs where (email => personalName).
* Example:
* <code>
* <?php
* //Sets two mailboxes in the Header, one with a personal name
* $header->setNameAddresses(array(
* 'chris@swiftmailer.org' => 'Chris Corbyn',
* 'mark@swiftmailer.org' //No associated personal name
* ));
* ?>
* </code>
*
* @see __construct()
* @see setAddresses()
* @see setValue()
*
* @param string|string[] $mailboxes
*
* @throws Swift_RfcComplianceException
*/
public function setNameAddresses($mailboxes)
{
$this->mailboxes = $this->normalizeMailboxes((array) $mailboxes);
$this->setCachedValue(null); //Clear any cached value
}
/**
* Get the full mailbox list of this Header as an array of valid RFC 2822 strings.
*
* Example:
* <code>
* <?php
* $header = new Swift_Mime_Headers_MailboxHeader('From',
* array('chris@swiftmailer.org' => 'Chris Corbyn',
* 'mark@swiftmailer.org' => 'Mark Corbyn')
* );
* print_r($header->getNameAddressStrings());
* // array (
* // 0 => Chris Corbyn <chris@swiftmailer.org>,
* // 1 => Mark Corbyn <mark@swiftmailer.org>
* // )
* ?>
* </code>
*
* @see getNameAddresses()
* @see toString()
*
* @throws Swift_RfcComplianceException
*
* @return string[]
*/
public function getNameAddressStrings()
{
return $this->createNameAddressStrings($this->getNameAddresses());
}
/**
* Get all mailboxes in this Header as key=>value pairs.
*
* The key is the address and the value is the name (or null if none set).
* Example:
* <code>
* <?php
* $header = new Swift_Mime_Headers_MailboxHeader('From',
* array('chris@swiftmailer.org' => 'Chris Corbyn',
* 'mark@swiftmailer.org' => 'Mark Corbyn')
* );
* print_r($header->getNameAddresses());
* // array (
* // chris@swiftmailer.org => Chris Corbyn,
* // mark@swiftmailer.org => Mark Corbyn
* // )
* ?>
* </code>
*
* @see getAddresses()
* @see getNameAddressStrings()
*
* @return string[]
*/
public function getNameAddresses()
{
return $this->mailboxes;
}
/**
* Makes this Header represent a list of plain email addresses with no names.
*
* Example:
* <code>
* <?php
* //Sets three email addresses as the Header data
* $header->setAddresses(
* array('one@domain.tld', 'two@domain.tld', 'three@domain.tld')
* );
* ?>
* </code>
*
* @see setNameAddresses()
* @see setValue()
*
* @param string[] $addresses
*
* @throws Swift_RfcComplianceException
*/
public function setAddresses($addresses)
{
$this->setNameAddresses(array_values((array) $addresses));
}
/**
* Get all email addresses in this Header.
*
* @see getNameAddresses()
*
* @return string[]
*/
public function getAddresses()
{
return array_keys($this->mailboxes);
}
/**
* Remove one or more addresses from this Header.
*
* @param string|string[] $addresses
*/
public function removeAddresses($addresses)
{
$this->setCachedValue(null);
foreach ((array) $addresses as $address) {
unset($this->mailboxes[$address]);
}
}
/**
* Get the string value of the body in this Header.
*
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
*
* @see toString()
*
* @throws Swift_RfcComplianceException
*
* @return string
*/
public function getFieldBody()
{
// Compute the string value of the header only if needed
if (null === $this->getCachedValue()) {
$this->setCachedValue($this->createMailboxListString($this->mailboxes));
}
return $this->getCachedValue();
}
/**
* Normalizes a user-input list of mailboxes into consistent key=>value pairs.
*
* @param string[] $mailboxes
*
* @return string[]
*/
protected function normalizeMailboxes(array $mailboxes)
{
$actualMailboxes = [];
foreach ($mailboxes as $key => $value) {
if (\is_string($key)) {
//key is email addr
$address = $key;
$name = $value;
} else {
$address = $value;
$name = null;
}
$this->assertValidAddress($address);
$actualMailboxes[$address] = $name;
}
return $actualMailboxes;
}
/**
* Produces a compliant, formatted display-name based on the string given.
*
* @param string $displayName as displayed
* @param bool $shorten the first line to make remove for header name
*
* @return string
*/
protected function createDisplayNameString($displayName, $shorten = false)
{
return $this->createPhrase($this, $displayName, $this->getCharset(), $this->getEncoder(), $shorten);
}
/**
* Creates a string form of all the mailboxes in the passed array.
*
* @param string[] $mailboxes
*
* @throws Swift_RfcComplianceException
*
* @return string
*/
protected function createMailboxListString(array $mailboxes)
{
return implode(', ', $this->createNameAddressStrings($mailboxes));
}
/**
* Redefine the encoding requirements for mailboxes.
*
* All "specials" must be encoded as the full header value will not be quoted
*
* @see RFC 2822 3.2.1
*
* @param string $token
*
* @return bool
*/
protected function tokenNeedsEncoding($token)
{
return preg_match('/[()<>\[\]:;@\,."]/', $token) || parent::tokenNeedsEncoding($token);
}
/**
* Return an array of strings conforming the the name-addr spec of RFC 2822.
*
* @param string[] $mailboxes
*
* @return string[]
*/
private function createNameAddressStrings(array $mailboxes)
{
$strings = [];
foreach ($mailboxes as $email => $name) {
$mailboxStr = $this->addressEncoder->encodeString($email);
if (null !== $name) {
$nameStr = $this->createDisplayNameString($name, empty($strings));
$mailboxStr = $nameStr.' <'.$mailboxStr.'>';
}
$strings[] = $mailboxStr;
}
return $strings;
}
/**
* Throws an Exception if the address passed does not comply with RFC 2822.
*
* @param string $address
*
* @throws Swift_RfcComplianceException if invalid
*/
private function assertValidAddress($address)
{
if (!$this->emailValidator->isValid($address, new RFCValidation())) {
throw new Swift_RfcComplianceException('Address in mailbox given ['.$address.'] does not comply with RFC 2822, 3.6.2.');
}
}
}

View File

@ -0,0 +1,135 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An OpenDKIM Specific Header using only raw header datas without encoding.
*
* @author De Cock Xavier <xdecock@gmail.com>
*
* @deprecated since SwiftMailer 6.1.0; use Swift_Signers_DKIMSigner instead.
*/
class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
{
/**
* The value of this Header.
*
* @var string
*/
private $value;
/**
* The name of this Header.
*
* @var string
*/
private $fieldName;
/**
* @param string $name
*/
public function __construct($name)
{
$this->fieldName = $name;
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_TEXT;
}
/**
* Set the model for the field body.
*
* This method takes a string for the field value.
*
* @param string $model
*/
public function setFieldBodyModel($model)
{
$this->setValue($model);
}
/**
* Get the model for the field body.
*
* This method returns a string.
*
* @return string
*/
public function getFieldBodyModel()
{
return $this->getValue();
}
/**
* Get the (unencoded) value of this header.
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set the (unencoded) value of this header.
*
* @param string $value
*/
public function setValue($value)
{
$this->value = $value;
}
/**
* Get the value of this header prepared for rendering.
*
* @return string
*/
public function getFieldBody()
{
return $this->value;
}
/**
* Get this Header rendered as a RFC 2822 compliant string.
*
* @return string
*/
public function toString()
{
return $this->fieldName.': '.$this->value."\r\n";
}
/**
* Set the Header FieldName.
*
* @see Swift_Mime_Header::getFieldName()
*/
public function getFieldName()
{
return $this->fieldName;
}
/**
* Ignored.
*/
public function setCharset($charset)
{
}
}

View File

@ -0,0 +1,255 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An abstract base MIME Header.
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_UnstructuredHeader
{
/**
* RFC 2231's definition of a token.
*
* @var string
*/
const TOKEN_REGEX = '(?:[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7E]+)';
/**
* The Encoder used to encode the parameters.
*
* @var Swift_Encoder
*/
private $paramEncoder;
/**
* The parameters as an associative array.
*
* @var string[]
*/
private $params = [];
/**
* Creates a new ParameterizedHeader with $name.
*
* @param string $name
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null)
{
parent::__construct($name, $encoder);
$this->paramEncoder = $paramEncoder;
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_PARAMETERIZED;
}
/**
* Set the character set used in this Header.
*
* @param string $charset
*/
public function setCharset($charset)
{
parent::setCharset($charset);
if (isset($this->paramEncoder)) {
$this->paramEncoder->charsetChanged($charset);
}
}
/**
* Set the value of $parameter.
*
* @param string $parameter
* @param string $value
*/
public function setParameter($parameter, $value)
{
$this->setParameters(array_merge($this->getParameters(), [$parameter => $value]));
}
/**
* Get the value of $parameter.
*
* @param string $parameter
*
* @return string
*/
public function getParameter($parameter)
{
$params = $this->getParameters();
return $params[$parameter] ?? null;
}
/**
* Set an associative array of parameter names mapped to values.
*
* @param string[] $parameters
*/
public function setParameters(array $parameters)
{
$this->clearCachedValueIf($this->params != $parameters);
$this->params = $parameters;
}
/**
* Returns an associative array of parameter names mapped to values.
*
* @return string[]
*/
public function getParameters()
{
return $this->params;
}
/**
* Get the value of this header prepared for rendering.
*
* @return string
*/
public function getFieldBody() //TODO: Check caching here
{
$body = parent::getFieldBody();
foreach ($this->params as $name => $value) {
if (null !== $value) {
// Add the parameter
$body .= '; '.$this->createParameter($name, $value);
}
}
return $body;
}
/**
* Generate a list of all tokens in the final header.
*
* This doesn't need to be overridden in theory, but it is for implementation
* reasons to prevent potential breakage of attributes.
*
* @param string $string The string to tokenize
*
* @return array An array of tokens as strings
*/
protected function toTokens($string = null)
{
$tokens = parent::toTokens(parent::getFieldBody());
// Try creating any parameters
foreach ($this->params as $name => $value) {
if (null !== $value) {
// Add the semi-colon separator
$tokens[\count($tokens) - 1] .= ';';
$tokens = array_merge($tokens, $this->generateTokenLines(
' '.$this->createParameter($name, $value)
));
}
}
return $tokens;
}
/**
* Render a RFC 2047 compliant header parameter from the $name and $value.
*
* @param string $name
* @param string $value
*
* @return string
*/
private function createParameter($name, $value)
{
$origValue = $value;
$encoded = false;
// Allow room for parameter name, indices, "=" and DQUOTEs
$maxValueLength = $this->getMaxLineLength() - \strlen($name.'=*N"";') - 1;
$firstLineOffset = 0;
// If it's not already a valid parameter value...
if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) {
// TODO: text, or something else??
// ... and it's not ascii
if (!preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $value)) {
$encoded = true;
// Allow space for the indices, charset and language
$maxValueLength = $this->getMaxLineLength() - \strlen($name.'*N*="";') - 1;
$firstLineOffset = \strlen(
$this->getCharset()."'".$this->getLanguage()."'"
);
}
}
// Encode if we need to
if ($encoded || \strlen($value) > $maxValueLength) {
if (isset($this->paramEncoder)) {
$value = $this->paramEncoder->encodeString(
$origValue, $firstLineOffset, $maxValueLength, $this->getCharset()
);
} else {
// We have to go against RFC 2183/2231 in some areas for interoperability
$value = $this->getTokenAsEncodedWord($origValue);
$encoded = false;
}
}
$valueLines = isset($this->paramEncoder) ? explode("\r\n", $value) : [$value];
// Need to add indices
if (\count($valueLines) > 1) {
$paramLines = [];
foreach ($valueLines as $i => $line) {
$paramLines[] = $name.'*'.$i.
$this->getEndOfParameterValue($line, true, 0 == $i);
}
return implode(";\r\n ", $paramLines);
} else {
return $name.$this->getEndOfParameterValue(
$valueLines[0], $encoded, true
);
}
}
/**
* Returns the parameter value from the "=" and beyond.
*
* @param string $value to append
* @param bool $encoded
* @param bool $firstLine
*
* @return string
*/
private function getEndOfParameterValue($value, $encoded = false, $firstLine = false)
{
if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) {
$value = '"'.$value.'"';
}
$prepend = '=';
if ($encoded) {
$prepend = '*=';
if ($firstLine) {
$prepend = '*='.$this->getCharset()."'".$this->getLanguage().
"'";
}
}
return $prepend.$value;
}
}

View File

@ -0,0 +1,153 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
/**
* A Path Header in Swift Mailer, such a Return-Path.
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The address in this Header (if specified).
*
* @var string
*/
private $address;
/**
* The strict EmailValidator.
*
* @var EmailValidator
*/
private $emailValidator;
private $addressEncoder;
/**
* Creates a new PathHeader with the given $name.
*
* @param string $name
*/
public function __construct($name, EmailValidator $emailValidator, Swift_AddressEncoder $addressEncoder = null)
{
$this->setFieldName($name);
$this->emailValidator = $emailValidator;
$this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_PATH;
}
/**
* Set the model for the field body.
* This method takes a string for an address.
*
* @param string $model
*
* @throws Swift_RfcComplianceException
*/
public function setFieldBodyModel($model)
{
$this->setAddress($model);
}
/**
* Get the model for the field body.
* This method returns a string email address.
*
* @return mixed
*/
public function getFieldBodyModel()
{
return $this->getAddress();
}
/**
* Set the Address which should appear in this Header.
*
* @param string $address
*
* @throws Swift_RfcComplianceException
*/
public function setAddress($address)
{
if (null === $address) {
$this->address = null;
} elseif ('' == $address) {
$this->address = '';
} else {
$this->assertValidAddress($address);
$this->address = $address;
}
$this->setCachedValue(null);
}
/**
* Get the address which is used in this Header (if any).
*
* Null is returned if no address is set.
*
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Get the string value of the body in this Header.
*
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
*
* @see toString()
*
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
if (isset($this->address)) {
$address = $this->addressEncoder->encodeString($this->address);
$this->setCachedValue('<'.$address.'>');
}
}
return $this->getCachedValue();
}
/**
* Throws an Exception if the address passed does not comply with RFC 2822.
*
* @param string $address
*
* @throws Swift_RfcComplianceException If address is invalid
*/
private function assertValidAddress($address)
{
if (!$this->emailValidator->isValid($address, new RFCValidation())) {
throw new Swift_RfcComplianceException('Address set in PathHeader does not comply with addr-spec of RFC 2822.');
}
}
}

View File

@ -0,0 +1,109 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A Simple MIME Header.
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The value of this Header.
*
* @var string
*/
private $value;
/**
* Creates a new SimpleHeader with $name.
*
* @param string $name
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder)
{
$this->setFieldName($name);
$this->setEncoder($encoder);
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_TEXT;
}
/**
* Set the model for the field body.
*
* This method takes a string for the field value.
*
* @param string $model
*/
public function setFieldBodyModel($model)
{
$this->setValue($model);
}
/**
* Get the model for the field body.
*
* This method returns a string.
*
* @return string
*/
public function getFieldBodyModel()
{
return $this->getValue();
}
/**
* Get the (unencoded) value of this header.
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set the (unencoded) value of this header.
*
* @param string $value
*/
public function setValue($value)
{
$this->clearCachedValueIf($this->value != $value);
$this->value = $value;
}
/**
* Get the value of this header prepared for rendering.
*
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
$this->setCachedValue(
$this->encodeWords($this, $this->value)
);
}
return $this->getCachedValue();
}
}

View File

@ -0,0 +1,54 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Message ID generator.
*/
class Swift_Mime_IdGenerator implements Swift_IdGenerator
{
private $idRight;
/**
* @param string $idRight
*/
public function __construct($idRight)
{
$this->idRight = $idRight;
}
/**
* Returns the right-hand side of the "@" used in all generated IDs.
*
* @return string
*/
public function getIdRight()
{
return $this->idRight;
}
/**
* Sets the right-hand side of the "@" to use in all generated IDs.
*
* @param string $idRight
*/
public function setIdRight($idRight)
{
$this->idRight = $idRight;
}
/**
* @return string
*/
public function generateId()
{
// 32 hex values for the left part
return bin2hex(random_bytes(16)).'@'.$this->idRight;
}
}

View File

@ -0,0 +1,199 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A MIME part, in a multipart message.
*
* @author Chris Corbyn
*/
class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
{
/** The format parameter last specified by the user */
protected $userFormat;
/** The charset last specified by the user */
protected $userCharset;
/** The delsp parameter last specified by the user */
protected $userDelSp;
/** The nesting level of this MimePart */
private $nestingLevel = self::LEVEL_ALTERNATIVE;
/**
* Create a new MimePart with $headers, $encoder and $cache.
*
* @param string $charset
*/
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null)
{
parent::__construct($headers, $encoder, $cache, $idGenerator);
$this->setContentType('text/plain');
if (null !== $charset) {
$this->setCharset($charset);
}
}
/**
* Set the body of this entity, either as a string, or as an instance of
* {@link Swift_OutputByteStream}.
*
* @param mixed $body
* @param string $contentType optional
* @param string $charset optional
*
* @return $this
*/
public function setBody($body, $contentType = null, $charset = null)
{
if (isset($charset)) {
$this->setCharset($charset);
}
$body = $this->convertString($body);
parent::setBody($body, $contentType);
return $this;
}
/**
* Get the character set of this entity.
*
* @return string
*/
public function getCharset()
{
return $this->getHeaderParameter('Content-Type', 'charset');
}
/**
* Set the character set of this entity.
*
* @param string $charset
*
* @return $this
*/
public function setCharset($charset)
{
$this->setHeaderParameter('Content-Type', 'charset', $charset);
if ($charset !== $this->userCharset) {
$this->clearCache();
}
$this->userCharset = $charset;
parent::charsetChanged($charset);
return $this;
}
/**
* Get the format of this entity (i.e. flowed or fixed).
*
* @return string
*/
public function getFormat()
{
return $this->getHeaderParameter('Content-Type', 'format');
}
/**
* Set the format of this entity (flowed or fixed).
*
* @param string $format
*
* @return $this
*/
public function setFormat($format)
{
$this->setHeaderParameter('Content-Type', 'format', $format);
$this->userFormat = $format;
return $this;
}
/**
* Test if delsp is being used for this entity.
*
* @return bool
*/
public function getDelSp()
{
return 'yes' === $this->getHeaderParameter('Content-Type', 'delsp');
}
/**
* Turn delsp on or off for this entity.
*
* @param bool $delsp
*
* @return $this
*/
public function setDelSp($delsp = true)
{
$this->setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null);
$this->userDelSp = $delsp;
return $this;
}
/**
* Get the nesting level of this entity.
*
* @see LEVEL_TOP, LEVEL_ALTERNATIVE, LEVEL_MIXED, LEVEL_RELATED
*
* @return int
*/
public function getNestingLevel()
{
return $this->nestingLevel;
}
/**
* Receive notification that the charset has changed on this document, or a
* parent document.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->setCharset($charset);
}
/** Fix the content-type and encoding of this entity */
protected function fixHeaders()
{
parent::fixHeaders();
if (\count($this->getChildren())) {
$this->setHeaderParameter('Content-Type', 'charset', null);
$this->setHeaderParameter('Content-Type', 'format', null);
$this->setHeaderParameter('Content-Type', 'delsp', null);
} else {
$this->setCharset($this->userCharset);
$this->setFormat($this->userFormat);
$this->setDelSp($this->userDelSp);
}
}
/** Set the nesting level of this entity */
protected function setNestingLevel($level)
{
$this->nestingLevel = $level;
}
/** Encode charset when charset is not utf-8 */
protected function convertString($string)
{
$charset = strtolower($this->getCharset());
if (!\in_array($charset, ['utf-8', 'iso-8859-1', 'iso-8859-15', ''])) {
return mb_convert_encoding($string, $charset, 'utf-8');
}
return $string;
}
}

View File

@ -0,0 +1,194 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Egulias\EmailValidator\EmailValidator;
/**
* Creates MIME headers.
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_CharsetObserver
{
/** The HeaderEncoder used by these headers */
private $encoder;
/** The Encoder used by parameters */
private $paramEncoder;
/** Strict EmailValidator */
private $emailValidator;
/** The charset of created Headers */
private $charset;
/** Swift_AddressEncoder */
private $addressEncoder;
/**
* Creates a new SimpleHeaderFactory using $encoder and $paramEncoder.
*
* @param string|null $charset
*/
public function __construct(Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder, EmailValidator $emailValidator, $charset = null, Swift_AddressEncoder $addressEncoder = null)
{
$this->encoder = $encoder;
$this->paramEncoder = $paramEncoder;
$this->emailValidator = $emailValidator;
$this->charset = $charset;
$this->addressEncoder = $addressEncoder ?? new Swift_AddressEncoder_IdnAddressEncoder();
}
/**
* Create a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string|null $addresses
*
* @return Swift_Mime_Header
*/
public function createMailboxHeader($name, $addresses = null)
{
$header = new Swift_Mime_Headers_MailboxHeader($name, $this->encoder, $this->emailValidator, $this->addressEncoder);
if (isset($addresses)) {
$header->setFieldBodyModel($addresses);
}
$this->setHeaderCharset($header);
return $header;
}
/**
* Create a new Date header using $dateTime.
*
* @param string $name
*
* @return Swift_Mime_Header
*/
public function createDateHeader($name, DateTimeInterface $dateTime = null)
{
$header = new Swift_Mime_Headers_DateHeader($name);
if (isset($dateTime)) {
$header->setFieldBodyModel($dateTime);
}
$this->setHeaderCharset($header);
return $header;
}
/**
* Create a new basic text header with $name and $value.
*
* @param string $name
* @param string $value
*
* @return Swift_Mime_Header
*/
public function createTextHeader($name, $value = null)
{
$header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->encoder);
if (isset($value)) {
$header->setFieldBodyModel($value);
}
$this->setHeaderCharset($header);
return $header;
}
/**
* Create a new ParameterizedHeader with $name, $value and $params.
*
* @param string $name
* @param string $value
* @param array $params
*
* @return Swift_Mime_Headers_ParameterizedHeader
*/
public function createParameterizedHeader($name, $value = null, $params = [])
{
$header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->encoder, ('content-disposition' == strtolower($name)) ? $this->paramEncoder : null);
if (isset($value)) {
$header->setFieldBodyModel($value);
}
foreach ($params as $k => $v) {
$header->setParameter($k, $v);
}
$this->setHeaderCharset($header);
return $header;
}
/**
* Create a new ID header for Message-ID or Content-ID.
*
* @param string $name
* @param string|array $ids
*
* @return Swift_Mime_Header
*/
public function createIdHeader($name, $ids = null)
{
$header = new Swift_Mime_Headers_IdentificationHeader($name, $this->emailValidator);
if (isset($ids)) {
$header->setFieldBodyModel($ids);
}
$this->setHeaderCharset($header);
return $header;
}
/**
* Create a new Path header with an address (path) in it.
*
* @param string $name
* @param string $path
*
* @return Swift_Mime_Header
*/
public function createPathHeader($name, $path = null)
{
$header = new Swift_Mime_Headers_PathHeader($name, $this->emailValidator);
if (isset($path)) {
$header->setFieldBodyModel($path);
}
$this->setHeaderCharset($header);
return $header;
}
/**
* Notify this observer that the entity's charset has changed.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->charset = $charset;
$this->encoder->charsetChanged($charset);
$this->paramEncoder->charsetChanged($charset);
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->encoder = clone $this->encoder;
$this->paramEncoder = clone $this->paramEncoder;
}
/** Apply the charset to the Header */
private function setHeaderCharset(Swift_Mime_Header $header)
{
if (isset($this->charset)) {
$header->setCharset($this->charset);
}
}
}

View File

@ -0,0 +1,399 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A collection of MIME headers.
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
{
/** HeaderFactory */
private $factory;
/** Collection of set Headers */
private $headers = [];
/** Field ordering details */
private $order = [];
/** List of fields which are required to be displayed */
private $required = [];
/** The charset used by Headers */
private $charset;
/**
* Create a new SimpleHeaderSet with the given $factory.
*
* @param string $charset
*/
public function __construct(Swift_Mime_SimpleHeaderFactory $factory, $charset = null)
{
$this->factory = $factory;
if (isset($charset)) {
$this->setCharset($charset);
}
}
public function newInstance()
{
return new self($this->factory);
}
/**
* Set the charset used by these headers.
*
* @param string $charset
*/
public function setCharset($charset)
{
$this->charset = $charset;
$this->factory->charsetChanged($charset);
$this->notifyHeadersOfCharset($charset);
}
/**
* Add a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string $addresses
*/
public function addMailboxHeader($name, $addresses = null)
{
$this->storeHeader($name, $this->factory->createMailboxHeader($name, $addresses));
}
/**
* Add a new Date header using $dateTime.
*
* @param string $name
*/
public function addDateHeader($name, DateTimeInterface $dateTime = null)
{
$this->storeHeader($name, $this->factory->createDateHeader($name, $dateTime));
}
/**
* Add a new basic text header with $name and $value.
*
* @param string $name
* @param string $value
*/
public function addTextHeader($name, $value = null)
{
$this->storeHeader($name, $this->factory->createTextHeader($name, $value));
}
/**
* Add a new ParameterizedHeader with $name, $value and $params.
*
* @param string $name
* @param string $value
* @param array $params
*/
public function addParameterizedHeader($name, $value = null, $params = [])
{
$this->storeHeader($name, $this->factory->createParameterizedHeader($name, $value, $params));
}
/**
* Add a new ID header for Message-ID or Content-ID.
*
* @param string $name
* @param string|array $ids
*/
public function addIdHeader($name, $ids = null)
{
$this->storeHeader($name, $this->factory->createIdHeader($name, $ids));
}
/**
* Add a new Path header with an address (path) in it.
*
* @param string $name
* @param string $path
*/
public function addPathHeader($name, $path = null)
{
$this->storeHeader($name, $this->factory->createPathHeader($name, $path));
}
/**
* Returns true if at least one header with the given $name exists.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*
* @return bool
*/
public function has($name, $index = 0)
{
$lowerName = strtolower($name);
if (!\array_key_exists($lowerName, $this->headers)) {
return false;
}
if (\func_num_args() < 2) {
// index was not specified, so we only need to check that there is at least one header value set
return (bool) \count($this->headers[$lowerName]);
}
return \array_key_exists($index, $this->headers[$lowerName]);
}
/**
* Set a header in the HeaderSet.
*
* The header may be a previously fetched header via {@link get()} or it may
* be one that has been created separately.
*
* If $index is specified, the header will be inserted into the set at this
* offset.
*
* @param int $index
*/
public function set(Swift_Mime_Header $header, $index = 0)
{
$this->storeHeader($header->getFieldName(), $header, $index);
}
/**
* Get the header with the given $name.
*
* If multiple headers match, the actual one may be specified by $index.
* Returns NULL if none present.
*
* @param string $name
* @param int $index
*
* @return Swift_Mime_Header|null
*/
public function get($name, $index = 0)
{
$name = strtolower($name);
if (\func_num_args() < 2) {
if ($this->has($name)) {
$values = array_values($this->headers[$name]);
return array_shift($values);
}
} else {
if ($this->has($name, $index)) {
return $this->headers[$name][$index];
}
}
}
/**
* Get all headers with the given $name.
*
* @param string $name
*
* @return array
*/
public function getAll($name = null)
{
if (!isset($name)) {
$headers = [];
foreach ($this->headers as $collection) {
$headers = array_merge($headers, $collection);
}
return $headers;
}
$lowerName = strtolower($name);
if (!\array_key_exists($lowerName, $this->headers)) {
return [];
}
return $this->headers[$lowerName];
}
/**
* Return the name of all Headers.
*
* @return array
*/
public function listAll()
{
$headers = $this->headers;
if ($this->canSort()) {
uksort($headers, [$this, 'sortHeaders']);
}
return array_keys($headers);
}
/**
* Remove the header with the given $name if it's set.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*/
public function remove($name, $index = 0)
{
$lowerName = strtolower($name);
unset($this->headers[$lowerName][$index]);
}
/**
* Remove all headers with the given $name.
*
* @param string $name
*/
public function removeAll($name)
{
$lowerName = strtolower($name);
unset($this->headers[$lowerName]);
}
/**
* Define a list of Header names as an array in the correct order.
*
* These Headers will be output in the given order where present.
*/
public function defineOrdering(array $sequence)
{
$this->order = array_flip(array_map('strtolower', $sequence));
}
/**
* Set a list of header names which must always be displayed when set.
*
* Usually headers without a field value won't be output unless set here.
*/
public function setAlwaysDisplayed(array $names)
{
$this->required = array_flip(array_map('strtolower', $names));
}
/**
* Notify this observer that the entity's charset has changed.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->setCharset($charset);
}
/**
* Returns a string with a representation of all headers.
*
* @return string
*/
public function toString()
{
$string = '';
$headers = $this->headers;
if ($this->canSort()) {
uksort($headers, [$this, 'sortHeaders']);
}
foreach ($headers as $collection) {
foreach ($collection as $header) {
if ($this->isDisplayed($header) || '' != $header->getFieldBody()) {
$string .= $header->toString();
}
}
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
/** Save a Header to the internal collection */
private function storeHeader($name, Swift_Mime_Header $header, $offset = null)
{
if (!isset($this->headers[strtolower($name)])) {
$this->headers[strtolower($name)] = [];
}
if (!isset($offset)) {
$this->headers[strtolower($name)][] = $header;
} else {
$this->headers[strtolower($name)][$offset] = $header;
}
}
/** Test if the headers can be sorted */
private function canSort()
{
return \count($this->order) > 0;
}
/** uksort() algorithm for Header ordering */
private function sortHeaders($a, $b)
{
$lowerA = strtolower($a);
$lowerB = strtolower($b);
$aPos = \array_key_exists($lowerA, $this->order) ? $this->order[$lowerA] : -1;
$bPos = \array_key_exists($lowerB, $this->order) ? $this->order[$lowerB] : -1;
if (-1 === $aPos && -1 === $bPos) {
// just be sure to be determinist here
return $a > $b ? -1 : 1;
}
if (-1 == $aPos) {
return 1;
} elseif (-1 == $bPos) {
return -1;
}
return $aPos < $bPos ? -1 : 1;
}
/** Test if the given Header is always displayed */
private function isDisplayed(Swift_Mime_Header $header)
{
return \array_key_exists(strtolower($header->getFieldName()), $this->required);
}
/** Notify all Headers of the new charset */
private function notifyHeadersOfCharset($charset)
{
foreach ($this->headers as $headerGroup) {
foreach ($headerGroup as $header) {
$header->setCharset($charset);
}
}
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->factory = clone $this->factory;
foreach ($this->headers as $groupKey => $headerGroup) {
foreach ($headerGroup as $key => $header) {
$this->headers[$groupKey][$key] = clone $header;
}
}
}
}

View File

@ -0,0 +1,642 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* The default email message class.
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
{
const PRIORITY_HIGHEST = 1;
const PRIORITY_HIGH = 2;
const PRIORITY_NORMAL = 3;
const PRIORITY_LOW = 4;
const PRIORITY_LOWEST = 5;
/**
* Create a new SimpleMessage with $headers, $encoder and $cache.
*
* @param string $charset
*/
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null)
{
parent::__construct($headers, $encoder, $cache, $idGenerator, $charset);
$this->getHeaders()->defineOrdering([
'Return-Path',
'Received',
'DKIM-Signature',
'DomainKey-Signature',
'Sender',
'Message-ID',
'Date',
'Subject',
'From',
'Reply-To',
'To',
'Cc',
'Bcc',
'MIME-Version',
'Content-Type',
'Content-Transfer-Encoding',
]);
$this->getHeaders()->setAlwaysDisplayed(['Date', 'Message-ID', 'From']);
$this->getHeaders()->addTextHeader('MIME-Version', '1.0');
$this->setDate(new DateTimeImmutable());
$this->setId($this->getId());
$this->getHeaders()->addMailboxHeader('From');
}
/**
* Always returns {@link LEVEL_TOP} for a message instance.
*
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_TOP;
}
/**
* Set the subject of this message.
*
* @param string $subject
*
* @return $this
*/
public function setSubject($subject)
{
if (!$this->setHeaderFieldModel('Subject', $subject)) {
$this->getHeaders()->addTextHeader('Subject', $subject);
}
return $this;
}
/**
* Get the subject of this message.
*
* @return string
*/
public function getSubject()
{
return $this->getHeaderFieldModel('Subject');
}
/**
* Set the date at which this message was created.
*
* @return $this
*/
public function setDate(DateTimeInterface $dateTime)
{
if (!$this->setHeaderFieldModel('Date', $dateTime)) {
$this->getHeaders()->addDateHeader('Date', $dateTime);
}
return $this;
}
/**
* Get the date at which this message was created.
*
* @return DateTimeInterface
*/
public function getDate()
{
return $this->getHeaderFieldModel('Date');
}
/**
* Set the return-path (the bounce address) of this message.
*
* @param string $address
*
* @return $this
*/
public function setReturnPath($address)
{
if (!$this->setHeaderFieldModel('Return-Path', $address)) {
$this->getHeaders()->addPathHeader('Return-Path', $address);
}
return $this;
}
/**
* Get the return-path (bounce address) of this message.
*
* @return string
*/
public function getReturnPath()
{
return $this->getHeaderFieldModel('Return-Path');
}
/**
* Set the sender of this message.
*
* This does not override the From field, but it has a higher significance.
*
* @param string $address
* @param string $name optional
*
* @return $this
*/
public function setSender($address, $name = null)
{
if (!\is_array($address) && isset($name)) {
$address = [$address => $name];
}
if (!$this->setHeaderFieldModel('Sender', (array) $address)) {
$this->getHeaders()->addMailboxHeader('Sender', (array) $address);
}
return $this;
}
/**
* Get the sender of this message.
*
* @return string
*/
public function getSender()
{
return $this->getHeaderFieldModel('Sender');
}
/**
* Add a From: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*
* @return $this
*/
public function addFrom($address, $name = null)
{
$current = $this->getFrom();
$current[$address] = $name;
return $this->setFrom($current);
}
/**
* Set the from address of this message.
*
* You may pass an array of addresses if this message is from multiple people.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param string|array $addresses
* @param string $name optional
*
* @return $this
*/
public function setFrom($addresses, $name = null)
{
if (!\is_array($addresses) && isset($name)) {
$addresses = [$addresses => $name];
}
if (!$this->setHeaderFieldModel('From', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('From', (array) $addresses);
}
return $this;
}
/**
* Get the from address of this message.
*
* @return mixed
*/
public function getFrom()
{
return $this->getHeaderFieldModel('From');
}
/**
* Add a Reply-To: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*
* @return $this
*/
public function addReplyTo($address, $name = null)
{
$current = $this->getReplyTo();
$current[$address] = $name;
return $this->setReplyTo($current);
}
/**
* Set the reply-to address of this message.
*
* You may pass an array of addresses if replies will go to multiple people.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*
* @return $this
*/
public function setReplyTo($addresses, $name = null)
{
if (!\is_array($addresses) && isset($name)) {
$addresses = [$addresses => $name];
}
if (!$this->setHeaderFieldModel('Reply-To', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses);
}
return $this;
}
/**
* Get the reply-to address of this message.
*
* @return string
*/
public function getReplyTo()
{
return $this->getHeaderFieldModel('Reply-To');
}
/**
* Add a To: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*
* @return $this
*/
public function addTo($address, $name = null)
{
$current = $this->getTo();
$current[$address] = $name;
return $this->setTo($current);
}
/**
* Set the to addresses of this message.
*
* If multiple recipients will receive the message an array should be used.
* Example: array('receiver@domain.org', 'other@domain.org' => 'A name')
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*
* @return $this
*/
public function setTo($addresses, $name = null)
{
if (!\is_array($addresses) && isset($name)) {
$addresses = [$addresses => $name];
}
if (!$this->setHeaderFieldModel('To', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('To', (array) $addresses);
}
return $this;
}
/**
* Get the To addresses of this message.
*
* @return array
*/
public function getTo()
{
return $this->getHeaderFieldModel('To');
}
/**
* Add a Cc: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*
* @return $this
*/
public function addCc($address, $name = null)
{
$current = $this->getCc();
$current[$address] = $name;
return $this->setCc($current);
}
/**
* Set the Cc addresses of this message.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*
* @return $this
*/
public function setCc($addresses, $name = null)
{
if (!\is_array($addresses) && isset($name)) {
$addresses = [$addresses => $name];
}
if (!$this->setHeaderFieldModel('Cc', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Cc', (array) $addresses);
}
return $this;
}
/**
* Get the Cc address of this message.
*
* @return array
*/
public function getCc()
{
return $this->getHeaderFieldModel('Cc');
}
/**
* Add a Bcc: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*
* @return $this
*/
public function addBcc($address, $name = null)
{
$current = $this->getBcc();
$current[$address] = $name;
return $this->setBcc($current);
}
/**
* Set the Bcc addresses of this message.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*
* @return $this
*/
public function setBcc($addresses, $name = null)
{
if (!\is_array($addresses) && isset($name)) {
$addresses = [$addresses => $name];
}
if (!$this->setHeaderFieldModel('Bcc', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses);
}
return $this;
}
/**
* Get the Bcc addresses of this message.
*
* @return array
*/
public function getBcc()
{
return $this->getHeaderFieldModel('Bcc');
}
/**
* Set the priority of this message.
*
* The value is an integer where 1 is the highest priority and 5 is the lowest.
*
* @param int $priority
*
* @return $this
*/
public function setPriority($priority)
{
$priorityMap = [
self::PRIORITY_HIGHEST => 'Highest',
self::PRIORITY_HIGH => 'High',
self::PRIORITY_NORMAL => 'Normal',
self::PRIORITY_LOW => 'Low',
self::PRIORITY_LOWEST => 'Lowest',
];
$pMapKeys = array_keys($priorityMap);
if ($priority > max($pMapKeys)) {
$priority = max($pMapKeys);
} elseif ($priority < min($pMapKeys)) {
$priority = min($pMapKeys);
}
if (!$this->setHeaderFieldModel('X-Priority',
sprintf('%d (%s)', $priority, $priorityMap[$priority]))) {
$this->getHeaders()->addTextHeader('X-Priority',
sprintf('%d (%s)', $priority, $priorityMap[$priority]));
}
return $this;
}
/**
* Get the priority of this message.
*
* The returned value is an integer where 1 is the highest priority and 5
* is the lowest.
*
* @return int
*/
public function getPriority()
{
list($priority) = sscanf($this->getHeaderFieldModel('X-Priority'),
'%[1-5]'
);
return $priority ?? 3;
}
/**
* Ask for a delivery receipt from the recipient to be sent to $addresses.
*
* @param array $addresses
*
* @return $this
*/
public function setReadReceiptTo($addresses)
{
if (!$this->setHeaderFieldModel('Disposition-Notification-To', $addresses)) {
$this->getHeaders()
->addMailboxHeader('Disposition-Notification-To', $addresses);
}
return $this;
}
/**
* Get the addresses to which a read-receipt will be sent.
*
* @return string
*/
public function getReadReceiptTo()
{
return $this->getHeaderFieldModel('Disposition-Notification-To');
}
/**
* Attach a {@link Swift_Mime_SimpleMimeEntity} such as an Attachment or MimePart.
*
* @return $this
*/
public function attach(Swift_Mime_SimpleMimeEntity $entity)
{
$this->setChildren(array_merge($this->getChildren(), [$entity]));
return $this;
}
/**
* Remove an already attached entity.
*
* @return $this
*/
public function detach(Swift_Mime_SimpleMimeEntity $entity)
{
$newChildren = [];
foreach ($this->getChildren() as $child) {
if ($entity !== $child) {
$newChildren[] = $child;
}
}
$this->setChildren($newChildren);
return $this;
}
/**
* Attach a {@link Swift_Mime_SimpleMimeEntity} and return it's CID source.
*
* This method should be used when embedding images or other data in a message.
*
* @return string
*/
public function embed(Swift_Mime_SimpleMimeEntity $entity)
{
$this->attach($entity);
return 'cid:'.$entity->getId();
}
/**
* Get this message as a complete string.
*
* @return string
*/
public function toString()
{
if (\count($children = $this->getChildren()) > 0 && '' != $this->getBody()) {
$this->setChildren(array_merge([$this->becomeMimePart()], $children));
$string = parent::toString();
$this->setChildren($children);
} else {
$string = parent::toString();
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @see toString()
*
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* Write this message to a {@link Swift_InputByteStream}.
*/
public function toByteStream(Swift_InputByteStream $is)
{
if (\count($children = $this->getChildren()) > 0 && '' != $this->getBody()) {
$this->setChildren(array_merge([$this->becomeMimePart()], $children));
parent::toByteStream($is);
$this->setChildren($children);
} else {
parent::toByteStream($is);
}
}
/** @see Swift_Mime_SimpleMimeEntity::getIdField() */
protected function getIdField()
{
return 'Message-ID';
}
/** Turn the body of this message into a child of itself if needed */
protected function becomeMimePart()
{
$part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(),
$this->getCache(), $this->getIdGenerator(), $this->userCharset
);
$part->setContentType($this->userContentType);
$part->setBody($this->getBody());
$part->setFormat($this->userFormat);
$part->setDelSp($this->userDelSp);
$part->setNestingLevel($this->getTopNestingLevel());
return $part;
}
/** Get the highest nesting level nested inside this message */
private function getTopNestingLevel()
{
$highestLevel = $this->getNestingLevel();
foreach ($this->getChildren() as $child) {
$childLevel = $child->getNestingLevel();
if ($highestLevel < $childLevel) {
$highestLevel = $childLevel;
}
}
return $highestLevel;
}
}

View File

@ -0,0 +1,826 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A MIME entity, in a multipart message.
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleMimeEntity implements Swift_Mime_CharsetObserver, Swift_Mime_EncodingObserver
{
/** Main message document; there can only be one of these */
const LEVEL_TOP = 16;
/** An entity which nests with the same precedence as an attachment */
const LEVEL_MIXED = 256;
/** An entity which nests with the same precedence as a mime part */
const LEVEL_ALTERNATIVE = 4096;
/** An entity which nests with the same precedence as embedded content */
const LEVEL_RELATED = 65536;
/** A collection of Headers for this mime entity */
private $headers;
/** The body as a string, or a stream */
private $body;
/** The encoder that encodes the body into a streamable format */
private $encoder;
/** Message ID generator */
private $idGenerator;
/** A mime boundary, if any is used */
private $boundary;
/** Mime types to be used based on the nesting level */
private $compositeRanges = [
'multipart/mixed' => [self::LEVEL_TOP, self::LEVEL_MIXED],
'multipart/alternative' => [self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE],
'multipart/related' => [self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED],
];
/** A set of filter rules to define what level an entity should be nested at */
private $compoundLevelFilters = [];
/** The nesting level of this entity */
private $nestingLevel = self::LEVEL_ALTERNATIVE;
/** A KeyCache instance used during encoding and streaming */
private $cache;
/** Direct descendants of this entity */
private $immediateChildren = [];
/** All descendants of this entity */
private $children = [];
/** The maximum line length of the body of this entity */
private $maxLineLength = 78;
/** The order in which alternative mime types should appear */
private $alternativePartOrder = [
'text/plain' => 1,
'text/html' => 2,
'multipart/related' => 3,
];
/** The CID of this entity */
private $id;
/** The key used for accessing the cache */
private $cacheKey;
protected $userContentType;
/**
* Create a new SimpleMimeEntity with $headers, $encoder and $cache.
*/
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator)
{
$this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values
$this->cache = $cache;
$this->headers = $headers;
$this->idGenerator = $idGenerator;
$this->setEncoder($encoder);
$this->headers->defineOrdering(['Content-Type', 'Content-Transfer-Encoding']);
// This array specifies that, when the entire MIME document contains
// $compoundLevel, then for each child within $level, if its Content-Type
// is $contentType then it should be treated as if it's level is
// $neededLevel instead. I tried to write that unambiguously! :-\
// Data Structure:
// array (
// $compoundLevel => array(
// $level => array(
// $contentType => $neededLevel
// )
// )
// )
$this->compoundLevelFilters = [
(self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => [
self::LEVEL_ALTERNATIVE => [
'text/plain' => self::LEVEL_ALTERNATIVE,
'text/html' => self::LEVEL_RELATED,
],
],
];
$this->id = $this->idGenerator->generateId();
}
/**
* Generate a new Content-ID or Message-ID for this MIME entity.
*
* @return string
*/
public function generateId()
{
$this->setId($this->idGenerator->generateId());
return $this->id;
}
/**
* Get the {@link Swift_Mime_SimpleHeaderSet} for this entity.
*
* @return Swift_Mime_SimpleHeaderSet
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get the nesting level of this entity.
*
* @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE
*
* @return int
*/
public function getNestingLevel()
{
return $this->nestingLevel;
}
/**
* Get the Content-type of this entity.
*
* @return string
*/
public function getContentType()
{
return $this->getHeaderFieldModel('Content-Type');
}
/**
* Get the Body Content-type of this entity.
*
* @return string
*/
public function getBodyContentType()
{
return $this->userContentType;
}
/**
* Set the Content-type of this entity.
*
* @param string $type
*
* @return $this
*/
public function setContentType($type)
{
$this->setContentTypeInHeaders($type);
// Keep track of the value so that if the content-type changes automatically
// due to added child entities, it can be restored if they are later removed
$this->userContentType = $type;
return $this;
}
/**
* Get the CID of this entity.
*
* The CID will only be present in headers if a Content-ID header is present.
*
* @return string
*/
public function getId()
{
$tmp = (array) $this->getHeaderFieldModel($this->getIdField());
return $this->headers->has($this->getIdField()) ? current($tmp) : $this->id;
}
/**
* Set the CID of this entity.
*
* @param string $id
*
* @return $this
*/
public function setId($id)
{
if (!$this->setHeaderFieldModel($this->getIdField(), $id)) {
$this->headers->addIdHeader($this->getIdField(), $id);
}
$this->id = $id;
return $this;
}
/**
* Get the description of this entity.
*
* This value comes from the Content-Description header if set.
*
* @return string
*/
public function getDescription()
{
return $this->getHeaderFieldModel('Content-Description');
}
/**
* Set the description of this entity.
*
* This method sets a value in the Content-ID header.
*
* @param string $description
*
* @return $this
*/
public function setDescription($description)
{
if (!$this->setHeaderFieldModel('Content-Description', $description)) {
$this->headers->addTextHeader('Content-Description', $description);
}
return $this;
}
/**
* Get the maximum line length of the body of this entity.
*
* @return int
*/
public function getMaxLineLength()
{
return $this->maxLineLength;
}
/**
* Set the maximum line length of lines in this body.
*
* Though not enforced by the library, lines should not exceed 1000 chars.
*
* @param int $length
*
* @return $this
*/
public function setMaxLineLength($length)
{
$this->maxLineLength = $length;
return $this;
}
/**
* Get all children added to this entity.
*
* @return Swift_Mime_SimpleMimeEntity[]
*/
public function getChildren()
{
return $this->children;
}
/**
* Set all children of this entity.
*
* @param Swift_Mime_SimpleMimeEntity[] $children
* @param int $compoundLevel For internal use only
*
* @return $this
*/
public function setChildren(array $children, $compoundLevel = null)
{
// TODO: Try to refactor this logic
$compoundLevel = $compoundLevel ?? $this->getCompoundLevel($children);
$immediateChildren = [];
$grandchildren = [];
$newContentType = $this->userContentType;
foreach ($children as $child) {
$level = $this->getNeededChildLevel($child, $compoundLevel);
if (empty($immediateChildren)) {
//first iteration
$immediateChildren = [$child];
} else {
$nextLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel);
if ($nextLevel == $level) {
$immediateChildren[] = $child;
} elseif ($level < $nextLevel) {
// Re-assign immediateChildren to grandchildren
$grandchildren = array_merge($grandchildren, $immediateChildren);
// Set new children
$immediateChildren = [$child];
} else {
$grandchildren[] = $child;
}
}
}
if ($immediateChildren) {
$lowestLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel);
// Determine which composite media type is needed to accommodate the
// immediate children
foreach ($this->compositeRanges as $mediaType => $range) {
if ($lowestLevel > $range[0] && $lowestLevel <= $range[1]) {
$newContentType = $mediaType;
break;
}
}
// Put any grandchildren in a subpart
if (!empty($grandchildren)) {
$subentity = $this->createChild();
$subentity->setNestingLevel($lowestLevel);
$subentity->setChildren($grandchildren, $compoundLevel);
array_unshift($immediateChildren, $subentity);
}
}
$this->immediateChildren = $immediateChildren;
$this->children = $children;
$this->setContentTypeInHeaders($newContentType);
$this->fixHeaders();
$this->sortChildren();
return $this;
}
/**
* Get the body of this entity as a string.
*
* @return string
*/
public function getBody()
{
return $this->body instanceof Swift_OutputByteStream ? $this->readStream($this->body) : $this->body;
}
/**
* Set the body of this entity, either as a string, or as an instance of
* {@link Swift_OutputByteStream}.
*
* @param mixed $body
* @param string $contentType optional
*
* @return $this
*/
public function setBody($body, $contentType = null)
{
if ($body !== $this->body) {
$this->clearCache();
}
$this->body = $body;
if (null !== $contentType) {
$this->setContentType($contentType);
}
return $this;
}
/**
* Get the encoder used for the body of this entity.
*
* @return Swift_Mime_ContentEncoder
*/
public function getEncoder()
{
return $this->encoder;
}
/**
* Set the encoder used for the body of this entity.
*
* @return $this
*/
public function setEncoder(Swift_Mime_ContentEncoder $encoder)
{
if ($encoder !== $this->encoder) {
$this->clearCache();
}
$this->encoder = $encoder;
$this->setEncoding($encoder->getName());
$this->notifyEncoderChanged($encoder);
return $this;
}
/**
* Get the boundary used to separate children in this entity.
*
* @return string
*/
public function getBoundary()
{
if (!isset($this->boundary)) {
$this->boundary = '_=_swift_'.time().'_'.bin2hex(random_bytes(16)).'_=_';
}
return $this->boundary;
}
/**
* Set the boundary used to separate children in this entity.
*
* @param string $boundary
*
* @throws Swift_RfcComplianceException
*
* @return $this
*/
public function setBoundary($boundary)
{
$this->assertValidBoundary($boundary);
$this->boundary = $boundary;
return $this;
}
/**
* Receive notification that the charset of this entity, or a parent entity
* has changed.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->notifyCharsetChanged($charset);
}
/**
* Receive notification that the encoder of this entity or a parent entity
* has changed.
*/
public function encoderChanged(Swift_Mime_ContentEncoder $encoder)
{
$this->notifyEncoderChanged($encoder);
}
/**
* Get this entire entity as a string.
*
* @return string
*/
public function toString()
{
$string = $this->headers->toString();
$string .= $this->bodyToString();
return $string;
}
/**
* Get this entire entity as a string.
*
* @return string
*/
protected function bodyToString()
{
$string = '';
if (isset($this->body) && empty($this->immediateChildren)) {
if ($this->cache->hasKey($this->cacheKey, 'body')) {
$body = $this->cache->getString($this->cacheKey, 'body');
} else {
$body = "\r\n".$this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength());
$this->cache->setString($this->cacheKey, 'body', $body, Swift_KeyCache::MODE_WRITE);
}
$string .= $body;
}
if (!empty($this->immediateChildren)) {
foreach ($this->immediateChildren as $child) {
$string .= "\r\n\r\n--".$this->getBoundary()."\r\n";
$string .= $child->toString();
}
$string .= "\r\n\r\n--".$this->getBoundary()."--\r\n";
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @see toString()
*
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* Write this entire entity to a {@see Swift_InputByteStream}.
*/
public function toByteStream(Swift_InputByteStream $is)
{
$is->write($this->headers->toString());
$is->commit();
$this->bodyToByteStream($is);
}
/**
* Write this entire entity to a {@link Swift_InputByteStream}.
*/
protected function bodyToByteStream(Swift_InputByteStream $is)
{
if (empty($this->immediateChildren)) {
if (isset($this->body)) {
if ($this->cache->hasKey($this->cacheKey, 'body')) {
$this->cache->exportToByteStream($this->cacheKey, 'body', $is);
} else {
$cacheIs = $this->cache->getInputByteStream($this->cacheKey, 'body');
if ($cacheIs) {
$is->bind($cacheIs);
}
$is->write("\r\n");
if ($this->body instanceof Swift_OutputByteStream) {
$this->body->setReadPointer(0);
$this->encoder->encodeByteStream($this->body, $is, 0, $this->getMaxLineLength());
} else {
$is->write($this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()));
}
if ($cacheIs) {
$is->unbind($cacheIs);
}
}
}
}
if (!empty($this->immediateChildren)) {
foreach ($this->immediateChildren as $child) {
$is->write("\r\n\r\n--".$this->getBoundary()."\r\n");
$child->toByteStream($is);
}
$is->write("\r\n\r\n--".$this->getBoundary()."--\r\n");
}
}
/**
* Get the name of the header that provides the ID of this entity.
*/
protected function getIdField()
{
return 'Content-ID';
}
/**
* Get the model data (usually an array or a string) for $field.
*/
protected function getHeaderFieldModel($field)
{
if ($this->headers->has($field)) {
return $this->headers->get($field)->getFieldBodyModel();
}
}
/**
* Set the model data for $field.
*/
protected function setHeaderFieldModel($field, $model)
{
if ($this->headers->has($field)) {
$this->headers->get($field)->setFieldBodyModel($model);
return true;
}
return false;
}
/**
* Get the parameter value of $parameter on $field header.
*/
protected function getHeaderParameter($field, $parameter)
{
if ($this->headers->has($field)) {
return $this->headers->get($field)->getParameter($parameter);
}
}
/**
* Set the parameter value of $parameter on $field header.
*/
protected function setHeaderParameter($field, $parameter, $value)
{
if ($this->headers->has($field)) {
$this->headers->get($field)->setParameter($parameter, $value);
return true;
}
return false;
}
/**
* Re-evaluate what content type and encoding should be used on this entity.
*/
protected function fixHeaders()
{
if (\count($this->immediateChildren)) {
$this->setHeaderParameter('Content-Type', 'boundary',
$this->getBoundary()
);
$this->headers->remove('Content-Transfer-Encoding');
} else {
$this->setHeaderParameter('Content-Type', 'boundary', null);
$this->setEncoding($this->encoder->getName());
}
}
/**
* Get the KeyCache used in this entity.
*
* @return Swift_KeyCache
*/
protected function getCache()
{
return $this->cache;
}
/**
* Get the ID generator.
*
* @return Swift_IdGenerator
*/
protected function getIdGenerator()
{
return $this->idGenerator;
}
/**
* Empty the KeyCache for this entity.
*/
protected function clearCache()
{
$this->cache->clearKey($this->cacheKey, 'body');
}
private function readStream(Swift_OutputByteStream $os)
{
$string = '';
while (false !== $bytes = $os->read(8192)) {
$string .= $bytes;
}
$os->setReadPointer(0);
return $string;
}
private function setEncoding($encoding)
{
if (!$this->setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) {
$this->headers->addTextHeader('Content-Transfer-Encoding', $encoding);
}
}
private function assertValidBoundary($boundary)
{
if (!preg_match('/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di', $boundary)) {
throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.');
}
}
private function setContentTypeInHeaders($type)
{
if (!$this->setHeaderFieldModel('Content-Type', $type)) {
$this->headers->addParameterizedHeader('Content-Type', $type);
}
}
private function setNestingLevel($level)
{
$this->nestingLevel = $level;
}
private function getCompoundLevel($children)
{
$level = 0;
foreach ($children as $child) {
$level |= $child->getNestingLevel();
}
return $level;
}
private function getNeededChildLevel($child, $compoundLevel)
{
$filter = [];
foreach ($this->compoundLevelFilters as $bitmask => $rules) {
if (($compoundLevel & $bitmask) === $bitmask) {
$filter = $rules + $filter;
}
}
$realLevel = $child->getNestingLevel();
$lowercaseType = strtolower($child->getContentType());
if (isset($filter[$realLevel]) && isset($filter[$realLevel][$lowercaseType])) {
return $filter[$realLevel][$lowercaseType];
}
return $realLevel;
}
private function createChild()
{
return new self($this->headers->newInstance(), $this->encoder, $this->cache, $this->idGenerator);
}
private function notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder)
{
foreach ($this->immediateChildren as $child) {
$child->encoderChanged($encoder);
}
}
private function notifyCharsetChanged($charset)
{
$this->encoder->charsetChanged($charset);
$this->headers->charsetChanged($charset);
foreach ($this->immediateChildren as $child) {
$child->charsetChanged($charset);
}
}
private function sortChildren()
{
$shouldSort = false;
foreach ($this->immediateChildren as $child) {
// NOTE: This include alternative parts moved into a related part
if (self::LEVEL_ALTERNATIVE == $child->getNestingLevel()) {
$shouldSort = true;
break;
}
}
// Sort in order of preference, if there is one
if ($shouldSort) {
// Group the messages by order of preference
$sorted = [];
foreach ($this->immediateChildren as $child) {
$type = $child->getContentType();
$level = \array_key_exists($type, $this->alternativePartOrder) ? $this->alternativePartOrder[$type] : max($this->alternativePartOrder) + 1;
if (empty($sorted[$level])) {
$sorted[$level] = [];
}
$sorted[$level][] = $child;
}
ksort($sorted);
$this->immediateChildren = array_reduce($sorted, 'array_merge', []);
}
}
/**
* Empties it's own contents from the cache.
*/
public function __destruct()
{
if ($this->cache instanceof Swift_KeyCache) {
$this->cache->clearAll($this->cacheKey);
}
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->headers = clone $this->headers;
$this->encoder = clone $this->encoder;
$this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values
$children = [];
foreach ($this->children as $pos => $child) {
$children[$pos] = clone $child;
}
$this->setChildren($children);
}
public function __wakeup()
{
$this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values
$this->cache = new Swift_KeyCache_ArrayKeyCache(new Swift_KeyCache_SimpleKeyCacheInputStream());
}
}