Added 3rd party KH modules

This commit is contained in:
Deon George
2013-04-22 14:19:54 +10:00
parent 8888719653
commit 711c11dc03
176 changed files with 20483 additions and 0 deletions

View File

@@ -0,0 +1,143 @@
<?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.
*/
//@require 'Swift/Mime/SimpleMimeEntity.php';
//@require 'Swift/Mime/ContentEncoder.php';
//@require 'Swift/Mime/HeaderSet.php';
//@require 'Swift/FileStream.php';
//@require 'Swift/KeyCache.php';
/**
* An attachment, in a multipart message.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_Attachment extends Swift_Mime_SimpleMimeEntity
{
/** Recognized MIME types */
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 array $mimeTypes optional
*/
public function __construct(Swift_Mime_HeaderSet $headers,
Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache,
$mimeTypes = array())
{
parent::__construct($headers, $encoder, $cache);
$this->setDisposition('attachment');
$this->setContentType('application/octet-stream');
$this->_mimeTypes = $mimeTypes;
}
/**
* Get the nesting level used for this attachment.
* Always returns {@link LEVEL_MIXED}.
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_MIXED;
}
/**
* Get the Content-Disposition of this attachment.
* By default attachments have a disposition of "attachment".
* @return string
*/
public function getDisposition()
{
return $this->_getHeaderFieldModel('Content-Disposition');
}
/**
* Set the Content-Disposition of this attachment.
* @param string $disposition
*/
public function setDisposition($disposition)
{
if (!$this->_setHeaderFieldModel('Content-Disposition', $disposition))
{
$this->getHeaders()->addParameterizedHeader(
'Content-Disposition', $disposition
);
}
return $this;
}
/**
* Get the filename of this attachment when downloaded.
* @return string
*/
public function getFilename()
{
return $this->_getHeaderParameter('Content-Disposition', 'filename');
}
/**
* Set the filename of this attachment.
* @param string $filename
*/
public function setFilename($filename)
{
$this->_setHeaderParameter('Content-Disposition', 'filename', $filename);
$this->_setHeaderParameter('Content-Type', 'name', $filename);
return $this;
}
/**
* Get the file size of this attachment.
* @return int
*/
public function getSize()
{
return $this->_getHeaderParameter('Content-Disposition', 'size');
}
/**
* Set the file size of this attachment.
* @param int $size
*/
public function setSize($size)
{
$this->_setHeaderParameter('Content-Disposition', 'size', $size);
return $this;
}
/**
* Set the file that this attachment is for.
* @param Swift_FileStream $file
* @param string $contentType optional
*/
public function setFile(Swift_FileStream $file, $contentType = null)
{
$this->setFilename(basename($file->getPath()));
$this->setBody($file, $contentType);
if (!isset($contentType))
{
$extension = strtolower(substr(
$file->getPath(), strrpos($file->getPath(), '.') + 1
));
if (array_key_exists($extension, $this->_mimeTypes))
{
$this->setContentType($this->_mimeTypes[$extension]);
}
}
return $this;
}
}

View File

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

View File

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

View File

@@ -0,0 +1,81 @@
<?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.
*/
//@require 'Swift/Mime/ContentEncoder.php';
//@require 'Swift/Encoder/Base64Encoder.php';
//@require 'Swift/InputByteStream.php';
//@require 'Swift/OutputByteStream.php';
/**
* Handles Base 64 Transfer Encoding in Swift Mailer.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_Base64ContentEncoder
extends Swift_Encoder_Base64Encoder
implements Swift_Mime_ContentEncoder
{
/**
* Encode stream $in to stream $out.
* @param Swift_OutputByteStream $in
* @param Swift_InputByteStream $out
* @param int $firstLineOffset
* @param int $maxLineLength, optional, 0 indicates the default of 76 bytes
*/
public function encodeByteStream(
Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0,
$maxLineLength = 0)
{
if (0 >= $maxLineLength || 76 < $maxLineLength)
{
$maxLineLength = 76;
}
$remainder = 0;
while (false !== $bytes = $os->read(8190))
{
$encoded = base64_encode($bytes);
$encodedTransformed = '';
$thisMaxLineLength = $maxLineLength - $remainder - $firstLineOffset;
while ($thisMaxLineLength < strlen($encoded))
{
$encodedTransformed .= substr($encoded, 0, $thisMaxLineLength) . "\r\n";
$firstLineOffset = 0;
$encoded = substr($encoded, $thisMaxLineLength);
$thisMaxLineLength = $maxLineLength;
$remainder = 0;
}
if (0 < $remainingLength = strlen($encoded))
{
$remainder += $remainingLength;
$encodedTransformed .= $encoded;
$encoded = null;
}
$is->write($encodedTransformed);
}
}
/**
* Get the name of this encoding scheme.
* Returns the string 'base64'.
* @return string
*/
public function getName()
{
return 'base64';
}
}

View File

@@ -0,0 +1,175 @@
<?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.
*/
//@require 'Swift/Mime/ContentEncoder.php';
//@require 'Swift/InputByteStream.php';
//@require 'Swift/OutputByteStream.php';
/**
* Handles binary/7/8-bit Transfer Encoding in Swift Mailer.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_PlainContentEncoder
implements Swift_Mime_ContentEncoder
{
/**
* The name of this encoding scheme (probably 7bit or 8bit).
* @var string
* @access private
*/
private $_name;
/**
* True if canonical transformations should be done.
* @var boolean
* @access private
*/
private $_canonical;
/**
* Creates a new PlainContentEncoder with $name (probably 7bit or 8bit).
* @param string $name
* @param boolean $canonical If canonicalization transformation should be done.
*/
public function __construct($name, $canonical = false)
{
$this->_name = $name;
$this->_canonical = $canonical;
}
/**
* Encode a given string to produce an encoded string.
* @param string $string
* @param int $firstLineOffset, ignored
* @param int $maxLineLength - 0 means no wrapping will occur
* @return string
*/
public function encodeString($string, $firstLineOffset = 0,
$maxLineLength = 0)
{
if ($this->_canonical)
{
$string = $this->_canonicalize($string);
}
return $this->_safeWordWrap($string, $maxLineLength, "\r\n");
}
/**
* Encode stream $in to stream $out.
* @param Swift_OutputByteStream $in
* @param Swift_InputByteStream $out
* @param int $firstLineOffset, ignored
* @param int $maxLineLength, optional, 0 means no wrapping will occur
*/
public function encodeByteStream(
Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0,
$maxLineLength = 0)
{
$leftOver = '';
while (false !== $bytes = $os->read(8192))
{
$toencode = $leftOver . $bytes;
if ($this->_canonical)
{
$toencode = $this->_canonicalize($toencode);
}
$wrapped = $this->_safeWordWrap($toencode, $maxLineLength, "\r\n");
$lastLinePos = strrpos($wrapped, "\r\n");
$leftOver = substr($wrapped, $lastLinePos);
$wrapped = substr($wrapped, 0, $lastLinePos);
$is->write($wrapped);
}
if (strlen($leftOver))
{
$is->write($leftOver);
}
}
/**
* Get the name of this encoding scheme.
* @return string
*/
public function getName()
{
return $this->_name;
}
/**
* Not used.
*/
public function charsetChanged($charset)
{
}
// -- Private methods
/**
* A safer (but weaker) wordwrap for unicode.
* @param string $string
* @param int $length
* @param string $le
* @return string
* @access private
*/
private function _safeWordwrap($string, $length = 75, $le = "\r\n")
{
if (0 >= $length)
{
return $string;
}
$originalLines = explode($le, $string);
$lines = array();
$lineCount = 0;
foreach ($originalLines as $originalLine)
{
$lines[] = '';
$currentLine =& $lines[$lineCount++];
//$chunks = preg_split('/(?<=[\ \t,\.!\?\-&\+\/])/', $originalLine);
$chunks = preg_split('/(?<=\s)/', $originalLine);
foreach ($chunks as $chunk)
{
if (0 != strlen($currentLine)
&& strlen($currentLine . $chunk) > $length)
{
$lines[] = '';
$currentLine =& $lines[$lineCount++];
}
$currentLine .= $chunk;
}
}
return implode("\r\n", $lines);
}
/**
* Canonicalize string input (fix CRLF).
* @param string $string
* @return string
* @access private
*/
private function _canonicalize($string)
{
return str_replace(
array("\r\n", "\r", "\n"),
array("\n", "\n", "\r\n"),
$string
);
}
}

View File

@@ -0,0 +1,117 @@
<?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.
*/
//@require 'Swift/Mime/ContentEncoder.php';
//@require 'Swift/Encoder/QpEncoder.php';
//@require 'Swift/InputByteStrean.php';
//@require 'Swift/OutputByteStream.php';
//@require 'Swift/CharacterStream.php';
/**
* Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder
implements Swift_Mime_ContentEncoder
{
/**
* Creates a new QpContentEncoder for the given CharacterStream.
* @param Swift_CharacterStream $charStream to use for reading characters
* @param Swift_StreamFilter $filter if canonicalization should occur
*/
public function __construct(Swift_CharacterStream $charStream,
Swift_StreamFilter $filter = null)
{
parent::__construct($charStream, $filter);
}
/**
* Encode stream $in to stream $out.
* QP encoded strings have a maximum line length of 76 characters.
* If the first line needs to be shorter, indicate the difference with
* $firstLineOffset.
* @param Swift_OutputByteStream $os output stream
* @param Swift_InputByteStream $is input stream
* @param int $firstLineOffset
* @param int $maxLineLength
*/
public function encodeByteStream(
Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0,
$maxLineLength = 0)
{
if ($maxLineLength > 76 || $maxLineLength <= 0)
{
$maxLineLength = 76;
}
$thisLineLength = $maxLineLength - $firstLineOffset;
$this->_charStream->flushContents();
$this->_charStream->importByteStream($os);
$currentLine = '';
$prepend = '';
$size=$lineLen=0;
while (false !== $bytes = $this->_nextSequence())
{
//If we're filtering the input
if (isset($this->_filter))
{
//If we can't filter because we need more bytes
while ($this->_filter->shouldBuffer($bytes))
{
//Then collect bytes into the buffer
if (false === $moreBytes = $this->_nextSequence(1))
{
break;
}
foreach ($moreBytes as $b)
{
$bytes[] = $b;
}
}
//And filter them
$bytes = $this->_filter->filter($bytes);
}
$enc = $this->_encodeByteSequence($bytes, $size);
if ($currentLine && $lineLen+$size >= $thisLineLength)
{
$is->write($prepend . $this->_standardize($currentLine));
$currentLine = '';
$prepend = "=\r\n";
$thisLineLength = $maxLineLength;
$lineLen=0;
}
$lineLen+=$size;
$currentLine .= $enc;
}
if (strlen($currentLine))
{
$is->write($prepend . $this->_standardize($currentLine));
}
}
/**
* Get the name of this encoding scheme.
* Returns the string 'quoted-printable'.
* @return string
*/
public function getName()
{
return 'quoted-printable';
}
}

View File

@@ -0,0 +1,51 @@
<?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.
*/
//@require 'Swift/Mime/Attachment.php';
//@require 'Swift/Mime/ContentEncoder.php';
//@require 'Swift/KeyCache.php';
//@require
/**
* An embedded file, in a multipart message.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
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 array $mimeTypes optional
*/
public function __construct(Swift_Mime_HeaderSet $headers,
Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache,
$mimeTypes = array())
{
parent::__construct($headers, $encoder, $cache, $mimeTypes);
$this->setDisposition('inline');
$this->setId($this->getId());
}
/**
* Get the nesting level of this EmbeddedFile.
* Returns {@link LEVEL_RELATED}.
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_RELATED;
}
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
//@require 'Swift/Mime/ContentEncoder.php';
/**
* Observes changes for a Mime entity's ContentEncoder.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
interface Swift_Mime_EncodingObserver
{
/**
* Notify this observer that the observed entity's ContentEncoder has changed.
* @param Swift_Mime_ContentEncoder $encoder
*/
public function encoderChanged(Swift_Mime_ContentEncoder $encoder);
}

