изменения , связанные с удалением устаревшего SwiftMailer и интеграцией SymfonyMailer, UP версии до v3.29 ALT

This commit is contained in:
2025-10-02 18:09:57 +05:00
parent 7283fd1671
commit d5d8b101fd
532 changed files with 49146 additions and 22331 deletions

View File

@@ -1,6 +1,13 @@
### Альтернативная версия AVE.CMS v3.28 ALT
### Альтернативная версия AVE.CMS v3.29 ALT
#### Основное отличие:
#### Удалены оригинальные запросы. На замену им вернулись запросы из старой доброй AVE.CMS ver 2.09RC1 с полным рефакторингом кода под текущие среды и задачи. Теперь снова доступен выпадающий список в качестве панели управления условиями запроса из публичной части сайта, создавать фильтры стало как никогда легко и просто, а условия, созданные в админке, полностью работоспособны.
#### Работает в программной среде: PHP-8.4 MySQL-8.4
#### Работает в программной среде: PHP-8.4.x MySQL-8.4.x
#### Добавлена поддержка графических файлов изображений в формате .webp
#### Обновлены библиотеки
### Changelog:
#### Версия v3.29 ALT - удален устаревший Swift Mailer, на замену ему интегрирован Symfony Mailer;
#### В Системных настройках, при выборе метода отправки почты: SMTP --> Шифрование, добавлены новые пункты: TLS (без проверки сертификата) и SSL (без проверки сертификата). Это дает возможность полноценно настраивать почту на локальном хосте.
####

View File

@@ -30,7 +30,11 @@ SETTINGS_MAIL_PORT = "Порт SMTP:"
SETTINGS_SMTP_NAME = "Пользователь:"
SETTINGS_SMTP_PASS = "Пароль:"
SETTINGS_SMTP_ENCRYPT = "Шифрование"
SETTINGS_SMTP_NOENCRYPT = "нет"
SETTINGS_SMTP_NOENCRYPT = "Нет"
SETTINGS_SMTP_TLS_CHECK = "TLS"
SETTINGS_SMTP_TLS_NO_CHECK = "TLS (без проверки сертификата)"
SETTINGS_SMTP_SSL_CHECK = "SSL"
SETTINGS_SMTP_SSL_NO_CHECK = "SSL (без проверки сертификата)"
SETTINGS_MAIL_PATH = "Путь до папки sendmail:"
SETTINGS_SYMBOL_BREAK = "Принудительный перенос после (знаков):"
SETTINGS_SYMBOL_BREAK_INFO = "Не более 1000 согласно RFC 2822"

View File

@@ -254,8 +254,10 @@
<div class="pr12">
<select name="mail_smtp_encrypt" class="mousetrap">
<option value="">{#SETTINGS_SMTP_NOENCRYPT#}</option>
<option value="tls"{if $row.mail_smtp_encrypt=='tls'} selected="selected"{/if}>TLS</option>
<option value="ssl"{if $row.mail_smtp_encrypt=='ssl'} selected="selected"{/if}>SSL</option>
<option value="tls"{if $row.mail_smtp_encrypt=='tls'} selected="selected"{/if}>{#SETTINGS_SMTP_TLS_CHECK#}</option>
<option value="tls_insecure"{if $row.mail_smtp_encrypt=='tls_insecure'} selected="selected"{/if}>{#SETTINGS_SMTP_TLS_NO_CHECK#}</option>
<option value="ssl"{if $row.mail_smtp_encrypt=='ssl'} selected="selected"{/if}>{#SETTINGS_SMTP_SSL_CHECK#}</option>
<option value="ssl_insecure"{if $row.mail_smtp_encrypt=='ssl_insecure'} selected="selected"{/if}>{#SETTINGS_SMTP_SSL_NO_CHECK#}</option>
</select>
</div>
</td>

View File

@@ -1,252 +1,349 @@
<?php
/**
* AVE.cms
*
* @package AVE.cms
* @version 3.x
* @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
*
* @license GPL v.2
*/
/**
* AVE.cms
*
* @package AVE.cms
* @version 3.x
* @filesource
* @copyright © 2007-2014 AVE.cms, http://www.ave-cms.ru
*
* @license GPL v.2
*/
// ----------------------------------------------------------------------
// БЛОК SYMFONY MAILER: Подключение и использование пространств имен
// ----------------------------------------------------------------------
// Подключаем Composer Autoload
require_once BASE_DIR . '/lib/SymfonyMailer/vendor/autoload.php';
// Импорт необходимых классов Symfony Mailer
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
// ----------------------------------------------------------------------
/**
* Отправка e-Mail
*
* @param string $to - email получателя
* @param string $body - текст сообщения
* @param string $subject - тема сообщения
* @param string $from_email - e-mail отправителя
* @param string $from_name - имя отправителя
* @param string $type - содержимое (html или text)
* @param array $attach - пути файлов вложений
* @param bool $saveattach - сохранять вложения после отправки в ATTACH_DIR?
* @param bool $signature - добавлять подпись из общих настроек?
*/
if (! function_exists('send_mail'))
{
function send_mail($to='', $body='', $subject='', $from_email='', $from_name='', $type='text', $attach=array(), $saveattach=true, $signature=true)
{
require_once BASE_DIR . '/lib/SwiftMailer/swift_required.php';
/**
* Отправка e-Mail
*
* @param string $to - email получателя
* @param string $body - текст сообщения
* @param string $subject - тема сообщения
* @param string $from_email - e-mail отправителя
* @param string $from_name - имя отправителя
* @param string $type - содержимое (html или text)
* @param array $attach - пути файлов вложений
* @param bool $saveattach - сохранять вложения после отправки в ATTACH_DIR?
* @param bool $signature - добавлять подпись из общих настроек?
*/
if (! function_exists('send_mail'))
{
function send_mail($to='', $body='', $subject='', $from_email='', $from_name='', $type='text', $attach=array(), $saveattach=true, $signature=true)
{
unset($transport, $message, $mailer);
unset($transport, $message, $mailer);
$to = str_nospace($to);
$to = str_nospace($to);
$from_email = str_nospace($from_email);
$from_email = str_nospace($from_email);
// Определяем тип письма
$type = ((strtolower($type) == 'html' || strtolower($type) == 'text/html') ? 'text/html' : 'text/plain');
// Определяем тип письма
$type = ((strtolower($type) == 'html' || strtolower($type) == 'text/html') ? 'text/html' : 'text/plain');
// Добавляем подпись, если просили
if ($signature)
{
if ($type == 'text/html')
{
$signature = '<br><br>' . nl2br(get_settings('mail_signature'));
}
else
{
$signature = "\r\n\r\n" . get_settings('mail_signature');
}
}
else $signature = '';
// Добавляем подпись, если просили
if ($signature)
{
if ($type == 'text/html')
{
$signature = '<br><br>' . nl2br(get_settings('mail_signature'));
}
else
{
$signature = "\r\n\r\n" . get_settings('mail_signature');
}
}
else $signature = '';
// Составляем тело письма
$body = stripslashes($body) . $signature;
// Составляем тело письма
$body = stripslashes($body) . $signature;
if ($type == 'text/html')
{
$body = str_replace(array("\t","\r","\n"),'',$body);
$body = str_replace(array(' ','> <'),array(' ','><'),$body);
}
if ($type == 'text/html')
{
$body = str_replace(array("\t","\r","\n"),'',$body);
$body = str_replace(array(' ','> <'),array(' ','><'),$body);
}
// ----------------------------------------------------
// БЛОК SYMFONY MAILER: Инициализация и настройка письма
// ----------------------------------------------------
// Формируем письмо
$message = Swift_Message::newInstance($subject)
-> setFrom(array($from_email => $from_name))
-> setTo($to)
-> setContentType($type)
-> setBody($body)
-> setMaxLineLength((int)get_settings('mail_word_wrap'));
$message = new Email();
$message->getHeaders()->addTextHeader('X-Mailer', 'AVE.cms Symfony Mailer');
$message->subject($subject);
// Прикрепляем вложения
if ($attach)
{
foreach ($attach as $attach_file)
{
$message -> attach(Swift_Attachment::fromPath(trim($attach_file)));
}
}
// Отправитель
$message->from(new Address($from_email, $from_name));
// Выбираем метод отправки и формируем транспорт
switch (get_settings('mail_type'))
{
default:
case 'mail':
$transport = Swift_MailTransport::newInstance();
break;
// Получатель (разбиваем строку $to на массив адресов)
$to_addresses = array_map('trim', explode(',', $to));
$message->to(...$to_addresses);
case 'smtp':
$transport = Swift_SmtpTransport::newInstance(stripslashes(get_settings('mail_host')), (int)get_settings('mail_port'));
// Тело письма
if ($type == 'text/html') {
$message->html($body);
$message->text(strip_tags($body)); // AltBody
} else {
$message->text($body);
}
// Добавляем шифрование
$smtp_encrypt = get_settings('mail_smtp_encrypt');
if($smtp_encrypt)
$transport
->setEncryption(strtolower(stripslashes($smtp_encrypt)));
// ----------------------------------------------------
// БЛОК SYMFONY MAILER: Прикрепление вложений
// ----------------------------------------------------
// Имя пользователя/пароль
$smtp_user = get_settings('mail_smtp_login');
$smtp_pass = get_settings('mail_smtp_pass');
if($smtp_user)
$transport
->setUsername(stripslashes($smtp_user))
->setPassword(stripslashes($smtp_pass));
break;
if ($attach)
{
foreach ($attach as $attach_file)
{
$file_path = trim($attach_file);
if ($file_path && file_exists($file_path)) {
$message->attachFromPath($file_path);
}
}
}
case 'sendmail':
$transport = Swift_SendmailTransport::newInstance(get_settings('mail_sendmail_path'));
break;
}
// ----------------------------------------------------
// БЛОК SYMFONY MAILER: Формирование DSN
// ----------------------------------------------------
// Сохраняем вложения в ATTACH_DIR, если просили
if ($attach && $saveattach)
{
$attach_dir = BASE_DIR . '/tmp/' . ATTACH_DIR . '/';
foreach ($attach as $file_path)
{
if ($file_path && file_exists($file_path))
{
$file_name = basename($file_path);
$file_name = str_replace(' ','',mb_strtolower(trim($file_name)));
if (file_exists($attach_dir . $file_name))
{
$file_name = rand(1000, 9999) . '_' . $file_name;
}
$file_path_new = $attach_dir . $file_name;
if (!@move_uploaded_file($file_path,$file_path_new))
{
copy($file_path,$file_path_new);
}
}
}
}
$transport_dsn = '';
$mail_type = get_settings('mail_type');
// Отправляем письмо
/** @var $transport TYPE_NAME */
$mailer = Swift_Mailer::newInstance($transport);
switch ($mail_type) {
// Резервный DSN (если выбрано что-то неизвестное)
default:
$transport_dsn = 'native://default';
break;
if (!@$mailer -> send($message, $failures))
{
reportLog('Не удалось отправить письма следующим адресатам: ' . implode(',',$failures));
return $failures;
}
// МЕТОД 'mail' (Самый простой и надежный)
case 'mail':
// DSN 'sendmail://default' использует внутреннюю, стабильную функцию PHP mail().
$transport_dsn = 'sendmail://default';
break;
}
}
// 2. МЕТОД 'sendmail' (Использует путь из настроек, но только если он работает, проверяйте на VDS командой # systemctl status sendmail)
case 'sendmail':
$path = get_settings('mail_sendmail_path'); // Берем путь из настроек
// DSN для прямого вызова исполняемого файла
$transport_dsn = 'sendmail://default?command=' . urlencode($path);
break;
if ( ! function_exists('safe_mailto'))
{
function safe_mailto($email, $title = '', $attributes = '')
{
$title = (string) $title;
case 'smtp':
$host = stripslashes(get_settings('mail_host'));
$port = (int)get_settings('mail_port');
$user = stripslashes(get_settings('mail_smtp_login'));
$pass = stripslashes(get_settings('mail_smtp_pass'));
// Получаем значение шифрования, которое теперь может быть 'tls_insecure' или 'ssl_insecure'
$encrypt_setting = strtolower(stripslashes(get_settings('mail_smtp_encrypt')));
if ($title == "")
{
$title = $email;
}
$scheme = 'smtp';
$encryption = '';
$extra_params = '';
for ($i = 0; $i < 16; $i++)
{
$x[] = substr('<a href="mailto:', $i, 1);
}
// 1. Определяем тип шифрования и необходимость отключения проверки
if (str_contains($encrypt_setting, 'insecure')) {
// Если выбрано *_insecure, отключаем проверку
$extra_params = '&verify_peer=0';
// Извлекаем чистый тип шифрования (tls или ssl)
$encryption = str_replace('_insecure', '', $encrypt_setting);
} elseif ($encrypt_setting === 'tls' || $encrypt_setting === 'ssl') {
// Если выбрано обычное шифрование, включаем его (проверка peer=1 по умолчанию)
$encryption = $encrypt_setting;
}
// 2. Формируем DSN в зависимости от наличия шифрования
if ($encryption) {
// Если есть шифрование (tls или ssl), добавляем его и доп. параметры
$transport_dsn = sprintf('%s://%s:%s@%s:%d?encryption=%s%s',
$scheme,
urlencode($user),
urlencode($pass),
$host,
$port,
$encryption, // 'tls' или 'ssl'
$extra_params // '' или '&verify_peer=0'
);
} else {
// Без шифрования (когда выбрано "Нет")
$transport_dsn = sprintf('smtp://%s:%s@%s:%d',
urlencode($user),
urlencode($pass),
$host,
$port ?: 25 // Порт 25 по умолчанию
);
}
for ($i = 0; $i < strlen($email); $i++)
{
$x[] = "|".ord(substr($email, $i, 1));
}
break;
$x[] = '"';
}
if ($attributes != '')
{
if (is_array($attributes))
{
foreach ($attributes as $key => $val)
{
$x[] = ' '.$key.'="';
for ($i = 0; $i < strlen($val); $i++)
{
$x[] = "|".ord(substr($val, $i, 1));
}
$x[] = '"';
}
}
else
{
for ($i = 0; $i < strlen($attributes); $i++)
{
$x[] = substr($attributes, $i, 1);
}
}
}
// Сохраняем вложения в ATTACH_DIR, если просили
if ($attach && $saveattach)
{
$attach_dir = BASE_DIR . '/tmp/' . ATTACH_DIR . '/';
foreach ($attach as $file_path)
{
if ($file_path && file_exists($file_path))
{
$file_name = basename($file_path);
$file_name = str_replace(' ','',mb_strtolower(trim($file_name)));
if (file_exists($attach_dir . $file_name))
{
$file_name = rand(1000, 9999) . '_' . $file_name;
}
$file_path_new = $attach_dir . $file_name;
if (!@move_uploaded_file($file_path,$file_path_new))
{
copy($file_path,$file_path_new);
}
}
}
}
$x[] = '>';
// ----------------------------------------------------
// БЛОК SYMFONY MAILER: Отправка и обработка ошибок
// ----------------------------------------------------
$temp = array();
try {
// 1. Создаем транспорт из DSN
$transport = Transport::fromDsn($transport_dsn);
for ($i = 0; $i < strlen($title); $i++)
{
$ordinal = ord($title[$i]);
// 2. Создаем почтальона (Mailer)
$mailer = new Mailer($transport);
if ($ordinal < 128)
{
$x[] = "|".$ordinal;
}
else
{
if (count($temp) == 0)
{
$count = ($ordinal < 224) ? 2 : 3;
}
// 3. Отправляем сообщение
$mailer->send($message);
$temp[] = $ordinal;
if (count($temp) == $count)
{
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
$x[] = "|".$number;
$count = 1;
$temp = array();
}
}
}
return true; // Успех
} catch (TransportExceptionInterface $e) {
// Записываем специфические ошибки Symfony Mailer в лог
reportLog('Не удалось отправить письма. Symfony Mailer Transport Error: ' . $e->getMessage());
return false; // Неудача
} catch (\Exception $e) {
// Общая ошибка (на всякий случай)
reportLog('Не удалось отправить письма. Symfony Mailer Fatal Error: ' . $e->getMessage());
return false;
}
// ----------------------------------------------------
// КОНЕЦ БЛОКА SYMFONY MAILER
// ----------------------------------------------------
$x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>';
}
}
$x = array_reverse($x);
ob_start();
if ( ! function_exists('safe_mailto'))
{
function safe_mailto($email, $title = '', $attributes = '')
{
$title = (string) $title;
?><script type="text/javascript">
//<![CDATA[
var l=new Array();
<?php
$i = 0;
foreach ($x as $val){ ?>l[<?php echo $i++; ?>]='<?php echo $val; ?>';<?php } ?>
if ($title == "")
{
$title = $email;
}
for (var i = l.length-1; i >= 0; i=i-1){
if
(l[i].substring(0, 1) == '|') document.write("&#"+unescape(l[i].substring(1))+";");
else
document.write(unescape(l[i]));}
//]]>
</script><?php
for ($i = 0; $i < 16; $i++)
{
$x[] = substr('<a href="mailto:', $i, 1);
}
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
}
for ($i = 0; $i < strlen($email); $i++)
{
$x[] = "|".ord(substr($email, $i, 1));
}
$x[] = '"';
if ($attributes != '')
{
if (is_array($attributes))
{
foreach ($attributes as $key => $val)
{
$x[] = ' '.$key.'="';
for ($i = 0; $i < strlen($val); $i++)
{
$x[] = "|".ord(substr($val, $i, 1));
}
$x[] = '"';
}
}
else
{
for ($i = 0; $i < strlen($attributes); $i++)
{
$x[] = substr($attributes, $i, 1);
}
}
}
$x[] = '>';
$temp = array();
for ($i = 0; $i < strlen($title); $i++)
{
$ordinal = ord($title[$i]);
if ($ordinal < 128)
{
$x[] = "|".$ordinal;
}
else
{
if (count($temp) == 0)
{
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) == $count)
{
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] % 64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
$x[] = "|".$number;
$count = 1;
$temp = array();
}
}
}
$x[] = '<'; $x[] = '/'; $x[] = 'a'; $x[] = '>';
$x = array_reverse($x);
ob_start();
?><script type="text/javascript">
//<![CDATA[
var l=new Array();
<?php
$i = 0;
foreach ($x as $val){ ?>l[<?php echo $i++; ?>]='<?php echo $val; ?>';<?php } ?>
for (var i = l.length-1; i >= 0; i=i-1){
if
(l[i].substring(0, 1) == '|') document.write("&#"+unescape(l[i].substring(1))+";");
else
document.write(unescape(l[i]));}
//]]>
</script><?php
$buffer = ob_get_contents();
ob_end_clean();
return $buffer;
}
}
?>

View File

@@ -12,7 +12,7 @@
*/
define('APP_NAME', 'AVE.cms');
define('APP_VERSION', '3.28 ALT');
define('APP_VERSION', '3.29 ALT');
define('APP_INFO', '<a target="_blank" href="https://ave-cms.ru/">Ave-Cms.Ru</a> '.'&copy; 2007-' . date('Y'));
$themes = [];

View File

@@ -1,80 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* General utility class in Swift Mailer, not to be instantiated.
*
*
* @author Chris Corbyn
*/
abstract class Swift
{
/** Swift Mailer Version number generated during dist release process */
const VERSION = '@SWIFT_VERSION_NUMBER@';
public static $initialized = false;
public static $inits = array();
/**
* Registers an initializer callable that will be called the first time
* a SwiftMailer class is autoloaded.
*
* This enables you to tweak the default configuration in a lazy way.
*
* @param mixed $callable A valid PHP callable that will be called when autoloading the first Swift class
*/
public static function init($callable)
{
self::$inits[] = $callable;
}
/**
* Internal autoloader for spl_autoload_register().
*
* @param string $class
*/
public static function autoload($class)
{
// Don't interfere with other autoloaders
if (0 !== strpos($class, 'Swift_')) {
return;
}
$path = __DIR__.'/'.str_replace('_', '/', $class).'.php';
if (!file_exists($path)) {
return;
}
require $path;
if (self::$inits && !self::$initialized) {
self::$initialized = true;
foreach (self::$inits as $init) {
call_user_func($init);
}
}
}
/**
* Configure autoloading using Swift Mailer.
*
* This is designed to play nicely with other autoloaders.
*
* @param mixed $callable A valid PHP callable that will be called when autoloading the first Swift class
*/
public static function registerAutoload($callable = null)
{
if (null !== $callable) {
self::$inits[] = $callable;
}
spl_autoload_register(array('Swift', 'autoload'));
}
}

View File

@@ -1,71 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Attachment class for attaching files to a {@link Swift_Mime_Message}.
*
* @author Chris Corbyn
*/
class Swift_Attachment extends Swift_Mime_Attachment
{
/**
* Create a new Attachment.
*
* Details may be optionally provided to the constructor.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*/
public function __construct($data = null, $filename = null, $contentType = null)
{
call_user_func_array(
array($this, 'Swift_Mime_Attachment::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.attachment')
);
$this->setBody($data);
$this->setFilename($filename);
if ($contentType) {
$this->setContentType($contentType);
}
}
/**
* Create a new Attachment.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*
* @return Swift_Mime_Attachment
*/
public static function newInstance($data = null, $filename = null, $contentType = null)
{
return new self($data, $filename, $contentType);
}
/**
* Create a new Attachment from a filesystem path.
*
* @param string $path
* @param string $contentType optional
*
* @return Swift_Mime_Attachment
*/
public static function fromPath($path, $contentType = null)
{
return self::newInstance()->setFile(
new Swift_ByteStream_FileByteStream($path),
$contentType
);
}
}

View File

@@ -1,181 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Provides the base functionality for an InputStream supporting filters.
*
* @author Chris Corbyn
*/
abstract class Swift_ByteStream_AbstractFilterableInputStream implements Swift_InputByteStream, Swift_Filterable
{
/**
* Write sequence.
*/
protected $_sequence = 0;
/**
* StreamFilters.
*
* @var Swift_StreamFilter[]
*/
private $_filters = array();
/**
* A buffer for writing.
*/
private $_writeBuffer = '';
/**
* Bound streams.
*
* @var Swift_InputByteStream[]
*/
private $_mirrors = array();
/**
* Commit the given bytes to the storage medium immediately.
*
* @param string $bytes
*/
abstract protected function _commit($bytes);
/**
* Flush any buffers/content with immediate effect.
*/
abstract protected function _flush();
/**
* Add a StreamFilter to this InputByteStream.
*
* @param Swift_StreamFilter $filter
* @param string $key
*/
public function addFilter(Swift_StreamFilter $filter, $key)
{
$this->_filters[$key] = $filter;
}
/**
* Remove an already present StreamFilter based on its $key.
*
* @param string $key
*/
public function removeFilter($key)
{
unset($this->_filters[$key]);
}
/**
* Writes $bytes to the end of the stream.
*
* @param string $bytes
*
* @throws Swift_IoException
*
* @return int
*/
public function write($bytes)
{
$this->_writeBuffer .= $bytes;
foreach ($this->_filters as $filter) {
if ($filter->shouldBuffer($this->_writeBuffer)) {
return;
}
}
$this->_doWrite($this->_writeBuffer);
return ++$this->_sequence;
}
/**
* For any bytes that are currently buffered inside the stream, force them
* off the buffer.
*
* @throws Swift_IoException
*/
public function commit()
{
$this->_doWrite($this->_writeBuffer);
}
/**
* Attach $is to this stream.
*
* The stream acts as an observer, receiving all data that is written.
* All {@link write()} and {@link flushBuffers()} operations will be mirrored.
*
* @param Swift_InputByteStream $is
*/
public function bind(Swift_InputByteStream $is)
{
$this->_mirrors[] = $is;
}
/**
* Remove an already bound stream.
*
* If $is is not bound, no errors will be raised.
* If the stream currently has any buffered data it will be written to $is
* before unbinding occurs.
*
* @param Swift_InputByteStream $is
*/
public function unbind(Swift_InputByteStream $is)
{
foreach ($this->_mirrors as $k => $stream) {
if ($is === $stream) {
if ($this->_writeBuffer !== '') {
$stream->write($this->_writeBuffer);
}
unset($this->_mirrors[$k]);
}
}
}
/**
* Flush the contents of the stream (empty it) and set the internal pointer
* to the beginning.
*
* @throws Swift_IoException
*/
public function flushBuffers()
{
if ($this->_writeBuffer !== '') {
$this->_doWrite($this->_writeBuffer);
}
$this->_flush();
foreach ($this->_mirrors as $stream) {
$stream->flushBuffers();
}
}
/** Run $bytes through all filters */
private function _filter($bytes)
{
foreach ($this->_filters as $filter) {
$bytes = $filter->filter($bytes);
}
return $bytes;
}
/** Just write the bytes to the stream */
private function _doWrite($bytes)
{
$this->_commit($this->_filter($bytes));
foreach ($this->_mirrors as $stream) {
$stream->write($bytes);
}
$this->_writeBuffer = '';
}
}

View File

@@ -1,182 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Allows reading and writing of bytes to and from an array.
*
* @author Chris Corbyn
*/
class Swift_ByteStream_ArrayByteStream implements Swift_InputByteStream, Swift_OutputByteStream
{
/**
* The internal stack of bytes.
*
* @var string[]
*/
private $_array = array();
/**
* The size of the stack.
*
* @var int
*/
private $_arraySize = 0;
/**
* The internal pointer offset.
*
* @var int
*/
private $_offset = 0;
/**
* Bound streams.
*
* @var Swift_InputByteStream[]
*/
private $_mirrors = array();
/**
* Create a new ArrayByteStream.
*
* If $stack is given the stream will be populated with the bytes it contains.
*
* @param mixed $stack of bytes in string or array form, optional
*/
public function __construct($stack = null)
{
if (is_array($stack)) {
$this->_array = $stack;
$this->_arraySize = count($stack);
} elseif (is_string($stack)) {
$this->write($stack);
} else {
$this->_array = array();
}
}
/**
* Reads $length bytes from the stream into a string and moves the pointer
* through the stream by $length.
*
* If less bytes exist than are requested the
* remaining bytes are given instead. If no bytes are remaining at all, boolean
* false is returned.
*
* @param int $length
*
* @return string
*/
public function read($length)
{
if ($this->_offset == $this->_arraySize) {
return false;
}
// Don't use array slice
$end = $length + $this->_offset;
$end = $this->_arraySize < $end ? $this->_arraySize : $end;
$ret = '';
for (; $this->_offset < $end; ++$this->_offset) {
$ret .= $this->_array[$this->_offset];
}
return $ret;
}
/**
* Writes $bytes to the end of the stream.
*
* @param string $bytes
*/
public function write($bytes)
{
$to_add = str_split($bytes);
foreach ($to_add as $value) {
$this->_array[] = $value;
}
$this->_arraySize = count($this->_array);
foreach ($this->_mirrors as $stream) {
$stream->write($bytes);
}
}
/**
* Not used.
*/
public function commit()
{
}
/**
* Attach $is to this stream.
*
* The stream acts as an observer, receiving all data that is written.
* All {@link write()} and {@link flushBuffers()} operations will be mirrored.
*
* @param Swift_InputByteStream $is
*/
public function bind(Swift_InputByteStream $is)
{
$this->_mirrors[] = $is;
}
/**
* Remove an already bound stream.
*
* If $is is not bound, no errors will be raised.
* If the stream currently has any buffered data it will be written to $is
* before unbinding occurs.
*
* @param Swift_InputByteStream $is
*/
public function unbind(Swift_InputByteStream $is)
{
foreach ($this->_mirrors as $k => $stream) {
if ($is === $stream) {
unset($this->_mirrors[$k]);
}
}
}
/**
* Move the internal read pointer to $byteOffset in the stream.
*
* @param int $byteOffset
*
* @return bool
*/
public function setReadPointer($byteOffset)
{
if ($byteOffset > $this->_arraySize) {
$byteOffset = $this->_arraySize;
} elseif ($byteOffset < 0) {
$byteOffset = 0;
}
$this->_offset = $byteOffset;
}
/**
* Flush the contents of the stream (empty it) and set the internal pointer
* to the beginning.
*/
public function flushBuffers()
{
$this->_offset = 0;
$this->_array = array();
$this->_arraySize = 0;
foreach ($this->_mirrors as $stream) {
$stream->flushBuffers();
}
}
}

View File

@@ -1,231 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Allows reading and writing of bytes to and from a file.
*
* @author Chris Corbyn
*/
class Swift_ByteStream_FileByteStream extends Swift_ByteStream_AbstractFilterableInputStream implements Swift_FileStream
{
/** The internal pointer offset */
private $_offset = 0;
/** The path to the file */
private $_path;
/** The mode this file is opened in for writing */
private $_mode;
/** A lazy-loaded resource handle for reading the file */
private $_reader;
/** A lazy-loaded resource handle for writing the file */
private $_writer;
/** If magic_quotes_runtime is on, this will be true */
private $_quotes = false;
/** If stream is seekable true/false, or null if not known */
private $_seekable = null;
/**
* Create a new FileByteStream for $path.
*
* @param string $path
* @param bool $writable if true
*/
public function __construct($path, $writable = false)
{
if (empty($path)) {
throw new Swift_IoException('The path cannot be empty');
}
$this->_path = $path;
$this->_mode = $writable ? 'w+b' : 'rb';
if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) {
$this->_quotes = true;
}
}
/**
* Get the complete path to the file.
*
* @return string
*/
public function getPath()
{
return $this->_path;
}
/**
* Reads $length bytes from the stream into a string and moves the pointer
* through the stream by $length.
*
* If less bytes exist than are requested the
* remaining bytes are given instead. If no bytes are remaining at all, boolean
* false is returned.
*
* @param int $length
*
* @throws Swift_IoException
*
* @return string|bool
*/
public function read($length)
{
$fp = $this->_getReadHandle();
if (!feof($fp)) {
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 0);
}
$bytes = fread($fp, $length);
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 1);
}
$this->_offset = ftell($fp);
// If we read one byte after reaching the end of the file
// feof() will return false and an empty string is returned
if ($bytes === '' && feof($fp)) {
$this->_resetReadHandle();
return false;
}
return $bytes;
}
$this->_resetReadHandle();
return false;
}
/**
* Move the internal read pointer to $byteOffset in the stream.
*
* @param int $byteOffset
*
* @return bool
*/
public function setReadPointer($byteOffset)
{
if (isset($this->_reader)) {
$this->_seekReadStreamToPosition($byteOffset);
}
$this->_offset = $byteOffset;
}
/** Just write the bytes to the file */
protected function _commit($bytes)
{
fwrite($this->_getWriteHandle(), $bytes);
$this->_resetReadHandle();
}
/** Not used */
protected function _flush()
{
}
/** Get the resource for reading */
private function _getReadHandle()
{
if (!isset($this->_reader)) {
$pointer = @fopen($this->_path, 'rb');
if (!$pointer) {
throw new Swift_IoException(
'Unable to open file for reading ['.$this->_path.']'
);
}
$this->_reader = $pointer;
if ($this->_offset != 0) {
$this->_getReadStreamSeekableStatus();
$this->_seekReadStreamToPosition($this->_offset);
}
}
return $this->_reader;
}
/** Get the resource for writing */
private function _getWriteHandle()
{
if (!isset($this->_writer)) {
if (!$this->_writer = fopen($this->_path, $this->_mode)) {
throw new Swift_IoException(
'Unable to open file for writing ['.$this->_path.']'
);
}
}
return $this->_writer;
}
/** Force a reload of the resource for reading */
private function _resetReadHandle()
{
if (isset($this->_reader)) {
fclose($this->_reader);
$this->_reader = null;
}
}
/** Check if ReadOnly Stream is seekable */
private function _getReadStreamSeekableStatus()
{
$metas = stream_get_meta_data($this->_reader);
$this->_seekable = $metas['seekable'];
}
/** Streams in a readOnly stream ensuring copy if needed */
private function _seekReadStreamToPosition($offset)
{
if ($this->_seekable === null) {
$this->_getReadStreamSeekableStatus();
}
if ($this->_seekable === false) {
$currentPos = ftell($this->_reader);
if ($currentPos < $offset) {
$toDiscard = $offset - $currentPos;
fread($this->_reader, $toDiscard);
return;
}
$this->_copyReadStream();
}
fseek($this->_reader, $offset, SEEK_SET);
}
/** Copy a readOnly Stream to ensure seekability */
private function _copyReadStream()
{
if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) {
/* We have opened a php:// Stream Should work without problem */
} elseif (function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir()) && ($tmpFile = tmpfile())) {
/* We have opened a tmpfile */
} else {
throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available');
}
$currentPos = ftell($this->_reader);
fclose($this->_reader);
$source = fopen($this->_path, 'rb');
if (!$source) {
throw new Swift_IoException('Unable to open file for copying ['.$this->_path.']');
}
fseek($tmpFile, 0, SEEK_SET);
while (!feof($source)) {
fwrite($tmpFile, fread($source, 4096));
}
fseek($tmpFile, $currentPos, SEEK_SET);
fclose($source);
$this->_reader = $tmpFile;
}
}

