2
0
forked from Wavyzz/dolibarr

swiftmailer

This commit is contained in:
Frédéric FRANCE
2018-01-21 15:55:56 +01:00
parent 3a8ceb130f
commit a34b99f3ec
191 changed files with 5164 additions and 4074 deletions

View File

@@ -9,7 +9,7 @@
*/
/**
* Attachment class for attaching files to a {@link Swift_Mime_Message}.
* Attachment class for attaching files to a {@link Swift_Mime_SimpleMessage}.
*
* @author Chris Corbyn
*/
@@ -39,20 +39,6 @@ class Swift_Attachment extends Swift_Mime_Attachment
}
}
/**
* Create a new Attachment.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*
* @return Swift_Mime_Attachment
*/
public static function newInstance($data = null, $filename = null, $contentType = null)
{
return new self($data, $filename, $contentType);
}
/**
* Create a new Attachment from a filesystem path.
*
@@ -63,9 +49,9 @@ class Swift_Attachment extends Swift_Mime_Attachment
*/
public static function fromPath($path, $contentType = null)
{
return self::newInstance()->setFile(
return (new self())->setFile(
new Swift_ByteStream_FileByteStream($path),
$contentType
);
);
}
}

View File

@@ -18,38 +18,38 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
/**
* Write sequence.
*/
protected $_sequence = 0;
protected $sequence = 0;
/**
* StreamFilters.
*
* @var Swift_StreamFilter[]
*/
private $_filters = array();
private $filters = array();
/**
* A buffer for writing.
*/
private $_writeBuffer = '';
private $writeBuffer = '';
/**
* Bound streams.
*
* @var Swift_InputByteStream[]
*/
private $_mirrors = array();
private $mirrors = array();
/**
* Commit the given bytes to the storage medium immediately.
*
* @param string $bytes
*/
abstract protected function _commit($bytes);
abstract protected function doCommit($bytes);
/**
* Flush any buffers/content with immediate effect.
*/
abstract protected function _flush();
abstract protected function flush();
/**
* Add a StreamFilter to this InputByteStream.
@@ -59,7 +59,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
*/
public function addFilter(Swift_StreamFilter $filter, $key)
{
$this->_filters[$key] = $filter;
$this->filters[$key] = $filter;
}
/**
@@ -69,7 +69,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
*/
public function removeFilter($key)
{
unset($this->_filters[$key]);
unset($this->filters[$key]);
}
/**
@@ -83,15 +83,15 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
*/
public function write($bytes)
{
$this->_writeBuffer .= $bytes;
foreach ($this->_filters as $filter) {
if ($filter->shouldBuffer($this->_writeBuffer)) {
$this->writeBuffer .= $bytes;
foreach ($this->filters as $filter) {
if ($filter->shouldBuffer($this->writeBuffer)) {
return;
}
}
$this->_doWrite($this->_writeBuffer);
$this->doWrite($this->writeBuffer);
return ++$this->_sequence;
return ++$this->sequence;
}
/**
@@ -102,7 +102,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
*/
public function commit()
{
$this->_doWrite($this->_writeBuffer);
$this->doWrite($this->writeBuffer);
}
/**
@@ -115,7 +115,7 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
*/
public function bind(Swift_InputByteStream $is)
{
$this->_mirrors[] = $is;
$this->mirrors[] = $is;
}
/**
@@ -129,12 +129,12 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
*/
public function unbind(Swift_InputByteStream $is)
{
foreach ($this->_mirrors as $k => $stream) {
foreach ($this->mirrors as $k => $stream) {
if ($is === $stream) {
if ($this->_writeBuffer !== '') {
$stream->write($this->_writeBuffer);
if ($this->writeBuffer !== '') {
$stream->write($this->writeBuffer);
}
unset($this->_mirrors[$k]);
unset($this->mirrors[$k]);
}
}
}
@@ -147,20 +147,20 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
*/
public function flushBuffers()
{
if ($this->_writeBuffer !== '') {
$this->_doWrite($this->_writeBuffer);
if ($this->writeBuffer !== '') {
$this->doWrite($this->writeBuffer);
}
$this->_flush();
$this->flush();
foreach ($this->_mirrors as $stream) {
foreach ($this->mirrors as $stream) {
$stream->flushBuffers();
}
}
/** Run $bytes through all filters */
private function _filter($bytes)
private function filter($bytes)
{
foreach ($this->_filters as $filter) {
foreach ($this->filters as $filter) {
$bytes = $filter->filter($bytes);
}
@@ -168,14 +168,14 @@ abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_I
}
/** Just write the bytes to the stream */
private function _doWrite($bytes)
private function doWrite($bytes)
{
$this->_commit($this->_filter($bytes));
$this->doCommit($this->filter($bytes));
foreach ($this->_mirrors as $stream) {
foreach ($this->mirrors as $stream) {
$stream->write($bytes);
}
$this->_writeBuffer = '';
$this->writeBuffer = '';
}
}

View File

@@ -11,7 +11,7 @@
/**
* Allows reading and writing of bytes to and from an array.
*
* @author Chris Corbyn
* @author Chris Corbyn
*/
class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_OutputByteStream
{
@@ -20,28 +20,28 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
*
* @var string[]
*/
private $_array = array();
private $array = array();
/**
* The size of the stack.
*
* @var int
*/
private $_arraySize = 0;
private $arraySize = 0;
/**
* The internal pointer offset.
*
* @var int
*/
private $_offset = 0;
private $offset = 0;
/**
* Bound streams.
*
* @var Swift_InputByteStream[]
*/
private $_mirrors = array();
private $mirrors = array();
/**
* Create a new ArrayByteStream.
@@ -53,12 +53,12 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
public function __construct($stack = null)
{
if (is_array($stack)) {
$this->_array = $stack;
$this->_arraySize = count($stack);
$this->array = $stack;
$this->arraySize = count($stack);
} elseif (is_string($stack)) {
$this->write($stack);
} else {
$this->_array = array();
$this->array = array();
}
}
@@ -76,16 +76,16 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
*/
public function read($length)
{
if ($this->_offset == $this->_arraySize) {
if ($this->offset == $this->arraySize) {
return false;
}
// Don't use array slice
$end = $length + $this->_offset;
$end = $this->_arraySize < $end ? $this->_arraySize : $end;
$end = $length + $this->offset;
$end = $this->arraySize < $end ? $this->arraySize : $end;
$ret = '';
for (; $this->_offset < $end; ++$this->_offset) {
$ret .= $this->_array[$this->_offset];
for (; $this->offset < $end; ++$this->offset) {
$ret .= $this->array[$this->offset];
}
return $ret;
@@ -100,11 +100,11 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
{
$to_add = str_split($bytes);
foreach ($to_add as $value) {
$this->_array[] = $value;
$this->array[] = $value;
}
$this->_arraySize = count($this->_array);
$this->arraySize = count($this->array);
foreach ($this->_mirrors as $stream) {
foreach ($this->mirrors as $stream) {
$stream->write($bytes);
}
}
@@ -126,7 +126,7 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
*/
public function bind(Swift_InputByteStream $is)
{
$this->_mirrors[] = $is;
$this->mirrors[] = $is;
}
/**
@@ -140,9 +140,9 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
*/
public function unbind(Swift_InputByteStream $is)
{
foreach ($this->_mirrors as $k => $stream) {
foreach ($this->mirrors as $k => $stream) {
if ($is === $stream) {
unset($this->_mirrors[$k]);
unset($this->mirrors[$k]);
}
}
}
@@ -156,13 +156,13 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
*/
public function setReadPointer($byteOffset)
{
if ($byteOffset > $this->_arraySize) {
$byteOffset = $this->_arraySize;
if ($byteOffset > $this->arraySize) {
$byteOffset = $this->arraySize;
} elseif ($byteOffset < 0) {
$byteOffset = 0;
}
$this->_offset = $byteOffset;
$this->offset = $byteOffset;
}
/**
@@ -171,11 +171,11 @@ class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_O
*/
public function flushBuffers()
{
$this->_offset = 0;
$this->_array = array();
$this->_arraySize = 0;
$this->offset = 0;
$this->array = array();
$this->arraySize = 0;
foreach ($this->_mirrors as $stream) {
foreach ($this->mirrors as $stream) {
$stream->flushBuffers();
}
}

View File

@@ -11,30 +11,27 @@
/**
* Allows reading and writing of bytes to and from a file.
*
* @author Chris Corbyn
* @author Chris Corbyn
*/
class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterableInputStream implements Swift_FileStream
{
/** The internal pointer offset */
private $_offset = 0;
private $offset = 0;
/** The path to the file */
private $_path;
private $path;
/** The mode this file is opened in for writing */
private $_mode;
private $mode;
/** A lazy-loaded resource handle for reading the file */
private $_reader;
private $reader;
/** A lazy-loaded resource handle for writing the file */
private $_writer;
/** If magic_quotes_runtime is on, this will be true */
private $_quotes = false;
private $writer;
/** If stream is seekable true/false, or null if not known */
private $_seekable = null;
private $seekable = null;
/**
* Create a new FileByteStream for $path.
@@ -47,12 +44,8 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
if (empty($path)) {
throw new Swift_IoException('The path cannot be empty');
}
$this->_path = $path;
$this->_mode = $writable ? 'w+b' : 'rb';
if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) {
$this->_quotes = true;
}
$this->path = $path;
$this->mode = $writable ? 'w+b' : 'rb';
}
/**
@@ -62,7 +55,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
*/
public function getPath()
{
return $this->_path;
return $this->path;
}
/**
@@ -75,27 +68,21 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
*
* @param int $length
*
* @throws Swift_IoException
*
* @return string|bool
*
* @throws Swift_IoException
*/
public function read($length)
{
$fp = $this->_getReadHandle();
$fp = $this->getReadHandle();
if (!feof($fp)) {
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 0);
}
$bytes = fread($fp, $length);
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 1);
}
$this->_offset = ftell($fp);
$this->offset = ftell($fp);
// If we read one byte after reaching the end of the file
// feof() will return false and an empty string is returned
if ($bytes === '' && feof($fp)) {
$this->_resetReadHandle();
$this->resetReadHandle();
return false;
}
@@ -103,7 +90,7 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
return $bytes;
}
$this->_resetReadHandle();
$this->resetReadHandle();
return false;
}
@@ -117,93 +104,93 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
*/
public function setReadPointer($byteOffset)
{
if (isset($this->_reader)) {
$this->_seekReadStreamToPosition($byteOffset);
if (isset($this->reader)) {
$this->seekReadStreamToPosition($byteOffset);
}
$this->_offset = $byteOffset;
$this->offset = $byteOffset;
}
/** Just write the bytes to the file */
protected function _commit($bytes)
protected function doCommit($bytes)
{
fwrite($this->_getWriteHandle(), $bytes);
$this->_resetReadHandle();
fwrite($this->getWriteHandle(), $bytes);
$this->resetReadHandle();
}
/** Not used */
protected function _flush()
protected function flush()
{
}
/** Get the resource for reading */
private function _getReadHandle()
private function getReadHandle()
{
if (!isset($this->_reader)) {
if (!$this->_reader = fopen($this->_path, 'rb')) {
throw new Swift_IoException(
'Unable to open file for reading ['.$this->_path.']'
);
if (!isset($this->reader)) {
$pointer = @fopen($this->path, 'rb');
if (!$pointer) {
throw new Swift_IoException('Unable to open file for reading ['.$this->path.']');
}
if ($this->_offset != 0) {
$this->_getReadStreamSeekableStatus();
$this->_seekReadStreamToPosition($this->_offset);
$this->reader = $pointer;
if ($this->offset != 0) {
$this->getReadStreamSeekableStatus();
$this->seekReadStreamToPosition($this->offset);
}
}
return $this->_reader;
return $this->reader;
}
/** Get the resource for writing */
private function _getWriteHandle()
private function getWriteHandle()
{
if (!isset($this->_writer)) {
if (!$this->_writer = fopen($this->_path, $this->_mode)) {
if (!isset($this->writer)) {
if (!$this->writer = fopen($this->path, $this->mode)) {
throw new Swift_IoException(
'Unable to open file for writing ['.$this->_path.']'
'Unable to open file for writing ['.$this->path.']'
);
}
}
return $this->_writer;
return $this->writer;
}
/** Force a reload of the resource for reading */
private function _resetReadHandle()
private function resetReadHandle()
{
if (isset($this->_reader)) {
fclose($this->_reader);
$this->_reader = null;
if (isset($this->reader)) {
fclose($this->reader);
$this->reader = null;
}
}
/** Check if ReadOnly Stream is seekable */
private function _getReadStreamSeekableStatus()
private function getReadStreamSeekableStatus()
{
$metas = stream_get_meta_data($this->_reader);
$this->_seekable = $metas['seekable'];
$metas = stream_get_meta_data($this->reader);
$this->seekable = $metas['seekable'];
}
/** Streams in a readOnly stream ensuring copy if needed */
private function _seekReadStreamToPosition($offset)
private function seekReadStreamToPosition($offset)
{
if ($this->_seekable === null) {
$this->_getReadStreamSeekableStatus();
if ($this->seekable === null) {
$this->getReadStreamSeekableStatus();
}
if ($this->_seekable === false) {
$currentPos = ftell($this->_reader);
if ($this->seekable === false) {
$currentPos = ftell($this->reader);
if ($currentPos < $offset) {
$toDiscard = $offset - $currentPos;
fread($this->_reader, $toDiscard);
fread($this->reader, $toDiscard);
return;
}
$this->_copyReadStream();
$this->copyReadStream();
}
fseek($this->_reader, $offset, SEEK_SET);
fseek($this->reader, $offset, SEEK_SET);
}
/** Copy a readOnly Stream to ensure seekability */
private function _copyReadStream()
private function copyReadStream()
{
if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) {
/* We have opened a php:// Stream Should work without problem */
@@ -212,11 +199,11 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
} else {
throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available');
}
$currentPos = ftell($this->_reader);
fclose($this->_reader);
$source = fopen($this->_path, 'rb');
$currentPos = ftell($this->reader);
fclose($this->reader);
$source = fopen($this->path, 'rb');
if (!$source) {
throw new Swift_IoException('Unable to open file for copying ['.$this->_path.']');
throw new Swift_IoException('Unable to open file for copying ['.$this->path.']');
}
fseek($tmpFile, 0, SEEK_SET);
while (!feof($source)) {
@@ -224,6 +211,6 @@ class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterabl
}
fseek($tmpFile, $currentPos, SEEK_SET);
fclose($source);
$this->_reader = $tmpFile;
$this->reader = $tmpFile;
}
}

View File

@@ -48,8 +48,8 @@ interface Swift_CharacterReader
* A value of zero means this is already a valid character.
* A value of -1 means this cannot possibly be a valid character.
*
* @param integer[] $bytes
* @param int $size
* @param int[] $bytes
* @param int $size
*
* @return int
*/

View File

@@ -11,8 +11,8 @@
/**
* Provides fixed-width byte sizes for reading fixed-width character sets.
*
* @author Chris Corbyn
* @author Xavier De Cock <xdecock@gmail.com>
* @author Chris Corbyn
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader
{
@@ -21,7 +21,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe
*
* @var int
*/
private $_width;
private $width;
/**
* Creates a new GenericFixedWidthReader using $width bytes per character.
@@ -30,7 +30,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe
*/
public function __construct($width)
{
$this->_width = $width;
$this->width = $width;
}
/**
@@ -47,11 +47,11 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe
{
$strlen = strlen($string);
// % and / are CPU intensive, so, maybe find a better way
$ignored = $strlen % $this->_width;
$ignoredChars = substr($string, -$ignored);
$currentMap = $this->_width;
$ignored = $strlen % $this->width;
$ignoredChars = $ignored ? substr($string, -$ignored) : '';
$currentMap = $this->width;
return ($strlen - $ignored) / $this->_width;
return ($strlen - $ignored) / $this->width;
}
/**
@@ -80,7 +80,7 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe
*/
public function validateByteSequence($bytes, $size)
{
$needed = $this->_width - $size;
$needed = $this->width - $size;
return $needed > -1 ? $needed : -1;
}
@@ -92,6 +92,6 @@ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterRe
*/
public function getInitialByteSize()
{
return $this->_width;
return $this->width;
}
}

View File

@@ -19,22 +19,22 @@ class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader
/** Pre-computed for optimization */
private static $length_map = array(
// N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x0N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x2N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x4N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x6N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7N
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x8N
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9N
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xAN
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBN
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xCN
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDN
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEN
4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0, // 0xFN
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x0N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x1N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x2N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x3N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x4N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x5N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x6N
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x7N
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x8N
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x9N
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xAN
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xBN
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xCN
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xDN
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xEN
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0, // 0xFN
);
private static $s_length_map = array(

View File

@@ -20,14 +20,14 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift
*
* @var array
*/
private static $_map = array();
private static $map = array();
/**
* Factories which have already been loaded.
*
* @var Swift_CharacterReaderFactory[]
*/
private static $_loaded = array();
private static $loaded = array();
/**
* Creates a new CharacterReaderFactory.
@@ -44,7 +44,7 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift
public function init()
{
if (count(self::$_map) > 0) {
if (count(self::$map) > 0) {
return;
}
@@ -66,32 +66,32 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift
);
// Utf-8
self::$_map['utf-?8'] = array(
self::$map['utf-?8'] = array(
'class' => $prefix.'Utf8Reader',
'constructor' => array(),
);
//7-8 bit charsets
self::$_map['(us-)?ascii'] = $singleByte;
self::$_map['(iso|iec)-?8859-?[0-9]+'] = $singleByte;
self::$_map['windows-?125[0-9]'] = $singleByte;
self::$_map['cp-?[0-9]+'] = $singleByte;
self::$_map['ansi'] = $singleByte;
self::$_map['macintosh'] = $singleByte;
self::$_map['koi-?7'] = $singleByte;
self::$_map['koi-?8-?.+'] = $singleByte;
self::$_map['mik'] = $singleByte;
self::$_map['(cork|t1)'] = $singleByte;
self::$_map['v?iscii'] = $singleByte;
self::$map['(us-)?ascii'] = $singleByte;
self::$map['(iso|iec)-?8859-?[0-9]+'] = $singleByte;
self::$map['windows-?125[0-9]'] = $singleByte;
self::$map['cp-?[0-9]+'] = $singleByte;
self::$map['ansi'] = $singleByte;
self::$map['macintosh'] = $singleByte;
self::$map['koi-?7'] = $singleByte;
self::$map['koi-?8-?.+'] = $singleByte;
self::$map['mik'] = $singleByte;
self::$map['(cork|t1)'] = $singleByte;
self::$map['v?iscii'] = $singleByte;
//16 bits
self::$_map['(ucs-?2|utf-?16)'] = $doubleByte;
self::$map['(ucs-?2|utf-?16)'] = $doubleByte;
//32 bits
self::$_map['(ucs-?4|utf-?32)'] = $fourBytes;
self::$map['(ucs-?4|utf-?32)'] = $fourBytes;
// Fallback
self::$_map['.*'] = $singleByte;
self::$map['.*'] = $singleByte;
}
/**
@@ -103,21 +103,21 @@ class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift
*/
public function getReaderFor($charset)
{
$charset = trim(strtolower($charset));
foreach (self::$_map as $pattern => $spec) {
$charset = strtolower(trim($charset));
foreach (self::$map as $pattern => $spec) {
$re = '/^'.$pattern.'$/D';
if (preg_match($re, $charset)) {
if (!array_key_exists($pattern, self::$_loaded)) {
if (!array_key_exists($pattern, self::$loaded)) {
$reflector = new ReflectionClass($spec['class']);
if ($reflector->getConstructor()) {
$reader = $reflector->newInstanceArgs($spec['constructor']);
} else {
$reader = $reflector->newInstance();
}
self::$_loaded[$pattern] = $reader;
self::$loaded[$pattern] = $reader;
}
return self::$_loaded[$pattern];
return self::$loaded[$pattern];
}
}
}

View File

@@ -16,28 +16,28 @@
class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStream
{
/** A map of byte values and their respective characters */
private static $_charMap;
private static $charMap;
/** A map of characters and their derivative byte values */
private static $_byteMap;
private static $byteMap;
/** The char reader (lazy-loaded) for the current charset */
private $_charReader;
private $charReader;
/** A factory for creating CharacterReader instances */
private $_charReaderFactory;
private $charReaderFactory;
/** The character set this stream is using */
private $_charset;
private $charset;
/** Array of characters */
private $_array = array();
private $array = array();
/** Size of the array of character */
private $_array_size = array();
private $array_size = array();
/** The current character offset in the stream */
private $_offset = 0;
private $offset = 0;
/**
* Create a new CharacterStream with the given $chars, if set.
@@ -47,7 +47,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*/
public function __construct(Swift_CharacterReaderFactory $factory, $charset)
{
self::_initializeMaps();
self::initializeMaps();
$this->setCharacterReaderFactory($factory);
$this->setCharacterSet($charset);
}
@@ -59,8 +59,8 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*/
public function setCharacterSet($charset)
{
$this->_charset = $charset;
$this->_charReader = null;
$this->charset = $charset;
$this->charReader = null;
}
/**
@@ -70,7 +70,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*/
public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory)
{
$this->_charReaderFactory = $factory;
$this->charReaderFactory = $factory;
}
/**
@@ -80,28 +80,28 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*/
public function importByteStream(Swift_OutputByteStream $os)
{
if (!isset($this->_charReader)) {
$this->_charReader = $this->_charReaderFactory
->getReaderFor($this->_charset);
if (!isset($this->charReader)) {
$this->charReader = $this->charReaderFactory
->getReaderFor($this->charset);
}
$startLength = $this->_charReader->getInitialByteSize();
$startLength = $this->charReader->getInitialByteSize();
while (false !== $bytes = $os->read($startLength)) {
$c = array();
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) {
$c[] = self::$_byteMap[$bytes[$i]];
$c[] = self::$byteMap[$bytes[$i]];
}
$size = count($c);
$need = $this->_charReader
$need = $this->charReader
->validateByteSequence($c, $size);
if ($need > 0 &&
false !== $bytes = $os->read($need)) {
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) {
$c[] = self::$_byteMap[$bytes[$i]];
$c[] = self::$byteMap[$bytes[$i]];
}
}
$this->_array[] = $c;
++$this->_array_size;
$this->array[] = $c;
++$this->array_size;
}
}
@@ -127,20 +127,20 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*/
public function read($length)
{
if ($this->_offset == $this->_array_size) {
if ($this->offset == $this->array_size) {
return false;
}
// Don't use array slice
$arrays = array();
$end = $length + $this->_offset;
for ($i = $this->_offset; $i < $end; ++$i) {
if (!isset($this->_array[$i])) {
$end = $length + $this->offset;
for ($i = $this->offset; $i < $end; ++$i) {
if (!isset($this->array[$i])) {
break;
}
$arrays[] = $this->_array[$i];
$arrays[] = $this->array[$i];
}
$this->_offset += $i - $this->_offset; // Limit function calls
$this->offset += $i - $this->offset; // Limit function calls
$chars = false;
foreach ($arrays as $array) {
$chars .= implode('', array_map('chr', $array));
@@ -155,24 +155,24 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*
* @param int $length
*
* @return integer[]
* @return int[]
*/
public function readBytes($length)
{
if ($this->_offset == $this->_array_size) {
if ($this->offset == $this->array_size) {
return false;
}
$arrays = array();
$end = $length + $this->_offset;
for ($i = $this->_offset; $i < $end; ++$i) {
if (!isset($this->_array[$i])) {
$end = $length + $this->offset;
for ($i = $this->offset; $i < $end; ++$i) {
if (!isset($this->array[$i])) {
break;
}
$arrays[] = $this->_array[$i];
$arrays[] = $this->array[$i];
}
$this->_offset += ($i - $this->_offset); // Limit function calls
$this->offset += ($i - $this->offset); // Limit function calls
return call_user_func_array('array_merge', $arrays);
return array_merge(...$arrays);
}
/**
@@ -182,12 +182,12 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*/
public function write($chars)
{
if (!isset($this->_charReader)) {
$this->_charReader = $this->_charReaderFactory->getReaderFor(
$this->_charset);
if (!isset($this->charReader)) {
$this->charReader = $this->charReaderFactory->getReaderFor(
$this->charset);
}
$startLength = $this->_charReader->getInitialByteSize();
$startLength = $this->charReader->getInitialByteSize();
$fp = fopen('php://memory', 'w+b');
fwrite($fp, $chars);
@@ -203,7 +203,7 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
// Buffer Filing
if ($buf_len - $buf_pos < $startLength) {
$buf = array_splice($buffer, $buf_pos);
$new = $this->_reloadBuffer($fp, 100);
$new = $this->reloadBuffer($fp, 100);
if ($new) {
$buffer = array_merge($buf, $new);
$buf_len = count($buffer);
@@ -218,11 +218,11 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
++$size;
$bytes[] = $buffer[$buf_pos++];
}
$need = $this->_charReader->validateByteSequence(
$need = $this->charReader->validateByteSequence(
$bytes, $size);
if ($need > 0) {
if ($buf_len - $buf_pos < $need) {
$new = $this->_reloadBuffer($fp, $need);
$new = $this->reloadBuffer($fp, $need);
if ($new) {
$buffer = array_merge($buffer, $new);
@@ -233,8 +233,8 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
$bytes[] = $buffer[$buf_pos++];
}
}
$this->_array[] = $bytes;
++$this->_array_size;
$this->array[] = $bytes;
++$this->array_size;
}
} while ($has_datas);
@@ -248,12 +248,12 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*/
public function setPointer($charOffset)
{
if ($charOffset > $this->_array_size) {
$charOffset = $this->_array_size;
if ($charOffset > $this->array_size) {
$charOffset = $this->array_size;
} elseif ($charOffset < 0) {
$charOffset = 0;
}
$this->_offset = $charOffset;
$this->offset = $charOffset;
}
/**
@@ -261,17 +261,17 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
*/
public function flushContents()
{
$this->_offset = 0;
$this->_array = array();
$this->_array_size = 0;
$this->offset = 0;
$this->array = array();
$this->array_size = 0;
}
private function _reloadBuffer($fp, $len)
private function reloadBuffer($fp, $len)
{
if (!feof($fp) && ($bytes = fread($fp, $len)) !== false) {
$buf = array();
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) {
$buf[] = self::$_byteMap[$bytes[$i]];
$buf[] = self::$byteMap[$bytes[$i]];
}
return $buf;
@@ -280,14 +280,14 @@ class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStrea
return false;
}
private static function _initializeMaps()
private static function initializeMaps()
{
if (!isset(self::$_charMap)) {
self::$_charMap = array();
if (!isset(self::$charMap)) {
self::$charMap = array();
for ($byte = 0; $byte < 256; ++$byte) {
self::$_charMap[$byte] = chr($byte);
self::$charMap[$byte] = chr($byte);
}
self::$_byteMap = array_flip(self::$_charMap);
self::$byteMap = array_flip(self::$charMap);
}
}
}

View File

@@ -11,7 +11,7 @@
/**
* A CharacterStream implementation which stores characters in an internal array.
*
* @author Xavier De Cock <xdecock@gmail.com>
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
{
@@ -20,63 +20,63 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
*
* @var Swift_CharacterReader
*/
private $_charReader;
private $charReader;
/**
* A factory for creating CharacterReader instances.
*
* @var Swift_CharacterReaderFactory
*/
private $_charReaderFactory;
private $charReaderFactory;
/**
* The character set this stream is using.
*
* @var string
*/
private $_charset;
private $charset;
/**
* The data's stored as-is.
*
* @var string
*/
private $_datas = '';
private $datas = '';
/**
* Number of bytes in the stream.
*
* @var int
*/
private $_datasSize = 0;
private $datasSize = 0;
/**
* Map.
*
* @var mixed
*/
private $_map;
private $map;
/**
* Map Type.
*
* @var int
*/
private $_mapType = 0;
private $mapType = 0;
/**
* Number of characters in the stream.
*
* @var int
*/
private $_charCount = 0;
private $charCount = 0;
/**
* Position in the stream.
*
* @var int
*/
private $_currentPos = 0;
private $currentPos = 0;
/**
* Constructor.
@@ -99,9 +99,9 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
*/
public function setCharacterSet($charset)
{
$this->_charset = $charset;
$this->_charReader = null;
$this->_mapType = 0;
$this->charset = $charset;
$this->charReader = null;
$this->mapType = 0;
}
/**
@@ -111,7 +111,7 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
*/
public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory)
{
$this->_charReaderFactory = $factory;
$this->charReaderFactory = $factory;
}
/**
@@ -119,11 +119,11 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
*/
public function flushContents()
{
$this->_datas = null;
$this->_map = null;
$this->_charCount = 0;
$this->_currentPos = 0;
$this->_datasSize = 0;
$this->datas = null;
$this->map = null;
$this->charCount = 0;
$this->currentPos = 0;
$this->datasSize = 0;
}
/**
@@ -161,49 +161,49 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
*/
public function read($length)
{
if ($this->_currentPos >= $this->_charCount) {
if ($this->currentPos >= $this->charCount) {
return false;
}
$ret = false;
$length = $this->_currentPos + $length > $this->_charCount ? $this->_charCount - $this->_currentPos : $length;
switch ($this->_mapType) {
$length = ($this->currentPos + $length > $this->charCount) ? $this->charCount - $this->currentPos : $length;
switch ($this->mapType) {
case Swift_CharacterReader::MAP_TYPE_FIXED_LEN:
$len = $length * $this->_map;
$ret = substr($this->_datas,
$this->_currentPos * $this->_map,
$len = $length * $this->map;
$ret = substr($this->datas,
$this->currentPos * $this->map,
$len);
$this->_currentPos += $length;
$this->currentPos += $length;
break;
case Swift_CharacterReader::MAP_TYPE_INVALID:
$ret = '';
for (; $this->_currentPos < $length; ++$this->_currentPos) {
if (isset($this->_map[$this->_currentPos])) {
for (; $this->currentPos < $length; ++$this->currentPos) {
if (isset($this->map[$this->currentPos])) {
$ret .= '?';
} else {
$ret .= $this->_datas[$this->_currentPos];
$ret .= $this->datas[$this->currentPos];
}
}
break;
case Swift_CharacterReader::MAP_TYPE_POSITIONS:
$end = $this->_currentPos + $length;
$end = $end > $this->_charCount ? $this->_charCount : $end;
$end = $this->currentPos + $length;
$end = $end > $this->charCount ? $this->charCount : $end;
$ret = '';
$start = 0;
if ($this->_currentPos > 0) {
$start = $this->_map['p'][$this->_currentPos - 1];
if ($this->currentPos > 0) {
$start = $this->map['p'][$this->currentPos - 1];
}
$to = $start;
for (; $this->_currentPos < $end; ++$this->_currentPos) {
if (isset($this->_map['i'][$this->_currentPos])) {
$ret .= substr($this->_datas, $start, $to - $start).'?';
$start = $this->_map['p'][$this->_currentPos];
for (; $this->currentPos < $end; ++$this->currentPos) {
if (isset($this->map['i'][$this->currentPos])) {
$ret .= substr($this->datas, $start, $to - $start).'?';
$start = $this->map['p'][$this->currentPos];
} else {
$to = $this->_map['p'][$this->_currentPos];
$to = $this->map['p'][$this->currentPos];
}
}
$ret .= substr($this->_datas, $start, $to - $start);
$ret .= substr($this->datas, $start, $to - $start);
break;
}
@@ -215,7 +215,7 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
*
* @param int $length
*
* @return integer[]
* @return int[]
*/
public function readBytes($length)
{
@@ -236,10 +236,10 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
*/
public function setPointer($charOffset)
{
if ($this->_charCount < $charOffset) {
$charOffset = $this->_charCount;
if ($this->charCount < $charOffset) {
$charOffset = $this->charCount;
}
$this->_currentPos = $charOffset;
$this->currentPos = $charOffset;
}
/**
@@ -249,19 +249,19 @@ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
*/
public function write($chars)
{
if (!isset($this->_charReader)) {
$this->_charReader = $this->_charReaderFactory->getReaderFor(
$this->_charset);
$this->_map = array();
$this->_mapType = $this->_charReader->getMapType();
if (!isset($this->charReader)) {
$this->charReader = $this->charReaderFactory->getReaderFor(
$this->charset);
$this->map = array();
$this->mapType = $this->charReader->getMapType();
}
$ignored = '';
$this->_datas .= $chars;
$this->_charCount += $this->_charReader->getCharPositions(substr($this->_datas, $this->_datasSize), $this->_datasSize, $this->_map, $ignored);
$this->datas .= $chars;
$this->charCount += $this->charReader->getCharPositions(substr($this->datas, $this->datasSize), $this->datasSize, $this->map, $ignored);
if ($ignored !== false) {
$this->_datasSize = strlen($this->_datas) - strlen($ignored);
$this->datasSize = strlen($this->datas) - strlen($ignored);
} else {
$this->_datasSize = strlen($this->_datas);
$this->datasSize = strlen($this->datas);
}
}
}

View File

@@ -16,10 +16,10 @@
abstract class Swift_ConfigurableSpool implements Swift_Spool
{
/** The maximum number of messages to send per flush */
private $_message_limit;
private $message_limit;
/** The time limit per flush */
private $_time_limit;
private $time_limit;
/**
* Sets the maximum number of messages to send per flush.
@@ -28,7 +28,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool
*/
public function setMessageLimit($limit)
{
$this->_message_limit = (int) $limit;
$this->message_limit = (int) $limit;
}
/**
@@ -38,7 +38,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool
*/
public function getMessageLimit()
{
return $this->_message_limit;
return $this->message_limit;
}
/**
@@ -48,7 +48,7 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool
*/
public function setTimeLimit($limit)
{
$this->_time_limit = (int) $limit;
$this->time_limit = (int) $limit;
}
/**
@@ -58,6 +58,6 @@ abstract class Swift_ConfigurableSpool implements Swift_Spool
*/
public function getTimeLimit()
{
return $this->_time_limit;
return $this->time_limit;
}
}

View File

@@ -11,7 +11,7 @@
/**
* Dependency Injection container.
*
* @author Chris Corbyn
* @author Chris Corbyn
*/
class Swift_DependencyContainer
{
@@ -28,13 +28,13 @@ class Swift_DependencyContainer
const TYPE_ALIAS = 0x1000;
/** Singleton instance */
private static $_instance = null;
private static $instance = null;
/** The data container */
private $_store = array();
private $store = array();
/** The current endpoint in the data container */
private $_endPoint;
private $endPoint;
/**
* Constructor should not be used.
@@ -48,15 +48,15 @@ class Swift_DependencyContainer
/**
* Returns a singleton of the DependencyContainer.
*
* @return Swift_DependencyContainer
* @return self
*/
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new self();
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$_instance;
return self::$instance;
}
/**
@@ -66,7 +66,7 @@ class Swift_DependencyContainer
*/
public function listItems()
{
return array_keys($this->_store);
return array_keys($this->store);
}
/**
@@ -80,8 +80,8 @@ class Swift_DependencyContainer
*/
public function has($itemName)
{
return array_key_exists($itemName, $this->_store)
&& isset($this->_store[$itemName]['lookupType']);
return array_key_exists($itemName, $this->store)
&& isset($this->store[$itemName]['lookupType']);
}
/**
@@ -91,9 +91,9 @@ class Swift_DependencyContainer
*
* @param string $itemName
*
* @throws Swift_DependencyException If the dependency is not found
*
* @return mixed
*
* @throws Swift_DependencyException If the dependency is not found
*/
public function lookup($itemName)
{
@@ -103,15 +103,15 @@ class Swift_DependencyContainer
);
}
switch ($this->_store[$itemName]['lookupType']) {
switch ($this->store[$itemName]['lookupType']) {
case self::TYPE_ALIAS:
return $this->_createAlias($itemName);
return $this->createAlias($itemName);
case self::TYPE_VALUE:
return $this->_getValue($itemName);
return $this->getValue($itemName);
case self::TYPE_INSTANCE:
return $this->_createNewInstance($itemName);
return $this->createNewInstance($itemName);
case self::TYPE_SHARED:
return $this->_createSharedInstance($itemName);
return $this->createSharedInstance($itemName);
}
}
@@ -125,8 +125,8 @@ class Swift_DependencyContainer
public function createDependenciesFor($itemName)
{
$args = array();
if (isset($this->_store[$itemName]['args'])) {
$args = $this->_resolveArgs($this->_store[$itemName]['args']);
if (isset($this->store[$itemName]['args'])) {
$args = $this->resolveArgs($this->store[$itemName]['args']);
}
return $args;
@@ -143,12 +143,12 @@ class Swift_DependencyContainer
*
* @param string $itemName
*
* @return Swift_DependencyContainer
* @return $this
*/
public function register($itemName)
{
$this->_store[$itemName] = array();
$this->_endPoint = &$this->_store[$itemName];
$this->store[$itemName] = array();
$this->endPoint = &$this->store[$itemName];
return $this;
}
@@ -160,11 +160,11 @@ class Swift_DependencyContainer
*
* @param mixed $value
*
* @return Swift_DependencyContainer
* @return $this
*/
public function asValue($value)
{
$endPoint = &$this->_getEndPoint();
$endPoint = &$this->getEndPoint();
$endPoint['lookupType'] = self::TYPE_VALUE;
$endPoint['value'] = $value;
@@ -176,11 +176,11 @@ class Swift_DependencyContainer
*
* @param string $lookup
*
* @return Swift_DependencyContainer
* @return $this
*/
public function asAliasOf($lookup)
{
$endPoint = &$this->_getEndPoint();
$endPoint = &$this->getEndPoint();
$endPoint['lookupType'] = self::TYPE_ALIAS;
$endPoint['ref'] = $lookup;
@@ -198,11 +198,11 @@ class Swift_DependencyContainer
*
* @param string $className
*
* @return Swift_DependencyContainer
* @return $this
*/
public function asNewInstanceOf($className)
{
$endPoint = &$this->_getEndPoint();
$endPoint = &$this->getEndPoint();
$endPoint['lookupType'] = self::TYPE_INSTANCE;
$endPoint['className'] = $className;
@@ -216,11 +216,11 @@ class Swift_DependencyContainer
*
* @param string $className
*
* @return Swift_DependencyContainer
* @return $this
*/
public function asSharedInstanceOf($className)
{
$endPoint = &$this->_getEndPoint();
$endPoint = &$this->getEndPoint();
$endPoint['lookupType'] = self::TYPE_SHARED;
$endPoint['className'] = $className;
@@ -236,11 +236,11 @@ class Swift_DependencyContainer
*
* @param array $lookups
*
* @return Swift_DependencyContainer
* @return $this
*/
public function withDependencies(array $lookups)
{
$endPoint = &$this->_getEndPoint();
$endPoint = &$this->getEndPoint();
$endPoint['args'] = array();
foreach ($lookups as $lookup) {
$this->addConstructorLookup($lookup);
@@ -257,11 +257,11 @@ class Swift_DependencyContainer
*
* @param mixed $value
*
* @return Swift_DependencyContainer
* @return $this
*/
public function addConstructorValue($value)
{
$endPoint = &$this->_getEndPoint();
$endPoint = &$this->getEndPoint();
if (!isset($endPoint['args'])) {
$endPoint['args'] = array();
}
@@ -278,12 +278,12 @@ class Swift_DependencyContainer
*
* @param string $lookup
*
* @return Swift_DependencyContainer
* @return $this
*/
public function addConstructorLookup($lookup)
{
$endPoint = &$this->_getEndPoint();
if (!isset($this->_endPoint['args'])) {
$endPoint = &$this->getEndPoint();
if (!isset($this->endPoint['args'])) {
$endPoint['args'] = array();
}
$endPoint['args'][] = array('type' => 'lookup', 'item' => $lookup);
@@ -292,21 +292,21 @@ class Swift_DependencyContainer
}
/** Get the literal value with $itemName */
private function _getValue($itemName)
private function getValue($itemName)
{
return $this->_store[$itemName]['value'];
return $this->store[$itemName]['value'];
}
/** Resolve an alias to another item */
private function _createAlias($itemName)
private function createAlias($itemName)
{
return $this->lookup($this->_store[$itemName]['ref']);
return $this->lookup($this->store[$itemName]['ref']);
}
/** Create a fresh instance of $itemName */
private function _createNewInstance($itemName)
private function createNewInstance($itemName)
{
$reflector = new ReflectionClass($this->_store[$itemName]['className']);
$reflector = new ReflectionClass($this->store[$itemName]['className']);
if ($reflector->getConstructor()) {
return $reflector->newInstanceArgs(
$this->createDependenciesFor($itemName)
@@ -317,35 +317,35 @@ class Swift_DependencyContainer
}
/** Create and register a shared instance of $itemName */
private function _createSharedInstance($itemName)
private function createSharedInstance($itemName)
{
if (!isset($this->_store[$itemName]['instance'])) {
$this->_store[$itemName]['instance'] = $this->_createNewInstance($itemName);
if (!isset($this->store[$itemName]['instance'])) {
$this->store[$itemName]['instance'] = $this->createNewInstance($itemName);
}
return $this->_store[$itemName]['instance'];
return $this->store[$itemName]['instance'];
}
/** Get the current endpoint in the store */
private function &_getEndPoint()
private function &getEndPoint()
{
if (!isset($this->_endPoint)) {
if (!isset($this->endPoint)) {
throw new BadMethodCallException(
'Component must first be registered by calling register()'
);
}
return $this->_endPoint;
return $this->endPoint;
}
/** Get an argument list with dependencies resolved */
private function _resolveArgs(array $args)
private function resolveArgs(array $args)
{
$resolved = array();
foreach ($args as $argDefinition) {
switch ($argDefinition['type']) {
case 'lookup':
$resolved[] = $this->_lookupRecursive($argDefinition['item']);
$resolved[] = $this->lookupRecursive($argDefinition['item']);
break;
case 'value':
$resolved[] = $argDefinition['item'];
@@ -357,12 +357,12 @@ class Swift_DependencyContainer
}
/** Resolve a single dependency with an collections */
private function _lookupRecursive($item)
private function lookupRecursive($item)
{
if (is_array($item)) {
$collection = array();
foreach ($item as $k => $v) {
$collection[$k] = $this->_lookupRecursive($v);
$collection[$k] = $this->lookupRecursive($v);
}
return $collection;

View File

@@ -39,20 +39,6 @@ class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile
}
}
/**
* Create a new EmbeddedFile.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*
* @return Swift_Mime_EmbeddedFile
*/
public static function newInstance($data = null, $filename = null, $contentType = null)
{
return new self($data, $filename, $contentType);
}
/**
* Create a new EmbeddedFile from a filesystem path.
*
@@ -62,8 +48,6 @@ class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile
*/
public static function fromPath($path)
{
return self::newInstance()->setFile(
new Swift_ByteStream_FileByteStream($path)
);
return (new self())->setFile(new Swift_ByteStream_FileByteStream($path));
}
}

View File

@@ -13,7 +13,7 @@
*
* Possibly the most accurate RFC 2045 QP implementation found in PHP.
*
* @author Chris Corbyn
* @author Chris Corbyn
*/
class Swift_Encoder_QpEncoder implements Swift_Encoder
{
@@ -22,21 +22,21 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
*
* @var Swift_CharacterStream
*/
protected $_charStream;
protected $charStream;
/**
* A filter used if input should be canonicalized.
*
* @var Swift_StreamFilter
*/
protected $_filter;
protected $filter;
/**
* Pre-computed QP for HUGE optimization.
*
* @var string[]
*/
protected static $_qpMap = array(
protected static $qpMap = array(
0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04',
5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09',
10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E',
@@ -91,14 +91,14 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
255 => '=FF',
);
protected static $_safeMapShare = array();
protected static $safeMapShare = array();
/**
* A map of non-encoded ascii characters.
*
* @var string[]
*/
protected $_safeMap = array();
protected $safeMap = array();
/**
* Creates a new QpEncoder for the given CharacterStream.
@@ -108,28 +108,28 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
*/
public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null)
{
$this->_charStream = $charStream;
if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) {
$this->charStream = $charStream;
if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) {
$this->initSafeMap();
self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap;
self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap;
} else {
$this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()];
$this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()];
}
$this->_filter = $filter;
$this->filter = $filter;
}
public function __sleep()
{
return array('_charStream', '_filter');
return array('charStream', 'filter');
}
public function __wakeup()
{
if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) {
if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) {
$this->initSafeMap();
self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap;
self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap;
} else {
$this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()];
$this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()];
}
}
@@ -142,7 +142,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
{
foreach (array_merge(
array(0x09, 0x20), range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) {
$this->_safeMap[$byte] = chr($byte);
$this->safeMap[$byte] = chr($byte);
}
}
@@ -173,19 +173,19 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
$currentLine = &$lines[$lNo++];
$size = $lineLen = 0;
$this->_charStream->flushContents();
$this->_charStream->importString($string);
$this->charStream->flushContents();
$this->charStream->importString($string);
// Fetching more than 4 chars at one is slower, as is fetching fewer bytes
// Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6
// bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes
while (false !== $bytes = $this->_nextSequence()) {
while (false !== $bytes = $this->nextSequence()) {
// If we're filtering the input
if (isset($this->_filter)) {
if (isset($this->filter)) {
// If we can't filter because we need more bytes
while ($this->_filter->shouldBuffer($bytes)) {
while ($this->filter->shouldBuffer($bytes)) {
// Then collect bytes into the buffer
if (false === $moreBytes = $this->_nextSequence(1)) {
if (false === $moreBytes = $this->nextSequence(1)) {
break;
}
@@ -194,10 +194,10 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
}
}
// And filter them
$bytes = $this->_filter->filter($bytes);
$bytes = $this->filter->filter($bytes);
}
$enc = $this->_encodeByteSequence($bytes, $size);
$enc = $this->encodeByteSequence($bytes, $size);
$i = strpos($enc, '=0D=0A');
$newLineLength = $lineLen + ($i === false ? $size : $i);
@@ -219,7 +219,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
}
}
return $this->_standardize(implode("=\r\n", $lines));
return $this->standardize(implode("=\r\n", $lines));
}
/**
@@ -229,27 +229,27 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
*/
public function charsetChanged($charset)
{
$this->_charStream->setCharacterSet($charset);
$this->charStream->setCharacterSet($charset);
}
/**
* Encode the given byte array into a verbatim QP form.
*
* @param integer[] $bytes
* @param int $size
* @param int[] $bytes
* @param int $size
*
* @return string
*/
protected function _encodeByteSequence(array $bytes, &$size)
protected function encodeByteSequence(array $bytes, &$size)
{
$ret = '';
$size = 0;
foreach ($bytes as $b) {
if (isset($this->_safeMap[$b])) {
$ret .= $this->_safeMap[$b];
if (isset($this->safeMap[$b])) {
$ret .= $this->safeMap[$b];
++$size;
} else {
$ret .= self::$_qpMap[$b];
$ret .= self::$qpMap[$b];
$size += 3;
}
}
@@ -262,11 +262,11 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
*
* @param int $size number of bytes to read
*
* @return integer[]
* @return int[]
*/
protected function _nextSequence($size = 4)
protected function nextSequence($size = 4)
{
return $this->_charStream->readBytes($size);
return $this->charStream->readBytes($size);
}
/**
@@ -276,7 +276,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
*
* @return string
*/
protected function _standardize($string)
protected function standardize($string)
{
$string = str_replace(array("\t=0D=0A", ' =0D=0A', '=0D=0A'),
array("=09\r\n", "=20\r\n", "\r\n"), $string
@@ -284,7 +284,7 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
switch ($end = ord(substr($string, -1))) {
case 0x09:
case 0x20:
$string = substr_replace($string, self::$_qpMap[$end], -1);
$string = substr_replace($string, self::$qpMap[$end], -1);
}
return $string;
@@ -295,6 +295,6 @@ class Swift_Encoder_QpEncoder implements Swift_Encoder
*/
public function __clone()
{
$this->_charStream = clone $this->_charStream;
$this->charStream = clone $this->charStream;
}
}

View File

@@ -20,7 +20,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
*
* @var Swift_CharacterStream
*/
private $_charStream;
private $charStream;
/**
* Creates a new Rfc2231Encoder using the given character stream instance.
@@ -29,7 +29,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
*/
public function __construct(Swift_CharacterStream $charStream)
{
$this->_charStream = $charStream;
$this->charStream = $charStream;
}
/**
@@ -53,12 +53,12 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
$maxLineLength = 75;
}
$this->_charStream->flushContents();
$this->_charStream->importString($string);
$this->charStream->flushContents();
$this->charStream->importString($string);
$thisLineLength = $maxLineLength - $firstLineOffset;
while (false !== $char = $this->_charStream->read(4)) {
while (false !== $char = $this->charStream->read(4)) {
$encodedChar = rawurlencode($char);
if (0 != strlen($currentLine)
&& strlen($currentLine.$encodedChar) > $thisLineLength) {
@@ -79,7 +79,7 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
*/
public function charsetChanged($charset)
{
$this->_charStream->setCharacterSet($charset);
$this->charStream->setCharacterSet($charset);
}
/**
@@ -87,6 +87,6 @@ class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
*/
public function __clone()
{
$this->_charStream = clone $this->_charStream;
$this->charStream = clone $this->charStream;
}
}

View File

@@ -1,64 +0,0 @@
<?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.
*/
/**
* Provides quick access to each encoding type.
*
* @author Chris Corbyn
*/
class Swift_Encoding
{
/**
* Get the Encoder that provides 7-bit encoding.
*
* @return Swift_Mime_ContentEncoder
*/
public static function get7BitEncoding()
{
return self::_lookup('mime.7bitcontentencoder');
}
/**
* Get the Encoder that provides 8-bit encoding.
*
* @return Swift_Mime_ContentEncoder
*/
public static function get8BitEncoding()
{
return self::_lookup('mime.8bitcontentencoder');
}
/**
* Get the Encoder that provides Quoted-Printable (QP) encoding.
*
* @return Swift_Mime_ContentEncoder
*/
public static function getQpEncoding()
{
return self::_lookup('mime.qpcontentencoder');
}
/**
* Get the Encoder that provides Base64 encoding.
*
* @return Swift_Mime_ContentEncoder
*/
public static function getBase64Encoding()
{
return self::_lookup('mime.base64contentencoder');
}
// -- Private Static Methods
private static function _lookup($key)
{
return Swift_DependencyContainer::getInstance()->lookup($key);
}
}

View File

@@ -20,14 +20,14 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject
*
* @var string
*/
private $_command;
private $command;
/**
* An array of codes which a successful response will contain.
*
* @var integer[]
* @var int[]
*/
private $_successCodes = array();
private $successCodes = array();
/**
* Create a new CommandEvent for $source with $command.
@@ -39,8 +39,8 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject
public function __construct(Swift_Transport $source, $command, $successCodes = array())
{
parent::__construct($source);
$this->_command = $command;
$this->_successCodes = $successCodes;
$this->command = $command;
$this->successCodes = $successCodes;
}
/**
@@ -50,16 +50,16 @@ class Swift_Events_CommandEvent extends Swift_Events_EventObject
*/
public function getCommand()
{
return $this->_command;
return $this->command;
}
/**
* Get the numeric response codes which indicate success for this command.
*
* @return integer[]
* @return int[]
*/
public function getSuccessCodes()
{
return $this->_successCodes;
return $this->successCodes;
}
}

View File

@@ -19,11 +19,11 @@ interface Swift_Events_EventDispatcher
* Create a new SendEvent for $source and $message.
*
* @param Swift_Transport $source
* @param Swift_Mime_Message
* @param Swift_Mime_SimpleMessage
*
* @return Swift_Events_SendEvent
*/
public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message);
public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message);
/**
* Create a new CommandEvent for $source and $command.

View File

@@ -16,10 +16,10 @@
class Swift_Events_EventObject implements Swift_Events_Event
{
/** The source of this Event */
private $_source;
private $source;
/** The state of this Event (should it bubble up the stack?) */
private $_bubbleCancelled = false;
private $bubbleCancelled = false;
/**
* Create a new EventObject originating at $source.
@@ -28,7 +28,7 @@ class Swift_Events_EventObject implements Swift_Events_Event
*/
public function __construct($source)
{
$this->_source = $source;
$this->source = $source;
}
/**
@@ -38,7 +38,7 @@ class Swift_Events_EventObject implements Swift_Events_Event
*/
public function getSource()
{
return $this->_source;
return $this->source;
}
/**
@@ -48,7 +48,7 @@ class Swift_Events_EventObject implements Swift_Events_Event
*/
public function cancelBubble($cancel = true)
{
$this->_bubbleCancelled = $cancel;
$this->bubbleCancelled = $cancel;
}
/**
@@ -58,6 +58,6 @@ class Swift_Events_EventObject implements Swift_Events_Event
*/
public function bubbleCancelled()
{
return $this->_bubbleCancelled;
return $this->bubbleCancelled;
}
}

View File

@@ -20,14 +20,14 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject
*
* @var bool
*/
private $_valid;
private $valid;
/**
* The response received from the server.
*
* @var string
*/
private $_response;
private $response;
/**
* Create a new ResponseEvent for $source and $response.
@@ -39,8 +39,8 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject
public function __construct(Swift_Transport $source, $response, $valid = false)
{
parent::__construct($source);
$this->_response = $response;
$this->_valid = $valid;
$this->response = $response;
$this->valid = $valid;
}
/**
@@ -50,7 +50,7 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject
*/
public function getResponse()
{
return $this->_response;
return $this->response;
}
/**
@@ -60,6 +60,6 @@ class Swift_Events_ResponseEvent extends Swift_Events_EventObject
*/
public function isValid()
{
return $this->_valid;
return $this->valid;
}
}

View File

@@ -33,35 +33,35 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject
/**
* The Message being sent.
*
* @var Swift_Mime_Message
* @var Swift_Mime_SimpleMessage
*/
private $_message;
private $message;
/**
* Any recipients which failed after sending.
*
* @var string[]
*/
private $_failedRecipients = array();
private $failedRecipients = array();
/**
* The overall result as a bitmask from the class constants.
*
* @var int
*/
private $_result;
private $result;
/**
* Create a new SendEvent for $source and $message.
*
* @param Swift_Transport $source
* @param Swift_Mime_Message $message
* @param Swift_Transport $source
* @param Swift_Mime_SimpleMessage $message
*/
public function __construct(Swift_Transport $source, Swift_Mime_Message $message)
public function __construct(Swift_Transport $source, Swift_Mime_SimpleMessage $message)
{
parent::__construct($source);
$this->_message = $message;
$this->_result = self::RESULT_PENDING;
$this->message = $message;
$this->result = self::RESULT_PENDING;
}
/**
@@ -77,11 +77,11 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject
/**
* Get the Message being sent.
*
* @return Swift_Mime_Message
* @return Swift_Mime_SimpleMessage
*/
public function getMessage()
{
return $this->_message;
return $this->message;
}
/**
@@ -91,7 +91,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject
*/
public function setFailedRecipients($recipients)
{
$this->_failedRecipients = $recipients;
$this->failedRecipients = $recipients;
}
/**
@@ -101,7 +101,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject
*/
public function getFailedRecipients()
{
return $this->_failedRecipients;
return $this->failedRecipients;
}
/**
@@ -111,7 +111,7 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject
*/
public function setResult($result)
{
$this->_result = $result;
$this->result = $result;
}
/**
@@ -124,6 +124,6 @@ class Swift_Events_SendEvent extends Swift_Events_EventObject
*/
public function getResult()
{
return $this->_result;
return $this->result;
}
}

View File

@@ -16,20 +16,20 @@
class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
{
/** A map of event types to their associated listener types */
private $_eventMap = array();
private $eventMap = array();
/** Event listeners bound to this dispatcher */
private $_listeners = array();
private $listeners = array();
/** Listeners queued to have an Event bubbled up the stack to them */
private $_bubbleQueue = array();
private $bubbleQueue = array();
/**
* Create a new EventDispatcher.
*/
public function __construct()
{
$this->_eventMap = array(
$this->eventMap = array(
'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener',
'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener',
'Swift_Events_SendEvent' => 'Swift_Events_SendListener',
@@ -42,11 +42,11 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
* Create a new SendEvent for $source and $message.
*
* @param Swift_Transport $source
* @param Swift_Mime_Message
* @param Swift_Mime_SimpleMessage
*
* @return Swift_Events_SendEvent
*/
public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message)
public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $message)
{
return new Swift_Events_SendEvent($source, $message);
}
@@ -111,13 +111,13 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
*/
public function bindEventListener(Swift_Events_EventListener $listener)
{
foreach ($this->_listeners as $l) {
foreach ($this->listeners as $l) {
// Already loaded
if ($l === $listener) {
return;
}
}
$this->_listeners[] = $listener;
$this->listeners[] = $listener;
}
/**
@@ -128,29 +128,29 @@ class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
*/
public function dispatchEvent(Swift_Events_EventObject $evt, $target)
{
$this->_prepareBubbleQueue($evt);
$this->_bubble($evt, $target);
$this->prepareBubbleQueue($evt);
$this->bubble($evt, $target);
}
/** Queue listeners on a stack ready for $evt to be bubbled up it */
private function _prepareBubbleQueue(Swift_Events_EventObject $evt)
private function prepareBubbleQueue(Swift_Events_EventObject $evt)
{
$this->_bubbleQueue = array();
$this->bubbleQueue = array();
$evtClass = get_class($evt);
foreach ($this->_listeners as $listener) {
if (array_key_exists($evtClass, $this->_eventMap)
&& ($listener instanceof $this->_eventMap[$evtClass])) {
$this->_bubbleQueue[] = $listener;
foreach ($this->listeners as $listener) {
if (array_key_exists($evtClass, $this->eventMap)
&& ($listener instanceof $this->eventMap[$evtClass])) {
$this->bubbleQueue[] = $listener;
}
}
}
/** Bubble $evt up the stack calling $target() on each listener */
private function _bubble(Swift_Events_EventObject $evt, $target)
private function bubble(Swift_Events_EventObject $evt, $target)
{
if (!$evt->bubbleCancelled() && $listener = array_shift($this->_bubbleQueue)) {
if (!$evt->bubbleCancelled() && $listener = array_shift($this->bubbleQueue)) {
$listener->$target($evt);
$this->_bubble($evt, $target);
$this->bubble($evt, $target);
}
}
}

View File

@@ -20,7 +20,7 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject
*
* @var Swift_TransportException
*/
private $_exception;
private $exception;
/**
* Create a new TransportExceptionEvent for $transport.
@@ -31,7 +31,7 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject
public function __construct(Swift_Transport $transport, Swift_TransportException $ex)
{
parent::__construct($transport);
$this->_exception = $ex;
$this->exception = $ex;
}
/**
@@ -41,6 +41,6 @@ class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject
*/
public function getException()
{
return $this->_exception;
return $this->exception;
}
}

View File

@@ -30,16 +30,4 @@ class Swift_FailoverTransport extends Swift_Transport_FailoverTransport
$this->setTransports($transports);
}
/**
* Create a new FailoverTransport instance.
*
* @param Swift_Transport[] $transports
*
* @return Swift_FailoverTransport
*/
public static function newInstance($transports = array())
{
return new self($transports);
}
}

View File

@@ -17,14 +17,14 @@
class Swift_FileSpool extends Swift_ConfigurableSpool
{
/** The spool directory */
private $_path;
private $path;
/**
* File WriteRetry Limit.
*
* @var int
*/
private $_retryLimit = 10;
private $retryLimit = 10;
/**
* Create a new FileSpool.
@@ -35,11 +35,11 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
*/
public function __construct($path)
{
$this->_path = $path;
$this->path = $path;
if (!file_exists($this->_path)) {
if (!mkdir($this->_path, 0777, true)) {
throw new Swift_IoException('Unable to create Path ['.$this->_path.']');
if (!file_exists($this->path)) {
if (!mkdir($this->path, 0777, true)) {
throw new Swift_IoException(sprintf('Unable to create path "%s".', $this->path));
}
}
}
@@ -77,25 +77,25 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
*/
public function setRetryLimit($limit)
{
$this->_retryLimit = $limit;
$this->retryLimit = $limit;
}
/**
* Queues a message.
*
* @param Swift_Mime_Message $message The message to store
* @param Swift_Mime_SimpleMessage $message The message to store
*
* @throws Swift_IoException
*
* @return bool
*/
public function queueMessage(Swift_Mime_Message $message)
public function queueMessage(Swift_Mime_SimpleMessage $message)
{
$ser = serialize($message);
$fileName = $this->_path.'/'.$this->getRandomString(10);
for ($i = 0; $i < $this->_retryLimit; ++$i) {
$fileName = $this->path.'/'.$this->getRandomString(10);
for ($i = 0; $i < $this->retryLimit; ++$i) {
/* We try an exclusive creation of the file. This is an atomic operation, it avoid locking mechanism */
$fp = @fopen($fileName.'.message', 'x');
$fp = @fopen($fileName.'.message', 'xb');
if (false !== $fp) {
if (false === fwrite($fp, $ser)) {
return false;
@@ -108,7 +108,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
}
}
throw new Swift_IoException('Unable to create a file for enqueuing Message');
throw new Swift_IoException(sprintf('Unable to create a file for enqueuing Message in "%s".', $this->path));
}
/**
@@ -118,7 +118,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
*/
public function recover($timeout = 900)
{
foreach (new DirectoryIterator($this->_path) as $file) {
foreach (new DirectoryIterator($this->path) as $file) {
$file = $file->getRealPath();
if (substr($file, -16) == '.message.sending') {
@@ -140,7 +140,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
*/
public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
{
$directoryIterator = new DirectoryIterator($this->_path);
$directoryIterator = new DirectoryIterator($this->path);
/* Start the transport only if there are queued files to send */
if (!$transport->isStarted()) {
@@ -200,7 +200,7 @@ class Swift_FileSpool extends Swift_ConfigurableSpool
$ret = '';
$strlen = strlen($base);
for ($i = 0; $i < $count; ++$i) {
$ret .= $base[((int) rand(0, $strlen - 1))];
$ret .= $base[random_int(0, $strlen - 1)];
}
return $ret;

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.
*/
/**
* Message ID generator.
*/
interface Swift_IdGenerator
{
/**
* Returns a globally unique string to use for Message-ID or Content-ID.
*
* @return string
*/
public function generateId();
}

View File

@@ -29,33 +29,15 @@ class Swift_Image extends Swift_EmbeddedFile
parent::__construct($data, $filename, $contentType);
}
/**
* Create a new Image.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*
* @return Swift_Image
*/
public static function newInstance($data = null, $filename = null, $contentType = null)
{
return new self($data, $filename, $contentType);
}
/**
* Create a new Image from a filesystem path.
*
* @param string $path
*
* @return Swift_Image
* @return self
*/
public static function fromPath($path)
{
$image = self::newInstance()->setFile(
new Swift_ByteStream_FileByteStream($path)
);
return $image;
return (new self())->setFile(new Swift_ByteStream_FileByteStream($path));
}
}

View File

@@ -20,14 +20,14 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*
* @var array
*/
private $_contents = array();
private $contents = array();
/**
* An InputStream for cloning.
*
* @var Swift_KeyCache_KeyCacheInputStream
*/
private $_stream;
private $stream;
/**
* Create a new ArrayKeyCache with the given $stream for cloning to make
@@ -37,7 +37,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function __construct(Swift_KeyCache_KeyCacheInputStream $stream)
{
$this->_stream = $stream;
$this->stream = $stream;
}
/**
@@ -52,16 +52,16 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function setString($nsKey, $itemKey, $string, $mode)
{
$this->_prepareCache($nsKey);
$this->prepareCache($nsKey);
switch ($mode) {
case self::MODE_WRITE:
$this->_contents[$nsKey][$itemKey] = $string;
$this->contents[$nsKey][$itemKey] = $string;
break;
case self::MODE_APPEND:
if (!$this->hasKey($nsKey, $itemKey)) {
$this->_contents[$nsKey][$itemKey] = '';
$this->contents[$nsKey][$itemKey] = '';
}
$this->_contents[$nsKey][$itemKey] .= $string;
$this->contents[$nsKey][$itemKey] .= $string;
break;
default:
throw new Swift_SwiftException(
@@ -83,16 +83,16 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode)
{
$this->_prepareCache($nsKey);
$this->prepareCache($nsKey);
switch ($mode) {
case self::MODE_WRITE:
$this->clearKey($nsKey, $itemKey);
case self::MODE_APPEND:
if (!$this->hasKey($nsKey, $itemKey)) {
$this->_contents[$nsKey][$itemKey] = '';
$this->contents[$nsKey][$itemKey] = '';
}
while (false !== $bytes = $os->read(8192)) {
$this->_contents[$nsKey][$itemKey] .= $bytes;
$this->contents[$nsKey][$itemKey] .= $bytes;
}
break;
default:
@@ -116,7 +116,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null)
{
$is = clone $this->_stream;
$is = clone $this->stream;
$is->setKeyCache($this);
$is->setNsKey($nsKey);
$is->setItemKey($itemKey);
@@ -137,9 +137,9 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function getString($nsKey, $itemKey)
{
$this->_prepareCache($nsKey);
$this->prepareCache($nsKey);
if ($this->hasKey($nsKey, $itemKey)) {
return $this->_contents[$nsKey][$itemKey];
return $this->contents[$nsKey][$itemKey];
}
}
@@ -152,7 +152,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is)
{
$this->_prepareCache($nsKey);
$this->prepareCache($nsKey);
$is->write($this->getString($nsKey, $itemKey));
}
@@ -166,9 +166,9 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function hasKey($nsKey, $itemKey)
{
$this->_prepareCache($nsKey);
$this->prepareCache($nsKey);
return array_key_exists($itemKey, $this->_contents[$nsKey]);
return array_key_exists($itemKey, $this->contents[$nsKey]);
}
/**
@@ -179,7 +179,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function clearKey($nsKey, $itemKey)
{
unset($this->_contents[$nsKey][$itemKey]);
unset($this->contents[$nsKey][$itemKey]);
}
/**
@@ -189,7 +189,7 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*/
public function clearAll($nsKey)
{
unset($this->_contents[$nsKey]);
unset($this->contents[$nsKey]);
}
/**
@@ -197,10 +197,10 @@ class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
*
* @param string $nsKey
*/
private function _prepareCache($nsKey)
private function prepareCache($nsKey)
{
if (!array_key_exists($nsKey, $this->_contents)) {
$this->_contents[$nsKey] = array();
if (!array_key_exists($nsKey, $this->contents)) {
$this->contents[$nsKey] = array();
}
}
}

View File

@@ -29,28 +29,21 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*
* @var Swift_KeyCache_KeyCacheInputStream
*/
private $_stream;
private $stream;
/**
* A path to write to.
*
* @var string
*/
private $_path;
private $path;
/**
* Stored keys.
*
* @var array
*/
private $_keys = array();
/**
* Will be true if magic_quotes_runtime is turned on.
*
* @var bool
*/
private $_quotes = false;
private $keys = array();
/**
* Create a new DiskKeyCache with the given $stream for cloning to make
@@ -61,12 +54,8 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/
public function __construct(Swift_KeyCache_KeyCacheInputStream $stream, $path)
{
$this->_stream = $stream;
$this->_path = $path;
if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) {
$this->_quotes = true;
}
$this->stream = $stream;
$this->path = $path;
}
/**
@@ -83,13 +72,13 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/
public function setString($nsKey, $itemKey, $string, $mode)
{
$this->_prepareCache($nsKey);
$this->prepareCache($nsKey);
switch ($mode) {
case self::MODE_WRITE:
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START);
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START);
break;
case self::MODE_APPEND:
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END);
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END);
break;
default:
throw new Swift_SwiftException(
@@ -99,7 +88,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
break;
}
fwrite($fp, $string);
$this->_freeHandle($nsKey, $itemKey);
$this->freeHandle($nsKey, $itemKey);
}
/**
@@ -116,13 +105,13 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode)
{
$this->_prepareCache($nsKey);
$this->prepareCache($nsKey);
switch ($mode) {
case self::MODE_WRITE:
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START);
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START);
break;
case self::MODE_APPEND:
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END);
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_END);
break;
default:
throw new Swift_SwiftException(
@@ -134,7 +123,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
while (false !== $bytes = $os->read(8192)) {
fwrite($fp, $bytes);
}
$this->_freeHandle($nsKey, $itemKey);
$this->freeHandle($nsKey, $itemKey);
}
/**
@@ -150,7 +139,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/
public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null)
{
$is = clone $this->_stream;
$is = clone $this->stream;
$is->setKeyCache($this);
$is->setNsKey($nsKey);
$is->setItemKey($itemKey);
@@ -173,20 +162,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/
public function getString($nsKey, $itemKey)
{
$this->_prepareCache($nsKey);
$this->prepareCache($nsKey);
if ($this->hasKey($nsKey, $itemKey)) {
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START);
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 0);
}
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START);
$str = '';
while (!feof($fp) && false !== $bytes = fread($fp, 8192)) {
$str .= $bytes;
}
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 1);
}
$this->_freeHandle($nsKey, $itemKey);
$this->freeHandle($nsKey, $itemKey);
return $str;
}
@@ -202,17 +185,11 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is)
{
if ($this->hasKey($nsKey, $itemKey)) {
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START);
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 0);
}
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_START);
while (!feof($fp) && false !== $bytes = fread($fp, 8192)) {
$is->write($bytes);
}
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 1);
}
$this->_freeHandle($nsKey, $itemKey);
$this->freeHandle($nsKey, $itemKey);
}
}
@@ -226,7 +203,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/
public function hasKey($nsKey, $itemKey)
{
return is_file($this->_path.'/'.$nsKey.'/'.$itemKey);
return is_file($this->path.'/'.$nsKey.'/'.$itemKey);
}
/**
@@ -238,8 +215,8 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
public function clearKey($nsKey, $itemKey)
{
if ($this->hasKey($nsKey, $itemKey)) {
$this->_freeHandle($nsKey, $itemKey);
unlink($this->_path.'/'.$nsKey.'/'.$itemKey);
$this->freeHandle($nsKey, $itemKey);
unlink($this->path.'/'.$nsKey.'/'.$itemKey);
}
}
@@ -250,14 +227,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/
public function clearAll($nsKey)
{
if (array_key_exists($nsKey, $this->_keys)) {
foreach ($this->_keys[$nsKey] as $itemKey => $null) {
if (array_key_exists($nsKey, $this->keys)) {
foreach ($this->keys[$nsKey] as $itemKey => $null) {
$this->clearKey($nsKey, $itemKey);
}
if (is_dir($this->_path.'/'.$nsKey)) {
rmdir($this->_path.'/'.$nsKey);
if (is_dir($this->path.'/'.$nsKey)) {
rmdir($this->path.'/'.$nsKey);
}
unset($this->_keys[$nsKey]);
unset($this->keys[$nsKey]);
}
}
@@ -266,14 +243,14 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*
* @param string $nsKey
*/
private function _prepareCache($nsKey)
private function prepareCache($nsKey)
{
$cacheDir = $this->_path.'/'.$nsKey;
$cacheDir = $this->path.'/'.$nsKey;
if (!is_dir($cacheDir)) {
if (!mkdir($cacheDir)) {
throw new Swift_IoException('Failed to create cache directory '.$cacheDir);
}
$this->_keys[$nsKey] = array();
$this->keys[$nsKey] = array();
}
}
@@ -286,27 +263,27 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*
* @return resource
*/
private function _getHandle($nsKey, $itemKey, $position)
private function getHandle($nsKey, $itemKey, $position)
{
if (!isset($this->_keys[$nsKey][$itemKey])) {
if (!isset($this->keys[$nsKey][$itemKey])) {
$openMode = $this->hasKey($nsKey, $itemKey) ? 'r+b' : 'w+b';
$fp = fopen($this->_path.'/'.$nsKey.'/'.$itemKey, $openMode);
$this->_keys[$nsKey][$itemKey] = $fp;
$fp = fopen($this->path.'/'.$nsKey.'/'.$itemKey, $openMode);
$this->keys[$nsKey][$itemKey] = $fp;
}
if (self::POSITION_START == $position) {
fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_SET);
fseek($this->keys[$nsKey][$itemKey], 0, SEEK_SET);
} elseif (self::POSITION_END == $position) {
fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_END);
fseek($this->keys[$nsKey][$itemKey], 0, SEEK_END);
}
return $this->_keys[$nsKey][$itemKey];
return $this->keys[$nsKey][$itemKey];
}
private function _freeHandle($nsKey, $itemKey)
private function freeHandle($nsKey, $itemKey)
{
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_CURRENT);
$fp = $this->getHandle($nsKey, $itemKey, self::POSITION_CURRENT);
fclose($fp);
$this->_keys[$nsKey][$itemKey] = null;
$this->keys[$nsKey][$itemKey] = null;
}
/**
@@ -314,7 +291,7 @@ class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
*/
public function __destruct()
{
foreach ($this->_keys as $nsKey => $null) {
foreach ($this->keys as $nsKey => $null) {
$this->clearAll($nsKey);
}
}

View File

@@ -16,16 +16,16 @@
class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCacheInputStream
{
/** The KeyCache being written to */
private $_keyCache;
private $keyCache;
/** The nsKey of the KeyCache being written to */
private $_nsKey;
private $nsKey;
/** The itemKey of the KeyCache being written to */
private $_itemKey;
private $itemKey;
/** A stream to write through on each write() */
private $_writeThrough = null;
private $writeThrough = null;
/**
* Set the KeyCache to wrap.
@@ -34,7 +34,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
*/
public function setKeyCache(Swift_KeyCache $keyCache)
{
$this->_keyCache = $keyCache;
$this->keyCache = $keyCache;
}
/**
@@ -44,7 +44,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
*/
public function setWriteThroughStream(Swift_InputByteStream $is)
{
$this->_writeThrough = $is;
$this->writeThrough = $is;
}
/**
@@ -55,14 +55,14 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
*/
public function write($bytes, Swift_InputByteStream $is = null)
{
$this->_keyCache->setString(
$this->_nsKey, $this->_itemKey, $bytes, Swift_KeyCache::MODE_APPEND
$this->keyCache->setString(
$this->nsKey, $this->itemKey, $bytes, Swift_KeyCache::MODE_APPEND
);
if (isset($is)) {
$is->write($bytes);
}
if (isset($this->_writeThrough)) {
$this->_writeThrough->write($bytes);
if (isset($this->writeThrough)) {
$this->writeThrough->write($bytes);
}
}
@@ -93,7 +93,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
*/
public function flushBuffers()
{
$this->_keyCache->clearKey($this->_nsKey, $this->_itemKey);
$this->keyCache->clearKey($this->nsKey, $this->itemKey);
}
/**
@@ -103,7 +103,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
*/
public function setNsKey($nsKey)
{
$this->_nsKey = $nsKey;
$this->nsKey = $nsKey;
}
/**
@@ -113,7 +113,7 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
*/
public function setItemKey($itemKey)
{
$this->_itemKey = $itemKey;
$this->itemKey = $itemKey;
}
/**
@@ -122,6 +122,6 @@ class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCach
*/
public function __clone()
{
$this->_writeThrough = null;
$this->writeThrough = null;
}
}

View File

@@ -30,16 +30,4 @@ class Swift_LoadBalancedTransport extends Swift_Transport_LoadBalancedTransport
$this->setTransports($transports);
}
/**
* Create a new LoadBalancedTransport instance.
*
* @param array $transports
*
* @return Swift_LoadBalancedTransport
*/
public static function newInstance($transports = array())
{
return new self($transports);
}
}

View File

@@ -1,45 +0,0 @@
<?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.
*/
/**
* Sends Messages using the mail() function.
*
* @author Chris Corbyn
*/
class Swift_MailTransport extends Swift_Transport_MailTransport
{
/**
* Create a new MailTransport, optionally specifying $extraParams.
*
* @param string $extraParams
*/
public function __construct($extraParams = '-f%s')
{
call_user_func_array(
array($this, 'Swift_Transport_MailTransport::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('transport.mail')
);
$this->setExtraParams($extraParams);
}
/**
* Create a new MailTransport instance.
*
* @param string $extraParams To be passed to mail()
*
* @return Swift_MailTransport
*/
public static function newInstance($extraParams = '-f%s')
{
return new self($extraParams);
}
}

View File

@@ -16,7 +16,7 @@
class Swift_Mailer
{
/** The Transport used to send messages */
private $_transport;
private $transport;
/**
* Create a new Mailer using $transport for delivery.
@@ -25,19 +25,7 @@ class Swift_Mailer
*/
public function __construct(Swift_Transport $transport)
{
$this->_transport = $transport;
}
/**
* Create a new Mailer instance.
*
* @param Swift_Transport $transport
*
* @return Swift_Mailer
*/
public static function newInstance(Swift_Transport $transport)
{
return new self($transport);
$this->transport = $transport;
}
/**
@@ -66,23 +54,23 @@ class Swift_Mailer
* The return value is the number of recipients who were accepted for
* delivery.
*
* @param Swift_Mime_Message $message
* @param array $failedRecipients An array of failures by-reference
* @param Swift_Mime_SimpleMessage $message
* @param array $failedRecipients An array of failures by-reference
*
* @return int
* @return int The number of successful recipients. Can be 0 which indicates failure
*/
public function send(Swift_Mime_Message $message, &$failedRecipients = null)
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
{
$failedRecipients = (array) $failedRecipients;
if (!$this->_transport->isStarted()) {
$this->_transport->start();
if (!$this->transport->isStarted()) {
$this->transport->start();
}
$sent = 0;
try {
$sent = $this->_transport->send($message, $failedRecipients);
$sent = $this->transport->send($message, $failedRecipients);
} catch (Swift_RfcComplianceException $e) {
foreach ($message->getTo() as $address => $name) {
$failedRecipients[] = $address;
@@ -99,7 +87,7 @@ class Swift_Mailer
*/
public function registerPlugin(Swift_Events_EventListener $plugin)
{
$this->_transport->registerPlugin($plugin);
$this->transport->registerPlugin($plugin);
}
/**
@@ -109,6 +97,6 @@ class Swift_Mailer
*/
public function getTransport()
{
return $this->_transport;
return $this->transport;
}
}

View File

@@ -20,7 +20,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera
*
* @var array
*/
private $_recipients = array();
private $recipients = array();
/**
* Create a new ArrayRecipientIterator from $recipients.
@@ -29,7 +29,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera
*/
public function __construct(array $recipients)
{
$this->_recipients = $recipients;
$this->recipients = $recipients;
}
/**
@@ -39,7 +39,7 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera
*/
public function hasNext()
{
return !empty($this->_recipients);
return !empty($this->recipients);
}
/**
@@ -50,6 +50,6 @@ class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientItera
*/
public function nextRecipient()
{
return array_splice($this->_recipients, 0, 1);
return array_splice($this->recipients, 0, 1);
}
}

View File

@@ -16,6 +16,7 @@
class Swift_MemorySpool implements Swift_Spool
{
protected $messages = array();
private $flushRetries = 3;
/**
* Tests if this Transport mechanism has started.
@@ -41,14 +42,22 @@ class Swift_MemorySpool implements Swift_Spool
{
}
/**
* @param int $retries
*/
public function setFlushRetries($retries)
{
$this->flushRetries = $retries;
}
/**
* Stores a message in the queue.
*
* @param Swift_Mime_Message $message The message to store
* @param Swift_Mime_SimpleMessage $message The message to store
*
* @return bool Whether the operation has succeeded
*/
public function queueMessage(Swift_Mime_Message $message)
public function queueMessage(Swift_Mime_SimpleMessage $message)
{
//clone the message to make sure it is not changed while in the queue
$this->messages[] = clone $message;
@@ -75,8 +84,25 @@ class Swift_MemorySpool implements Swift_Spool
}
$count = 0;
while ($message = array_pop($this->messages)) {
$count += $transport->send($message, $failedRecipients);
$retries = $this->flushRetries;
while ($retries--) {
try {
while ($message = array_pop($this->messages)) {
$count += $transport->send($message, $failedRecipients);
}
} catch (Swift_TransportException $exception) {
if ($retries) {
// re-queue the message at the end of the queue to give a chance
// to the other messages to be sent, in case the failure was due to
// this message and not just the transport failing
array_unshift($this->messages, $message);
// wait half a second before we try again
usleep(500000);
} else {
throw $exception;
}
}
}
return $count;

View File

@@ -60,21 +60,6 @@ class Swift_Message extends Swift_Mime_SimpleMessage
}
}
/**
* Create a new Message.
*
* @param string $subject
* @param string $body
* @param string $contentType
* @param string $charset
*
* @return Swift_Message
*/
public static function newInstance($subject = null, $body = null, $contentType = null, $charset = null)
{
return new self($subject, $body, $contentType, $charset);
}
/**
* Add a MimePart to this Message.
*
@@ -82,21 +67,19 @@ class Swift_Message extends Swift_Mime_SimpleMessage
* @param string $contentType
* @param string $charset
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function addPart($body, $contentType = null, $charset = null)
{
return $this->attach(Swift_MimePart::newInstance(
$body, $contentType, $charset
));
return $this->attach((new Swift_MimePart($body, $contentType, $charset))->setEncoder($this->getEncoder()));
}
/**
* Attach a new signature handler to the message.
* Detach a signature handler from a message.
*
* @param Swift_Signer $signer
*
* @return Swift_Message
* @return $this
*/
public function attachSigner(Swift_Signer $signer)
{
@@ -114,7 +97,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage
*
* @param Swift_Signer $signer
*
* @return Swift_Message
* @return $this
*/
public function detachSigner(Swift_Signer $signer)
{
@@ -207,7 +190,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage
$signer->setHeaders($this->getHeaders());
$signer->startBody();
$this->_bodyToByteStream($signer);
$this->bodyToByteStream($signer);
$signer->endBody();
$signer->addSignature($this->getHeaders());
@@ -223,7 +206,7 @@ class Swift_Message extends Swift_Mime_SimpleMessage
$this->savedMessage['body'] = $this->getBody();
$this->savedMessage['children'] = $this->getChildren();
if (count($this->savedMessage['children']) > 0 && $this->getBody() != '') {
$this->setChildren(array_merge(array($this->_becomeMimePart()), $this->savedMessage['children']));
$this->setChildren(array_merge(array($this->becomeMimePart()), $this->savedMessage['children']));
$this->setBody('');
}
}
@@ -281,11 +264,11 @@ class Swift_Message extends Swift_Mime_SimpleMessage
{
parent::__clone();
foreach ($this->bodySigners as $key => $bodySigner) {
$this->bodySigners[$key] = clone($bodySigner);
$this->bodySigners[$key] = clone $bodySigner;
}
foreach ($this->headerSigners as $key => $headerSigner) {
$this->headerSigners[$key] = clone($headerSigner);
$this->headerSigners[$key] = clone $headerSigner;
}
}
}

View File

@@ -16,23 +16,23 @@
class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
{
/** Recognized MIME types */
private $_mimeTypes = array();
private $mimeTypes = array();
/**
* Create a new Attachment with $headers, $encoder and $cache.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_Mime_Grammar $grammar
* @param array $mimeTypes optional
* @param Swift_Mime_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param array $mimeTypes
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $mimeTypes = array())
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array())
{
parent::__construct($headers, $encoder, $cache, $grammar);
parent::__construct($headers, $encoder, $cache, $idGenerator);
$this->setDisposition('attachment');
$this->setContentType('application/octet-stream');
$this->_mimeTypes = $mimeTypes;
$this->mimeTypes = $mimeTypes;
}
/**
@@ -56,7 +56,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
*/
public function getDisposition()
{
return $this->_getHeaderFieldModel('Content-Disposition');
return $this->getHeaderFieldModel('Content-Disposition');
}
/**
@@ -64,11 +64,11 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
*
* @param string $disposition
*
* @return Swift_Mime_Attachment
* @return $this
*/
public function setDisposition($disposition)
{
if (!$this->_setHeaderFieldModel('Content-Disposition', $disposition)) {
if (!$this->setHeaderFieldModel('Content-Disposition', $disposition)) {
$this->getHeaders()->addParameterizedHeader('Content-Disposition', $disposition);
}
@@ -82,7 +82,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
*/
public function getFilename()
{
return $this->_getHeaderParameter('Content-Disposition', 'filename');
return $this->getHeaderParameter('Content-Disposition', 'filename');
}
/**
@@ -90,12 +90,12 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
*
* @param string $filename
*
* @return Swift_Mime_Attachment
* @return $this
*/
public function setFilename($filename)
{
$this->_setHeaderParameter('Content-Disposition', 'filename', $filename);
$this->_setHeaderParameter('Content-Type', 'name', $filename);
$this->setHeaderParameter('Content-Disposition', 'filename', $filename);
$this->setHeaderParameter('Content-Type', 'name', $filename);
return $this;
}
@@ -107,7 +107,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
*/
public function getSize()
{
return $this->_getHeaderParameter('Content-Disposition', 'size');
return $this->getHeaderParameter('Content-Disposition', 'size');
}
/**
@@ -115,11 +115,11 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
*
* @param int $size
*
* @return Swift_Mime_Attachment
* @return $this
*/
public function setSize($size)
{
$this->_setHeaderParameter('Content-Disposition', 'size', $size);
$this->setHeaderParameter('Content-Disposition', 'size', $size);
return $this;
}
@@ -130,7 +130,7 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
* @param Swift_FileStream $file
* @param string $contentType optional
*
* @return Swift_Mime_Attachment
* @return $this
*/
public function setFile(Swift_FileStream $file, $contentType = null)
{
@@ -139,8 +139,8 @@ class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
if (!isset($contentType)) {
$extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1));
if (array_key_exists($extension, $this->_mimeTypes)) {
$this->setContentType($this->_mimeTypes[$extension]);
if (array_key_exists($extension, $this->mimeTypes)) {
$this->setContentType($this->mimeTypes[$extension]);
}
}

View File

@@ -92,7 +92,7 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con
sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset));
}
return $this->_standardize(quoted_printable_encode($string));
return $this->standardize(quoted_printable_encode($string));
}
/**
@@ -102,7 +102,7 @@ class Swift_Mime_ContentEncoder_NativeQpContentEncoder implements Swift_Mime_Con
*
* @return string
*/
protected function _standardize($string)
protected function standardize($string)
{
// transform CR or LF to CRLF
$string = preg_replace('~=0D(?!=0A)|(?<!=0D)=0A~', '=0D=0A', $string);

View File

@@ -20,14 +20,14 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
*
* @var string
*/
private $_name;
private $name;
/**
* True if canonical transformations should be done.
*
* @var bool
*/
private $_canonical;
private $canonical;
/**
* Creates a new PlainContentEncoder with $name (probably 7bit or 8bit).
@@ -37,8 +37,8 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
*/
public function __construct($name, $canonical = false)
{
$this->_name = $name;
$this->_canonical = $canonical;
$this->name = $name;
$this->canonical = $canonical;
}
/**
@@ -52,11 +52,11 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
if ($this->_canonical) {
$string = $this->_canonicalize($string);
if ($this->canonical) {
$string = $this->canonicalize($string);
}
return $this->_safeWordWrap($string, $maxLineLength, "\r\n");
return $this->safeWordwrap($string, $maxLineLength, "\r\n");
}
/**
@@ -72,10 +72,10 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
$leftOver = '';
while (false !== $bytes = $os->read(8192)) {
$toencode = $leftOver.$bytes;
if ($this->_canonical) {
$toencode = $this->_canonicalize($toencode);
if ($this->canonical) {
$toencode = $this->canonicalize($toencode);
}
$wrapped = $this->_safeWordWrap($toencode, $maxLineLength, "\r\n");
$wrapped = $this->safeWordwrap($toencode, $maxLineLength, "\r\n");
$lastLinePos = strrpos($wrapped, "\r\n");
$leftOver = substr($wrapped, $lastLinePos);
$wrapped = substr($wrapped, 0, $lastLinePos);
@@ -94,7 +94,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
*/
public function getName()
{
return $this->_name;
return $this->name;
}
/**
@@ -113,7 +113,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
*
* @return string
*/
private function _safeWordwrap($string, $length = 75, $le = "\r\n")
private function safeWordwrap($string, $length = 75, $le = "\r\n")
{
if (0 >= $length) {
return $string;
@@ -151,7 +151,7 @@ class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_Conten
*
* @return string
*/
private function _canonicalize($string)
private function canonicalize($string)
{
return str_replace(
array("\r\n", "\r", "\n"),

View File

@@ -11,11 +11,11 @@
/**
* Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer.
*
* @author Chris Corbyn
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_ContentEncoder
{
protected $_dotEscape;
protected $dotEscape;
/**
* Creates a new QpContentEncoder for the given CharacterStream.
@@ -26,26 +26,26 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder
*/
public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null, $dotEscape = false)
{
$this->_dotEscape = $dotEscape;
$this->dotEscape = $dotEscape;
parent::__construct($charStream, $filter);
}
public function __sleep()
{
return array('_charStream', '_filter', '_dotEscape');
return array('charStream', 'filter', 'dotEscape');
}
protected function getSafeMapShareId()
{
return get_class($this).($this->_dotEscape ? '.dotEscape' : '');
return get_class($this).($this->dotEscape ? '.dotEscape' : '');
}
protected function initSafeMap()
{
parent::initSafeMap();
if ($this->_dotEscape) {
if ($this->dotEscape) {
/* Encode . as =2e for buggy remote servers */
unset($this->_safeMap[0x2e]);
unset($this->safeMap[0x2e]);
}
}
@@ -69,20 +69,20 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder
$thisLineLength = $maxLineLength - $firstLineOffset;
$this->_charStream->flushContents();
$this->_charStream->importByteStream($os);
$this->charStream->flushContents();
$this->charStream->importByteStream($os);
$currentLine = '';
$prepend = '';
$size = $lineLen = 0;
while (false !== $bytes = $this->_nextSequence()) {
while (false !== $bytes = $this->nextSequence()) {
// If we're filtering the input
if (isset($this->_filter)) {
if (isset($this->filter)) {
// If we can't filter because we need more bytes
while ($this->_filter->shouldBuffer($bytes)) {
while ($this->filter->shouldBuffer($bytes)) {
// Then collect bytes into the buffer
if (false === $moreBytes = $this->_nextSequence(1)) {
if (false === $moreBytes = $this->nextSequence(1)) {
break;
}
@@ -91,16 +91,16 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder
}
}
// And filter them
$bytes = $this->_filter->filter($bytes);
$bytes = $this->filter->filter($bytes);
}
$enc = $this->_encodeByteSequence($bytes, $size);
$enc = $this->encodeByteSequence($bytes, $size);
$i = strpos($enc, '=0D=0A');
$newLineLength = $lineLen + ($i === false ? $size : $i);
if ($currentLine && $newLineLength >= $thisLineLength) {
$is->write($prepend.$this->_standardize($currentLine));
$is->write($prepend.$this->standardize($currentLine));
$currentLine = '';
$prepend = "=\r\n";
$thisLineLength = $maxLineLength;
@@ -117,7 +117,7 @@ class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder
}
}
if (strlen($currentLine)) {
$is->write($prepend.$this->_standardize($currentLine));
$is->write($prepend.$this->standardize($currentLine));
}
}

View File

@@ -18,15 +18,15 @@ class Swift_Mime_EmbeddedFile extends Swift_Mime_Attachment
/**
* Creates a new Attachment with $headers and $encoder.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_Mime_Grammar $grammar
* @param array $mimeTypes optional
* @param Swift_Mime_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param array $mimeTypes optional
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $mimeTypes = array())
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array())
{
parent::__construct($headers, $encoder, $cache, $grammar, $mimeTypes);
parent::__construct($headers, $encoder, $cache, $idGenerator, $mimeTypes);
$this->setDisposition('inline');
$this->setId($this->getId());
}

View File

@@ -1,176 +0,0 @@
<?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.
*/
/**
* Defines the grammar to use for validation, implements the RFC 2822 (and friends) ABNF grammar definitions.
*
* @author Fabien Potencier
* @author Chris Corbyn
*/
class Swift_Mime_Grammar
{
/**
* Special characters used in the syntax which need to be escaped.
*
* @var string[]
*/
private static $_specials = array();
/**
* Tokens defined in RFC 2822 (and some related RFCs).
*
* @var string[]
*/
private static $_grammar = array();
/**
* Initialize some RFC 2822 (and friends) ABNF grammar definitions.
*/
public function __construct()
{
$this->init();
}
public function __wakeup()
{
$this->init();
}
protected function init()
{
if (count(self::$_specials) > 0) {
return;
}
self::$_specials = array(
'(', ')', '<', '>', '[', ']',
':', ';', '@', ',', '.', '"',
);
/*** Refer to RFC 2822 for ABNF grammar ***/
// All basic building blocks
self::$_grammar['NO-WS-CTL'] = '[\x01-\x08\x0B\x0C\x0E-\x19\x7F]';
self::$_grammar['WSP'] = '[ \t]';
self::$_grammar['CRLF'] = '(?:\r\n)';
self::$_grammar['FWS'] = '(?:(?:'.self::$_grammar['WSP'].'*'.
self::$_grammar['CRLF'].')?'.self::$_grammar['WSP'].')';
self::$_grammar['text'] = '[\x00-\x08\x0B\x0C\x0E-\x7F]';
self::$_grammar['quoted-pair'] = '(?:\\\\'.self::$_grammar['text'].')';
self::$_grammar['ctext'] = '(?:'.self::$_grammar['NO-WS-CTL'].
'|[\x21-\x27\x2A-\x5B\x5D-\x7E])';
// Uses recursive PCRE (?1) -- could be a weak point??
self::$_grammar['ccontent'] = '(?:'.self::$_grammar['ctext'].'|'.
self::$_grammar['quoted-pair'].'|(?1))';
self::$_grammar['comment'] = '(\((?:'.self::$_grammar['FWS'].'|'.
self::$_grammar['ccontent'].')*'.self::$_grammar['FWS'].'?\))';
self::$_grammar['CFWS'] = '(?:(?:'.self::$_grammar['FWS'].'?'.
self::$_grammar['comment'].')*(?:(?:'.self::$_grammar['FWS'].'?'.
self::$_grammar['comment'].')|'.self::$_grammar['FWS'].'))';
self::$_grammar['qtext'] = '(?:'.self::$_grammar['NO-WS-CTL'].
'|[\x21\x23-\x5B\x5D-\x7E])';
self::$_grammar['qcontent'] = '(?:'.self::$_grammar['qtext'].'|'.
self::$_grammar['quoted-pair'].')';
self::$_grammar['quoted-string'] = '(?:'.self::$_grammar['CFWS'].'?"'.
'('.self::$_grammar['FWS'].'?'.self::$_grammar['qcontent'].')*'.
self::$_grammar['FWS'].'?"'.self::$_grammar['CFWS'].'?)';
self::$_grammar['atext'] = '[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]';
self::$_grammar['atom'] = '(?:'.self::$_grammar['CFWS'].'?'.
self::$_grammar['atext'].'+'.self::$_grammar['CFWS'].'?)';
self::$_grammar['dot-atom-text'] = '(?:'.self::$_grammar['atext'].'+'.
'(\.'.self::$_grammar['atext'].'+)*)';
self::$_grammar['dot-atom'] = '(?:'.self::$_grammar['CFWS'].'?'.
self::$_grammar['dot-atom-text'].'+'.self::$_grammar['CFWS'].'?)';
self::$_grammar['word'] = '(?:'.self::$_grammar['atom'].'|'.
self::$_grammar['quoted-string'].')';
self::$_grammar['phrase'] = '(?:'.self::$_grammar['word'].'+?)';
self::$_grammar['no-fold-quote'] = '(?:"(?:'.self::$_grammar['qtext'].
'|'.self::$_grammar['quoted-pair'].')*")';
self::$_grammar['dtext'] = '(?:'.self::$_grammar['NO-WS-CTL'].
'|[\x21-\x5A\x5E-\x7E])';
self::$_grammar['no-fold-literal'] = '(?:\[(?:'.self::$_grammar['dtext'].
'|'.self::$_grammar['quoted-pair'].')*\])';
// Message IDs
self::$_grammar['id-left'] = '(?:'.self::$_grammar['dot-atom-text'].'|'.
self::$_grammar['no-fold-quote'].')';
self::$_grammar['id-right'] = '(?:'.self::$_grammar['dot-atom-text'].'|'.
self::$_grammar['no-fold-literal'].')';
// Addresses, mailboxes and paths
self::$_grammar['local-part'] = '(?:'.self::$_grammar['dot-atom'].'|'.
self::$_grammar['quoted-string'].')';
self::$_grammar['dcontent'] = '(?:'.self::$_grammar['dtext'].'|'.
self::$_grammar['quoted-pair'].')';
self::$_grammar['domain-literal'] = '(?:'.self::$_grammar['CFWS'].'?\[('.
self::$_grammar['FWS'].'?'.self::$_grammar['dcontent'].')*?'.
self::$_grammar['FWS'].'?\]'.self::$_grammar['CFWS'].'?)';
self::$_grammar['domain'] = '(?:'.self::$_grammar['dot-atom'].'|'.
self::$_grammar['domain-literal'].')';
self::$_grammar['addr-spec'] = '(?:'.self::$_grammar['local-part'].'@'.
self::$_grammar['domain'].')';
}
/**
* Get the grammar defined for $name token.
*
* @param string $name exactly as written in the RFC
*
* @return string
*/
public function getDefinition($name)
{
if (array_key_exists($name, self::$_grammar)) {
return self::$_grammar[$name];
}
throw new Swift_RfcComplianceException(
"No such grammar '".$name."' defined."
);
}
/**
* Returns the tokens defined in RFC 2822 (and some related RFCs).
*
* @return array
*/
public function getGrammarDefinitions()
{
return self::$_grammar;
}
/**
* Returns the current special characters used in the syntax which need to be escaped.
*
* @return array
*/
public function getSpecials()
{
return self::$_specials;
}
/**
* Escape special characters in a string (convert to quoted-pairs).
*
* @param string $token
* @param string[] $include additional chars to escape
* @param string[] $exclude chars from escaping
*
* @return string
*/
public function escapeSpecials($token, $include = array(), $exclude = array())
{
foreach (array_merge(array('\\'), array_diff(self::$_specials, $exclude), $include) as $char) {
$token = str_replace($char, '\\'.$char, $token);
}
return $token;
}
}

View File

@@ -31,7 +31,7 @@ class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder i
range(0x61, 0x7A), range(0x41, 0x5A),
range(0x30, 0x39), array(0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F)
) as $byte) {
$this->_safeMap[$byte] = chr($byte);
$this->safeMap[$byte] = chr($byte);
}
}

View File

@@ -1,78 +0,0 @@
<?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.
*/
/**
* Creates MIME headers.
*
* @author Chris Corbyn
*/
interface Swift_Mime_HeaderFactory extends Swift_Mime_CharsetObserver
{
/**
* Create a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string $addresses
*
* @return Swift_Mime_Header
*/
public function createMailboxHeader($name, $addresses = null);
/**
* Create a new Date header using $timestamp (UNIX time).
*
* @param string $name
* @param int $timestamp
*
* @return Swift_Mime_Header
*/
public function createDateHeader($name, $timestamp = null);
/**
* 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);
/**
* Create a new ParameterizedHeader with $name, $value and $params.
*
* @param string $name
* @param string $value
* @param array $params
*
* @return Swift_Mime_ParameterizedHeader
*/
public function createParameterizedHeader($name, $value = null, $params = array());
/**
* 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);
/**
* 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);
}

View File

@@ -1,169 +0,0 @@
<?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
*/
interface Swift_Mime_HeaderSet extends Swift_Mime_CharsetObserver
{
/**
* Add a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string $addresses
*/
public function addMailboxHeader($name, $addresses = null);
/**
* Add a new Date header using $timestamp (UNIX time).
*
* @param string $name
* @param int $timestamp
*/
public function addDateHeader($name, $timestamp = null);
/**
* Add a new basic text header with $name and $value.
*
* @param string $name
* @param string $value
*/
public function addTextHeader($name, $value = null);
/**
* 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 = array());
/**
* Add a new ID header for Message-ID or Content-ID.
*
* @param string $name
* @param string|array $ids
*/
public function addIdHeader($name, $ids = null);
/**
* Add a new Path header with an address (path) in it.
*
* @param string $name
* @param string $path
*/
public function addPathHeader($name, $path = null);
/**
* 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);
/**
* 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 Swift_Mime_Header $header
* @param int $index
*/
public function set(Swift_Mime_Header $header, $index = 0);
/**
* 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
*/
public function get($name, $index = 0);
/**
* Get all headers with the given $name.
*
* @param string $name
*
* @return array
*/
public function getAll($name = null);
/**
* Return the name of all Headers.
*
* @return array
*/
public function listAll();
/**
* 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);
/**
* Remove all headers with the given $name.
*
* @param string $name
*/
public function removeAll($name);
/**
* Create a new instance of this HeaderSet.
*
* @return Swift_Mime_HeaderSet
*/
public function newInstance();
/**
* Define a list of Header names as an array in the correct order.
*
* These Headers will be output in the given order where present.
*
* @param array $sequence
*/
public function defineOrdering(array $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.
*
* @param array $names
*/
public function setAlwaysDisplayed(array $names);
/**
* Returns a string with a representation of all headers.
*
* @return string
*/
public function toString();
}

View File

@@ -11,68 +11,53 @@
/**
* An abstract base MIME Header.
*
* @author Chris Corbyn
* @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 Grammar used for this Header.
*
* @var Swift_Mime_Grammar
*/
private $_grammar;
private $name;
/**
* The Encoder used to encode this Header.
*
* @var Swift_Encoder
*/
private $_encoder;
private $encoder;
/**
* The maximum length of a line in the header.
*
* @var int
*/
private $_lineLength = 78;
private $lineLength = 78;
/**
* The language used in this Header.
*
* @var string
*/
private $_lang;
private $lang;
/**
* The character set of the text in this Header.
*
* @var string
*/
private $_charset = 'utf-8';
private $charset = 'utf-8';
/**
* The value of this Header, cached.
*
* @var string
*/
private $_cachedValue = null;
/**
* Creates a new Header.
*
* @param Swift_Mime_Grammar $grammar
*/
public function __construct(Swift_Mime_Grammar $grammar)
{
$this->setGrammar($grammar);
}
private $cachedValue = null;
/**
* Set the character set used in this Header.
@@ -81,10 +66,10 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function setCharset($charset)
{
$this->clearCachedValueIf($charset != $this->_charset);
$this->_charset = $charset;
if (isset($this->_encoder)) {
$this->_encoder->charsetChanged($charset);
$this->clearCachedValueIf($charset != $this->charset);
$this->charset = $charset;
if (isset($this->encoder)) {
$this->encoder->charsetChanged($charset);
}
}
@@ -95,7 +80,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function getCharset()
{
return $this->_charset;
return $this->charset;
}
/**
@@ -108,8 +93,8 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function setLanguage($lang)
{
$this->clearCachedValueIf($this->_lang != $lang);
$this->_lang = $lang;
$this->clearCachedValueIf($this->lang != $lang);
$this->lang = $lang;
}
/**
@@ -119,7 +104,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function getLanguage()
{
return $this->_lang;
return $this->lang;
}
/**
@@ -129,7 +114,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function setEncoder(Swift_Mime_HeaderEncoder $encoder)
{
$this->_encoder = $encoder;
$this->encoder = $encoder;
$this->setCachedValue(null);
}
@@ -140,28 +125,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function getEncoder()
{
return $this->_encoder;
}
/**
* Set the grammar used for the header.
*
* @param Swift_Mime_Grammar $grammar
*/
public function setGrammar(Swift_Mime_Grammar $grammar)
{
$this->_grammar = $grammar;
$this->setCachedValue(null);
}
/**
* Get the grammar used for this Header.
*
* @return Swift_Mime_Grammar
*/
public function getGrammar()
{
return $this->_grammar;
return $this->encoder;
}
/**
@@ -171,7 +135,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function getFieldName()
{
return $this->_name;
return $this->name;
}
/**
@@ -181,8 +145,8 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function setMaxLineLength($lineLength)
{
$this->clearCachedValueIf($this->_lineLength != $lineLength);
$this->_lineLength = $lineLength;
$this->clearCachedValueIf($this->lineLength != $lineLength);
$this->lineLength = $lineLength;
}
/**
@@ -192,19 +156,19 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
public function getMaxLineLength()
{
return $this->_lineLength;
return $this->lineLength;
}
/**
* Get this Header rendered as a RFC 2822 compliant string.
*
* @throws Swift_RfcComplianceException
*
* @return string
*
* @throws Swift_RfcComplianceException
*/
public function toString()
{
return $this->_tokensToString($this->toTokens());
return $this->tokensToString($this->toTokens());
}
/**
@@ -219,8 +183,6 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
return $this->toString();
}
// -- Points of extension
/**
* Set the name of this Header field.
*
@@ -228,7 +190,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
protected function setFieldName($name)
{
$this->_name = $name;
$this->name = $name;
}
/**
@@ -247,13 +209,12 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
// Treat token as exactly what was given
$phraseStr = $string;
// If it's not valid
if (!preg_match('/^'.$this->getGrammar()->getDefinition('phrase').'$/D', $phraseStr)) {
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('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $phraseStr)) {
$phraseStr = $this->getGrammar()->escapeSpecials(
$phraseStr, array('"'), $this->getGrammar()->getSpecials()
);
if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) {
$phraseStr = $this->escapeSpecials($phraseStr, array('"'));
$phraseStr = '"'.$phraseStr.'"';
} else {
// ... otherwise it needs encoding
@@ -270,6 +231,23 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
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 = array())
{
foreach (array_merge(array('\\'), $include) as $char) {
$token = str_replace($char, '\\'.$char, $token);
}
return $token;
}
/**
* Encode needed word tokens within a string of input.
*
@@ -365,12 +343,12 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
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;
$charsetDecl = $this->charset;
if (isset($this->lang)) {
$charsetDecl .= '*'.$this->lang;
}
$encodingWrapperLength = strlen(
'=?'.$charsetDecl.'?'.$this->_encoder->getName().'??='
'=?'.$charsetDecl.'?'.$this->encoder->getName().'??='
);
if ($firstLineOffset >= 75) {
@@ -379,16 +357,16 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
}
$encodedTextLines = explode("\r\n",
$this->_encoder->encodeString(
$token, $firstLineOffset, 75 - $encodingWrapperLength, $this->_charset
$this->encoder->encodeString(
$token, $firstLineOffset, 75 - $encodingWrapperLength, $this->charset
)
);
if (strtolower($this->_charset) !== 'iso-2022-jp') {
if (strtolower($this->charset) !== 'iso-2022-jp') {
// special encoding for iso-2022-jp using mb_encode_mimeheader
foreach ($encodedTextLines as $lineNum => $line) {
$encodedTextLines[$lineNum] = '=?'.$charsetDecl.
'?'.$this->_encoder->getName().
'?'.$this->encoder->getName().
'?'.$line.'?=';
}
}
@@ -415,7 +393,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
protected function setCachedValue($value)
{
$this->_cachedValue = $value;
$this->cachedValue = $value;
}
/**
@@ -425,7 +403,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
protected function getCachedValue()
{
return $this->_cachedValue;
return $this->cachedValue;
}
/**
@@ -449,7 +427,7 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*/
protected function toTokens($string = null)
{
if (is_null($string)) {
if (null === $string) {
$string = $this->getFieldBody();
}
@@ -474,18 +452,18 @@ abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
*
* @return string
*/
private function _tokensToString(array $tokens)
private function tokensToString(array $tokens)
{
$lineCount = 0;
$headerLines = array();
$headerLines[] = $this->_name.': ';
$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)
($i > 0 && strlen($currentLine.$token) > $this->lineLength)
&& 0 < strlen($currentLine)) {
$headerLines[] = '';
$currentLine = &$headerLines[$lineCount++];

View File

@@ -16,29 +16,20 @@
class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The UNIX timestamp value of this Header.
* Date-time value of this Header.
*
* @var int
* @var DateTimeImmutable
*/
private $_timestamp;
private $dateTime;
/**
* Creates a new DateHeader with $name and $timestamp.
* Creates a new DateHeader with $name.
*
* Example:
* <code>
* <?php
* $header = new Swift_Mime_Headers_DateHeader('Date', time());
* ?>
* </code>
*
* @param string $name of Header
* @param Swift_Mime_Grammar $grammar
* @param string $name of Header
*/
public function __construct($name, Swift_Mime_Grammar $grammar)
public function __construct($name)
{
$this->setFieldName($name);
parent::__construct($grammar);
}
/**
@@ -57,49 +48,48 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader
/**
* Set the model for the field body.
*
* This method takes a UNIX timestamp.
*
* @param int $model
* @param DateTimeInterface $model
*/
public function setFieldBodyModel($model)
{
$this->setTimestamp($model);
$this->setDateTime($model);
}
/**
* Get the model for the field body.
*
* This method returns a UNIX timestamp.
*
* @return mixed
* @return DateTimeImmutable
*/
public function getFieldBodyModel()
{
return $this->getTimestamp();
return $this->getDateTime();
}
/**
* Get the UNIX timestamp of the Date in this Header.
* Get the date-time representing the Date in this Header.
*
* @return int
* @return DateTimeImmutable
*/
public function getTimestamp()
public function getDateTime()
{
return $this->_timestamp;
return $this->dateTime;
}
/**
* Set the UNIX timestamp of the Date in this Header.
* Set the date-time of the Date in this Header.
*
* @param int $timestamp
* If a DateTime instance is provided, it is converted to DateTimeImmutable.
*
* @param DateTimeInterface $dateTime
*/
public function setTimestamp($timestamp)
public function setDateTime(DateTimeInterface $dateTime)
{
if (!is_null($timestamp)) {
$timestamp = (int) $timestamp;
$this->clearCachedValueIf($this->getCachedValue() != $dateTime->format(DateTime::RFC2822));
if ($dateTime instanceof DateTime) {
$immutable = new DateTimeImmutable('@'.$dateTime->getTimestamp());
$dateTime = $immutable->setTimezone($dateTime->getTimezone());
}
$this->clearCachedValueIf($this->_timestamp != $timestamp);
$this->_timestamp = $timestamp;
$this->dateTime = $dateTime;
}
/**
@@ -115,8 +105,8 @@ class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader
public function getFieldBody()
{
if (!$this->getCachedValue()) {
if (isset($this->_timestamp)) {
$this->setCachedValue(date('r', $this->_timestamp));
if (isset($this->dateTime)) {
$this->setCachedValue($this->dateTime->format(DateTime::RFC2822));
}
}

View File

@@ -8,6 +8,9 @@
* file that was distributed with this source code.
*/
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
/**
* An ID MIME Header for something like Message-ID or Content-ID.
*
@@ -22,18 +25,25 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*
* @var string[]
*/
private $_ids = array();
private $ids = array();
/**
* The strict EmailValidator.
*
* @var EmailValidator
*/
private $emailValidator;
/**
* Creates a new IdentificationHeader with the given $name and $id.
*
* @param string $name
* @param Swift_Mime_Grammar $grammar
* @param string $name
* @param EmailValidator $emailValidator
*/
public function __construct($name, Swift_Mime_Grammar $grammar)
public function __construct($name, EmailValidator $emailValidator)
{
$this->setFieldName($name);
parent::__construct($grammar);
$this->emailValidator = $emailValidator;
}
/**
@@ -96,8 +106,8 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*/
public function getId()
{
if (count($this->_ids) > 0) {
return $this->_ids[0];
if (count($this->ids) > 0) {
return $this->ids[0];
}
}
@@ -113,12 +123,12 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
$actualIds = array();
foreach ($ids as $id) {
$this->_assertValidId($id);
$this->assertValidId($id);
$actualIds[] = $id;
}
$this->clearCachedValueIf($this->_ids != $actualIds);
$this->_ids = $actualIds;
$this->clearCachedValueIf($this->ids != $actualIds);
$this->ids = $actualIds;
}
/**
@@ -128,7 +138,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*/
public function getIds()
{
return $this->_ids;
return $this->ids;
}
/**
@@ -148,7 +158,7 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
if (!$this->getCachedValue()) {
$angleAddrs = array();
foreach ($this->_ids as $id) {
foreach ($this->ids as $id) {
$angleAddrs[] = '<'.$id.'>';
}
@@ -165,16 +175,10 @@ class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_Abstrac
*
* @throws Swift_RfcComplianceException
*/
private function _assertValidId($id)
private function assertValidId($id)
{
if (!preg_match(
'/^'.$this->getGrammar()->getDefinition('id-left').'@'.
$this->getGrammar()->getDefinition('id-right').'$/D',
$id
)) {
throw new Swift_RfcComplianceException(
'Invalid ID given <'.$id.'>'
);
if (!$this->emailValidator->isValid($id, new RFCValidation())) {
throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>');
}
}
}

View File

@@ -8,6 +8,9 @@
* 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.
*
@@ -20,20 +23,27 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*
* @var string[]
*/
private $_mailboxes = array();
private $mailboxes = array();
/**
* The strict EmailValidator.
*
* @var EmailValidator
*/
private $emailValidator;
/**
* Creates a new MailboxHeader with $name.
*
* @param string $name of Header
* @param string $name of Header
* @param Swift_Mime_HeaderEncoder $encoder
* @param Swift_Mime_Grammar $grammar
* @param EmailValidator $emailValidator
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Mime_Grammar $grammar)
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, EmailValidator $emailValidator)
{
$this->setFieldName($name);
$this->setEncoder($encoder);
parent::__construct($grammar);
$this->emailValidator = $emailValidator;
}
/**
@@ -103,7 +113,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/
public function setNameAddresses($mailboxes)
{
$this->_mailboxes = $this->normalizeMailboxes((array) $mailboxes);
$this->mailboxes = $this->normalizeMailboxes((array) $mailboxes);
$this->setCachedValue(null); //Clear any cached value
}
@@ -134,7 +144,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/
public function getNameAddressStrings()
{
return $this->_createNameAddressStrings($this->getNameAddresses());
return $this->createNameAddressStrings($this->getNameAddresses());
}
/**
@@ -163,7 +173,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/
public function getNameAddresses()
{
return $this->_mailboxes;
return $this->mailboxes;
}
/**
@@ -200,7 +210,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/
public function getAddresses()
{
return array_keys($this->_mailboxes);
return array_keys($this->mailboxes);
}
/**
@@ -212,7 +222,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
{
$this->setCachedValue(null);
foreach ((array) $addresses as $address) {
unset($this->_mailboxes[$address]);
unset($this->mailboxes[$address]);
}
}
@@ -231,15 +241,13 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
public function getFieldBody()
{
// Compute the string value of the header only if needed
if (is_null($this->getCachedValue())) {
$this->setCachedValue($this->createMailboxListString($this->_mailboxes));
if (null === $this->getCachedValue()) {
$this->setCachedValue($this->createMailboxListString($this->mailboxes));
}
return $this->getCachedValue();
}
// -- Points of extension
/**
* Normalizes a user-input list of mailboxes into consistent key=>value pairs.
*
@@ -260,7 +268,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
$address = $value;
$name = null;
}
$this->_assertValidAddress($address);
$this->assertValidAddress($address);
$actualMailboxes[$address] = $name;
}
@@ -277,9 +285,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/
protected function createDisplayNameString($displayName, $shorten = false)
{
return $this->createPhrase($this, $displayName,
$this->getCharset(), $this->getEncoder(), $shorten
);
return $this->createPhrase($this, $displayName, $this->getCharset(), $this->getEncoder(), $shorten);
}
/**
@@ -293,14 +299,15 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/
protected function createMailboxListString(array $mailboxes)
{
return implode(', ', $this->_createNameAddressStrings($mailboxes));
return implode(', ', $this->createNameAddressStrings($mailboxes));
}
/**
* Redefine the encoding requirements for mailboxes.
*
* Commas and semicolons are used to separate
* multiple addresses, and should therefore be encoded
* All "specials" must be encoded as the full header value will not be quoted
*
* @see RFC 2822 3.2.1
*
* @param string $token
*
@@ -308,7 +315,7 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*/
protected function tokenNeedsEncoding($token)
{
return preg_match('/[,;]/', $token) || parent::tokenNeedsEncoding($token);
return preg_match('/[()<>\[\]:;@\,."]/', $token) || parent::tokenNeedsEncoding($token);
}
/**
@@ -318,13 +325,13 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*
* @return string[]
*/
private function _createNameAddressStrings(array $mailboxes)
private function createNameAddressStrings(array $mailboxes)
{
$strings = array();
foreach ($mailboxes as $email => $name) {
$mailboxStr = $email;
if (!is_null($name)) {
if (null !== $name) {
$nameStr = $this->createDisplayNameString($name, empty($strings));
$mailboxStr = $nameStr.' <'.$mailboxStr.'>';
}
@@ -341,14 +348,12 @@ class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
*
* @throws Swift_RfcComplianceException If invalid.
*/
private function _assertValidAddress($address)
private function assertValidAddress($address)
{
if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D',
$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.'
);
'Address in mailbox given ['.$address.'] does not comply with RFC 2822, 3.6.2.'
);
}
}
}

View File

@@ -20,25 +20,21 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
*
* @var string
*/
private $_value;
private $value;
/**
* The name of this Header.
*
* @var string
*/
private $_fieldName;
private $fieldName;
/**
* Creates a new SimpleHeader with $name.
*
* @param string $name
* @param Swift_Mime_HeaderEncoder $encoder
* @param Swift_Mime_Grammar $grammar
* @param string $name
*/
public function __construct($name)
{
$this->_fieldName = $name;
$this->fieldName = $name;
}
/**
@@ -85,7 +81,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
*/
public function getValue()
{
return $this->_value;
return $this->value;
}
/**
@@ -95,7 +91,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
*/
public function setValue($value)
{
$this->_value = $value;
$this->value = $value;
}
/**
@@ -105,7 +101,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
*/
public function getFieldBody()
{
return $this->_value;
return $this->value;
}
/**
@@ -115,7 +111,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
*/
public function toString()
{
return $this->_fieldName.': '.$this->_value;
return $this->fieldName.': '.$this->value;
}
/**
@@ -125,7 +121,7 @@ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header
*/
public function getFieldName()
{
return $this->_fieldName;
return $this->fieldName;
}
/**

View File

@@ -13,7 +13,7 @@
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_UnstructuredHeader implements Swift_Mime_ParameterizedHeader
class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_UnstructuredHeader
{
/**
* RFC 2231's definition of a token.
@@ -27,14 +27,14 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
*
* @var Swift_Encoder
*/
private $_paramEncoder;
private $paramEncoder;
/**
* The parameters as an associative array.
*
* @var string[]
*/
private $_params = array();
private $params = array();
/**
* Creates a new ParameterizedHeader with $name.
@@ -42,12 +42,11 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
* @param string $name
* @param Swift_Mime_HeaderEncoder $encoder
* @param Swift_Encoder $paramEncoder, optional
* @param Swift_Mime_Grammar $grammar
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null, Swift_Mime_Grammar $grammar)
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder = null)
{
parent::__construct($name, $encoder, $grammar);
$this->_paramEncoder = $paramEncoder;
parent::__construct($name, $encoder);
$this->paramEncoder = $paramEncoder;
}
/**
@@ -71,8 +70,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
public function setCharset($charset)
{
parent::setCharset($charset);
if (isset($this->_paramEncoder)) {
$this->_paramEncoder->charsetChanged($charset);
if (isset($this->paramEncoder)) {
$this->paramEncoder->charsetChanged($charset);
}
}
@@ -98,7 +97,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
{
$params = $this->getParameters();
return array_key_exists($parameter, $params) ? $params[$parameter] : null;
return $params[$parameter] ?? null;
}
/**
@@ -108,8 +107,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
*/
public function setParameters(array $parameters)
{
$this->clearCachedValueIf($this->_params != $parameters);
$this->_params = $parameters;
$this->clearCachedValueIf($this->params != $parameters);
$this->params = $parameters;
}
/**
@@ -119,7 +118,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
*/
public function getParameters()
{
return $this->_params;
return $this->params;
}
/**
@@ -130,10 +129,10 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
public function getFieldBody() //TODO: Check caching here
{
$body = parent::getFieldBody();
foreach ($this->_params as $name => $value) {
if (!is_null($value)) {
foreach ($this->params as $name => $value) {
if (null !== $value) {
// Add the parameter
$body .= '; '.$this->_createParameter($name, $value);
$body .= '; '.$this->createParameter($name, $value);
}
}
@@ -155,12 +154,12 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
$tokens = parent::toTokens(parent::getFieldBody());
// Try creating any parameters
foreach ($this->_params as $name => $value) {
if (!is_null($value)) {
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)
' '.$this->createParameter($name, $value)
));
}
}
@@ -176,7 +175,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
*
* @return string
*/
private function _createParameter($name, $value)
private function createParameter($name, $value)
{
$origValue = $value;
@@ -189,7 +188,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) {
// TODO: text, or something else??
// ... and it's not ascii
if (!preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $value)) {
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;
@@ -201,8 +200,8 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
// Encode if we need to
if ($encoded || strlen($value) > $maxValueLength) {
if (isset($this->_paramEncoder)) {
$value = $this->_paramEncoder->encodeString(
if (isset($this->paramEncoder)) {
$value = $this->paramEncoder->encodeString(
$origValue, $firstLineOffset, $maxValueLength, $this->getCharset()
);
} else {
@@ -212,19 +211,19 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
}
}
$valueLines = isset($this->_paramEncoder) ? explode("\r\n", $value) : array($value);
$valueLines = isset($this->paramEncoder) ? explode("\r\n", $value) : array($value);
// Need to add indices
if (count($valueLines) > 1) {
$paramLines = array();
foreach ($valueLines as $i => $line) {
$paramLines[] = $name.'*'.$i.
$this->_getEndOfParameterValue($line, true, $i == 0);
$this->getEndOfParameterValue($line, true, $i == 0);
}
return implode(";\r\n ", $paramLines);
} else {
return $name.$this->_getEndOfParameterValue(
return $name.$this->getEndOfParameterValue(
$valueLines[0], $encoded, true
);
}
@@ -239,7 +238,7 @@ class Swift_Mime_Headers_ParameterizedHeader extends Swift_Mime_Headers_Unstruct
*
* @return string
*/
private function _getEndOfParameterValue($value, $encoded = false, $firstLine = false)
private function getEndOfParameterValue($value, $encoded = false, $firstLine = false)
{
if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) {
$value = '"'.$value.'"';

View File

@@ -8,6 +8,9 @@
* 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.
*
@@ -20,18 +23,25 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
*
* @var string
*/
private $_address;
private $address;
/**
* The strict EmailValidator.
*
* @var EmailValidator
*/
private $emailValidator;
/**
* Creates a new PathHeader with the given $name.
*
* @param string $name
* @param Swift_Mime_Grammar $grammar
* @param string $name
* @param EmailValidator $emailValidator
*/
public function __construct($name, Swift_Mime_Grammar $grammar)
public function __construct($name, EmailValidator $emailValidator)
{
$this->setFieldName($name);
parent::__construct($grammar);
$this->emailValidator = $emailValidator;
}
/**
@@ -80,13 +90,13 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
*/
public function setAddress($address)
{
if (is_null($address)) {
$this->_address = null;
if (null === $address) {
$this->address = null;
} elseif ('' == $address) {
$this->_address = '';
$this->address = '';
} else {
$this->_assertValidAddress($address);
$this->_address = $address;
$this->assertValidAddress($address);
$this->address = $address;
}
$this->setCachedValue(null);
}
@@ -100,7 +110,7 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
*/
public function getAddress()
{
return $this->_address;
return $this->address;
}
/**
@@ -116,8 +126,8 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
public function getFieldBody()
{
if (!$this->getCachedValue()) {
if (isset($this->_address)) {
$this->setCachedValue('<'.$this->_address.'>');
if (isset($this->address)) {
$this->setCachedValue('<'.$this->address.'>');
}
}
@@ -131,13 +141,12 @@ class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
*
* @throws Swift_RfcComplianceException If address is invalid
*/
private function _assertValidAddress($address)
private function assertValidAddress($address)
{
if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D',
$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

@@ -20,20 +20,18 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH
*
* @var string
*/
private $_value;
private $value;
/**
* Creates a new SimpleHeader with $name.
*
* @param string $name
* @param Swift_Mime_HeaderEncoder $encoder
* @param Swift_Mime_Grammar $grammar
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder, Swift_Mime_Grammar $grammar)
public function __construct($name, Swift_Mime_HeaderEncoder $encoder)
{
$this->setFieldName($name);
$this->setEncoder($encoder);
parent::__construct($grammar);
}
/**
@@ -80,7 +78,7 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH
*/
public function getValue()
{
return $this->_value;
return $this->value;
}
/**
@@ -90,8 +88,8 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH
*/
public function setValue($value)
{
$this->clearCachedValueIf($this->_value != $value);
$this->_value = $value;
$this->clearCachedValueIf($this->value != $value);
$this->value = $value;
}
/**
@@ -103,7 +101,7 @@ class Swift_Mime_Headers_UnstructuredHeader extends Swift_Mime_Headers_AbstractH
{
if (!$this->getCachedValue()) {
$this->setCachedValue(
$this->encodeWords($this, $this->_value)
$this->encodeWords($this, $this->value)
);
}

View File

@@ -0,0 +1,53 @@
<?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
{
/**
* @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()
{
$idLeft = bin2hex(random_bytes(16)); // set 32 hex values
return $idLeft.'@'.$this->idRight;
}
}

View File

@@ -1,223 +0,0 @@
<?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 Message (RFC 2822) object.
*
* @author Chris Corbyn
*/
interface Swift_Mime_Message extends Swift_Mime_MimeEntity
{
/**
* Generates a valid Message-ID and switches to it.
*
* @return string
*/
public function generateId();
/**
* Set the subject of the message.
*
* @param string $subject
*/
public function setSubject($subject);
/**
* Get the subject of the message.
*
* @return string
*/
public function getSubject();
/**
* Set the origination date of the message as a UNIX timestamp.
*
* @param int $date
*/
public function setDate($date);
/**
* Get the origination date of the message as a UNIX timestamp.
*
* @return int
*/
public function getDate();
/**
* Set the return-path (bounce-detect) address.
*
* @param string $address
*/
public function setReturnPath($address);
/**
* Get the return-path (bounce-detect) address.
*
* @return string
*/
public function getReturnPath();
/**
* Set the sender of this message.
*
* If multiple addresses are present in the From field, this SHOULD be set.
*
* According to RFC 2822 it is a requirement when there are multiple From
* addresses, but Swift itself does not require it directly.
*
* An associative array (with one element!) can be used to provide a display-
* name: i.e. array('email@address' => 'Real Name').
*
* If the second parameter is provided and the first is a string, then $name
* is associated with the address.
*
* @param mixed $address
* @param string $name optional
*/
public function setSender($address, $name = null);
/**
* Get the sender address for this message.
*
* This has a higher significance than the From address.
*
* @return string
*/
public function getSender();
/**
* Set the From address of this message.
*
* It is permissible for multiple From addresses to be set using an array.
*
* If multiple From addresses are used, you SHOULD set the Sender address and
* according to RFC 2822, MUST set the sender address.
*
* An array can be used if display names are to be provided: i.e.
* array('email@address.com' => 'Real Name').
*
* If the second parameter is provided and the first is a string, then $name
* is associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setFrom($addresses, $name = null);
/**
* Get the From address(es) of this message.
*
* This method always returns an associative array where the keys are the
* addresses.
*
* @return string[]
*/
public function getFrom();
/**
* Set the Reply-To address(es).
*
* Any replies from the receiver will be sent to this address.
*
* It is permissible for multiple reply-to addresses to be set using an array.
*
* This method has the same synopsis as {@link setFrom()} and {@link setTo()}.
*
* If the second parameter is provided and the first is a string, then $name
* is associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setReplyTo($addresses, $name = null);
/**
* Get the Reply-To addresses for this message.
*
* This method always returns an associative array where the keys provide the
* email addresses.
*
* @return string[]
*/
public function getReplyTo();
/**
* Set the To address(es).
*
* Recipients set in this field will receive a copy of this message.
*
* This method has the same synopsis as {@link setFrom()} and {@link setCc()}.
*
* If the second parameter is provided and the first is a string, then $name
* is associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setTo($addresses, $name = null);
/**
* Get the To addresses for this message.
*
* This method always returns an associative array, whereby the keys provide
* the actual email addresses.
*
* @return string[]
*/
public function getTo();
/**
* Set the Cc address(es).
*
* Recipients set in this field will receive a 'carbon-copy' of this message.
*
* This method has the same synopsis as {@link setFrom()} and {@link setTo()}.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setCc($addresses, $name = null);
/**
* Get the Cc addresses for this message.
*
* This method always returns an associative array, whereby the keys provide
* the actual email addresses.
*
* @return string[]
*/
public function getCc();
/**
* Set the Bcc address(es).
*
* Recipients set in this field will receive a 'blind-carbon-copy' of this
* message.
*
* In other words, they will get the message, but any other recipients of the
* message will have no such knowledge of their receipt of it.
*
* This method has the same synopsis as {@link setFrom()} and {@link setTo()}.
*
* @param mixed $addresses
* @param string $name optional
*/
public function setBcc($addresses, $name = null);
/**
* Get the Bcc addresses for this message.
*
* This method always returns an associative array, whereby the keys provide
* the actual email addresses.
*
* @return string[]
*/
public function getBcc();
}

View File

@@ -1,117 +0,0 @@
<?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, such as an attachment.
*
* @author Chris Corbyn
*/
interface Swift_Mime_MimeEntity extends 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;
/**
* Get the level at which this entity shall be nested in final document.
*
* The lower the value, the more outermost the entity will be nested.
*
* @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE
*
* @return int
*/
public function getNestingLevel();
/**
* Get the qualified content-type of this mime entity.
*
* @return string
*/
public function getContentType();
/**
* Returns a unique ID for this entity.
*
* For most entities this will likely be the Content-ID, though it has
* no explicit semantic meaning and can be considered an identifier for
* programming logic purposes.
*
* If a Content-ID header is present, this value SHOULD match the value of
* the header.
*
* @return string
*/
public function getId();
/**
* Get all children nested inside this entity.
*
* These are not just the immediate children, but all children.
*
* @return Swift_Mime_MimeEntity[]
*/
public function getChildren();
/**
* Set all children nested inside this entity.
*
* This includes grandchildren.
*
* @param Swift_Mime_MimeEntity[] $children
*/
public function setChildren(array $children);
/**
* Get the collection of Headers in this Mime entity.
*
* @return Swift_Mime_HeaderSet
*/
public function getHeaders();
/**
* Get the body content of this entity as a string.
*
* Returns NULL if no body has been set.
*
* @return string|null
*/
public function getBody();
/**
* Set the body content of this entity as a string.
*
* @param string $body
* @param string $contentType optional
*/
public function setBody($body, $contentType = null);
/**
* Get this entire entity in its string form.
*
* @return string
*/
public function toString();
/**
* Get this entire entity as a ByteStream.
*
* @param Swift_InputByteStream $is to write to
*/
public function toByteStream(Swift_InputByteStream $is);
}

View File

@@ -16,31 +16,31 @@
class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
{
/** The format parameter last specified by the user */
protected $_userFormat;
protected $userFormat;
/** The charset last specified by the user */
protected $_userCharset;
protected $userCharset;
/** The delsp parameter last specified by the user */
protected $_userDelSp;
protected $userDelSp;
/** The nesting level of this MimePart */
private $_nestingLevel = self::LEVEL_ALTERNATIVE;
private $nestingLevel = self::LEVEL_ALTERNATIVE;
/**
* Create a new MimePart with $headers, $encoder and $cache.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_Mime_Grammar $grammar
* @param string $charset
* @param Swift_Mime_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $charset = null)
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null)
{
parent::__construct($headers, $encoder, $cache, $grammar);
parent::__construct($headers, $encoder, $cache, $idGenerator);
$this->setContentType('text/plain');
if (!is_null($charset)) {
if (null !== $charset) {
$this->setCharset($charset);
}
}
@@ -53,14 +53,14 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
* @param string $contentType optional
* @param string $charset optional
*
* @return Swift_Mime_MimePart
* @return $this
*/
public function setBody($body, $contentType = null, $charset = null)
{
if (isset($charset)) {
$this->setCharset($charset);
}
$body = $this->_convertString($body);
$body = $this->convertString($body);
parent::setBody($body, $contentType);
@@ -74,7 +74,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
*/
public function getCharset()
{
return $this->_getHeaderParameter('Content-Type', 'charset');
return $this->getHeaderParameter('Content-Type', 'charset');
}
/**
@@ -82,15 +82,15 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
*
* @param string $charset
*
* @return Swift_Mime_MimePart
* @return $this
*/
public function setCharset($charset)
{
$this->_setHeaderParameter('Content-Type', 'charset', $charset);
if ($charset !== $this->_userCharset) {
$this->_clearCache();
$this->setHeaderParameter('Content-Type', 'charset', $charset);
if ($charset !== $this->userCharset) {
$this->clearCache();
}
$this->_userCharset = $charset;
$this->userCharset = $charset;
parent::charsetChanged($charset);
return $this;
@@ -103,7 +103,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
*/
public function getFormat()
{
return $this->_getHeaderParameter('Content-Type', 'format');
return $this->getHeaderParameter('Content-Type', 'format');
}
/**
@@ -111,12 +111,12 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
*
* @param string $format
*
* @return Swift_Mime_MimePart
* @return $this
*/
public function setFormat($format)
{
$this->_setHeaderParameter('Content-Type', 'format', $format);
$this->_userFormat = $format;
$this->setHeaderParameter('Content-Type', 'format', $format);
$this->userFormat = $format;
return $this;
}
@@ -128,7 +128,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
*/
public function getDelSp()
{
return 'yes' == $this->_getHeaderParameter('Content-Type', 'delsp') ? true : false;
return 'yes' === $this->getHeaderParameter('Content-Type', 'delsp');
}
/**
@@ -136,12 +136,12 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
*
* @param bool $delsp
*
* @return Swift_Mime_MimePart
* @return $this
*/
public function setDelSp($delsp = true)
{
$this->_setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null);
$this->_userDelSp = $delsp;
$this->setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null);
$this->userDelSp = $delsp;
return $this;
}
@@ -155,7 +155,7 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
*/
public function getNestingLevel()
{
return $this->_nestingLevel;
return $this->nestingLevel;
}
/**
@@ -170,31 +170,31 @@ class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
}
/** Fix the content-type and encoding of this entity */
protected function _fixHeaders()
protected function fixHeaders()
{
parent::_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);
$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);
$this->setCharset($this->userCharset);
$this->setFormat($this->userFormat);
$this->setDelSp($this->userDelSp);
}
}
/** Set the nesting level of this entity */
protected function _setNestingLevel($level)
protected function setNestingLevel($level)
{
$this->_nestingLevel = $level;
$this->nestingLevel = $level;
}
/** Encode charset when charset is not utf-8 */
protected function _convertString($string)
protected function convertString($string)
{
$charset = strtolower($this->getCharset());
if (!in_array($charset, array('utf-8', 'iso-8859-1', ''))) {
if (!in_array($charset, array('utf-8', 'iso-8859-1', 'iso-8859-15', ''))) {
// mb_convert_encoding must be the first one to check, since iconv cannot convert some words.
if (function_exists('mb_convert_encoding')) {
$string = mb_convert_encoding($string, $charset, 'utf-8');

View File

@@ -1,34 +0,0 @@
<?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 with parameters.
*
* @author Chris Corbyn
*/
interface Swift_Mime_ParameterizedHeader extends Swift_Mime_Header
{
/**
* Set the value of $parameter.
*
* @param string $parameter
* @param string $value
*/
public function setParameter($parameter, $value);
/**
* Get the value of $parameter.
*
* @param string $parameter
*
* @return string
*/
public function getParameter($parameter);
}

View File

@@ -8,39 +8,44 @@
* 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_HeaderFactory
class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_CharsetObserver
{
/** The HeaderEncoder used by these headers */
private $_encoder;
private $encoder;
/** The Encoder used by parameters */
private $_paramEncoder;
private $paramEncoder;
/** The Grammar */
private $_grammar;
private $grammar;
/** Strict EmailValidator */
private $emailValidator;
/** The charset of created Headers */
private $_charset;
private $charset;
/**
* Creates a new SimpleHeaderFactory using $encoder and $paramEncoder.
*
* @param Swift_Mime_HeaderEncoder $encoder
* @param Swift_Encoder $paramEncoder
* @param Swift_Mime_Grammar $grammar
* @param EmailValidator $emailValidator
* @param string|null $charset
*/
public function __construct(Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder, Swift_Mime_Grammar $grammar, $charset = null)
public function __construct(Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder, EmailValidator $emailValidator, $charset = null)
{
$this->_encoder = $encoder;
$this->_paramEncoder = $paramEncoder;
$this->_grammar = $grammar;
$this->_charset = $charset;
$this->encoder = $encoder;
$this->paramEncoder = $paramEncoder;
$this->emailValidator = $emailValidator;
$this->charset = $charset;
}
/**
@@ -53,30 +58,30 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
*/
public function createMailboxHeader($name, $addresses = null)
{
$header = new Swift_Mime_Headers_MailboxHeader($name, $this->_encoder, $this->_grammar);
$header = new Swift_Mime_Headers_MailboxHeader($name, $this->encoder, $this->emailValidator);
if (isset($addresses)) {
$header->setFieldBodyModel($addresses);
}
$this->_setHeaderCharset($header);
$this->setHeaderCharset($header);
return $header;
}
/**
* Create a new Date header using $timestamp (UNIX time).
* Create a new Date header using $dateTime.
*
* @param string $name
* @param int|null $timestamp
* @param string $name
* @param DateTimeInterface|null $dateTime
*
* @return Swift_Mime_Header
*/
public function createDateHeader($name, $timestamp = null)
public function createDateHeader($name, DateTimeInterface $dateTime = null)
{
$header = new Swift_Mime_Headers_DateHeader($name, $this->_grammar);
if (isset($timestamp)) {
$header->setFieldBodyModel($timestamp);
$header = new Swift_Mime_Headers_DateHeader($name);
if (isset($dateTime)) {
$header->setFieldBodyModel($dateTime);
}
$this->_setHeaderCharset($header);
$this->setHeaderCharset($header);
return $header;
}
@@ -91,11 +96,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
*/
public function createTextHeader($name, $value = null)
{
$header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->_encoder, $this->_grammar);
$header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->encoder);
if (isset($value)) {
$header->setFieldBodyModel($value);
}
$this->_setHeaderCharset($header);
$this->setHeaderCharset($header);
return $header;
}
@@ -107,19 +112,18 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
* @param string $value
* @param array $params
*
* @return Swift_Mime_ParameterizedHeader
* @return Swift_Mime_Headers_ParameterizedHeader
*/
public function createParameterizedHeader($name, $value = null,
$params = array())
public function createParameterizedHeader($name, $value = null, $params = array())
{
$header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->_encoder, strtolower($name) == 'content-disposition' ? $this->_paramEncoder : null, $this->_grammar);
$header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->encoder, (strtolower($name) == 'content-disposition') ? $this->paramEncoder : null);
if (isset($value)) {
$header->setFieldBodyModel($value);
}
foreach ($params as $k => $v) {
$header->setParameter($k, $v);
}
$this->_setHeaderCharset($header);
$this->setHeaderCharset($header);
return $header;
}
@@ -134,11 +138,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
*/
public function createIdHeader($name, $ids = null)
{
$header = new Swift_Mime_Headers_IdentificationHeader($name, $this->_grammar);
$header = new Swift_Mime_Headers_IdentificationHeader($name, $this->emailValidator);
if (isset($ids)) {
$header->setFieldBodyModel($ids);
}
$this->_setHeaderCharset($header);
$this->setHeaderCharset($header);
return $header;
}
@@ -153,11 +157,11 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
*/
public function createPathHeader($name, $path = null)
{
$header = new Swift_Mime_Headers_PathHeader($name, $this->_grammar);
$header = new Swift_Mime_Headers_PathHeader($name, $this->emailValidator);
if (isset($path)) {
$header->setFieldBodyModel($path);
}
$this->_setHeaderCharset($header);
$this->setHeaderCharset($header);
return $header;
}
@@ -169,9 +173,9 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
*/
public function charsetChanged($charset)
{
$this->_charset = $charset;
$this->_encoder->charsetChanged($charset);
$this->_paramEncoder->charsetChanged($charset);
$this->charset = $charset;
$this->encoder->charsetChanged($charset);
$this->paramEncoder->charsetChanged($charset);
}
/**
@@ -179,15 +183,15 @@ class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
*/
public function __clone()
{
$this->_encoder = clone $this->_encoder;
$this->_paramEncoder = clone $this->_paramEncoder;
$this->encoder = clone $this->encoder;
$this->paramEncoder = clone $this->paramEncoder;
}
/** Apply the charset to the Header */
private function _setHeaderCharset(Swift_Mime_Header $header)
private function setHeaderCharset(Swift_Mime_Header $header)
{
if (isset($this->_charset)) {
$header->setCharset($this->_charset);
if (isset($this->charset)) {
$header->setCharset($this->charset);
}
}
}

View File

@@ -13,37 +13,42 @@
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
{
/** HeaderFactory */
private $_factory;
private $factory;
/** Collection of set Headers */
private $_headers = array();
private $headers = array();
/** Field ordering details */
private $_order = array();
private $order = array();
/** List of fields which are required to be displayed */
private $_required = array();
private $required = array();
/** The charset used by Headers */
private $_charset;
private $charset;
/**
* Create a new SimpleHeaderSet with the given $factory.
*
* @param Swift_Mime_HeaderFactory $factory
* @param string $charset
* @param Swift_Mime_SimpleHeaderFactory $factory
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderFactory $factory, $charset = null)
public function __construct(Swift_Mime_SimpleHeaderFactory $factory, $charset = null)
{
$this->_factory = $factory;
$this->factory = $factory;
if (isset($charset)) {
$this->setCharset($charset);
}
}
public function newInstance()
{
return new self($this->factory);
}
/**
* Set the charset used by these headers.
*
@@ -51,9 +56,9 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function setCharset($charset)
{
$this->_charset = $charset;
$this->_factory->charsetChanged($charset);
$this->_notifyHeadersOfCharset($charset);
$this->charset = $charset;
$this->factory->charsetChanged($charset);
$this->notifyHeadersOfCharset($charset);
}
/**
@@ -64,20 +69,20 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function addMailboxHeader($name, $addresses = null)
{
$this->_storeHeader($name,
$this->_factory->createMailboxHeader($name, $addresses));
$this->storeHeader($name,
$this->factory->createMailboxHeader($name, $addresses));
}
/**
* Add a new Date header using $timestamp (UNIX time).
* Add a new Date header using $dateTime.
*
* @param string $name
* @param int $timestamp
* @param string $name
* @param DateTimeInterface $dateTime
*/
public function addDateHeader($name, $timestamp = null)
public function addDateHeader($name, DateTimeInterface $dateTime = null)
{
$this->_storeHeader($name,
$this->_factory->createDateHeader($name, $timestamp));
$this->storeHeader($name,
$this->factory->createDateHeader($name, $dateTime));
}
/**
@@ -88,8 +93,8 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function addTextHeader($name, $value = null)
{
$this->_storeHeader($name,
$this->_factory->createTextHeader($name, $value));
$this->storeHeader($name,
$this->factory->createTextHeader($name, $value));
}
/**
@@ -101,7 +106,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function addParameterizedHeader($name, $value = null, $params = array())
{
$this->_storeHeader($name, $this->_factory->createParameterizedHeader($name, $value, $params));
$this->storeHeader($name, $this->factory->createParameterizedHeader($name, $value, $params));
}
/**
@@ -112,7 +117,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function addIdHeader($name, $ids = null)
{
$this->_storeHeader($name, $this->_factory->createIdHeader($name, $ids));
$this->storeHeader($name, $this->factory->createIdHeader($name, $ids));
}
/**
@@ -123,7 +128,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function addPathHeader($name, $path = null)
{
$this->_storeHeader($name, $this->_factory->createPathHeader($name, $path));
$this->storeHeader($name, $this->factory->createPathHeader($name, $path));
}
/**
@@ -140,7 +145,16 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
{
$lowerName = strtolower($name);
return array_key_exists($lowerName, $this->_headers) && array_key_exists($index, $this->_headers[$lowerName]);
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]);
}
/**
@@ -157,7 +171,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function set(Swift_Mime_Header $header, $index = 0)
{
$this->_storeHeader($header->getFieldName(), $header, $index);
$this->storeHeader($header->getFieldName(), $header, $index);
}
/**
@@ -173,10 +187,18 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function get($name, $index = 0)
{
if ($this->has($name, $index)) {
$lowerName = strtolower($name);
$name = strtolower($name);
return $this->_headers[$lowerName][$index];
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];
}
}
}
@@ -191,7 +213,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
{
if (!isset($name)) {
$headers = array();
foreach ($this->_headers as $collection) {
foreach ($this->headers as $collection) {
$headers = array_merge($headers, $collection);
}
@@ -199,11 +221,11 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
}
$lowerName = strtolower($name);
if (!array_key_exists($lowerName, $this->_headers)) {
if (!array_key_exists($lowerName, $this->headers)) {
return array();
}
return $this->_headers[$lowerName];
return $this->headers[$lowerName];
}
/**
@@ -213,9 +235,9 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function listAll()
{
$headers = $this->_headers;
if ($this->_canSort()) {
uksort($headers, array($this, '_sortHeaders'));
$headers = $this->headers;
if ($this->canSort()) {
uksort($headers, array($this, 'sortHeaders'));
}
return array_keys($headers);
@@ -232,7 +254,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
public function remove($name, $index = 0)
{
$lowerName = strtolower($name);
unset($this->_headers[$lowerName][$index]);
unset($this->headers[$lowerName][$index]);
}
/**
@@ -243,17 +265,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
public function removeAll($name)
{
$lowerName = strtolower($name);
unset($this->_headers[$lowerName]);
}
/**
* Create a new instance of this HeaderSet.
*
* @return Swift_Mime_HeaderSet
*/
public function newInstance()
{
return new self($this->_factory);
unset($this->headers[$lowerName]);
}
/**
@@ -265,7 +277,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function defineOrdering(array $sequence)
{
$this->_order = array_flip(array_map('strtolower', $sequence));
$this->order = array_flip(array_map('strtolower', $sequence));
}
/**
@@ -277,7 +289,7 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function setAlwaysDisplayed(array $names)
{
$this->_required = array_flip(array_map('strtolower', $names));
$this->required = array_flip(array_map('strtolower', $names));
}
/**
@@ -298,13 +310,13 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
public function toString()
{
$string = '';
$headers = $this->_headers;
if ($this->_canSort()) {
uksort($headers, array($this, '_sortHeaders'));
$headers = $this->headers;
if ($this->canSort()) {
uksort($headers, array($this, 'sortHeaders'));
}
foreach ($headers as $collection) {
foreach ($collection as $header) {
if ($this->_isDisplayed($header) || $header->getFieldBody() != '') {
if ($this->isDisplayed($header) || $header->getFieldBody() != '') {
$string .= $header->toString();
}
}
@@ -326,31 +338,31 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
}
/** Save a Header to the internal collection */
private function _storeHeader($name, Swift_Mime_Header $header, $offset = null)
private function storeHeader($name, Swift_Mime_Header $header, $offset = null)
{
if (!isset($this->_headers[strtolower($name)])) {
$this->_headers[strtolower($name)] = array();
if (!isset($this->headers[strtolower($name)])) {
$this->headers[strtolower($name)] = array();
}
if (!isset($offset)) {
$this->_headers[strtolower($name)][] = $header;
$this->headers[strtolower($name)][] = $header;
} else {
$this->_headers[strtolower($name)][$offset] = $header;
$this->headers[strtolower($name)][$offset] = $header;
}
}
/** Test if the headers can be sorted */
private function _canSort()
private function canSort()
{
return count($this->_order) > 0;
return count($this->order) > 0;
}
/** uksort() algorithm for Header ordering */
private function _sortHeaders($a, $b)
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;
$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
@@ -367,15 +379,15 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
}
/** Test if the given Header is always displayed */
private function _isDisplayed(Swift_Mime_Header $header)
private function isDisplayed(Swift_Mime_Header $header)
{
return array_key_exists(strtolower($header->getFieldName()), $this->_required);
return array_key_exists(strtolower($header->getFieldName()), $this->required);
}
/** Notify all Headers of the new charset */
private function _notifyHeadersOfCharset($charset)
private function notifyHeadersOfCharset($charset)
{
foreach ($this->_headers as $headerGroup) {
foreach ($this->headers as $headerGroup) {
foreach ($headerGroup as $header) {
$header->setCharset($charset);
}
@@ -387,10 +399,10 @@ class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
*/
public function __clone()
{
$this->_factory = clone $this->_factory;
foreach ($this->_headers as $groupKey => $headerGroup) {
$this->factory = clone $this->factory;
foreach ($this->headers as $groupKey => $headerGroup) {
foreach ($headerGroup as $key => $header) {
$this->_headers[$groupKey][$key] = clone $header;
$this->headers[$groupKey][$key] = clone $header;
}
}
}

View File

@@ -13,20 +13,26 @@
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime_Message
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 Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_Mime_Grammar $grammar
* @param string $charset
* @param Swift_Mime_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $charset = null)
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null)
{
parent::__construct($headers, $encoder, $cache, $grammar, $charset);
parent::__construct($headers, $encoder, $cache, $idGenerator, $charset);
$this->getHeaders()->defineOrdering(array(
'Return-Path',
'Received',
@@ -47,7 +53,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
));
$this->getHeaders()->setAlwaysDisplayed(array('Date', 'Message-ID', 'From'));
$this->getHeaders()->addTextHeader('MIME-Version', '1.0');
$this->setDate(time());
$this->setDate(new DateTimeImmutable());
$this->setId($this->getId());
$this->getHeaders()->addMailboxHeader('From');
}
@@ -67,11 +73,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*
* @param string $subject
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setSubject($subject)
{
if (!$this->_setHeaderFieldModel('Subject', $subject)) {
if (!$this->setHeaderFieldModel('Subject', $subject)) {
$this->getHeaders()->addTextHeader('Subject', $subject);
}
@@ -85,20 +91,20 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getSubject()
{
return $this->_getHeaderFieldModel('Subject');
return $this->getHeaderFieldModel('Subject');
}
/**
* Set the date at which this message was created.
*
* @param int $date
* @param DateTimeInterface $dateTime
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setDate($date)
public function setDate(DateTimeInterface $dateTime)
{
if (!$this->_setHeaderFieldModel('Date', $date)) {
$this->getHeaders()->addDateHeader('Date', $date);
if (!$this->setHeaderFieldModel('Date', $dateTime)) {
$this->getHeaders()->addDateHeader('Date', $dateTime);
}
return $this;
@@ -107,11 +113,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
/**
* Get the date at which this message was created.
*
* @return int
* @return DateTimeInterface
*/
public function getDate()
{
return $this->_getHeaderFieldModel('Date');
return $this->getHeaderFieldModel('Date');
}
/**
@@ -119,11 +125,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*
* @param string $address
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setReturnPath($address)
{
if (!$this->_setHeaderFieldModel('Return-Path', $address)) {
if (!$this->setHeaderFieldModel('Return-Path', $address)) {
$this->getHeaders()->addPathHeader('Return-Path', $address);
}
@@ -137,7 +143,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getReturnPath()
{
return $this->_getHeaderFieldModel('Return-Path');
return $this->getHeaderFieldModel('Return-Path');
}
/**
@@ -148,7 +154,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param string $address
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setSender($address, $name = null)
{
@@ -156,7 +162,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
$address = array($address => $name);
}
if (!$this->_setHeaderFieldModel('Sender', (array) $address)) {
if (!$this->setHeaderFieldModel('Sender', (array) $address)) {
$this->getHeaders()->addMailboxHeader('Sender', (array) $address);
}
@@ -170,7 +176,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getSender()
{
return $this->_getHeaderFieldModel('Sender');
return $this->getHeaderFieldModel('Sender');
}
/**
@@ -181,7 +187,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param string $address
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function addFrom($address, $name = null)
{
@@ -202,7 +208,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param string|array $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setFrom($addresses, $name = null)
{
@@ -210,7 +216,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('From', (array) $addresses)) {
if (!$this->setHeaderFieldModel('From', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('From', (array) $addresses);
}
@@ -224,7 +230,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getFrom()
{
return $this->_getHeaderFieldModel('From');
return $this->getHeaderFieldModel('From');
}
/**
@@ -235,7 +241,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param string $address
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function addReplyTo($address, $name = null)
{
@@ -256,7 +262,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param mixed $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setReplyTo($addresses, $name = null)
{
@@ -264,7 +270,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Reply-To', (array) $addresses)) {
if (!$this->setHeaderFieldModel('Reply-To', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses);
}
@@ -278,7 +284,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getReplyTo()
{
return $this->_getHeaderFieldModel('Reply-To');
return $this->getHeaderFieldModel('Reply-To');
}
/**
@@ -289,7 +295,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param string $address
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function addTo($address, $name = null)
{
@@ -311,7 +317,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param mixed $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setTo($addresses, $name = null)
{
@@ -319,7 +325,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('To', (array) $addresses)) {
if (!$this->setHeaderFieldModel('To', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('To', (array) $addresses);
}
@@ -333,7 +339,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getTo()
{
return $this->_getHeaderFieldModel('To');
return $this->getHeaderFieldModel('To');
}
/**
@@ -344,7 +350,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param string $address
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function addCc($address, $name = null)
{
@@ -363,7 +369,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param mixed $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setCc($addresses, $name = null)
{
@@ -371,7 +377,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Cc', (array) $addresses)) {
if (!$this->setHeaderFieldModel('Cc', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Cc', (array) $addresses);
}
@@ -385,7 +391,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getCc()
{
return $this->_getHeaderFieldModel('Cc');
return $this->getHeaderFieldModel('Cc');
}
/**
@@ -396,7 +402,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param string $address
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function addBcc($address, $name = null)
{
@@ -415,7 +421,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
* @param mixed $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setBcc($addresses, $name = null)
{
@@ -423,7 +429,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Bcc', (array) $addresses)) {
if (!$this->setHeaderFieldModel('Bcc', (array) $addresses)) {
$this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses);
}
@@ -437,7 +443,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getBcc()
{
return $this->_getHeaderFieldModel('Bcc');
return $this->getHeaderFieldModel('Bcc');
}
/**
@@ -447,16 +453,16 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*
* @param int $priority
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setPriority($priority)
{
$priorityMap = array(
1 => 'Highest',
2 => 'High',
3 => 'Normal',
4 => 'Low',
5 => 'Lowest',
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)) {
@@ -464,7 +470,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
} elseif ($priority < min($pMapKeys)) {
$priority = min($pMapKeys);
}
if (!$this->_setHeaderFieldModel('X-Priority',
if (!$this->setHeaderFieldModel('X-Priority',
sprintf('%d (%s)', $priority, $priorityMap[$priority]))) {
$this->getHeaders()->addTextHeader('X-Priority',
sprintf('%d (%s)', $priority, $priorityMap[$priority]));
@@ -483,11 +489,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getPriority()
{
list($priority) = sscanf($this->_getHeaderFieldModel('X-Priority'),
list($priority) = sscanf($this->getHeaderFieldModel('X-Priority'),
'%[1-5]'
);
return isset($priority) ? $priority : 3;
return $priority ?? 3;
}
/**
@@ -495,11 +501,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*
* @param array $addresses
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function setReadReceiptTo($addresses)
{
if (!$this->_setHeaderFieldModel('Disposition-Notification-To', $addresses)) {
if (!$this->setHeaderFieldModel('Disposition-Notification-To', $addresses)) {
$this->getHeaders()
->addMailboxHeader('Disposition-Notification-To', $addresses);
}
@@ -514,17 +520,17 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
*/
public function getReadReceiptTo()
{
return $this->_getHeaderFieldModel('Disposition-Notification-To');
return $this->getHeaderFieldModel('Disposition-Notification-To');
}
/**
* Attach a {@link Swift_Mime_MimeEntity} such as an Attachment or MimePart.
* Attach a {@link Swift_Mime_SimpleMimeEntity} such as an Attachment or MimePart.
*
* @param Swift_Mime_MimeEntity $entity
* @param Swift_Mime_SimpleMimeEntity $entity
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function attach(Swift_Mime_MimeEntity $entity)
public function attach(Swift_Mime_SimpleMimeEntity $entity)
{
$this->setChildren(array_merge($this->getChildren(), array($entity)));
@@ -534,11 +540,11 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
/**
* Remove an already attached entity.
*
* @param Swift_Mime_MimeEntity $entity
* @param Swift_Mime_SimpleMimeEntity $entity
*
* @return Swift_Mime_SimpleMessage
* @return $this
*/
public function detach(Swift_Mime_MimeEntity $entity)
public function detach(Swift_Mime_SimpleMimeEntity $entity)
{
$newChildren = array();
foreach ($this->getChildren() as $child) {
@@ -552,14 +558,14 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
}
/**
* Attach a {@link Swift_Mime_MimeEntity} and return it's CID source.
* 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.
*
* @param Swift_Mime_MimeEntity $entity
* @param Swift_Mime_SimpleMimeEntity $entity
*
* @return string
*/
public function embed(Swift_Mime_MimeEntity $entity)
public function embed(Swift_Mime_SimpleMimeEntity $entity)
{
$this->attach($entity);
@@ -574,7 +580,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
public function toString()
{
if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') {
$this->setChildren(array_merge(array($this->_becomeMimePart()), $children));
$this->setChildren(array_merge(array($this->becomeMimePart()), $children));
$string = parent::toString();
$this->setChildren($children);
} else {
@@ -604,7 +610,7 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
public function toByteStream(Swift_InputByteStream $is)
{
if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') {
$this->setChildren(array_merge(array($this->_becomeMimePart()), $children));
$this->setChildren(array_merge(array($this->becomeMimePart()), $children));
parent::toByteStream($is);
$this->setChildren($children);
} else {
@@ -612,29 +618,29 @@ class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart implements Swift_Mime
}
}
/** @see Swift_Mime_SimpleMimeEntity::_getIdField() */
protected function _getIdField()
/** @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()
protected function becomeMimePart()
{
$part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(),
$this->_getCache(), $this->_getGrammar(), $this->_userCharset
$this->getCache(), $this->getIdGenerator(), $this->userCharset
);
$part->setContentType($this->_userContentType);
$part->setContentType($this->userContentType);
$part->setBody($this->getBody());
$part->setFormat($this->_userFormat);
$part->setDelSp($this->_userDelSp);
$part->_setNestingLevel($this->_getTopNestingLevel());
$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()
private function getTopNestingLevel()
{
$highestLevel = $this->getNestingLevel();
foreach ($this->getChildren() as $child) {

View File

@@ -13,79 +13,91 @@
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
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;
private $headers;
/** The body as a string, or a stream */
private $_body;
private $body;
/** The encoder that encodes the body into a streamable format */
private $_encoder;
private $encoder;
/** The grammar to use for id validation */
private $_grammar;
/** Message ID generator */
private $idGenerator;
/** A mime boundary, if any is used */
private $_boundary;
private $boundary;
/** Mime types to be used based on the nesting level */
private $_compositeRanges = array(
private $compositeRanges = array(
'multipart/mixed' => array(self::LEVEL_TOP, self::LEVEL_MIXED),
'multipart/alternative' => array(self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE),
'multipart/related' => array(self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED),
);
/** A set of filter rules to define what level an entity should be nested at */
private $_compoundLevelFilters = array();
private $compoundLevelFilters = array();
/** The nesting level of this entity */
private $_nestingLevel = self::LEVEL_ALTERNATIVE;
private $nestingLevel = self::LEVEL_ALTERNATIVE;
/** A KeyCache instance used during encoding and streaming */
private $_cache;
private $cache;
/** Direct descendants of this entity */
private $_immediateChildren = array();
private $immediateChildren = array();
/** All descendants of this entity */
private $_children = array();
private $children = array();
/** The maximum line length of the body of this entity */
private $_maxLineLength = 78;
private $maxLineLength = 78;
/** The order in which alternative mime types should appear */
private $_alternativePartOrder = array(
private $alternativePartOrder = array(
'text/plain' => 1,
'text/html' => 2,
'multipart/related' => 3,
);
/** The CID of this entity */
private $_id;
private $id;
/** The key used for accessing the cache */
private $_cacheKey;
private $cacheKey;
protected $_userContentType;
protected $userContentType;
/**
* Create a new SimpleMimeEntity with $headers, $encoder and $cache.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_Mime_Grammar $grammar
* @param Swift_Mime_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar)
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator)
{
$this->_cacheKey = md5(uniqid(getmypid().mt_rand(), true));
$this->_cache = $cache;
$this->_headers = $headers;
$this->_grammar = $grammar;
$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(array('Content-Type', 'Content-Transfer-Encoding'));
$this->headers->defineOrdering(array('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
@@ -100,7 +112,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
// )
// )
$this->_compoundLevelFilters = array(
$this->compoundLevelFilters = array(
(self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array(
self::LEVEL_ALTERNATIVE => array(
'text/plain' => self::LEVEL_ALTERNATIVE,
@@ -109,7 +121,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
),
);
$this->_id = $this->getRandomId();
$this->id = $this->idGenerator->generateId();
}
/**
@@ -119,19 +131,19 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function generateId()
{
$this->setId($this->getRandomId());
$this->setId($this->idGenerator->generateId());
return $this->_id;
return $this->id;
}
/**
* Get the {@link Swift_Mime_HeaderSet} for this entity.
* Get the {@link Swift_Mime_SimpleHeaderSet} for this entity.
*
* @return Swift_Mime_HeaderSet
* @return Swift_Mime_SimpleHeaderSet
*/
public function getHeaders()
{
return $this->_headers;
return $this->headers;
}
/**
@@ -143,7 +155,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function getNestingLevel()
{
return $this->_nestingLevel;
return $this->nestingLevel;
}
/**
@@ -153,7 +165,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function getContentType()
{
return $this->_getHeaderFieldModel('Content-Type');
return $this->getHeaderFieldModel('Content-Type');
}
/**
@@ -161,14 +173,14 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @param string $type
*
* @return Swift_Mime_SimpleMimeEntity
* @return $this
*/
public function setContentType($type)
{
$this->_setContentTypeInHeaders($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;
$this->userContentType = $type;
return $this;
}
@@ -182,9 +194,9 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function getId()
{
$tmp = (array) $this->_getHeaderFieldModel($this->_getIdField());
$tmp = (array) $this->getHeaderFieldModel($this->getIdField());
return $this->_headers->has($this->_getIdField()) ? current($tmp) : $this->_id;
return $this->headers->has($this->getIdField()) ? current($tmp) : $this->id;
}
/**
@@ -192,14 +204,14 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @param string $id
*
* @return Swift_Mime_SimpleMimeEntity
* @return $this
*/
public function setId($id)
{
if (!$this->_setHeaderFieldModel($this->_getIdField(), $id)) {
$this->_headers->addIdHeader($this->_getIdField(), $id);
if (!$this->setHeaderFieldModel($this->getIdField(), $id)) {
$this->headers->addIdHeader($this->getIdField(), $id);
}
$this->_id = $id;
$this->id = $id;
return $this;
}
@@ -213,7 +225,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function getDescription()
{
return $this->_getHeaderFieldModel('Content-Description');
return $this->getHeaderFieldModel('Content-Description');
}
/**
@@ -223,12 +235,12 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @param string $description
*
* @return Swift_Mime_SimpleMimeEntity
* @return $this
*/
public function setDescription($description)
{
if (!$this->_setHeaderFieldModel('Content-Description', $description)) {
$this->_headers->addTextHeader('Content-Description', $description);
if (!$this->setHeaderFieldModel('Content-Description', $description)) {
$this->headers->addTextHeader('Content-Description', $description);
}
return $this;
@@ -241,7 +253,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function getMaxLineLength()
{
return $this->_maxLineLength;
return $this->maxLineLength;
}
/**
@@ -251,11 +263,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @param int $length
*
* @return Swift_Mime_SimpleMimeEntity
* @return $this
*/
public function setMaxLineLength($length)
{
$this->_maxLineLength = $length;
$this->maxLineLength = $length;
return $this;
}
@@ -263,37 +275,36 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
/**
* Get all children added to this entity.
*
* @return Swift_Mime_MimeEntity[]
* @return Swift_Mime_SimpleMimeEntity[]
*/
public function getChildren()
{
return $this->_children;
return $this->children;
}
/**
* Set all children of this entity.
*
* @param Swift_Mime_MimeEntity[] $children
* @param int $compoundLevel For internal use only
* @param Swift_Mime_SimpleMimeEntity[] $children
* @param int $compoundLevel For internal use only
*
* @return Swift_Mime_SimpleMimeEntity
* @return $this
*/
public function setChildren(array $children, $compoundLevel = null)
{
// TODO: Try to refactor this logic
$compoundLevel = isset($compoundLevel) ? $compoundLevel : $this->_getCompoundLevel($children);
$compoundLevel = $compoundLevel ?? $this->getCompoundLevel($children);
$immediateChildren = array();
$grandchildren = array();
$newContentType = $this->_userContentType;
$newContentType = $this->userContentType;
foreach ($children as $child) {
$level = $this->_getNeededChildLevel($child, $compoundLevel);
$level = $this->getNeededChildLevel($child, $compoundLevel);
if (empty($immediateChildren)) {
//first iteration
$immediateChildren = array($child);
} else {
$nextLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
$nextLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel);
if ($nextLevel == $level) {
$immediateChildren[] = $child;
} elseif ($level < $nextLevel) {
@@ -308,11 +319,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
}
if ($immediateChildren) {
$lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
$lowestLevel = $this->getNeededChildLevel($immediateChildren[0], $compoundLevel);
// Determine which composite media type is needed to accommodate the
// immediate children
foreach ($this->_compositeRanges as $mediaType => $range) {
foreach ($this->compositeRanges as $mediaType => $range) {
if ($lowestLevel > $range[0] && $lowestLevel <= $range[1]) {
$newContentType = $mediaType;
@@ -322,18 +333,18 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
// Put any grandchildren in a subpart
if (!empty($grandchildren)) {
$subentity = $this->_createChild();
$subentity->_setNestingLevel($lowestLevel);
$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();
$this->immediateChildren = $immediateChildren;
$this->children = $children;
$this->setContentTypeInHeaders($newContentType);
$this->fixHeaders();
$this->sortChildren();
return $this;
}
@@ -345,7 +356,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function getBody()
{
return $this->_body instanceof Swift_OutputByteStream ? $this->_readStream($this->_body) : $this->_body;
return $this->body instanceof Swift_OutputByteStream ? $this->readStream($this->body) : $this->body;
}
/**
@@ -355,15 +366,15 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
* @param mixed $body
* @param string $contentType optional
*
* @return Swift_Mime_SimpleMimeEntity
* @return $this
*/
public function setBody($body, $contentType = null)
{
if ($body !== $this->_body) {
$this->_clearCache();
if ($body !== $this->body) {
$this->clearCache();
}
$this->_body = $body;
$this->body = $body;
if (isset($contentType)) {
$this->setContentType($contentType);
}
@@ -378,7 +389,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function getEncoder()
{
return $this->_encoder;
return $this->encoder;
}
/**
@@ -386,17 +397,17 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @param Swift_Mime_ContentEncoder $encoder
*
* @return Swift_Mime_SimpleMimeEntity
* @return $this
*/
public function setEncoder(Swift_Mime_ContentEncoder $encoder)
{
if ($encoder !== $this->_encoder) {
$this->_clearCache();
if ($encoder !== $this->encoder) {
$this->clearCache();
}
$this->_encoder = $encoder;
$this->_setEncoding($encoder->getName());
$this->_notifyEncoderChanged($encoder);
$this->encoder = $encoder;
$this->setEncoding($encoder->getName());
$this->notifyEncoderChanged($encoder);
return $this;
}
@@ -408,11 +419,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function getBoundary()
{
if (!isset($this->_boundary)) {
$this->_boundary = '_=_swift_v4_'.time().'_'.md5(getmypid().mt_rand().uniqid('', true)).'_=_';
if (!isset($this->boundary)) {
$this->boundary = '_=_swift_'.time().'_'.bin2hex(random_bytes(16)).'_=_';
}
return $this->_boundary;
return $this->boundary;
}
/**
@@ -422,12 +433,12 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @throws Swift_RfcComplianceException
*
* @return Swift_Mime_SimpleMimeEntity
* @return $this
*/
public function setBoundary($boundary)
{
$this->_assertValidBoundary($boundary);
$this->_boundary = $boundary;
$this->assertValidBoundary($boundary);
$this->boundary = $boundary;
return $this;
}
@@ -440,7 +451,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function charsetChanged($charset)
{
$this->_notifyCharsetChanged($charset);
$this->notifyCharsetChanged($charset);
}
/**
@@ -451,7 +462,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function encoderChanged(Swift_Mime_ContentEncoder $encoder)
{
$this->_notifyEncoderChanged($encoder);
$this->notifyEncoderChanged($encoder);
}
/**
@@ -461,8 +472,8 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function toString()
{
$string = $this->_headers->toString();
$string .= $this->_bodyToString();
$string = $this->headers->toString();
$string .= $this->bodyToString();
return $string;
}
@@ -472,22 +483,22 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @return string
*/
protected function _bodyToString()
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');
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);
$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) {
if (!empty($this->immediateChildren)) {
foreach ($this->immediateChildren as $child) {
$string .= "\r\n\r\n--".$this->getBoundary()."\r\n";
$string .= $child->toString();
}
@@ -516,10 +527,10 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function toByteStream(Swift_InputByteStream $is)
{
$is->write($this->_headers->toString());
$is->write($this->headers->toString());
$is->commit();
$this->_bodyToByteStream($is);
$this->bodyToByteStream($is);
}
/**
@@ -527,26 +538,26 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @param Swift_InputByteStream
*/
protected function _bodyToByteStream(Swift_InputByteStream $is)
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);
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');
$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);
if ($this->body instanceof Swift_OutputByteStream) {
$this->body->setReadPointer(0);
$this->_encoder->encodeByteStream($this->_body, $is, 0, $this->getMaxLineLength());
$this->encoder->encodeByteStream($this->body, $is, 0, $this->getMaxLineLength());
} else {
$is->write($this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()));
$is->write($this->encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()));
}
if ($cacheIs) {
@@ -556,8 +567,8 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
}
}
if (!empty($this->_immediateChildren)) {
foreach ($this->_immediateChildren as $child) {
if (!empty($this->immediateChildren)) {
foreach ($this->immediateChildren as $child) {
$is->write("\r\n\r\n--".$this->getBoundary()."\r\n");
$child->toByteStream($is);
}
@@ -568,7 +579,7 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
/**
* Get the name of the header that provides the ID of this entity.
*/
protected function _getIdField()
protected function getIdField()
{
return 'Content-ID';
}
@@ -576,20 +587,20 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
/**
* Get the model data (usually an array or a string) for $field.
*/
protected function _getHeaderFieldModel($field)
protected function getHeaderFieldModel($field)
{
if ($this->_headers->has($field)) {
return $this->_headers->get($field)->getFieldBodyModel();
if ($this->headers->has($field)) {
return $this->headers->get($field)->getFieldBodyModel();
}
}
/**
* Set the model data for $field.
*/
protected function _setHeaderFieldModel($field, $model)
protected function setHeaderFieldModel($field, $model)
{
if ($this->_headers->has($field)) {
$this->_headers->get($field)->setFieldBodyModel($model);
if ($this->headers->has($field)) {
$this->headers->get($field)->setFieldBodyModel($model);
return true;
}
@@ -600,20 +611,20 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
/**
* Get the parameter value of $parameter on $field header.
*/
protected function _getHeaderParameter($field, $parameter)
protected function getHeaderParameter($field, $parameter)
{
if ($this->_headers->has($field)) {
return $this->_headers->get($field)->getParameter($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)
protected function setHeaderParameter($field, $parameter, $value)
{
if ($this->_headers->has($field)) {
$this->_headers->get($field)->setParameter($parameter, $value);
if ($this->headers->has($field)) {
$this->headers->get($field)->setParameter($parameter, $value);
return true;
}
@@ -624,16 +635,16 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
/**
* Re-evaluate what content type and encoding should be used on this entity.
*/
protected function _fixHeaders()
protected function fixHeaders()
{
if (count($this->_immediateChildren)) {
$this->_setHeaderParameter('Content-Type', 'boundary',
if (count($this->immediateChildren)) {
$this->setHeaderParameter('Content-Type', 'boundary',
$this->getBoundary()
);
$this->_headers->remove('Content-Transfer-Encoding');
$this->headers->remove('Content-Transfer-Encoding');
} else {
$this->_setHeaderParameter('Content-Type', 'boundary', null);
$this->_setEncoding($this->_encoder->getName());
$this->setHeaderParameter('Content-Type', 'boundary', null);
$this->setEncoding($this->encoder->getName());
}
}
@@ -642,50 +653,30 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*
* @return Swift_KeyCache
*/
protected function _getCache()
protected function getCache()
{
return $this->_cache;
return $this->cache;
}
/**
* Get the grammar used for validation.
* Get the ID generator.
*
* @return Swift_Mime_Grammar
* @return Swift_IdGenerator
*/
protected function _getGrammar()
protected function getIdGenerator()
{
return $this->_grammar;
return $this->idGenerator;
}
/**
* Empty the KeyCache for this entity.
*/
protected function _clearCache()
protected function clearCache()
{
$this->_cache->clearKey($this->_cacheKey, 'body');
$this->cache->clearKey($this->cacheKey, 'body');
}
/**
* Returns a random Content-ID or Message-ID.
*
* @return string
*/
protected function getRandomId()
{
$idLeft = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true));
$idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated';
$id = $idLeft.'@'.$idRight;
try {
$this->_assertValidId($id);
} catch (Swift_RfcComplianceException $e) {
$id = $idLeft.'@swift.generated';
}
return $id;
}
private function _readStream(Swift_OutputByteStream $os)
private function readStream(Swift_OutputByteStream $os)
{
$string = '';
while (false !== $bytes = $os->read(8192)) {
@@ -697,33 +688,33 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
return $string;
}
private function _setEncoding($encoding)
private function setEncoding($encoding)
{
if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) {
$this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding);
if (!$this->setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) {
$this->headers->addTextHeader('Content-Transfer-Encoding', $encoding);
}
}
private function _assertValidBoundary($boundary)
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)
private function setContentTypeInHeaders($type)
{
if (!$this->_setHeaderFieldModel('Content-Type', $type)) {
$this->_headers->addParameterizedHeader('Content-Type', $type);
if (!$this->setHeaderFieldModel('Content-Type', $type)) {
$this->headers->addParameterizedHeader('Content-Type', $type);
}
}
private function _setNestingLevel($level)
private function setNestingLevel($level)
{
$this->_nestingLevel = $level;
$this->nestingLevel = $level;
}
private function _getCompoundLevel($children)
private function getCompoundLevel($children)
{
$level = 0;
foreach ($children as $child) {
@@ -733,10 +724,10 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
return $level;
}
private function _getNeededChildLevel($child, $compoundLevel)
private function getNeededChildLevel($child, $compoundLevel)
{
$filter = array();
foreach ($this->_compoundLevelFilters as $bitmask => $rules) {
foreach ($this->compoundLevelFilters as $bitmask => $rules) {
if (($compoundLevel & $bitmask) === $bitmask) {
$filter = $rules + $filter;
}
@@ -752,31 +743,31 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
return $realLevel;
}
private function _createChild()
private function createChild()
{
return new self($this->_headers->newInstance(), $this->_encoder, $this->_cache, $this->_grammar);
return new self($this->headers->newInstance(), $this->encoder, $this->cache, $this->idGenerator);
}
private function _notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder)
private function notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder)
{
foreach ($this->_immediateChildren as $child) {
foreach ($this->immediateChildren as $child) {
$child->encoderChanged($encoder);
}
}
private function _notifyCharsetChanged($charset)
private function notifyCharsetChanged($charset)
{
$this->_encoder->charsetChanged($charset);
$this->_headers->charsetChanged($charset);
foreach ($this->_immediateChildren as $child) {
$this->encoder->charsetChanged($charset);
$this->headers->charsetChanged($charset);
foreach ($this->immediateChildren as $child) {
$child->charsetChanged($charset);
}
}
private function _sortChildren()
private function sortChildren()
{
$shouldSort = false;
foreach ($this->_immediateChildren as $child) {
foreach ($this->immediateChildren as $child) {
// NOTE: This include alternative parts moved into a related part
if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE) {
$shouldSort = true;
@@ -786,43 +777,32 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
// Sort in order of preference, if there is one
if ($shouldSort) {
usort($this->_immediateChildren, array($this, '_childSortAlgorithm'));
// Group the messages by order of preference
$sorted = array();
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] = array();
}
$sorted[$level][] = $child;
}
ksort($sorted);
$this->immediateChildren = array_reduce($sorted, 'array_merge', array());
}
}
private function _childSortAlgorithm($a, $b)
{
$typePrefs = array();
$types = array(strtolower($a->getContentType()), strtolower($b->getContentType()));
foreach ($types as $type) {
$typePrefs[] = array_key_exists($type, $this->_alternativePartOrder) ? $this->_alternativePartOrder[$type] : max($this->_alternativePartOrder) + 1;
}
return $typePrefs[0] >= $typePrefs[1] ? 1 : -1;
}
// -- Destructor
/**
* Empties it's own contents from the cache.
*/
public function __destruct()
{
$this->_cache->clearAll($this->_cacheKey);
}
/**
* Throws an Exception if the id passed does not comply with RFC 2822.
*
* @param string $id
*
* @throws Swift_RfcComplianceException
*/
private function _assertValidId($id)
{
if (!preg_match('/^'.$this->_grammar->getDefinition('id-left').'@'.$this->_grammar->getDefinition('id-right').'$/D', $id)) {
throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>');
if ($this->cache instanceof Swift_KeyCache) {
$this->cache->clearAll($this->cacheKey);
}
}
@@ -831,11 +811,11 @@ class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
*/
public function __clone()
{
$this->_headers = clone $this->_headers;
$this->_encoder = clone $this->_encoder;
$this->_cacheKey = uniqid();
$this->headers = clone $this->headers;
$this->encoder = clone $this->encoder;
$this->cacheKey = bin2hex(random_bytes(16)); // set 32 hex values
$children = array();
foreach ($this->_children as $pos => $child) {
foreach ($this->children as $pos => $child) {
$children[$pos] = clone $child;
}
$this->setChildren($children);

View File

@@ -42,18 +42,4 @@ class Swift_MimePart extends Swift_Mime_MimePart
$this->setContentType($contentType);
}
}
/**
* Create a new MimePart.
*
* @param string $body
* @param string $contentType
* @param string $charset
*
* @return Swift_Mime_MimePart
*/
public static function newInstance($body = null, $contentType = null, $charset = null)
{
return new self($body, $contentType, $charset);
}
}

View File

@@ -15,9 +15,6 @@
*/
class Swift_NullTransport extends Swift_Transport_NullTransport
{
/**
* Create a new NullTransport.
*/
public function __construct()
{
call_user_func_array(
@@ -26,14 +23,4 @@ class Swift_NullTransport extends Swift_Transport_NullTransport
->createDependenciesFor('transport.null')
);
}
/**
* Create a new NullTransport instance.
*
* @return Swift_NullTransport
*/
public static function newInstance()
{
return new self();
}
}

View File

@@ -20,28 +20,28 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_
*
* @var int
*/
private $_threshold;
private $threshold;
/**
* The number of seconds to sleep for during a restart.
*
* @var int
*/
private $_sleep;
private $sleep;
/**
* The internal counter.
*
* @var int
*/
private $_counter = 0;
private $counter = 0;
/**
* The Sleeper instance for sleeping.
*
* @var Swift_Plugins_Sleeper
*/
private $_sleeper;
private $sleeper;
/**
* Create a new AntiFloodPlugin with $threshold and $sleep time.
@@ -54,7 +54,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_
{
$this->setThreshold($threshold);
$this->setSleepTime($sleep);
$this->_sleeper = $sleeper;
$this->sleeper = $sleeper;
}
/**
@@ -64,7 +64,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_
*/
public function setThreshold($threshold)
{
$this->_threshold = $threshold;
$this->threshold = $threshold;
}
/**
@@ -74,7 +74,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_
*/
public function getThreshold()
{
return $this->_threshold;
return $this->threshold;
}
/**
@@ -84,7 +84,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_
*/
public function setSleepTime($sleep)
{
$this->_sleep = $sleep;
$this->sleep = $sleep;
}
/**
@@ -94,7 +94,7 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_
*/
public function getSleepTime()
{
return $this->_sleep;
return $this->sleep;
}
/**
@@ -113,15 +113,15 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
{
++$this->_counter;
if ($this->_counter >= $this->_threshold) {
++$this->counter;
if ($this->counter >= $this->threshold) {
$transport = $evt->getTransport();
$transport->stop();
if ($this->_sleep) {
$this->sleep($this->_sleep);
if ($this->sleep) {
$this->sleep($this->sleep);
}
$transport->start();
$this->_counter = 0;
$this->counter = 0;
}
}
@@ -132,8 +132,8 @@ class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_
*/
public function sleep($seconds)
{
if (isset($this->_sleeper)) {
$this->_sleeper->sleep($seconds);
if (isset($this->sleeper)) {
$this->sleeper->sleep($seconds);
} else {
sleep($seconds);
}

View File

@@ -20,17 +20,17 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
*
* @var int
*/
private $_out = 0;
private $out = 0;
/**
* The incoming traffic counter.
*
* @var int
*/
private $_in = 0;
private $in = 0;
/** Bound byte streams */
private $_mirrors = array();
private $mirrors = array();
/**
* Not used.
@@ -58,7 +58,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
public function commandSent(Swift_Events_CommandEvent $evt)
{
$command = $evt->getCommand();
$this->_out += strlen($command);
$this->out += strlen($command);
}
/**
@@ -69,7 +69,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
public function responseReceived(Swift_Events_ResponseEvent $evt)
{
$response = $evt->getResponse();
$this->_in += strlen($response);
$this->in += strlen($response);
}
/**
@@ -79,8 +79,8 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
*/
public function write($bytes)
{
$this->_out += strlen($bytes);
foreach ($this->_mirrors as $stream) {
$this->out += strlen($bytes);
foreach ($this->mirrors as $stream) {
$stream->write($bytes);
}
}
@@ -102,7 +102,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
*/
public function bind(Swift_InputByteStream $is)
{
$this->_mirrors[] = $is;
$this->mirrors[] = $is;
}
/**
@@ -116,9 +116,9 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
*/
public function unbind(Swift_InputByteStream $is)
{
foreach ($this->_mirrors as $k => $stream) {
foreach ($this->mirrors as $k => $stream) {
if ($is === $stream) {
unset($this->_mirrors[$k]);
unset($this->mirrors[$k]);
}
}
}
@@ -128,7 +128,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
*/
public function flushBuffers()
{
foreach ($this->_mirrors as $stream) {
foreach ($this->mirrors as $stream) {
$stream->flushBuffers();
}
}
@@ -140,7 +140,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
*/
public function getBytesOut()
{
return $this->_out;
return $this->out;
}
/**
@@ -150,7 +150,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
*/
public function getBytesIn()
{
return $this->_in;
return $this->in;
}
/**
@@ -158,7 +158,7 @@ class Swift_Plugins_BandwidthMonitorPlugin implements Swift_Events_SendListener,
*/
public function reset()
{
$this->_out = 0;
$this->_in = 0;
$this->out = 0;
$this->in = 0;
}
}

View File

@@ -17,19 +17,19 @@
class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_Plugins_Decorator_Replacements
{
/** The replacement map */
private $_replacements;
private $replacements;
/** The body as it was before replacements */
private $_originalBody;
private $originalBody;
/** The original headers of the message, before replacements */
private $_originalHeaders = array();
private $originalHeaders = array();
/** Bodies of children before they are replaced */
private $_originalChildBodies = array();
private $originalChildBodies = array();
/** The Message that was last replaced */
private $_lastMessage;
private $lastMessage;
/**
* Create a new DecoratorPlugin with $replacements.
@@ -66,9 +66,9 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_
public function setReplacements($replacements)
{
if (!($replacements instanceof Swift_Plugins_Decorator_Replacements)) {
$this->_replacements = (array) $replacements;
$this->replacements = (array) $replacements;
} else {
$this->_replacements = $replacements;
$this->replacements = $replacements;
}
}
@@ -80,7 +80,7 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_
public function beforeSendPerformed(Swift_Events_SendEvent $evt)
{
$message = $evt->getMessage();
$this->_restoreMessage($message);
$this->restoreMessage($message);
$to = array_keys($message->getTo());
$address = array_shift($to);
if ($replacements = $this->getReplacementsFor($address)) {
@@ -91,7 +91,7 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_
$search, $replace, $body
);
if ($body != $bodyReplaced) {
$this->_originalBody = $body;
$this->originalBody = $body;
$message->setBody($bodyReplaced);
}
@@ -111,12 +111,12 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_
$count = 1;
}
}
} else {
} elseif (is_string($body)) {
$bodyReplaced = str_replace($search, $replace, $body, $count);
}
if ($count) {
$this->_originalHeaders[$header->getFieldName()] = $body;
$this->originalHeaders[$header->getFieldName()] = $body;
$header->setFieldBodyModel($bodyReplaced);
}
}
@@ -131,11 +131,11 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_
);
if ($body != $bodyReplaced) {
$child->setBody($bodyReplaced);
$this->_originalChildBodies[$child->getId()] = $body;
$this->originalChildBodies[$child->getId()] = $body;
}
}
}
$this->_lastMessage = $message;
$this->lastMessage = $message;
}
}
@@ -155,11 +155,11 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_
*/
public function getReplacementsFor($address)
{
if ($this->_replacements instanceof Swift_Plugins_Decorator_Replacements) {
return $this->_replacements->getReplacementsFor($address);
if ($this->replacements instanceof Swift_Plugins_Decorator_Replacements) {
return $this->replacements->getReplacementsFor($address);
}
return isset($this->_replacements[$address]) ? $this->_replacements[$address] : null;
return $this->replacements[$address] ?? null;
}
/**
@@ -169,36 +169,36 @@ class Swift_Plugins_DecoratorPlugin implements Swift_Events_SendListener, Swift_
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
{
$this->_restoreMessage($evt->getMessage());
$this->restoreMessage($evt->getMessage());
}
/** Restore a changed message back to its original state */
private function _restoreMessage(Swift_Mime_Message $message)
private function restoreMessage(Swift_Mime_SimpleMessage $message)
{
if ($this->_lastMessage === $message) {
if (isset($this->_originalBody)) {
$message->setBody($this->_originalBody);
$this->_originalBody = null;
if ($this->lastMessage === $message) {
if (isset($this->originalBody)) {
$message->setBody($this->originalBody);
$this->originalBody = null;
}
if (!empty($this->_originalHeaders)) {
if (!empty($this->originalHeaders)) {
foreach ($message->getHeaders()->getAll() as $header) {
if (array_key_exists($header->getFieldName(), $this->_originalHeaders)) {
$header->setFieldBodyModel($this->_originalHeaders[$header->getFieldName()]);
if (array_key_exists($header->getFieldName(), $this->originalHeaders)) {
$header->setFieldBodyModel($this->originalHeaders[$header->getFieldName()]);
}
}
$this->_originalHeaders = array();
$this->originalHeaders = array();
}
if (!empty($this->_originalChildBodies)) {
if (!empty($this->originalChildBodies)) {
$children = (array) $message->getChildren();
foreach ($children as $child) {
$id = $child->getId();
if (array_key_exists($id, $this->_originalChildBodies)) {
$child->setBody($this->_originalChildBodies[$id]);
if (array_key_exists($id, $this->originalChildBodies)) {
$child->setBody($this->originalChildBodies[$id]);
}
}
$this->_originalChildBodies = array();
$this->originalChildBodies = array();
}
$this->_lastMessage = null;
$this->lastMessage = null;
}
}
}

View File

@@ -18,9 +18,9 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener
/**
* The sender to impersonate.
*
* @var String
* @var string
*/
private $_sender;
private $sender;
/**
* Create a new ImpersonatePlugin to impersonate $sender.
@@ -29,7 +29,7 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener
*/
public function __construct($sender)
{
$this->_sender = $sender;
$this->sender = $sender;
}
/**
@@ -46,7 +46,7 @@ class Swift_Plugins_ImpersonatePlugin implements Swift_Events_SendListener
$headers->addPathHeader('X-Swift-Return-Path', $message->getReturnPath());
// replace them with the one to send to
$message->setReturnPath($this->_sender);
$message->setReturnPath($this->sender);
}
/**

View File

@@ -11,12 +11,12 @@
/**
* Does real time logging of Transport level information.
*
* @author Chris Corbyn
* @author Chris Corbyn
*/
class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_Events_ResponseListener, Swift_Events_TransportChangeListener, Swift_Events_TransportExceptionListener, Swift_Plugins_Logger
{
/** The logger which is delegated to */
private $_logger;
private $logger;
/**
* Create a new LoggerPlugin using $logger.
@@ -25,7 +25,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
*/
public function __construct(Swift_Plugins_Logger $logger)
{
$this->_logger = $logger;
$this->logger = $logger;
}
/**
@@ -35,7 +35,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
*/
public function add($entry)
{
$this->_logger->add($entry);
$this->logger->add($entry);
}
/**
@@ -43,7 +43,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
*/
public function clear()
{
$this->_logger->clear();
$this->logger->clear();
}
/**
@@ -53,7 +53,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
*/
public function dump()
{
return $this->_logger->dump();
return $this->logger->dump();
}
/**
@@ -64,7 +64,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
public function commandSent(Swift_Events_CommandEvent $evt)
{
$command = $evt->getCommand();
$this->_logger->add(sprintf('>> %s', $command));
$this->logger->add(sprintf('>> %s', $command));
}
/**
@@ -75,7 +75,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
public function responseReceived(Swift_Events_ResponseEvent $evt)
{
$response = $evt->getResponse();
$this->_logger->add(sprintf('<< %s', $response));
$this->logger->add(sprintf('<< %s', $response));
}
/**
@@ -86,7 +86,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt)
{
$transportName = get_class($evt->getSource());
$this->_logger->add(sprintf('++ Starting %s', $transportName));
$this->logger->add(sprintf('++ Starting %s', $transportName));
}
/**
@@ -97,7 +97,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
public function transportStarted(Swift_Events_TransportChangeEvent $evt)
{
$transportName = get_class($evt->getSource());
$this->_logger->add(sprintf('++ %s started', $transportName));
$this->logger->add(sprintf('++ %s started', $transportName));
}
/**
@@ -108,7 +108,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt)
{
$transportName = get_class($evt->getSource());
$this->_logger->add(sprintf('++ Stopping %s', $transportName));
$this->logger->add(sprintf('++ Stopping %s', $transportName));
}
/**
@@ -119,7 +119,7 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
public function transportStopped(Swift_Events_TransportChangeEvent $evt)
{
$transportName = get_class($evt->getSource());
$this->_logger->add(sprintf('++ %s stopped', $transportName));
$this->logger->add(sprintf('++ %s stopped', $transportName));
}
/**
@@ -132,10 +132,10 @@ class Swift_Plugins_LoggerPlugin implements Swift_Events_CommandListener, Swift_
$e = $evt->getException();
$message = $e->getMessage();
$code = $e->getCode();
$this->_logger->add(sprintf('!! %s (code: %s)', $message, $code));
$this->logger->add(sprintf('!! %s (code: %s)', $message, $code));
$message .= PHP_EOL;
$message .= 'Log data:'.PHP_EOL;
$message .= $this->_logger->dump();
$message .= $this->logger->dump();
$evt->cancelBubble();
throw new Swift_TransportException($message, $code, $e->getPrevious());
}

View File

@@ -20,14 +20,14 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger
*
* @var array
*/
private $_log = array();
private $log = array();
/**
* Max size of the log.
*
* @var int
*/
private $_size = 0;
private $size = 0;
/**
* Create a new ArrayLogger with a maximum of $size entries.
@@ -36,7 +36,7 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger
*/
public function __construct($size = 50)
{
$this->_size = $size;
$this->size = $size;
}
/**
@@ -46,9 +46,9 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger
*/
public function add($entry)
{
$this->_log[] = $entry;
while (count($this->_log) > $this->_size) {
array_shift($this->_log);
$this->log[] = $entry;
while (count($this->log) > $this->size) {
array_shift($this->log);
}
}
@@ -57,7 +57,7 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger
*/
public function clear()
{
$this->_log = array();
$this->log = array();
}
/**
@@ -67,6 +67,6 @@ class Swift_Plugins_Loggers_ArrayLogger implements Swift_Plugins_Logger
*/
public function dump()
{
return implode(PHP_EOL, $this->_log);
return implode(PHP_EOL, $this->log);
}
}

View File

@@ -16,7 +16,7 @@
class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger
{
/** Whether or not HTML should be output */
private $_isHtml;
private $isHtml;
/**
* Create a new EchoLogger.
@@ -25,7 +25,7 @@ class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger
*/
public function __construct($isHtml = true)
{
$this->_isHtml = $isHtml;
$this->isHtml = $isHtml;
}
/**
@@ -35,7 +35,7 @@ class Swift_Plugins_Loggers_EchoLogger implements Swift_Plugins_Logger
*/
public function add($entry)
{
if ($this->_isHtml) {
if ($this->isHtml) {
printf('%s%s%s', htmlspecialchars($entry, ENT_QUOTES), '<br />', PHP_EOL);
} else {
printf('%s%s', $entry, PHP_EOL);

View File

@@ -16,7 +16,7 @@
class Swift_Plugins_MessageLogger implements Swift_Events_SendListener
{
/**
* @var array
* @var Swift_Mime_Message[]
*/
private $messages;
@@ -28,7 +28,7 @@ class Swift_Plugins_MessageLogger implements Swift_Events_SendListener
/**
* Get the message list.
*
* @return array
* @return Swift_Mime_Message[]
*/
public function getMessages()
{

View File

@@ -11,36 +11,36 @@
/**
* Makes sure a connection to a POP3 host has been established prior to connecting to SMTP.
*
* @author Chris Corbyn
* @author Chris Corbyn
*/
class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeListener, Swift_Plugins_Pop_Pop3Connection
{
/** A delegate connection to use (mostly a test hook) */
private $_connection;
private $connection;
/** Hostname of the POP3 server */
private $_host;
private $host;
/** Port number to connect on */
private $_port;
private $port;
/** Encryption type to use (if any) */
private $_crypto;
private $crypto;
/** Username to use (if any) */
private $_username;
private $username;
/** Password to use (if any) */
private $_password;
private $password;
/** Established connection via TCP socket */
private $_socket;
private $socket;
/** Connect timeout in seconds */
private $_timeout = 10;
private $timeout = 10;
/** SMTP Transport to bind to */
private $_transport;
private $transport;
/**
* Create a new PopBeforeSmtpPlugin for $host and $port.
@@ -51,23 +51,9 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*/
public function __construct($host, $port = 110, $crypto = null)
{
$this->_host = $host;
$this->_port = $port;
$this->_crypto = $crypto;
}
/**
* Create a new PopBeforeSmtpPlugin for $host and $port.
*
* @param string $host
* @param int $port
* @param string $crypto as "tls" or "ssl"
*
* @return Swift_Plugins_PopBeforeSmtpPlugin
*/
public static function newInstance($host, $port = 110, $crypto = null)
{
return new self($host, $port, $crypto);
$this->host = $host;
$this->port = $port;
$this->crypto = $crypto;
}
/**
@@ -75,11 +61,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*
* @param Swift_Plugins_Pop_Pop3Connection $connection
*
* @return Swift_Plugins_PopBeforeSmtpPlugin
* @return $this
*/
public function setConnection(Swift_Plugins_Pop_Pop3Connection $connection)
{
$this->_connection = $connection;
$this->connection = $connection;
return $this;
}
@@ -91,7 +77,7 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*/
public function bindSmtp(Swift_Transport $smtp)
{
$this->_transport = $smtp;
$this->transport = $smtp;
}
/**
@@ -99,11 +85,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*
* @param int $timeout
*
* @return Swift_Plugins_PopBeforeSmtpPlugin
* @return $this
*/
public function setTimeout($timeout)
{
$this->_timeout = (int) $timeout;
$this->timeout = (int) $timeout;
return $this;
}
@@ -113,11 +99,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*
* @param string $username
*
* @return Swift_Plugins_PopBeforeSmtpPlugin
* @return $this
*/
public function setUsername($username)
{
$this->_username = $username;
$this->username = $username;
return $this;
}
@@ -127,11 +113,11 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*
* @param string $password
*
* @return Swift_Plugins_PopBeforeSmtpPlugin
* @return $this
*/
public function setPassword($password)
{
$this->_password = $password;
$this->password = $password;
return $this;
}
@@ -143,29 +129,29 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*/
public function connect()
{
if (isset($this->_connection)) {
$this->_connection->connect();
if (isset($this->connection)) {
$this->connection->connect();
} else {
if (!isset($this->_socket)) {
if (!isset($this->socket)) {
if (!$socket = fsockopen(
$this->_getHostString(), $this->_port, $errno, $errstr, $this->_timeout)) {
$this->getHostString(), $this->port, $errno, $errstr, $this->timeout)) {
throw new Swift_Plugins_Pop_Pop3Exception(
sprintf('Failed to connect to POP3 host [%s]: %s', $this->_host, $errstr)
sprintf('Failed to connect to POP3 host [%s]: %s', $this->host, $errstr)
);
}
$this->_socket = $socket;
$this->socket = $socket;
if (false === $greeting = fgets($this->_socket)) {
if (false === $greeting = fgets($this->socket)) {
throw new Swift_Plugins_Pop_Pop3Exception(
sprintf('Failed to connect to POP3 host [%s]', trim($greeting))
);
}
$this->_assertOk($greeting);
$this->assertOk($greeting);
if ($this->_username) {
$this->_command(sprintf("USER %s\r\n", $this->_username));
$this->_command(sprintf("PASS %s\r\n", $this->_password));
if ($this->username) {
$this->command(sprintf("USER %s\r\n", $this->username));
$this->command(sprintf("PASS %s\r\n", $this->password));
}
}
}
@@ -176,16 +162,16 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*/
public function disconnect()
{
if (isset($this->_connection)) {
$this->_connection->disconnect();
if (isset($this->connection)) {
$this->connection->disconnect();
} else {
$this->_command("QUIT\r\n");
if (!fclose($this->_socket)) {
$this->command("QUIT\r\n");
if (!fclose($this->socket)) {
throw new Swift_Plugins_Pop_Pop3Exception(
sprintf('POP3 host [%s] connection could not be stopped', $this->_host)
sprintf('POP3 host [%s] connection could not be stopped', $this->host)
);
}
$this->_socket = null;
$this->socket = null;
}
}
@@ -196,8 +182,8 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
*/
public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt)
{
if (isset($this->_transport)) {
if ($this->_transport !== $evt->getTransport()) {
if (isset($this->transport)) {
if ($this->transport !== $evt->getTransport()) {
return;
}
}
@@ -227,26 +213,26 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
{
}
private function _command($command)
private function command($command)
{
if (!fwrite($this->_socket, $command)) {
if (!fwrite($this->socket, $command)) {
throw new Swift_Plugins_Pop_Pop3Exception(
sprintf('Failed to write command [%s] to POP3 host', trim($command))
);
}
if (false === $response = fgets($this->_socket)) {
if (false === $response = fgets($this->socket)) {
throw new Swift_Plugins_Pop_Pop3Exception(
sprintf('Failed to read from POP3 host after command [%s]', trim($command))
);
}
$this->_assertOk($response);
$this->assertOk($response);
return $response;
}
private function _assertOk($response)
private function assertOk($response)
{
if (substr($response, 0, 3) != '+OK') {
throw new Swift_Plugins_Pop_Pop3Exception(
@@ -255,10 +241,10 @@ class Swift_Plugins_PopBeforeSmtpPlugin implements Swift_Events_TransportChangeL
}
}
private function _getHostString()
private function getHostString()
{
$host = $this->_host;
switch (strtolower($this->_crypto)) {
$host = $this->host;
switch (strtolower($this->crypto)) {
case 'ssl':
$host = 'ssl://'.$host;
break;

View File

@@ -11,7 +11,7 @@
/**
* Redirects all email to a single recipient.
*
* @author Fabien Potencier
* @author Fabien Potencier
*/
class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
{
@@ -20,14 +20,14 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*
* @var mixed
*/
private $_recipient;
private $recipient;
/**
* List of regular expression for recipient whitelisting.
*
* @var array
*/
private $_whitelist = array();
private $whitelist = array();
/**
* Create a new RedirectingPlugin.
@@ -37,8 +37,8 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*/
public function __construct($recipient, array $whitelist = array())
{
$this->_recipient = $recipient;
$this->_whitelist = $whitelist;
$this->recipient = $recipient;
$this->whitelist = $whitelist;
}
/**
@@ -48,7 +48,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*/
public function setRecipient($recipient)
{
$this->_recipient = $recipient;
$this->recipient = $recipient;
}
/**
@@ -58,7 +58,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*/
public function getRecipient()
{
return $this->_recipient;
return $this->recipient;
}
/**
@@ -68,7 +68,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*/
public function setWhitelist(array $whitelist)
{
$this->_whitelist = $whitelist;
$this->whitelist = $whitelist;
}
/**
@@ -78,7 +78,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*/
public function getWhitelist()
{
return $this->_whitelist;
return $this->whitelist;
}
/**
@@ -106,9 +106,9 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
}
// Filter remaining headers against whitelist
$this->_filterHeaderSet($headers, 'To');
$this->_filterHeaderSet($headers, 'Cc');
$this->_filterHeaderSet($headers, 'Bcc');
$this->filterHeaderSet($headers, 'To');
$this->filterHeaderSet($headers, 'Cc');
$this->filterHeaderSet($headers, 'Bcc');
// Add each hard coded recipient
$to = $message->getTo();
@@ -116,7 +116,7 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
$to = array();
}
foreach ((array) $this->_recipient as $recipient) {
foreach ((array) $this->recipient as $recipient) {
if (!array_key_exists($recipient, $to)) {
$message->addTo($recipient);
}
@@ -126,13 +126,13 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
/**
* Filter header set against a whitelist of regular expressions.
*
* @param Swift_Mime_HeaderSet $headerSet
* @param string $type
* @param Swift_Mime_SimpleHeaderSet $headerSet
* @param string $type
*/
private function _filterHeaderSet(Swift_Mime_HeaderSet $headerSet, $type)
private function filterHeaderSet(Swift_Mime_SimpleHeaderSet $headerSet, $type)
{
foreach ($headerSet->getAll($type) as $headers) {
$headers->setNameAddresses($this->_filterNameAddresses($headers->getNameAddresses()));
$headers->setNameAddresses($this->filterNameAddresses($headers->getNameAddresses()));
}
}
@@ -143,12 +143,12 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*
* @return array
*/
private function _filterNameAddresses(array $recipients)
private function filterNameAddresses(array $recipients)
{
$filtered = array();
foreach ($recipients as $address => $name) {
if ($this->_isWhitelisted($address)) {
if ($this->isWhitelisted($address)) {
$filtered[$address] = $name;
}
}
@@ -163,13 +163,13 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*
* @return bool
*/
protected function _isWhitelisted($recipient)
protected function isWhitelisted($recipient)
{
if (in_array($recipient, (array) $this->_recipient)) {
if (in_array($recipient, (array) $this->recipient)) {
return true;
}
foreach ($this->_whitelist as $pattern) {
foreach ($this->whitelist as $pattern) {
if (preg_match($pattern, $recipient)) {
return true;
}
@@ -185,10 +185,10 @@ class Swift_Plugins_RedirectingPlugin implements Swift_Events_SendListener
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
{
$this->_restoreMessage($evt->getMessage());
$this->restoreMessage($evt->getMessage());
}
private function _restoreMessage(Swift_Mime_Message $message)
private function restoreMessage(Swift_Mime_SimpleMessage $message)
{
// restore original headers
$headers = $message->getHeaders();

View File

@@ -24,9 +24,9 @@ interface Swift_Plugins_Reporter
/**
* Notifies this ReportNotifier that $address failed or succeeded.
*
* @param Swift_Mime_Message $message
* @param string $address
* @param int $result from {@link RESULT_PASS, RESULT_FAIL}
* @param Swift_Mime_SimpleMessage $message
* @param string $address
* @param int $result from {@link RESULT_PASS, RESULT_FAIL}
*/
public function notify(Swift_Mime_Message $message, $address, $result);
public function notify(Swift_Mime_SimpleMessage $message, $address, $result);
}

View File

@@ -20,7 +20,7 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener
*
* @var Swift_Plugins_Reporter
*/
private $_reporter;
private $reporter;
/**
* Create a new ReporterPlugin using $reporter.
@@ -29,7 +29,7 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener
*/
public function __construct(Swift_Plugins_Reporter $reporter)
{
$this->_reporter = $reporter;
$this->reporter = $reporter;
}
/**
@@ -49,13 +49,13 @@ class Swift_Plugins_ReporterPlugin implements Swift_Events_SendListener
$message = $evt->getMessage();
$failures = array_flip($evt->getFailedRecipients());
foreach ((array) $message->getTo() as $address => $null) {
$this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS);
$this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS));
}
foreach ((array) $message->getCc() as $address => $null) {
$this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS);
$this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS));
}
foreach ((array) $message->getBcc() as $address => $null) {
$this->_reporter->notify($message, $address, array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS);
$this->reporter->notify($message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS));
}
}
}

View File

@@ -20,22 +20,22 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter
*
* @var array
*/
private $_failures = array();
private $failures = array();
private $_failures_cache = array();
private $failures_cache = array();
/**
* Notifies this ReportNotifier that $address failed or succeeded.
*
* @param Swift_Mime_Message $message
* @param string $address
* @param int $result from {@link RESULT_PASS, RESULT_FAIL}
* @param Swift_Mime_SimpleMessage $message
* @param string $address
* @param int $result from {@link RESULT_PASS, RESULT_FAIL}
*/
public function notify(Swift_Mime_Message $message, $address, $result)
public function notify(Swift_Mime_SimpleMessage $message, $address, $result)
{
if (self::RESULT_FAIL == $result && !isset($this->_failures_cache[$address])) {
$this->_failures[] = $address;
$this->_failures_cache[$address] = true;
if (self::RESULT_FAIL == $result && !isset($this->failures_cache[$address])) {
$this->failures[] = $address;
$this->failures_cache[$address] = true;
}
}
@@ -46,7 +46,7 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter
*/
public function getFailedRecipients()
{
return $this->_failures;
return $this->failures;
}
/**
@@ -54,6 +54,6 @@ class Swift_Plugins_Reporters_HitReporter implements Swift_Plugins_Reporter
*/
public function clear()
{
$this->_failures = $this->_failures_cache = array();
$this->failures = $this->failures_cache = array();
}
}

View File

@@ -18,11 +18,11 @@ class Swift_Plugins_Reporters_HtmlReporter implements Swift_Plugins_Reporter
/**
* Notifies this ReportNotifier that $address failed or succeeded.
*
* @param Swift_Mime_Message $message
* @param string $address
* @param int $result from {@see RESULT_PASS, RESULT_FAIL}
* @param Swift_Mime_SimpleMessage $message
* @param string $address
* @param int $result from {@see RESULT_PASS, RESULT_FAIL}
*/
public function notify(Swift_Mime_Message $message, $address, $result)
public function notify(Swift_Mime_SimpleMessage $message, $address, $result)
{
if (self::RESULT_PASS == $result) {
echo '<div style="color: #fff; background: #006600; padding: 2px; margin: 2px;">'.PHP_EOL;

View File

@@ -29,28 +29,28 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
*
* @var Swift_Plugins_Sleeper
*/
private $_sleeper;
private $sleeper;
/**
* The Timer instance which provides the timestamp.
*
* @var Swift_Plugins_Timer
*/
private $_timer;
private $timer;
/**
* The time at which the first email was sent.
*
* @var int
*/
private $_start;
private $start;
/**
* The rate at which messages should be sent.
*
* @var int
*/
private $_rate;
private $rate;
/**
* The mode for throttling.
@@ -59,14 +59,14 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
*
* @var int
*/
private $_mode;
private $mode;
/**
* An internal counter of the number of messages sent.
*
* @var int
*/
private $_messages = 0;
private $messages = 0;
/**
* Create a new ThrottlerPlugin.
@@ -78,10 +78,10 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
*/
public function __construct($rate, $mode = self::BYTES_PER_MINUTE, Swift_Plugins_Sleeper $sleeper = null, Swift_Plugins_Timer $timer = null)
{
$this->_rate = $rate;
$this->_mode = $mode;
$this->_sleeper = $sleeper;
$this->_timer = $timer;
$this->rate = $rate;
$this->mode = $mode;
$this->sleeper = $sleeper;
$this->timer = $timer;
}
/**
@@ -92,22 +92,22 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
public function beforeSendPerformed(Swift_Events_SendEvent $evt)
{
$time = $this->getTimestamp();
if (!isset($this->_start)) {
$this->_start = $time;
if (!isset($this->start)) {
$this->start = $time;
}
$duration = $time - $this->_start;
$duration = $time - $this->start;
switch ($this->_mode) {
case self::BYTES_PER_MINUTE :
$sleep = $this->_throttleBytesPerMinute($duration);
switch ($this->mode) {
case self::BYTES_PER_MINUTE:
$sleep = $this->throttleBytesPerMinute($duration);
break;
case self::MESSAGES_PER_SECOND :
$sleep = $this->_throttleMessagesPerSecond($duration);
case self::MESSAGES_PER_SECOND:
$sleep = $this->throttleMessagesPerSecond($duration);
break;
case self::MESSAGES_PER_MINUTE :
$sleep = $this->_throttleMessagesPerMinute($duration);
case self::MESSAGES_PER_MINUTE:
$sleep = $this->throttleMessagesPerMinute($duration);
break;
default :
default:
$sleep = 0;
break;
}
@@ -125,7 +125,7 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
public function sendPerformed(Swift_Events_SendEvent $evt)
{
parent::sendPerformed($evt);
++$this->_messages;
++$this->messages;
}
/**
@@ -135,8 +135,8 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
*/
public function sleep($seconds)
{
if (isset($this->_sleeper)) {
$this->_sleeper->sleep($seconds);
if (isset($this->sleeper)) {
$this->sleeper->sleep($seconds);
} else {
sleep($seconds);
}
@@ -149,8 +149,8 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
*/
public function getTimestamp()
{
if (isset($this->_timer)) {
return $this->_timer->getTimestamp();
if (isset($this->timer)) {
return $this->timer->getTimestamp();
}
return time();
@@ -163,9 +163,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
*
* @return int
*/
private function _throttleBytesPerMinute($timePassed)
private function throttleBytesPerMinute($timePassed)
{
$expectedDuration = $this->getBytesOut() / ($this->_rate / 60);
$expectedDuration = $this->getBytesOut() / ($this->rate / 60);
return (int) ceil($expectedDuration - $timePassed);
}
@@ -177,9 +177,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
*
* @return int
*/
private function _throttleMessagesPerSecond($timePassed)
private function throttleMessagesPerSecond($timePassed)
{
$expectedDuration = $this->_messages / ($this->_rate);
$expectedDuration = $this->messages / $this->rate;
return (int) ceil($expectedDuration - $timePassed);
}
@@ -191,9 +191,9 @@ class Swift_Plugins_ThrottlerPlugin extends Swift_Plugins_BandwidthMonitorPlugin
*
* @return int
*/
private function _throttleMessagesPerMinute($timePassed)
private function throttleMessagesPerMinute($timePassed)
{
$expectedDuration = $this->_messages / ($this->_rate / 60);
$expectedDuration = $this->messages / ($this->rate / 60);
return (int) ceil($expectedDuration - $timePassed);
}

View File

@@ -16,7 +16,7 @@
class Swift_Preferences
{
/** Singleton instance */
private static $_instance = null;
private static $instance = null;
/** Constructor not to be used */
private function __construct()
@@ -26,15 +26,15 @@ class Swift_Preferences
/**
* Gets the instance of Preferences.
*
* @return Swift_Preferences
* @return self
*/
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new self();
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$_instance;
return self::$instance;
}
/**
@@ -42,12 +42,11 @@ class Swift_Preferences
*
* @param string $charset
*
* @return Swift_Preferences
* @return $this
*/
public function setCharset($charset)
{
Swift_DependencyContainer::getInstance()
->register('properties.charset')->asValue($charset);
Swift_DependencyContainer::getInstance()->register('properties.charset')->asValue($charset);
return $this;
}
@@ -57,12 +56,11 @@ class Swift_Preferences
*
* @param string $dir
*
* @return Swift_Preferences
* @return $this
*/
public function setTempDir($dir)
{
Swift_DependencyContainer::getInstance()
->register('tempdir')->asValue($dir);
Swift_DependencyContainer::getInstance()->register('tempdir')->asValue($dir);
return $this;
}
@@ -72,12 +70,11 @@ class Swift_Preferences
*
* @param string $type
*
* @return Swift_Preferences
* @return $this
*/
public function setCacheType($type)
{
Swift_DependencyContainer::getInstance()
->register('cache')->asAliasOf(sprintf('cache.%s', $type));
Swift_DependencyContainer::getInstance()->register('cache')->asAliasOf(sprintf('cache.%s', $type));
return $this;
}
@@ -87,7 +84,7 @@ class Swift_Preferences
*
* @param bool $dotEscape
*
* @return Swift_Preferences
* @return $this
*/
public function setQPDotEscape($dotEscape)
{

View File

@@ -30,16 +30,4 @@ class Swift_SendmailTransport extends Swift_Transport_SendmailTransport
$this->setCommand($command);
}
/**
* Create a new SendmailTransport instance.
*
* @param string $command
*
* @return Swift_SendmailTransport
*/
public static function newInstance($command = '/usr/sbin/sendmail -bs')
{
return new self($command);
}
}

View File

@@ -1,23 +0,0 @@
<?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.
*/
/**
* Signed Message, message that can be signed using a signer.
*
* This class is only kept for compatibility
*
*
* @author Xavier De Cock <xdecock@gmail.com>
*
* @deprecated
*/
class Swift_SignedMessage extends Swift_Message
{
}

View File

@@ -20,7 +20,7 @@ interface Swift_Signers_BodySigner extends Swift_Signer
*
* @param Swift_Message $message
*
* @return Swift_Signers_BodySigner
* @return self
*/
public function signMessage(Swift_Message $message);

View File

@@ -11,7 +11,7 @@
/**
* DKIM Signer used to apply DKIM Signature to a message.
*
* @author Xavier De Cock <xdecock@gmail.com>
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
{
@@ -20,99 +20,103 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @var string
*/
protected $_privateKey;
protected $privateKey;
/**
* DomainName.
*
* @var string
*/
protected $_domainName;
protected $domainName;
/**
* Selector.
*
* @var string
*/
protected $_selector;
protected $selector;
private $passphrase = '';
/**
* Hash algorithm used.
*
* @see RFC6376 3.3: Signers MUST implement and SHOULD sign using rsa-sha256.
*
* @var string
*/
protected $_hashAlgorithm = 'rsa-sha1';
protected $hashAlgorithm = 'rsa-sha256';
/**
* Body canon method.
*
* @var string
*/
protected $_bodyCanon = 'simple';
protected $bodyCanon = 'simple';
/**
* Header canon method.
*
* @var string
*/
protected $_headerCanon = 'simple';
protected $headerCanon = 'simple';
/**
* Headers not being signed.
*
* @var array
*/
protected $_ignoredHeaders = array('return-path' => true);
protected $ignoredHeaders = array('return-path' => true);
/**
* Signer identity.
*
* @var string
*/
protected $_signerIdentity;
protected $signerIdentity;
/**
* BodyLength.
*
* @var int
*/
protected $_bodyLen = 0;
protected $bodyLen = 0;
/**
* Maximum signedLen.
*
* @var int
*/
protected $_maxLen = PHP_INT_MAX;
protected $maxLen = PHP_INT_MAX;
/**
* Embbed bodyLen in signature.
*
* @var bool
*/
protected $_showLen = false;
protected $showLen = false;
/**
* When the signature has been applied (true means time()), false means not embedded.
*
* @var mixed
*/
protected $_signatureTimestamp = true;
protected $signatureTimestamp = true;
/**
* When will the signature expires false means not embedded, if sigTimestamp is auto
* Expiration is relative, otherwhise it's absolute.
* Expiration is relative, otherwise it's absolute.
*
* @var int
*/
protected $_signatureExpiration = false;
protected $signatureExpiration = false;
/**
* Must we embed signed headers?
*
* @var bool
*/
protected $_debugHeaders = false;
protected $debugHeaders = false;
// work variables
/**
@@ -120,46 +124,46 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @var array
*/
protected $_signedHeaders = array();
protected $signedHeaders = array();
/**
* If debugHeaders is set store debugDatas here.
* If debugHeaders is set store debugData here.
*
* @var string
*/
private $_debugHeadersData = '';
private $debugHeadersData = '';
/**
* Stores the bodyHash.
*
* @var string
*/
private $_bodyHash = '';
private $bodyHash = '';
/**
* Stores the signature header.
*
* @var Swift_Mime_Headers_ParameterizedHeader
*/
protected $_dkimHeader;
protected $dkimHeader;
private $_bodyHashHandler;
private $bodyHashHandler;
private $_headerHash;
private $headerHash;
private $_headerCanonData = '';
private $headerCanonData = '';
private $_bodyCanonEmptyCounter = 0;
private $bodyCanonEmptyCounter = 0;
private $_bodyCanonIgnoreStart = 2;
private $bodyCanonIgnoreStart = 2;
private $_bodyCanonSpace = false;
private $bodyCanonSpace = false;
private $_bodyCanonLastChar = null;
private $bodyCanonLastChar = null;
private $_bodyCanonLine = '';
private $bodyCanonLine = '';
private $_bound = array();
private $bound = array();
/**
* Constructor.
@@ -167,27 +171,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
* @param string $privateKey
* @param string $domainName
* @param string $selector
* @param string $passphrase
*/
public function __construct($privateKey, $domainName, $selector)
public function __construct($privateKey, $domainName, $selector, $passphrase = '')
{
$this->_privateKey = $privateKey;
$this->_domainName = $domainName;
$this->_signerIdentity = '@'.$domainName;
$this->_selector = $selector;
}
/**
* Instanciate DKIMSigner.
*
* @param string $privateKey
* @param string $domainName
* @param string $selector
*
* @return Swift_Signers_DKIMSigner
*/
public static function newInstance($privateKey, $domainName, $selector)
{
return new static($privateKey, $domainName, $selector);
$this->privateKey = $privateKey;
$this->domainName = $domainName;
$this->signerIdentity = '@'.$domainName;
$this->selector = $selector;
$this->passphrase = $passphrase;
}
/**
@@ -197,14 +189,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*/
public function reset()
{
$this->_headerHash = null;
$this->_signedHeaders = array();
$this->_bodyHash = null;
$this->_bodyHashHandler = null;
$this->_bodyCanonIgnoreStart = 2;
$this->_bodyCanonEmptyCounter = 0;
$this->_bodyCanonLastChar = null;
$this->_bodyCanonSpace = false;
$this->headerHash = null;
$this->signedHeaders = array();
$this->bodyHash = null;
$this->bodyHashHandler = null;
$this->bodyCanonIgnoreStart = 2;
$this->bodyCanonEmptyCounter = 0;
$this->bodyCanonLastChar = null;
$this->bodyCanonSpace = false;
}
/**
@@ -219,14 +211,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @param string $bytes
*
* @throws Swift_IoException
*
* @return int
*
* @throws Swift_IoException
*/
// TODO fix return
public function write($bytes)
{
$this->_canonicalizeBody($bytes);
foreach ($this->_bound as $is) {
$this->canonicalizeBody($bytes);
foreach ($this->bound as $is) {
$is->write($bytes);
}
}
@@ -234,8 +227,6 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
/**
* For any bytes that are currently buffered inside the stream, force them
* off the buffer.
*
* @throws Swift_IoException
*/
public function commit()
{
@@ -253,7 +244,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
public function bind(Swift_InputByteStream $is)
{
// Don't have to mirror anything
$this->_bound[] = $is;
$this->bound[] = $is;
return;
}
@@ -269,15 +260,13 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
public function unbind(Swift_InputByteStream $is)
{
// Don't have to mirror anything
foreach ($this->_bound as $k => $stream) {
foreach ($this->bound as $k => $stream) {
if ($stream === $is) {
unset($this->_bound[$k]);
unset($this->bound[$k]);
return;
}
}
return;
}
/**
@@ -292,19 +281,28 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
}
/**
* Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256.
* Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1.
*
* @param string $hash
* @param string $hash 'rsa-sha1' or 'rsa-sha256'
*
* @return Swift_Signers_DKIMSigner
* @throws Swift_SwiftException
*
* @return $this
*/
public function setHashAlgorithm($hash)
{
// Unable to sign with rsa-sha256
if ($hash == 'rsa-sha1') {
$this->_hashAlgorithm = 'rsa-sha1';
} else {
$this->_hashAlgorithm = 'rsa-sha256';
switch ($hash) {
case 'rsa-sha1':
$this->hashAlgorithm = 'rsa-sha1';
break;
case 'rsa-sha256':
$this->hashAlgorithm = 'rsa-sha256';
if (!defined('OPENSSL_ALGO_SHA256')) {
throw new Swift_SwiftException('Unable to set sha256 as it is not supported by OpenSSL.');
}
break;
default:
throw new Swift_SwiftException('Unable to set the hash algorithm, must be one of rsa-sha1 or rsa-sha256 (%s given).', $hash);
}
return $this;
@@ -315,14 +313,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @param string $canon
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setBodyCanon($canon)
{
if ($canon == 'relaxed') {
$this->_bodyCanon = 'relaxed';
$this->bodyCanon = 'relaxed';
} else {
$this->_bodyCanon = 'simple';
$this->bodyCanon = 'simple';
}
return $this;
@@ -333,14 +331,14 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @param string $canon
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setHeaderCanon($canon)
{
if ($canon == 'relaxed') {
$this->_headerCanon = 'relaxed';
$this->headerCanon = 'relaxed';
} else {
$this->_headerCanon = 'simple';
$this->headerCanon = 'simple';
}
return $this;
@@ -351,11 +349,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @param string $identity
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setSignerIdentity($identity)
{
$this->_signerIdentity = $identity;
$this->signerIdentity = $identity;
return $this;
}
@@ -365,19 +363,19 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @param mixed $len (bool or int)
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setBodySignedLen($len)
{
if ($len === true) {
$this->_showLen = true;
$this->_maxLen = PHP_INT_MAX;
$this->showLen = true;
$this->maxLen = PHP_INT_MAX;
} elseif ($len === false) {
$this->showLen = false;
$this->_maxLen = PHP_INT_MAX;
$this->maxLen = PHP_INT_MAX;
} else {
$this->_showLen = true;
$this->_maxLen = (int) $len;
$this->showLen = true;
$this->maxLen = (int) $len;
}
return $this;
@@ -388,11 +386,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @param int $time A timestamp
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setSignatureTimestamp($time)
{
$this->_signatureTimestamp = $time;
$this->signatureTimestamp = $time;
return $this;
}
@@ -402,11 +400,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @param int $time A timestamp
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setSignatureExpiration($time)
{
$this->_signatureExpiration = $time;
$this->signatureExpiration = $time;
return $this;
}
@@ -420,7 +418,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*/
public function setDebugHeaders($debug)
{
$this->_debugHeaders = (bool) $debug;
$this->debugHeaders = (bool) $debug;
return $this;
}
@@ -431,15 +429,15 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
public function startBody()
{
// Init
switch ($this->_hashAlgorithm) {
case 'rsa-sha256' :
$this->_bodyHashHandler = hash_init('sha256');
switch ($this->hashAlgorithm) {
case 'rsa-sha256':
$this->bodyHashHandler = hash_init('sha256');
break;
case 'rsa-sha1' :
$this->_bodyHashHandler = hash_init('sha1');
case 'rsa-sha1':
$this->bodyHashHandler = hash_init('sha1');
break;
}
$this->_bodyCanonLine = '';
$this->bodyCanonLine = '';
}
/**
@@ -447,7 +445,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*/
public function endBody()
{
$this->_endOfBody();
$this->endOfBody();
}
/**
@@ -457,7 +455,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*/
public function getAlteredHeaders()
{
if ($this->_debugHeaders) {
if ($this->debugHeaders) {
return array('DKIM-Signature', 'X-DebugHash');
} else {
return array('DKIM-Signature');
@@ -473,7 +471,7 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*/
public function ignoreHeader($header_name)
{
$this->_ignoredHeaders[strtolower($header_name)] = true;
$this->ignoredHeaders[strtolower($header_name)] = true;
return $this;
}
@@ -481,24 +479,24 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
/**
* Set the headers to sign.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_SimpleHeaderSet $headers
*
* @return Swift_Signers_DKIMSigner
*/
public function setHeaders(Swift_Mime_HeaderSet $headers)
public function setHeaders(Swift_Mime_SimpleHeaderSet $headers)
{
$this->_headerCanonData = '';
$this->headerCanonData = '';
// Loop through Headers
$listHeaders = $headers->listAll();
foreach ($listHeaders as $hName) {
// Check if we need to ignore Header
if (!isset($this->_ignoredHeaders[strtolower($hName)])) {
if (!isset($this->ignoredHeaders[strtolower($hName)])) {
if ($headers->has($hName)) {
$tmp = $headers->getAll($hName);
foreach ($tmp as $header) {
if ($header->getFieldBody() != '') {
$this->_addHeader($header->toString());
$this->_signedHeaders[] = $header->getFieldName();
$this->addHeader($header->toString());
$this->signedHeaders[] = $header->getFieldName();
}
}
}
@@ -511,37 +509,37 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
/**
* Add the signature to the given Headers.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_SimpleHeaderSet $headers
*
* @return Swift_Signers_DKIMSigner
*/
public function addSignature(Swift_Mime_HeaderSet $headers)
public function addSignature(Swift_Mime_SimpleHeaderSet $headers)
{
// Prepare the DKIM-Signature
$params = array('v' => '1', 'a' => $this->_hashAlgorithm, 'bh' => base64_encode($this->_bodyHash), 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'i' => $this->_signerIdentity, 's' => $this->_selector);
if ($this->_bodyCanon != 'simple') {
$params['c'] = $this->_headerCanon.'/'.$this->_bodyCanon;
} elseif ($this->_headerCanon != 'simple') {
$params['c'] = $this->_headerCanon;
$params = array('v' => '1', 'a' => $this->hashAlgorithm, 'bh' => base64_encode($this->bodyHash), 'd' => $this->domainName, 'h' => implode(': ', $this->signedHeaders), 'i' => $this->signerIdentity, 's' => $this->selector);
if ($this->bodyCanon != 'simple') {
$params['c'] = $this->headerCanon.'/'.$this->bodyCanon;
} elseif ($this->headerCanon != 'simple') {
$params['c'] = $this->headerCanon;
}
if ($this->_showLen) {
$params['l'] = $this->_bodyLen;
if ($this->showLen) {
$params['l'] = $this->bodyLen;
}
if ($this->_signatureTimestamp === true) {
if ($this->signatureTimestamp === true) {
$params['t'] = time();
if ($this->_signatureExpiration !== false) {
$params['x'] = $params['t'] + $this->_signatureExpiration;
if ($this->signatureExpiration !== false) {
$params['x'] = $params['t'] + $this->signatureExpiration;
}
} else {
if ($this->_signatureTimestamp !== false) {
$params['t'] = $this->_signatureTimestamp;
if ($this->signatureTimestamp !== false) {
$params['t'] = $this->signatureTimestamp;
}
if ($this->_signatureExpiration !== false) {
$params['x'] = $this->_signatureExpiration;
if ($this->signatureExpiration !== false) {
$params['x'] = $this->signatureExpiration;
}
}
if ($this->_debugHeaders) {
$params['z'] = implode('|', $this->_debugHeadersData);
if ($this->debugHeaders) {
$params['z'] = implode('|', $this->debugHeadersData);
}
$string = '';
foreach ($params as $k => $v) {
@@ -551,67 +549,57 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
$headers->addTextHeader('DKIM-Signature', $string);
// Add the last DKIM-Signature
$tmp = $headers->getAll('DKIM-Signature');
$this->_dkimHeader = end($tmp);
$this->_addHeader(trim($this->_dkimHeader->toString())."\r\n b=", true);
$this->_endOfHeaders();
if ($this->_debugHeaders) {
$headers->addTextHeader('X-DebugHash', base64_encode($this->_headerHash));
$this->dkimHeader = end($tmp);
$this->addHeader(trim($this->dkimHeader->toString())."\r\n b=", true);
if ($this->debugHeaders) {
$headers->addTextHeader('X-DebugHash', base64_encode($this->headerHash));
}
$this->_dkimHeader->setValue($string.' b='.trim(chunk_split(base64_encode($this->_getEncryptedHash()), 73, ' ')));
$this->dkimHeader->setValue($string.' b='.trim(chunk_split(base64_encode($this->getEncryptedHash()), 73, ' ')));
return $this;
}
/* Private helpers */
protected function _addHeader($header, $is_sig = false)
protected function addHeader($header, $is_sig = false)
{
switch ($this->_headerCanon) {
case 'relaxed' :
switch ($this->headerCanon) {
case 'relaxed':
// Prepare Header and cascade
$exploded = explode(':', $header, 2);
$name = strtolower(trim($exploded[0]));
$value = str_replace("\r\n", '', $exploded[1]);
$value = preg_replace("/[ \t][ \t]+/", ' ', $value);
$header = $name.':'.trim($value).($is_sig ? '' : "\r\n");
case 'simple' :
case 'simple':
// Nothing to do
}
$this->_addToHeaderHash($header);
$this->addToHeaderHash($header);
}
/**
* @deprecated This method is currently useless in this class but it must be
* kept for BC reasons due to its "protected" scope. This method
* might be overriden by custom client code.
*/
protected function _endOfHeaders()
{
}
protected function _canonicalizeBody($string)
protected function canonicalizeBody($string)
{
$len = strlen($string);
$canon = '';
$method = ($this->_bodyCanon == 'relaxed');
$method = ($this->bodyCanon == 'relaxed');
for ($i = 0; $i < $len; ++$i) {
if ($this->_bodyCanonIgnoreStart > 0) {
--$this->_bodyCanonIgnoreStart;
if ($this->bodyCanonIgnoreStart > 0) {
--$this->bodyCanonIgnoreStart;
continue;
}
switch ($string[$i]) {
case "\r" :
$this->_bodyCanonLastChar = "\r";
case "\r":
$this->bodyCanonLastChar = "\r";
break;
case "\n" :
if ($this->_bodyCanonLastChar == "\r") {
case "\n":
if ($this->bodyCanonLastChar == "\r") {
if ($method) {
$this->_bodyCanonSpace = false;
$this->bodyCanonSpace = false;
}
if ($this->_bodyCanonLine == '') {
++$this->_bodyCanonEmptyCounter;
if ($this->bodyCanonLine == '') {
++$this->bodyCanonEmptyCounter;
} else {
$this->_bodyCanonLine = '';
$this->bodyCanonLine = '';
$canon .= "\r\n";
}
} else {
@@ -619,55 +607,55 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
// todo handle it but should never happen
}
break;
case ' ' :
case "\t" :
case ' ':
case "\t":
if ($method) {
$this->_bodyCanonSpace = true;
$this->bodyCanonSpace = true;
break;
}
default :
if ($this->_bodyCanonEmptyCounter > 0) {
$canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter);
$this->_bodyCanonEmptyCounter = 0;
default:
if ($this->bodyCanonEmptyCounter > 0) {
$canon .= str_repeat("\r\n", $this->bodyCanonEmptyCounter);
$this->bodyCanonEmptyCounter = 0;
}
if ($this->_bodyCanonSpace) {
$this->_bodyCanonLine .= ' ';
if ($this->bodyCanonSpace) {
$this->bodyCanonLine .= ' ';
$canon .= ' ';
$this->_bodyCanonSpace = false;
$this->bodyCanonSpace = false;
}
$this->_bodyCanonLine .= $string[$i];
$this->bodyCanonLine .= $string[$i];
$canon .= $string[$i];
}
}
$this->_addToBodyHash($canon);
$this->addToBodyHash($canon);
}
protected function _endOfBody()
protected function endOfBody()
{
// Add trailing Line return if last line is non empty
if (strlen($this->_bodyCanonLine) > 0) {
$this->_addToBodyHash("\r\n");
if (strlen($this->bodyCanonLine) > 0) {
$this->addToBodyHash("\r\n");
}
$this->_bodyHash = hash_final($this->_bodyHashHandler, true);
$this->bodyHash = hash_final($this->bodyHashHandler, true);
}
private function _addToBodyHash($string)
private function addToBodyHash($string)
{
$len = strlen($string);
if ($len > ($new_len = ($this->_maxLen - $this->_bodyLen))) {
if ($len > ($new_len = ($this->maxLen - $this->bodyLen))) {
$string = substr($string, 0, $new_len);
$len = $new_len;
}
hash_update($this->_bodyHashHandler, $string);
$this->_bodyLen += $len;
hash_update($this->bodyHashHandler, $string);
$this->bodyLen += $len;
}
private function _addToHeaderHash($header)
private function addToHeaderHash($header)
{
if ($this->_debugHeaders) {
$this->_debugHeadersData[] = trim($header);
if ($this->debugHeaders) {
$this->debugHeadersData[] = trim($header);
}
$this->_headerCanonData .= $header;
$this->headerCanonData .= $header;
}
/**
@@ -675,10 +663,10 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
*
* @return string
*/
private function _getEncryptedHash()
private function getEncryptedHash()
{
$signature = '';
switch ($this->_hashAlgorithm) {
switch ($this->hashAlgorithm) {
case 'rsa-sha1':
$algorithm = OPENSSL_ALGO_SHA1;
break;
@@ -686,11 +674,11 @@ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
$algorithm = OPENSSL_ALGO_SHA256;
break;
}
$pkeyId = openssl_get_privatekey($this->_privateKey);
$pkeyId = openssl_get_privatekey($this->privateKey, $this->passphrase);
if (!$pkeyId) {
throw new Swift_SwiftException('Unable to load DKIM Private Key ['.openssl_error_string().']');
}
if (openssl_sign($this->_headerCanonData, $signature, $pkeyId, $algorithm)) {
if (openssl_sign($this->headerCanonData, $signature, $pkeyId, $algorithm)) {
return $signature;
}
throw new Swift_SwiftException('Unable to sign DKIM Hash ['.openssl_error_string().']');

View File

@@ -11,7 +11,7 @@
/**
* DomainKey Signer used to apply DomainKeys Signature to a message.
*
* @author Xavier De Cock <xdecock@gmail.com>
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
{
@@ -20,56 +20,56 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @var string
*/
protected $_privateKey;
protected $privateKey;
/**
* DomainName.
*
* @var string
*/
protected $_domainName;
protected $domainName;
/**
* Selector.
*
* @var string
*/
protected $_selector;
protected $selector;
/**
* Hash algorithm used.
*
* @var string
*/
protected $_hashAlgorithm = 'rsa-sha1';
protected $hashAlgorithm = 'rsa-sha1';
/**
* Canonisation method.
*
* @var string
*/
protected $_canon = 'simple';
protected $canon = 'simple';
/**
* Headers not being signed.
*
* @var array
*/
protected $_ignoredHeaders = array();
protected $ignoredHeaders = array();
/**
* Signer identity.
*
* @var string
*/
protected $_signerIdentity;
protected $signerIdentity;
/**
* Must we embed signed headers?
*
* @var bool
*/
protected $_debugHeaders = false;
protected $debugHeaders = false;
// work variables
/**
@@ -77,37 +77,37 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @var array
*/
private $_signedHeaders = array();
private $signedHeaders = array();
/**
* Stores the signature header.
*
* @var Swift_Mime_Headers_ParameterizedHeader
*/
protected $_domainKeyHeader;
protected $domainKeyHeader;
/**
* Hash Handler.
*
* @var resource|null
*/
private $_hashHandler;
private $hashHandler;
private $_hash;
private $hash;
private $_canonData = '';
private $canonData = '';
private $_bodyCanonEmptyCounter = 0;
private $bodyCanonEmptyCounter = 0;
private $_bodyCanonIgnoreStart = 2;
private $bodyCanonIgnoreStart = 2;
private $_bodyCanonSpace = false;
private $bodyCanonSpace = false;
private $_bodyCanonLastChar = null;
private $bodyCanonLastChar = null;
private $_bodyCanonLine = '';
private $bodyCanonLine = '';
private $_bound = array();
private $bound = array();
/**
* Constructor.
@@ -118,39 +118,25 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*/
public function __construct($privateKey, $domainName, $selector)
{
$this->_privateKey = $privateKey;
$this->_domainName = $domainName;
$this->_signerIdentity = '@'.$domainName;
$this->_selector = $selector;
}
/**
* Instanciate DomainKeySigner.
*
* @param string $privateKey
* @param string $domainName
* @param string $selector
*
* @return Swift_Signers_DomainKeySigner
*/
public static function newInstance($privateKey, $domainName, $selector)
{
return new static($privateKey, $domainName, $selector);
$this->privateKey = $privateKey;
$this->domainName = $domainName;
$this->signerIdentity = '@'.$domainName;
$this->selector = $selector;
}
/**
* Resets internal states.
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function reset()
{
$this->_hash = null;
$this->_hashHandler = null;
$this->_bodyCanonIgnoreStart = 2;
$this->_bodyCanonEmptyCounter = 0;
$this->_bodyCanonLastChar = null;
$this->_bodyCanonSpace = false;
$this->hash = null;
$this->hashHandler = null;
$this->bodyCanonIgnoreStart = 2;
$this->bodyCanonEmptyCounter = 0;
$this->bodyCanonLastChar = null;
$this->bodyCanonSpace = false;
return $this;
}
@@ -167,15 +153,16 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @param string $bytes
*
* @return int
*
* @throws Swift_IoException
*
* @return int
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function write($bytes)
{
$this->_canonicalizeBody($bytes);
foreach ($this->_bound as $is) {
$this->canonicalizeBody($bytes);
foreach ($this->bound as $is) {
$is->write($bytes);
}
@@ -188,7 +175,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @throws Swift_IoException
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function commit()
{
@@ -203,12 +190,12 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @param Swift_InputByteStream $is
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function bind(Swift_InputByteStream $is)
{
// Don't have to mirror anything
$this->_bound[] = $is;
$this->bound[] = $is;
return $this;
}
@@ -221,16 +208,16 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @param Swift_InputByteStream $is
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function unbind(Swift_InputByteStream $is)
{
// Don't have to mirror anything
foreach ($this->_bound as $k => $stream) {
foreach ($this->bound as $k => $stream) {
if ($stream === $is) {
unset($this->_bound[$k]);
unset($this->bound[$k]);
return;
break;
}
}
@@ -243,7 +230,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @throws Swift_IoException
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function flushBuffers()
{
@@ -257,11 +244,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @param string $hash
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function setHashAlgorithm($hash)
{
$this->_hashAlgorithm = 'rsa-sha1';
$this->hashAlgorithm = 'rsa-sha1';
return $this;
}
@@ -271,14 +258,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @param string $canon simple | nofws defaults to simple
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function setCanon($canon)
{
if ($canon == 'nofws') {
$this->_canon = 'nofws';
$this->canon = 'nofws';
} else {
$this->_canon = 'simple';
$this->canon = 'simple';
}
return $this;
@@ -289,11 +276,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @param string $identity
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function setSignerIdentity($identity)
{
$this->_signerIdentity = $identity;
$this->signerIdentity = $identity;
return $this;
}
@@ -303,11 +290,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @param bool $debug
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function setDebugHeaders($debug)
{
$this->_debugHeaders = (bool) $debug;
$this->debugHeaders = (bool) $debug;
return $this;
}
@@ -324,7 +311,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*/
public function endBody()
{
$this->_endOfBody();
$this->endOfBody();
}
/**
@@ -334,7 +321,7 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*/
public function getAlteredHeaders()
{
if ($this->_debugHeaders) {
if ($this->debugHeaders) {
return array('DomainKey-Signature', 'X-DebugHash');
}
@@ -346,11 +333,11 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @param string $header_name
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function ignoreHeader($header_name)
{
$this->_ignoredHeaders[strtolower($header_name)] = true;
$this->ignoredHeaders[strtolower($header_name)] = true;
return $this;
}
@@ -358,31 +345,31 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
/**
* Set the headers to sign.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_SimpleHeaderSet $headers
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function setHeaders(Swift_Mime_HeaderSet $headers)
public function setHeaders(Swift_Mime_SimpleHeaderSet $headers)
{
$this->_startHash();
$this->_canonData = '';
$this->startHash();
$this->canonData = '';
// Loop through Headers
$listHeaders = $headers->listAll();
foreach ($listHeaders as $hName) {
// Check if we need to ignore Header
if (!isset($this->_ignoredHeaders[strtolower($hName)])) {
if (!isset($this->ignoredHeaders[strtolower($hName)])) {
if ($headers->has($hName)) {
$tmp = $headers->getAll($hName);
foreach ($tmp as $header) {
if ($header->getFieldBody() != '') {
$this->_addHeader($header->toString());
$this->_signedHeaders[] = $header->getFieldName();
$this->addHeader($header->toString());
$this->signedHeaders[] = $header->getFieldName();
}
}
}
}
}
$this->_endOfHeaders();
$this->endOfHeaders();
return $this;
}
@@ -390,14 +377,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
/**
* Add the signature to the given Headers.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_SimpleHeaderSet $headers
*
* @return Swift_Signers_DomainKeySigner
* @return $this
*/
public function addSignature(Swift_Mime_HeaderSet $headers)
public function addSignature(Swift_Mime_SimpleHeaderSet $headers)
{
// Prepare the DomainKey-Signature Header
$params = array('a' => $this->_hashAlgorithm, 'b' => chunk_split(base64_encode($this->_getEncryptedHash()), 73, ' '), 'c' => $this->_canon, 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'q' => 'dns', 's' => $this->_selector);
$params = array('a' => $this->hashAlgorithm, 'b' => chunk_split(base64_encode($this->getEncryptedHash()), 73, ' '), 'c' => $this->canon, 'd' => $this->domainName, 'h' => implode(': ', $this->signedHeaders), 'q' => 'dns', 's' => $this->selector);
$string = '';
foreach ($params as $k => $v) {
$string .= $k.'='.$v.'; ';
@@ -410,50 +397,50 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
/* Private helpers */
protected function _addHeader($header)
protected function addHeader($header)
{
switch ($this->_canon) {
case 'nofws' :
switch ($this->canon) {
case 'nofws':
// Prepare Header and cascade
$exploded = explode(':', $header, 2);
$name = strtolower(trim($exploded[0]));
$value = str_replace("\r\n", '', $exploded[1]);
$value = preg_replace("/[ \t][ \t]+/", ' ', $value);
$header = $name.':'.trim($value)."\r\n";
case 'simple' :
case 'simple':
// Nothing to do
}
$this->_addToHash($header);
$this->addToHash($header);
}
protected function _endOfHeaders()
protected function endOfHeaders()
{
$this->_bodyCanonEmptyCounter = 1;
$this->bodyCanonEmptyCounter = 1;
}
protected function _canonicalizeBody($string)
protected function canonicalizeBody($string)
{
$len = strlen($string);
$canon = '';
$nofws = ($this->_canon == 'nofws');
$nofws = ($this->canon == 'nofws');
for ($i = 0; $i < $len; ++$i) {
if ($this->_bodyCanonIgnoreStart > 0) {
--$this->_bodyCanonIgnoreStart;
if ($this->bodyCanonIgnoreStart > 0) {
--$this->bodyCanonIgnoreStart;
continue;
}
switch ($string[$i]) {
case "\r" :
$this->_bodyCanonLastChar = "\r";
case "\r":
$this->bodyCanonLastChar = "\r";
break;
case "\n" :
if ($this->_bodyCanonLastChar == "\r") {
case "\n":
if ($this->bodyCanonLastChar == "\r") {
if ($nofws) {
$this->_bodyCanonSpace = false;
$this->bodyCanonSpace = false;
}
if ($this->_bodyCanonLine == '') {
++$this->_bodyCanonEmptyCounter;
if ($this->bodyCanonLine == '') {
++$this->bodyCanonEmptyCounter;
} else {
$this->_bodyCanonLine = '';
$this->bodyCanonLine = '';
$canon .= "\r\n";
}
} else {
@@ -461,48 +448,48 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
throw new Swift_SwiftException('Invalid new line sequence in mail found \n without preceding \r');
}
break;
case ' ' :
case "\t" :
case ' ':
case "\t":
case "\x09": //HTAB
if ($nofws) {
$this->_bodyCanonSpace = true;
$this->bodyCanonSpace = true;
break;
}
default :
if ($this->_bodyCanonEmptyCounter > 0) {
$canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter);
$this->_bodyCanonEmptyCounter = 0;
default:
if ($this->bodyCanonEmptyCounter > 0) {
$canon .= str_repeat("\r\n", $this->bodyCanonEmptyCounter);
$this->bodyCanonEmptyCounter = 0;
}
$this->_bodyCanonLine .= $string[$i];
$this->bodyCanonLine .= $string[$i];
$canon .= $string[$i];
}
}
$this->_addToHash($canon);
$this->addToHash($canon);
}
protected function _endOfBody()
protected function endOfBody()
{
if (strlen($this->_bodyCanonLine) > 0) {
$this->_addToHash("\r\n");
if (strlen($this->bodyCanonLine) > 0) {
$this->addToHash("\r\n");
}
$this->_hash = hash_final($this->_hashHandler, true);
$this->hash = hash_final($this->hashHandler, true);
}
private function _addToHash($string)
private function addToHash($string)
{
$this->_canonData .= $string;
hash_update($this->_hashHandler, $string);
$this->canonData .= $string;
hash_update($this->hashHandler, $string);
}
private function _startHash()
private function startHash()
{
// Init
switch ($this->_hashAlgorithm) {
case 'rsa-sha1' :
$this->_hashHandler = hash_init('sha1');
switch ($this->hashAlgorithm) {
case 'rsa-sha1':
$this->hashHandler = hash_init('sha1');
break;
}
$this->_canonLine = '';
$this->bodyCanonLine = '';
}
/**
@@ -510,14 +497,14 @@ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner
*
* @return string
*/
private function _getEncryptedHash()
private function getEncryptedHash()
{
$signature = '';
$pkeyId = openssl_get_privatekey($this->_privateKey);
$pkeyId = openssl_get_privatekey($this->privateKey);
if (!$pkeyId) {
throw new Swift_SwiftException('Unable to load DomainKey Private Key ['.openssl_error_string().']');
}
if (openssl_sign($this->_canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) {
if (openssl_sign($this->canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) {
return $signature;
}
throw new Swift_SwiftException('Unable to sign DomainKey Hash ['.openssl_error_string().']');

View File

@@ -20,21 +20,21 @@ interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream
*
* @param string $header_name
*
* @return Swift_Signers_HeaderSigner
* @return self
*/
public function ignoreHeader($header_name);
/**
* Prepare the Signer to get a new Body.
*
* @return Swift_Signers_HeaderSigner
* @return self
*/
public function startBody();
/**
* Give the signal that the body has finished streaming.
*
* @return Swift_Signers_HeaderSigner
* @return self
*/
public function endBody();
@@ -43,18 +43,18 @@ interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream
*
* @param Swift_Mime_SimpleHeaderSet $headers
*
* @return Swift_Signers_HeaderSigner
* @return self
*/
public function setHeaders(Swift_Mime_HeaderSet $headers);
public function setHeaders(Swift_Mime_SimpleHeaderSet $headers);
/**
* Add the header(s) to the headerSet.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_SimpleHeaderSet $headers
*
* @return Swift_Signers_HeaderSigner
* @return self
*/
public function addSignature(Swift_Mime_HeaderSet $headers);
public function addSignature(Swift_Mime_SimpleHeaderSet $headers);
/**
* Return the list of header a signer might tamper.

View File

@@ -12,13 +12,13 @@
* DKIM Signer used to apply DKIM Signature to a message
* Takes advantage of pecl extension.
*
* @author Xavier De Cock <xdecock@gmail.com>
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner
{
private $_peclLoaded = false;
private $peclLoaded = false;
private $_dkimHandler = null;
private $dkimHandler = null;
private $dropFirstLF = true;
@@ -33,22 +33,17 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner
throw new Swift_SwiftException('php-opendkim extension not found');
}
$this->_peclLoaded = true;
$this->peclLoaded = true;
parent::__construct($privateKey, $domainName, $selector);
}
public static function newInstance($privateKey, $domainName, $selector)
{
return new static($privateKey, $domainName, $selector);
}
public function addSignature(Swift_Mime_HeaderSet $headers)
public function addSignature(Swift_Mime_SimpleHeaderSet $headers)
{
$header = new Swift_Mime_Headers_OpenDKIMHeader('DKIM-Signature');
$headerVal = $this->_dkimHandler->getSignatureHeader();
$headerVal = $this->dkimHandler->getSignatureHeader();
if (!$headerVal) {
throw new Swift_SwiftException('OpenDKIM Error: '.$this->_dkimHandler->getError());
throw new Swift_SwiftException('OpenDKIM Error: '.$this->dkimHandler->getError());
}
$header->setValue($headerVal);
$headers->set($header);
@@ -56,40 +51,40 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner
return $this;
}
public function setHeaders(Swift_Mime_HeaderSet $headers)
public function setHeaders(Swift_Mime_SimpleHeaderSet $headers)
{
$bodyLen = $this->_bodyLen;
$bodyLen = $this->bodyLen;
if (is_bool($bodyLen)) {
$bodyLen = -1;
}
$hash = $this->_hashAlgorithm == 'rsa-sha1' ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256;
$bodyCanon = $this->_bodyCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED;
$headerCanon = $this->_headerCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED;
$this->_dkimHandler = new OpenDKIMSign($this->_privateKey, $this->_selector, $this->_domainName, $headerCanon, $bodyCanon, $hash, $bodyLen);
$hash = $this->hashAlgorithm == 'rsa-sha1' ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256;
$bodyCanon = $this->bodyCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED;
$headerCanon = $this->headerCanon == 'simple' ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED;
$this->dkimHandler = new OpenDKIMSign($this->privateKey, $this->selector, $this->domainName, $headerCanon, $bodyCanon, $hash, $bodyLen);
// Hardcode signature Margin for now
$this->_dkimHandler->setMargin(78);
$this->dkimHandler->setMargin(78);
if (!is_numeric($this->_signatureTimestamp)) {
if (!is_numeric($this->signatureTimestamp)) {
OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, time());
} else {
if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->_signatureTimestamp)) {
if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->signatureTimestamp)) {
throw new Swift_SwiftException('Unable to force signature timestamp ['.openssl_error_string().']');
}
}
if (isset($this->_signerIdentity)) {
$this->_dkimHandler->setSigner($this->_signerIdentity);
if (isset($this->signerIdentity)) {
$this->dkimHandler->setSigner($this->signerIdentity);
}
$listHeaders = $headers->listAll();
foreach ($listHeaders as $hName) {
// Check if we need to ignore Header
if (!isset($this->_ignoredHeaders[strtolower($hName)])) {
if (!isset($this->ignoredHeaders[strtolower($hName)])) {
$tmp = $headers->getAll($hName);
if ($headers->has($hName)) {
foreach ($tmp as $header) {
if ($header->getFieldBody() != '') {
$htosign = $header->toString();
$this->_dkimHandler->header($htosign);
$this->_signedHeaders[] = $header->getFieldName();
$this->dkimHandler->header($htosign);
$this->signedHeaders[] = $header->getFieldName();
}
}
}
@@ -101,28 +96,28 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner
public function startBody()
{
if (!$this->_peclLoaded) {
if (!$this->peclLoaded) {
return parent::startBody();
}
$this->dropFirstLF = true;
$this->_dkimHandler->eoh();
$this->dkimHandler->eoh();
return $this;
}
public function endBody()
{
if (!$this->_peclLoaded) {
if (!$this->peclLoaded) {
return parent::endBody();
}
$this->_dkimHandler->eom();
$this->dkimHandler->eom();
return $this;
}
public function reset()
{
$this->_dkimHandler = null;
$this->dkimHandler = null;
parent::reset();
return $this;
@@ -133,11 +128,11 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner
*
* @param int $time
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setSignatureTimestamp($time)
{
$this->_signatureTimestamp = $time;
$this->signatureTimestamp = $time;
return $this;
}
@@ -147,11 +142,11 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner
*
* @param int $time
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setSignatureExpiration($time)
{
$this->_signatureExpiration = $time;
$this->signatureExpiration = $time;
return $this;
}
@@ -161,21 +156,21 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner
*
* @param bool $debug
*
* @return Swift_Signers_DKIMSigner
* @return $this
*/
public function setDebugHeaders($debug)
{
$this->_debugHeaders = (bool) $debug;
$this->debugHeaders = (bool) $debug;
return $this;
}
// Protected
protected function _canonicalizeBody($string)
protected function canonicalizeBody($string)
{
if (!$this->_peclLoaded) {
return parent::_canonicalizeBody($string);
if (!$this->peclLoaded) {
return parent::canonicalizeBody($string);
}
if (false && $this->dropFirstLF === true) {
if ($string[0] == "\r" && $string[1] == "\n") {
@@ -184,7 +179,7 @@ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner
}
$this->dropFirstLF = false;
if (strlen($string)) {
$this->_dkimHandler->body($string);
$this->dkimHandler->body($string);
}
}
}

View File

@@ -34,7 +34,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
protected $replacementFactory;
/**
* @var Swift_Mime_HeaderFactory
* @var Swift_Mime_SimpleHeaderFactory
*/
protected $headerFactory;
@@ -59,39 +59,20 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
->lookup('transport.replacementfactory');
$this->signOptions = PKCS7_DETACHED;
// Supported since php5.4
if (defined('OPENSSL_CIPHER_AES_128_CBC')) {
$this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC;
} else {
$this->encryptCipher = OPENSSL_CIPHER_RC2_128;
}
}
/**
* Returns an new Swift_Signers_SMimeSigner instance.
*
* @param string $certificate
* @param string $privateKey
*
* @return Swift_Signers_SMimeSigner
*/
public static function newInstance($certificate = null, $privateKey = null)
{
return new self($certificate, $privateKey);
$this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC;
}
/**
* Set the certificate location to use for signing.
*
* @link http://www.php.net/manual/en/openssl.pkcs7.flags.php
* @see http://www.php.net/manual/en/openssl.pkcs7.flags.php
*
* @param string $certificate
* @param string|array $privateKey If the key needs an passphrase use array('file-location', 'passphrase') instead
* @param int $signOptions Bitwise operator options for openssl_pkcs7_sign()
* @param string $extraCerts A file containing intermediate certificates needed by the signing certificate
*
* @return Swift_Signers_SMimeSigner
* @return $this
*/
public function setSignCertificate($certificate, $privateKey = null, $signOptions = PKCS7_DETACHED, $extraCerts = null)
{
@@ -117,13 +98,13 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
/**
* Set the certificate location to use for encryption.
*
* @link http://www.php.net/manual/en/openssl.pkcs7.flags.php
* @link http://nl3.php.net/manual/en/openssl.ciphers.php
* @see http://www.php.net/manual/en/openssl.pkcs7.flags.php
* @see http://nl3.php.net/manual/en/openssl.ciphers.php
*
* @param string|array $recipientCerts Either an single X.509 certificate, or an assoc array of X.509 certificates.
* @param int $cipher
*
* @return Swift_Signers_SMimeSigner
* @return $this
*/
public function setEncryptCertificate($recipientCerts, $cipher = null)
{
@@ -169,7 +150,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
*
* @param bool $signThenEncrypt
*
* @return Swift_Signers_SMimeSigner
* @return $this
*/
public function setSignThenEncrypt($signThenEncrypt = true)
{
@@ -189,7 +170,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
/**
* Resets internal states.
*
* @return Swift_Signers_SMimeSigner
* @return $this
*/
public function reset()
{
@@ -201,7 +182,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
*
* @param Swift_Message $message
*
* @return Swift_Signers_SMimeSigner
* @return $this
*/
public function signMessage(Swift_Message $message)
{
@@ -297,7 +278,7 @@ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
$args[] = $this->extraCerts;
}
if (!call_user_func_array('openssl_pkcs7_sign', $args)) {
if (!openssl_pkcs7_sign(...$args)) {
throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
}

View File

@@ -11,7 +11,7 @@
/**
* Sends Messages over SMTP with ESMTP support.
*
* @author Chris Corbyn
* @author Chris Corbyn
*
* @method Swift_SmtpTransport setUsername(string $username) Set the username to authenticate with.
* @method string getUsername() Get the username to authenticate with.
@@ -41,18 +41,4 @@ class Swift_SmtpTransport extends Swift_Transport_EsmtpTransport
$this->setPort($port);
$this->setEncryption($security);
}
/**
* Create a new SmtpTransport instance.
*
* @param string $host
* @param int $port
* @param string $security
*
* @return Swift_SmtpTransport
*/
public static function newInstance($host = 'localhost', $port = 25, $security = null)
{
return new self($host, $port, $security);
}
}

View File

@@ -35,11 +35,11 @@ interface Swift_Spool
/**
* Queues a message.
*
* @param Swift_Mime_Message $message The message to store
* @param Swift_Mime_SimpleMessage $message The message to store
*
* @return bool Whether the operation has succeeded
*/
public function queueMessage(Swift_Mime_Message $message);
public function queueMessage(Swift_Mime_SimpleMessage $message);
/**
* Sends messages using the given transport instance.

View File

@@ -32,16 +32,4 @@ class Swift_SpoolTransport extends Swift_Transport_SpoolTransport
$arguments
);
}
/**
* Create a new SpoolTransport instance.
*
* @param Swift_Spool $spool
*
* @return Swift_SpoolTransport
*/
public static function newInstance(Swift_Spool $spool)
{
return new self($spool);
}
}

View File

@@ -13,26 +13,26 @@
*
* This stream filter deals with Byte arrays rather than simple strings.
*
* @author Chris Corbyn
* @author Chris Corbyn
*/
class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilter
{
/** The needle(s) to search for */
private $_search;
private $search;
/** The replacement(s) to make */
private $_replace;
private $replace;
/** The Index for searching */
private $_index;
private $index;
/** The Search Tree */
private $_tree = array();
private $tree = array();
/** Gives the size of the largest search */
private $_treeMaxLen = 0;
private $treeMaxLen = 0;
private $_repSize;
private $repSize;
/**
* Create a new ByteArrayReplacementFilter with $search and $replace.
@@ -42,11 +42,11 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt
*/
public function __construct($search, $replace)
{
$this->_search = $search;
$this->_index = array();
$this->_tree = array();
$this->_replace = array();
$this->_repSize = array();
$this->search = $search;
$this->index = array();
$this->tree = array();
$this->replace = array();
$this->repSize = array();
$tree = null;
$i = null;
@@ -56,10 +56,10 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt
$tree[-1] = min(count($replace) - 1, $i - 1);
$tree[-2] = $last_size;
}
$tree = &$this->_tree;
$tree = &$this->tree;
if (is_array($search_element)) {
foreach ($search_element as $k => $char) {
$this->_index[$char] = true;
$this->index[$char] = true;
if (!isset($tree[$char])) {
$tree[$char] = array();
}
@@ -74,23 +74,23 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt
}
$tree = &$tree[$search_element];
$size = max($last_size, $size);
$this->_index[$search_element] = true;
$this->index[$search_element] = true;
}
}
if ($i !== null) {
$tree[-1] = min(count($replace) - 1, $i);
$tree[-2] = $last_size;
$this->_treeMaxLen = $size;
$this->treeMaxLen = $size;
}
foreach ($replace as $rep) {
if (!is_array($rep)) {
$rep = array($rep);
}
$this->_replace[] = $rep;
$this->replace[] = $rep;
}
for ($i = count($this->_replace) - 1; $i >= 0; --$i) {
$this->_replace[$i] = $rep = $this->filter($this->_replace[$i], $i);
$this->_repSize[$i] = count($rep);
for ($i = count($this->replace) - 1; $i >= 0; --$i) {
$this->replace[$i] = $rep = $this->filter($this->replace[$i], $i);
$this->repSize[$i] = count($rep);
}
}
@@ -105,36 +105,37 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt
{
$endOfBuffer = end($buffer);
return isset($this->_index[$endOfBuffer]);
return isset($this->index[$endOfBuffer]);
}
/**
* Perform the actual replacements on $buffer and return the result.
*
* @param array $buffer
* @param int $_minReplaces
* @param int $minReplaces
*
* @return array
*/
public function filter($buffer, $_minReplaces = -1)
public function filter($buffer, $minReplaces = -1)
{
if ($this->_treeMaxLen == 0) {
if ($this->treeMaxLen == 0) {
return $buffer;
}
$newBuffer = array();
$buf_size = count($buffer);
$last_size = 0;
for ($i = 0; $i < $buf_size; ++$i) {
$search_pos = $this->_tree;
$search_pos = $this->tree;
$last_found = PHP_INT_MAX;
// We try to find if the next byte is part of a search pattern
for ($j = 0; $j <= $this->_treeMaxLen; ++$j) {
for ($j = 0; $j <= $this->treeMaxLen; ++$j) {
// We have a new byte for a search pattern
if (isset($buffer [$p = $i + $j]) && isset($search_pos[$buffer[$p]])) {
if (isset($buffer[$p = $i + $j]) && isset($search_pos[$buffer[$p]])) {
$search_pos = $search_pos[$buffer[$p]];
// We have a complete pattern, save, in case we don't find a better match later
if (isset($search_pos[-1]) && $search_pos[-1] < $last_found
&& $search_pos[-1] > $_minReplaces) {
&& $search_pos[-1] > $minReplaces) {
$last_found = $search_pos[-1];
$last_size = $search_pos[-2];
}
@@ -142,9 +143,9 @@ class Swift_StreamFilters_ByteArrayReplacementFilter implements Swift_StreamFilt
// We got a complete pattern
elseif ($last_found !== PHP_INT_MAX) {
// Adding replacement datas to output buffer
$rep_size = $this->_repSize[$last_found];
$rep_size = $this->repSize[$last_found];
for ($j = 0; $j < $rep_size; ++$j) {
$newBuffer[] = $this->_replace[$last_found][$j];
$newBuffer[] = $this->replace[$last_found][$j];
}
// We Move cursor forward
$i += $last_size - 1;

View File

@@ -16,10 +16,10 @@
class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter
{
/** The needle(s) to search for */
private $_search;
private $search;
/** The replacement(s) to make */
private $_replace;
private $replace;
/**
* Create a new StringReplacementFilter with $search and $replace.
@@ -29,8 +29,8 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter
*/
public function __construct($search, $replace)
{
$this->_search = $search;
$this->_replace = $replace;
$this->search = $search;
$this->replace = $replace;
}
/**
@@ -42,8 +42,12 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter
*/
public function shouldBuffer($buffer)
{
if ('' === $buffer) {
return false;
}
$endOfBuffer = substr($buffer, -1);
foreach ((array) $this->_search as $needle) {
foreach ((array) $this->search as $needle) {
if (false !== strpos($needle, $endOfBuffer)) {
return true;
}
@@ -61,6 +65,6 @@ class Swift_StreamFilters_StringReplacementFilter implements Swift_StreamFilter
*/
public function filter($buffer)
{
return str_replace($this->_search, $this->_replace, $buffer);
return str_replace($this->search, $this->replace, $buffer);
}
}

View File

@@ -16,7 +16,7 @@
class Swift_StreamFilters_StringReplacementFilterFactory implements Swift_ReplacementFilterFactory
{
/** Lazy-loaded filters */
private $_filters = array();
private $filters = array();
/**
* Create a new StreamFilter to replace $search with $replace in a string.
@@ -28,18 +28,18 @@ class Swift_StreamFilters_StringReplacementFilterFactory implements Swift_Replac
*/
public function createFilter($search, $replace)
{
if (!isset($this->_filters[$search][$replace])) {
if (!isset($this->_filters[$search])) {
$this->_filters[$search] = array();
if (!isset($this->filters[$search][$replace])) {
if (!isset($this->filters[$search])) {
$this->filters[$search] = array();
}
if (!isset($this->_filters[$search][$replace])) {
$this->_filters[$search][$replace] = array();
if (!isset($this->filters[$search][$replace])) {
$this->filters[$search][$replace] = array();
}
$this->_filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace);
$this->filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace);
}
return $this->_filters[$search][$replace];
return $this->filters[$search][$replace];
}
}

View File

@@ -32,18 +32,41 @@ interface Swift_Transport
*/
public function stop();
/**
* Check if this Transport mechanism is alive.
*
* If a Transport mechanism session is no longer functional, the method
* returns FALSE. It is the responsibility of the developer to handle this
* case and restart the Transport mechanism manually.
*
* @example
*
* if (!$transport->ping()) {
* $transport->stop();
* $transport->start();
* }
*
* The Transport mechanism will be started, if it is not already.
*
* It is undefined if the Transport mechanism attempts to restart as long as
* the return value reflects whether the mechanism is now functional.
*
* @return bool TRUE if the transport is alive
*/
public function ping();
/**
* Send the given Message.
*
* Recipient/sender data will be retrieved from the Message API.
* The return value is the number of recipients who were accepted for delivery.
*
* @param Swift_Mime_Message $message
* @param Swift_Mime_SimpleMessage $message
* @param string[] $failedRecipients An array of failures by-reference
*
* @return int
*/
public function send(Swift_Mime_Message $message, &$failedRecipients = null);
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null);
/**
* Register a plugin in the Transport.

View File

@@ -16,34 +16,35 @@
abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
{
/** Input-Output buffer for sending/receiving SMTP commands and responses */
protected $_buffer;
protected $buffer;
/** Connection status */
protected $_started = false;
protected $started = false;
/** The domain name to use in HELO command */
protected $_domain = '[127.0.0.1]';
protected $domain = '[127.0.0.1]';
/** The event dispatching layer */
protected $_eventDispatcher;
protected $eventDispatcher;
/** Source Ip */
protected $_sourceIp;
protected $sourceIp;
/** Return an array of params for the Buffer */
abstract protected function _getBufferParams();
abstract protected function getBufferParams();
/**
* Creates a new EsmtpTransport using the given I/O buffer.
*
* @param Swift_Transport_IoBuffer $buf
* @param Swift_Events_EventDispatcher $dispatcher
* @param string $localDomain
*/
public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher)
public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher, $localDomain = '127.0.0.1')
{
$this->_eventDispatcher = $dispatcher;
$this->_buffer = $buf;
$this->_lookupHostname();
$this->eventDispatcher = $dispatcher;
$this->buffer = $buf;
$this->setLocalDomain($localDomain);
}
/**
@@ -52,16 +53,25 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
* This should be a fully-qualified domain name and should be truly the domain
* you're using.
*
* If your server doesn't have a domain name, use the IP in square
* brackets (i.e. [127.0.0.1]).
* If your server does not have a domain name, use the IP address. This will
* automatically be wrapped in square brackets as described in RFC 5321,
* section 4.1.3.
*
* @param string $domain
*
* @return Swift_Transport_AbstractSmtpTransport
* @return $this
*/
public function setLocalDomain($domain)
{
$this->_domain = $domain;
if (substr($domain, 0, 1) !== '[') {
if (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$domain = '['.$domain.']';
} elseif (filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$domain = '[IPv6:'.$domain.']';
}
}
$this->domain = $domain;
return $this;
}
@@ -69,11 +79,14 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
/**
* Get the name of the domain Swift will identify as.
*
* If an IP address was specified, this will be returned wrapped in square
* brackets as described in RFC 5321, section 4.1.3.
*
* @return string
*/
public function getLocalDomain()
{
return $this->_domain;
return $this->domain;
}
/**
@@ -83,7 +96,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
*/
public function setSourceIp($source)
{
$this->_sourceIp = $source;
$this->sourceIp = $source;
}
/**
@@ -93,7 +106,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
*/
public function getSourceIp()
{
return $this->_sourceIp;
return $this->sourceIp;
}
/**
@@ -101,27 +114,27 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
*/
public function start()
{
if (!$this->_started) {
if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) {
$this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted');
if (!$this->started) {
if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) {
$this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted');
if ($evt->bubbleCancelled()) {
return;
}
}
try {
$this->_buffer->initialize($this->_getBufferParams());
$this->buffer->initialize($this->getBufferParams());
} catch (Swift_TransportException $e) {
$this->_throwException($e);
$this->throwException($e);
}
$this->_readGreeting();
$this->_doHeloCommand();
$this->readGreeting();
$this->doHeloCommand();
if ($evt) {
$this->_eventDispatcher->dispatchEvent($evt, 'transportStarted');
$this->eventDispatcher->dispatchEvent($evt, 'transportStarted');
}
$this->_started = true;
$this->started = true;
}
}
@@ -132,7 +145,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
*/
public function isStarted()
{
return $this->_started;
return $this->started;
}
/**
@@ -141,25 +154,25 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
* Recipient/sender data will be retrieved from the Message API.
* The return value is the number of recipients who were accepted for delivery.
*
* @param Swift_Mime_Message $message
* @param Swift_Mime_SimpleMessage $message
* @param string[] $failedRecipients An array of failures by-reference
*
* @return int
*/
public function send(Swift_Mime_Message $message, &$failedRecipients = null)
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
{
$sent = 0;
$failedRecipients = (array) $failedRecipients;
if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) {
$this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed');
if ($evt = $this->eventDispatcher->createSendEvent($this, $message)) {
$this->eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed');
if ($evt->bubbleCancelled()) {
return 0;
}
}
if (!$reversePath = $this->_getReversePath($message)) {
$this->_throwException(new Swift_TransportException(
if (!$reversePath = $this->getReversePath($message)) {
$this->throwException(new Swift_TransportException(
'Cannot send message without a sender address'
)
);
@@ -173,8 +186,8 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
$message->setBcc(array());
try {
$sent += $this->_sendTo($message, $reversePath, $tos, $failedRecipients);
$sent += $this->_sendBcc($message, $reversePath, $bcc, $failedRecipients);
$sent += $this->sendTo($message, $reversePath, $tos, $failedRecipients);
$sent += $this->sendBcc($message, $reversePath, $bcc, $failedRecipients);
} catch (Exception $e) {
$message->setBcc($bcc);
throw $e;
@@ -191,7 +204,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
$evt->setResult(Swift_Events_SendEvent::RESULT_FAILED);
}
$evt->setFailedRecipients($failedRecipients);
$this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed');
$this->eventDispatcher->dispatchEvent($evt, 'sendPerformed');
}
$message->generateId(); //Make sure a new Message ID is used
@@ -204,9 +217,9 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
*/
public function stop()
{
if ($this->_started) {
if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) {
$this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped');
if ($this->started) {
if ($evt = $this->eventDispatcher->createTransportChangeEvent($this)) {
$this->eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped');
if ($evt->bubbleCancelled()) {
return;
}
@@ -218,16 +231,39 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
try {
$this->_buffer->terminate();
$this->buffer->terminate();
if ($evt) {
$this->_eventDispatcher->dispatchEvent($evt, 'transportStopped');
$this->eventDispatcher->dispatchEvent($evt, 'transportStopped');
}
} catch (Swift_TransportException $e) {
$this->_throwException($e);
$this->throwException($e);
}
}
$this->_started = false;
$this->started = false;
}
/**
* {@inheritdoc}
*/
public function ping()
{
try {
if (!$this->isStarted()) {
$this->start();
}
$this->executeCommand("NOOP\r\n", array(250));
} catch (Swift_TransportException $e) {
try {
$this->stop();
} catch (Swift_TransportException $e) {
}
return false;
}
return true;
}
/**
@@ -237,7 +273,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
*/
public function registerPlugin(Swift_Events_EventListener $plugin)
{
$this->_eventDispatcher->bindEventListener($plugin);
$this->eventDispatcher->bindEventListener($plugin);
}
/**
@@ -255,7 +291,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
*/
public function getBuffer()
{
return $this->_buffer;
return $this->buffer;
}
/**
@@ -273,32 +309,32 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
public function executeCommand($command, $codes = array(), &$failures = null)
{
$failures = (array) $failures;
$seq = $this->_buffer->write($command);
$response = $this->_getFullResponse($seq);
if ($evt = $this->_eventDispatcher->createCommandEvent($this, $command, $codes)) {
$this->_eventDispatcher->dispatchEvent($evt, 'commandSent');
$seq = $this->buffer->write($command);
$response = $this->getFullResponse($seq);
if ($evt = $this->eventDispatcher->createCommandEvent($this, $command, $codes)) {
$this->eventDispatcher->dispatchEvent($evt, 'commandSent');
}
$this->_assertResponseCode($response, $codes);
$this->assertResponseCode($response, $codes);
return $response;
}
/** Read the opening SMTP greeting */
protected function _readGreeting()
protected function readGreeting()
{
$this->_assertResponseCode($this->_getFullResponse(0), array(220));
$this->assertResponseCode($this->getFullResponse(0), array(220));
}
/** Send the HELO welcome */
protected function _doHeloCommand()
protected function doHeloCommand()
{
$this->executeCommand(
sprintf("HELO %s\r\n", $this->_domain), array(250)
sprintf("HELO %s\r\n", $this->domain), array(250)
);
}
/** Send the MAIL FROM command */
protected function _doMailFromCommand($address)
protected function doMailFromCommand($address)
{
$this->executeCommand(
sprintf("MAIL FROM:<%s>\r\n", $address), array(250)
@@ -306,7 +342,7 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
/** Send the RCPT TO command */
protected function _doRcptToCommand($address)
protected function doRcptToCommand($address)
{
$this->executeCommand(
sprintf("RCPT TO:<%s>\r\n", $address), array(250, 251, 252)
@@ -314,27 +350,27 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
/** Send the DATA command */
protected function _doDataCommand()
protected function doDataCommand()
{
$this->executeCommand("DATA\r\n", array(354));
}
/** Stream the contents of the message over the buffer */
protected function _streamMessage(Swift_Mime_Message $message)
protected function streamMessage(Swift_Mime_SimpleMessage $message)
{
$this->_buffer->setWriteTranslations(array("\r\n." => "\r\n.."));
$this->buffer->setWriteTranslations(array("\r\n." => "\r\n.."));
try {
$message->toByteStream($this->_buffer);
$this->_buffer->flushBuffers();
$message->toByteStream($this->buffer);
$this->buffer->flushBuffers();
} catch (Swift_TransportException $e) {
$this->_throwException($e);
$this->throwException($e);
}
$this->_buffer->setWriteTranslations(array());
$this->buffer->setWriteTranslations(array());
$this->executeCommand("\r\n.\r\n", array(250));
}
/** Determine the best-use reverse path for this message */
protected function _getReversePath(Swift_Mime_Message $message)
protected function getReversePath(Swift_Mime_SimpleMessage $message)
{
$return = $message->getReturnPath();
$sender = $message->getSender();
@@ -355,10 +391,10 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
/** Throw a TransportException, first sending it to any listeners */
protected function _throwException(Swift_TransportException $e)
protected function throwException(Swift_TransportException $e)
{
if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) {
$this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown');
if ($evt = $this->eventDispatcher->createTransportExceptionEvent($this, $e)) {
$this->eventDispatcher->dispatchEvent($evt, 'exceptionThrown');
if (!$evt->bubbleCancelled()) {
throw $e;
}
@@ -368,18 +404,18 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
/** Throws an Exception if a response code is incorrect */
protected function _assertResponseCode($response, $wanted)
protected function assertResponseCode($response, $wanted)
{
list($code) = sscanf($response, '%3d');
$valid = (empty($wanted) || in_array($code, $wanted));
if ($evt = $this->_eventDispatcher->createResponseEvent($this, $response,
if ($evt = $this->eventDispatcher->createResponseEvent($this, $response,
$valid)) {
$this->_eventDispatcher->dispatchEvent($evt, 'responseReceived');
$this->eventDispatcher->dispatchEvent($evt, 'responseReceived');
}
if (!$valid) {
$this->_throwException(
$this->throwException(
new Swift_TransportException(
'Expected response code '.implode('/', $wanted).' but got code '.
'"'.$code.'", with message "'.$response.'"',
@@ -389,18 +425,18 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
/** Get an entire multi-line response using its sequence number */
protected function _getFullResponse($seq)
protected function getFullResponse($seq)
{
$response = '';
try {
do {
$line = $this->_buffer->readLine($seq);
$line = $this->buffer->readLine($seq);
$response .= $line;
} while (null !== $line && false !== $line && ' ' != $line{3});
} while (null !== $line && false !== $line && ' ' != $line[3]);
} catch (Swift_TransportException $e) {
$this->_throwException($e);
$this->throwException($e);
} catch (Swift_IoException $e) {
$this->_throwException(
$this->throwException(
new Swift_TransportException(
$e->getMessage())
);
@@ -410,13 +446,13 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
/** Send an email to the given recipients from the given reverse path */
private function _doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients)
private function doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients)
{
$sent = 0;
$this->_doMailFromCommand($reversePath);
$this->doMailFromCommand($reversePath);
foreach ($recipients as $forwardPath) {
try {
$this->_doRcptToCommand($forwardPath);
$this->doRcptToCommand($forwardPath);
++$sent;
} catch (Swift_TransportException $e) {
$failedRecipients[] = $forwardPath;
@@ -424,8 +460,8 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
if ($sent != 0) {
$this->_doDataCommand();
$this->_streamMessage($message);
$this->doDataCommand();
$this->streamMessage($message);
} else {
$this->reset();
}
@@ -434,23 +470,23 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
}
/** Send a message to the given To: recipients */
private function _sendTo(Swift_Mime_Message $message, $reversePath, array $to, array &$failedRecipients)
private function sendTo(Swift_Mime_SimpleMessage $message, $reversePath, array $to, array &$failedRecipients)
{
if (empty($to)) {
return 0;
}
return $this->_doMailTransaction($message, $reversePath, array_keys($to),
return $this->doMailTransaction($message, $reversePath, array_keys($to),
$failedRecipients);
}
/** Send a message to all Bcc: recipients */
private function _sendBcc(Swift_Mime_Message $message, $reversePath, array $bcc, array &$failedRecipients)
private function sendBcc(Swift_Mime_SimpleMessage $message, $reversePath, array $bcc, array &$failedRecipients)
{
$sent = 0;
foreach ($bcc as $forwardPath => $name) {
$message->setBcc(array($forwardPath => $name));
$sent += $this->_doMailTransaction(
$sent += $this->doMailTransaction(
$message, $reversePath, array($forwardPath), $failedRecipients
);
}
@@ -458,33 +494,14 @@ abstract class Swift_Transport_AbstractSmtpTransport implements Swift_Transport
return $sent;
}
/** Try to determine the hostname of the server this is run on */
private function _lookupHostname()
{
if (!empty($_SERVER['SERVER_NAME'])
&& $this->_isFqdn($_SERVER['SERVER_NAME'])) {
$this->_domain = $_SERVER['SERVER_NAME'];
} elseif (!empty($_SERVER['SERVER_ADDR'])) {
$this->_domain = sprintf('[%s]', $_SERVER['SERVER_ADDR']);
}
}
/** Determine is the $hostname is a fully-qualified name */
private function _isFqdn($hostname)
{
// We could do a really thorough check, but there's really no point
if (false !== $dotPos = strpos($hostname, '.')) {
return ($dotPos > 0) && ($dotPos != strlen($hostname) - 1);
}
return false;
}
/**
* Destructor.
*/
public function __destruct()
{
$this->stop();
try {
$this->stop();
} catch (Exception $e) {
}
}
}

View File

@@ -40,7 +40,7 @@ class Swift_Transport_Esmtp_Auth_CramMd5Authenticator implements Swift_Transport
$challenge = $agent->executeCommand("AUTH CRAM-MD5\r\n", array(334));
$challenge = base64_decode(substr($challenge, 4));
$message = base64_encode(
$username.' '.$this->_getResponse($password, $challenge)
$username.' '.$this->getResponse($password, $challenge)
);
$agent->executeCommand(sprintf("%s\r\n", $message), array(235));
@@ -60,7 +60,7 @@ class Swift_Transport_Esmtp_Auth_CramMd5Authenticator implements Swift_Transport
*
* @return string
*/
private function _getResponse($secret, $challenge)
private function getResponse($secret, $challenge)
{
if (strlen($secret) > 64) {
$secret = pack('H32', md5($secret));

View File

@@ -13,7 +13,7 @@
/**
* Handles NTLM authentication.
*
* @author Ward Peeters <ward@coding-tech.com>
* @author Ward Peeters <ward@coding-tech.com>
*/
class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Esmtp_Authenticator
{
@@ -38,19 +38,17 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
* @param string $password
*
* @return bool
*
* @throws \LogicException
*/
public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password)
{
if (!function_exists('mcrypt_module_open')) {
throw new LogicException('The mcrypt functions need to be enabled to use the NTLM authenticator.');
}
if (!function_exists('openssl_random_pseudo_bytes')) {
if (!function_exists('openssl_encrypt')) {
throw new LogicException('The OpenSSL extension must be enabled to use the NTLM authenticator.');
}
if (!function_exists('bcmul')) {
throw new LogicException('The BCMatch functions must be enabled to use the NTLM authenticator.');
throw new LogicException('The BCMath functions must be enabled to use the NTLM authenticator.');
}
try {
@@ -60,7 +58,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
// extra parameters for our unit cases
$timestamp = func_num_args() > 3 ? func_get_arg(3) : $this->getCorrectTimestamp(bcmul(microtime(true), '1000'));
$client = func_num_args() > 4 ? func_get_arg(4) : $this->getRandomBytes(8);
$client = func_num_args() > 4 ? func_get_arg(4) : random_bytes(8);
// Message 3 response
$this->sendMessage3($response, $username, $password, $timestamp, $client, $agent);
@@ -125,10 +123,10 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
$responseHex = bin2hex($response);
$length = floor(hexdec(substr($responseHex, 28, 4)) / 256) * 2;
$offset = floor(hexdec(substr($responseHex, 32, 4)) / 256) * 2;
$challenge = $this->hex2bin(substr($responseHex, 48, 16));
$context = $this->hex2bin(substr($responseHex, 64, 16));
$targetInfoH = $this->hex2bin(substr($responseHex, 80, 16));
$targetName = $this->hex2bin(substr($responseHex, $offset, $length));
$challenge = hex2bin(substr($responseHex, 48, 16));
$context = hex2bin(substr($responseHex, 64, 16));
$targetInfoH = hex2bin(substr($responseHex, 80, 16));
$targetName = hex2bin(substr($responseHex, $offset, $length));
$offset = floor(hexdec(substr($responseHex, 88, 4)) / 256) * 2;
$targetInfoBlock = substr($responseHex, $offset);
list($domainName, $serverName, $DNSDomainName, $DNSServerName, $terminatorByte) = $this->readSubBlock($targetInfoBlock);
@@ -142,7 +140,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
$serverName,
$DNSDomainName,
$DNSServerName,
$this->hex2bin($targetInfoBlock),
hex2bin($targetInfoBlock),
$terminatorByte,
);
}
@@ -165,7 +163,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
while ($offset < $length) {
$blockLength = hexdec(substr(substr($block, $offset, 8), -4)) / 256;
$offset += 8;
$data[] = $this->hex2bin(substr($block, $offset, $blockLength * 2));
$data[] = hex2bin(substr($block, $offset, $blockLength * 2));
$offset += $blockLength * 2;
}
@@ -300,9 +298,14 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
return explode('\\', $name);
}
list($user, $domain) = explode('@', $name);
if (false !== strpos($name, '@')) {
list($user, $domain) = explode('@', $name);
return array($domain, $user);
return array($domain, $user);
}
// no domain passed
return array('', $name);
}
/**
@@ -365,11 +368,9 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
protected function getCorrectTimestamp($time)
{
// Get our timestamp (tricky!)
bcscale(0);
$time = number_format($time, 0, '.', ''); // save microtime to string
$time = bcadd($time, '11644473600000'); // add epoch time
$time = bcmul($time, 10000); // tenths of a microsecond.
$time = bcadd($time, '11644473600000', 0); // add epoch time
$time = bcmul($time, 10000, 0); // tenths of a microsecond.
$binary = $this->si2bin($time, 64); // create 64 bit binary string
$timestamp = '';
@@ -459,10 +460,11 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
}
}
return $this->hex2bin(implode('', $material));
return hex2bin(implode('', $material));
}
/** HELPER FUNCTIONS */
/**
* Create our security buffer depending on length and offset.
*
@@ -538,7 +540,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
protected function createByte($input, $bytes = 4, $isHex = true)
{
if ($isHex) {
$byte = $this->hex2bin(str_pad($input, $bytes * 2, '00'));
$byte = hex2bin(str_pad($input, $bytes * 2, '00'));
} else {
$byte = str_pad($input, $bytes, "\x00");
}
@@ -546,39 +548,19 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
return $byte;
}
/**
* Create random bytes.
*
* @param $length
*
* @return string
*/
protected function getRandomBytes($length)
{
$bytes = openssl_random_pseudo_bytes($length, $strong);
if (false !== $bytes && true === $strong) {
return $bytes;
}
throw new RuntimeException('OpenSSL did not produce a secure random number.');
}
/** ENCRYPTION ALGORITHMS */
/**
* DES Encryption.
*
* @param string $value
* @param string $value An 8-byte string
* @param string $key
*
* @return string
*/
protected function desEncrypt($value, $key)
{
$cipher = mcrypt_module_open(MCRYPT_DES, '', 'ecb', '');
mcrypt_generic_init($cipher, $key, mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_DEV_RANDOM));
return mcrypt_generic($cipher, $value);
return substr(openssl_encrypt($value, 'DES-ECB', $key, \OPENSSL_RAW_DATA), 0, 8);
}
/**
@@ -616,7 +598,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
{
$input = $this->convertTo16bit($input);
return function_exists('hash') ? $this->hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input);
return function_exists('hash') ? hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input);
}
/**
@@ -631,22 +613,6 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
return iconv('UTF-8', 'UTF-16LE', $input);
}
/**
* Hex2bin replacement for < PHP 5.4.
*
* @param string $hex
*
* @return string Binary
*/
protected function hex2bin($hex)
{
if (function_exists('hex2bin')) {
return hex2bin($hex);
} else {
return pack('H*', $hex);
}
}
/**
* @param string $message
*/
@@ -671,7 +637,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
'Target Information Terminator',
);
$data = $this->parseMessage2($this->hex2bin($message));
$data = $this->parseMessage2(hex2bin($message));
foreach ($map as $key => $value) {
echo bin2hex($data[$key]).' - '.$data[$key].' ||| '.$value."<br />\n";
@@ -717,7 +683,7 @@ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Es
);
foreach ($map as $key => $value) {
echo $data[$key].' - '.$this->hex2bin($data[$key]).' ||| '.$value."<br />\n";
echo $data[$key].' - '.hex2bin($data[$key]).' ||| '.$value."<br />\n";
}
}

View File

@@ -13,7 +13,7 @@
*
* Example:
* <code>
* $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls')
* $transport = (new Swift_SmtpTransport('smtp.gmail.com', 587, 'tls'))
* ->setAuthMode('XOAUTH2')
* ->setUsername('YOUR_EMAIL_ADDRESS')
* ->setPassword('YOUR_ACCESS_TOKEN');

View File

@@ -20,35 +20,35 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*
* @var Swift_Transport_Esmtp_Authenticator[]
*/
private $_authenticators = array();
private $authenticators = array();
/**
* The username for authentication.
*
* @var string
*/
private $_username;
private $username;
/**
* The password for authentication.
*
* @var string
*/
private $_password;
private $password;
/**
* The auth mode for authentication.
*
* @var string
*/
private $_auth_mode;
private $auth_mode;
/**
* The ESMTP AUTH parameters available.
*
* @var string[]
*/
private $_esmtpParams = array();
private $esmtpParams = array();
/**
* Create a new AuthHandler with $authenticators for support.
@@ -67,7 +67,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function setAuthenticators(array $authenticators)
{
$this->_authenticators = $authenticators;
$this->authenticators = $authenticators;
}
/**
@@ -77,7 +77,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function getAuthenticators()
{
return $this->_authenticators;
return $this->authenticators;
}
/**
@@ -87,7 +87,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function setUsername($username)
{
$this->_username = $username;
$this->username = $username;
}
/**
@@ -97,7 +97,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function getUsername()
{
return $this->_username;
return $this->username;
}
/**
@@ -107,7 +107,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function setPassword($password)
{
$this->_password = $password;
$this->password = $password;
}
/**
@@ -117,7 +117,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function getPassword()
{
return $this->_password;
return $this->password;
}
/**
@@ -127,7 +127,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function setAuthMode($mode)
{
$this->_auth_mode = $mode;
$this->auth_mode = $mode;
}
/**
@@ -137,7 +137,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function getAuthMode()
{
return $this->_auth_mode;
return $this->auth_mode;
}
/**
@@ -157,7 +157,7 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function setKeywordParams(array $parameters)
{
$this->_esmtpParams = $parameters;
$this->esmtpParams = $parameters;
}
/**
@@ -167,20 +167,20 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*/
public function afterEhlo(Swift_Transport_SmtpAgent $agent)
{
if ($this->_username) {
if ($this->username) {
$count = 0;
foreach ($this->_getAuthenticatorsForAgent() as $authenticator) {
foreach ($this->getAuthenticatorsForAgent() as $authenticator) {
if (in_array(strtolower($authenticator->getAuthKeyword()),
array_map('strtolower', $this->_esmtpParams))) {
array_map('strtolower', $this->esmtpParams))) {
++$count;
if ($authenticator->authenticate($agent, $this->_username, $this->_password)) {
if ($authenticator->authenticate($agent, $this->username, $this->password)) {
return;
}
}
}
throw new Swift_TransportException(
'Failed to authenticate on SMTP server with username "'.
$this->_username.'" using '.$count.' possible authenticators'
$this->username.'" using '.$count.' possible authenticators'
);
}
}
@@ -246,13 +246,13 @@ class Swift_Transport_Esmtp_AuthHandler implements Swift_Transport_EsmtpHandler
*
* @return array
*/
protected function _getAuthenticatorsForAgent()
protected function getAuthenticatorsForAgent()
{
if (!$mode = strtolower($this->_auth_mode)) {
return $this->_authenticators;
if (!$mode = strtolower($this->auth_mode)) {
return $this->authenticators;
}
foreach ($this->_authenticators as $authenticator) {
foreach ($this->authenticators as $authenticator) {
if (strtolower($authenticator->getAuthKeyword()) == $mode) {
return array($authenticator);
}

Some files were not shown because too many files have changed in this diff Show More