View File

@@ -0,0 +1,85 @@
<?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.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
interface Swift_Mime_Header
{
/** Text headers */
const TYPE_TEXT = 2;
/** Parameterized headers (text + params) */
const TYPE_PARAMETERIZED = 6;
/** Mailbox and address headers */
const TYPE_MAILBOX = 8;
/** Date and time headers */
const TYPE_DATE = 16;
/** Identification headers */
const TYPE_ID = 32;
/** Address path headers */
const TYPE_PATH = 64;
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType();
/**
* Set the model for the field body.
* The actual types needed will vary depending upon the type of Header.
* @param mixed $model
*/
public function setFieldBodyModel($model);
/**
* Set the charset used when rendering the Header.
* @param string $charset
*/
public function setCharset($charset);
/**
* Get the model for the field body.
* The return type depends on the specifics of the Header.
* @return mixed
*/
public function getFieldBodyModel();
/**
* Get the name of this header (e.g. Subject).
* The name is an identifier and as such will be immutable.
* @return string
*/
public function getFieldName();
/**
* Get the field body, prepared for folding into a final header value.
* @return string
*/
public function getFieldBody();
/**
* Get this Header rendered as a compliant string.
* @return string
*/
public function toString();
}

View File

@@ -0,0 +1,28 @@
<?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.
*/
//@require 'Swift/Encoder.php';
/**
* Interface for all Header Encoding schemes.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
interface Swift_Mime_HeaderEncoder extends Swift_Encoder
{
/**
* Get the MIME name of this content encoding scheme.
* @return string
*/
public function getName();
}

View File

@@ -0,0 +1,36 @@
<?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.
*/
require_once dirname(__FILE__) . '/../HeaderEncoder.php';
require_once dirname(__FILE__) . '/../../Encoder/Base64Encoder.php';
/**
* Handles Base64 (B) Header Encoding in Swift Mailer.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_HeaderEncoder_Base64HeaderEncoder
extends Swift_Encoder_Base64Encoder
implements Swift_Mime_HeaderEncoder
{
/**
* Get the name of this encoding scheme.
* Returns the string 'B'.
* @return string
*/
public function getName()
{
return 'B';
}
}

View File

@@ -0,0 +1,99 @@
<?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.
*/
require_once dirname(__FILE__) . '/../HeaderEncoder.php';
require_once dirname(__FILE__) . '/../../Encoder/QpEncoder.php';
require_once dirname(__FILE__) . '/../../CharacterStream.php';
/**
* Handles Quoted Printable (Q) Header Encoding in Swift Mailer.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder
implements Swift_Mime_HeaderEncoder
{
private static $_headerSafeMap = array();
/**
* Creates a new QpHeaderEncoder for the given CharacterStream.
* @param Swift_CharacterStream $charStream to use for reading characters
*/
public function __construct(Swift_CharacterStream $charStream)
{
parent::__construct($charStream);
if (empty(self::$_headerSafeMap))
{
foreach (array_merge(
range(0x61, 0x7A), range(0x41, 0x5A),
range(0x30, 0x39), array(0x20, 0x21, 0x2A, 0x2B, 0x2D, 0x2F)
) as $byte)
{
self::$_headerSafeMap[$byte] = chr($byte);
}
}
}
/**
* Get the name of this encoding scheme.
* Returns the string 'Q'.
* @return string
*/
public function getName()
{
return 'Q';
}
/**
* Takes an unencoded string and produces a Q encoded string from it.
* @param string $string to encode
* @param int $firstLineOffset, optional
* @param int $maxLineLength, optional, 0 indicates the default of 76 chars
* @return string
*/
public function encodeString($string, $firstLineOffset = 0,
$maxLineLength = 0)
{
return str_replace(array(' ', '=20', "=\r\n"), array('_', '_', "\r\n"),
parent::encodeString($string, $firstLineOffset, $maxLineLength)
);
}
// -- Overridden points of extension
/**
* Encode the given byte array into a verbatim QP form.
* @param int[] $bytes
* @return string
* @access protected
*/
protected function _encodeByteSequence(array $bytes, &$size)
{
$ret = '';
$size=0;
foreach ($bytes as $b)
{
if (isset(self::$_headerSafeMap[$b]))
{
$ret .= self::$_headerSafeMap[$b];
++$size;
}
else
{
$ret .= self::$_qpMap[$b];
$size+=3;
}
}
return $ret;
}
}

View File