View File

@@ -1,42 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @author Romain-Geissler
*/
class Swift_ByteStream_TemporaryFileByteStream extends Swift_ByteStream_FileByteStream
{
public function __construct()
{
$filePath = tempnam(sys_get_temp_dir(), 'FileByteStream');
if ($filePath === false) {
throw new Swift_IoException('Failed to retrieve temporary file name.');
}
parent::__construct($filePath, true);
}
public function getContent()
{
if (($content = file_get_contents($this->getPath())) === false) {
throw new Swift_IoException('Failed to get temporary file content.');
}
return $content;
}
public function __destruct()
{
if (file_exists($this->getPath())) {
@unlink($this->getPath());
}
}
}

View File

@@ -1,67 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Analyzes characters for a specific character set.
*
* @author Chris Corbyn
* @author Xavier De Cock <xdecock@gmail.com>
*/
interface Swift_CharacterReader
{
const MAP_TYPE_INVALID = 0x01;
const MAP_TYPE_FIXED_LEN = 0x02;
const MAP_TYPE_POSITIONS = 0x03;
/**
* Returns the complete character map.
*
* @param string $string
* @param int $startOffset
* @param array $currentMap
* @param mixed $ignoredChars
*
* @return int
*/
public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars);
/**
* Returns the mapType, see constants.
*
* @return int
*/
public function getMapType();
/**
* Returns an integer which specifies how many more bytes to read.
*
* A positive integer indicates the number of more bytes to fetch before invoking
* this method again.
*
* A value of zero means this is already a valid character.
* A value of -1 means this cannot possibly be a valid character.
*
* @param integer[] $bytes
* @param int $size
*
* @return int
*/
public function validateByteSequence($bytes, $size);
/**
* Returns the number of bytes which should be read to start each character.
*
* For fixed width character sets this should be the number of octets-per-character.
* For multibyte character sets this will probably be 1.
*
* @return int
*/
public function getInitialByteSize();
}

View File

@@ -1,97 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Provides fixed-width byte sizes for reading fixed-width character sets.
*
* @author Chris Corbyn
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader
{
/**
* The number of bytes in a single character.
*
* @var int
*/
private $_width;
/**
* Creates a new GenericFixedWidthReader using $width bytes per character.
*
* @param int $width
*/
public function __construct($width)
{
$this->_width = $width;
}
/**
* Returns the complete character map.
*
* @param string $string
* @param int $startOffset
* @param array $currentMap
* @param mixed $ignoredChars
*
* @return int
*/
public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars)
{
$strlen = strlen($string);
// % and / are CPU intensive, so, maybe find a better way
$ignored = $strlen % $this->_width;
$ignoredChars = $ignored ? substr($string, -$ignored) : '';
$currentMap = $this->_width;
return ($strlen - $ignored) / $this->_width;
}
/**
* Returns the mapType.
*
* @return int
*/
public function getMapType()
{
return self::MAP_TYPE_FIXED_LEN;
}
/**
* Returns an integer which specifies how many more bytes to read.
*
* A positive integer indicates the number of more bytes to fetch before invoking
* this method again.
*
* A value of zero means this is already a valid character.
* A value of -1 means this cannot possibly be a valid character.
*
* @param string $bytes
* @param int $size
*
* @return int
*/
public function validateByteSequence($bytes, $size)
{
$needed = $this->_width - $size;
return $needed > -1 ? $needed : -1;
}
/**
* Returns the number of bytes which should be read to start each character.
*
* @return int
*/
public function getInitialByteSize()
{
return $this->_width;
}
}

View File

@@ -1,84 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Analyzes US-ASCII characters.
*
* @author Chris Corbyn
*/
class Swift_CharacterReader_UsAsciiReader implements Swift_CharacterReader
{
/**
* Returns the complete character map.
*
* @param string $string
* @param int $startOffset
* @param array $currentMap
* @param string $ignoredChars
*
* @return int
*/
public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars)
{
$strlen = strlen($string);
$ignoredChars = '';
for ($i = 0; $i < $strlen; ++$i) {
if ($string[$i] > "\x07F") {
// Invalid char
$currentMap[$i + $startOffset] = $string[$i];
}
}
return $strlen;
}
/**
* Returns mapType.
*
* @return int mapType
*/
public function getMapType()
{
return self::MAP_TYPE_INVALID;
}
/**
* Returns an integer which specifies how many more bytes to read.
*
* A positive integer indicates the number of more bytes to fetch before invoking
* this method again.
* A value of zero means this is already a valid character.
* A value of -1 means this cannot possibly be a valid character.
*
* @param string $bytes
* @param int $size
*
* @return int
*/
public function validateByteSequence($bytes, $size)
{
$byte = reset($bytes);
if (1 == count($bytes) && $byte >= 0x00 && $byte <= 0x7F) {
return 0;
}
return -1;
}
/**
* Returns the number of bytes which should be read to start each character.
*
* @return int
*/
public function getInitialByteSize()
{
return 1;
}
}

View File

@@ -1,176 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Analyzes UTF-8 characters.
*
* @author Chris Corbyn
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader
{
/** Pre-computed for optimization */
private static $length_map = array(
// N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x0N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x2N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x4N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x6N
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7N
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x8N
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9N
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xAN
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBN
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xCN
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDN
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEN
4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0, // 0xFN
);
private static $s_length_map = array(
"\x00" => 1, "\x01" => 1, "\x02" => 1, "\x03" => 1, "\x04" => 1, "\x05" => 1, "\x06" => 1, "\x07" => 1,
"\x08" => 1, "\x09" => 1, "\x0a" => 1, "\x0b" => 1, "\x0c" => 1, "\x0d" => 1, "\x0e" => 1, "\x0f" => 1,
"\x10" => 1, "\x11" => 1, "\x12" => 1, "\x13" => 1, "\x14" => 1, "\x15" => 1, "\x16" => 1, "\x17" => 1,
"\x18" => 1, "\x19" => 1, "\x1a" => 1, "\x1b" => 1, "\x1c" => 1, "\x1d" => 1, "\x1e" => 1, "\x1f" => 1,
"\x20" => 1, "\x21" => 1, "\x22" => 1, "\x23" => 1, "\x24" => 1, "\x25" => 1, "\x26" => 1, "\x27" => 1,
"\x28" => 1, "\x29" => 1, "\x2a" => 1, "\x2b" => 1, "\x2c" => 1, "\x2d" => 1, "\x2e" => 1, "\x2f" => 1,
"\x30" => 1, "\x31" => 1, "\x32" => 1, "\x33" => 1, "\x34" => 1, "\x35" => 1, "\x36" => 1, "\x37" => 1,
"\x38" => 1, "\x39" => 1, "\x3a" => 1, "\x3b" => 1, "\x3c" => 1, "\x3d" => 1, "\x3e" => 1, "\x3f" => 1,
"\x40" => 1, "\x41" => 1, "\x42" => 1, "\x43" => 1, "\x44" => 1, "\x45" => 1, "\x46" => 1, "\x47" => 1,
"\x48" => 1, "\x49" => 1, "\x4a" => 1, "\x4b" => 1, "\x4c" => 1, "\x4d" => 1, "\x4e" => 1, "\x4f" => 1,
"\x50" => 1, "\x51" => 1, "\x52" => 1, "\x53" => 1, "\x54" => 1, "\x55" => 1, "\x56" => 1, "\x57" => 1,
"\x58" => 1, "\x59" => 1, "\x5a" => 1, "\x5b" => 1, "\x5c" => 1, "\x5d" => 1, "\x5e" => 1, "\x5f" => 1,
"\x60" => 1, "\x61" => 1, "\x62" => 1, "\x63" => 1, "\x64" => 1, "\x65" => 1, "\x66" => 1, "\x67" => 1,
"\x68" => 1, "\x69" => 1, "\x6a" => 1, "\x6b" => 1, "\x6c" => 1, "\x6d" => 1, "\x6e" => 1, "\x6f" => 1,
"\x70" => 1, "\x71" => 1, "\x72" => 1, "\x73" => 1, "\x74" => 1, "\x75" => 1, "\x76" => 1, "\x77" => 1,
"\x78" => 1, "\x79" => 1, "\x7a" => 1, "\x7b" => 1, "\x7c" => 1, "\x7d" => 1, "\x7e" => 1, "\x7f" => 1,
"\x80" => 0, "\x81" => 0, "\x82" => 0, "\x83" => 0, "\x84" => 0, "\x85" => 0, "\x86" => 0, "\x87" => 0,
"\x88" => 0, "\x89" => 0, "\x8a" => 0, "\x8b" => 0, "\x8c" => 0, "\x8d" => 0, "\x8e" => 0, "\x8f" => 0,
"\x90" => 0, "\x91" => 0, "\x92" => 0, "\x93" => 0, "\x94" => 0, "\x95" => 0, "\x96" => 0, "\x97" => 0,
"\x98" => 0, "\x99" => 0, "\x9a" => 0, "\x9b" => 0, "\x9c" => 0, "\x9d" => 0, "\x9e" => 0, "\x9f" => 0,
"\xa0" => 0, "\xa1" => 0, "\xa2" => 0, "\xa3" => 0, "\xa4" => 0, "\xa5" => 0, "\xa6" => 0, "\xa7" => 0,
"\xa8" => 0, "\xa9" => 0, "\xaa" => 0, "\xab" => 0, "\xac" => 0, "\xad" => 0, "\xae" => 0, "\xaf" => 0,
"\xb0" => 0, "\xb1" => 0, "\xb2" => 0, "\xb3" => 0, "\xb4" => 0, "\xb5" => 0, "\xb6" => 0, "\xb7" => 0,
"\xb8" => 0, "\xb9" => 0, "\xba" => 0, "\xbb" => 0, "\xbc" => 0, "\xbd" => 0, "\xbe" => 0, "\xbf" => 0,
"\xc0" => 2, "\xc1" => 2, "\xc2" => 2, "\xc3" => 2, "\xc4" => 2, "\xc5" => 2, "\xc6" => 2, "\xc7" => 2,
"\xc8" => 2, "\xc9" => 2, "\xca" => 2, "\xcb" => 2, "\xcc" => 2, "\xcd" => 2, "\xce" => 2, "\xcf" => 2,
"\xd0" => 2, "\xd1" => 2, "\xd2" => 2, "\xd3" => 2, "\xd4" => 2, "\xd5" => 2, "\xd6" => 2, "\xd7" => 2,
"\xd8" => 2, "\xd9" => 2, "\xda" => 2, "\xdb" => 2, "\xdc" => 2, "\xdd" => 2, "\xde" => 2, "\xdf" => 2,
"\xe0" => 3, "\xe1" => 3, "\xe2" => 3, "\xe3" => 3, "\xe4" => 3, "\xe5" => 3, "\xe6" => 3, "\xe7" => 3,
"\xe8" => 3, "\xe9" => 3, "\xea" => 3, "\xeb" => 3, "\xec" => 3, "\xed" => 3, "\xee" => 3, "\xef" => 3,
"\xf0" => 4, "\xf1" => 4, "\xf2" => 4, "\xf3" => 4, "\xf4" => 4, "\xf5" => 4, "\xf6" => 4, "\xf7" => 4,
"\xf8" => 5, "\xf9" => 5, "\xfa" => 5, "\xfb" => 5, "\xfc" => 6, "\xfd" => 6, "\xfe" => 0, "\xff" => 0,
);
/**
* Returns the complete character map.
*
* @param string $string
* @param int $startOffset
* @param array $currentMap
* @param mixed $ignoredChars
*
* @return int
*/
public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars)
{
if (!isset($currentMap['i']) || !isset($currentMap['p'])) {
$currentMap['p'] = $currentMap['i'] = array();
}
$strlen = strlen($string);
$charPos = count($currentMap['p']);
$foundChars = 0;
$invalid = false;
for ($i = 0; $i < $strlen; ++$i) {
$char = $string[$i];
$size = self::$s_length_map[$char];
if ($size == 0) {
/* char is invalid, we must wait for a resync */
$invalid = true;
continue;
} else {
if ($invalid == true) {
/* We mark the chars as invalid and start a new char */
$currentMap['p'][$charPos + $foundChars] = $startOffset + $i;
$currentMap['i'][$charPos + $foundChars] = true;
++$foundChars;
$invalid = false;
}
if (($i + $size) > $strlen) {
$ignoredChars = substr($string, $i);
break;
}
for ($j = 1; $j < $size; ++$j) {
$char = $string[$i + $j];
if ($char > "\x7F" && $char < "\xC0") {
// Valid - continue parsing
} else {
/* char is invalid, we must wait for a resync */
$invalid = true;
continue 2;
}
}
/* Ok we got a complete char here */
$currentMap['p'][$charPos + $foundChars] = $startOffset + $i + $size;
$i += $j - 1;
++$foundChars;
}
}
return $foundChars;
}
/**
* Returns mapType.
*
* @return int mapType
*/
public function getMapType()
{
return self::MAP_TYPE_POSITIONS;
}
/**
* Returns an integer which specifies how many more bytes to read.
*
* A positive integer indicates the number of more bytes to fetch before invoking
* this method again.
* A value of zero means this is already a valid character.
* A value of -1 means this cannot possibly be a valid character.
*
* @param string $bytes
* @param int $size
*
* @return int
*/
public function validateByteSequence($bytes, $size)
{
if ($size < 1) {
return -1;
}
$needed = self::$length_map[$bytes[0]] - $size;
return $needed > -1 ? $needed : -1;
}
/**
* Returns the number of bytes which should be read to start each character.
*
* @return int
*/
public function getInitialByteSize()
{
return 1;
}
}

