first commit

This commit is contained in:
2026-04-30 14:38:11 +02:00
commit e22bbde336
1994 changed files with 613950 additions and 0 deletions

View File

@@ -0,0 +1,161 @@
<?php
/**
* Swift Mailer Message Attachment
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
/**
* Attachment component for Swift Mailer
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message_Attachment extends Swift_Message_Mime
{
/**
* A numeric counter, incremented by 1 when a filename is made.
* @var int
*/
protected static $fileId = 0;
/**
* Constructor
* @param mixed The data to use in the body
* @param string Mime type
* @param string The encoding format used
* @param string The charset used
*/
public function __construct($data=null, $name=null, $type="application/octet-stream", $encoding="base64", $disposition="attachment")
{
parent::__construct();
$this->setContentType($type);
$this->setEncoding($encoding);
$this->setDescription($name);
$this->setDisposition($disposition);
$this->setFileName($name);
if ($data !== null) $this->setData($data, ($name === null));
}
/**
* Get a unique filename (just a sequence)
* @param string the prefix for the filename
* @return string
*/
public static function generateFileName($prefix="file")
{
return $prefix . (self::$fileId++);
}
/**
* Get the level in the MIME hierarchy at which this section should appear.
* @return string
*/
public function getLevel()
{
return Swift_Message_Mime::LEVEL_MIXED;
}
/**
* Overrides setData() in MIME so that a filename can be set
* @param mixed The data to set for the body
* @param boolean If the stream is a file, should it's filename be used?
* @throws Swift_FileException If the stream cannot be read
*/
public function setData($data, $read_filename=true)
{
parent::setData($data);
if ($read_filename && ($data instanceof Swift_file))
{
$this->setFileName($data->getFileName());
}
}
/**
* Set the name (and description) used to identify the file
* This method overrides any value previously set with setDescription()
* @param string The filename including it's extension if any
* @throws Swift_Message_MimeException If some required headers have been deliberately removed
*/
public function setFileName($name)
{
$this->headers->setAttribute("Content-Type", "name", $name);
$this->setDescription($name);
if ($this->headers->has("Content-Disposition"))
{
$this->headers->setAttribute("Content-Disposition", "filename", $name);
}
}
/**
* Get the filename of this attachment
* @return string
* @throws Swift_Message_MimeException If some vital headers have been removed
*/
public function getFileName()
{
if ($this->headers->hasAttribute("Content-Type", "name"))
{
return $this->headers->getAttribute("Content-Type", "name");
}
else return null;
}
/**
* Set the Content-Description header
* @param string The description in the header (filename usually!)
*/
public function setDescription($desc)
{
$this->headers->set("Content-Description", $desc);
}
/**
* Return the description in the headers
* @return string
*/
public function getDescription()
{
if ($this->headers->has("Content-Description"))
{
return $this->headers->get("Content-Description");
}
else return null;
}
/**
* Set the disposition of the attachment (usually inline or attachment)
* @param string The value to use in the Content-Disposition field
*/
public function setDisposition($disposition)
{
$this->headers->set("Content-Disposition", $disposition);
}
/**
* Get the disposition used in the attachment (usually inline or attachment)
* @return string
*/
public function getDisposition()
{
if ($this->headers->has("Content-Disposition"))
{
return $this->headers->get("Content-Disposition");
}
else return null;
}
/**
* Execute needed logic prior to building
*/
public function preBuild()
{
if ($this->getFileName() === null)
{
if ($this->getData() instanceof Swift_File)
{
$this->setFileName($this->getData()->getFileName());
}
else
{
$this->setFileName(self::generateFileName("file.att."));
}
}
}
}

View File

@@ -0,0 +1,77 @@
<?php
/**
* Swift Mailer Embedded File (like an image or a midi file)
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/../ClassLoader.php";
Swift_ClassLoader::load("Swift_Message_Attachment");
/**
* Embedded File component for Swift Mailer
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message_EmbeddedFile extends Swift_Message_Attachment
{
/**
* The content-id in the headers (used in <img src=...> values)
* @var string
*/
protected $cid = null;
/**
* Constructor
* @param mixed The input source. Can be a file or a string
* @param string The filename to use, optional
* @param string The MIME type to use, optional
* @param string The Content-ID to use, optional
* @param string The encoding format to use, optional
*/
public function __construct($data=null, $name=null, $type="application/octet-stream", $cid=null, $encoding="base64")
{
parent::__construct($data, $name, $type, $encoding, "inline");
if ($cid === null)
{
$cid = self::generateFileName("swift-" . uniqid(time()) . ".");
$cid = urlencode($cid) . "@" . (!empty($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : "swift");
}
$this->setContentId($cid);
if ($name === null && !($data instanceof Swift_File)) $this->setFileName($cid);
$this->headers->set("Content-Description", null);
}
/**
* Get the level in the MIME hierarchy at which this section should appear.
* @return string
*/
public function getLevel()
{
return Swift_Message_Mime::LEVEL_RELATED;
}
/**
* Set the Content-Id to use
* @param string The content-id
*/
public function setContentId($id)
{
$id = (string) $id;
$this->cid = $id;
$this->headers->set("Content-ID", "<" . $id . ">");
}
/**
* Get the content-id of this file
* @return string
*/
public function getContentId()
{
return $this->cid;
}
}

View File