@@ -0,0 +1,72 @@
<?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.
*/
//@require 'Swift/Mime/CharsetObserver.php';
/**
* Creates MIME headers.
* @package Swift
* @subpackage Mime
* @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

@@ -0,0 +1,170 @@
<?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.
*/
//@require 'Swift/Mime/CharsetObserver.php';
/**
* A collection of MIME headers.
*
* @package Swift
* @subpackage Mime
*
* @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 boolean
*/
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);
/**
* 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

@@ -0,0 +1,596 @@
<?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.
*/
//@require 'Swift/Mime/Header.php';
//@require 'Swift/Mime/HeaderEncoder.php';
//@require 'Swift/RfcComplianceException.php';
/**
* An abstract base MIME Header.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
{
/**
* Special characters used in the syntax which need to be escaped.
* @var string[]
* @access private
*/
private $_specials = array();
/**
* Tokens defined in RFC 2822 (and some related RFCs).
* @var string[]
* @access private
*/
private $_grammar = array();
/**
* The name of this Header.
* @var string
* @access private
*/
private $_name;
/**
* The Encoder used to encode this Header.
* @var Swift_Encoder
* @access private
*/
private $_encoder;
/**
* The maximum length of a line in the header.
* @var int
* @access private
*/
private $_lineLength = 78;
/**
* The language used in this Header.
* @var string
*/
private $_lang;
/**
* The character set of the text in this Header.
* @var string
* @access private
*/
private $_charset = 'utf-8';
/**
* The value of this Header, cached.
* @var string
* @access private
*/
private $_cachedValue = null;
/**
* Set the character set used in this Header.
* @param string $charset
*/
public function setCharset($charset)
{
$this->clearCachedValueIf($charset != $this->_charset);
$this->_charset = $charset;
if (isset($this->_encoder))
{
$this->_encoder->charsetChanged($charset);
}
}
/**
* Get the character set used in this Header.
* @return string
*/
public function getCharset()
{
return $this->_charset;
}
/**
* Set the language used in this Header.
* For example, for US English, 'en-us'.
* This can be unspecified.
* @param string $lang
*/
public function setLanguage($lang)
{
$this->clearCachedValueIf($this->_lang != $lang);
$this->_lang = $lang;
}
/**
* Get the language used in this Header.
* @return string
*/
public function getLanguage()
{
return $this->_lang;
}
/**
* Set the encoder used for encoding the header.
* @param Swift_Mime_HeaderEncoder $encoder
*/
public function setEncoder(Swift_Mime_HeaderEncoder $encoder)
{
$this->_encoder = $encoder;
$this->setCachedValue(null);
}
/**
* Get the encoder used for encoding this Header.
* @return Swift_Mime_HeaderEncoder
*/
public function getEncoder()
{
return $this->_encoder;
}
/**
* Get the name of this header (e.g. charset).
* @return string
*/
public function getFieldName()
{
return $this->_name;
}
/**
* Set the maximum length of lines in the header (excluding EOL).
* @param int $lineLength
*/
public function setMaxLineLength($lineLength)
{
$this->clearCachedValueIf($this->_lineLength != $lineLength);
$this->_lineLength = $lineLength;
}
/**
* Get the maximum permitted length of lines in this Header.
* @return int
*/
public function getMaxLineLength()
{
return $this->_lineLength;
}
/**
* Get this Header rendered as a RFC 2822 compliant string.
* @return string
* @throws Swift_RfcComplianceException
*/
public function toString()
{
return $this->_tokensToString($this->toTokens());
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
// -- Points of extension
/**
* Set the name of this Header field.
* @param string $name
* @access protected
*/
protected function setFieldName($name)
{
$this->_name = $name;
}
/**
* Initialize some RFC 2822 (and friends) ABNF grammar definitions.
* @access protected
*/
protected function initializeGrammar()
{
$this->_specials = array(
'(', ')', '<', '>', '[', ']',
':', ';', '@', ',', '.', '"'
);
/*** Refer to RFC 2822 for ABNF grammar ***/
//All basic building blocks
$this->_grammar['NO-WS-CTL'] = '[\x01-\x08\x0B\x0C\x0E-\x19\x7F]';
$this->_grammar['WSP'] = '[ \t]';
$this->_grammar['CRLF'] = '(?:\r\n)';
$this->_grammar['FWS'] = '(?:(?:' . $this->_grammar['WSP'] . '*' .
$this->_grammar['CRLF'] . ')?' . $this->_grammar['WSP'] . ')';
$this->_grammar['text'] = '[\x00-\x08\x0B\x0C\x0E-\x7F]';
$this->_grammar['quoted-pair'] = '(?:\\\\' . $this->_grammar['text'] . ')';
$this->_grammar['ctext'] = '(?:' . $this->_grammar['NO-WS-CTL'] .
'|[\x21-\x27\x2A-\x5B\x5D-\x7E])';
//Uses recursive PCRE (?1) -- could be a weak point??
$this->_grammar['ccontent'] = '(?:' . $this->_grammar['ctext'] . '|' .
$this->_grammar['quoted-pair'] . '|(?1))';
$this->_grammar['comment'] = '(\((?:' . $this->_grammar['FWS'] . '|' .
$this->_grammar['ccontent']. ')*' . $this->_grammar['FWS'] . '?\))';
$this->_grammar['CFWS'] = '(?:(?:' . $this->_grammar['FWS'] . '?' .
$this->_grammar['comment'] . ')*(?:(?:' . $this->_grammar['FWS'] . '?' .
$this->_grammar['comment'] . ')|' . $this->_grammar['FWS'] . '))';
$this->_grammar['qtext'] = '(?:' . $this->_grammar['NO-WS-CTL'] .
'|[\x21\x23-\x5B\x5D-\x7E])';
$this->_grammar['qcontent'] = '(?:' . $this->_grammar['qtext'] . '|' .
$this->_grammar['quoted-pair'] . ')';
$this->_grammar['quoted-string'] = '(?:' . $this->_grammar['CFWS'] . '?"' .
'(' . $this->_grammar['FWS'] . '?' . $this->_grammar['qcontent'] . ')*' .
$this->_grammar['FWS'] . '?"' . $this->_grammar['CFWS'] . '?)';
$this->_grammar['atext'] = '[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]';
$this->_grammar['atom'] = '(?:' . $this->_grammar['CFWS'] . '?' .
$this->_grammar['atext'] . '+' . $this->_grammar['CFWS'] . '?)';
$this->_grammar['dot-atom-text'] = '(?:' . $this->_grammar['atext'] . '+' .
'(\.' . $this->_grammar['atext'] . '+)*)';
$this->_grammar['dot-atom'] = '(?:' . $this->_grammar['CFWS'] . '?' .
$this->_grammar['dot-atom-text'] . '+' . $this->_grammar['CFWS'] . '?)';
$this->_grammar['word'] = '(?:' . $this->_grammar['atom'] . '|' .
$this->_grammar['quoted-string'] . ')';
$this->_grammar['phrase'] = '(?:' . $this->_grammar['word'] . '+?)';
$this->_grammar['no-fold-quote'] = '(?:"(?:' . $this->_grammar['qtext'] .
'|' . $this->_grammar['quoted-pair'] . ')*")';
$this->_grammar['dtext'] = '(?:' . $this->_grammar['NO-WS-CTL'] .
'|[\x21-\x5A\x5E-\x7E])';
$this->_grammar['no-fold-literal'] = '(?:\[(?:' . $this->_grammar['dtext'] .
'|' . $this->_grammar['quoted-pair'] . ')*\])';
//Message IDs
$this->_grammar['id-left'] = '(?:' . $this->_grammar['dot-atom-text'] . '|' .
$this->_grammar['no-fold-quote'] . ')';
$this->_grammar['id-right'] = '(?:' . $this->_grammar['dot-atom-text'] . '|' .
$this->_grammar['no-fold-literal'] . ')';
//Addresses, mailboxes and paths
$this->_grammar['local-part'] = '(?:' . $this->_grammar['dot-atom'] . '|' .
$this->_grammar['quoted-string'] . ')';
$this->_grammar['dcontent'] = '(?:' . $this->_grammar['dtext'] . '|' .
$this->_grammar['quoted-pair'] . ')';
$this->_grammar['domain-literal'] = '(?:' . $this->_grammar['CFWS'] . '?\[(' .
$this->_grammar['FWS'] . '?' . $this->_grammar['dcontent'] . ')*?' .
$this->_grammar['FWS'] . '?\]' . $this->_grammar['CFWS'] . '?)';
$this->_grammar['domain'] = '(?:' . $this->_grammar['dot-atom'] . '|' .
$this->_grammar['domain-literal'] . ')';
$this->_grammar['addr-spec'] = '(?:' . $this->_grammar['local-part'] . '@' .
$this->_grammar['domain'] . ')';
}
/**
* Get the grammar defined for $name token.
* @param string $name execatly as written in the RFC
* @return string
*/
protected function getGrammar($name)
{
if (array_key_exists($name, $this->_grammar))
{
return $this->_grammar[$name];
}
else
{
throw new Swift_RfcComplianceException(
"No such grammar '" . $name . "' defined."
);
}
}
/**
* Escape special characters in a string (convert to quoted-pairs).
* @param string $token
* @param string[] $include additonal chars to escape
* @param string[] $exclude chars from escaping
* @return string
*/
protected function escapeSpecials($token, $include = array(),
$exclude = array())
{
foreach (
array_merge(array('\\'), array_diff($this->_specials, $exclude), $include) as $char)
{
$token = str_replace($char, '\\' . $char, $token);
}
return $token;
}
/**
* Produces a compliant, formatted RFC 2822 'phrase' based on the string given.
* @param Swift_Mime_Header $header
* @param string $string as displayed
* @param string $charset of the text
* @param Swift_Mime_HeaderEncoder $encoder
* @param boolean $shorten the first line to make remove for header name
* @return string
*/
protected function createPhrase(Swift_Mime_Header $header, $string, $charset,
Swift_Mime_HeaderEncoder $encoder = null, $shorten = false)
{
//Treat token as exactly what was given
$phraseStr = $string;
//If it's not valid
if (!preg_match('/^' . $this->_grammar['phrase'] . '$/D', $phraseStr))
{
// .. but it is just ascii text, try escaping some characters
// and make it a quoted-string
if (preg_match('/^' . $this->_grammar['text'] . '*$/D', $phraseStr))
{
$phraseStr = $this->escapeSpecials(
$phraseStr, array('"'), $this->_specials
);
$phraseStr = '"' . $phraseStr . '"';
}
else // ... otherwise it needs encoding
{
//Determine space remaining on line if first line
if ($shorten)
{
$usedLength = strlen($header->getFieldName() . ': ');
}
else
{
$usedLength = 0;
}
$phraseStr = $this->encodeWords($header, $string, $usedLength);
}
}
return $phraseStr;
}
/**
* Encode needed word tokens within a string of input.
* @param string $input
* @param string $usedLength, optional
* @return string
*/
protected function encodeWords(Swift_Mime_Header $header, $input,
$usedLength = -1)
{
$value = '';
$tokens = $this->getEncodableWordTokens($input);
foreach ($tokens as $token)
{
//See RFC 2822, Sect 2.2 (really 2.2 ??)
if ($this->tokenNeedsEncoding($token))
{
//Don't encode starting WSP
$firstChar = substr($token, 0, 1);
switch($firstChar)
{
case ' ':
case "\t":
$value .= $firstChar;
$token = substr($token, 1);
}
if (-1 == $usedLength)
{
$usedLength = strlen($header->getFieldName() . ': ') + strlen($value);
}
$value .= $this->getTokenAsEncodedWord($token, $usedLength);
$header->setMaxLineLength(76); //Forefully override
}
else
{
$value .= $token;
}
}
return $value;
}
/**
* Test if a token needs to be encoded or not.
* @param string $token
* @return boolean
*/
protected function tokenNeedsEncoding($token)
{
return preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token);
}
/**
* Splits a string into tokens in blocks of words which can be encoded quickly.
* @param string $string
* @return string[]
*/
protected function getEncodableWordTokens($string)
{
$tokens = array();
$encodedToken = '';
//Split at all whitespace boundaries
foreach (preg_split('~(?=[\t ])~', $string) as $token)
{
if ($this->tokenNeedsEncoding($token))
{
$encodedToken .= $token;
}
else
{
if (strlen($encodedToken) > 0)
{
$tokens[] = $encodedToken;
$encodedToken = '';
}
$tokens[] = $token;
}
}
if (strlen($encodedToken))
{
$tokens[] = $encodedToken;
}
return $tokens;
}
/**
* Get a token as an encoded word for safe insertion into headers.
* @param string $token to encode
* @param int $firstLineOffset, optional
* @return string
*/
protected function getTokenAsEncodedWord($token, $firstLineOffset = 0)
{
//Adjust $firstLineOffset to account for space needed for syntax
$charsetDecl = $this->_charset;
if (isset($this->_lang))
{
$charsetDecl .= '*' . $this->_lang;
}
$encodingWrapperLength = strlen(
'=?' . $charsetDecl . '?' . $this->_encoder->getName() . '??='
);
if ($firstLineOffset >= 75) //Does this logic need to be here?
{
$firstLineOffset = 0;
}
$encodedTextLines = explode("\r\n",
$this->_encoder->encodeString(
$token, $firstLineOffset, 75 - $encodingWrapperLength
)
);
foreach ($encodedTextLines as $lineNum => $line)
{
$encodedTextLines[$lineNum] = '=?' . $charsetDecl .
'?' . $this->_encoder->getName() .
'?' . $line . '?=';
}
return implode("\r\n ", $encodedTextLines);
}
/**
* Generates tokens from the given string which include CRLF as individual tokens.
* @param string $token
* @return string[]
* @access protected
*/
protected function generateTokenLines($token)
{
return preg_split('~(\r\n)~', $token, -1, PREG_SPLIT_DELIM_CAPTURE);
}
/**
* Set a value into the cache.
* @param string $value
* @access protected
*/
protected function setCachedValue($value)
{
$this->_cachedValue = $value;
}
/**
* Get the value in the cache.
* @return string
* @access protected
*/
protected function getCachedValue()
{
return $this->_cachedValue;
}
/**
* Clear the cached value if $condition is met.
* @param boolean $condition
* @access protected
*/
protected function clearCachedValueIf($condition)
{
if ($condition)
{
$this->setCachedValue(null);
}
}
// -- Private methods
/**
* Generate a list of all tokens in the final header.
* @param string $string input, optional
* @return string[]
* @access private
*/
protected function toTokens($string = null)
{
if (is_null($string))
{
$string = $this->getFieldBody();
}
$tokens = array();
//Generate atoms; split at all invisible boundaries followed by WSP
foreach (preg_split('~(?=[ \t])~', $string) as $token)
{
$tokens = array_merge($tokens, $this->generateTokenLines($token));
}
return $tokens;
}
/**
* Takes an array of tokens which appear in the header and turns them into
* an RFC 2822 compliant string, adding FWSP where needed.
* @param string[] $tokens
* @return string
* @access private
*/
private function _tokensToString(array $tokens)
{
$lineCount = 0;
$headerLines = array();
$headerLines[] = $this->_name . ': ';
$currentLine =& $headerLines[$lineCount++];
//Build all tokens back into compliant header
foreach ($tokens as $i => $token)
{
//Line longer than specified maximum or token was just a new line
if (("\r\n" == $token) ||
($i > 0 && strlen($currentLine . $token) > $this->_lineLength)
&& 0 < strlen($currentLine))
{
$headerLines[] = '';
$currentLine =& $headerLines[$lineCount++];
}
//Append token to the line
if ("\r\n" != $token)
{
$currentLine .= $token;
}
}
//Implode with FWS (RFC 2822, 2.2.3)
return implode("\r\n", $headerLines) . "\r\n";
}
}

View File

@@ -0,0 +1,118 @@
<?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.
*/
//@require 'Swift/Mime/Headers/AbstractHeader.php';
/**
* A Date MIME Header for Swift Mailer.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The UNIX timestamp value of this Header.
* @var int
* @access private
*/
private $_timestamp;
/**
* Creates a new DateHeader with $name and $timestamp.
* Example:
* <code>
* <?php
* $header = new Swift_Mime_Headers_DateHeader('Date', time());
* ?>
* </code>
* @param string $name of Header
*/
public function __construct($name)
{
$this->setFieldName($name);
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_DATE;
}
/**
* Set the model for the field body.
* This method takes a UNIX timestamp.
* @param int $model
*/
public function setFieldBodyModel($model)
{
$this->setTimestamp($model);
}
/**
* Get the model for the field body.
* This method returns a UNIX timestamp.
* @return mixed
*/
public function getFieldBodyModel()
{
return $this->getTimestamp();
}
/**
* Get the UNIX timestamp of the Date in this Header.
* @return int
*/
public function getTimestamp()
{
return $this->_timestamp;
}
/**
* Set the UNIX timestamp of the Date in this Header.
* @param int $timestamp
*/
public function setTimestamp($timestamp)
{
if (!is_null($timestamp))
{
$timestamp = (int) $timestamp;
}
$this->clearCachedValueIf($this->_timestamp != $timestamp);
$this->_timestamp = $timestamp;
}
/**
* Get the string value of the body in this Header.
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
* @return string
* @see toString()
*/
public function getFieldBody()
{
if (!$this->getCachedValue())
{
if (isset($this->_timestamp))
{
$this->setCachedValue(date('r', $this->_timestamp));
}
}
return $this->getCachedValue();
}
}

View File