View File

@@ -1,26 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A factory for creating CharacterReaders.
*
* @author Chris Corbyn
*/
interface Swift_CharacterReaderFactory
{
/**
* Returns a CharacterReader suitable for the charset applied.
*
* @param string $charset
*
* @return Swift_CharacterReader
*/
public function getReaderFor($charset);
}

View File

@@ -1,124 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Standard factory for creating CharacterReaders.
*
* @author Chris Corbyn
*/
class Swift_CharacterReaderFactory_SimpleCharacterReaderFactory implements Swift_CharacterReaderFactory
{
/**
* A map of charset patterns to their implementation classes.
*
* @var array
*/
private static $_map = array();
/**
* Factories which have already been loaded.
*
* @var Swift_CharacterReaderFactory[]
*/
private static $_loaded = array();
/**
* Creates a new CharacterReaderFactory.
*/
public function __construct()
{
$this->init();
}
public function __wakeup()
{
$this->init();
}
public function init()
{
if (count(self::$_map) > 0) {
return;
}
$prefix = 'Swift_CharacterReader_';
$singleByte = array(
'class' => $prefix.'GenericFixedWidthReader',
'constructor' => array(1),
);
$doubleByte = array(
'class' => $prefix.'GenericFixedWidthReader',
'constructor' => array(2),
);
$fourBytes = array(
'class' => $prefix.'GenericFixedWidthReader',
'constructor' => array(4),
);
// Utf-8
self::$_map['utf-?8'] = array(
'class' => $prefix.'Utf8Reader',
'constructor' => array(),
);
//7-8 bit charsets
self::$_map['(us-)?ascii'] = $singleByte;
self::$_map['(iso|iec)-?8859-?[0-9]+'] = $singleByte;
self::$_map['windows-?125[0-9]'] = $singleByte;
self::$_map['cp-?[0-9]+'] = $singleByte;
self::$_map['ansi'] = $singleByte;
self::$_map['macintosh'] = $singleByte;
self::$_map['koi-?7'] = $singleByte;
self::$_map['koi-?8-?.+'] = $singleByte;
self::$_map['mik'] = $singleByte;
self::$_map['(cork|t1)'] = $singleByte;
self::$_map['v?iscii'] = $singleByte;
//16 bits
self::$_map['(ucs-?2|utf-?16)'] = $doubleByte;
//32 bits
self::$_map['(ucs-?4|utf-?32)'] = $fourBytes;
// Fallback
self::$_map['.*'] = $singleByte;
}
/**
* Returns a CharacterReader suitable for the charset applied.
*
* @param string $charset
*
* @return Swift_CharacterReader
*/
public function getReaderFor($charset)
{
$charset = trim(strtolower($charset));
foreach (self::$_map as $pattern => $spec) {
$re = '/^'.$pattern.'$/D';
if (preg_match($re, $charset)) {
if (!array_key_exists($pattern, self::$_loaded)) {
$reflector = new ReflectionClass($spec['class']);
if ($reflector->getConstructor()) {
$reader = $reflector->newInstanceArgs($spec['constructor']);
} else {
$reader = $reflector->newInstance();
}
self::$_loaded[$pattern] = $reader;
}
return self::$_loaded[$pattern];
}
}
}
}

View File

@@ -1,89 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An abstract means of reading and writing data in terms of characters as opposed
* to bytes.
*
* Classes implementing this interface may use a subsystem which requires less
* memory than working with large strings of data.
*
* @author Chris Corbyn
*/
interface Swift_CharacterStream
{
/**
* Set the character set used in this CharacterStream.
*
* @param string $charset
*/
public function setCharacterSet($charset);
/**
* Set the CharacterReaderFactory for multi charset support.
*
* @param Swift_CharacterReaderFactory $factory
*/
public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory);
/**
* Overwrite this character stream using the byte sequence in the byte stream.
*
* @param Swift_OutputByteStream $os output stream to read from
*/
public function importByteStream(Swift_OutputByteStream $os);
/**
* Import a string a bytes into this CharacterStream, overwriting any existing
* data in the stream.
*
* @param string $string
*/
public function importString($string);
/**
* Read $length characters from the stream and move the internal pointer
* $length further into the stream.
*
* @param int $length
*
* @return string
*/
public function read($length);
/**
* Read $length characters from the stream and return a 1-dimensional array
* containing there octet values.
*
* @param int $length
*
* @return int[]
*/
public function readBytes($length);
/**
* Write $chars to the end of the stream.
*
* @param string $chars
*/
public function write($chars);
/**
* Move the internal pointer to $charOffset in the stream.
*
* @param int $charOffset
*/
public function setPointer($charOffset);
/**
* Empty the stream and reset the internal pointer.
*/
public function flushContents();
}

View File

@@ -1,293 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A CharacterStream implementation which stores characters in an internal array.
*
* @author Chris Corbyn
*/
class Swift_CharacterStream_ArrayCharacterStream implements Swift_CharacterStream
{
/** A map of byte values and their respective characters */
private static $_charMap;
/** A map of characters and their derivative byte values */
private static $_byteMap;
/** The char reader (lazy-loaded) for the current charset */
private $_charReader;
/** A factory for creating CharacterReader instances */
private $_charReaderFactory;
/** The character set this stream is using */
private $_charset;
/** Array of characters */
private $_array = array();
/** Size of the array of character */
private $_array_size = array();
/** The current character offset in the stream */
private $_offset = 0;
/**
* Create a new CharacterStream with the given $chars, if set.
*
* @param Swift_CharacterReaderFactory $factory for loading validators
* @param string $charset used in the stream
*/
public function __construct(Swift_CharacterReaderFactory $factory, $charset)
{
self::_initializeMaps();
$this->setCharacterReaderFactory($factory);
$this->setCharacterSet($charset);
}
/**
* Set the character set used in this CharacterStream.
*
* @param string $charset
*/
public function setCharacterSet($charset)
{
$this->_charset = $charset;
$this->_charReader = null;
}
/**
* Set the CharacterReaderFactory for multi charset support.
*
* @param Swift_CharacterReaderFactory $factory
*/
public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory)
{
$this->_charReaderFactory = $factory;
}
/**
* Overwrite this character stream using the byte sequence in the byte stream.
*
* @param Swift_OutputByteStream $os output stream to read from
*/
public function importByteStream(Swift_OutputByteStream $os)
{
if (!isset($this->_charReader)) {
$this->_charReader = $this->_charReaderFactory
->getReaderFor($this->_charset);
}
$startLength = $this->_charReader->getInitialByteSize();
while (false !== $bytes = $os->read($startLength)) {
$c = array();
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) {
$c[] = self::$_byteMap[$bytes[$i]];
}
$size = count($c);
$need = $this->_charReader
->validateByteSequence($c, $size);
if ($need > 0 &&
false !== $bytes = $os->read($need)) {
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) {
$c[] = self::$_byteMap[$bytes[$i]];
}
}
$this->_array[] = $c;
++$this->_array_size;
}
}
/**
* Import a string a bytes into this CharacterStream, overwriting any existing
* data in the stream.
*
* @param string $string
*/
public function importString($string)
{
$this->flushContents();
$this->write($string);
}
/**
* Read $length characters from the stream and move the internal pointer
* $length further into the stream.
*
* @param int $length
*
* @return string
*/
public function read($length)
{
if ($this->_offset == $this->_array_size) {
return false;
}
// Don't use array slice
$arrays = array();
$end = $length + $this->_offset;
for ($i = $this->_offset; $i < $end; ++$i) {
if (!isset($this->_array[$i])) {
break;
}
$arrays[] = $this->_array[$i];
}
$this->_offset += $i - $this->_offset; // Limit function calls
$chars = false;
foreach ($arrays as $array) {
$chars .= implode('', array_map('chr', $array));
}
return $chars;
}
/**
* Read $length characters from the stream and return a 1-dimensional array
* containing there octet values.
*
* @param int $length
*
* @return integer[]
*/
public function readBytes($length)
{
if ($this->_offset == $this->_array_size) {
return false;
}
$arrays = array();
$end = $length + $this->_offset;
for ($i = $this->_offset; $i < $end; ++$i) {
if (!isset($this->_array[$i])) {
break;
}
$arrays[] = $this->_array[$i];
}
$this->_offset += ($i - $this->_offset); // Limit function calls
return call_user_func_array('array_merge', $arrays);
}
/**
* Write $chars to the end of the stream.
*
* @param string $chars
*/
public function write($chars)
{
if (!isset($this->_charReader)) {
$this->_charReader = $this->_charReaderFactory->getReaderFor(
$this->_charset);
}
$startLength = $this->_charReader->getInitialByteSize();
$fp = fopen('php://memory', 'w+b');
fwrite($fp, $chars);
unset($chars);
fseek($fp, 0, SEEK_SET);
$buffer = array(0);
$buf_pos = 1;
$buf_len = 1;
$has_datas = true;
do {
$bytes = array();
// Buffer Filing
if ($buf_len - $buf_pos < $startLength) {
$buf = array_splice($buffer, $buf_pos);
$new = $this->_reloadBuffer($fp, 100);
if ($new) {
$buffer = array_merge($buf, $new);
$buf_len = count($buffer);
$buf_pos = 0;
} else {
$has_datas = false;
}
}
if ($buf_len - $buf_pos > 0) {
$size = 0;
for ($i = 0; $i < $startLength && isset($buffer[$buf_pos]); ++$i) {
++$size;
$bytes[] = $buffer[$buf_pos++];
}
$need = $this->_charReader->validateByteSequence(
$bytes, $size);
if ($need > 0) {
if ($buf_len - $buf_pos < $need) {
$new = $this->_reloadBuffer($fp, $need);
if ($new) {
$buffer = array_merge($buffer, $new);
$buf_len = count($buffer);
}
}
for ($i = 0; $i < $need && isset($buffer[$buf_pos]); ++$i) {
$bytes[] = $buffer[$buf_pos++];
}
}
$this->_array[] = $bytes;
++$this->_array_size;
}
} while ($has_datas);
fclose($fp);
}
/**
* Move the internal pointer to $charOffset in the stream.
*
* @param int $charOffset
*/
public function setPointer($charOffset)
{
if ($charOffset > $this->_array_size) {
$charOffset = $this->_array_size;
} elseif ($charOffset < 0) {
$charOffset = 0;
}
$this->_offset = $charOffset;
}
/**
* Empty the stream and reset the internal pointer.
*/
public function flushContents()
{
$this->_offset = 0;
$this->_array = array();
$this->_array_size = 0;
}
private function _reloadBuffer($fp, $len)
{
if (!feof($fp) && ($bytes = fread($fp, $len)) !== false) {
$buf = array();
for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) {
$buf[] = self::$_byteMap[$bytes[$i]];
}
return $buf;
}
return false;
}
private static function _initializeMaps()
{
if (!isset(self::$_charMap)) {
self::$_charMap = array();
for ($byte = 0; $byte < 256; ++$byte) {
self::$_charMap[$byte] = chr($byte);
}
self::$_byteMap = array_flip(self::$_charMap);
}
}
}

View File

@@ -1,267 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A CharacterStream implementation which stores characters in an internal array.
*
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream
{
/**
* The char reader (lazy-loaded) for the current charset.
*
* @var Swift_CharacterReader
*/
private $_charReader;
/**
* A factory for creating CharacterReader instances.
*
* @var Swift_CharacterReaderFactory
*/
private $_charReaderFactory;
/**
* The character set this stream is using.
*
* @var string
*/
private $_charset;
/**
* The data's stored as-is.
*
* @var string
*/
private $_datas = '';
/**
* Number of bytes in the stream.
*
* @var int
*/
private $_datasSize = 0;
/**
* Map.
*
* @var mixed
*/
private $_map;
/**
* Map Type.
*
* @var int
*/
private $_mapType = 0;
/**
* Number of characters in the stream.
*
* @var int
*/
private $_charCount = 0;
/**
* Position in the stream.
*
* @var int
*/
private $_currentPos = 0;
/**
* Constructor.
*
* @param Swift_CharacterReaderFactory $factory
* @param string $charset
*/
public function __construct(Swift_CharacterReaderFactory $factory, $charset)
{
$this->setCharacterReaderFactory($factory);
$this->setCharacterSet($charset);
}
/* -- Changing parameters of the stream -- */
/**
* Set the character set used in this CharacterStream.
*
* @param string $charset
*/
public function setCharacterSet($charset)
{
$this->_charset = $charset;
$this->_charReader = null;
$this->_mapType = 0;
}
/**
* Set the CharacterReaderFactory for multi charset support.
*
* @param Swift_CharacterReaderFactory $factory
*/
public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory)
{
$this->_charReaderFactory = $factory;
}
/**
* @see Swift_CharacterStream::flushContents()
*/
public function flushContents()
{
$this->_datas = null;
$this->_map = null;
$this->_charCount = 0;
$this->_currentPos = 0;
$this->_datasSize = 0;
}
/**
* @see Swift_CharacterStream::importByteStream()
*
* @param Swift_OutputByteStream $os
*/
public function importByteStream(Swift_OutputByteStream $os)
{
$this->flushContents();
$blocks = 512;
$os->setReadPointer(0);
while (false !== ($read = $os->read($blocks))) {
$this->write($read);
}
}
/**
* @see Swift_CharacterStream::importString()
*
* @param string $string
*/
public function importString($string)
{
$this->flushContents();
$this->write($string);
}
/**
* @see Swift_CharacterStream::read()
*
* @param int $length
*
* @return string
*/
public function read($length)
{
if ($this->_currentPos >= $this->_charCount) {
return false;
}
$ret = false;
$length = $this->_currentPos + $length > $this->_charCount ? $this->_charCount - $this->_currentPos : $length;
switch ($this->_mapType) {
case Swift_CharacterReader::MAP_TYPE_FIXED_LEN:
$len = $length * $this->_map;
$ret = substr($this->_datas,
$this->_currentPos * $this->_map,
$len);
$this->_currentPos += $length;
break;
case Swift_CharacterReader::MAP_TYPE_INVALID:
$ret = '';
for (; $this->_currentPos < $length; ++$this->_currentPos) {
if (isset($this->_map[$this->_currentPos])) {
$ret .= '?';
} else {
$ret .= $this->_datas[$this->_currentPos];
}
}
break;
case Swift_CharacterReader::MAP_TYPE_POSITIONS:
$end = $this->_currentPos + $length;
$end = $end > $this->_charCount ? $this->_charCount : $end;
$ret = '';
$start = 0;
if ($this->_currentPos > 0) {
$start = $this->_map['p'][$this->_currentPos - 1];
}
$to = $start;
for (; $this->_currentPos < $end; ++$this->_currentPos) {
if (isset($this->_map['i'][$this->_currentPos])) {
$ret .= substr($this->_datas, $start, $to - $start).'?';
$start = $this->_map['p'][$this->_currentPos];
} else {
$to = $this->_map['p'][$this->_currentPos];
}
}
$ret .= substr($this->_datas, $start, $to - $start);
break;
}
return $ret;
}
/**
* @see Swift_CharacterStream::readBytes()
*
* @param int $length
*
* @return int[]
*/
public function readBytes($length)
{
$read = $this->read($length);
if ($read !== false) {
$ret = array_map('ord', str_split($read, 1));
return $ret;
}
return false;
}
/**
* @see Swift_CharacterStream::setPointer()
*
* @param int $charOffset
*/
public function setPointer($charOffset)
{
if ($this->_charCount < $charOffset) {
$charOffset = $this->_charCount;
}
$this->_currentPos = $charOffset;
}
/**
* @see Swift_CharacterStream::write()
*
* @param string $chars
*/
public function write($chars)
{
if (!isset($this->_charReader)) {
$this->_charReader = $this->_charReaderFactory->getReaderFor(
$this->_charset);
$this->_map = array();
$this->_mapType = $this->_charReader->getMapType();
}
$ignored = '';
$this->_datas .= $chars;
$this->_charCount += $this->_charReader->getCharPositions(substr($this->_datas, $this->_datasSize), $this->_datasSize, $this->_map, $ignored);
if ($ignored !== false) {
$this->_datasSize = strlen($this->_datas) - strlen($ignored);
} else {
$this->_datasSize = strlen($this->_datas);
}
}
}

View File

@@ -1,63 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2009 Fabien Potencier <fabien.potencier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Base class for Spools (implements time and message limits).
*
* @author Fabien Potencier
*/
abstract class Swift_ConfigurableSpool implements Swift_Spool
{
/** The maximum number of messages to send per flush */
private $_message_limit;
/** The time limit per flush */
private $_time_limit;
/**
* Sets the maximum number of messages to send per flush.
*
* @param int $limit
*/
public function setMessageLimit($limit)
{
$this->_message_limit = (int) $limit;
}
/**
* Gets the maximum number of messages to send per flush.
*
* @return int The limit
*/
public function getMessageLimit()
{
return $this->_message_limit;
}
/**
* Sets the time limit (in seconds) per flush.
*
* @param int $limit The limit
*/
public function setTimeLimit($limit)
{
$this->_time_limit = (int) $limit;
}
/**
* Gets the time limit (in seconds) per flush.
*
* @return int The limit
*/
public function getTimeLimit()
{
return $this->_time_limit;
}
}

View File