@@ -0,0 +1,455 @@
<?php
/**
* Swift Mailer Message Encoder
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/../ClassLoader.php";
Swift_ClassLoader::load("Swift_File");
/**
* Encodes strings in a variety of formats and detects some encoding formats
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message_Encoder
{
/**
* A regular expression which matches valid e-mail addresses (including some unlikely ones)
*/
const CHEAP_ADDRESS_RE = '(?#Start of dot-atom
)[-!#\$%&\'\*\+\/=\?\^_`{}\|~0-9A-Za-z]+(?:\.[-!#\$%&\'\*\+\/=\?\^_`{}\|~0-9A-Za-z]+)*(?#
End of dot-atom)(?:@(?#Start of domain)[-0-9A-Za-z]+(?:\.[-0-9A-Za-z]+)*(?#End of domain))?';
/**
* A singleton of this class
* @var Swift_Message_Encoder
*/
protected static $instance = null;
/**
* Retreive an instance of the encoder as a singleton.
* New instances are never ever needed since it's monostatic.
* @return Message_Encoder
*/
public static function instance()
{
if (self::$instance === null)
{
self::$instance = new Swift_Message_Encoder();
}
return self::$instance;
}
/**
* Break a string apart at every occurence of <add@ress> and return an array
* This method does NOT remove any characters like a preg_split() would do.
* Elements matching an address start with "a" followed by the numeric index
* @param string The input string to separate
* @return array
*/
public function addressChunk($input)
{
$elements = 0;
while (preg_match('/^(.*?)(<' . self::CHEAP_ADDRESS_RE . '>)/s', $input, $matches))
{
if (!empty($matches[1])) $ret[($elements++)] = $matches[1];
$ret[('a' . ($elements++))] = $matches[2];
$input = substr($input, strlen($matches[0]));
}
if ($input != "") $ret[($elements++)] = $input; //Whatever is left over
return $ret;
}
/**
* Break a string apart at every occurence of <xxxyyy> and return an array
* This method does NOT remove any characters like a preg_split() would do.
* Elements matching a quoted string start with "a" followed by the numeric index
* @param string The input string to separate
* @return array
*/
public function quoteChunk($input)
{
$elements = 0;
while (preg_match('/^(.*?)(<[\x20-\x3A\x3C-\x7E]*>)/s', $input, $matches))
{
if (!empty($matches[1])) $ret[($elements++)] = $matches[1];
$ret[('a' . ($elements++))] = $matches[2];
$input = substr($input, strlen($matches[0]));
}
if ($input != "") $ret[($elements++)] = $input; //Whatever is left over
return $ret;
}
/**
* Return the base64 encoded version of the string
* @param string The input string to encode
* @param int The maximum length of each line of output (inc CRLF)
* @param int The maximum length of the first line in the output (for headers)
* @param boolean Whether email addresses between < and > chars should be preserved or not
* @param string The line ending
* @return string
*/
public function base64Encode($data, $chunk=76, $init_chunk=0, $headers=false, $le="\r\n")
{
$ret = "";
$chunk -= 2;
$chunk = $this->getHcf($chunk, 4);
if ($init_chunk >= 2)
{
$init_chunk -= 2;
$init_chunk = $this->getHcf($init_chunk, 4);
}
if ($headers) $data = $this->quoteChunk($data);
else $data = array($data);
foreach ($data as $key => $string)
{
$key = (string) $key;
if ($key{0} == 'a') //This is an address
{
if ($init_chunk && $init_chunk < (strlen($string)+2)) $ret .= $le;
$ret .= $le . $string;
}
else
{
$string = $this->rawBase64Encode($string);
if ($init_chunk > 2)
{
$ret .= substr($string, 0, $init_chunk) . $le;
$string = substr($string, $init_chunk);
}
elseif ($init_chunk) $ret .= $le;
$ret .= trim(chunk_split($string, $chunk, $le)) . $le;
}
$init_chunk = 0;
}
return trim($ret);
}
/**
* Return the base64 encoded version of a string with no breaks
* @param The input string to encode
* @return string
*/
public function rawBase64Encode($string)
{
return $string = base64_encode($string);
}
/**
* Return the base64 encoded version of a file
* @param Swift_File The file input stream
* @param int Max line length
* @param string The line ending
* @return Swift_Cache_OutputStream
* @throws Swift_FileException If the file cannot be read
*/
public function base64EncodeFile(Swift_File $file, $chunk=76, $le="\r\n")
{
Swift_ClassLoader::load("Swift_CacheFactory");
$cache = Swift_CacheFactory::getCache();
$chunk -= 2;
$chunk = $this->getHcf($chunk, 4);
$loop = false;
//We have to read in multiples of 3 bytes but avoid doing such small chunks that it takes too long
while (false !== $bytes = $file->read(8190))
{
if ($loop) $cache->write("b64", $le);
$loop = true;
$next = chunk_split($this->rawBase64Encode($bytes), $chunk, $le);
$next = trim($next);
$cache->write("b64", $next);
}
$file->reset();
return $cache->getOutputStream("b64");
}
/**
* Return the quoted printable version of the input string
* @param string The input string to encode
* @param int The maximum length of each line of output (inc CRLF)
* @param int The maximum length of the first line in the output (for headers)
* @param boolean Whether email addresses between < and > chars should be preserved or not
* @param string The line ending
* @return string
*/
public function QPEncode($data, $chunk=76, $init_chunk=0, $headers=false, $le="\r\n")
{
$ret = "";
if ($headers) $data = $this->quoteChunk($data);
else $data = array($data);
$trailing_spaces = chr(9) . chr(32);
foreach ($data as $key => $string)
{
$key = (string) $key;
if ($key{0} == 'a') //An address
{
if ($init_chunk && $init_chunk < (strlen($string)+3)) $ret .= "=";
$ret .= $le . $string;
}
else
{
$lines = explode($le, $string);
foreach ($lines as $n => $line)
$lines[$n] = $this->rawQPEncode(rtrim($line, $trailing_spaces));
$string = implode($le, $lines);
if ($init_chunk > 3)
{
if (preg_match('/^.{1,'.($init_chunk-5).'}[^=]{2}(?!=[A-F0-9]{2})/', $string, $matches)
|| preg_match('/^.{1,'.($init_chunk-6).'}([^=]{0,3})?/', $string, $matches))
{
$ret .= $this->fixLE($matches[0] . "=", $le); //fixLE added 24/08/07
$string = substr($string, strlen($matches[0]));
}
}
elseif ($init_chunk) $ret .= "=";
while (preg_match('/^.{1,'.($init_chunk-5).'}[^=]{2}(?!=[A-F0-9]{2})/', $string, $matches)
|| preg_match('/^.{1,'.($chunk-6).'}([^=]{0,3})?/', $string, $matches)
|| (strlen($string) > 0 && $matches = array($string)))
{
$ret .= $this->fixLE($le . $matches[0] . "=", $le); //fixLE added 24/08/07
$string = substr($string, strlen($matches[0]));
}
}
$init_chunk = 0;
}
if (substr($ret, -1) == "=") return trim(substr($ret, 0, -1));
else return trim($ret);
}
/**
* Return the QP encoded version of a string with no breaks
* @param string The input to encode
* @param boolean True if the data we're encoding is binary
* @return string
*/
public function rawQPEncode($string, $bin=false)
{
$ret = "";
if (!$bin)
{
$string = str_replace(array("\r\n", "\r"), "\n", $string);
$string = str_replace("\n", "\r\n", $string);
}
$len = strlen($string);
for ($i = 0; $i < $len; $i++)
{
$val = ord($string{$i});
//9, 32 = HT, SP; 10, 13 = CR, LF; 33-60 & 62-126 are ok
// 63 = '?'; 95 = '_' and need encoding to go in the headers
if ((!$bin && ($val == 32 || $val == 9 || $val == 10 || $val == 13))
|| ($val >= 33 && $val <= 60) || ($val >= 62 && $val <= 126)
&& $val != 63)
{
$ret .= $string{$i};
}
else
{
$ret .= sprintf("=%02X", $val);
}
}
return $ret;
}
/**
* Return a file as a quoted printable encoded string
* @param Swift_File The file to encode
* @param int Max line length
* @param string The line ending
* @return Swift_Cache_OutputStream
* @throws Swift_FileException If the file cannot be read
*/
public function QPEncodeFile(Swift_File $file, $chunk=76, $le="\r\n")
{
Swift_ClassLoader::load("Swift_CacheFactory");
$cache = Swift_CacheFactory::getCache();
while (false !== $bytes = $file->readln())
{
$next = $this->rawQPEncode($bytes, true);
preg_match_all('/.{1,'.($chunk-6).'}([^=]{0,3})?/', $next, $next);
if (count($next[0])) $cache->write("qp", $this->fixLE(implode("=" . $le, $next[0]), $le));
}
return $cache->getOutputStream("qp");
}
/**
* Encode a string as 7bit ascii
* @param string Input data to encode
* @param int Max line length
* @param string The line ending
* @return string
*/
public function encode7Bit($data, $chunk=76, $le="\r\n")
{
return $this->fixLE(wordwrap($data, $chunk-2, $le, 1), $le);
}
/**
* Return a 7bit string from a file
* @param Swift_File The file stream to read from
* @param int The max line length
* @param string The line ending
* @return Swift_Cache_OutputStream
* @throws Swift_FileException If the file cannot be read
*/
public function encode7BitFile(Swift_File $file, $chunk=76, $le="\r\n")
{
Swift_ClassLoader::load("Swift_CacheFactory");
$cache = Swift_CacheFactory::getCache();
$ret = "";
while (false !== $bytes = $file->read(8192)) $ret .= $bytes;
$cache->write("7b", $this->fixLE(wordwrap($ret, $chunk-2, $le, 1), $le));
return $cache->getOutputStream("7b");
}
/**
* Return the 8bit encoded form of a string (unchanged there-abouts)
* @param string Input data to encode
* @param int Maximum line length
* @param string The line ending
* @return string
*/
public function encode8Bit($data, $chunk=76, $le="\r\n")
{
return $this->fixLE(wordwrap($data, $chunk-2, $le, 1), $le);
}
/**
* Return a 8bit string from a file
* @param Swift_File The file stream to read from
* @param int Max line length (including CRLF)
* @param string The line ending
* @return Swift_Cache_OutputStream
* @throws Swift_FileException If the file cannot be read
*/
public function encode8BitFile(Swift_File $file, $chunk=76, $le="\r\n")
{
Swift_ClassLoader::load("Swift_CacheFactory");
$cache = Swift_CacheFactory::getCache();
$ret = "";
while (false !== $bytes = $file->read(8192)) $ret .= $bytes;
$cache->write("8b", $this->fixLE(wordwrap($ret, $chunk-2, $le, 1), $le));
return $cache->getOutputStream("8b");
}
/**
* Keeps lines longer than 76 characters trimmed down to size
* This currently does not convert other string encodings into 7bit
* @param string The data to make safe for headers (defaults to RFC 2822 standards)
* @param int maximum length of lines returned
* @param int The maximum length of the first line
* @param string The Line ending
* @return string
*/
public function header7BitEncode($data, $chunk=76, $init_chunk=0, $le="\r\n")
{
$data = $this->encode7BitPrintable($data);
$ret = "";
if ($init_chunk > 2)
{
$data_wrapped = wordwrap($data, $init_chunk, $le);
$lines = explode($le, $data_wrapped);
$first_line = array_shift($lines);
$ret .= $first_line . $le;
$data = preg_replace("~^[ \t]~D", "", substr($data, strlen($first_line)));
}
elseif ($init_chunk) $ret .= $le;
$ret .= wordwrap($data, $chunk-2, $le);
return trim($ret);
}
/**
* Strip out any characters which are not in the ASCII 7bit printable range
* @param string The string to clean
* @return string
*/
public function encode7BitPrintable($data)
{
return preg_replace('/[^\x20-\x7E]/', '', $data);
}
/**
* Detect if a string contains multi-byte non-ascii chars that fall in the UTF-8 ranges
* @param string Data to detect UTF-8 sequences in
* @return boolean
*/
public function isUTF8($data)
{
return preg_match('%(?:
[\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
|\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
|\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
|\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
|[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
|\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)+%xs', $data);
}
/**
* This function checks for 7bit *printable* characters
* which excludes \r \n \t etc and so, is safe for use in mail headers
* Actual permitted chars [\ !"#\$%&'\(\)\*\+,-\.\/0123456789:;<=>\?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\[\\\]\^_`abcdefghijklmnopqrstuvwxyz{\|}~]
* Ranges \x00-\x1F are printer control sequences
* \x7F is the ascii delete character
* @param string Data to check against
* @return boolean
*/
public function is7BitPrintable($data)
{
return (!preg_match('/[^\x20-\x7E]/', $data));
}
/**
* Check that a string does not contain any evil characters for headers.
* @param string The string to check
* @return boolean
*/
public function isHeaderSafe($data)
{
return ($this->is7BitPrintable($data) && strpos($data, ";") === false);
}
/**
* If the characters fall exclusively in the 7bit ascii range, return true
* @param string Input to check
* @return boolean
*/
public function is7BitAscii($data)
{
return (!preg_match('/[^\x01-\x7F]/', $data));
}
/**
* Encode a string for RFC 2047 compatability (url-encode)
* @param string The input for encoding
* @param string The charset used
* @param string The language used
* @param int The maximum line length
* @param int The maximum length of the first line
* @param string The line ending
* @return string
*/
public function rfc2047Encode($str, $charset="iso-8859-1", $language="en-us", $chunk=76, $le="\r\n")
{
$lang_spec = "";
if (!$this->is7BitPrintable($str))
{
$lang_spec = $charset . "'" . $language . "'";
$str = $lang_spec . str_replace("+", "%20", urlencode($str));
}
preg_match_all('~.{1,'.($chunk-6).'}([^%]{0,3})~', $str, $matches);
if (count($matches[0])) return implode($le, $matches[0]);
}
/**
* Fixes line endings to be whatever is specified by the user
* SMTP requires the CRLF be used, but using sendmail in -t mode uses LF
* This method also escapes dots on a start of line to avoid injection
* @param string The data to fix
* @return string
*/
protected function fixLE($data, $le)
{
$data = str_replace(array("\r\n", "\r"), "\n", $data);
if ($le != "\n") $data = str_replace("\n", $le, $data);
return $data = str_replace($le . ".", $le . "..", $data);
}
protected function getHcf($value, $factor)
{
return ($value - ($value % $factor));
}
}

View File

@@ -0,0 +1,573 @@
<?php
/**
* Swift Mailer MIME Library Headers component
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/../ClassLoader.php";
/**
* Contains and constructs the headers for a MIME document
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message_Headers
{
/**
* Headers which may contain email addresses, and therefore should take notice when encoding
* @var array headers
*/
protected $emailContainingHeaders = array(
"To", "From", "Reply-To", "Cc", "Bcc", "Return-Path", "Sender");
/**
* The encoding format used for the body of the document
* @var string format
*/
protected $encoding = "B";
/**
* The charset used in the headers
* @var string
*/
protected $charset = false;
/**
* A collection of headers
* @var array headers
*/
protected $headers = array();
/**
* A container of references to the headers
* @var array
*/
protected $lowerHeaders = array();
/**
* Attributes appended to headers
* @var array
*/
protected $attributes = array();
/**
* If QP or Base64 encoding should be forced
* @var boolean
*/
protected $forceEncoding = false;
/**
* The language used in the headers (doesn't really matter much)
* @var string
*/
protected $language = "en-us";
/**
* Cached, pre-built headers
* @var string
*/
protected $cached = array();
/**
* The line ending used in the headers
* @var string
*/
protected $LE = "\r\n";
/**
* Set the line ending character to use
* @param string The line ending sequence
* @return boolean
*/
public function setLE($le)
{
if (in_array($le, array("\r", "\n", "\r\n")))
{
foreach (array_keys($this->cached) as $k) $this->cached[$k] = null;
$this->LE = $le;
return true;
}
else return false;
}
/**
* Get the line ending sequence
* @return string
*/
public function getLE()
{
return $this->LE;
}
/**
* Reset the cache state in these headers
*/
public function uncacheAll()
{
foreach (array_keys($this->cached) as $k)
{
$this->cached[$k] = null;
}
}
/**
* Add a header or change an existing header value
* @param string The header name, for example "From" or "Subject"
* @param string The value to be inserted into the header. This is safe from header injection.
*/
public function set($name, $value)
{
$lname = strtolower($name);
if (!isset($this->lowerHeaders[$lname]))
{
$this->headers[$name] = null;
$this->lowerHeaders[$lname] =& $this->headers[$name];
}
$this->cached[$lname] = null;
Swift_ClassLoader::load("Swift_Message_Encoder");
if (is_array($value))
{
foreach ($value as $v)
{
if (!$this->getCharset() && Swift_Message_Encoder::instance()->isUTF8($v))
{
$this->setCharset("utf-8");
break;
}
}
}
elseif ($value !== null)
{
if (!$this->getCharset() && Swift_Message_Encoder::instance()->isUTF8($value))
{
$this->setCharset("utf-8");
}
}
if (!is_array($value) && $value !== null) $this->lowerHeaders[$lname] = (string) $value;
else $this->lowerHeaders[$lname] = $value;
}
/**
* Get the value at a given header
* @param string The name of the header, for example "From" or "Subject"
* @return string
* @throws Swift_Message_MimeException If no such header exists
* @see hasHeader
*/
public function get($name)
{
$lname = strtolower($name);
if ($this->has($name))
{
return $this->lowerHeaders[$lname];
}
}
/**
* Remove a header from the list
* @param string The name of the header
*/
public function remove($name)
{
$lname = strtolower($name);
if ($this->has($name))
{
unset($this->headers[$name]);
unset($this->lowerHeaders[$lname]);
unset($this->cached[$lname]);
if (isset($this->attributes[$lname])) unset($this->attributes[$lname]);
}
}
/**
* Just fetch the array containing the headers
* @return array
*/
public function getList()
{
return $this->headers;
}
/**
* Check if a header has been set or not
* @param string The name of the header, for example "From" or "Subject"
* @return boolean
*/
public function has($name)
{
$lname = strtolower($name);
return (array_key_exists($lname, $this->lowerHeaders) && $this->lowerHeaders[$lname] !== null);
}
/**
* Set the language used in the headers to $lang (e.g. en-us, en-gb, sv etc)
* @param string The language to use
*/
public function setLanguage($lang)
{
$this->language = (string) $lang;
}
/**
* Get the language used in the headers to $lang (e.g. en-us, en-gb, sv etc)
* @return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* Set the charset used in the headers
* @param string The charset name
*/
public function setCharset($charset)
{
$this->charset = (string) $charset;
}
/**
* Get the current charset used
* @return string
*/
public function getCharset()
{
return $this->charset;
}
/**
* Specify the encoding to use for the headers if characters outside the 7-bit-printable ascii range are found
* This encoding will never be used if only 7-bit-printable characters are found in the headers.
* Possible values are:
* - QP
* - Q
* - Quoted-Printable
* - B
* - Base64
* NOTE: Q, QP, Quoted-Printable are all the same; as are B and Base64
* @param string The encoding format to use
* @return boolean
*/
public function setEncoding($encoding)
{
switch (strtolower($encoding))
{
case "qp": case "q": case "quoted-printable":
$this->encoding = "Q";
return true;
case "base64": case "b":
$this->encoding = "B";
return true;
default: return false;
}
}
/**
* Get the encoding format used in this document
* @return string
*/
public function getEncoding()
{
return $this->encoding;
}
/**
* Turn on or off forced header encoding
* @param boolean On/Off
*/
public function forceEncoding($force=true)
{
$this->forceEncoding = (boolean) $force;
}
/**
* Set an attribute in a major header
* For example $headers->setAttribute("Content-Type", "format", "flowed")
* @param string The main header these values exist in
* @param string The name for this value
* @param string The value to set
* @throws Swift_Message_MimeException If no such header exists
*/
public function setAttribute($header, $name, $value)
{
$name = strtolower($name);
$lheader = strtolower($header);
$this->cached[$lheader] = null;
if (!$this->has($header))
{
throw new Swift_Message_MimeException(
"Cannot set attribute '" . $name . "' for header '" . $header . "' as the header does not exist. " .
"Consider using Swift_Message_Headers-&gt;has() to check.");
}
else
{
Swift_ClassLoader::load("Swift_Message_Encoder");
if (!$this->getCharset() && Swift_Message_Encoder::instance()->isUTF8($value)) $this->setCharset("utf-8");
if (!isset($this->attributes[$lheader])) $this->attributes[$lheader] = array();
if ($value !== null) $this->attributes[$lheader][$name] = (string) $value;
else $this->attributes[$lheader][$name] = $value;
}
}
/**
* Check if a header has a given attribute applied to it
* @param string The name of the main header
* @param string The name of the attribute
* @return boolean
*/
public function hasAttribute($header, $name)
{
$name = strtolower($name);
$lheader = strtolower($header);
if (!$this->has($header))
{
return false;
}
else
{
return (isset($this->attributes[$lheader]) && isset($this->attributes[$lheader][$name]) && ($this->attributes[$lheader][$name] !== null));
}
}
/**
* Get the value for a given attribute on a given header
* @param string The name of the main header
* @param string The name of the attribute
* @return string
* @throws Swift_Message_MimeException If no header is set
*/
public function getAttribute($header, $name)
{
if (!$this->has($header))
{
throw new Swift_Message_MimeException(
"Cannot locate attribute '" . $name . "' for header '" . $header . "' as the header does not exist. " .
"Consider using Swift_Message_Headers-&gt;has() to check.");
}
$name = strtolower($name);
$lheader = strtolower($header);
if ($this->hasAttribute($header, $name))
{
return $this->attributes[$lheader][$name];
}
}
/**
* Remove an attribute from a header
* @param string The name of the header to remove the attribute from
* @param string The name of the attribute to remove
*/
public function removeAttribute($header, $name)
{
$name = strtolower($name);
$lheader = strtolower($header);
if ($this->has($header))
{
unset($this->attributes[$lheader][$name]);
}
}
/**
* Get a list of all the attributes in the given header.
* @param string The name of the header
* @return array
*/
public function listAttributes($header)
{
$header = strtolower($header);
if (array_key_exists($header, $this->attributes))
{
return $this->attributes[$header];
}
else return array();
}
/**
* Get the header in it's compliant, encoded form
* @param string The name of the header
* @return string
* @throws Swift_Message_MimeException If the header doesn't exist
*/
public function getEncoded($name)
{
if (!$this->getCharset()) $this->setCharset("iso-8859-1");
Swift_ClassLoader::load("Swift_Message_Encoder");
//I'll try as best I can to walk through this...
$lname = strtolower($name);
if ($this->cached[$lname] !== null) return $this->cached[$lname];
$value = $this->get($name);
$is_email = in_array($name, $this->emailContainingHeaders);
$encoded_value = (array) $value; //Turn strings into arrays (just to make the following logic simpler)
//Look at each value in this header
// There will only be 1 value if it was a string to begin with, and usually only address lists will be multiple
foreach ($encoded_value as $key => $row)
{
$spec = ""; //The bit which specifies the encoding of the header (if any)
$end = ""; //The end delimiter for an encoded header
//If the header is 7-bit printable it's at no risk of injection
if (Swift_Message_Encoder::instance()->isHeaderSafe($row) && !$this->forceEncoding)
{
//Keeps the total line length at less than 76 chars, taking into account the Header name length
$encoded_value[$key] = Swift_Message_Encoder::instance()->header7BitEncode(
$row, 72, ($key > 0 ? 0 : (75-(strlen($name)+5))), $this->LE);
}
elseif ($this->encoding == "Q") //QP encode required
{
$spec = "=?" . $this->getCharset() . "?Q?"; //e.g. =?iso-8859-1?Q?
$end = "?=";
//Calculate the length of, for example: "From: =?iso-8859-1?Q??="
$used_length = strlen($name) + 2 + strlen($spec) + 2;
//Encode to QP, excluding the specification for now but keeping the lines short enough to be compliant
$encoded_value[$key] = str_replace(" ", "_", Swift_Message_Encoder::instance()->QPEncode(
$row, (75-(strlen($spec)+6)), ($key > 0 ? 0 : (75-$used_length)), true, $this->LE));
}
elseif ($this->encoding == "B") //Need to Base64 encode
{
//See the comments in the elseif() above since the logic is the same (refactor?)
$spec = "=?" . $this->getCharset() . "?B?";
$end = "?=";
$used_length = strlen($name) + 2 + strlen($spec) + 2;
$encoded_value[$key] = Swift_Message_Encoder::instance()->base64Encode(
$row, (75-(strlen($spec)+5)), ($key > 0 ? 0 : (76-($used_length+3))), true, $this->LE);
}
if (false !== $p = strpos($encoded_value[$key], $this->LE))
{
$cb = 'str_replace("' . $this->LE . '", "", "<$1>");';
$encoded_value[$key] = preg_replace("/<([^>]+)>/e", $cb, $encoded_value[$key]);
}
//Turn our header into an array of lines ready for wrapping around the encoding specification
$lines = explode($this->LE, $encoded_value[$key]);
for ($i = 0, $len = count($lines); $i < $len; $i++)
{
//Don't allow commas in address fields without quotes unless they're encoded
if (empty($spec) && $is_email && (false !== $p = strpos($lines[$i], ",")))
{
$s = strpos($lines[$i], " <");
$e = strpos($lines[$i], ">");
if ($s < $e)
{
$addr = substr($lines[$i], $s);
$lines[$i] = "\"" . substr($lines[$i], 0, $s) . "\"" . $addr;
}
else
{
$lines[$i] = "\"" . $lines[$i] . "\"";
}
}
if ($this->encoding == "Q") $lines[$i] = rtrim($lines[$i], "=");
if ($lines[$i] == "" && $i > 0)
{
unset($lines[$i]); //Empty line, we'd rather not have these in the headers thank you!
continue;
}
if ($i > 0)
{
//Don't stick the specification part around the line if it's an address
if (substr($lines[$i], 0, 1) == '<' && substr($lines[$i], -1) == '>') $lines[$i] = " " . $lines[$i];
else $lines[$i] = " " . $spec . $lines[$i] . $end;
}
else
{
if (substr($lines[$i], 0, 1) != '<' || substr($lines[$i], -1) != '>') $lines[$i] = $spec . $lines[$i] . $end;
}
}
//Build back into a string, now includes the specification
$encoded_value[$key] = implode($this->LE, $lines);
$lines = null;
}
//If there are multiple values in this header, put them on separate lines, cleared by commas
$this->cached[$lname] = implode("," . $this->LE . " ", $encoded_value);
//Append attributes if there are any
if (!empty($this->attributes[$lname])) $this->cached[$lname] .= $this->buildAttributes($this->cached[$lname], $lname);
return $this->cached[$lname];
}
/**
* Build the list of attributes for appending to the given header
* This is RFC 2231 & 2047 compliant.
* A HUGE thanks to Joaquim Homrighausen for heaps of help, advice
* and testing to get this working rock solid.
* @param string The header built without attributes
* @param string The lowercase name of the header
* @return string
* @throws Swift_Message_MimeException If no such header exists or there are no attributes
*/
protected function buildAttributes($header_line, $header_name)
{
Swift_ClassLoader::load("Swift_Message_Encoder");
$lines = explode($this->LE, $header_line);
$used_len = strlen($lines[count($lines)-1]);
$lines= null;
$ret = "";
foreach ($this->attributes[$header_name] as $attribute => $att_value)
{
if ($att_value === null) continue;
// 70 to account for LWSP, CRLF, quotes and a semi-colon
// + length of attribute
// + 4 for a 2 digit number and 2 asterisks
$avail_len = 70 - (strlen($attribute) + 4);
$encoded = Swift_Message_Encoder::instance()->rfc2047Encode($att_value, $this->charset, $this->language, $avail_len, $this->LE);
$lines = explode($this->LE, $encoded);
foreach ($lines as $i => $line)
{
//Add quotes if needed (RFC 2045)
if (preg_match("~[\\s\";,<>\\(\\)@:\\\\/\\[\\]\\?=]~", $line)) $lines[$i] = '"' . $line . '"';
}
$encoded = implode($this->LE, $lines);
//If we can fit this entire attribute onto the same line as the header then do it!
if ((strlen($encoded) + $used_len + strlen($attribute) + 4) < 74)
{
if (strpos($encoded, "'") !== false) $attribute .= "*";
$append = "; " . $attribute . "=" . $encoded;
$ret .= $append;
$used_len += strlen($append);
}
else //... otherwise list of underneath
{
$ret .= ";";
if (count($lines) > 1)
{
$loop = false;
$add_asterisk = false;
foreach ($lines as $i => $line)
{
$att_copy = $attribute; //Because it's multi-line it needs asterisks with decimal indices
$att_copy .= "*" . $i;
if ($add_asterisk || strpos($encoded, "'") !== false)
{
$att_copy .= "*"; //And if it's got a ' then it needs another asterisk
$add_asterisk = true;
}
$append = "";
if ($loop) $append .= ";";
$append .= $this->LE . " " . $att_copy . "=" . $line;
$ret .= $append;
$used_len = strlen($append)+1;
$loop = true;
}
}
else
{
if (strpos($encoded, "'") !== false) $attribute .= "*";
$append = $this->LE . " " . $attribute . "=" . $encoded;
$used_len = strlen($append)+1;
$ret .= $append;
}
}
$lines= null;
}
return $ret;
}
/**
* Compile the list of headers which have been set and return an ascii string
* The return value should always be 7-bit ascii and will have been cleaned for header injection
* If this looks complicated it's probably because it is!! Keeping everything compliant is not easy.
* This is RFC 2822 compliant
* @return string
*/
public function build()
{
$ret = "";
foreach ($this->headers as $name => $value) //Look at each header
{
if ($value === null) continue;
$ret .= ltrim($name, ".") . ": " . $this->getEncoded($name) . $this->LE;
}
return trim($ret);
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* Swift Mailer Image Component
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/../ClassLoader.php";
Swift_ClassLoader::load("Swift_Message_EmbeddedFile");
/**
* Embedded Image component for Swift Mailer
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message_Image extends Swift_Message_EmbeddedFile
{
/**
* Constructor
* @param Swift_File The input source file
* @param string The filename to use, optional
* @param string The MIME type to use, optional
* @param string The Content-ID to use, optional
* @param string The encoding format to use, optional
*/
public function __construct(Swift_File $data=null, $name=null, $type="application/octet-stream", $cid=null, $encoding="base64")
{
parent::__construct($data, $name, $type, $cid, $encoding);
}
/**
* Set data for the image
* This overrides setData() in Swift_Message_Attachment
* @param Swift_File The data to set, as a file
* @throws Swift_Message_MimeException If the image cannot be used, or the file is not
*/
public function setData($data, $read_filename=true)
{
if (!($data instanceof Swift_File)) throw new Exception("Parameter 1 of " . __METHOD__ . " must be instance of Swift_File");
parent::setData($data, $read_filename);
$img_data = @getimagesize($data->getPath());
if (!$img_data)
{
throw new Swift_Message_MimeException(
"Cannot use file '" . $data->getPath() . "' as image since getimagesize() was unable to detect a file format. " .
"Try using Swift_Message_EmbeddedFile instead");
}
$type = image_type_to_mime_type($img_data[2]);
$this->setContentType($type);
if (!$this->getFileName()) $this->setFileName($data->getFileName());
}
}

View File

@@ -0,0 +1,500 @@
<?php
/**
* Swift Mailer MIME Library central component
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/../ClassLoader.php";
Swift_ClassLoader::load("Swift_File");
Swift_ClassLoader::load("Swift_Message_MimeException");
/**
* Mime is the underbelly for Messages, Attachments, Parts, Embedded Images, Forwarded Mail, etc
* In fact, every single component of the composed email is simply a new Mime document nested inside another
* When you piece an email together in this way you see just how straight-forward it really is
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
abstract class Swift_Message_Mime
{
/**
* Constant for plain-text emails
*/
const PLAIN = "text/plain";
/**
* Constant for HTML emails
*/
const HTML = "text/html";
/**
* Constant for miscellaneous mime type
*/
const MISC = "application/octet-stream";
/**
* Constant for MIME sections which must appear in the multipart/alternative section.
*/
const LEVEL_ALTERNATIVE = "alternative";
/**
* Constant for MIME sections which must appear in the multipart/related section.
*/
const LEVEL_RELATED = "related";
/**
* Constant for MIME sections which must appear in the multipart/mixed section.
*/
const LEVEL_MIXED = "mixed";
/**
* Constant for MIME sections which must appear in the multipart/mixed section.
*/
const LEVEL_TOP = "top";
/**
* Constant for safe line length in almost all places
*/
const SAFE_LENGTH = 1000; //RFC 2822
/**
* Constant for really safe line length
*/
const VERY_SAFE_LENGTH = 76; //For command line mail clients such as pine
/**
* The header part of this MIME document
* @var Swift_Message_Headers
*/
public $headers = null;
/**
* The body of the documented (unencoded)
* @var string data
*/
protected $data = "";
/**
* Maximum line length
* @var int
*/
protected $wrap = 1000; //RFC 2822
/**
* Nested mime parts
* @var array
*/
protected $children = array();
/**
* The boundary used to separate mime parts
* @var string
*/
protected $boundary = null;
/**
* The line ending characters needed
* @var string
*/
protected $LE = "\r\n";
/**
* An instance of Swift_Cache
* @var Swift_Cache
*/
protected $cache;
/**
* A list of used MIME boundaries after they're generated.
* @var array
*/
protected static $usedBoundaries = array();
/**
* Constructor
*/
public function __construct()
{
Swift_ClassLoader::load("Swift_Message_Headers");
$this->setHeaders(new Swift_Message_Headers());
Swift_ClassLoader::load("Swift_CacheFactory");
$this->cache = Swift_CacheFactory::getCache();
}
/**
* Compute a unique boundary
* @return string
*/
public static function generateBoundary()
{
do
{
$boundary = uniqid(rand(), true);
} while (in_array($boundary, self::$usedBoundaries));
self::$usedBoundaries[] = $boundary;
return "_=_swift-" . $boundary . "_=_";
}
/**
* Replace the current headers with new ones
* DO NOT DO THIS UNLESS YOU KNOW WHAT YOU'RE DOING!
* @param Swift_Message_Headers The headers to use
*/
public function setHeaders($headers)
{
$this->headers = $headers;
}
/**
* Set the line ending character to use
* @param string The line ending sequence
* @return boolean
*/
public function setLE($le)
{
if (in_array($le, array("\r", "\n", "\r\n")))
{
$this->cache->clear("body");
$this->LE = $le;
//This change should be recursive
$this->headers->setLE($le);
foreach ($this->children as $id => $child)
{
$this->children[$id]->setLE($le);
}
return true;
}
else return false;
}
/**
* Get the line ending sequence
* @return string
*/
public function getLE()
{
return $this->LE;
}
/**
* Reset the entire cache state from this branch of the tree and traversing down through the children
*/
public function uncacheAll()
{
$this->cache->clear("body");
$this->cache->clear("append");
$this->cache->clear("headers");
$this->cache->clear("dbl_le");
$this->headers->uncacheAll();
foreach ($this->children as $id => $child)
{
$this->children[$id]->uncacheAll();
}
}
/**
* Set the content type of this MIME document
* @param string The content type to use in the same format as MIME 1.0 expects
*/
public function setContentType($type)
{
$this->headers->set("Content-Type", $type);
}
/**
* Get the content type which has been set
* The MIME 1.0 Content-Type is provided as a string
* @return string
*/
public function getContentType()
{
try {
return $this->headers->get("Content-Type");
} catch (Swift_Message_MimeException $e) {
return false;
}
}
/**
* Set the encoding format to be used on the body of the document
* @param string The encoding type used
* @param boolean If this encoding format should be used recursively. Note, this only takes effect if no encoding is set in the children.
* @param boolean If the encoding should only be applied when the string is not ascii.
*/
public function setEncoding($encoding, $recursive=false, $non_ascii=false)
{
$this->cache->clear("body");
switch (strtolower($encoding))
{
case "q": case "qp": case "quoted-printable":
$encoding = "quoted-printable";
break;
case "b": case "base64":
$encoding = "base64";
break;
case "7bit": case "8bit": case "binary":
$encoding = strtolower($encoding);
break;
}
$data = $this->getData();
Swift_ClassLoader::load("Swift_Message_Encoder");
if ($non_ascii && is_string($data) && strlen($data) > 0 && !Swift_Message_Encoder::instance()->is7BitAscii($data))
{
$this->headers->set("Content-Transfer-Encoding", $encoding);
}
elseif (!$non_ascii || !is_string($data))
{
$this->headers->set("Content-Transfer-Encoding", $encoding);
}
if ($recursive)
{
foreach ($this->children as $id => $child)
{
if (!$child->getEncoding()) $this->children[$id]->setEncoding($encoding, $recursive, $non_ascii);
}
}
}
/**
* Get the encoding format used in this document
* @return string
*/
public function getEncoding()
{
try {
return $this->headers->get("Content-Transfer-Encoding");
} catch (Swift_Message_MimeException $e) {
return false;
}
}
/**
* Specify the string which makes up the body of this message
* HINT: You can always nest another MIME document here if you call it's build() method.
* $data can be an object of Swift_File or a string
* @param mixed The body of the document
*/
public function setData($data)
{
$this->cache->clear("body");
if ($data instanceof Swift_File) $this->data = $data;
else $this->data = (string) $data;
}
/**
* Return the string which makes up the body of this MIME document
* @return string,Swift_File
*/
public function getData()
{
return $this->data;
}
/**
* Get the data in the format suitable for sending
* @return Swift_Cache_OutputStream
* @throws Swift_FileException If the file stream given cannot be read
* @throws Swift_Message_MimeException If some required headers have been forcefully removed
*/
public function buildData()
{
Swift_ClassLoader::load("Swift_Message_Encoder");
Swift_ClassLoader::load("Swift_Cache_JointOutputStream");
if (!empty($this->children)) //If we've got some mime parts we need to stick them onto the end of the message
{
if ($this->boundary === null) $this->boundary = self::generateBoundary();
$this->headers->setAttribute("Content-Type", "boundary", $this->boundary);
$this->cache->clear("append");
foreach ($this->children as $part)
{
$this->cache->write("append", $this->LE . "--" . $this->boundary . $this->LE);
$part_stream = $part->build();
while (false !== $bytes = $part_stream->read()) $this->cache->write("append", $bytes);
}
$this->cache->write("append", $this->LE . "--" . $this->boundary . "--" . $this->LE);
}
$joint_os = new Swift_Cache_JointOutputStream();
//Try using a cached version to save some cycles (at the expense of memory)
//if ($this->cache !== null) return $this->cache . $append;
if ($this->cache->has("body"))
{
$joint_os->addStream($this->cache->getOutputStream("body"));
$joint_os->addStream($this->cache->getOutputStream("append"));
return $joint_os;
}
$is_file = ($this->getData() instanceof Swift_File);
switch ($this->getEncoding())
{
case "quoted-printable":
if ($is_file)
{
$qp_os = Swift_Message_Encoder::instance()->QPEncodeFile($this->getData(), 76, $this->LE);
while (false !== $bytes = $qp_os->read())
$this->cache->write("body", $bytes);
}
else
{
$this->cache->write("body", Swift_Message_Encoder::instance()->QPEncode($this->getData(), 76, 0, false, $this->LE));
}
break;
case "base64":
if ($is_file)
{
$b64_os = Swift_Message_Encoder::instance()->base64EncodeFile($this->getData(), 76, $this->LE);
while (false !== $bytes = $b64_os->read())
$this->cache->write("body", $bytes);
}
else
{
$this->cache->write("body", Swift_Message_Encoder::instance()->base64Encode($this->getData(), 76, 0, false, $this->LE));
}
break;
case "binary":
if ($is_file)
{
$data = $this->getData();
while (false !== $bytes = $data->read(8192))
$this->cache->write("body", $bytes);
}
else
{
$this->cache->write("body", $this->getData());
}
break;
case "7bit":
if ($is_file)
{
$os = Swift_Message_Encoder::instance()->encode7BitFile($this->getData(), $this->wrap, $this->LE);
while (false !== $bytes = $os->read())
$this->cache->write("body", $bytes);
}
else
{
$this->cache->write("body", Swift_Message_Encoder::instance()->encode7Bit($this->getData(), $this->wrap, $this->LE));
}
break;
case "8bit": default:
if ($is_file)
{
$os = Swift_Message_Encoder::instance()->encode8BitFile($this->getData(), $this->wrap, $this->LE);
while (false !== $bytes = $os->read())
$this->cache->write("body", $bytes);
}
else
{
$this->cache->write("body", Swift_Message_Encoder::instance()->encode8Bit($this->getData(), $this->wrap, $this->LE));
}
break;
}
$joint_os->addStream($this->cache->getOutputStream("body"));
$joint_os->addStream($this->cache->getOutputStream("append"));
return $joint_os;
}
/**
* Set the size at which lines wrap around (includes the CRLF)
* @param int The length of a line
*/
public function setLineWrap($len)
{
$this->cache->clear("body");
$this->wrap = (int) $len;
}
/**
* Nest a child mime part in this document
* @param Swift_Message_Mime
* @param string The identifier to use, optional
* @param int Add the part before (-1) or after (+1) the other parts
* @return string The identifier for this part
*/
public function addChild(Swift_Message_Mime $mime, $id=null, $after=1)
{
if (empty($id))
{
do
{
$id = uniqid();
} while (array_key_exists($id, $this->children));
}
$id = (string) $id;
if ($after == -1) $this->children = array_merge(array($id => $mime), $this->children);
else $this->children[$id] = $mime;
return $id;
}
/**
* Check if a child exists identified by $id
* @param string Identifier to look for
* @return boolean
*/
public function hasChild($id)
{
return array_key_exists($id, $this->children);
}
/**
* Get a child document, identified by $id
* @param string The identifier for this child
* @return Swift_Message_Mime The child document
* @throws Swift_Message_MimeException If no such child exists
*/
public function getChild($id)
{
if ($this->hasChild($id))
{
return $this->children[$id];
}
else
{
throw new Swift_Message_MimeException(
"Cannot retrieve child part identified by '" . $id . "' as it does not exist. Consider using hasChild() to check.");
}
}
/**
* Remove a part from the document
* @param string The identifier of the child
* @throws Swift_Message_MimeException If no such part exists
*/
public function removeChild($id)
{
$id = (string) $id;
if (!$this->hasChild($id))
{
throw new Swift_Message_MimeException(
"Cannot remove child part identified by '" . $id . "' as it does not exist. Consider using hasChild() to check.");
}
else
{
$this->children[$id] = null;
unset($this->children[$id]);
}
}
/**
* List the IDs of all children in this document
* @return array
*/
public function listChildren()
{
return array_keys($this->children);
}
/**
* Get the total number of children present in this document
* @return int
*/
public function numChildren()
{
return count($this->children);
}
/**
* Get the level at which this mime part would appear in a document
* One of "mixed", "alternative" or "related"
* @return string
*/
abstract public function getLevel();
/**
* Compile the entire MIME document into a string
* The returned string may be used in other documents if needed.
* @return Swift_Cache_OutputStream
*/
public function build()
{
$this->preBuild();
$data = $this->buildData();
$joint_os = new Swift_Cache_JointOutputStream();
$this->cache->clear("headers");
$this->cache->write("headers", $this->headers->build());
$joint_os->addStream($this->cache->getOutputStream("headers"));
$this->cache->clear("dbl_le");
$this->cache->write("dbl_le", str_repeat($this->LE, 2));
$joint_os->addStream($this->cache->getOutputStream("dbl_le"));
$joint_os->addStream($data);
return $joint_os;
//return $this->headers->build() . str_repeat($this->LE, 2) . $data;
}
/**
* Execute any logic needed prior to building
*/
abstract public function preBuild();
}

View File

@@ -0,0 +1,22 @@
<?php
/**
* Swift MIME Exception
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/../ClassLoader.php";
Swift_ClassLoader::load("Swift_Exception");
/**
* Swift MIME Exception
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message_MimeException extends Swift_Exception
{
}

View File

@@ -0,0 +1,134 @@
<?php
/**
* Swift Mailer Message MIME Part
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/../ClassLoader.php";
Swift_ClassLoader::load("Swift_Message_Mime");
/**
* MIME Part body component for Swift Mailer
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message_Part extends Swift_Message_Mime
{
/**
* Constructor
* @param mixed The data to use in the body
* @param string Mime type
* @param string The encoding format used
* @param string The charset used
*/
public function __construct($data=null, $type="text/plain", $encoding=null, $charset=null)
{
parent::__construct();
$this->setContentType($type);
$this->setEncoding($encoding);
$this->setCharset($charset);
$this->setFlowed(false);
if ($data !== null)
{
$this->setData($data);
if ($charset === null)
{
Swift_ClassLoader::load("Swift_Message_Encoder");
if (is_string($data) && Swift_Message_Encoder::instance()->isUTF8($data)) $this->setCharset("utf-8");
else $this->setCharset("iso-8859-1"); //The likely encoding
}
}
}
/**
* Get the level in the MIME hierarchy at which this section should appear.
* @return string
*/
public function getLevel()
{
return Swift_Message_Mime::LEVEL_ALTERNATIVE;
}
/**
* Alias for setData()
* @param mixed Body
*/
public function setBody($body)
{
$this->setData($body);
}
/**
* Alias for getData()
* @return mixed The document body
*/
public function getBody()
{
return $this->getData();
}
/**
* Set the charset of the document
* @param string The charset used
*/
public function setCharset($charset)
{
$this->headers->setAttribute("Content-Type", "charset", $charset);
if (($this->getEncoding() == "7bit") && (strtolower($charset) == "utf-8" || strtolower($charset) == "utf8")) $this->setEncoding("8bit");
}
/**
* Get the charset used in the document
* Returns null if none is set
* @return string
*/
public function getCharset()
{
if ($this->headers->hasAttribute("Content-Type", "charset"))
{
return $this->headers->getAttribute("Content-Type", "charset");
}
else
{
return null;
}
}
/**
* Set the "format" attribute to flowed
* @param boolean On or Off
*/
public function setFlowed($flowed=true)
{
$value = null;
if ($flowed) $value = "flowed";
$this->headers->setAttribute("Content-Type", "format", $value);
}
/**
* Pre-compilation logic
*/
public function preBuild()
{
if (!($enc = $this->getEncoding())) $this->setEncoding("8bit");
$data = $this->getData();
if ($this->getCharset() === null && !$this->numChildren())
{
if (is_string($data) && Swift_Message_Encoder::instance()->isUTF8($data))
{
$this->setCharset("utf-8");
}
elseif (is_string($data) && Swift_Message_Encoder::instance()->is7BitAscii($data))
{
$this->setCharset("us-ascii");
if (!$enc) $this->setEncoding("7bit");
}
else $this->setCharset("iso-8859-1");
}
elseif ($this->numChildren())
{
$this->setCharset(null);
$this->setEncoding("7bit");
}
}
}