@@ -0,0 +1,161 @@
<?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.
*/
//@require 'Swift/Mime/Headers/AbstractHeader.php';
//@require 'Swift/RfcComplianceException.php';
/**
* An ID MIME Header for something like Message-ID or Content-ID.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_Headers_IdentificationHeader
extends Swift_Mime_Headers_AbstractHeader
{
/**
* The IDs used in the value of this Header.
* This may hold multiple IDs or just a single ID.
* @var string[]
* @access private
*/
private $_ids = array();
/**
* Creates a new IdentificationHeader with the given $name and $id.
* @param string $name
*/
public function __construct($name)
{
$this->setFieldName($name);
$this->initializeGrammar();
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_ID;
}
/**
* Set the model for the field body.
* This method takes a string ID, or an array of IDs
* @param mixed $model
* @throws Swift_RfcComplianceException
*/
public function setFieldBodyModel($model)
{
$this->setId($model);
}
/**
* Get the model for the field body.
* This method returns an array of IDs
* @return array
*/
public function getFieldBodyModel()
{
return $this->getIds();
}
/**
* Set the ID used in the value of this header.
* @param string $id
* @throws Swift_RfcComplianceException
*/
public function setId($id)
{
return $this->setIds(array($id));
}
/**
* Get the ID used in the value of this Header.
* If multiple IDs are set only the first is returned.
* @return string
*/
public function getId()
{
if (count($this->_ids) > 0)
{
return $this->_ids[0];
}
}
/**
* Set a collection of IDs to use in the value of this Header.
* @param string[] $ids
* @throws Swift_RfcComplianceException
*/
public function setIds(array $ids)
{
$actualIds = array();
foreach ($ids as $k => $id)
{
if (preg_match(
'/^' . $this->getGrammar('id-left') . '@' .
$this->getGrammar('id-right') . '$/D',
$id
))
{
$actualIds[] = $id;
}
else
{
throw new Swift_RfcComplianceException(
'Invalid ID given <' . $id . '>'
);
}
}
$this->clearCachedValueIf($this->_ids != $actualIds);
$this->_ids = $actualIds;
}
/**
* Get the list of IDs used in this Header.
* @return string[]
*/
public function getIds()
{
return $this->_ids;
}
/**
* Get the string value of the body in this Header.
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
* @return string
* @see toString()
* @throws Swift_RfcComplianceException
*/
public function getFieldBody()
{
if (!$this->getCachedValue())
{
$angleAddrs = array();
foreach ($this->_ids as $id)
{
$angleAddrs[] = '<' . $id . '>';
}
$this->setCachedValue(implode(' ', $angleAddrs));
}
return $this->getCachedValue();
}
}

View File

@@ -0,0 +1,316 @@
<?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.
*/
//@require 'Swift/Mime/Headers/AbstractHeader.php';
//@require 'Swift/Mime/HeaderEncoder.php';
/**
* A Mailbox Address MIME Header for something like From or Sender.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_Headers_MailboxHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The mailboxes used in this Header.
* @var string[]
* @access private
*/
private $_mailboxes = array();
/**
* Creates a new MailboxHeader with $name.
* @param string $name of Header
* @param Swift_Mime_HeaderEncoder $encoder
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder)
{
$this->setFieldName($name);
$this->setEncoder($encoder);
$this->initializeGrammar();
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_MAILBOX;
}
/**
* Set the model for the field body.
* This method takes a string, or an array of addresses.
* @param mixed $model
* @throws Swift_RfcComplianceException
*/
public function setFieldBodyModel($model)
{
$this->setNameAddresses($model);
}
/**
* Get the model for the field body.
* This method returns an associative array like {@link getNameAddresses()}
* @return array
* @throws Swift_RfcComplianceException
*/
public function getFieldBodyModel()
{
return $this->getNameAddresses();
}
/**
* Set a list of mailboxes to be shown in this Header.
* The mailboxes can be a simple array of addresses, or an array of
* key=>value pairs where (email => personalName).
* Example:
* <code>
* <?php
* //Sets two mailboxes in the Header, one with a personal name
* $header->setNameAddresses(array(
* 'chris@swiftmailer.org' => 'Chris Corbyn',
* 'mark@swiftmailer.org' //No associated personal name
* ));
* ?>
* </code>
* @param string|string[] $mailboxes
* @throws Swift_RfcComplianceException
* @see __construct()
* @see setAddresses()
* @see setValue()
*/
public function setNameAddresses($mailboxes)
{
$this->_mailboxes = $this->normalizeMailboxes((array) $mailboxes);
$this->setCachedValue(null); //Clear any cached value
}
/**
* Get the full mailbox list of this Header as an array of valid RFC 2822 strings.
* Example:
* <code>
* <?php
* $header = new Swift_Mime_Headers_MailboxHeader('From',
* array('chris@swiftmailer.org' => 'Chris Corbyn',
* 'mark@swiftmailer.org' => 'Mark Corbyn')
* );
* print_r($header->getNameAddressStrings());
* // array (
* // 0 => Chris Corbyn <chris@swiftmailer.org>,
* // 1 => Mark Corbyn <mark@swiftmailer.org>
* // )
* ?>
* </code>
* @return string[]
* @throws Swift_RfcComplianceException
* @see getNameAddresses()
* @see toString()
*/
public function getNameAddressStrings()
{
return $this->_createNameAddressStrings($this->getNameAddresses());
}
/**
* Get all mailboxes in this Header as key=>value pairs.
* The key is the address and the value is the name (or null if none set).
* Example:
* <code>
* <?php
* $header = new Swift_Mime_Headers_MailboxHeader('From',
* array('chris@swiftmailer.org' => 'Chris Corbyn',
* 'mark@swiftmailer.org' => 'Mark Corbyn')
* );
* print_r($header->getNameAddresses());
* // array (
* // chris@swiftmailer.org => Chris Corbyn,
* // mark@swiftmailer.org => Mark Corbyn
* // )
* ?>
* </code>
* @return string[]
* @see getAddresses()
* @see getNameAddressStrings()
*/
public function getNameAddresses()
{
return $this->_mailboxes;
}
/**
* Makes this Header represent a list of plain email addresses with no names.
* Example:
* <code>
* <?php
* //Sets three email addresses as the Header data
* $header->setAddresses(
* array('one@domain.tld', 'two@domain.tld', 'three@domain.tld')
* );
* ?>
* </code>
* @param string[] $addresses
* @throws Swift_RfcComplianceException
* @see setNameAddresses()
* @see setValue()
*/
public function setAddresses($addresses)
{
return $this->setNameAddresses(array_values((array) $addresses));
}
/**
* Get all email addresses in this Header.
* @return string[]
* @see getNameAddresses()
*/
public function getAddresses()
{
return array_keys($this->_mailboxes);
}
/**
* Remove one or more addresses from this Header.
* @param string|string[] $addresses
*/
public function removeAddresses($addresses)
{
$this->setCachedValue(null);
foreach ((array) $addresses as $address)
{
unset($this->_mailboxes[$address]);
}
}
/**
* Get the string value of the body in this Header.
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
* @return string
* @throws Swift_RfcComplianceException
* @see toString()
*/
public function getFieldBody()
{
//Compute the string value of the header only if needed
if (is_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.
* @param string[] $mailboxes
* @return string[]
* @access protected
*/
protected function normalizeMailboxes(array $mailboxes)
{
$actualMailboxes = array();
foreach ($mailboxes as $key => $value)
{
if (is_string($key)) //key is email addr
{
$address = $key;
$name = $value;
}
else
{
$address = $value;
$name = null;
}
$this->_assertValidAddress($address);
$actualMailboxes[$address] = $name;
}
return $actualMailboxes;
}
/**
* Produces a compliant, formatted display-name based on the string given.
* @param string $displayName as displayed
* @param boolean $shorten the first line to make remove for header name
* @return string
* @access protected
*/
protected function createDisplayNameString($displayName, $shorten = false)
{
return $this->createPhrase($this, $displayName,
$this->getCharset(), $this->getEncoder(), $shorten
);
}
/**
* Creates a string form of all the mailboxes in the passed array.
* @param string[] $mailboxes
* @return string
* @throws Swift_RfcComplianceException
* @access protected
*/
protected function createMailboxListString(array $mailboxes)
{
return implode(', ', $this->_createNameAddressStrings($mailboxes));
}
// -- Private methods
/**
* Return an array of strings conforming the the name-addr spec of RFC 2822.
* @param string[] $mailboxes
* @return string[]
* @access private
*/
private function _createNameAddressStrings(array $mailboxes)
{
$strings = array();
foreach ($mailboxes as $email => $name)
{
$mailboxStr = $email;
if (!is_null($name))
{
$nameStr = $this->createDisplayNameString($name, empty($strings));
$mailboxStr = $nameStr . ' <' . $mailboxStr . '>';
}
$strings[] = $mailboxStr;
}
return $strings;
}
/**
* Throws an Exception if the address passed does not comply with RFC 2822.
* @param string $address
* @throws Exception If invalid.
* @access protected
*/
private function _assertValidAddress($address)
{
if (!preg_match('/^' . $this->getGrammar('addr-spec') . '$/D',
$address))
{
throw new Swift_RfcComplianceException(
'Address in mailbox given [' . $address .
'] does not comply with RFC 2822, 3.6.2.'
);
}
}
}

View File

@@ -0,0 +1,274 @@
<?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.
*/
//@require 'Swift/Mime/Headers/UnstructuredHeader.php';
//@require 'Swift/Mime/HeaderEncoder.php';
//@require 'Swift/Mime/ParameterizedHeader.php';
//@require 'Swift/Encoder.php';
/**
* An abstract base MIME Header.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_Headers_ParameterizedHeader
extends Swift_Mime_Headers_UnstructuredHeader
implements Swift_Mime_ParameterizedHeader
{
/**
* The Encoder used to encode the parameters.
* @var Swift_Encoder
* @access private
*/
private $_paramEncoder;
/**
* The parameters as an associative array.
* @var string[]
* @access private
*/
private $_params = array();
/**
* RFC 2231's definition of a token.
* @var string
* @access private
*/
private $_tokenRe;
/**
* Creates a new ParameterizedHeader with $name.
* @param string $name
* @param Swift_Mime_HeaderEncoder $encoder
* @param Swift_Encoder $paramEncoder, optional
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder,
Swift_Encoder $paramEncoder = null)
{
$this->setFieldName($name);
$this->setEncoder($encoder);
$this->_paramEncoder = $paramEncoder;
$this->initializeGrammar();
$this->_tokenRe = '(?:[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7E]+)';
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_PARAMETERIZED;
}
/**
* Set the character set used in this Header.
* @param string $charset
*/
public function setCharset($charset)
{
parent::setCharset($charset);
if (isset($this->_paramEncoder))
{
$this->_paramEncoder->charsetChanged($charset);
}
}
/**
* Set the value of $parameter.
* @param string $parameter
* @param string $value
*/
public function setParameter($parameter, $value)
{
$this->setParameters(array_merge($this->getParameters(), array($parameter => $value)));
}
/**
* Get the value of $parameter.
* @return string
*/
public function getParameter($parameter)
{
$params = $this->getParameters();
return array_key_exists($parameter, $params)
? $params[$parameter]
: null;
}
/**
* Set an associative array of parameter names mapped to values.
* @param string[]
*/
public function setParameters(array $parameters)
{
$this->clearCachedValueIf($this->_params != $parameters);
$this->_params = $parameters;
}
/**
* Returns an associative array of parameter names mapped to values.
* @return string[]
*/
public function getParameters()
{
return $this->_params;
}
/**
* Get the value of this header prepared for rendering.
* @return string
*/
public function getFieldBody() //TODO: Check caching here
{
$body = parent::getFieldBody();
foreach ($this->_params as $name => $value)
{
if (!is_null($value))
{
//Add the parameter
$body .= '; ' . $this->_createParameter($name, $value);
}
}
return $body;
}
// -- Protected methods
/**
* Generate a list of all tokens in the final header.
* This doesn't need to be overridden in theory, but it is for implementation
* reasons to prevent potential breakage of attributes.
* @return string[]
* @access protected
*/
protected function toTokens($string = null)
{
$tokens = parent::toTokens(parent::getFieldBody());
//Try creating any parameters
foreach ($this->_params as $name => $value)
{
if (!is_null($value))
{
//Add the semi-colon separator
$tokens[count($tokens)-1] .= ';';
$tokens = array_merge($tokens, $this->generateTokenLines(
' ' . $this->_createParameter($name, $value)
));
}
}
return $tokens;
}
// -- Private methods
/**
* Render a RFC 2047 compliant header parameter from the $name and $value.
* @param string $name
* @param string $value
* @return string
* @access private
*/
private function _createParameter($name, $value)
{
$origValue = $value;
$encoded = false;
//Allow room for parameter name, indices, "=" and DQUOTEs
$maxValueLength = $this->getMaxLineLength() - strlen($name . '=*N"";') - 1;
$firstLineOffset = 0;
//If it's not already a valid parameter value...
if (!preg_match('/^' . $this->_tokenRe . '$/D', $value))
{
//TODO: text, or something else??
//... and it's not ascii
if (!preg_match('/^' . $this->getGrammar('text') . '*$/D', $value))
{
$encoded = true;
//Allow space for the indices, charset and language
$maxValueLength = $this->getMaxLineLength() - strlen($name . '*N*="";') - 1;
$firstLineOffset = strlen(
$this->getCharset() . "'" . $this->getLanguage() . "'"
);
}
}
//Encode if we need to
if ($encoded || strlen($value) > $maxValueLength)
{
if (isset($this->_paramEncoder))
{
$value = $this->_paramEncoder->encodeString(
$origValue, $firstLineOffset, $maxValueLength
);
}
else //We have to go against RFC 2183/2231 in some areas for interoperability
{
$value = $this->getTokenAsEncodedWord($origValue);
$encoded = false;
}
}
$valueLines = isset($this->_paramEncoder) ? explode("\r\n", $value) : array($value);
//Need to add indices
if (count($valueLines) > 1)
{
$paramLines = array();
foreach ($valueLines as $i => $line)
{
$paramLines[] = $name . '*' . $i .
$this->_getEndOfParameterValue($line, $encoded, $i == 0);
}
return implode(";\r\n ", $paramLines);
}
else
{
return $name . $this->_getEndOfParameterValue(
$valueLines[0], $encoded, true
);
}
}
/**
* Returns the parameter value from the "=" and beyond.
* @param string $value to append
* @param boolean $encoded
* @param boolean $firstLine
* @return string
* @access private
*/
private function _getEndOfParameterValue($value, $encoded = false, $firstLine = false)
{
if (!preg_match('/^' . $this->_tokenRe . '$/D', $value))
{
$value = '"' . $value . '"';
}
$prepend = '=';
if ($encoded)
{
$prepend = '*=';
if ($firstLine)
{
$prepend = '*=' . $this->getCharset() . "'" . $this->getLanguage() .
"'";
}
}
return $prepend . $value;
}
}