@@ -1,373 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Dependency Injection container.
*
* @author Chris Corbyn
*/
class Swift_DependencyContainer
{
/** Constant for literal value types */
const TYPE_VALUE = 0x0001;
/** Constant for new instance types */
const TYPE_INSTANCE = 0x0010;
/** Constant for shared instance types */
const TYPE_SHARED = 0x0100;
/** Constant for aliases */
const TYPE_ALIAS = 0x1000;
/** Singleton instance */
private static $_instance = null;
/** The data container */
private $_store = array();
/** The current endpoint in the data container */
private $_endPoint;
/**
* Constructor should not be used.
*
* Use {@link getInstance()} instead.
*/
public function __construct()
{
}
/**
* Returns a singleton of the DependencyContainer.
*
* @return Swift_DependencyContainer
*/
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* List the names of all items stored in the Container.
*
* @return array
*/
public function listItems()
{
return array_keys($this->_store);
}
/**
* Test if an item is registered in this container with the given name.
*
* @see register()
*
* @param string $itemName
*
* @return bool
*/
public function has($itemName)
{
return array_key_exists($itemName, $this->_store)
&& isset($this->_store[$itemName]['lookupType']);
}
/**
* Lookup the item with the given $itemName.
*
* @see register()
*
* @param string $itemName
*
* @throws Swift_DependencyException If the dependency is not found
*
* @return mixed
*/
public function lookup($itemName)
{
if (!$this->has($itemName)) {
throw new Swift_DependencyException(
'Cannot lookup dependency "'.$itemName.'" since it is not registered.'
);
}
switch ($this->_store[$itemName]['lookupType']) {
case self::TYPE_ALIAS:
return $this->_createAlias($itemName);
case self::TYPE_VALUE:
return $this->_getValue($itemName);
case self::TYPE_INSTANCE:
return $this->_createNewInstance($itemName);
case self::TYPE_SHARED:
return $this->_createSharedInstance($itemName);
}
}
/**
* Create an array of arguments passed to the constructor of $itemName.
*
* @param string $itemName
*
* @return array
*/
public function createDependenciesFor($itemName)
{
$args = array();
if (isset($this->_store[$itemName]['args'])) {
$args = $this->_resolveArgs($this->_store[$itemName]['args']);
}
return $args;
}
/**
* Register a new dependency with $itemName.
*
* This method returns the current DependencyContainer instance because it
* requires the use of the fluid interface to set the specific details for the
* dependency.
*
* @see asNewInstanceOf(), asSharedInstanceOf(), asValue()
*
* @param string $itemName
*
* @return Swift_DependencyContainer
*/
public function register($itemName)
{
$this->_store[$itemName] = array();
$this->_endPoint = &$this->_store[$itemName];
return $this;
}
/**
* Specify the previously registered item as a literal value.
*
* {@link register()} must be called before this will work.
*
* @param mixed $value
*
* @return Swift_DependencyContainer
*/
public function asValue($value)
{
$endPoint = &$this->_getEndPoint();
$endPoint['lookupType'] = self::TYPE_VALUE;
$endPoint['value'] = $value;
return $this;
}
/**
* Specify the previously registered item as an alias of another item.
*
* @param string $lookup
*
* @return Swift_DependencyContainer
*/
public function asAliasOf($lookup)
{
$endPoint = &$this->_getEndPoint();
$endPoint['lookupType'] = self::TYPE_ALIAS;
$endPoint['ref'] = $lookup;
return $this;
}
/**
* Specify the previously registered item as a new instance of $className.
*
* {@link register()} must be called before this will work.
* Any arguments can be set with {@link withDependencies()},
* {@link addConstructorValue()} or {@link addConstructorLookup()}.
*
* @see withDependencies(), addConstructorValue(), addConstructorLookup()
*
* @param string $className
*
* @return Swift_DependencyContainer
*/
public function asNewInstanceOf($className)
{
$endPoint = &$this->_getEndPoint();
$endPoint['lookupType'] = self::TYPE_INSTANCE;
$endPoint['className'] = $className;
return $this;
}
/**
* Specify the previously registered item as a shared instance of $className.
*
* {@link register()} must be called before this will work.
*
* @param string $className
*
* @return Swift_DependencyContainer
*/
public function asSharedInstanceOf($className)
{
$endPoint = &$this->_getEndPoint();
$endPoint['lookupType'] = self::TYPE_SHARED;
$endPoint['className'] = $className;
return $this;
}
/**
* Specify a list of injected dependencies for the previously registered item.
*
* This method takes an array of lookup names.
*
* @see addConstructorValue(), addConstructorLookup()
*
* @param array $lookups
*
* @return Swift_DependencyContainer
*/
public function withDependencies(array $lookups)
{
$endPoint = &$this->_getEndPoint();
$endPoint['args'] = array();
foreach ($lookups as $lookup) {
$this->addConstructorLookup($lookup);
}
return $this;
}
/**
* Specify a literal (non looked up) value for the constructor of the
* previously registered item.
*
* @see withDependencies(), addConstructorLookup()
*
* @param mixed $value
*
* @return Swift_DependencyContainer
*/
public function addConstructorValue($value)
{
$endPoint = &$this->_getEndPoint();
if (!isset($endPoint['args'])) {
$endPoint['args'] = array();
}
$endPoint['args'][] = array('type' => 'value', 'item' => $value);
return $this;
}
/**
* Specify a dependency lookup for the constructor of the previously
* registered item.
*
* @see withDependencies(), addConstructorValue()
*
* @param string $lookup
*
* @return Swift_DependencyContainer
*/
public function addConstructorLookup($lookup)
{
$endPoint = &$this->_getEndPoint();
if (!isset($this->_endPoint['args'])) {
$endPoint['args'] = array();
}
$endPoint['args'][] = array('type' => 'lookup', 'item' => $lookup);
return $this;
}
/** Get the literal value with $itemName */
private function _getValue($itemName)
{
return $this->_store[$itemName]['value'];
}
/** Resolve an alias to another item */
private function _createAlias($itemName)
{
return $this->lookup($this->_store[$itemName]['ref']);
}
/** Create a fresh instance of $itemName */
private function _createNewInstance($itemName)
{
$reflector = new ReflectionClass($this->_store[$itemName]['className']);
if ($reflector->getConstructor()) {
return $reflector->newInstanceArgs(
$this->createDependenciesFor($itemName)
);
}
return $reflector->newInstance();
}
/** Create and register a shared instance of $itemName */
private function _createSharedInstance($itemName)
{
if (!isset($this->_store[$itemName]['instance'])) {
$this->_store[$itemName]['instance'] = $this->_createNewInstance($itemName);
}
return $this->_store[$itemName]['instance'];
}
/** Get the current endpoint in the store */
private function &_getEndPoint()
{
if (!isset($this->_endPoint)) {
throw new BadMethodCallException(
'Component must first be registered by calling register()'
);
}
return $this->_endPoint;
}
/** Get an argument list with dependencies resolved */
private function _resolveArgs(array $args)
{
$resolved = array();
foreach ($args as $argDefinition) {
switch ($argDefinition['type']) {
case 'lookup':
$resolved[] = $this->_lookupRecursive($argDefinition['item']);
break;
case 'value':
$resolved[] = $argDefinition['item'];
break;
}
}
return $resolved;
}
/** Resolve a single dependency with an collections */
private function _lookupRecursive($item)
{
if (is_array($item)) {
$collection = array();
foreach ($item as $k => $v) {
$collection[$k] = $this->_lookupRecursive($v);
}
return $collection;
}
return $this->lookup($item);
}
}

View File

@@ -1,27 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* DependencyException gets thrown when a requested dependency is missing.
*
* @author Chris Corbyn
*/
class Swift_DependencyException extends Swift_SwiftException
{
/**
* Create a new DependencyException with $message.
*
* @param string $message
*/
public function __construct($message)
{
parent::__construct($message);
}
}

View File

@@ -1,69 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An embedded file, in a multipart message.
*
* @author Chris Corbyn
*/
class Swift_EmbeddedFile extends Swift_Mime_EmbeddedFile
{
/**
* Create a new EmbeddedFile.
*
* Details may be optionally provided to the constructor.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*/
public function __construct($data = null, $filename = null, $contentType = null)
{
call_user_func_array(
array($this, 'Swift_Mime_EmbeddedFile::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.embeddedfile')
);
$this->setBody($data);
$this->setFilename($filename);
if ($contentType) {
$this->setContentType($contentType);
}
}
/**
* Create a new EmbeddedFile.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*
* @return Swift_Mime_EmbeddedFile
*/
public static function newInstance($data = null, $filename = null, $contentType = null)
{
return new self($data, $filename, $contentType);
}
/**
* Create a new EmbeddedFile from a filesystem path.
*
* @param string $path
*
* @return Swift_Mime_EmbeddedFile
*/
public static function fromPath($path)
{
return self::newInstance()->setFile(
new Swift_ByteStream_FileByteStream($path)
);
}
}

View File

@@ -1,28 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Interface for all Encoder schemes.
*
* @author Chris Corbyn
*/
interface Swift_Encoder extends Swift_Mime_CharsetObserver
{
/**
* Encode a given string to produce an encoded string.
*
* @param string $string
* @param int $firstLineOffset if first line needs to be shorter
* @param int $maxLineLength - 0 indicates the default length for this encoding
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0);
}

View File

@@ -1,58 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Base 64 Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Encoder_Base64Encoder implements Swift_Encoder
{
/**
* Takes an unencoded string and produces a Base64 encoded string from it.
*
* Base64 encoded strings have a maximum line length of 76 characters.
* If the first line needs to be shorter, indicate the difference with
* $firstLineOffset.
*
* @param string $string to encode
* @param int $firstLineOffset
* @param int $maxLineLength optional, 0 indicates the default of 76 bytes
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
if (0 >= $maxLineLength || 76 < $maxLineLength) {
$maxLineLength = 76;
}
$encodedString = base64_encode($string);
$firstLine = '';
if (0 != $firstLineOffset) {
$firstLine = substr(
$encodedString, 0, $maxLineLength - $firstLineOffset
)."\r\n";
$encodedString = substr(
$encodedString, $maxLineLength - $firstLineOffset
);
}
return $firstLine.trim(chunk_split($encodedString, $maxLineLength, "\r\n"));
}
/**
* Does nothing.
*/
public function charsetChanged($charset)
{
}
}

View File

@@ -1,92 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles RFC 2231 specified Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Encoder_Rfc2231Encoder implements Swift_Encoder
{
/**
* A character stream to use when reading a string as characters instead of bytes.
*
* @var Swift_CharacterStream
*/
private $_charStream;
/**
* Creates a new Rfc2231Encoder using the given character stream instance.
*
* @param Swift_CharacterStream
*/
public function __construct(Swift_CharacterStream $charStream)
{
$this->_charStream = $charStream;
}
/**
* Takes an unencoded string and produces a string encoded according to
* RFC 2231 from it.
*
* @param string $string
* @param int $firstLineOffset
* @param int $maxLineLength optional, 0 indicates the default of 75 bytes
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
$lines = array();
$lineCount = 0;
$lines[] = '';
$currentLine = &$lines[$lineCount++];
if (0 >= $maxLineLength) {
$maxLineLength = 75;
}
$this->_charStream->flushContents();
$this->_charStream->importString($string);
$thisLineLength = $maxLineLength - $firstLineOffset;
while (false !== $char = $this->_charStream->read(4)) {
$encodedChar = rawurlencode($char);
if (0 != strlen($currentLine)
&& strlen($currentLine.$encodedChar) > $thisLineLength) {
$lines[] = '';
$currentLine = &$lines[$lineCount++];
$thisLineLength = $maxLineLength;
}
$currentLine .= $encodedChar;
}
return implode("\r\n", $lines);
}
/**
* Updates the charset used.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->_charStream->setCharacterSet($charset);
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->_charStream = clone $this->_charStream;
}
}

View File

@@ -1,64 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Provides quick access to each encoding type.
*
* @author Chris Corbyn
*/
class Swift_Encoding
{
/**
* Get the Encoder that provides 7-bit encoding.
*
* @return Swift_Mime_ContentEncoder
*/
public static function get7BitEncoding()
{
return self::_lookup('mime.7bitcontentencoder');
}
/**
* Get the Encoder that provides 8-bit encoding.
*
* @return Swift_Mime_ContentEncoder
*/
public static function get8BitEncoding()
{
return self::_lookup('mime.8bitcontentencoder');
}
/**
* Get the Encoder that provides Quoted-Printable (QP) encoding.
*
* @return Swift_Mime_ContentEncoder
*/
public static function getQpEncoding()
{
return self::_lookup('mime.qpcontentencoder');
}
/**
* Get the Encoder that provides Base64 encoding.
*
* @return Swift_Mime_ContentEncoder
*/
public static function getBase64Encoding()
{
return self::_lookup('mime.base64contentencoder');
}
// -- Private Static Methods
private static function _lookup($key)
{
return Swift_DependencyContainer::getInstance()->lookup($key);
}
}

View File

@@ -1,65 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Generated when a command is sent over an SMTP connection.
*
* @author Chris Corbyn
*/
class Swift_Events_CommandEvent extends Swift_Events_EventObject
{
/**
* The command sent to the server.
*
* @var string
*/
private $_command;
/**
* An array of codes which a successful response will contain.
*
* @var integer[]
*/
private $_successCodes = array();
/**
* Create a new CommandEvent for $source with $command.
*
* @param Swift_Transport $source
* @param string $command
* @param array $successCodes
*/
public function __construct(Swift_Transport $source, $command, $successCodes = array())
{
parent::__construct($source);
$this->_command = $command;
$this->_successCodes = $successCodes;
}
/**
* Get the command which was sent to the server.
*
* @return string
*/
public function getCommand()
{
return $this->_command;
}
/**
* Get the numeric response codes which indicate success for this command.
*
* @return integer[]
*/
public function getSuccessCodes()
{
return $this->_successCodes;
}
}

View File

@@ -1,24 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Listens for Transports to send commands to the server.
*
* @author Chris Corbyn
*/
interface Swift_Events_CommandListener extends Swift_Events_EventListener
{
/**
* Invoked immediately following a command being sent.
*
* @param Swift_Events_CommandEvent $evt
*/
public function commandSent(Swift_Events_CommandEvent $evt);
}

View File

@@ -1,38 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* The minimum interface for an Event.
*
* @author Chris Corbyn
*/
interface Swift_Events_Event
{
/**
* Get the source object of this event.
*
* @return object
*/
public function getSource();
/**
* Prevent this Event from bubbling any further up the stack.
*
* @param bool $cancel, optional
*/
public function cancelBubble($cancel = true);
/**
* Returns true if this Event will not bubble any further up the stack.
*
* @return bool
*/
public function bubbleCancelled();
}

View File

@@ -1,83 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Interface for the EventDispatcher which handles the event dispatching layer.
*
* @author Chris Corbyn
*/
interface Swift_Events_EventDispatcher
{
/**
* Create a new SendEvent for $source and $message.
*
* @param Swift_Transport $source
* @param Swift_Mime_Message
*
* @return Swift_Events_SendEvent
*/
public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message);
/**
* Create a new CommandEvent for $source and $command.
*
* @param Swift_Transport $source
* @param string $command That will be executed
* @param array $successCodes That are needed
*
* @return Swift_Events_CommandEvent
*/
public function createCommandEvent(Swift_Transport $source, $command, $successCodes = array());
/**
* Create a new ResponseEvent for $source and $response.
*
* @param Swift_Transport $source
* @param string $response
* @param bool $valid If the response is valid
*
* @return Swift_Events_ResponseEvent
*/
public function createResponseEvent(Swift_Transport $source, $response, $valid);
/**
* Create a new TransportChangeEvent for $source.
*
* @param Swift_Transport $source
*
* @return Swift_Events_TransportChangeEvent
*/
public function createTransportChangeEvent(Swift_Transport $source);
/**
* Create a new TransportExceptionEvent for $source.
*
* @param Swift_Transport $source
* @param Swift_TransportException $ex
*
* @return Swift_Events_TransportExceptionEvent
*/
public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex);
/**
* Bind an event listener to this dispatcher.
*
* @param Swift_Events_EventListener $listener
*/
public function bindEventListener(Swift_Events_EventListener $listener);
/**
* Dispatch the given Event to all suitable listeners.
*
* @param Swift_Events_EventObject $evt
* @param string $target method
*/
public function dispatchEvent(Swift_Events_EventObject $evt, $target);
}

View File

@@ -1,18 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An identity interface which all EventListeners must extend.
*
* @author Chris Corbyn
*/
interface Swift_Events_EventListener
{
}

View File

@@ -1,63 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A base Event which all Event classes inherit from.
*
* @author Chris Corbyn
*/
class Swift_Events_EventObject implements Swift_Events_Event
{
/** The source of this Event */
private $_source;
/** The state of this Event (should it bubble up the stack?) */
private $_bubbleCancelled = false;
/**
* Create a new EventObject originating at $source.
*
* @param object $source
*/
public function __construct($source)
{
$this->_source = $source;
}
/**
* Get the source object of this event.
*
* @return object
*/
public function getSource()
{
return $this->_source;
}
/**
* Prevent this Event from bubbling any further up the stack.
*
* @param bool $cancel, optional
*/
public function cancelBubble($cancel = true)
{
$this->_bubbleCancelled = $cancel;
}
/**
* Returns true if this Event will not bubble any further up the stack.
*
* @return bool
*/
public function bubbleCancelled()
{
return $this->_bubbleCancelled;
}
}

View File

@@ -1,65 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Generated when a response is received on a SMTP connection.
*
* @author Chris Corbyn
*/
class Swift_Events_ResponseEvent extends Swift_Events_EventObject
{
/**
* The overall result.
*
* @var bool
*/
private $_valid;
/**
* The response received from the server.
*
* @var string
*/
private $_response;
/**
* Create a new ResponseEvent for $source and $response.
*
* @param Swift_Transport $source
* @param string $response
* @param bool $valid
*/
public function __construct(Swift_Transport $source, $response, $valid = false)
{
parent::__construct($source);
$this->_response = $response;
$this->_valid = $valid;
}
/**
* Get the response which was received from the server.
*
* @return string
*/
public function getResponse()
{
return $this->_response;
}
/**
* Get the success status of this Event.
*
* @return bool
*/
public function isValid()
{
return $this->_valid;
}
}

View File

@@ -1,24 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Listens for responses from a remote SMTP server.
*
* @author Chris Corbyn
*/
interface Swift_Events_ResponseListener extends Swift_Events_EventListener
{
/**
* Invoked immediately following a response coming back.
*
* @param Swift_Events_ResponseEvent $evt
*/
public function responseReceived(Swift_Events_ResponseEvent $evt);
}

View File

@@ -1,129 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Generated when a message is being sent.
*
* @author Chris Corbyn
*/
class Swift_Events_SendEvent extends Swift_Events_EventObject
{
/** Sending has yet to occur */
const RESULT_PENDING = 0x0001;
/** Email is spooled, ready to be sent */
const RESULT_SPOOLED = 0x0011;
/** Sending was successful */
const RESULT_SUCCESS = 0x0010;
/** Sending worked, but there were some failures */
const RESULT_TENTATIVE = 0x0100;
/** Sending failed */
const RESULT_FAILED = 0x1000;
/**
* The Message being sent.
*
* @var Swift_Mime_Message
*/
private $_message;
/**
* Any recipients which failed after sending.
*
* @var string[]
*/
private $_failedRecipients = array();
/**
* The overall result as a bitmask from the class constants.
*
* @var int
*/
private $_result;
/**
* Create a new SendEvent for $source and $message.
*
* @param Swift_Transport $source
* @param Swift_Mime_Message $message
*/
public function __construct(Swift_Transport $source, Swift_Mime_Message $message)
{
parent::__construct($source);
$this->_message = $message;
$this->_result = self::RESULT_PENDING;
}
/**
* Get the Transport used to send the Message.
*
* @return Swift_Transport
*/
public function getTransport()
{
return $this->getSource();
}
/**
* Get the Message being sent.
*
* @return Swift_Mime_Message
*/
public function getMessage()
{
return $this->_message;
}
/**
* Set the array of addresses that failed in sending.
*
* @param array $recipients
*/
public function setFailedRecipients($recipients)
{
$this->_failedRecipients = $recipients;
}
/**
* Get an recipient addresses which were not accepted for delivery.
*
* @return string[]
*/
public function getFailedRecipients()
{
return $this->_failedRecipients;
}
/**
* Set the result of sending.
*
* @param int $result
*/
public function setResult($result)
{
$this->_result = $result;
}
/**
* Get the result of this Event.
*
* The return value is a bitmask from
* {@see RESULT_PENDING, RESULT_SUCCESS, RESULT_TENTATIVE, RESULT_FAILED}
*
* @return int
*/
public function getResult()
{
return $this->_result;
}
}

View File

@@ -1,31 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Listens for Messages being sent from within the Transport system.
*
* @author Chris Corbyn
*/
interface Swift_Events_SendListener extends Swift_Events_EventListener
{
/**
* Invoked immediately before the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(Swift_Events_SendEvent $evt);
/**
* Invoked immediately after the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(Swift_Events_SendEvent $evt);
}

View File

@@ -1,156 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* The EventDispatcher which handles the event dispatching layer.
*
* @author Chris Corbyn
*/
class Swift_Events_SimpleEventDispatcher implements Swift_Events_EventDispatcher
{
/** A map of event types to their associated listener types */
private $_eventMap = array();
/** Event listeners bound to this dispatcher */
private $_listeners = array();
/** Listeners queued to have an Event bubbled up the stack to them */
private $_bubbleQueue = array();
/**
* Create a new EventDispatcher.
*/
public function __construct()
{
$this->_eventMap = array(
'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener',
'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener',
'Swift_Events_SendEvent' => 'Swift_Events_SendListener',
'Swift_Events_TransportChangeEvent' => 'Swift_Events_TransportChangeListener',
'Swift_Events_TransportExceptionEvent' => 'Swift_Events_TransportExceptionListener',
);
}
/**
* Create a new SendEvent for $source and $message.
*
* @param Swift_Transport $source
* @param Swift_Mime_Message
*
* @return Swift_Events_SendEvent
*/
public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message)
{
return new Swift_Events_SendEvent($source, $message);
}
/**
* Create a new CommandEvent for $source and $command.
*
* @param Swift_Transport $source
* @param string $command That will be executed
* @param array $successCodes That are needed
*
* @return Swift_Events_CommandEvent
*/
public function createCommandEvent(Swift_Transport $source, $command, $successCodes = array())
{
return new Swift_Events_CommandEvent($source, $command, $successCodes);
}
/**
* Create a new ResponseEvent for $source and $response.
*
* @param Swift_Transport $source
* @param string $response
* @param bool $valid If the response is valid
*
* @return Swift_Events_ResponseEvent
*/
public function createResponseEvent(Swift_Transport $source, $response, $valid)
{
return new Swift_Events_ResponseEvent($source, $response, $valid);
}
/**
* Create a new TransportChangeEvent for $source.
*
* @param Swift_Transport $source
*
* @return Swift_Events_TransportChangeEvent
*/
public function createTransportChangeEvent(Swift_Transport $source)
{
return new Swift_Events_TransportChangeEvent($source);
}
/**
* Create a new TransportExceptionEvent for $source.
*
* @param Swift_Transport $source
* @param Swift_TransportException $ex
*
* @return Swift_Events_TransportExceptionEvent
*/
public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex)
{
return new Swift_Events_TransportExceptionEvent($source, $ex);
}
/**
* Bind an event listener to this dispatcher.
*
* @param Swift_Events_EventListener $listener
*/
public function bindEventListener(Swift_Events_EventListener $listener)
{
foreach ($this->_listeners as $l) {
// Already loaded
if ($l === $listener) {
return;
}
}
$this->_listeners[] = $listener;
}
/**
* Dispatch the given Event to all suitable listeners.
*
* @param Swift_Events_EventObject $evt
* @param string $target method
*/
public function dispatchEvent(Swift_Events_EventObject $evt, $target)
{
$this->_prepareBubbleQueue($evt);
$this->_bubble($evt, $target);
}
/** Queue listeners on a stack ready for $evt to be bubbled up it */
private function _prepareBubbleQueue(Swift_Events_EventObject $evt)
{
$this->_bubbleQueue = array();
$evtClass = get_class($evt);
foreach ($this->_listeners as $listener) {
if (array_key_exists($evtClass, $this->_eventMap)
&& ($listener instanceof $this->_eventMap[$evtClass])) {
$this->_bubbleQueue[] = $listener;
}
}
}
/** Bubble $evt up the stack calling $target() on each listener */
private function _bubble(Swift_Events_EventObject $evt, $target)
{
if (!$evt->bubbleCancelled() && $listener = array_shift($this->_bubbleQueue)) {
$listener->$target($evt);
$this->_bubble($evt, $target);
}
}
}