View File

@@ -0,0 +1,126 @@
<?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.
*/
//@require 'Swift/Mime/Headers/AbstractHeader.php';
//@require 'Swift/RfcComplianceException.php';
/**
* A Path Header in Swift Mailer, such a Return-Path.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The address in this Header (if specified).
* @var string
* @access private
*/
private $_address;
/**
* Creates a new PathHeader with the given $name.
* @param string $name
*/
public function __construct($name)
{
$this->setFieldName($name);
$this->initializeGrammar();
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_PATH;
}
/**
* Set the model for the field body.
* This method takes a string for an address.
* @param string $model
* @throws Swift_RfcComplianceException
*/
public function setFieldBodyModel($model)
{
$this->setAddress($model);
}
/**
* Get the model for the field body.
* This method returns a string email address.
* @return mixed
*/
public function getFieldBodyModel()
{
return $this->getAddress();
}
/**
* Set the Address which should appear in this Header.
* @param string $address
* @throws Swift_RfcComplianceException
*/
public function setAddress($address)
{
if (is_null($address))
{
$this->_address = null;
}
elseif ('' == $address
|| preg_match('/^' . $this->getGrammar('addr-spec') . '$/D', $address))
{
$this->_address = $address;
}
else
{
throw new Swift_RfcComplianceException(
'Address set in PathHeader does not comply with addr-spec of RFC 2822.'
);
}
$this->setCachedValue(null);
}
/**
* Get the address which is used in this Header (if any).
* Null is returned if no address is set.
* @return string
*/
public function getAddress()
{
return $this->_address;
}
/**
* Get the string value of the body in this Header.
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@link toString()} for that).
* @return string
* @see toString()
*/
public function getFieldBody()
{
if (!$this->getCachedValue())
{
if (isset($this->_address))
{
$this->setCachedValue('<' . $this->_address . '>');
}
}
return $this->getCachedValue();
}
}

View File

@@ -0,0 +1,108 @@
<?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.
*/
//@require 'Swift/Mime/Headers/AbstractHeader.php';
//@require 'Swift/Mime/HeaderEncoder.php';
/**
* A Simple MIME Header.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_Headers_UnstructuredHeader
extends Swift_Mime_Headers_AbstractHeader
{
/**
* The value of this Header.
* @var string
* @access private
*/
private $_value;
/**
* Creates a new SimpleHeader with $name.
* @param string $name
* @param Swift_Mime_HeaderEncoder $encoder
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder)
{
$this->setFieldName($name);
$this->setEncoder($encoder);
}
/**
* Get the type of Header that this instance represents.
* @return int
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*/
public function getFieldType()
{
return self::TYPE_TEXT;
}
/**
* Set the model for the field body.
* This method takes a string for the field value.
* @param string $model
*/
public function setFieldBodyModel($model)
{
$this->setValue($model);
}
/**
* Get the model for the field body.
* This method returns a string.
* @return string
*/
public function getFieldBodyModel()
{
return $this->getValue();
}
/**
* Get the (unencoded) value of this header.
* @return string
*/
public function getValue()
{
return $this->_value;
}
/**
* Set the (unencoded) value of this header.
* @param string $value
*/
public function setValue($value)
{
$this->clearCachedValueIf($this->_value != $value);
$this->_value = $value;
}
/**
* Get the value of this header prepared for rendering.
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue())
{
$this->setCachedValue(
str_replace('\\', '\\\\', $this->encodeWords(
$this, $this->_value, -1, $this->getCharset(), $this->getEncoder()
))
);
}
return $this->getCachedValue();
}
}

View File

@@ -0,0 +1,230 @@
<?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.
*/
//@require 'Swift/Mime/MimeEntity.php';
/**
* A Message (RFC 2822) object.
*
* @package Swift
* @subpackage Mime
*
* @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

@@ -0,0 +1,108 @@
<?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.
*/
//@require 'Swift/InputByteStream.php';
//@require 'Swift/Mime/EncodingObserver.php';
//@require 'Swift/Mime/CharsetObserver.php';
/**
* A MIME entity, such as an attachment.
* @package Swift
* @subpackage Mime
* @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.
* @return int
* @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE
*/
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_Header[]
*/
public function getHeaders();
/**
* Get the body content of this entity as a string.
* Returns NULL if no body has been set.
* @return string
*/
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

@@ -0,0 +1,196 @@
<?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.
*/
//@require 'Swift/Mime/SimpleMimeEntity.php';
//@require 'Swift/Mime/ContentEncoder.php';
//@require 'Swift/Mime/HeaderSet.php';
//@require 'Swift/KeyCache.php';
/**
* A MIME part, in a multipart message.
*
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
{
/** The format parameter last specified by the user */
protected $_userFormat;
/** The charset last specified by the user */
protected $_userCharset;
/** The delsp parameter last specified by the user */
protected $_userDelSp;
/** The nesting level of this MimePart */
private $_nestingLevel = self::LEVEL_ALTERNATIVE;
/**
* Create a new MimePart with $headers, $encoder and $cache.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderSet $headers,
Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, $charset = null)
{
parent::__construct($headers, $encoder, $cache);
$this->setContentType('text/plain');
if (!is_null($charset))
{
$this->setCharset($charset);
}
}
/**
* Set the body of this entity, either as a string, or as an instance of
* {@link Swift_OutputByteStream}.
*
* @param mixed $body
* @param string $contentType optional
* @param string $charset optional
*/
public function setBody($body, $contentType = null, $charset = null)
{
parent::setBody($body, $contentType);
if (isset($charset))
{
$this->setCharset($charset);
}
return $this;
}
/**
* Get the character set of this entity.
*
* @return string
*/
public function getCharset()
{
return $this->_getHeaderParameter('Content-Type', 'charset');
}
/**
* Set the character set of this entity.
*
* @param string $charset
*/
public function setCharset($charset)
{
$this->_setHeaderParameter('Content-Type', 'charset', $charset);
if ($charset !== $this->_userCharset)
{
$this->_clearCache();
}
$this->_userCharset = $charset;
parent::charsetChanged($charset);
return $this;
}
/**
* Get the format of this entity (i.e. flowed or fixed).
*
* @return string
*/
public function getFormat()
{
return $this->_getHeaderParameter('Content-Type', 'format');
}
/**
* Set the format of this entity (flowed or fixed).
*
* @param string $format
*/
public function setFormat($format)
{
$this->_setHeaderParameter('Content-Type', 'format', $format);
$this->_userFormat = $format;
return $this;
}
/**
* Test if delsp is being used for this entity.
*
* @return boolean
*/
public function getDelSp()
{
return ($this->_getHeaderParameter('Content-Type', 'delsp') == 'yes')
? true
: false;
}
/**
* Turn delsp on or off for this entity.
*
* @param boolean $delsp
*/
public function setDelSp($delsp = true)
{
$this->_setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null);
$this->_userDelSp = $delsp;
return $this;
}
/**
* Get the nesting level of this entity.
*
* @return int
* @see LEVEL_TOP, LEVEL_ALTERNATIVE, LEVEL_MIXED, LEVEL_RELATED
*/
public function getNestingLevel()
{
return $this->_nestingLevel;
}
/**
* Receive notification that the charset has changed on this document, or a
* parent document.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->setCharset($charset);
}
// -- Protected methods
/** Fix the content-type and encoding of this entity */
protected function _fixHeaders()
{
parent::_fixHeaders();
if (count($this->getChildren()))
{
$this->_setHeaderParameter('Content-Type', 'charset', null);
$this->_setHeaderParameter('Content-Type', 'format', null);
$this->_setHeaderParameter('Content-Type', 'delsp', null);
}
else
{
$this->setCharset($this->_userCharset);
$this->setFormat($this->_userFormat);
$this->setDelSp($this->_userDelSp);
}
}
/** Set the nesting level of this entity */
protected function _setNestingLevel($level)
{
$this->_nestingLevel = $level;
}
}

View File

@@ -0,0 +1,35 @@
<?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.
*/
//@require 'Swift/Mime/Header.php';
/**
* A MIME Header with parameters.
* @package Swift
* @subpackage Mime
* @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.
* @return string
*/
public function getParameter($parameter);
}

View File