View File

@@ -1,27 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Generated when the state of a Transport is changed (i.e. stopped/started).
*
* @author Chris Corbyn
*/
class Swift_Events_TransportChangeEvent extends Swift_Events_EventObject
{
/**
* Get the Transport.
*
* @return Swift_Transport
*/
public function getTransport()
{
return $this->getSource();
}
}

View File

@@ -1,45 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Listens for changes within the Transport system.
*
* @author Chris Corbyn
*/
interface Swift_Events_TransportChangeListener extends Swift_Events_EventListener
{
/**
* Invoked just before a Transport is started.
*
* @param Swift_Events_TransportChangeEvent $evt
*/
public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt);
/**
* Invoked immediately after the Transport is started.
*
* @param Swift_Events_TransportChangeEvent $evt
*/
public function transportStarted(Swift_Events_TransportChangeEvent $evt);
/**
* Invoked just before a Transport is stopped.
*
* @param Swift_Events_TransportChangeEvent $evt
*/
public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt);
/**
* Invoked immediately after the Transport is stopped.
*
* @param Swift_Events_TransportChangeEvent $evt
*/
public function transportStopped(Swift_Events_TransportChangeEvent $evt);
}

View File

@@ -1,46 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Generated when a TransportException is thrown from the Transport system.
*
* @author Chris Corbyn
*/
class Swift_Events_TransportExceptionEvent extends Swift_Events_EventObject
{
/**
* The Exception thrown.
*
* @var Swift_TransportException
*/
private $_exception;
/**
* Create a new TransportExceptionEvent for $transport.
*
* @param Swift_Transport $transport
* @param Swift_TransportException $ex
*/
public function __construct(Swift_Transport $transport, Swift_TransportException $ex)
{
parent::__construct($transport);
$this->_exception = $ex;
}
/**
* Get the TransportException thrown.
*
* @return Swift_TransportException
*/
public function getException()
{
return $this->_exception;
}
}

View File

@@ -1,24 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Listens for Exceptions thrown from within the Transport system.
*
* @author Chris Corbyn
*/
interface Swift_Events_TransportExceptionListener extends Swift_Events_EventListener
{
/**
* Invoked as a TransportException is thrown in the Transport system.
*
* @param Swift_Events_TransportExceptionEvent $evt
*/
public function exceptionThrown(Swift_Events_TransportExceptionEvent $evt);
}

View File

@@ -1,45 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Contains a list of redundant Transports so when one fails, the next is used.
*
* @author Chris Corbyn
*/
class Swift_FailoverTransport extends Swift_Transport_FailoverTransport
{
/**
* Creates a new FailoverTransport with $transports.
*
* @param Swift_Transport[] $transports
*/
public function __construct($transports = array())
{
call_user_func_array(
array($this, 'Swift_Transport_FailoverTransport::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('transport.failover')
);
$this->setTransports($transports);
}
/**
* Create a new FailoverTransport instance.
*
* @param Swift_Transport[] $transports
*
* @return Swift_FailoverTransport
*/
public static function newInstance($transports = array())
{
return new self($transports);
}
}

View File

@@ -1,208 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2009 Fabien Potencier <fabien.potencier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Stores Messages on the filesystem.
*
* @author Fabien Potencier
* @author Xavier De Cock <xdecock@gmail.com>
*/
class Swift_FileSpool extends Swift_ConfigurableSpool
{
/** The spool directory */
private $_path;
/**
* File WriteRetry Limit.
*
* @var int
*/
private $_retryLimit = 10;
/**
* Create a new FileSpool.
*
* @param string $path
*
* @throws Swift_IoException
*/
public function __construct($path)
{
$this->_path = $path;
if (!file_exists($this->_path)) {
if (!mkdir($this->_path, 0777, true)) {
throw new Swift_IoException(sprintf('Unable to create path "%s".', $this->_path));
}
}
}
/**
* Tests if this Spool mechanism has started.
*
* @return bool
*/
public function isStarted()
{
return true;
}
/**
* Starts this Spool mechanism.
*/
public function start()
{
}
/**
* Stops this Spool mechanism.
*/
public function stop()
{
}
/**
* Allow to manage the enqueuing retry limit.
*
* Default, is ten and allows over 64^20 different fileNames
*
* @param int $limit
*/
public function setRetryLimit($limit)
{
$this->_retryLimit = $limit;
}
/**
* Queues a message.
*
* @param Swift_Mime_Message $message The message to store
*
* @throws Swift_IoException
*
* @return bool
*/
public function queueMessage(Swift_Mime_Message $message)
{
$ser = serialize($message);
$fileName = $this->_path.'/'.$this->getRandomString(10);
for ($i = 0; $i < $this->_retryLimit; ++$i) {
/* We try an exclusive creation of the file. This is an atomic operation, it avoid locking mechanism */
$fp = @fopen($fileName.'.message', 'x');
if (false !== $fp) {
if (false === fwrite($fp, $ser)) {
return false;
}
return fclose($fp);
} else {
/* The file already exists, we try a longer fileName */
$fileName .= $this->getRandomString(1);
}
}
throw new Swift_IoException(sprintf('Unable to create a file for enqueuing Message in "%s".', $this->_path));
}
/**
* Execute a recovery if for any reason a process is sending for too long.
*
* @param int $timeout in second Defaults is for very slow smtp responses
*/
public function recover($timeout = 900)
{
foreach (new DirectoryIterator($this->_path) as $file) {
$file = $file->getRealPath();
if (substr($file, -16) == '.message.sending') {
$lockedtime = filectime($file);
if ((time() - $lockedtime) > $timeout) {
rename($file, substr($file, 0, -8));
}
}
}
}
/**
* Sends messages using the given transport instance.
*
* @param Swift_Transport $transport A transport instance
* @param string[] $failedRecipients An array of failures by-reference
*
* @return int The number of sent e-mail's
*/
public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
{
$directoryIterator = new DirectoryIterator($this->_path);
/* Start the transport only if there are queued files to send */
if (!$transport->isStarted()) {
foreach ($directoryIterator as $file) {
if (substr($file->getRealPath(), -8) == '.message') {
$transport->start();
break;
}
}
}
$failedRecipients = (array) $failedRecipients;
$count = 0;
$time = time();
foreach ($directoryIterator as $file) {
$file = $file->getRealPath();
if (substr($file, -8) != '.message') {
continue;
}
/* We try a rename, it's an atomic operation, and avoid locking the file */
if (rename($file, $file.'.sending')) {
$message = unserialize(file_get_contents($file.'.sending'));
$count += $transport->send($message, $failedRecipients);
unlink($file.'.sending');
} else {
/* This message has just been catched by another process */
continue;
}
if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) {
break;
}
if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit()) {
break;
}
}
return $count;
}
/**
* Returns a random string needed to generate a fileName for the queue.
*
* @param int $count
*
* @return string
*/
protected function getRandomString($count)
{
// This string MUST stay FS safe, avoid special chars
$base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
$ret = '';
$strlen = strlen($base);
for ($i = 0; $i < $count; ++$i) {
$ret .= $base[((int) rand(0, $strlen - 1))];
}
return $ret;
}
}

View File

@@ -1,24 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An OutputByteStream which specifically reads from a file.
*
* @author Chris Corbyn
*/
interface Swift_FileStream extends Swift_OutputByteStream
{
/**
* Get the complete path to the file.
*
* @return string
*/
public function getPath();
}

View File

@@ -1,32 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Allows StreamFilters to operate on a stream.
*
* @author Chris Corbyn
*/
interface Swift_Filterable
{
/**
* Add a new StreamFilter, referenced by $key.
*
* @param Swift_StreamFilter $filter
* @param string $key
*/
public function addFilter(Swift_StreamFilter $filter, $key);
/**
* Remove an existing filter using $key.
*
* @param string $key
*/
public function removeFilter($key);
}

View File

@@ -1,61 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An image, embedded in a multipart message.
*
* @author Chris Corbyn
*/
class Swift_Image extends Swift_EmbeddedFile
{
/**
* Create a new EmbeddedFile.
*
* Details may be optionally provided to the constructor.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*/
public function __construct($data = null, $filename = null, $contentType = null)
{
parent::__construct($data, $filename, $contentType);
}
/**
* Create a new Image.
*
* @param string|Swift_OutputByteStream $data
* @param string $filename
* @param string $contentType
*
* @return Swift_Image
*/
public static function newInstance($data = null, $filename = null, $contentType = null)
{
return new self($data, $filename, $contentType);
}
/**
* Create a new Image from a filesystem path.
*
* @param string $path
*
* @return Swift_Image
*/
public static function fromPath($path)
{
$image = self::newInstance()->setFile(
new Swift_ByteStream_FileByteStream($path)
);
return $image;
}
}

View File

@@ -1,75 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An abstract means of writing data.
*
* Classes implementing this interface may use a subsystem which requires less
* memory than working with large strings of data.
*
* @author Chris Corbyn
*/
interface Swift_InputByteStream
{
/**
* Writes $bytes to the end of the stream.
*
* Writing may not happen immediately if the stream chooses to buffer. If
* you want to write these bytes with immediate effect, call {@link commit()}
* after calling write().
*
* This method returns the sequence ID of the write (i.e. 1 for first, 2 for
* second, etc etc).
*
* @param string $bytes
*
* @throws Swift_IoException
*
* @return int
*/
public function write($bytes);
/**
* For any bytes that are currently buffered inside the stream, force them
* off the buffer.
*
* @throws Swift_IoException
*/
public function commit();
/**
* Attach $is to this stream.
*
* The stream acts as an observer, receiving all data that is written.
* All {@link write()} and {@link flushBuffers()} operations will be mirrored.
*
* @param Swift_InputByteStream $is
*/
public function bind(Swift_InputByteStream $is);
/**
* Remove an already bound stream.
*
* If $is is not bound, no errors will be raised.
* If the stream currently has any buffered data it will be written to $is
* before unbinding occurs.
*
* @param Swift_InputByteStream $is
*/
public function unbind(Swift_InputByteStream $is);
/**
* Flush the contents of the stream (empty it) and set the internal pointer
* to the beginning.
*
* @throws Swift_IoException
*/
public function flushBuffers();
}

View File

@@ -1,29 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* I/O Exception class.
*
* @author Chris Corbyn
*/
class Swift_IoException extends Swift_SwiftException
{
/**
* Create a new IoException with $message.
*
* @param string $message
* @param int $code
* @param Exception $previous
*/
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View File

@@ -1,105 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Provides a mechanism for storing data using two keys.
*
* @author Chris Corbyn
*/
interface Swift_KeyCache
{
/** Mode for replacing existing cached data */
const MODE_WRITE = 1;
/** Mode for appending data to the end of existing cached data */
const MODE_APPEND = 2;
/**
* Set a string into the cache under $itemKey for the namespace $nsKey.
*
* @see MODE_WRITE, MODE_APPEND
*
* @param string $nsKey
* @param string $itemKey
* @param string $string
* @param int $mode
*/
public function setString($nsKey, $itemKey, $string, $mode);
/**
* Set a ByteStream into the cache under $itemKey for the namespace $nsKey.
*
* @see MODE_WRITE, MODE_APPEND
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_OutputByteStream $os
* @param int $mode
*/
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode);
/**
* Provides a ByteStream which when written to, writes data to $itemKey.
*
* NOTE: The stream will always write in append mode.
* If the optional third parameter is passed all writes will go through $is.
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_InputByteStream $is optional input stream
*
* @return Swift_InputByteStream
*/
public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $is = null);
/**
* Get data back out of the cache as a string.
*
* @param string $nsKey
* @param string $itemKey
*
* @return string
*/
public function getString($nsKey, $itemKey);
/**
* Get data back out of the cache as a ByteStream.
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_InputByteStream $is stream to write the data to
*/
public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is);
/**
* Check if the given $itemKey exists in the namespace $nsKey.
*
* @param string $nsKey
* @param string $itemKey
*
* @return bool
*/
public function hasKey($nsKey, $itemKey);
/**
* Clear data for $itemKey in the namespace $nsKey if it exists.
*
* @param string $nsKey
* @param string $itemKey
*/
public function clearKey($nsKey, $itemKey);
/**
* Clear all data in the namespace $nsKey if it exists.
*
* @param string $nsKey
*/
public function clearAll($nsKey);
}

View File

@@ -1,206 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A basic KeyCache backed by an array.
*
* @author Chris Corbyn
*/
class Swift_KeyCache_ArrayKeyCache implements Swift_KeyCache
{
/**
* Cache contents.
*
* @var array
*/
private $_contents = array();
/**
* An InputStream for cloning.
*
* @var Swift_KeyCache_KeyCacheInputStream
*/
private $_stream;
/**
* Create a new ArrayKeyCache with the given $stream for cloning to make
* InputByteStreams.
*
* @param Swift_KeyCache_KeyCacheInputStream $stream
*/
public function __construct(Swift_KeyCache_KeyCacheInputStream $stream)
{
$this->_stream = $stream;
}
/**
* Set a string into the cache under $itemKey for the namespace $nsKey.
*
* @see MODE_WRITE, MODE_APPEND
*
* @param string $nsKey
* @param string $itemKey
* @param string $string
* @param int $mode
*/
public function setString($nsKey, $itemKey, $string, $mode)
{
$this->_prepareCache($nsKey);
switch ($mode) {
case self::MODE_WRITE:
$this->_contents[$nsKey][$itemKey] = $string;
break;
case self::MODE_APPEND:
if (!$this->hasKey($nsKey, $itemKey)) {
$this->_contents[$nsKey][$itemKey] = '';
}
$this->_contents[$nsKey][$itemKey] .= $string;
break;
default:
throw new Swift_SwiftException(
'Invalid mode ['.$mode.'] used to set nsKey='.
$nsKey.', itemKey='.$itemKey
);
}
}
/**
* Set a ByteStream into the cache under $itemKey for the namespace $nsKey.
*
* @see MODE_WRITE, MODE_APPEND
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_OutputByteStream $os
* @param int $mode
*/
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode)
{
$this->_prepareCache($nsKey);
switch ($mode) {
case self::MODE_WRITE:
$this->clearKey($nsKey, $itemKey);
case self::MODE_APPEND:
if (!$this->hasKey($nsKey, $itemKey)) {
$this->_contents[$nsKey][$itemKey] = '';
}
while (false !== $bytes = $os->read(8192)) {
$this->_contents[$nsKey][$itemKey] .= $bytes;
}
break;
default:
throw new Swift_SwiftException(
'Invalid mode ['.$mode.'] used to set nsKey='.
$nsKey.', itemKey='.$itemKey
);
}
}
/**
* Provides a ByteStream which when written to, writes data to $itemKey.
*
* NOTE: The stream will always write in append mode.
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_InputByteStream $writeThrough
*
* @return Swift_InputByteStream
*/
public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null)
{
$is = clone $this->_stream;
$is->setKeyCache($this);
$is->setNsKey($nsKey);
$is->setItemKey($itemKey);
if (isset($writeThrough)) {
$is->setWriteThroughStream($writeThrough);
}
return $is;
}
/**
* Get data back out of the cache as a string.
*
* @param string $nsKey
* @param string $itemKey
*
* @return string
*/
public function getString($nsKey, $itemKey)
{
$this->_prepareCache($nsKey);
if ($this->hasKey($nsKey, $itemKey)) {
return $this->_contents[$nsKey][$itemKey];
}
}
/**
* Get data back out of the cache as a ByteStream.
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_InputByteStream $is to write the data to
*/
public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is)
{
$this->_prepareCache($nsKey);
$is->write($this->getString($nsKey, $itemKey));
}
/**
* Check if the given $itemKey exists in the namespace $nsKey.
*
* @param string $nsKey
* @param string $itemKey
*
* @return bool
*/
public function hasKey($nsKey, $itemKey)
{
$this->_prepareCache($nsKey);
return array_key_exists($itemKey, $this->_contents[$nsKey]);
}
/**
* Clear data for $itemKey in the namespace $nsKey if it exists.
*
* @param string $nsKey
* @param string $itemKey
*/
public function clearKey($nsKey, $itemKey)
{
unset($this->_contents[$nsKey][$itemKey]);
}
/**
* Clear all data in the namespace $nsKey if it exists.
*
* @param string $nsKey
*/
public function clearAll($nsKey)
{
unset($this->_contents[$nsKey]);
}
/**
* Initialize the namespace of $nsKey if needed.
*
* @param string $nsKey
*/
private function _prepareCache($nsKey)
{
if (!array_key_exists($nsKey, $this->_contents)) {
$this->_contents[$nsKey] = array();
}
}
}

View File

@@ -1,321 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A KeyCache which streams to and from disk.
*
* @author Chris Corbyn
*/
class Swift_KeyCache_DiskKeyCache implements Swift_KeyCache
{
/** Signal to place pointer at start of file */
const POSITION_START = 0;
/** Signal to place pointer at end of file */
const POSITION_END = 1;
/** Signal to leave pointer in whatever position it currently is */
const POSITION_CURRENT = 2;
/**
* An InputStream for cloning.
*
* @var Swift_KeyCache_KeyCacheInputStream
*/
private $_stream;
/**
* A path to write to.
*
* @var string
*/
private $_path;
/**
* Stored keys.
*
* @var array
*/
private $_keys = array();
/**
* Will be true if magic_quotes_runtime is turned on.
*
* @var bool
*/
private $_quotes = false;
/**
* Create a new DiskKeyCache with the given $stream for cloning to make
* InputByteStreams, and the given $path to save to.
*
* @param Swift_KeyCache_KeyCacheInputStream $stream
* @param string $path to save to
*/
public function __construct(Swift_KeyCache_KeyCacheInputStream $stream, $path)
{
$this->_stream = $stream;
$this->_path = $path;
if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) {
$this->_quotes = true;
}
}
/**
* Set a string into the cache under $itemKey for the namespace $nsKey.
*
* @see MODE_WRITE, MODE_APPEND
*
* @param string $nsKey
* @param string $itemKey
* @param string $string
* @param int $mode
*
* @throws Swift_IoException
*/
public function setString($nsKey, $itemKey, $string, $mode)
{
$this->_prepareCache($nsKey);
switch ($mode) {
case self::MODE_WRITE:
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START);
break;
case self::MODE_APPEND:
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END);
break;
default:
throw new Swift_SwiftException(
'Invalid mode ['.$mode.'] used to set nsKey='.
$nsKey.', itemKey='.$itemKey
);
break;
}
fwrite($fp, $string);
$this->_freeHandle($nsKey, $itemKey);
}
/**
* Set a ByteStream into the cache under $itemKey for the namespace $nsKey.
*
* @see MODE_WRITE, MODE_APPEND
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_OutputByteStream $os
* @param int $mode
*
* @throws Swift_IoException
*/
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode)
{
$this->_prepareCache($nsKey);
switch ($mode) {
case self::MODE_WRITE:
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START);
break;
case self::MODE_APPEND:
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END);
break;
default:
throw new Swift_SwiftException(
'Invalid mode ['.$mode.'] used to set nsKey='.
$nsKey.', itemKey='.$itemKey
);
break;
}
while (false !== $bytes = $os->read(8192)) {
fwrite($fp, $bytes);
}
$this->_freeHandle($nsKey, $itemKey);
}
/**
* Provides a ByteStream which when written to, writes data to $itemKey.
*
* NOTE: The stream will always write in append mode.
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_InputByteStream $writeThrough
*
* @return Swift_InputByteStream
*/
public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null)
{
$is = clone $this->_stream;
$is->setKeyCache($this);
$is->setNsKey($nsKey);
$is->setItemKey($itemKey);
if (isset($writeThrough)) {
$is->setWriteThroughStream($writeThrough);
}
return $is;
}
/**
* Get data back out of the cache as a string.
*
* @param string $nsKey
* @param string $itemKey
*
* @throws Swift_IoException
*
* @return string
*/
public function getString($nsKey, $itemKey)
{
$this->_prepareCache($nsKey);
if ($this->hasKey($nsKey, $itemKey)) {
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START);
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 0);
}
$str = '';
while (!feof($fp) && false !== $bytes = fread($fp, 8192)) {
$str .= $bytes;
}
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 1);
}
$this->_freeHandle($nsKey, $itemKey);
return $str;
}
}
/**
* Get data back out of the cache as a ByteStream.
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_InputByteStream $is to write the data to
*/
public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is)
{
if ($this->hasKey($nsKey, $itemKey)) {
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START);
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 0);
}
while (!feof($fp) && false !== $bytes = fread($fp, 8192)) {
$is->write($bytes);
}
if ($this->_quotes) {
ini_set('magic_quotes_runtime', 1);
}
$this->_freeHandle($nsKey, $itemKey);
}
}
/**
* Check if the given $itemKey exists in the namespace $nsKey.
*
* @param string $nsKey
* @param string $itemKey
*
* @return bool
*/
public function hasKey($nsKey, $itemKey)
{
return is_file($this->_path.'/'.$nsKey.'/'.$itemKey);
}
/**
* Clear data for $itemKey in the namespace $nsKey if it exists.
*
* @param string $nsKey
* @param string $itemKey
*/
public function clearKey($nsKey, $itemKey)
{
if ($this->hasKey($nsKey, $itemKey)) {
$this->_freeHandle($nsKey, $itemKey);
unlink($this->_path.'/'.$nsKey.'/'.$itemKey);
}
}
/**
* Clear all data in the namespace $nsKey if it exists.
*
* @param string $nsKey
*/
public function clearAll($nsKey)
{
if (array_key_exists($nsKey, $this->_keys)) {
foreach ($this->_keys[$nsKey] as $itemKey => $null) {
$this->clearKey($nsKey, $itemKey);
}
if (is_dir($this->_path.'/'.$nsKey)) {
rmdir($this->_path.'/'.$nsKey);
}
unset($this->_keys[$nsKey]);
}
}
/**
* Initialize the namespace of $nsKey if needed.
*
* @param string $nsKey
*/
private function _prepareCache($nsKey)
{
$cacheDir = $this->_path.'/'.$nsKey;
if (!is_dir($cacheDir)) {
if (!mkdir($cacheDir)) {
throw new Swift_IoException('Failed to create cache directory '.$cacheDir);
}
$this->_keys[$nsKey] = array();
}
}
/**
* Get a file handle on the cache item.
*
* @param string $nsKey
* @param string $itemKey
* @param int $position
*
* @return resource
*/
private function _getHandle($nsKey, $itemKey, $position)
{
if (!isset($this->_keys[$nsKey][$itemKey])) {
$openMode = $this->hasKey($nsKey, $itemKey) ? 'r+b' : 'w+b';
$fp = fopen($this->_path.'/'.$nsKey.'/'.$itemKey, $openMode);
$this->_keys[$nsKey][$itemKey] = $fp;
}
if (self::POSITION_START == $position) {
fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_SET);
} elseif (self::POSITION_END == $position) {
fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_END);
}
return $this->_keys[$nsKey][$itemKey];
}
private function _freeHandle($nsKey, $itemKey)
{
$fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_CURRENT);
fclose($fp);
$this->_keys[$nsKey][$itemKey] = null;
}
/**
* Destructor.
*/
public function __destruct()
{
foreach ($this->_keys as $nsKey => $null) {
$this->clearAll($nsKey);
}
}
}