@@ -0,0 +1,187 @@
<?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.
*/
//@require 'Swift/Mime/HeaderFactory.php';
//@require 'Swift/Mime/HeaderEncoder.php';
//@require 'Swift/Encoder.php';
//@require 'Swift/Mime/Headers/MailboxHeader.php';
//@require 'Swift/Mime/Headers/DateHeader.php';
//@require 'Swift/Mime/Headers/UnstructuredHeader.php';
//@require 'Swift/Mime/Headers/ParameterizedHeader.php';
//@require 'Swift/Mime/Headers/IdentificationHeader.php';
//@require 'Swift/Mime/Headers/PathHeader.php';
/**
* Creates MIME headers.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
{
/** The HeaderEncoder used by these headers */
private $_encoder;
/** The Encoder used by parameters */
private $_paramEncoder;
/** The charset of created Headers */
private $_charset;
/**
* Creates a new SimpleHeaderFactory using $encoder and $paramEncoder.
* @param Swift_Mime_HeaderEncoder $encoder
* @param Swift_Encoder $paramEncoder
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderEncoder $encoder,
Swift_Encoder $paramEncoder, $charset = null)
{
$this->_encoder = $encoder;
$this->_paramEncoder = $paramEncoder;
$this->_charset = $charset;
}
/**
* 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)
{
$header = new Swift_Mime_Headers_MailboxHeader($name, $this->_encoder);
if (isset($addresses))
{
$header->setFieldBodyModel($addresses);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* 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)
{
$header = new Swift_Mime_Headers_DateHeader($name);
if (isset($timestamp))
{
$header->setFieldBodyModel($timestamp);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new basic text header with $name and $value.
* @param string $name
* @param string $value
* @return Swift_Mime_Header
*/
public function createTextHeader($name, $value = null)
{
$header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->_encoder);
if (isset($value))
{
$header->setFieldBodyModel($value);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new ParameterizedHeader with $name, $value and $params.
* @param string $name
* @param string $value
* @param array $params
* @return Swift_Mime_ParameterizedHeader
*/
public function createParameterizedHeader($name, $value = null,
$params = array())
{
$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);
return $header;
}
/**
* Create a new ID header for Message-ID or Content-ID.
* @param string $name
* @param string|array $ids
* @return Swift_Mime_Header
*/
public function createIdHeader($name, $ids = null)
{
$header = new Swift_Mime_Headers_IdentificationHeader($name);
if (isset($ids))
{
$header->setFieldBodyModel($ids);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new Path header with an address (path) in it.
* @param string $name
* @param string $path
* @return Swift_Mime_Header
*/
public function createPathHeader($name, $path = null)
{
$header = new Swift_Mime_Headers_PathHeader($name);
if (isset($path))
{
$header->setFieldBodyModel($path);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Notify this observer that the entity's charset has changed.
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->_charset = $charset;
$this->_encoder->charsetChanged($charset);
$this->_paramEncoder->charsetChanged($charset);
}
// -- Private methods
/** Apply the charset to the Header */
private function _setHeaderCharset(Swift_Mime_Header $header)
{
if (isset($this->_charset))
{
$header->setCharset($this->_charset);
}
}
}

View File

@@ -0,0 +1,396 @@
<?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.
*/
//@require 'Swift/Mime/HeaderSet.php';
//@require 'Swift/Mime/HeaderFactory.php';
/**
* A collection of MIME headers.
*
* @package Swift
* @subpackage Mime
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleHeaderSet implements Swift_Mime_HeaderSet
{
/** HeaderFactory */
private $_factory;
/** Collection of set Headers */
private $_headers = array();
/** Field ordering details */
private $_order = array();
/** List of fields which are required to be displayed */
private $_required = array();
/** The charset used by Headers */
private $_charset;
/**
* Create a new SimpleHeaderSet with the given $factory.
*
* @param Swift_Mime_HeaderFactory $factory
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderFactory $factory,
$charset = null)
{
$this->_factory = $factory;
if (isset($charset))
{
$this->setCharset($charset);
}
}
/**
* Set the charset used by these headers.
*
* @param string $charset
*/
public function setCharset($charset)
{
$this->_charset = $charset;
$this->_factory->charsetChanged($charset);
$this->_notifyHeadersOfCharset($charset);
}
/**
* Add a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string $addresses
*/
public function addMailboxHeader($name, $addresses = null)
{
$this->_storeHeader($name,
$this->_factory->createMailboxHeader($name, $addresses));
}
/**
* Add a new Date header using $timestamp (UNIX time).
*
* @param string $name
* @param int $timestamp
*/
public function addDateHeader($name, $timestamp = null)
{
$this->_storeHeader($name,
$this->_factory->createDateHeader($name, $timestamp));
}
/**
* Add a new basic text header with $name and $value.
*
* @param string $name
* @param string $value
*/
public function addTextHeader($name, $value = null)
{
$this->_storeHeader($name,
$this->_factory->createTextHeader($name, $value));
}
/**
* Add a new ParameterizedHeader with $name, $value and $params.
*
* @param string $name
* @param string $value
* @param array $params
*/
public function addParameterizedHeader($name, $value = null,
$params = array())
{
$this->_storeHeader($name,
$this->_factory->createParameterizedHeader($name, $value,
$params));
}
/**
* Add a new ID header for Message-ID or Content-ID.
*
* @param string $name
* @param string|array $ids
*/
public function addIdHeader($name, $ids = null)
{
$this->_storeHeader($name, $this->_factory->createIdHeader($name, $ids));
}
/**
* Add a new Path header with an address (path) in it.
*
* @param string $name
* @param string $path
*/
public function addPathHeader($name, $path = null)
{
$this->_storeHeader($name, $this->_factory->createPathHeader($name, $path));
}
/**
* Returns true if at least one header with the given $name exists.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*
* @return boolean
*/
public function has($name, $index = 0)
{
$lowerName = strtolower($name);
return array_key_exists($lowerName, $this->_headers)
&& array_key_exists($index, $this->_headers[$lowerName]);
}
/**
* Set a header in the HeaderSet.
*
* The header may be a previously fetched header via {@link get()} or it may
* be one that has been created separately.
*
* If $index is specified, the header will be inserted into the set at this
* offset.
*
* @param Swift_Mime_Header $header
* @param int $index
*/
public function set(Swift_Mime_Header $header, $index = 0)
{
$this->_storeHeader($header->getFieldName(), $header, $index);
}
/**
* Get the header with the given $name.
*
* If multiple headers match, the actual one may be specified by $index.
* Returns NULL if none present.
*
* @param string $name
* @param int $index
*
* @return Swift_Mime_Header
*/
public function get($name, $index = 0)
{
if ($this->has($name, $index))
{
$lowerName = strtolower($name);
return $this->_headers[$lowerName][$index];
}
}
/**
* Get all headers with the given $name.
*
* @param string $name
*
* @return array
*/
public function getAll($name = null)
{
if (!isset($name))
{
$headers = array();
foreach ($this->_headers as $collection)
{
$headers = array_merge($headers, $collection);
}
return $headers;
}
$lowerName = strtolower($name);
if (!array_key_exists($lowerName, $this->_headers))
{
return array();
}
return $this->_headers[$lowerName];
}
/**
* Remove the header with the given $name if it's set.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*/
public function remove($name, $index = 0)
{
$lowerName = strtolower($name);
unset($this->_headers[$lowerName][$index]);
}
/**
* Remove all headers with the given $name.
*
* @param string $name
*/
public function removeAll($name)
{
$lowerName = strtolower($name);
unset($this->_headers[$lowerName]);
}
/**
* Create a new instance of this HeaderSet.
*
* @return Swift_Mime_HeaderSet
*/
public function newInstance()
{
return new self($this->_factory);
}
/**
* 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)
{
$this->_order = array_flip(array_map('strtolower', $sequence));
}
/**
* Set a list of header names which must always be displayed when set.
*
* Usually headers without a field value won't be output unless set here.
*
* @param array $names
*/
public function setAlwaysDisplayed(array $names)
{
$this->_required = array_flip(array_map('strtolower', $names));
}
/**
* Notify this observer that the entity's charset has changed.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->setCharset($charset);
}
/**
* Returns a string with a representation of all headers.
*
* @return string
*/
public function toString()
{
$string = '';
$headers = $this->_headers;
if ($this->_canSort())
{
uksort($headers, array($this, '_sortHeaders'));
}
foreach ($headers as $collection)
{
foreach ($collection as $header)
{
if ($this->_isDisplayed($header) || $header->getFieldBody() != '')
{
$string .= $header->toString();
}
}
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
// -- Private methods
/** Save a Header to the internal collection */
private function _storeHeader($name, Swift_Mime_Header $header, $offset = null)
{
if (!isset($this->_headers[strtolower($name)]))
{
$this->_headers[strtolower($name)] = array();
}
if (!isset($offset))
{
$this->_headers[strtolower($name)][] = $header;
}
else
{
$this->_headers[strtolower($name)][$offset] = $header;
}
}
/** Test if the headers can be sorted */
private function _canSort()
{
return count($this->_order) > 0;
}
/** uksort() algorithm for Header ordering */
private function _sortHeaders($a, $b)
{
$lowerA = strtolower($a);
$lowerB = strtolower($b);
$aPos = array_key_exists($lowerA, $this->_order)
? $this->_order[$lowerA]
: -1;
$bPos = array_key_exists($lowerB, $this->_order)
? $this->_order[$lowerB]
: -1;
if ($aPos == -1)
{
return 1;
}
elseif ($bPos == -1)
{
return -1;
}
return ($aPos < $bPos) ? -1 : 1;
}
/** Test if the given Header is always displayed */
private function _isDisplayed(Swift_Mime_Header $header)
{
return array_key_exists(strtolower($header->getFieldName()), $this->_required);
}
/** Notify all Headers of the new charset */
private function _notifyHeadersOfCharset($charset)
{
foreach ($this->_headers as $headerGroup)
{
foreach ($headerGroup as $header)
{
$header->setCharset($charset);
}
}
}
}

View File

@@ -0,0 +1,609 @@
<?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.
*/
//@require 'Swift/Mime/Message.php';
//@require 'Swift/Mime/MimePart.php';
//@require 'Swift/Mime/MimeEntity.php';
//@require 'Swift/Mime/HeaderSet.php';
//@require 'Swift/Mime/ContentEncoder.php';
/**
* The default email message class.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_SimpleMessage extends Swift_Mime_MimePart
implements Swift_Mime_Message
{
/**
* Create a new SimpleMessage with $headers, $encoder and $cache.
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderSet $headers,
Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, $charset = null)
{
parent::__construct($headers, $encoder, $cache, $charset);
$this->getHeaders()->defineOrdering(array(
'Return-Path',
'Sender',
'Message-ID',
'Date',
'Subject',
'From',
'Reply-To',
'To',
'Cc',
'Bcc',
'MIME-Version',
'Content-Type',
'Content-Transfer-Encoding'
));
$this->getHeaders()->setAlwaysDisplayed(
array('Date', 'Message-ID', 'From')
);
$this->getHeaders()->addTextHeader('MIME-Version', '1.0');
$this->setDate(time());
$this->setId($this->getId());
$this->getHeaders()->addMailboxHeader('From');
}
/**
* Always returns {@link LEVEL_TOP} for a message instance.
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_TOP;
}
/**
* Set the subject of this message.
* @param string $subject
*/
public function setSubject($subject)
{
if (!$this->_setHeaderFieldModel('Subject', $subject))
{
$this->getHeaders()->addTextHeader('Subject', $subject);
}
return $this;
}
/**
* Get the subject of this message.
* @return string
*/
public function getSubject()
{
return $this->_getHeaderFieldModel('Subject');
}
/**
* Set the date at which this message was created.
* @param int $date
*/
public function setDate($date)
{
if (!$this->_setHeaderFieldModel('Date', $date))
{
$this->getHeaders()->addDateHeader('Date', $date);
}
return $this;
}
/**
* Get the date at which this message was created.
* @return int
*/
public function getDate()
{
return $this->_getHeaderFieldModel('Date');
}
/**
* Set the return-path (the bounce address) of this message.
* @param string $address
*/
public function setReturnPath($address)
{
if (!$this->_setHeaderFieldModel('Return-Path', $address))
{
$this->getHeaders()->addPathHeader('Return-Path', $address);
}
return $this;
}
/**
* Get the return-path (bounce address) of this message.
* @return string
*/
public function getReturnPath()
{
return $this->_getHeaderFieldModel('Return-Path');
}
/**
* Set the sender of this message.
* This does not override the From field, but it has a higher significance.
* @param string $sender
* @param string $name optional
*/
public function setSender($address, $name = null)
{
if (!is_array($address) && isset($name))
{
$address = array($address => $name);
}
if (!$this->_setHeaderFieldModel('Sender', (array) $address))
{
$this->getHeaders()->addMailboxHeader('Sender', (array) $address);
}
return $this;
}
/**
* Get the sender of this message.
* @return string
*/
public function getSender()
{
return $this->_getHeaderFieldModel('Sender');
}
/**
* Add a From: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*/
public function addFrom($address, $name = null)
{
$current = $this->getFrom();
$current[$address] = $name;
return $this->setFrom($current);
}
/**
* Set the from address of this message.
*
* You may pass an array of addresses if this message is from multiple people.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param string $addresses
* @param string $name optional
*/
public function setFrom($addresses, $name = null)
{
if (!is_array($addresses) && isset($name))
{
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('From', (array) $addresses))
{
$this->getHeaders()->addMailboxHeader('From', (array) $addresses);
}
return $this;
}
/**
* Get the from address of this message.
*
* @return string
*/
public function getFrom()
{
return $this->_getHeaderFieldModel('From');
}
/**
* Add a Reply-To: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*/
public function addReplyTo($address, $name = null)
{
$current = $this->getReplyTo();
$current[$address] = $name;
return $this->setReplyTo($current);
}
/**
* Set the reply-to address of this message.
*
* You may pass an array of addresses if replies will go to multiple people.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param string $addresses
* @param string $name optional
*/
public function setReplyTo($addresses, $name = null)
{
if (!is_array($addresses) && isset($name))
{
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Reply-To', (array) $addresses))
{
$this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses);
}
return $this;
}
/**
* Get the reply-to address of this message.
*
* @return string
*/
public function getReplyTo()
{
return $this->_getHeaderFieldModel('Reply-To');
}
/**
* Add a To: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*/
public function addTo($address, $name = null)
{
$current = $this->getTo();
$current[$address] = $name;
return $this->setTo($current);
}
/**
* Set the to addresses of this message.
*
* If multiple recipients will receive the message and array should be used.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param array $addresses
* @param string $name optional
*/
public function setTo($addresses, $name = null)
{
if (!is_array($addresses) && isset($name))
{
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('To', (array) $addresses))
{
$this->getHeaders()->addMailboxHeader('To', (array) $addresses);
}
return $this;
}
/**
* Get the To addresses of this message.
*
* @return array
*/
public function getTo()
{
return $this->_getHeaderFieldModel('To');
}
/**
* Add a Cc: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*/
public function addCc($address, $name = null)
{
$current = $this->getCc();
$current[$address] = $name;
return $this->setCc($current);
}
/**
* Set the Cc addresses of this message.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param array $addresses
* @param string $name optional
*/
public function setCc($addresses, $name = null)
{
if (!is_array($addresses) && isset($name))
{
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Cc', (array) $addresses))
{
$this->getHeaders()->addMailboxHeader('Cc', (array) $addresses);
}
return $this;
}
/**
* Get the Cc address of this message.
*
* @return array
*/
public function getCc()
{
return $this->_getHeaderFieldModel('Cc');
}
/**
* Add a Bcc: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*/
public function addBcc($address, $name = null)
{
$current = $this->getBcc();
$current[$address] = $name;
return $this->setBcc($current);
}
/**
* Set the Bcc addresses of this message.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param array $addresses
* @param string $name optional
*/
public function setBcc($addresses, $name = null)
{
if (!is_array($addresses) && isset($name))
{
$addresses = array($addresses => $name);
}
if (!$this->_setHeaderFieldModel('Bcc', (array) $addresses))
{
$this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses);
}
return $this;
}
/**
* Get the Bcc addresses of this message.
*
* @return array
*/
public function getBcc()
{
return $this->_getHeaderFieldModel('Bcc');
}
/**
* Set the priority of this message.
* The value is an integer where 1 is the highest priority and 5 is the lowest.
* @param int $priority
*/
public function setPriority($priority)
{
$priorityMap = array(
1 => 'Highest',
2 => 'High',
3 => 'Normal',
4 => 'Low',
5 => 'Lowest'
);
$pMapKeys = array_keys($priorityMap);
if ($priority > max($pMapKeys))
{
$priority = max($pMapKeys);
}
elseif ($priority < min($pMapKeys))
{
$priority = min($pMapKeys);
}
if (!$this->_setHeaderFieldModel('X-Priority',
sprintf('%d (%s)', $priority, $priorityMap[$priority])))
{
$this->getHeaders()->addTextHeader('X-Priority',
sprintf('%d (%s)', $priority, $priorityMap[$priority]));
}
return $this;
}
/**
* Get the priority of this message.
* The returned value is an integer where 1 is the highest priority and 5
* is the lowest.
* @return int
*/
public function getPriority()
{
list($priority) = sscanf($this->_getHeaderFieldModel('X-Priority'),
'%[1-5]'
);
return isset($priority) ? $priority : 3;
}
/**
* Ask for a delivery receipt from the recipient to be sent to $addresses
* @param array $addresses
*/
public function setReadReceiptTo($addresses)
{
if (!$this->_setHeaderFieldModel('Disposition-Notification-To', $addresses))
{
$this->getHeaders()
->addMailboxHeader('Disposition-Notification-To', $addresses);
}
return $this;
}
/**
* Get the addresses to which a read-receipt will be sent.
* @return string
*/
public function getReadReceiptTo()
{
return $this->_getHeaderFieldModel('Disposition-Notification-To');
}
/**
* Attach a {@link Swift_Mime_MimeEntity} such as an Attachment or MimePart.
* @param Swift_Mime_MimeEntity $entity
*/
public function attach(Swift_Mime_MimeEntity $entity)
{
$this->setChildren(array_merge($this->getChildren(), array($entity)));
return $this;
}
/**
* Remove an already attached entity.
* @param Swift_Mime_MimeEntity $entity
*/
public function detach(Swift_Mime_MimeEntity $entity)
{
$newChildren = array();
foreach ($this->getChildren() as $child)
{
if ($entity !== $child)
{
$newChildren[] = $child;
}
}
$this->setChildren($newChildren);
return $this;
}
/**
* Attach a {@link Swift_Mime_MimeEntity} 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
* @return string
*/
public function embed(Swift_Mime_MimeEntity $entity)
{
$this->attach($entity);
return 'cid:' . $entity->getId();
}
/**
* Get this message as a complete string.
* @return string
*/
public function toString()
{
if (count($children = $this->getChildren()) > 0 && $this->getBody() != '')
{
$this->setChildren(array_merge(array($this->_becomeMimePart()), $children));
$string = parent::toString();
$this->setChildren($children);
}
else
{
$string = parent::toString();
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
/**
* Write this message to a {@link Swift_InputByteStream}.
* @param Swift_InputByteStream $is
*/
public function toByteStream(Swift_InputByteStream $is)
{
if (count($children = $this->getChildren()) > 0 && $this->getBody() != '')
{
$this->setChildren(array_merge(array($this->_becomeMimePart()), $children));
parent::toByteStream($is);
$this->setChildren($children);
}
else
{
parent::toByteStream($is);
}
}
// -- Protected methods
/** @see Swift_Mime_SimpleMimeEntity::_getIdField() */
protected function _getIdField()
{
return 'Message-ID';
}
// -- Private methods
/** Turn the body of this message into a child of itself if needed */
private function _becomeMimePart()
{
$part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(),
$this->_getCache(), $this->_userCharset
);
$part->setContentType($this->_userContentType);
$part->setBody($this->getBody());
$part->setFormat($this->_userFormat);
$part->setDelSp($this->_userDelSp);
$part->_setNestingLevel($this->_getTopNestingLevel());
return $part;
}
/** Get the highest nesting level nested inside this message */
private function _getTopNestingLevel()
{
$highestLevel = $this->getNestingLevel();
foreach ($this->getChildren() as $child)
{
$childLevel = $child->getNestingLevel();
if ($highestLevel < $childLevel)
{
$highestLevel = $childLevel;
}
}
return $highestLevel;
}
}

View File

@@ -0,0 +1,803 @@
<?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.
*/
//@require 'Swift/Mime/HeaderSet.php';
//@require 'Swift/OutputByteStream.php';
//@require 'Swift/Mime/ContentEncoder.php';
//@require 'Swift/KeyCache.php';
/**
* A MIME entity, in a multipart message.
* @package Swift
* @subpackage Mime
* @author Chris Corbyn
*/
class Swift_Mime_SimpleMimeEntity implements Swift_Mime_MimeEntity
{
/** A collection of Headers for this mime entity */
private $_headers;
/** The body as a string, or a stream */
private $_body;
/** The encoder that encodes the body into a streamable format */
private $_encoder;
/** A mime bounary, if any is used */
private $_boundary;
/** Mime types to be used based on the nesting level */
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();
/** The nesting level of this entity */
private $_nestingLevel = self::LEVEL_ALTERNATIVE;
/** A KeyCache instance used during encoding and streaming */
private $_cache;
/** Direct descendants of this entity */
private $_immediateChildren = array();
/** All descendants of this entity */
private $_children = array();
/** The maximum line length of the body of this entity */
private $_maxLineLength = 78;
/** The order in which alternative mime types should appear */
private $_alternativePartOrder = array(
'text/plain' => 1,
'text/html' => 2,
'multipart/related' => 3
);
/** The CID of this entity */
private $_id;
/** The key used for accessing the cache */
private $_cacheKey;
protected $_userContentType;
/**
* Create a new SimpleMimeEntity with $headers, $encoder and $cache.
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
*/
public function __construct(Swift_Mime_HeaderSet $headers,
Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache)
{
$this->_cacheKey = uniqid();
$this->_cache = $cache;
$this->_headers = $headers;
$this->setEncoder($encoder);
$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
// is $contentType then it should be treated as if it's level is
// $neededLevel instead. I tried to write that unambiguously! :-\
// Data Structure:
// array (
// $compoundLevel => array(
// $level => array(
// $contentType => $neededLevel
// )
// )
// )
$this->_compoundLevelFilters = array(
(self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array(
self::LEVEL_ALTERNATIVE => array(
'text/plain' => self::LEVEL_ALTERNATIVE,
'text/html' => self::LEVEL_RELATED
)
)
);
$this->_id = $this->getRandomId();
}
/**
* Generate a new Content-ID or Message-ID for this MIME entity.
* @return string
*/
public function generateId()
{
$this->setId($this->getRandomId());
return $this->_id;
}
/**
* Get the {@link Swift_Mime_HeaderSet} for this entity.
* @return Swift_Mime_HeaderSet
*/
public function getHeaders()
{
return $this->_headers;
}
/**
* Get the nesting level of this entity.
* @return int
* @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE
*/
public function getNestingLevel()
{
return $this->_nestingLevel;
}
/**
* Get the Content-type of this entity.
* @return string
*/
public function getContentType()
{
return $this->_getHeaderFieldModel('Content-Type');
}
/**
* Set the Content-type of this entity.
* @param string $type
*/
public function setContentType($type)
{
$this->_setContentTypeInHeaders($type);
// Keep track of the value so that if the content-type changes automatically
// due to added child entities, it can be restored if they are later removed
$this->_userContentType = $type;
return $this;
}
/**
* Get the CID of this entity.
* The CID will only be present in headers if a Content-ID header is present.
* @return string
*/
public function getId()
{
return $this->_headers->has($this->_getIdField())
? current((array) $this->_getHeaderFieldModel($this->_getIdField()))
: $this->_id;
}
/**
* Set the CID of this entity.
* @param string $id
*/
public function setId($id)
{
if (!$this->_setHeaderFieldModel($this->_getIdField(), $id))
{
$this->_headers->addIdHeader($this->_getIdField(), $id);
}
$this->_id = $id;
return $this;
}
/**
* Get the description of this entity.
* This value comes from the Content-Description header if set.
* @return string
*/
public function getDescription()
{
return $this->_getHeaderFieldModel('Content-Description');
}
/**
* Set the description of this entity.
* This method sets a value in the Content-ID header.
* @param string $description
*/
public function setDescription($description)
{
if (!$this->_setHeaderFieldModel('Content-Description', $description))
{
$this->_headers->addTextHeader('Content-Description', $description);
}
return $this;
}
/**
* Get the maximum line length of the body of this entity.
* @return int
*/
public function getMaxLineLength()
{
return $this->_maxLineLength;
}
/**
* Set the maximum line length of lines in this body.
* Though not enforced by the library, lines should not exceed 1000 chars.
* @param int $length
*/
public function setMaxLineLength($length)
{
$this->_maxLineLength = $length;
return $this;
}
/**
* Get all children added to this entity.
* @return array of Swift_Mime_Entity
*/
public function getChildren()
{
return $this->_children;
}
/**
* Set all children of this entity.
* @param array $children Swiift_Mime_Entity instances
* @param int $compoundLevel For internal use only
*/
public function setChildren(array $children, $compoundLevel = null)
{
//TODO: Try to refactor this logic
$compoundLevel = isset($compoundLevel)
? $compoundLevel
: $this->_getCompoundLevel($children)
;
$immediateChildren = array();
$grandchildren = array();
$newContentType = $this->_userContentType;
foreach ($children as $child)
{
$level = $this->_getNeededChildLevel($child, $compoundLevel);
if (empty($immediateChildren)) //first iteration
{
$immediateChildren = array($child);
}
else
{
$nextLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
if ($nextLevel == $level)
{
$immediateChildren[] = $child;
}
elseif ($level < $nextLevel)
{
//Re-assign immediateChildren to grandchilden
$grandchildren = array_merge($grandchildren, $immediateChildren);
//Set new children
$immediateChildren = array($child);
}
else
{
$grandchildren[] = $child;
}
}
}
if (!empty($immediateChildren))
{
$lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
//Determine which composite media type is needed to accomodate the
// immediate children
foreach ($this->_compositeRanges as $mediaType => $range)
{
if ($lowestLevel > $range[0]
&& $lowestLevel <= $range[1])
{
$newContentType = $mediaType;
break;
}
}
//Put any grandchildren in a subpart
if (!empty($grandchildren))
{
$subentity = $this->_createChild();
$subentity->_setNestingLevel($lowestLevel);
$subentity->setChildren($grandchildren, $compoundLevel);
array_unshift($immediateChildren, $subentity);
}
}
$this->_immediateChildren = $immediateChildren;
$this->_children = $children;
$this->_setContentTypeInHeaders($newContentType);
$this->_fixHeaders();
$this->_sortChildren();
return $this;
}
/**
* Get the body of this entity as a string.
* @return string
*/
public function getBody()
{
return ($this->_body instanceof Swift_OutputByteStream)
? $this->_readStream($this->_body)
: $this->_body;
}
/**
* Set the body of this entity, either as a string, or as an instance of
* {@link Swift_OutputByteStream}.
* @param mixed $body
* @param string $contentType optional
*/
public function setBody($body, $contentType = null)
{
if ($body !== $this->_body)
{
$this->_clearCache();
}
$this->_body = $body;
if (isset($contentType))
{
$this->setContentType($contentType);
}
return $this;
}
/**
* Get the encoder used for the body of this entity.
* @return Swift_Mime_ContentEncoder
*/
public function getEncoder()
{
return $this->_encoder;
}
/**
* Set the encoder used for the body of this entity.
* @param Swift_Mime_ContentEncoder $encoder
*/
public function setEncoder(Swift_Mime_ContentEncoder $encoder)
{
if ($encoder !== $this->_encoder)
{
$this->_clearCache();
}
$this->_encoder = $encoder;
$this->_setEncoding($encoder->getName());
$this->_notifyEncoderChanged($encoder);
return $this;
}
/**
* Get the boundary used to separate children in this entity.
* @return string
*/
public function getBoundary()
{
if (!isset($this->_boundary))
{
$this->_boundary = '_=_swift_v4_' . time() . uniqid() . '_=_';
}
return $this->_boundary;
}
/**
* Set the boundary used to separate children in this entity.
* @param string $boundary
* @throws Swift_RfcComplianceException
*/
public function setBoundary($boundary)
{
$this->_assertValidBoundary($boundary);
$this->_boundary = $boundary;
return $this;
}
/**
* Receive notification that the charset of this entity, or a parent entity
* has changed.
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->_notifyCharsetChanged($charset);
}
/**
* Receive notification that the encoder of this entity or a parent entity
* has changed.
* @param Swift_Mime_ContentEncoder $encoder
*/
public function encoderChanged(Swift_Mime_ContentEncoder $encoder)
{
$this->_notifyEncoderChanged($encoder);
}
/**
* Get this entire entity as a string.
* @return string
*/
public function toString()
{
$string = $this->_headers->toString();
if (isset($this->_body) && empty($this->_immediateChildren))
{
if ($this->_cache->hasKey($this->_cacheKey, 'body'))
{
$body = $this->_cache->getString($this->_cacheKey, 'body');
}
else
{
$body = "\r\n" . $this->_encoder->encodeString($this->getBody(), 0,
$this->getMaxLineLength()
);
$this->_cache->setString($this->_cacheKey, 'body', $body,
Swift_KeyCache::MODE_WRITE
);
}
$string .= $body;
}
if (!empty($this->_immediateChildren))
{
foreach ($this->_immediateChildren as $child)
{
$string .= "\r\n\r\n--" . $this->getBoundary() . "\r\n";
$string .= $child->toString();
}
$string .= "\r\n\r\n--" . $this->getBoundary() . "--\r\n";
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
/**
* Write this entire entity to a {@link Swift_InputByteStream}.
* @param Swift_InputByteStream
*/
public function toByteStream(Swift_InputByteStream $is)
{
$is->write($this->_headers->toString());
$is->commit();
if (empty($this->_immediateChildren))
{
if (isset($this->_body))
{
if ($this->_cache->hasKey($this->_cacheKey, 'body'))
{
$this->_cache->exportToByteStream($this->_cacheKey, 'body', $is);
}
else
{
$cacheIs = $this->_cache->getInputByteStream($this->_cacheKey, 'body');
if ($cacheIs)
{
$is->bind($cacheIs);
}
$is->write("\r\n");
if ($this->_body instanceof Swift_OutputByteStream)
{
$this->_body->setReadPointer(0);
$this->_encoder->encodeByteStream($this->_body, $is, 0,
$this->getMaxLineLength()
);
}
else
{
$is->write($this->_encoder->encodeString(
$this->getBody(), 0, $this->getMaxLineLength()
));
}
if ($cacheIs)
{
$is->unbind($cacheIs);
}
}
}
}
if (!empty($this->_immediateChildren))
{
foreach ($this->_immediateChildren as $child)
{
$is->write("\r\n\r\n--" . $this->getBoundary() . "\r\n");
$child->toByteStream($is);
}
$is->write("\r\n\r\n--" . $this->getBoundary() . "--\r\n");
}
}
// -- Protected methods
/**
* Get the name of the header that provides the ID of this entity */
protected function _getIdField()
{
return 'Content-ID';
}
/**
* Get the model data (usually an array or a string) for $field.
*/
protected function _getHeaderFieldModel($field)
{
if ($this->_headers->has($field))
{
return $this->_headers->get($field)->getFieldBodyModel();
}
}
/**
* Set the model data for $field.
*/
protected function _setHeaderFieldModel($field, $model)
{
if ($this->_headers->has($field))
{
$this->_headers->get($field)->setFieldBodyModel($model);
return true;
}
else
{
return false;
}
}
/**
* Get the parameter value of $parameter on $field header.
*/
protected function _getHeaderParameter($field, $parameter)
{
if ($this->_headers->has($field))
{
return $this->_headers->get($field)->getParameter($parameter);
}
}
/**
* Set the parameter value of $parameter on $field header.
*/
protected function _setHeaderParameter($field, $parameter, $value)
{
if ($this->_headers->has($field))
{
$this->_headers->get($field)->setParameter($parameter, $value);
return true;
}
else
{
return false;
}
}
/**
* Re-evaluate what content type and encoding should be used on this entity.
*/
protected function _fixHeaders()
{
if (count($this->_immediateChildren))
{
$this->_setHeaderParameter('Content-Type', 'boundary',
$this->getBoundary()
);
$this->_headers->remove('Content-Transfer-Encoding');
}
else
{
$this->_setHeaderParameter('Content-Type', 'boundary', null);
$this->_setEncoding($this->_encoder->getName());
}
}
/**
* Get the KeyCache used in this entity.
*/
protected function _getCache()
{
return $this->_cache;
}
/**
* Empty the KeyCache for this entity.
*/
protected function _clearCache()
{
$this->_cache->clearKey($this->_cacheKey, 'body');
}
/**
* Returns a random Content-ID or Message-ID.
* @return string
*/
protected function getRandomId()
{
$idLeft = time() . '.' . uniqid();
$idRight = !empty($_SERVER['SERVER_NAME'])
? $_SERVER['SERVER_NAME']
: 'swift.generated';
return $idLeft . '@' . $idRight;
}
// -- Private methods
private function _readStream(Swift_OutputByteStream $os)
{
$string = '';
while (false !== $bytes = $os->read(8192))
{
$string .= $bytes;
}
return $string;
}
private function _setEncoding($encoding)
{
if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding))
{
$this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding);
}
}
private function _assertValidBoundary($boundary)
{
if (!preg_match(
'/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di',
$boundary))
{
throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.');
}
}
private function _setContentTypeInHeaders($type)
{
if (!$this->_setHeaderFieldModel('Content-Type', $type))
{
$this->_headers->addParameterizedHeader('Content-Type', $type);
}
}
private function _setNestingLevel($level)
{
$this->_nestingLevel = $level;
}
private function _getCompoundLevel($children)
{
$level = 0;
foreach ($children as $child)
{
$level |= $child->getNestingLevel();
}
return $level;
}
private function _getNeededChildLevel($child, $compoundLevel)
{
$filter = array();
foreach ($this->_compoundLevelFilters as $bitmask => $rules)
{
if (($compoundLevel & $bitmask) === $bitmask)
{
$filter = $rules + $filter;
}
}
$realLevel = $child->getNestingLevel();
$lowercaseType = strtolower($child->getContentType());
if (isset($filter[$realLevel])
&& isset($filter[$realLevel][$lowercaseType]))
{
return $filter[$realLevel][$lowercaseType];
}
else
{
return $realLevel;
}
}
private function _createChild()
{
return new self($this->_headers->newInstance(),
$this->_encoder, $this->_cache);
}
private function _notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder)
{
foreach ($this->_immediateChildren as $child)
{
$child->encoderChanged($encoder);
}
}
private function _notifyCharsetChanged($charset)
{
$this->_encoder->charsetChanged($charset);
$this->_headers->charsetChanged($charset);
foreach ($this->_immediateChildren as $child)
{
$child->charsetChanged($charset);
}
}
private function _sortChildren()
{
$shouldSort = false;
foreach ($this->_immediateChildren as $child)
{
//NOTE: This include alternative parts moved into a related part
if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE)
{
$shouldSort = true;
break;
}
}
//Sort in order of preference, if there is one
if ($shouldSort)
{
usort($this->_immediateChildren, array($this, '_childSortAlgorithm'));
}
}
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);
}
}