View File

@@ -1,51 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Writes data to a KeyCache using a stream.
*
* @author Chris Corbyn
*/
interface Swift_KeyCache_KeyCacheInputStream extends Swift_InputByteStream
{
/**
* Set the KeyCache to wrap.
*
* @param Swift_KeyCache $keyCache
*/
public function setKeyCache(Swift_KeyCache $keyCache);
/**
* Set the nsKey which will be written to.
*
* @param string $nsKey
*/
public function setNsKey($nsKey);
/**
* Set the itemKey which will be written to.
*
* @param string $itemKey
*/
public function setItemKey($itemKey);
/**
* Specify a stream to write through for each write().
*
* @param Swift_InputByteStream $is
*/
public function setWriteThroughStream(Swift_InputByteStream $is);
/**
* Any implementation should be cloneable, allowing the clone to access a
* separate $nsKey and $itemKey.
*/
public function __clone();
}

View File

@@ -1,115 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A null KeyCache that does not cache at all.
*
* @author Chris Corbyn
*/
class Swift_KeyCache_NullKeyCache implements Swift_KeyCache
{
/**
* Set a string into the cache under $itemKey for the namespace $nsKey.
*
* @see MODE_WRITE, MODE_APPEND
*
* @param string $nsKey
* @param string $itemKey
* @param string $string
* @param int $mode
*/
public function setString($nsKey, $itemKey, $string, $mode)
{
}
/**
* Set a ByteStream into the cache under $itemKey for the namespace $nsKey.
*
* @see MODE_WRITE, MODE_APPEND
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_OutputByteStream $os
* @param int $mode
*/
public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode)
{
}
/**
* Provides a ByteStream which when written to, writes data to $itemKey.
*
* NOTE: The stream will always write in append mode.
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_InputByteStream $writeThrough
*
* @return Swift_InputByteStream
*/
public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null)
{
}
/**
* Get data back out of the cache as a string.
*
* @param string $nsKey
* @param string $itemKey
*
* @return string
*/
public function getString($nsKey, $itemKey)
{
}
/**
* Get data back out of the cache as a ByteStream.
*
* @param string $nsKey
* @param string $itemKey
* @param Swift_InputByteStream $is to write the data to
*/
public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is)
{
}
/**
* Check if the given $itemKey exists in the namespace $nsKey.
*
* @param string $nsKey
* @param string $itemKey
*
* @return bool
*/
public function hasKey($nsKey, $itemKey)
{
return false;
}
/**
* Clear data for $itemKey in the namespace $nsKey if it exists.
*
* @param string $nsKey
* @param string $itemKey
*/
public function clearKey($nsKey, $itemKey)
{
}
/**
* Clear all data in the namespace $nsKey if it exists.
*
* @param string $nsKey
*/
public function clearAll($nsKey)
{
}
}

View File

@@ -1,127 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Writes data to a KeyCache using a stream.
*
* @author Chris Corbyn
*/
class Swift_KeyCache_SimpleKeyCacheInputStream implements Swift_KeyCache_KeyCacheInputStream
{
/** The KeyCache being written to */
private $_keyCache;
/** The nsKey of the KeyCache being written to */
private $_nsKey;
/** The itemKey of the KeyCache being written to */
private $_itemKey;
/** A stream to write through on each write() */
private $_writeThrough = null;
/**
* Set the KeyCache to wrap.
*
* @param Swift_KeyCache $keyCache
*/
public function setKeyCache(Swift_KeyCache $keyCache)
{
$this->_keyCache = $keyCache;
}
/**
* Specify a stream to write through for each write().
*
* @param Swift_InputByteStream $is
*/
public function setWriteThroughStream(Swift_InputByteStream $is)
{
$this->_writeThrough = $is;
}
/**
* Writes $bytes to the end of the stream.
*
* @param string $bytes
* @param Swift_InputByteStream $is optional
*/
public function write($bytes, Swift_InputByteStream $is = null)
{
$this->_keyCache->setString(
$this->_nsKey, $this->_itemKey, $bytes, Swift_KeyCache::MODE_APPEND
);
if (isset($is)) {
$is->write($bytes);
}
if (isset($this->_writeThrough)) {
$this->_writeThrough->write($bytes);
}
}
/**
* Not used.
*/
public function commit()
{
}
/**
* Not used.
*/
public function bind(Swift_InputByteStream $is)
{
}
/**
* Not used.
*/
public function unbind(Swift_InputByteStream $is)
{
}
/**
* Flush the contents of the stream (empty it) and set the internal pointer
* to the beginning.
*/
public function flushBuffers()
{
$this->_keyCache->clearKey($this->_nsKey, $this->_itemKey);
}
/**
* Set the nsKey which will be written to.
*
* @param string $nsKey
*/
public function setNsKey($nsKey)
{
$this->_nsKey = $nsKey;
}
/**
* Set the itemKey which will be written to.
*
* @param string $itemKey
*/
public function setItemKey($itemKey)
{
$this->_itemKey = $itemKey;
}
/**
* Any implementation should be cloneable, allowing the clone to access a
* separate $nsKey and $itemKey.
*/
public function __clone()
{
$this->_writeThrough = null;
}
}

View File

@@ -1,45 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Redundantly and rotationally uses several Transport implementations when sending.
*
* @author Chris Corbyn
*/
class Swift_LoadBalancedTransport extends Swift_Transport_LoadBalancedTransport
{
/**
* Creates a new LoadBalancedTransport with $transports.
*
* @param array $transports
*/
public function __construct($transports = array())
{
call_user_func_array(
array($this, 'Swift_Transport_LoadBalancedTransport::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('transport.loadbalanced')
);
$this->setTransports($transports);
}
/**
* Create a new LoadBalancedTransport instance.
*
* @param array $transports
*
* @return Swift_LoadBalancedTransport
*/
public static function newInstance($transports = array())
{
return new self($transports);
}
}

View File

@@ -1,45 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Sends Messages using the mail() function.
*
* @author Chris Corbyn
*/
class Swift_MailTransport extends Swift_Transport_MailTransport
{
/**
* Create a new MailTransport, optionally specifying $extraParams.
*
* @param string $extraParams
*/
public function __construct($extraParams = '-f%s')
{
call_user_func_array(
array($this, 'Swift_Transport_MailTransport::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('transport.mail')
);
$this->setExtraParams($extraParams);
}
/**
* Create a new MailTransport instance.
*
* @param string $extraParams To be passed to mail()
*
* @return Swift_MailTransport
*/
public static function newInstance($extraParams = '-f%s')
{
return new self($extraParams);
}
}

View File

@@ -1,114 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Swift Mailer class.
*
* @author Chris Corbyn
*/
class Swift_Mailer
{
/** The Transport used to send messages */
private $_transport;
/**
* Create a new Mailer using $transport for delivery.
*
* @param Swift_Transport $transport
*/
public function __construct(Swift_Transport $transport)
{
$this->_transport = $transport;
}
/**
* Create a new Mailer instance.
*
* @param Swift_Transport $transport
*
* @return Swift_Mailer
*/
public static function newInstance(Swift_Transport $transport)
{
return new self($transport);
}
/**
* Create a new class instance of one of the message services.
*
* For example 'mimepart' would create a 'message.mimepart' instance
*
* @param string $service
*
* @return object
*/
public function createMessage($service = 'message')
{
return Swift_DependencyContainer::getInstance()
->lookup('message.'.$service);
}
/**
* Send the given Message like it would be sent in a mail client.
*
* All recipients (with the exception of Bcc) will be able to see the other
* recipients this message was sent to.
*
* Recipient/sender data will be retrieved from the Message object.
*
* The return value is the number of recipients who were accepted for
* delivery.
*
* @param Swift_Mime_Message $message
* @param array $failedRecipients An array of failures by-reference
*
* @return int The number of successful recipients. Can be 0 which indicates failure
*/
public function send(Swift_Mime_Message $message, &$failedRecipients = null)
{
$failedRecipients = (array) $failedRecipients;
if (!$this->_transport->isStarted()) {
$this->_transport->start();
}
$sent = 0;
try {
$sent = $this->_transport->send($message, $failedRecipients);
} catch (Swift_RfcComplianceException $e) {
foreach ($message->getTo() as $address => $name) {
$failedRecipients[] = $address;
}
}
return $sent;
}
/**
* Register a plugin using a known unique key (e.g. myPlugin).
*
* @param Swift_Events_EventListener $plugin
*/
public function registerPlugin(Swift_Events_EventListener $plugin)
{
$this->_transport->registerPlugin($plugin);
}
/**
* The Transport used to send messages.
*
* @return Swift_Transport
*/
public function getTransport()
{
return $this->_transport;
}
}

View File

@@ -1,55 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Wraps a standard PHP array in an iterator.
*
* @author Chris Corbyn
*/
class Swift_Mailer_ArrayRecipientIterator implements Swift_Mailer_RecipientIterator
{
/**
* The list of recipients.
*
* @var array
*/
private $_recipients = array();
/**
* Create a new ArrayRecipientIterator from $recipients.
*
* @param array $recipients
*/
public function __construct(array $recipients)
{
$this->_recipients = $recipients;
}
/**
* Returns true only if there are more recipients to send to.
*
* @return bool
*/
public function hasNext()
{
return !empty($this->_recipients);
}
/**
* Returns an array where the keys are the addresses of recipients and the
* values are the names. e.g. ('foo@bar' => 'Foo') or ('foo@bar' => NULL).
*
* @return array
*/
public function nextRecipient()
{
return array_splice($this->_recipients, 0, 1);
}
}

View File

@@ -1,32 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Provides an abstract way of specifying recipients for batch sending.
*
* @author Chris Corbyn
*/
interface Swift_Mailer_RecipientIterator
{
/**
* Returns true only if there are more recipients to send to.
*
* @return bool
*/
public function hasNext();
/**
* Returns an array where the keys are the addresses of recipients and the
* values are the names. e.g. ('foo@bar' => 'Foo') or ('foo@bar' => NULL).
*
* @return array
*/
public function nextRecipient();
}

View File

@@ -1,110 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2011 Fabien Potencier <fabien.potencier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Stores Messages in memory.
*
* @author Fabien Potencier
*/
class Swift_MemorySpool implements Swift_Spool
{
protected $messages = array();
private $flushRetries = 3;
/**
* Tests if this Transport mechanism has started.
*
* @return bool
*/
public function isStarted()
{
return true;
}
/**
* Starts this Transport mechanism.
*/
public function start()
{
}
/**
* Stops this Transport mechanism.
*/
public function stop()
{
}
/**
* @param int $retries
*/
public function setFlushRetries($retries)
{
$this->flushRetries = $retries;
}
/**
* Stores a message in the queue.
*
* @param Swift_Mime_Message $message The message to store
*
* @return bool Whether the operation has succeeded
*/
public function queueMessage(Swift_Mime_Message $message)
{
//clone the message to make sure it is not changed while in the queue
$this->messages[] = clone $message;
return true;
}
/**
* Sends messages using the given transport instance.
*
* @param Swift_Transport $transport A transport instance
* @param string[] $failedRecipients An array of failures by-reference
*
* @return int The number of sent emails
*/
public function flushQueue(Swift_Transport $transport, &$failedRecipients = null)
{
if (!$this->messages) {
return 0;
}
if (!$transport->isStarted()) {
$transport->start();
}
$count = 0;
$retries = $this->flushRetries;
while ($retries--) {
try {
while ($message = array_pop($this->messages)) {
$count += $transport->send($message, $failedRecipients);
}
} catch (Swift_TransportException $exception) {
if ($retries) {
// re-queue the message at the end of the queue to give a chance
// to the other messages to be sent, in case the failure was due to
// this message and not just the transport failing
array_unshift($this->messages, $message);
// wait half a second before we try again
usleep(500000);
} else {
throw $exception;
}
}
}
return $count;
}
}

View File

@@ -1,291 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* The Message class for building emails.
*
* @author Chris Corbyn
*/
class Swift_Message extends Swift_Mime_SimpleMessage
{
/**
* @var Swift_Signers_HeaderSigner[]
*/
private $headerSigners = array();
/**
* @var Swift_Signers_BodySigner[]
*/
private $bodySigners = array();
/**
* @var array
*/
private $savedMessage = array();
/**
* Create a new Message.
*
* Details may be optionally passed into the constructor.
*
* @param string $subject
* @param string $body
* @param string $contentType
* @param string $charset
*/
public function __construct($subject = null, $body = null, $contentType = null, $charset = null)
{
call_user_func_array(
array($this, 'Swift_Mime_SimpleMessage::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.message')
);
if (!isset($charset)) {
$charset = Swift_DependencyContainer::getInstance()
->lookup('properties.charset');
}
$this->setSubject($subject);
$this->setBody($body);
$this->setCharset($charset);
if ($contentType) {
$this->setContentType($contentType);
}
}
/**
* Create a new Message.
*
* @param string $subject
* @param string $body
* @param string $contentType
* @param string $charset
*
* @return Swift_Message
*/
public static function newInstance($subject = null, $body = null, $contentType = null, $charset = null)
{
return new self($subject, $body, $contentType, $charset);
}
/**
* Add a MimePart to this Message.
*
* @param string|Swift_OutputByteStream $body
* @param string $contentType
* @param string $charset
*
* @return Swift_Mime_SimpleMessage
*/
public function addPart($body, $contentType = null, $charset = null)
{
return $this->attach(Swift_MimePart::newInstance(
$body, $contentType, $charset
));
}
/**
* Detach a signature handler from a message.
*
* @param Swift_Signer $signer
*
* @return Swift_Message
*/
public function attachSigner(Swift_Signer $signer)
{
if ($signer instanceof Swift_Signers_HeaderSigner) {
$this->headerSigners[] = $signer;
} elseif ($signer instanceof Swift_Signers_BodySigner) {
$this->bodySigners[] = $signer;
}
return $this;
}
/**
* Attach a new signature handler to the message.
*
* @param Swift_Signer $signer
*
* @return Swift_Message
*/
public function detachSigner(Swift_Signer $signer)
{
if ($signer instanceof Swift_Signers_HeaderSigner) {
foreach ($this->headerSigners as $k => $headerSigner) {
if ($headerSigner === $signer) {
unset($this->headerSigners[$k]);
return $this;
}
}
} elseif ($signer instanceof Swift_Signers_BodySigner) {
foreach ($this->bodySigners as $k => $bodySigner) {
if ($bodySigner === $signer) {
unset($this->bodySigners[$k]);
return $this;
}
}
}
return $this;
}
/**
* Get this message as a complete string.
*
* @return string
*/
public function toString()
{
if (empty($this->headerSigners) && empty($this->bodySigners)) {
return parent::toString();
}
$this->saveMessage();
$this->doSign();
$string = parent::toString();
$this->restoreMessage();
return $string;
}
/**
* Write this message to a {@link Swift_InputByteStream}.
*
* @param Swift_InputByteStream $is
*/
public function toByteStream(Swift_InputByteStream $is)
{
if (empty($this->headerSigners) && empty($this->bodySigners)) {
parent::toByteStream($is);
return;
}
$this->saveMessage();
$this->doSign();
parent::toByteStream($is);
$this->restoreMessage();
}
public function __wakeup()
{
Swift_DependencyContainer::getInstance()->createDependenciesFor('mime.message');
}
/**
* loops through signers and apply the signatures.
*/
protected function doSign()
{
foreach ($this->bodySigners as $signer) {
$altered = $signer->getAlteredHeaders();
$this->saveHeaders($altered);
$signer->signMessage($this);
}
foreach ($this->headerSigners as $signer) {
$altered = $signer->getAlteredHeaders();
$this->saveHeaders($altered);
$signer->reset();
$signer->setHeaders($this->getHeaders());
$signer->startBody();
$this->_bodyToByteStream($signer);
$signer->endBody();
$signer->addSignature($this->getHeaders());
}
}
/**
* save the message before any signature is applied.
*/
protected function saveMessage()
{
$this->savedMessage = array('headers' => array());
$this->savedMessage['body'] = $this->getBody();
$this->savedMessage['children'] = $this->getChildren();
if (count($this->savedMessage['children']) > 0 && $this->getBody() != '') {
$this->setChildren(array_merge(array($this->_becomeMimePart()), $this->savedMessage['children']));
$this->setBody('');
}
}
/**
* save the original headers.
*
* @param array $altered
*/
protected function saveHeaders(array $altered)
{
foreach ($altered as $head) {
$lc = strtolower($head);
if (!isset($this->savedMessage['headers'][$lc])) {
$this->savedMessage['headers'][$lc] = $this->getHeaders()->getAll($head);
}
}
}
/**
* Remove or restore altered headers.
*/
protected function restoreHeaders()
{
foreach ($this->savedMessage['headers'] as $name => $savedValue) {
$headers = $this->getHeaders()->getAll($name);
foreach ($headers as $key => $value) {
if (!isset($savedValue[$key])) {
$this->getHeaders()->remove($name, $key);
}
}
}
}
/**
* Restore message body.
*/
protected function restoreMessage()
{
$this->setBody($this->savedMessage['body']);
$this->setChildren($this->savedMessage['children']);
$this->restoreHeaders();
$this->savedMessage = array();
}
/**
* Clone Message Signers.
*
* @see Swift_Mime_SimpleMimeEntity::__clone()
*/
public function __clone()
{
parent::__clone();
foreach ($this->bodySigners as $key => $bodySigner) {
$this->bodySigners[$key] = clone($bodySigner);
}
foreach ($this->headerSigners as $key => $headerSigner) {
$this->headerSigners[$key] = clone($headerSigner);
}
}
}

View File

@@ -1,149 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An attachment, in a multipart message.
*
* @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 Swift_Mime_Grammar $grammar
* @param array $mimeTypes optional
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $mimeTypes = array())
{
parent::__construct($headers, $encoder, $cache, $grammar);
$this->setDisposition('attachment');
$this->setContentType('application/octet-stream');
$this->_mimeTypes = $mimeTypes;
}
/**
* Get the nesting level used for this attachment.
*
* Always returns {@link LEVEL_MIXED}.
*
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_MIXED;
}
/**
* Get the Content-Disposition of this attachment.
*
* By default attachments have a disposition of "attachment".
*
* @return string
*/
public function getDisposition()
{
return $this->_getHeaderFieldModel('Content-Disposition');
}
/**
* Set the Content-Disposition of this attachment.
*
* @param string $disposition
*
* @return Swift_Mime_Attachment
*/
public function setDisposition($disposition)
{
if (!$this->_setHeaderFieldModel('Content-Disposition', $disposition)) {
$this->getHeaders()->addParameterizedHeader('Content-Disposition', $disposition);
}
return $this;
}
/**
* Get the filename of this attachment when downloaded.
*
* @return string
*/
public function getFilename()
{
return $this->_getHeaderParameter('Content-Disposition', 'filename');
}
/**
* Set the filename of this attachment.
*
* @param string $filename
*
* @return Swift_Mime_Attachment
*/
public function setFilename($filename)
{
$this->_setHeaderParameter('Content-Disposition', 'filename', $filename);
$this->_setHeaderParameter('Content-Type', 'name', $filename);
return $this;
}
/**
* Get the file size of this attachment.
*
* @return int
*/
public function getSize()
{
return $this->_getHeaderParameter('Content-Disposition', 'size');
}
/**
* Set the file size of this attachment.
*
* @param int $size
*
* @return Swift_Mime_Attachment
*/
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
*
* @return Swift_Mime_Attachment
*/
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

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

View File

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

View File

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

View File

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

View File

@@ -1,162 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles binary/7/8-bit Transfer Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_PlainContentEncoder implements Swift_Mime_ContentEncoder
{
/**
* The name of this encoding scheme (probably 7bit or 8bit).
*
* @var string
*/
private $_name;
/**
* True if canonical transformations should be done.
*
* @var bool
*/
private $_canonical;
/**
* Creates a new PlainContentEncoder with $name (probably 7bit or 8bit).
*
* @param string $name
* @param bool $canonical If canonicalization transformation should be done.
*/
public function __construct($name, $canonical = false)
{
$this->_name = $name;
$this->_canonical = $canonical;
}
/**
* Encode a given string to produce an encoded string.
*
* @param string $string
* @param int $firstLineOffset ignored
* @param int $maxLineLength - 0 means no wrapping will occur
*
* @return string
*/
public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
{
if ($this->_canonical) {
$string = $this->_canonicalize($string);
}
return $this->_safeWordWrap($string, $maxLineLength, "\r\n");
}
/**
* Encode stream $in to stream $out.
*
* @param Swift_OutputByteStream $os
* @param Swift_InputByteStream $is
* @param int $firstLineOffset ignored
* @param int $maxLineLength optional, 0 means no wrapping will occur
*/
public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0)
{
$leftOver = '';
while (false !== $bytes = $os->read(8192)) {
$toencode = $leftOver.$bytes;
if ($this->_canonical) {
$toencode = $this->_canonicalize($toencode);
}
$wrapped = $this->_safeWordWrap($toencode, $maxLineLength, "\r\n");
$lastLinePos = strrpos($wrapped, "\r\n");
$leftOver = substr($wrapped, $lastLinePos);
$wrapped = substr($wrapped, 0, $lastLinePos);
$is->write($wrapped);
}
if (strlen($leftOver)) {
$is->write($leftOver);
}
}
/**
* Get the name of this encoding scheme.
*
* @return string
*/
public function getName()
{
return $this->_name;
}
/**
* Not used.
*/
public function charsetChanged($charset)
{
}
/**
* A safer (but weaker) wordwrap for unicode.
*
* @param string $string
* @param int $length
* @param string $le
*
* @return string
*/
private function _safeWordwrap($string, $length = 75, $le = "\r\n")
{
if (0 >= $length) {
return $string;
}
$originalLines = explode($le, $string);
$lines = 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
*/
private function _canonicalize($string)
{
return str_replace(
array("\r\n", "\r", "\n"),
array("\n", "\n", "\r\n"),
$string
);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,78 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Creates MIME headers.
*
* @author Chris Corbyn
*/
interface Swift_Mime_HeaderFactory extends Swift_Mime_CharsetObserver
{
/**
* Create a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string $addresses
*
* @return Swift_Mime_Header
*/
public function createMailboxHeader($name, $addresses = null);
/**
* Create a new Date header using $timestamp (UNIX time).
*
* @param string $name
* @param int $timestamp
*
* @return Swift_Mime_Header
*/
public function createDateHeader($name, $timestamp = null);
/**
* Create a new basic text header with $name and $value.
*
* @param string $name
* @param string $value
*
* @return Swift_Mime_Header
*/
public function createTextHeader($name, $value = null);
/**
* Create a new ParameterizedHeader with $name, $value and $params.
*
* @param string $name
* @param string $value
* @param array $params
*
* @return Swift_Mime_ParameterizedHeader
*/
public function createParameterizedHeader($name, $value = null, $params = array());
/**
* Create a new ID header for Message-ID or Content-ID.
*
* @param string $name
* @param string|array $ids
*
* @return Swift_Mime_Header
*/
public function createIdHeader($name, $ids = null);
/**
* Create a new Path header with an address (path) in it.
*
* @param string $name
* @param string $path
*
* @return Swift_Mime_Header
*/
public function createPathHeader($name, $path = null);
}

View File

@@ -1,169 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A collection of MIME headers.
*
* @author Chris Corbyn
*/
interface Swift_Mime_HeaderSet extends Swift_Mime_CharsetObserver
{
/**
* Add a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string $addresses
*/
public function addMailboxHeader($name, $addresses = null);
/**
* Add a new Date header using $timestamp (UNIX time).
*
* @param string $name
* @param int $timestamp
*/
public function addDateHeader($name, $timestamp = null);
/**
* Add a new basic text header with $name and $value.
*
* @param string $name
* @param string $value
*/
public function addTextHeader($name, $value = null);
/**
* Add a new ParameterizedHeader with $name, $value and $params.
*
* @param string $name
* @param string $value
* @param array $params
*/
public function addParameterizedHeader($name, $value = null, $params = array());
/**
* Add a new ID header for Message-ID or Content-ID.
*
* @param string $name
* @param string|array $ids
*/
public function addIdHeader($name, $ids = null);
/**
* Add a new Path header with an address (path) in it.
*
* @param string $name
* @param string $path
*/
public function addPathHeader($name, $path = null);
/**
* Returns true if at least one header with the given $name exists.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*
* @return bool
*/
public function has($name, $index = 0);
/**
* Set a header in the HeaderSet.
*
* The header may be a previously fetched header via {@link get()} or it may
* be one that has been created separately.
*
* If $index is specified, the header will be inserted into the set at this
* offset.
*
* @param Swift_Mime_Header $header
* @param int $index
*/
public function set(Swift_Mime_Header $header, $index = 0);
/**
* Get the header with the given $name.
* If multiple headers match, the actual one may be specified by $index.
* Returns NULL if none present.
*
* @param string $name
* @param int $index
*
* @return Swift_Mime_Header
*/
public function get($name, $index = 0);
/**
* Get all headers with the given $name.
*
* @param string $name
*
* @return array
*/
public function getAll($name = null);
/**
* Return the name of all Headers.
*
* @return array
*/
public function listAll();
/**
* Remove the header with the given $name if it's set.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*/
public function remove($name, $index = 0);
/**
* Remove all headers with the given $name.
*
* @param string $name
*/
public function removeAll($name);
/**
* Create a new instance of this HeaderSet.
*
* @return Swift_Mime_HeaderSet
*/
public function newInstance();
/**
* Define a list of Header names as an array in the correct order.
*
* These Headers will be output in the given order where present.
*
* @param array $sequence
*/
public function defineOrdering(array $sequence);
/**
* Set a list of header names which must always be displayed when set.
*
* Usually headers without a field value won't be output unless set here.
*
* @param array $names
*/
public function setAlwaysDisplayed(array $names);
/**
* Returns a string with a representation of all headers.
*
* @return string
*/
public function toString();
}

View File

@@ -1,503 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An abstract base MIME Header.
*
* @author Chris Corbyn
*/
abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
{
/**
* The name of this Header.
*
* @var string
*/
private $_name;
/**
* The Grammar used for this Header.
*
* @var Swift_Mime_Grammar
*/
private $_grammar;
/**
* The Encoder used to encode this Header.
*
* @var Swift_Encoder
*/
private $_encoder;
/**
* The maximum length of a line in the header.
*
* @var int
*/
private $_lineLength = 78;
/**
* The language used in this Header.
*
* @var string
*/
private $_lang;
/**
* The character set of the text in this Header.
*
* @var string
*/
private $_charset = 'utf-8';
/**
* The value of this Header, cached.
*
* @var string
*/
private $_cachedValue = null;
/**
* Creates a new Header.
*
* @param Swift_Mime_Grammar $grammar
*/
public function __construct(Swift_Mime_Grammar $grammar)
{
$this->setGrammar($grammar);
}
/**
* 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;
}
/**
* Set the grammar used for the header.
*
* @param Swift_Mime_Grammar $grammar
*/
public function setGrammar(Swift_Mime_Grammar $grammar)
{
$this->_grammar = $grammar;
$this->setCachedValue(null);
}
/**
* Get the grammar used for this Header.
*
* @return Swift_Mime_Grammar
*/
public function getGrammar()
{
return $this->_grammar;
}
/**
* 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.
*
* @throws Swift_RfcComplianceException
*
* @return string
*/
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
*/
protected function setFieldName($name)
{
$this->_name = $name;
}
/**
* 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 bool $shorten the first line to make remove for header name
*
* @return string
*/
protected function createPhrase(Swift_Mime_Header $header, $string, $charset, Swift_Mime_HeaderEncoder $encoder = null, $shorten = false)
{
// Treat token as exactly what was given
$phraseStr = $string;
// If it's not valid
if (!preg_match('/^'.$this->getGrammar()->getDefinition('phrase').'$/D', $phraseStr)) {
// .. but it is just ascii text, try escaping some characters
// and make it a quoted-string
if (preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $phraseStr)) {
$phraseStr = $this->getGrammar()->escapeSpecials(
$phraseStr, array('"'), $this->getGrammar()->getSpecials()
);
$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 Swift_Mime_Header $header
* @param string $input
* @param string $usedLength optional
*
* @return string
*/
protected function encodeWords(Swift_Mime_Header $header, $input, $usedLength = -1)
{
$value = '';
$tokens = $this->getEncodableWordTokens($input);
foreach ($tokens as $token) {
// See RFC 2822, Sect 2.2 (really 2.2 ??)
if ($this->tokenNeedsEncoding($token)) {
// Don't encode starting WSP
$firstChar = substr($token, 0, 1);
switch ($firstChar) {
case ' ':
case "\t":
$value .= $firstChar;
$token = substr($token, 1);
}
if (-1 == $usedLength) {
$usedLength = strlen($header->getFieldName().': ') + strlen($value);
}
$value .= $this->getTokenAsEncodedWord($token, $usedLength);
$header->setMaxLineLength(76); // Forcefully override
} else {
$value .= $token;
}
}
return $value;
}
/**
* Test if a token needs to be encoded or not.
*
* @param string $token
*
* @return bool
*/
protected function tokenNeedsEncoding($token)
{
return preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token);
}
/**
* Splits a string into tokens in blocks of words which can be encoded quickly.
*
* @param string $string
*
* @return string[]
*/
protected function getEncodableWordTokens($string)
{
$tokens = 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 token to encode
* @param int $firstLineOffset optional
*
* @return string
*/
protected function getTokenAsEncodedWord($token, $firstLineOffset = 0)
{
// Adjust $firstLineOffset to account for space needed for syntax
$charsetDecl = $this->_charset;
if (isset($this->_lang)) {
$charsetDecl .= '*'.$this->_lang;
}
$encodingWrapperLength = strlen(
'=?'.$charsetDecl.'?'.$this->_encoder->getName().'??='
);
if ($firstLineOffset >= 75) {
//Does this logic need to be here?
$firstLineOffset = 0;
}
$encodedTextLines = explode("\r\n",
$this->_encoder->encodeString(
$token, $firstLineOffset, 75 - $encodingWrapperLength, $this->_charset
)
);
if (strtolower($this->_charset) !== 'iso-2022-jp') {
// special encoding for iso-2022-jp using mb_encode_mimeheader
foreach ($encodedTextLines as $lineNum => $line) {
$encodedTextLines[$lineNum] = '=?'.$charsetDecl.
'?'.$this->_encoder->getName().
'?'.$line.'?=';
}
}
return implode("\r\n ", $encodedTextLines);
}
/**
* Generates tokens from the given string which include CRLF as individual tokens.
*
* @param string $token
*
* @return string[]
*/
protected function generateTokenLines($token)
{
return preg_split('~(\r\n)~', $token, -1, PREG_SPLIT_DELIM_CAPTURE);
}
/**
* Set a value into the cache.
*
* @param string $value
*/
protected function setCachedValue($value)
{
$this->_cachedValue = $value;
}
/**
* Get the value in the cache.
*
* @return string
*/
protected function getCachedValue()
{
return $this->_cachedValue;
}
/**
* Clear the cached value if $condition is met.
*
* @param bool $condition
*/
protected function clearCachedValueIf($condition)
{
if ($condition) {
$this->setCachedValue(null);
}
}
/**
* Generate a list of all tokens in the final header.
*
* @param string $string The string to tokenize
*
* @return array An array of tokens as strings
*/
protected function toTokens($string = null)
{
if (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) {
$newTokens = $this->generateTokenLines($token);
foreach ($newTokens as $newToken) {
$tokens[] = $newToken;
}
}
return $tokens;
}
/**
* Takes an array of tokens which appear in the header and turns them into
* an RFC 2822 compliant string, adding FWSP where needed.
*
* @param string[] $tokens
*
* @return string
*/
private function _tokensToString(array $tokens)
{
$lineCount = 0;
$headerLines = 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

@@ -1,125 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A Date MIME Header for Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_DateHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The UNIX timestamp value of this Header.
*
* @var int
*/
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
* @param Swift_Mime_Grammar $grammar
*/
public function __construct($name, Swift_Mime_Grammar $grammar)
{
$this->setFieldName($name);
parent::__construct($grammar);
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_DATE;
}
/**
* Set the model for the field body.
*
* 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).
*
* @see toString()
*
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
if (isset($this->_timestamp)) {
$this->setCachedValue(date('r', $this->_timestamp));
}
}
return $this->getCachedValue();
}
}

View File

@@ -1,180 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An ID MIME Header for something like Message-ID or Content-ID.
*
* @author Chris Corbyn
*/
class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_AbstractHeader
{
/**
* The IDs used in the value of this Header.
*
* This may hold multiple IDs or just a single ID.
*
* @var string[]
*/
private $_ids = array();
/**
* Creates a new IdentificationHeader with the given $name and $id.
*
* @param string $name
* @param Swift_Mime_Grammar $grammar
*/
public function __construct($name, Swift_Mime_Grammar $grammar)
{
$this->setFieldName($name);
parent::__construct($grammar);
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_ID;
}
/**
* Set the model for the field body.
*
* This method takes a string ID, or an array of IDs.
*
* @param mixed $model
*
* @throws Swift_RfcComplianceException
*/
public function setFieldBodyModel($model)
{
$this->setId($model);
}
/**
* Get the model for the field body.
*
* This method returns an array of IDs
*
* @return array
*/
public function getFieldBodyModel()
{
return $this->getIds();
}
/**
* Set the ID used in the value of this header.
*
* @param string|array $id
*
* @throws Swift_RfcComplianceException
*/
public function setId($id)
{
$this->setIds(is_array($id) ? $id : 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 $id) {
$this->_assertValidId($id);
$actualIds[] = $id;
}
$this->clearCachedValueIf($this->_ids != $actualIds);
$this->_ids = $actualIds;
}
/**
* Get the list of IDs used in this Header.
*
* @return string[]
*/
public function getIds()
{
return $this->_ids;
}
/**
* Get the string value of the body in this Header.
*
* This is not necessarily RFC 2822 compliant since folding white space will
* not be added at this stage (see {@see toString()} for that).
*
* @see toString()
*
* @throws Swift_RfcComplianceException
*
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
$angleAddrs = array();
foreach ($this->_ids as $id) {
$angleAddrs[] = '<'.$id.'>';
}
$this->setCachedValue(implode(' ', $angleAddrs));
}
return $this->getCachedValue();
}
/**
* Throws an Exception if the id passed does not comply with RFC 2822.
*
* @param string $id
*
* @throws Swift_RfcComplianceException
*/
private function _assertValidId($id)
{
if (!preg_match(
'/^'.$this->getGrammar()->getDefinition('id-left').'@'.
$this->getGrammar()->getDefinition('id-right').'$/D',
$id
)) {
throw new Swift_RfcComplianceException(
'Invalid ID given <'.$id.'>'
);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,117 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A MIME entity, such as an attachment.
*
* @author Chris Corbyn
*/
interface Swift_Mime_MimeEntity extends Swift_Mime_CharsetObserver, Swift_Mime_EncodingObserver
{
/** Main message document; there can only be one of these */
const LEVEL_TOP = 16;
/** An entity which nests with the same precedence as an attachment */
const LEVEL_MIXED = 256;
/** An entity which nests with the same precedence as a mime part */
const LEVEL_ALTERNATIVE = 4096;
/** An entity which nests with the same precedence as embedded content */
const LEVEL_RELATED = 65536;
/**
* Get the level at which this entity shall be nested in final document.
*
* The lower the value, the more outermost the entity will be nested.
*
* @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE
*
* @return int
*/
public function getNestingLevel();
/**
* Get the qualified content-type of this mime entity.
*
* @return string
*/
public function getContentType();
/**
* Returns a unique ID for this entity.
*
* For most entities this will likely be the Content-ID, though it has
* no explicit semantic meaning and can be considered an identifier for
* programming logic purposes.
*
* If a Content-ID header is present, this value SHOULD match the value of
* the header.
*
* @return string
*/
public function getId();
/**
* Get all children nested inside this entity.
*
* These are not just the immediate children, but all children.
*
* @return Swift_Mime_MimeEntity[]
*/
public function getChildren();
/**
* Set all children nested inside this entity.
*
* This includes grandchildren.
*
* @param Swift_Mime_MimeEntity[] $children
*/
public function setChildren(array $children);
/**
* Get the collection of Headers in this Mime entity.
*
* @return Swift_Mime_HeaderSet
*/
public function getHeaders();
/**
* Get the body content of this entity as a string.
*
* Returns NULL if no body has been set.
*
* @return string|null
*/
public function getBody();
/**
* Set the body content of this entity as a string.
*
* @param string $body
* @param string $contentType optional
*/
public function setBody($body, $contentType = null);
/**
* Get this entire entity in its string form.
*
* @return string
*/
public function toString();
/**
* Get this entire entity as a ByteStream.
*
* @param Swift_InputByteStream $is to write to
*/
public function toByteStream(Swift_InputByteStream $is);
}

View File

@@ -1,212 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A MIME part, in a multipart message.
*
* @author Chris Corbyn
*/
class Swift_Mime_MimePart extends Swift_Mime_SimpleMimeEntity
{
/** The format parameter last specified by the user */
protected $_userFormat;
/** The charset last specified by the user */
protected $_userCharset;
/** The delsp parameter last specified by the user */
protected $_userDelSp;
/** The nesting level of this MimePart */
private $_nestingLevel = self::LEVEL_ALTERNATIVE;
/**
* Create a new MimePart with $headers, $encoder and $cache.
*
* @param Swift_Mime_HeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_Mime_Grammar $grammar
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $charset = null)
{
parent::__construct($headers, $encoder, $cache, $grammar);
$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
*
* @return Swift_Mime_MimePart
*/
public function setBody($body, $contentType = null, $charset = null)
{
if (isset($charset)) {
$this->setCharset($charset);
}
$body = $this->_convertString($body);
parent::setBody($body, $contentType);
return $this;
}
/**
* Get the character set of this entity.
*
* @return string
*/
public function getCharset()
{
return $this->_getHeaderParameter('Content-Type', 'charset');
}
/**
* Set the character set of this entity.
*
* @param string $charset
*
* @return Swift_Mime_MimePart
*/
public function setCharset($charset)
{
$this->_setHeaderParameter('Content-Type', 'charset', $charset);
if ($charset !== $this->_userCharset) {
$this->_clearCache();
}
$this->_userCharset = $charset;
parent::charsetChanged($charset);
return $this;
}
/**
* Get the format of this entity (i.e. flowed or fixed).
*
* @return string
*/
public function getFormat()
{
return $this->_getHeaderParameter('Content-Type', 'format');
}
/**
* Set the format of this entity (flowed or fixed).
*
* @param string $format
*
* @return Swift_Mime_MimePart
*/
public function setFormat($format)
{
$this->_setHeaderParameter('Content-Type', 'format', $format);
$this->_userFormat = $format;
return $this;
}
/**
* Test if delsp is being used for this entity.
*
* @return bool
*/
public function getDelSp()
{
return 'yes' == $this->_getHeaderParameter('Content-Type', 'delsp') ? true : false;
}
/**
* Turn delsp on or off for this entity.
*
* @param bool $delsp
*
* @return Swift_Mime_MimePart
*/
public function setDelSp($delsp = true)
{
$this->_setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null);
$this->_userDelSp = $delsp;
return $this;
}
/**
* Get the nesting level of this entity.
*
* @see LEVEL_TOP, LEVEL_ALTERNATIVE, LEVEL_MIXED, LEVEL_RELATED
*
* @return int
*/
public function getNestingLevel()
{
return $this->_nestingLevel;
}
/**
* Receive notification that the charset has changed on this document, or a
* parent document.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->setCharset($charset);
}
/** Fix the content-type and encoding of this entity */
protected function _fixHeaders()
{
parent::_fixHeaders();
if (count($this->getChildren())) {
$this->_setHeaderParameter('Content-Type', 'charset', null);
$this->_setHeaderParameter('Content-Type', 'format', null);
$this->_setHeaderParameter('Content-Type', 'delsp', null);
} else {
$this->setCharset($this->_userCharset);
$this->setFormat($this->_userFormat);
$this->setDelSp($this->_userDelSp);
}
}
/** Set the nesting level of this entity */
protected function _setNestingLevel($level)
{
$this->_nestingLevel = $level;
}
/** Encode charset when charset is not utf-8 */
protected function _convertString($string)
{
$charset = strtolower($this->getCharset());
if (!in_array($charset, array('utf-8', 'iso-8859-1', 'iso-8859-15', ''))) {
// mb_convert_encoding must be the first one to check, since iconv cannot convert some words.
if (function_exists('mb_convert_encoding')) {
$string = mb_convert_encoding($string, $charset, 'utf-8');
} elseif (function_exists('iconv')) {
$string = iconv('utf-8//TRANSLIT//IGNORE', $charset, $string);
} else {
throw new Swift_SwiftException('No suitable convert encoding function (use UTF-8 as your charset or install the mbstring or iconv extension).');
}
return $string;
}
return $string;
}
}

View File

@@ -1,34 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A MIME Header with parameters.
*
* @author Chris Corbyn
*/
interface Swift_Mime_ParameterizedHeader extends Swift_Mime_Header
{
/**
* Set the value of $parameter.
*
* @param string $parameter
* @param string $value
*/
public function setParameter($parameter, $value);
/**
* Get the value of $parameter.
*
* @param string $parameter
*
* @return string
*/
public function getParameter($parameter);
}

View File

@@ -1,193 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Creates MIME headers.
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleHeaderFactory implements Swift_Mime_HeaderFactory
{
/** The HeaderEncoder used by these headers */
private $_encoder;
/** The Encoder used by parameters */
private $_paramEncoder;
/** The Grammar */
private $_grammar;
/** 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 Swift_Mime_Grammar $grammar
* @param string|null $charset
*/
public function __construct(Swift_Mime_HeaderEncoder $encoder, Swift_Encoder $paramEncoder, Swift_Mime_Grammar $grammar, $charset = null)
{
$this->_encoder = $encoder;
$this->_paramEncoder = $paramEncoder;
$this->_grammar = $grammar;
$this->_charset = $charset;
}
/**
* Create a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string|null $addresses
*
* @return Swift_Mime_Header
*/
public function createMailboxHeader($name, $addresses = null)
{
$header = new Swift_Mime_Headers_MailboxHeader($name, $this->_encoder, $this->_grammar);
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|null $timestamp
*
* @return Swift_Mime_Header
*/
public function createDateHeader($name, $timestamp = null)
{
$header = new Swift_Mime_Headers_DateHeader($name, $this->_grammar);
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, $this->_grammar);
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, $this->_grammar);
if (isset($value)) {
$header->setFieldBodyModel($value);
}
foreach ($params as $k => $v) {
$header->setParameter($k, $v);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new ID header for Message-ID or Content-ID.
*
* @param string $name
* @param string|array $ids
*
* @return Swift_Mime_Header
*/
public function createIdHeader($name, $ids = null)
{
$header = new Swift_Mime_Headers_IdentificationHeader($name, $this->_grammar);
if (isset($ids)) {
$header->setFieldBodyModel($ids);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Create a new Path header with an address (path) in it.
*
* @param string $name
* @param string $path
*
* @return Swift_Mime_Header
*/
public function createPathHeader($name, $path = null)
{
$header = new Swift_Mime_Headers_PathHeader($name, $this->_grammar);
if (isset($path)) {
$header->setFieldBodyModel($path);
}
$this->_setHeaderCharset($header);
return $header;
}
/**
* Notify this observer that the entity's charset has changed.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->_charset = $charset;
$this->_encoder->charsetChanged($charset);
$this->_paramEncoder->charsetChanged($charset);
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->_encoder = clone $this->_encoder;
$this->_paramEncoder = clone $this->_paramEncoder;
}
/** Apply the charset to the Header */
private function _setHeaderCharset(Swift_Mime_Header $header)
{
if (isset($this->_charset)) {
$header->setCharset($this->_charset);
}
}
}

View File

@@ -1,414 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A collection of MIME headers.
*
* @author Chris Corbyn
*/
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 bool
*/
public function has($name, $index = 0)
{
$lowerName = strtolower($name);
if (!array_key_exists($lowerName, $this->_headers)) {
return false;
}
if (func_num_args() < 2) {
// index was not specified, so we only need to check that there is at least one header value set
return (bool) count($this->_headers[$lowerName]);
}
return array_key_exists($index, $this->_headers[$lowerName]);
}
/**
* Set a header in the HeaderSet.
*
* The header may be a previously fetched header via {@link get()} or it may
* be one that has been created separately.
*
* If $index is specified, the header will be inserted into the set at this
* offset.
*
* @param 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)
{
$name = strtolower($name);
if (func_num_args() < 2) {
if ($this->has($name)) {
$values = array_values($this->_headers[$name]);
return array_shift($values);
}
} else {
if ($this->has($name, $index)) {
return $this->_headers[$name][$index];
}
}
}
/**
* Get all headers with the given $name.
*
* @param string $name
*
* @return array
*/
public function getAll($name = null)
{
if (!isset($name)) {
$headers = 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];
}
/**
* Return the name of all Headers.
*
* @return array
*/
public function listAll()
{
$headers = $this->_headers;
if ($this->_canSort()) {
uksort($headers, array($this, '_sortHeaders'));
}
return array_keys($headers);
}
/**
* Remove the header with the given $name if it's set.
*
* If multiple headers match, the actual one may be specified by $index.
*
* @param string $name
* @param int $index
*/
public function remove($name, $index = 0)
{
$lowerName = strtolower($name);
unset($this->_headers[$lowerName][$index]);
}
/**
* Remove all headers with the given $name.
*
* @param string $name
*/
public function removeAll($name)
{
$lowerName = strtolower($name);
unset($this->_headers[$lowerName]);
}
/**
* 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();
}
/** 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 (-1 === $aPos && -1 === $bPos) {
// just be sure to be determinist here
return $a > $b ? -1 : 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);
}
}
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->_factory = clone $this->_factory;
foreach ($this->_headers as $groupKey => $headerGroup) {
foreach ($headerGroup as $key => $header) {
$this->_headers[$groupKey][$key] = clone $header;
}
}
}
}

View File

@@ -1,649 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* The default email message class.
*
* @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 Swift_Mime_Grammar $grammar
* @param string $charset
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar, $charset = null)
{
parent::__construct($headers, $encoder, $cache, $grammar, $charset);
$this->getHeaders()->defineOrdering(array(
'Return-Path',
'Received',
'DKIM-Signature',
'DomainKey-Signature',
'Sender',
'Message-ID',
'Date',
'Subject',
'From',
'Reply-To',
'To',
'Cc',
'Bcc',
'MIME-Version',
'Content-Type',
'Content-Transfer-Encoding',
));
$this->getHeaders()->setAlwaysDisplayed(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
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
public function setReturnPath($address)
{
if (!$this->_setHeaderFieldModel('Return-Path', $address)) {
$this->getHeaders()->addPathHeader('Return-Path', $address);
}
return $this;
}
/**
* Get the return-path (bounce address) of this message.
*
* @return string
*/
public function getReturnPath()
{
return $this->_getHeaderFieldModel('Return-Path');
}
/**
* Set the sender of this message.
*
* This does not override the From field, but it has a higher significance.
*
* @param string $address
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
public function addFrom($address, $name = null)
{
$current = $this->getFrom();
$current[$address] = $name;
return $this->setFrom($current);
}
/**
* Set the from address of this message.
*
* You may pass an array of addresses if this message is from multiple people.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param string|array $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
*/
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 mixed
*/
public function getFrom()
{
return $this->_getHeaderFieldModel('From');
}
/**
* Add a Reply-To: address to this message.
*
* If $name is passed this name will be associated with the address.
*
* @param string $address
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
*/
public function addReplyTo($address, $name = null)
{
$current = $this->getReplyTo();
$current[$address] = $name;
return $this->setReplyTo($current);
}
/**
* Set the reply-to address of this message.
*
* You may pass an array of addresses if replies will go to multiple people.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
public function addTo($address, $name = null)
{
$current = $this->getTo();
$current[$address] = $name;
return $this->setTo($current);
}
/**
* Set the to addresses of this message.
*
* If multiple recipients will receive the message an array should be used.
* Example: array('receiver@domain.org', 'other@domain.org' => 'A name')
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
public function addCc($address, $name = null)
{
$current = $this->getCc();
$current[$address] = $name;
return $this->setCc($current);
}
/**
* Set the Cc addresses of this message.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
public function addBcc($address, $name = null)
{
$current = $this->getBcc();
$current[$address] = $name;
return $this->setBcc($current);
}
/**
* Set the Bcc addresses of this message.
*
* If $name is passed and the first parameter is a string, this name will be
* associated with the address.
*
* @param mixed $addresses
* @param string $name optional
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
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
*
* @return Swift_Mime_SimpleMessage
*/
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.
*
* @see toString()
*
* @return string
*/
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);
}
}
/** @see Swift_Mime_SimpleMimeEntity::_getIdField() */
protected function _getIdField()
{
return 'Message-ID';
}
/** Turn the body of this message into a child of itself if needed */
protected function _becomeMimePart()
{
$part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(),
$this->_getCache(), $this->_getGrammar(), $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

@@ -1,843 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A MIME entity, in a multipart message.
*
* @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;
/** The grammar to use for id validation */
private $_grammar;
/** A mime boundary, 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
* @param Swift_Mime_Grammar $grammar
*/
public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar)
{
$this->_cacheKey = md5(uniqid(getmypid().mt_rand(), true));
$this->_cache = $cache;
$this->_headers = $headers;
$this->_grammar = $grammar;
$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.
*
* @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE
*
* @return int
*/
public function getNestingLevel()
{
return $this->_nestingLevel;
}
/**
* Get the Content-type of this entity.
*
* @return string
*/
public function getContentType()
{
return $this->_getHeaderFieldModel('Content-Type');
}
/**
* Set the Content-type of this entity.
*
* @param string $type
*
* @return Swift_Mime_SimpleMimeEntity
*/
public function setContentType($type)
{
$this->_setContentTypeInHeaders($type);
// Keep track of the value so that if the content-type changes automatically
// due to added child entities, it can be restored if they are later removed
$this->_userContentType = $type;
return $this;
}
/**
* Get the CID of this entity.
*
* The CID will only be present in headers if a Content-ID header is present.
*
* @return string
*/
public function getId()
{
$tmp = (array) $this->_getHeaderFieldModel($this->_getIdField());
return $this->_headers->has($this->_getIdField()) ? current($tmp) : $this->_id;
}
/**
* Set the CID of this entity.
*
* @param string $id
*
* @return Swift_Mime_SimpleMimeEntity
*/
public function setId($id)
{
if (!$this->_setHeaderFieldModel($this->_getIdField(), $id)) {
$this->_headers->addIdHeader($this->_getIdField(), $id);
}
$this->_id = $id;
return $this;
}
/**
* Get the description of this entity.
*
* This value comes from the Content-Description header if set.
*
* @return string
*/
public function getDescription()
{
return $this->_getHeaderFieldModel('Content-Description');
}
/**
* Set the description of this entity.
*
* This method sets a value in the Content-ID header.
*
* @param string $description
*
* @return Swift_Mime_SimpleMimeEntity
*/
public function setDescription($description)
{
if (!$this->_setHeaderFieldModel('Content-Description', $description)) {
$this->_headers->addTextHeader('Content-Description', $description);
}
return $this;
}
/**
* Get the maximum line length of the body of this entity.
*
* @return int
*/
public function getMaxLineLength()
{
return $this->_maxLineLength;
}
/**
* Set the maximum line length of lines in this body.
*
* Though not enforced by the library, lines should not exceed 1000 chars.
*
* @param int $length
*
* @return Swift_Mime_SimpleMimeEntity
*/
public function setMaxLineLength($length)
{
$this->_maxLineLength = $length;
return $this;
}
/**
* Get all children added to this entity.
*
* @return Swift_Mime_MimeEntity[]
*/
public function getChildren()
{
return $this->_children;
}
/**
* Set all children of this entity.
*
* @param Swift_Mime_MimeEntity[] $children
* @param int $compoundLevel For internal use only
*
* @return Swift_Mime_SimpleMimeEntity
*/
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 grandchildren
$grandchildren = array_merge($grandchildren, $immediateChildren);
// Set new children
$immediateChildren = array($child);
} else {
$grandchildren[] = $child;
}
}
}
if ($immediateChildren) {
$lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel);
// Determine which composite media type is needed to accommodate the
// immediate children
foreach ($this->_compositeRanges as $mediaType => $range) {
if ($lowestLevel > $range[0] && $lowestLevel <= $range[1]) {
$newContentType = $mediaType;
break;
}
}
// Put any grandchildren in a subpart
if (!empty($grandchildren)) {
$subentity = $this->_createChild();
$subentity->_setNestingLevel($lowestLevel);
$subentity->setChildren($grandchildren, $compoundLevel);
array_unshift($immediateChildren, $subentity);
}
}
$this->_immediateChildren = $immediateChildren;
$this->_children = $children;
$this->_setContentTypeInHeaders($newContentType);
$this->_fixHeaders();
$this->_sortChildren();
return $this;
}
/**
* Get the body of this entity as a string.
*
* @return string
*/
public function getBody()
{
return $this->_body instanceof Swift_OutputByteStream ? $this->_readStream($this->_body) : $this->_body;
}
/**
* Set the body of this entity, either as a string, or as an instance of
* {@link Swift_OutputByteStream}.
*
* @param mixed $body
* @param string $contentType optional
*
* @return Swift_Mime_SimpleMimeEntity
*/
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
*
* @return Swift_Mime_SimpleMimeEntity
*/
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().'_'.md5(getmypid().mt_rand().uniqid('', true)).'_=_';
}
return $this->_boundary;
}
/**
* Set the boundary used to separate children in this entity.
*
* @param string $boundary
*
* @throws Swift_RfcComplianceException
*
* @return Swift_Mime_SimpleMimeEntity
*/
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();
$string .= $this->_bodyToString();
return $string;
}
/**
* Get this entire entity as a string.
*
* @return string
*/
protected function _bodyToString()
{
$string = '';
if (isset($this->_body) && empty($this->_immediateChildren)) {
if ($this->_cache->hasKey($this->_cacheKey, 'body')) {
$body = $this->_cache->getString($this->_cacheKey, 'body');
} else {
$body = "\r\n".$this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength());
$this->_cache->setString($this->_cacheKey, 'body', $body, Swift_KeyCache::MODE_WRITE);
}
$string .= $body;
}
if (!empty($this->_immediateChildren)) {
foreach ($this->_immediateChildren as $child) {
$string .= "\r\n\r\n--".$this->getBoundary()."\r\n";
$string .= $child->toString();
}
$string .= "\r\n\r\n--".$this->getBoundary()."--\r\n";
}
return $string;
}
/**
* Returns a string representation of this object.
*
* @see toString()
*
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* Write this entire entity to a {@see Swift_InputByteStream}.
*
* @param Swift_InputByteStream
*/
public function toByteStream(Swift_InputByteStream $is)
{
$is->write($this->_headers->toString());
$is->commit();
$this->_bodyToByteStream($is);
}
/**
* Write this entire entity to a {@link Swift_InputByteStream}.
*
* @param Swift_InputByteStream
*/
protected function _bodyToByteStream(Swift_InputByteStream $is)
{
if (empty($this->_immediateChildren)) {
if (isset($this->_body)) {
if ($this->_cache->hasKey($this->_cacheKey, 'body')) {
$this->_cache->exportToByteStream($this->_cacheKey, 'body', $is);
} else {
$cacheIs = $this->_cache->getInputByteStream($this->_cacheKey, 'body');
if ($cacheIs) {
$is->bind($cacheIs);
}
$is->write("\r\n");
if ($this->_body instanceof Swift_OutputByteStream) {
$this->_body->setReadPointer(0);
$this->_encoder->encodeByteStream($this->_body, $is, 0, $this->getMaxLineLength());
} else {
$is->write($this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength()));
}
if ($cacheIs) {
$is->unbind($cacheIs);
}
}
}
}
if (!empty($this->_immediateChildren)) {
foreach ($this->_immediateChildren as $child) {
$is->write("\r\n\r\n--".$this->getBoundary()."\r\n");
$child->toByteStream($is);
}
$is->write("\r\n\r\n--".$this->getBoundary()."--\r\n");
}
}
/**
* Get the name of the header that provides the ID of this entity.
*/
protected function _getIdField()
{
return 'Content-ID';
}
/**
* Get the model data (usually an array or a string) for $field.
*/
protected function _getHeaderFieldModel($field)
{
if ($this->_headers->has($field)) {
return $this->_headers->get($field)->getFieldBodyModel();
}
}
/**
* Set the model data for $field.
*/
protected function _setHeaderFieldModel($field, $model)
{
if ($this->_headers->has($field)) {
$this->_headers->get($field)->setFieldBodyModel($model);
return true;
}
return false;
}
/**
* Get the parameter value of $parameter on $field header.
*/
protected function _getHeaderParameter($field, $parameter)
{
if ($this->_headers->has($field)) {
return $this->_headers->get($field)->getParameter($parameter);
}
}
/**
* Set the parameter value of $parameter on $field header.
*/
protected function _setHeaderParameter($field, $parameter, $value)
{
if ($this->_headers->has($field)) {
$this->_headers->get($field)->setParameter($parameter, $value);
return true;
}
return false;
}
/**
* Re-evaluate what content type and encoding should be used on this entity.
*/
protected function _fixHeaders()
{
if (count($this->_immediateChildren)) {
$this->_setHeaderParameter('Content-Type', 'boundary',
$this->getBoundary()
);
$this->_headers->remove('Content-Transfer-Encoding');
} else {
$this->_setHeaderParameter('Content-Type', 'boundary', null);
$this->_setEncoding($this->_encoder->getName());
}
}
/**
* Get the KeyCache used in this entity.
*
* @return Swift_KeyCache
*/
protected function _getCache()
{
return $this->_cache;
}
/**
* Get the grammar used for validation.
*
* @return Swift_Mime_Grammar
*/
protected function _getGrammar()
{
return $this->_grammar;
}
/**
* 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 = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true));
$idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated';
$id = $idLeft.'@'.$idRight;
try {
$this->_assertValidId($id);
} catch (Swift_RfcComplianceException $e) {
$id = $idLeft.'@swift.generated';
}
return $id;
}
private function _readStream(Swift_OutputByteStream $os)
{
$string = '';
while (false !== $bytes = $os->read(8192)) {
$string .= $bytes;
}
$os->setReadPointer(0);
return $string;
}
private function _setEncoding($encoding)
{
if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) {
$this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding);
}
}
private function _assertValidBoundary($boundary)
{
if (!preg_match('/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di', $boundary)) {
throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.');
}
}
private function _setContentTypeInHeaders($type)
{
if (!$this->_setHeaderFieldModel('Content-Type', $type)) {
$this->_headers->addParameterizedHeader('Content-Type', $type);
}
}
private function _setNestingLevel($level)
{
$this->_nestingLevel = $level;
}
private function _getCompoundLevel($children)
{
$level = 0;
foreach ($children as $child) {
$level |= $child->getNestingLevel();
}
return $level;
}
private function _getNeededChildLevel($child, $compoundLevel)
{
$filter = 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];
}
return $realLevel;
}
private function _createChild()
{
return new self($this->_headers->newInstance(), $this->_encoder, $this->_cache, $this->_grammar);
}
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);
}
/**
* Throws an Exception if the id passed does not comply with RFC 2822.
*
* @param string $id
*
* @throws Swift_RfcComplianceException
*/
private function _assertValidId($id)
{
if (!preg_match('/^'.$this->_grammar->getDefinition('id-left').'@'.$this->_grammar->getDefinition('id-right').'$/D', $id)) {
throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>');
}
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->_headers = clone $this->_headers;
$this->_encoder = clone $this->_encoder;
$this->_cacheKey = md5(uniqid(getmypid().mt_rand(), true));
$children = array();
foreach ($this->_children as $pos => $child) {
$children[$pos] = clone $child;
}
$this->setChildren($children);
}
}

View File

@@ -1,59 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A MIME part, in a multipart message.
*
* @author Chris Corbyn
*/
class Swift_MimePart extends Swift_Mime_MimePart
{
/**
* Create a new MimePart.
*
* Details may be optionally passed into the constructor.
*
* @param string $body
* @param string $contentType
* @param string $charset
*/
public function __construct($body = null, $contentType = null, $charset = null)
{
call_user_func_array(
array($this, 'Swift_Mime_MimePart::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.part')
);
if (!isset($charset)) {
$charset = Swift_DependencyContainer::getInstance()
->lookup('properties.charset');
}
$this->setBody($body);
$this->setCharset($charset);
if ($contentType) {
$this->setContentType($contentType);
}
}
/**
* Create a new MimePart.
*
* @param string $body
* @param string $contentType
* @param string $charset
*
* @return Swift_Mime_MimePart
*/
public static function newInstance($body = null, $contentType = null, $charset = null)
{
return new self($body, $contentType, $charset);
}
}

View File

@@ -1,39 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2009 Fabien Potencier <fabien.potencier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Pretends messages have been sent, but just ignores them.
*
* @author Fabien Potencier
*/
class Swift_NullTransport extends Swift_Transport_NullTransport
{
/**
* Create a new NullTransport.
*/
public function __construct()
{
call_user_func_array(
array($this, 'Swift_Transport_NullTransport::__construct'),
Swift_DependencyContainer::getInstance()
->createDependenciesFor('transport.null')
);
}
/**
* Create a new NullTransport instance.
*
* @return Swift_NullTransport
*/
public static function newInstance()
{
return new self();
}
}

View File

@@ -1,46 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An abstract means of reading data.
*
* Classes implementing this interface may use a subsystem which requires less
* memory than working with large strings of data.
*
* @author Chris Corbyn
*/
interface Swift_OutputByteStream
{
/**
* Reads $length bytes from the stream into a string and moves the pointer
* through the stream by $length.
*
* If less bytes exist than are requested the remaining bytes are given instead.
* If no bytes are remaining at all, boolean false is returned.
*
* @param int $length
*
* @throws Swift_IoException
*
* @return string|bool
*/
public function read($length);
/**
* Move the internal read pointer to $byteOffset in the stream.
*
* @param int $byteOffset
*
* @throws Swift_IoException
*
* @return bool
*/
public function setReadPointer($byteOffset);
}

View File

@@ -1,141 +0,0 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Reduces network flooding when sending large amounts of mail.
*
* @author Chris Corbyn
*/
class Swift_Plugins_AntiFloodPlugin implements Swift_Events_SendListener, Swift_Plugins_Sleeper
{
/**
* The number of emails to send before restarting Transport.
*
* @var int
*/
private $_threshold;
/**
* The number of seconds to sleep for during a restart.
*
* @var int
*/
private $_sleep;
/**
* The internal counter.
*
* @var int
*/
private $_counter = 0;
/**
* The Sleeper instance for sleeping.
*
* @var Swift_Plugins_Sleeper
*/
private $_sleeper;
/**
* Create a new AntiFloodPlugin with $threshold and $sleep time.
*
* @param int $threshold
* @param int $sleep time
* @param Swift_Plugins_Sleeper $sleeper (not needed really)
*/
public function __construct($threshold = 99, $sleep = 0, Swift_Plugins_Sleeper $sleeper = null)
{
$this->setThreshold($threshold);
$this->setSleepTime($sleep);
$this->_sleeper = $sleeper;
}
/**
* Set the number of emails to send before restarting.
*
* @param int $threshold
*/
public function setThreshold($threshold)
{
$this->_threshold = $threshold;
}
/**
* Get the number of emails to send before restarting.
*
* @return int
*/
public function getThreshold()
{
return $this->_threshold;
}
/**
* Set the number of seconds to sleep for during a restart.
*
* @param int $sleep time
*/
public function setSleepTime($sleep)
{
$this->_sleep = $sleep;
}
/**
* Get the number of seconds to sleep for during a restart.
*
* @return int
*/
public function getSleepTime()
{
return $this->_sleep;
}
/**
* Invoked immediately before the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(Swift_Events_SendEvent $evt)
{
}
/**
* Invoked immediately after the Message is sent.
*
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(Swift_Events_SendEvent $evt)
{
++$this->_counter;
if ($this->_counter >= $this->_threshold) {
$transport = $evt->getTransport();
$transport->stop();
if ($this->_sleep) {
$this->sleep($this->_sleep);
}
$transport->start();
$this->_counter = 0;
}
}
/**
* Sleep for $seconds.
*
* @param int $seconds
*/
public function sleep($seconds)
{
if (isset($this->_sleeper)) {
$this->_sleeper->sleep($seconds);
} else {
sleep($seconds);
}
}
}

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