Added Laravel project

This commit is contained in:
2017-09-17 00:35:10 +02:00
parent a3c19304d5
commit ecf605b8f5
6246 changed files with 682270 additions and 2 deletions

View File

@@ -0,0 +1,9 @@
*.crt -crlf
*.key -crlf
*.srl -crlf
*.pub -crlf
*.priv -crlf
*.txt -crlf
# ignore /notes in the git-generated distributed .zip archive
/doc/notes export-ignore

View File

@@ -0,0 +1,8 @@
/.php_cs.cache
/.phpunit
/build/*
/composer.lock
/phpunit.xml
/tests/acceptance.conf.php
/tests/smoke.conf.php
/vendor/

View File

@@ -0,0 +1,15 @@
<?php
return PhpCsFixer\Config::create()
->setRules(array(
'@Symfony' => true,
'@Symfony:risky' => true,
'array_syntax' => array('syntax' => 'long'),
'no_unreachable_default_argument_value' => false,
'braces' => array('allow_single_line_closure' => true),
'heredoc_to_nowdoc' => false,
'phpdoc_annotation_without_dot' => false,
))
->setRiskyAllowed(true)
->setFinder(PhpCsFixer\Finder::create()->in(__DIR__))
;

View File

@@ -0,0 +1,24 @@
language: php
sudo: false
before_script:
- cp tests/acceptance.conf.php.default tests/acceptance.conf.php
- cp tests/smoke.conf.php.default tests/smoke.conf.php
- composer self-update
- composer update --no-interaction --prefer-source
- gem install mime-types -v 2.99.1
- gem install mailcatcher
- mailcatcher --smtp-port 4456
script: SYMFONY_PHPUNIT_VERSION=6.1 ./vendor/bin/simple-phpunit
matrix:
include:
- php: 7.0
- php: 7.1
fast_finish: true
cache:
directories:
- .phpunit

View File

@@ -0,0 +1,292 @@
Changelog
=========
6.0.1 (2017-05-20)
------------------
* fixed BC break that can be avoided easily
6.0.0 (2017-05-19)
------------------
* added Swift_Transport::ping()
* removed Swift_Mime_HeaderFactory, Swift_Mime_HeaderSet, Swift_Mime_Message, Swift_Mime_MimeEntity,
and Swift_Mime_ParameterizedHeader interfaces
* removed Swift_MailTransport and Swift_Transport_MailTransport
* removed Swift_Encoding
* removed the Swift_Transport_MailInvoker interface and Swift_Transport_SimpleMailInvoker class
* removed the Swift_SignedMessage class
* removed newInstance() methods everywhere
* methods operating on Date header now use DateTimeImmutable object instead of Unix timestamp;
Swift_Mime_Headers_DateHeader::getTimestamp()/setTimestamp() renamed to getDateTime()/setDateTime()
* bumped minimum version to PHP 7.0
5.4.9 (2017-XX-XX)
------------------
* n/a
5.4.8 (2017-05-01)
------------------
* fixed encoding inheritance in addPart()
* fixed sorting MIME children when their types are equal
5.4.7 (2017-04-20)
------------------
* fixed NTLMAuthenticator clobbering bcmath scale
5.4.6 (2017-02-13)
------------------
* removed exceptions thrown in destructors as they lead to fatal errors
* switched to use sha256 by default in DKIM as per the RFC
* fixed an 'Undefined variable: pipes' PHP notice
* fixed long To headers when using the mail transport
* fixed NTLMAuthenticator when no domain is passed with the username
* prevented fatal error during unserialization of a message
* fixed a PHP warning when sending a message that has a length of a multiple of 8192
5.4.5 (2016-12-29)
------------------
* SECURITY FIX: fixed CVE-2016-10074 by disallowing potentially unsafe shell characters
Prior to 5.4.5, the mail transport (Swift_Transport_MailTransport) was vulnerable to passing
arbitrary shell arguments if the "From", "ReturnPath" or "Sender" header came
from a non-trusted source, potentially allowing Remote Code Execution
* deprecated the mail transport
5.4.4 (2016-11-23)
------------------
* reverted escaping command-line args to mail (PHP mail() function already does it)
5.4.3 (2016-07-08)
------------------
* fixed SimpleHeaderSet::has()/get() when the 0 index is removed
* removed the need to have mcrypt installed
* fixed broken MIME header encoding with quotes/colons and non-ascii chars
* allowed mail transport send for messages without To header
* fixed PHP 7 support
5.4.2 (2016-05-01)
------------------
* fixed support for IPv6 sockets
* added auto-retry when sending messages from the memory spool
* fixed consecutive read calls in Swift_ByteStream_FileByteStream
* added support for iso-8859-15 encoding
* fixed PHP mail extra params on missing reversePath
* added methods to set custom stream context options
* fixed charset changes in QpContentEncoderProxy
* added return-path header to the ignoredHeaders list of DKIMSigner
* fixed crlf for subject using mail
* fixed add soft line break only when necessary
* fixed escaping command-line args to mail
5.4.1 (2015-06-06)
------------------
* made Swiftmailer exceptions confirm to PHP base exception constructor signature
* fixed MAIL FROM & RCPT TO headers to be RFC compliant
5.4.0 (2015-03-14)
------------------
* added the possibility to add extra certs to PKCS#7 signature
* fix base64 encoding with streams
* added a new RESULT_SPOOLED status for SpoolTransport
* fixed getBody() on attachments when called more than once
* removed dots from generated filenames in filespool
5.3.1 (2014-12-05)
------------------
* fixed cloning of messages with attachments
5.3.0 (2014-10-04)
------------------
* fixed cloning when using signers
* reverted removal of Swift_Encoding
* drop support for PHP 5.2.x
5.2.2 (2014-09-20)
------------------
* fixed Japanese support
* fixed the memory spool when the message changes when in the pool
* added support for cloning messages
* fixed PHP warning in the redirect plugin
* changed the way to and cc-ed email are sent to only use one transaction
5.2.1 (2014-06-13)
------------------
* SECURITY FIX: fixed CLI escaping when using sendmail as a transport
Prior to 5.2.1, the sendmail transport (Swift_Transport_SendmailTransport)
was vulnerable to an arbitrary shell execution if the "From" header came
from a non-trusted source and no "Return-Path" is configured.
* fixed parameter in DKIMSigner
* fixed compatibility with PHP < 5.4
5.2.0 (2014-05-08)
------------------
* fixed Swift_ByteStream_FileByteStream::read() to match to the specification
* fixed from-charset and to-charset arguments in mbstring_convert_encoding() usages
* fixed infinite loop in StreamBuffer
* fixed NullTransport to return the number of ignored emails instead of 0
* Use phpunit and mockery for unit testing (realityking)
5.1.0 (2014-03-18)
------------------
* fixed data writing to stream when sending large messages
* added support for libopendkim (https://github.com/xdecock/php-opendkim)
* merged SignedMessage and Message
* added Gmail XOAuth2 authentication
* updated the list of known mime types
* added NTLM authentication
5.0.3 (2013-12-03)
------------------
* fixed double-dot bug
* fixed DKIM signer
5.0.2 (2013-08-30)
------------------
* handled correct exception type while reading IoBuffer output
5.0.1 (2013-06-17)
------------------
* changed the spool to only start the transport when a mail has to be sent
* fixed compatibility with PHP 5.2
* fixed LICENSE file
5.0.0 (2013-04-30)
------------------
* changed the license from LGPL to MIT
4.3.1 (2013-04-11)
------------------
* removed usage of the native QP encoder when the charset is not UTF-8
* fixed usage of uniqid to avoid collisions
* made a performance improvement when tokenizing large headers
* fixed usage of the PHP native QP encoder on PHP 5.4.7+
4.3.0 (2013-01-08)
------------------
* made the temporary directory configurable via the TMPDIR env variable
* added S/MIME signer and encryption support
4.2.2 (2012-10-25)
------------------
* added the possibility to throttle messages per second in ThrottlerPlugin (mostly for Amazon SES)
* switched mime.qpcontentencoder to automatically use the PHP native encoder on PHP 5.4.7+
* allowed specifying a whitelist with regular expressions in RedirectingPlugin
4.2.1 (2012-07-13)
------------------
* changed the coding standards to PSR-1/2
* fixed issue with autoloading
* added NativeQpContentEncoder to enhance performance (for PHP 5.3+)
4.2.0 (2012-06-29)
------------------
* added documentation about how to use the Japanese support introduced in 4.1.8
* added a way to override the default configuration in a lazy way
* changed the PEAR init script to lazy-load the initialization
* fixed a bug when calling Swift_Preferences before anything else (regression introduced in 4.1.8)
4.1.8 (2012-06-17)
------------------
* added Japanese iso-2022-jp support
* changed the init script to lazy-load the initialization
* fixed docblocks (@id) which caused some problems with libraries parsing the dobclocks
* fixed Swift_Mime_Headers_IdentificationHeader::setId() when passed an array of ids
* fixed encoding of email addresses in headers
* added replacements setter to the Decorator plugin
4.1.7 (2012-04-26)
------------------
* fixed QpEncoder safeMapShareId property
4.1.6 (2012-03-23)
------------------
* reduced the size of serialized Messages
4.1.5 (2012-01-04)
------------------
* enforced Swift_Spool::queueMessage() to return a Boolean
* made an optimization to the memory spool: start the transport only when required
* prevented stream_socket_client() from generating an error and throw a Swift_TransportException instead
* fixed a PHP warning when calling to mail() when safe_mode is off
* many doc tweaks
4.1.4 (2011-12-16)
------------------
* added a memory spool (Swift_MemorySpool)
* fixed too many opened files when sending emails with attachments
4.1.3 (2011-10-27)
------------------
* added STARTTLS support
* added missing @return tags on fluent methods
* added a MessageLogger plugin that logs all sent messages
* added composer.json
4.1.2 (2011-09-13)
------------------
* fixed wrong detection of magic_quotes_runtime
* fixed fatal errors when no To or Subject header has been set
* fixed charset on parameter header continuations
* added documentation about how to install Swiftmailer from the PEAR channel
* fixed various typos and markup problem in the documentation
* fixed warning when cache directory does not exist
* fixed "slashes are escaped" bug
* changed require_once() to require() in autoload
4.1.1 (2011-07-04)
------------------
* added missing file in PEAR package
4.1.0 (2011-06-30)
------------------
* documentation has been converted to ReST
4.1.0 RC1 (2011-06-17)
----------------------
New features:
* changed the Decorator Plugin to allow replacements in all headers
* added Swift_Mime_Grammar and Swift_Validate to validate an email address
* modified the autoloader to lazy-initialize Swiftmailer
* removed Swift_Mailer::batchSend()
* added NullTransport
* added new plugins: RedirectingPlugin and ImpersonatePlugin
* added a way to send messages asynchronously (Spool)

View File

@@ -0,0 +1,19 @@
Copyright (c) 2013-2016 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,15 @@
Swift Mailer
------------
Swift Mailer is a component based mailing solution for PHP 5.
It is released under the MIT license.
Homepage: http://swiftmailer.org
Documentation: http://swiftmailer.org/docs
Bugs: https://github.com/swiftmailer/swiftmailer/issues
Repository: https://github.com/swiftmailer/swiftmailer
Swift Mailer is highly object-oriented by design and lends itself
to use in complex web application with a great deal of flexibility.
For full details on usage, see the documentation.

View File

@@ -0,0 +1,36 @@
{
"name": "swiftmailer/swiftmailer",
"type": "library",
"description": "Swiftmailer, free feature-rich PHP mailer",
"keywords": ["mail","mailer","email"],
"homepage": "http://swiftmailer.org",
"license": "MIT",
"authors": [
{
"name": "Chris Corbyn"
},
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
}
],
"require": {
"php": ">=7.0.0",
"egulias/email-validator": "~2.0"
},
"require-dev": {
"mockery/mockery": "~0.9.1",
"symfony/phpunit-bridge": "~3.3@dev"
},
"autoload": {
"files": ["lib/swift_required.php"]
},
"autoload-dev": {
"psr-0": { "Swift_": "tests/unit" }
},
"extra": {
"branch-alias": {
"dev-master": "6.0-dev"
}
}
}

View File

@@ -0,0 +1,609 @@
Message Headers
===============
Sometimes you'll want to add your own headers to a message or modify/remove
headers that are already present. You work with the message's HeaderSet to do
this.
Header Basics
-------------
All MIME entities in Swift Mailer -- including the message itself -- store
their headers in a single object called a HeaderSet. This HeaderSet is
retrieved with the ``getHeaders()`` method.
As mentioned in the previous chapter, everything that forms a part of a message
in Swift Mailer is a MIME entity that is represented by an instance of
``Swift_Mime_SimpleMimeEntity``. This includes -- most notably -- the message
object itself, attachments, MIME parts and embedded images. Each of these MIME
entities consists of a body and a set of headers that describe the body.
For all of the "standard" headers in these MIME entities, such as the
``Content-Type``, there are named methods for working with them, such as
``setContentType()`` and ``getContentType()``. This is because headers are a
moderately complex area of the library. Each header has a slightly different
required structure that it must meet in order to comply with the standards that
govern email (and that are checked by spam blockers etc).
You fetch the HeaderSet from a MIME entity like so::
$message = new Swift_Message();
// Fetch the HeaderSet from a Message object
$headers = $message->getHeaders();
$attachment = Swift_Attachment::fromPath('document.pdf');
// Fetch the HeaderSet from an attachment object
$headers = $attachment->getHeaders();
The job of the HeaderSet is to contain and manage instances of Header objects.
Depending upon the MIME entity the HeaderSet came from, the contents of the
HeaderSet will be different, since an attachment for example has a different
set of headers to those in a message.
You can find out what the HeaderSet contains with a quick loop, dumping out the
names of the headers::
foreach ($headers->getAll() as $header) {
printf("%s<br />\n", $header->getFieldName());
}
/*
Content-Transfer-Encoding
Content-Type
MIME-Version
Date
Message-ID
From
Subject
To
*/
You can also dump out the rendered HeaderSet by calling its ``toString()``
method::
echo $headers->toString();
/*
Message-ID: <1234869991.499a9ee7f1d5e@swift.generated>
Date: Tue, 17 Feb 2009 22:26:31 +1100
Subject: Awesome subject!
From: sender@example.org
To: recipient@example.org
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
*/
Where the complexity comes in is when you want to modify an existing header.
This complexity comes from the fact that each header can be of a slightly
different type (such as a Date header, or a header that contains email
addresses, or a header that has key-value parameters on it!). Each header in
the HeaderSet is an instance of ``Swift_Mime_Header``. They all have common
functionality, but knowing exactly what type of header you're working with will
allow you a little more control.
You can determine the type of header by comparing the return value of its
``getFieldType()`` method with the constants ``TYPE_TEXT``,
``TYPE_PARAMETERIZED``, ``TYPE_DATE``, ``TYPE_MAILBOX``, ``TYPE_ID`` and
``TYPE_PATH`` which are defined in ``Swift_Mime_Header``::
foreach ($headers->getAll() as $header) {
switch ($header->getFieldType()) {
case Swift_Mime_Header::TYPE_TEXT: $type = 'text';
break;
case Swift_Mime_Header::TYPE_PARAMETERIZED: $type = 'parameterized';
break;
case Swift_Mime_Header::TYPE_MAILBOX: $type = 'mailbox';
break;
case Swift_Mime_Header::TYPE_DATE: $type = 'date';
break;
case Swift_Mime_Header::TYPE_ID: $type = 'ID';
break;
case Swift_Mime_Header::TYPE_PATH: $type = 'path';
break;
}
printf("%s: is a %s header<br />\n", $header->getFieldName(), $type);
}
/*
Content-Transfer-Encoding: is a text header
Content-Type: is a parameterized header
MIME-Version: is a text header
Date: is a date header
Message-ID: is a ID header
From: is a mailbox header
Subject: is a text header
To: is a mailbox header
*/
Headers can be removed from the set, modified within the set, or added to the
set.
The following sections show you how to work with the HeaderSet and explain the
details of each implementation of ``Swift_Mime_Header`` that may exist within
the HeaderSet.
Header Types
------------
Because all headers are modeled on different data (dates, addresses, text!)
there are different types of Header in Swift Mailer. Swift Mailer attempts to
categorize all possible MIME headers into more general groups, defined by a
small number of classes.
Text Headers
~~~~~~~~~~~~
Text headers are the simplest type of Header. They contain textual information
with no special information included within it -- for example the Subject
header in a message.
There's nothing particularly interesting about a text header, though it is
probably the one you'd opt to use if you need to add a custom header to a
message. It represents text just like you'd think it does. If the text contains
characters that are not permitted in a message header (such as new lines, or
non-ascii characters) then the header takes care of encoding the text so that
it can be used.
No header -- including text headers -- in Swift Mailer is vulnerable to
header-injection attacks. Swift Mailer breaks any attempt at header injection
by encoding the dangerous data into a non-dangerous form.
It's easy to add a new text header to a HeaderSet. You do this by calling the
HeaderSet's ``addTextHeader()`` method::
$message = new Swift_Message();
$headers = $message->getHeaders();
$headers->addTextHeader('Your-Header-Name', 'the header value');
Changing the value of an existing text header is done by calling it's
``setValue()`` method::
$subject = $message->getHeaders()->get('Subject');
$subject->setValue('new subject');
When output via ``toString()``, a text header produces something like the
following::
$subject = $message->getHeaders()->get('Subject');
$subject->setValue('amazing subject line');
echo $subject->toString();
/*
Subject: amazing subject line
*/
If the header contains any characters that are outside of the US-ASCII range
however, they will be encoded. This is nothing to be concerned about since mail
clients will decode them back::
$subject = $message->getHeaders()->get('Subject');
$subject->setValue('contains dash');
echo $subject->toString();
/*
Subject: contains =?utf-8?Q?=E2=80=93?= dash
*/
Parameterized Headers
~~~~~~~~~~~~~~~~~~~~~
Parameterized headers are text headers that contain key-value parameters
following the textual content. The Content-Type header of a message is a
parameterized header since it contains charset information after the content
type.
The parameterized header type is a special type of text header. It extends the
text header by allowing additional information to follow it. All of the methods
from text headers are available in addition to the methods described here.
Adding a parameterized header to a HeaderSet is done by using the
``addParameterizedHeader()`` method which takes a text value like
``addTextHeader()`` but it also accepts an associative array of key-value
parameters::
$message = new Swift_Message();
$headers = $message->getHeaders();
$headers->addParameterizedHeader(
'Header-Name', 'header value',
['foo' => 'bar']
);
To change the text value of the header, call it's ``setValue()`` method just as
you do with text headers.
To change the parameters in the header, call the header's ``setParameters()``
method or the ``setParameter()`` method (note the pluralization)::
$type = $message->getHeaders()->get('Content-Type');
// setParameters() takes an associative array
$type->setParameters([
'name' => 'file.txt',
'charset' => 'iso-8859-1'
]);
// setParameter() takes two args for $key and $value
$type->setParameter('charset', 'iso-8859-1');
When output via ``toString()``, a parameterized header produces something like
the following::
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'utf-8');
echo $type->toString();
/*
Content-Type: text/html; charset=utf-8
*/
If the header contains any characters that are outside of the US-ASCII range
however, they will be encoded, just like they are for text headers. This is
nothing to be concerned about since mail clients will decode them back.
Likewise, if the parameters contain any non-ascii characters they will be
encoded so that they can be transmitted safely::
$attachment = new Swift_Attachment();
$disp = $attachment->getHeaders()->get('Content-Disposition');
$disp->setValue('attachment');
$disp->setParameter('filename', 'reportmay.pdf');
echo $disp->toString();
/*
Content-Disposition: attachment; filename*=utf-8''report%E2%80%93may.pdf
*/
Date Headers
~~~~~~~~~~~~
Date headers contains an RFC 2822 formatted date (i.e. what PHP's ``date('r')``
returns). They are used anywhere a date or time is needed to be presented as a
message header.
The data on which a date header is modeled as a DateTimeImmutable object. The
object is used to create a correctly structured RFC 2822 formatted date with
timezone such as ``Tue, 17 Feb 2009 22:26:31 +1100``.
The obvious place this header type is used is in the ``Date:`` header of the
message itself.
It's easy to add a new date header to a HeaderSet. You do this by calling the
HeaderSet's ``addDateHeader()`` method::
$message = new Swift_Message();
$headers = $message->getHeaders();
$headers->addDateHeader('Your-Header', new DateTimeImmutable('3 days ago'));
Changing the value of an existing date header is done by calling it's
``setDateTime()`` method::
$date = $message->getHeaders()->get('Date');
$date->setDateTime(new DateTimeImmutable());
When output via ``toString()``, a date header produces something like the
following::
$date = $message->getHeaders()->get('Date');
echo $date->toString();
/*
Date: Wed, 18 Feb 2009 13:35:02 +1100
*/
Mailbox (e-mail address) Headers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mailbox headers contain one or more email addresses, possibly with personalized
names attached to them. The data on which they are modeled is represented by an
associative array of email addresses and names.
Mailbox headers are probably the most complex header type to understand in
Swift Mailer because they accept their input as an array which can take various
forms, as described in the previous chapter.
All of the headers that contain e-mail addresses in a message -- with the
exception of ``Return-Path:`` which has a stricter syntax -- use this header
type. That is, ``To:``, ``From:`` etc.
You add a new mailbox header to a HeaderSet by calling the HeaderSet's
``addMailboxHeader()`` method::
$message = new Swift_Message();
$headers = $message->getHeaders();
$headers->addMailboxHeader('Your-Header-Name', [
'person1@example.org' => 'Person Name One',
'person2@example.org',
'person3@example.org',
'person4@example.org' => 'Another named person'
]);
Changing the value of an existing mailbox header is done by calling it's
``setNameAddresses()`` method::
$to = $message->getHeaders()->get('To');
$to->setNameAddresses([
'joe@example.org' => 'Joe Bloggs',
'john@example.org' => 'John Doe',
'no-name@example.org'
]);
If you don't wish to concern yourself with the complicated accepted input
formats accepted by ``setNameAddresses()`` as described in the previous chapter
and you only want to set one or more addresses (not names) then you can just
use the ``setAddresses()`` method instead::
$to = $message->getHeaders()->get('To');
$to->setAddresses([
'joe@example.org',
'john@example.org',
'no-name@example.org'
]);
.. note::
Both methods will accept the above input format in practice.
If all you want to do is set a single address in the header, you can use a
string as the input parameter to ``setAddresses()`` and/or
``setNameAddresses()``::
$to = $message->getHeaders()->get('To');
$to->setAddresses('joe-bloggs@example.org');
When output via ``toString()``, a mailbox header produces something like the
following::
$to = $message->getHeaders()->get('To');
$to->setNameAddresses([
'person1@example.org' => 'Name of Person',
'person2@example.org',
'person3@example.org' => 'Another Person'
]);
echo $to->toString();
/*
To: Name of Person <person1@example.org>, person2@example.org, Another Person
<person3@example.org>
*/
ID Headers
~~~~~~~~~~
ID headers contain identifiers for the entity (or the message). The most
notable ID header is the Message-ID header on the message itself.
An ID that exists inside an ID header looks more-or-less less like an email
address. For example, ``<1234955437.499becad62ec2@example.org>``. The part to
the left of the @ sign is usually unique, based on the current time and some
random factor. The part on the right is usually a domain name.
Any ID passed to the header's ``setId()`` method absolutely MUST conform to
this structure, otherwise you'll get an Exception thrown at you by Swift Mailer
(a ``Swift_RfcComplianceException``). This is to ensure that the generated
email complies with relevant RFC documents and therefore is less likely to be
blocked as spam.
It's easy to add a new ID header to a HeaderSet. You do this by calling the
HeaderSet's ``addIdHeader()`` method::
$message = new Swift_Message();
$headers = $message->getHeaders();
$headers->addIdHeader('Your-Header-Name', '123456.unqiue@example.org');
Changing the value of an existing date header is done by calling its
``setId()`` method::
$msgId = $message->getHeaders()->get('Message-ID');
$msgId->setId(time() . '.' . uniqid('thing') . '@example.org');
When output via ``toString()``, an ID header produces something like the
following::
$msgId = $message->getHeaders()->get('Message-ID');
echo $msgId->toString();
/*
Message-ID: <1234955437.499becad62ec2@example.org>
*/
Path Headers
~~~~~~~~~~~~
Path headers are like very-restricted mailbox headers. They contain a single
email address with no associated name. The Return-Path header of a message is a
path header.
You add a new path header to a HeaderSet by calling the HeaderSet's
``addPathHeader()`` method::
$message = new Swift_Message();
$headers = $message->getHeaders();
$headers->addPathHeader('Your-Header-Name', 'person@example.org');
Changing the value of an existing path header is done by calling its
``setAddress()`` method::
$return = $message->getHeaders()->get('Return-Path');
$return->setAddress('my-address@example.org');
When output via ``toString()``, a path header produces something like the
following::
$return = $message->getHeaders()->get('Return-Path');
$return->setAddress('person@example.org');
echo $return->toString();
/*
Return-Path: <person@example.org>
*/
Header Operations
-----------------
Working with the headers in a message involves knowing how to use the methods
on the HeaderSet and on the individual Headers within the HeaderSet.
Adding new Headers
~~~~~~~~~~~~~~~~~~
New headers can be added to the HeaderSet by using one of the provided
``add..Header()`` methods.
The added header will appear in the message when it is sent::
// Adding a custom header to a message
$message = new Swift_Message();
$headers = $message->getHeaders();
$headers->addTextHeader('X-Mine', 'something here');
// Adding a custom header to an attachment
$attachment = Swift_Attachment::fromPath('/path/to/doc.pdf');
$attachment->getHeaders()->addDateHeader('X-Created-Time', time());
Retrieving Headers
~~~~~~~~~~~~~~~~~~
Headers are retrieved through the HeaderSet's ``get()`` and ``getAll()``
methods::
$headers = $message->getHeaders();
// Get the To: header
$toHeader = $headers->get('To');
// Get all headers named "X-Foo"
$fooHeaders = $headers->getAll('X-Foo');
// Get the second header named "X-Foo"
$foo = $headers->get('X-Foo', 1);
// Get all headers that are present
$all = $headers->getAll();
When using ``get()`` a single header is returned that matches the name (case
insensitive) that is passed to it. When using ``getAll()`` with a header name,
an array of headers with that name are returned. Calling ``getAll()`` with no
arguments returns an array of all headers present in the entity.
.. note::
It's valid for some headers to appear more than once in a message (e.g.
the Received header). For this reason ``getAll()`` exists to fetch all
headers with a specified name. In addition, ``get()`` accepts an optional
numerical index, starting from zero to specify which header you want more
specifically.
.. note::
If you want to modify the contents of the header and you don't know for
sure what type of header it is then you may need to check the type by
calling its ``getFieldType()`` method.
Check if a Header Exists
~~~~~~~~~~~~~~~~~~~~~~~~
You can check if a named header is present in a HeaderSet by calling its
``has()`` method::
$headers = $message->getHeaders();
// Check if the To: header exists
if ($headers->has('To')) {
echo 'To: exists';
}
// Check if an X-Foo header exists twice (i.e. check for the 2nd one)
if ($headers->has('X-Foo', 1)) {
echo 'Second X-Foo header exists';
}
If the header exists, ``true`` will be returned or ``false`` if not.
.. note::
It's valid for some headers to appear more than once in a message (e.g.
the Received header). For this reason ``has()`` accepts an optional
numerical index, starting from zero to specify which header you want to
check more specifically.
Removing Headers
~~~~~~~~~~~~~~~~
Removing a Header from the HeaderSet is done by calling the HeaderSet's
``remove()`` or ``removeAll()`` methods::
$headers = $message->getHeaders();
// Remove the Subject: header
$headers->remove('Subject');
// Remove all X-Foo headers
$headers->removeAll('X-Foo');
// Remove only the second X-Foo header
$headers->remove('X-Foo', 1);
When calling ``remove()`` a single header will be removed. When calling
``removeAll()`` all headers with the given name will be removed. If no headers
exist with the given name, no errors will occur.
.. note::
It's valid for some headers to appear more than once in a message (e.g.
the Received header). For this reason ``remove()`` accepts an optional
numerical index, starting from zero to specify which header you want to
check more specifically. For the same reason, ``removeAll()`` exists to
remove all headers that have the given name.
Modifying a Header's Content
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To change a Header's content you should know what type of header it is and then
call it's appropriate setter method. All headers also have a
``setFieldBodyModel()`` method that accepts a mixed parameter and delegates to
the correct setter::
The header will be updated inside the HeaderSet and the changes will be seen
when the message is sent::
$headers = $message->getHeaders();
// Change the Subject: header
$subj = $headers->get('Subject');
$subj->setValue('new subject here');
// Change the To: header
$to = $headers->get('To');
$to->setNameAddresses([
'person@example.org' => 'Person',
'thing@example.org'
]);
// Using the setFieldBodyModel() just delegates to the correct method
// So here to calls setNameAddresses()
$to->setFieldBodyModel([
'person@example.org' => 'Person',
'thing@example.org'
]);

View File

@@ -0,0 +1,12 @@
Swiftmailer
===========
.. toctree::
:maxdepth: 2
introduction
messages
headers
sending
plugins
japanese

View File

@@ -0,0 +1,61 @@
Introduction
============
Swift Mailer is a for sending e-mails from PHP applications.
System Requirements
-------------------
Swift Mailer requires PHP 7.0 or higher (``proc_*`` functions must be
available).
Swift Mailer does not work when used with function overloading as implemented
by ``mbstring`` when ``mbstring.func_overload`` is set to ``2``.
Installation
------------
The recommended way to install Swiftmailer is via Composer:
.. code-block:: bash
$ composer require "swiftmailer/swiftmailer:^6.0"
Basic Usage
-----------
Here is the simplest way to send emails with Swift Mailer::
require_once '/path/to/vendor/autoload.php';
// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
->setUsername('your username')
->setPassword('your password')
;
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = new Swift_Message('Wonderful Subject')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);
You can also use Sendmail as a transport::
// Sendmail
$transport = new Swift_SendmailTransport('/usr/sbin/sendmail -bs');
Getting Help
------------
For bug reports and feature requests, create a new ticket in `GitHub
<https://github.com/swiftmailer/swiftmailer/issues>`_.
For general support, use Stack Overflow.

View File

@@ -0,0 +1,19 @@
Using Swift Mailer for Japanese Emails
======================================
To send emails in Japanese, you need to tweak the default configuration.
Call the ``Swift::init()`` method with the following code as early as possible
in your code::
Swift::init(function () {
Swift_DependencyContainer::getInstance()
->register('mime.qpheaderencoder')
->asAliasOf('mime.base64headerencoder');
Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
});
/* rest of code goes here */
That's all!

View File

@@ -0,0 +1,903 @@
Creating Messages
=================
Creating messages in Swift Mailer is done by making use of the various MIME
entities provided with the library. Complex messages can be quickly created
with very little effort.
Quick Reference
---------------
You can think of creating a Message as being similar to the steps you perform
when you click the Compose button in your mail client. You give it a subject,
specify some recipients, add any attachments and write your message::
// Create the message
$message = (new Swift_Message())
// Give the message a subject
->setSubject('Your subject')
// Set the From address with an associative array
->setFrom(['john@doe.com' => 'John Doe'])
// Set the To addresses with an associative array (setTo/setCc/setBcc)
->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
// Give it a body
->setBody('Here is the message itself')
// And optionally an alternative body
->addPart('<q>Here is the message itself</q>', 'text/html')
// Optionally add any attachments
->attach(Swift_Attachment::fromPath('my-document.pdf'))
;
Message Basics
--------------
A message is a container for anything you want to send to somebody else. There
are several basic aspects of a message that you should know.
An e-mail message is made up of several relatively simple entities that are
combined in different ways to achieve different results. All of these entities
have the same fundamental outline but serve a different purpose. The Message
itself can be defined as a MIME entity, an Attachment is a MIME entity, all
MIME parts are MIME entities -- and so on!
The basic units of each MIME entity -- be it the Message itself, or an
Attachment -- are its Headers and its body:
.. code-block:: text
Header-Name: A header value
Other-Header: Another value
The body content itself
The Headers of a MIME entity, and its body must conform to some strict
standards defined by various RFC documents. Swift Mailer ensures that these
specifications are followed by using various types of object, including
Encoders and different Header types to generate the entity.
The Structure of a Message
~~~~~~~~~~~~~~~~~~~~~~~~~~
Of all of the MIME entities, a message -- ``Swift_Message`` is the largest and
most complex. It has many properties that can be updated and it can contain
other MIME entities -- attachments for example -- nested inside it.
A Message has a lot of different Headers which are there to present information
about the message to the recipients' mail client. Most of these headers will be
familiar to the majority of users, but we'll list the basic ones. Although it's
possible to work directly with the Headers of a Message (or other MIME entity),
the standard Headers have accessor methods provided to abstract away the
complex details for you. For example, although the Date on a message is written
with a strict format, you only need to pass a DateTimeInterface instance to
``setDate()``.
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| Header | Description | Accessors |
+===============================+====================================================================================================================================+=============================================+
| ``Message-ID`` | Identifies this message with a unique ID, usually containing the domain name and time generated | ``getId()`` / ``setId()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Return-Path`` | Specifies where bounces should go (Swift Mailer reads this for other uses) | ``getReturnPath()`` / ``setReturnPath()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``From`` | Specifies the address of the person who the message is from. This can be multiple addresses if multiple people wrote the message. | ``getFrom()`` / ``setFrom()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Sender`` | Specifies the address of the person who physically sent the message (higher precedence than ``From:``) | ``getSender()`` / ``setSender()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``To`` | Specifies the addresses of the intended recipients | ``getTo()`` / ``setTo()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Cc`` | Specifies the addresses of recipients who will be copied in on the message | ``getCc()`` / ``setCc()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Bcc`` | Specifies the addresses of recipients who the message will be blind-copied to. Other recipients will not be aware of these copies. | ``getBcc()`` / ``setBcc()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Reply-To`` | Specifies the address where replies are sent to | ``getReplyTo()`` / ``setReplyTo()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Subject`` | Specifies the subject line that is displayed in the recipients' mail client | ``getSubject()`` / ``setSubject()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Date`` | Specifies the date at which the message was sent | ``getDate()`` / ``setDate()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Content-Type`` | Specifies the format of the message (usually text/plain or text/html) | ``getContentType()`` / ``setContentType()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
| ``Content-Transfer-Encoding`` | Specifies the encoding scheme in the message | ``getEncoder()`` / ``setEncoder()`` |
+-------------------------------+------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------------+
Working with a Message Object
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Although there are a lot of available methods on a message object, you only
need to make use of a small subset of them. Usually you'll use
``setSubject()``, ``setTo()`` and ``setFrom()`` before setting the body of your
message with ``setBody()``::
$message = new Swift_Message();
$message->setSubject('My subject');
All MIME entities (including a message) have a ``toString()`` method that you
can call if you want to take a look at what is going to be sent. For example,
if you ``echo $message->toString();`` you would see something like this:
.. code-block:: text
Message-ID: <1230173678.4952f5eeb1432@swift.generated>
Date: Thu, 25 Dec 2008 13:54:38 +1100
Subject: Example subject
From: Chris Corbyn <chris@w3style.co.uk>
To: Receiver Name <recipient@example.org>
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
Here is the message
We'll take a closer look at the methods you use to create your message in the
following sections.
Adding Content to Your Message
------------------------------
Rich content can be added to messages in Swift Mailer with relative ease by
calling methods such as ``setSubject()``, ``setBody()``, ``addPart()`` and
``attach()``.
Setting the Subject Line
~~~~~~~~~~~~~~~~~~~~~~~~
The subject line, displayed in the recipients' mail client can be set with the
``setSubject()`` method, or as a parameter to ``new Swift_Message()``::
// Pass it as a parameter when you create the message
$message = new Swift_Message('My amazing subject');
// Or set it after like this
$message->setSubject('My amazing subject');
Setting the Body Content
~~~~~~~~~~~~~~~~~~~~~~~~
The body of the message -- seen when the user opens the message -- is specified
by calling the ``setBody()`` method. If an alternative body is to be included,
``addPart()`` can be used.
The body of a message is the main part that is read by the user. Often people
want to send a message in HTML format (``text/html``), other times people want
to send in plain text (``text/plain``), or sometimes people want to send both
versions and allow the recipient to choose how they view the message.
As a rule of thumb, if you're going to send a HTML email, always include a
plain-text equivalent of the same content so that users who prefer to read
plain text can do so.
If the recipient's mail client offers preferences for displaying text vs. HTML
then the mail client will present that part to the user where available. In
other cases the mail client will display the "best" part it can - usually HTML
if you've included HTML::
// Pass it as a parameter when you create the message
$message = new Swift_Message('Subject here', 'My amazing body');
// Or set it after like this
$message->setBody('My <em>amazing</em> body', 'text/html');
// Add alternative parts with addPart()
$message->addPart('My amazing body in plain text', 'text/plain');
Attaching Files
---------------
Attachments are downloadable parts of a message and can be added by calling the
``attach()`` method on the message. You can add attachments that exist on disk,
or you can create attachments on-the-fly.
Although we refer to files sent over e-mails as "attachments" -- because
they're attached to the message -- lots of other parts of the message are
actually "attached" even if we don't refer to these parts as attachments.
File attachments are created by the ``Swift_Attachment`` class and then
attached to the message via the ``attach()`` method on it. For all of the
"every day" MIME types such as all image formats, word documents, PDFs and
spreadsheets you don't need to explicitly set the content-type of the
attachment, though it would do no harm to do so. For less common formats you
should set the content-type -- which we'll cover in a moment.
Attaching Existing Files
~~~~~~~~~~~~~~~~~~~~~~~~
Files that already exist, either on disk or at a URL can be attached to a
message with just one line of code, using ``Swift_Attachment::fromPath()``.
You can attach files that exist locally, or if your PHP installation has
``allow_url_fopen`` turned on you can attach files from other
websites.
The attachment will be presented to the recipient as a downloadable file with
the same filename as the one you attached::
// Create the attachment
// * Note that you can technically leave the content-type parameter out
$attachment = Swift_Attachment::fromPath('/path/to/image.jpg', 'image/jpeg');
// Attach it to the message
$message->attach($attachment);
// The two statements above could be written in one line instead
$message->attach(Swift_Attachment::fromPath('/path/to/image.jpg'));
// You can attach files from a URL if allow_url_fopen is on in php.ini
$message->attach(Swift_Attachment::fromPath('http://site.tld/logo.png'));
Setting the Filename
~~~~~~~~~~~~~~~~~~~~
Usually you don't need to explicitly set the filename of an attachment because
the name of the attached file will be used by default, but if you want to set
the filename you use the ``setFilename()`` method of the Attachment.
The attachment will be attached in the normal way, but meta-data sent inside
the email will rename the file to something else::
// Create the attachment and call its setFilename() method
$attachment = Swift_Attachment::fromPath('/path/to/image.jpg')
->setFilename('cool.jpg');
// Because there's a fluid interface, you can do this in one statement
$message->attach(
Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('cool.jpg')
);
Attaching Dynamic Content
~~~~~~~~~~~~~~~~~~~~~~~~~
Files that are generated at runtime, such as PDF documents or images created
via GD can be attached directly to a message without writing them out to disk.
Use ``Swift_Attachment`` directly.
The attachment will be presented to the recipient as a downloadable file
with the filename and content-type you specify::
// Create your file contents in the normal way, but don't write them to disk
$data = create_my_pdf_data();
// Create the attachment with your data
$attachment = new Swift_Attachment($data, 'my-file.pdf', 'application/pdf');
// Attach it to the message
$message->attach($attachment);
// You can alternatively use method chaining to build the attachment
$attachment = (new Swift_Attachment())
->setFilename('my-file.pdf')
->setContentType('application/pdf')
->setBody($data)
;
.. note::
If you would usually write the file to disk anyway you should just attach
it with ``Swift_Attachment::fromPath()`` since this will use less memory.
Changing the Disposition
~~~~~~~~~~~~~~~~~~~~~~~~
Attachments just appear as files that can be saved to the Desktop if desired.
You can make attachment appear inline where possible by using the
``setDisposition()`` method of an attachment.
The attachment will be displayed within the email viewing window if the mail
client knows how to display it::
// Create the attachment and call its setDisposition() method
$attachment = Swift_Attachment::fromPath('/path/to/image.jpg')
->setDisposition('inline');
// Because there's a fluid interface, you can do this in one statement
$message->attach(
Swift_Attachment::fromPath('/path/to/image.jpg')->setDisposition('inline')
);
.. note::
If you try to create an inline attachment for a non-displayable file type
such as a ZIP file, the mail client should just present the attachment as
normal.
Embedding Inline Media Files
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Often, people want to include an image or other content inline with a HTML
message. It's easy to do this with HTML linking to remote resources, but this
approach is usually blocked by mail clients. Swift Mailer allows you to embed
your media directly into the message.
Mail clients usually block downloads from remote resources because this
technique was often abused as a mean of tracking who opened an email. If
you're sending a HTML email and you want to include an image in the message
another approach you can take is to embed the image directly.
Swift Mailer makes embedding files into messages extremely streamlined. You
embed a file by calling the ``embed()`` method of the message,
which returns a value you can use in a ``src`` or
``href`` attribute in your HTML.
Just like with attachments, it's possible to embed dynamically generated
content without having an existing file available.
The embedded files are sent in the email as a special type of attachment that
has a unique ID used to reference them within your HTML attributes. On mail
clients that do not support embedded files they may appear as attachments.
Although this is commonly done for images, in theory it will work for any
displayable (or playable) media type. Support for other media types (such as
video) is dependent on the mail client however.
Embedding Existing Files
........................
Files that already exist, either on disk or at a URL can be embedded in a
message with just one line of code, using ``Swift_EmbeddedFile::fromPath()``.
You can embed files that exist locally, or if your PHP installation has
``allow_url_fopen`` turned on you can embed files from other websites.
The file will be displayed with the message inline with the HTML wherever its ID
is used as a ``src`` attribute::
// Create the message
$message = new Swift_Message('My subject');
// Set the body
$message->setBody(
'<html>' .
' <body>' .
' Here is an image <img src="' . // Embed the file
$message->embed(Swift_Image::fromPath('image.png')) .
'" alt="Image" />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html' // Mark the content-type as HTML
);
// You can embed files from a URL if allow_url_fopen is on in php.ini
$message->setBody(
'<html>' .
' <body>' .
' Here is an image <img src="' .
$message->embed(Swift_Image::fromPath('http://site.tld/logo.png')) .
'" alt="Image" />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html'
);
.. note::
``Swift_Image`` and ``Swift_EmbeddedFile`` are just aliases of one another.
``Swift_Image`` exists for semantic purposes.
.. note::
You can embed files in two stages if you prefer. Just capture the return
value of ``embed()`` in a variable and use that as the ``src`` attribute::
// If placing the embed() code inline becomes cumbersome
// it's easy to do this in two steps
$cid = $message->embed(Swift_Image::fromPath('image.png'));
$message->setBody(
'<html>' .
' <body>' .
' Here is an image <img src="' . $cid . '" alt="Image" />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html' // Mark the content-type as HTML
);
Embedding Dynamic Content
.........................
Images that are generated at runtime, such as images created via GD can be
embedded directly to a message without writing them out to disk. Use the
standard ``new Swift_Image()`` method.
The file will be displayed with the message inline with the HTML wherever its ID
is used as a ``src`` attribute::
// Create your file contents in the normal way, but don't write them to disk
$img_data = create_my_image_data();
// Create the message
$message = new Swift_Message('My subject');
// Set the body
$message->setBody(
'<html>' .
' <body>' .
' Here is an image <img src="' . // Embed the file
$message->embed(new Swift_Image($img_data, 'image.jpg', 'image/jpeg')) .
'" alt="Image" />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html' // Mark the content-type as HTML
);
.. note::
``Swift_Image`` and ``Swift_EmbeddedFile`` are just aliases of one another.
``Swift_Image`` exists for semantic purposes.
.. note::
You can embed files in two stages if you prefer. Just capture the return
value of ``embed()`` in a variable and use that as the ``src`` attribute::
// If placing the embed() code inline becomes cumbersome
// it's easy to do this in two steps
$cid = $message->embed(new Swift_Image($img_data, 'image.jpg', 'image/jpeg'));
$message->setBody(
'<html>' .
' <body>' .
' Here is an image <img src="' . $cid . '" alt="Image" />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html' // Mark the content-type as HTML
);
Adding Recipients to Your Message
---------------------------------
Recipients are specified within the message itself via ``setTo()``, ``setCc()``
and ``setBcc()``. Swift Mailer reads these recipients from the message when it
gets sent so that it knows where to send the message to.
Message recipients are one of three types:
* ``To:`` recipients -- the primary recipients (required)
* ``Cc:`` recipients -- receive a copy of the message (optional)
* ``Bcc:`` recipients -- hidden from other recipients (optional)
Each type can contain one, or several addresses. It's possible to list only the
addresses of the recipients, or you can personalize the address by providing
the real name of the recipient.
Make sure to add only valid email addresses as recipients. If you try to add an
invalid email address with ``setTo()``, ``setCc()`` or ``setBcc()``, Swift
Mailer will throw a ``Swift_RfcComplianceException``.
If you add recipients automatically based on a data source that may contain
invalid email addresses, you can prevent possible exceptions by validating the
addresses using ``Swift_Validate::email($email)`` and only adding addresses
that validate. Another way would be to wrap your ``setTo()``, ``setCc()`` and
``setBcc()`` calls in a try-catch block and handle the
``Swift_RfcComplianceException`` in the catch block.
.. sidebar:: Syntax for Addresses
If you only wish to refer to a single email address (for example your
``From:`` address) then you can just use a string::
$message->setFrom('some@address.tld');
If you want to include a name then you must use an associative array::
$message->setFrom(['some@address.tld' => 'The Name']);
If you want to include multiple addresses then you must use an array::
$message->setTo(['some@address.tld', 'other@address.tld']);
You can mix personalized (addresses with a name) and non-personalized
addresses in the same list by mixing the use of associative and
non-associative array syntax::
$message->setTo([
'recipient-with-name@example.org' => 'Recipient Name One',
'no-name@example.org', // Note that this is not a key-value pair
'named-recipient@example.org' => 'Recipient Name Two'
]);
Setting ``To:`` Recipients
~~~~~~~~~~~~~~~~~~~~~~~~~~
``To:`` recipients are required in a message and are set with the ``setTo()``
or ``addTo()`` methods of the message.
To set ``To:`` recipients, create the message object using either ``new
Swift_Message( ... )`` or ``new Swift_Message( ... )``, then call the
``setTo()`` method with a complete array of addresses, or use the ``addTo()``
method to iteratively add recipients.
The ``setTo()`` method accepts input in various formats as described earlier in
this chapter. The ``addTo()`` method takes either one or two parameters. The
first being the email address and the second optional parameter being the name
of the recipient.
``To:`` recipients are visible in the message headers and will be seen by the
other recipients::
// Using setTo() to set all recipients in one go
$message->setTo([
'person1@example.org',
'person2@otherdomain.org' => 'Person 2 Name',
'person3@example.org',
'person4@example.org',
'person5@example.org' => 'Person 5 Name'
]);
.. note::
Multiple calls to ``setTo()`` will not add new recipients -- each
call overrides the previous calls. If you want to iteratively add
recipients, use the ``addTo()`` method::
// Using addTo() to add recipients iteratively
$message->addTo('person1@example.org');
$message->addTo('person2@example.org', 'Person 2 Name');
Setting ``Cc:`` Recipients
~~~~~~~~~~~~~~~~~~~~~~~~~~
``Cc:`` recipients are set with the ``setCc()`` or ``addCc()`` methods of the
message.
To set ``Cc:`` recipients, create the message object using either ``new
Swift_Message( ... )`` or ``new Swift_Message( ... )``, then call the
``setCc()`` method with a complete array of addresses, or use the ``addCc()``
method to iteratively add recipients.
The ``setCc()`` method accepts input in various formats as described earlier in
this chapter. The ``addCc()`` method takes either one or two parameters. The
first being the email address and the second optional parameter being the name
of the recipient.
``Cc:`` recipients are visible in the message headers and will be seen by the
other recipients::
// Using setTo() to set all recipients in one go
$message->setTo([
'person1@example.org',
'person2@otherdomain.org' => 'Person 2 Name',
'person3@example.org',
'person4@example.org',
'person5@example.org' => 'Person 5 Name'
]);
.. note::
Multiple calls to ``setCc()`` will not add new recipients -- each call
overrides the previous calls. If you want to iteratively add Cc:
recipients, use the ``addCc()`` method::
// Using addCc() to add recipients iteratively
$message->addCc('person1@example.org');
$message->addCc('person2@example.org', 'Person 2 Name');
Setting ``Bcc:`` Recipients
~~~~~~~~~~~~~~~~~~~~~~~~~~~
``Bcc:`` recipients receive a copy of the message without anybody else knowing
it, and are set with the ``setBcc()`` or ``addBcc()`` methods of the message.
To set ``Bcc:`` recipients, create the message object using either ``new
Swift_Message( ... )`` or ``new Swift_Message( ... )``, then call the
``setBcc()`` method with a complete array of addresses, or use the ``addBcc()``
method to iteratively add recipients.
The ``setBcc()`` method accepts input in various formats as described earlier
in this chapter. The ``addBcc()`` method takes either one or two parameters.
The first being the email address and the second optional parameter being the
name of the recipient.
Only the individual ``Bcc:`` recipient will see their address in the message
headers. Other recipients (including other ``Bcc:`` recipients) will not see
the address::
// Using setBcc() to set all recipients in one go
$message->setBcc([
'person1@example.org',
'person2@otherdomain.org' => 'Person 2 Name',
'person3@example.org',
'person4@example.org',
'person5@example.org' => 'Person 5 Name'
]);
.. note::
Multiple calls to ``setBcc()`` will not add new recipients -- each call
overrides the previous calls. If you want to iteratively add Bcc:
recipients, use the ``addBcc()`` method::
// Using addBcc() to add recipients iteratively
$message->addBcc('person1@example.org');
$message->addBcc('person2@example.org', 'Person 2 Name');
Specifying Sender Details
-------------------------
An email must include information about who sent it. Usually this is managed by
the ``From:`` address, however there are other options.
The sender information is contained in three possible places:
* ``From:`` -- the address(es) of who wrote the message (required)
* ``Sender:`` -- the address of the single person who sent the message
(optional)
* ``Return-Path:`` -- the address where bounces should go to (optional)
You must always include a ``From:`` address by using ``setFrom()`` on the
message. Swift Mailer will use this as the default ``Return-Path:`` unless
otherwise specified.
The ``Sender:`` address exists because the person who actually sent the email
may not be the person who wrote the email. It has a higher precedence than the
``From:`` address and will be used as the ``Return-Path:`` unless otherwise
specified.
Setting the ``From:`` Address
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A ``From:`` address is required and is set with the ``setFrom()`` method of the
message. ``From:`` addresses specify who actually wrote the email, and usually
who sent it.
What most people probably don't realize is that you can have more than one
``From:`` address if more than one person wrote the email -- for example if an
email was put together by a committee.
The ``From:`` address(es) are visible in the message headers and will be seen
by the recipients.
.. note::
If you set multiple ``From:`` addresses then you absolutely must set a
``Sender:`` address to indicate who physically sent the message.
::
// Set a single From: address
$message->setFrom('your@address.tld');
// Set a From: address including a name
$message->setFrom(['your@address.tld' => 'Your Name']);
// Set multiple From: addresses if multiple people wrote the email
$message->setFrom([
'person1@example.org' => 'Sender One',
'person2@example.org' => 'Sender Two'
]);
Setting the ``Sender:`` Address
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A ``Sender:`` address specifies who sent the message and is set with the
``setSender()`` method of the message.
The ``Sender:`` address is visible in the message headers and will be seen by
the recipients.
This address will be used as the ``Return-Path:`` unless otherwise specified.
.. note::
If you set multiple ``From:`` addresses then you absolutely must set a
``Sender:`` address to indicate who physically sent the message.
You must not set more than one sender address on a message because it's not
possible for more than one person to send a single message::
$message->setSender('your@address.tld');
Setting the ``Return-Path:`` (Bounce) Address
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ``Return-Path:`` address specifies where bounce notifications should be
sent and is set with the ``setReturnPath()`` method of the message.
You can only have one ``Return-Path:`` and it must not include a personal name.
Bounce notifications will be sent to this address::
$message->setReturnPath('bounces@address.tld');
Signed/Encrypted Message
------------------------
To increase the integrity/security of a message it is possible to sign and/or
encrypt an message using one or multiple signers.
S/MIME
~~~~~~
S/MIME can sign and/or encrypt a message using the OpenSSL extension.
When signing a message, the signer creates a signature of the entire content of
the message (including attachments).
The certificate and private key must be PEM encoded, and can be either created
using for example OpenSSL or obtained at an official Certificate Authority (CA).
**The recipient must have the CA certificate in the list of trusted issuers in
order to verify the signature.**
**Make sure the certificate supports emailProtection.**
When using OpenSSL this can done by the including the *-addtrust
emailProtection* parameter when creating the certificate::
$message = new Swift_Message();
$smimeSigner = new Swift_Signers_SMimeSigner();
$smimeSigner->setSignCertificate('/path/to/certificate.pem', '/path/to/private-key.pem');
$message->attachSigner($smimeSigner);
When the private key is secured using a passphrase use the following instead::
$message = new Swift_Message();
$smimeSigner = new Swift_Signers_SMimeSigner();
$smimeSigner->setSignCertificate('/path/to/certificate.pem', ['/path/to/private-key.pem', 'passphrase']);
$message->attachSigner($smimeSigner);
By default the signature is added as attachment, making the message still
readable for mailing agents not supporting signed messages.
Storing the message as binary is also possible but not recommended::
$smimeSigner->setSignCertificate('/path/to/certificate.pem', '/path/to/private-key.pem', PKCS7_BINARY);
When encrypting the message (also known as enveloping), the entire message
(including attachments) is encrypted using a certificate, and the recipient can
then decrypt the message using corresponding private key.
Encrypting ensures nobody can read the contents of the message without the
private key.
Normally the recipient provides a certificate for encrypting and keeping the
decryption key private.
Using both signing and encrypting is also possible::
$message = new Swift_Message();
$smimeSigner = new Swift_Signers_SMimeSigner();
$smimeSigner->setSignCertificate('/path/to/sign-certificate.pem', '/path/to/private-key.pem');
$smimeSigner->setEncryptCertificate('/path/to/encrypt-certificate.pem');
$message->attachSigner($smimeSigner);
The used encryption cipher can be set as the second parameter of
setEncryptCertificate()
See http://php.net/manual/openssl.ciphers for a list of supported ciphers.
By default the message is first signed and then encrypted, this can be changed
by adding::
$smimeSigner->setSignThenEncrypt(false);
**Changing this is not recommended as most mail agents don't support this
none-standard way.**
Only when having trouble with sign then encrypt method, this should be changed.
Requesting a Read Receipt
-------------------------
It is possible to request a read-receipt to be sent to an address when the
email is opened. To request a read receipt set the address with
``setReadReceiptTo()``:
$message->setReadReceiptTo('your@address.tld');
When the email is opened, if the mail client supports it a notification will be
sent to this address.
.. note::
Read receipts won't work for the majority of recipients since many mail
clients auto-disable them. Those clients that will send a read receipt
will make the user aware that one has been requested.
Setting the Character Set
-------------------------
The character set of the message (and it's MIME parts) is set with the
``setCharset()`` method. You can also change the global default of UTF-8 by
working with the ``Swift_Preferences`` class.
Swift Mailer will default to the UTF-8 character set unless otherwise
overridden. UTF-8 will work in most instances since it includes all of the
standard US keyboard characters in addition to most international characters.
It is absolutely vital however that you know what character set your message
(or it's MIME parts) are written in otherwise your message may be received
completely garbled.
There are two places in Swift Mailer where you can change the character set:
* In the ``Swift_Preferences`` class
* On each individual message and/or MIME part
To set the character set of your Message:
* Change the global UTF-8 setting by calling
``Swift_Preferences::setCharset()``; or
* Call the ``setCharset()`` method on the message or the MIME part::
// Approach 1: Change the global setting (suggested)
Swift_Preferences::getInstance()->setCharset('iso-8859-2');
// Approach 2: Call the setCharset() method of the message
$message = new Swift_Message()
->setCharset('iso-8859-2');
// Approach 3: Specify the charset when setting the body
$message->setBody('My body', 'text/html', 'iso-8859-2');
// Approach 4: Specify the charset for each part added
$message->addPart('My part', 'text/plain', 'iso-8859-2');
Setting the Line Length
-----------------------
The length of lines in a message can be changed by using the
``setMaxLineLength()`` method on the message::
$message->setMaxLineLength(1000);
Swift Mailer defaults to using 78 characters per line in a message. This is
done for historical reasons and so that the message can be easily viewed in
plain-text terminals
Lines that are longer than the line length specified will be wrapped between
words.
.. note::
You should never set a maximum length longer than 1000 characters
according to RFC 2822. Doing so could have unspecified side-effects such
as truncating parts of your message when it is transported between SMTP
servers.
Setting the Message Priority
----------------------------
You can change the priority of the message with ``setPriority()``. Setting the
priority will not change the way your email is sent -- it is purely an
indicative setting for the recipient::
// Indicate "High" priority
$message->setPriority(2);
The priority of a message is an indication to the recipient what significance
it has. Swift Mailer allows you to set the priority by calling the
``setPriority`` method. This method takes an integer value between 1 and 5:
* ``Swift_Mime_SimpleMessage::PRIORITY_HIGHEST``: 1
* ``Swift_Mime_SimpleMessage::PRIORITY_HIGH``: 2
* ``Swift_Mime_SimpleMessage::PRIORITY_NORMAL``: 3
* ``Swift_Mime_SimpleMessage::PRIORITY_LOW``: 4
* ``Swift_Mime_SimpleMessage::PRIORITY_LOWEST``: 5
::
// Or use the constant to be more explicit
$message->setPriority(Swift_Mime_SimpleMessage::PRIORITY_HIGH);

View File

@@ -0,0 +1,337 @@
Plugins
=======
Plugins exist to extend, or modify the behaviour of Swift Mailer. They respond
to Events that are fired within the Transports during sending.
There are a number of Plugins provided as part of the base Swift Mailer package
and they all follow a common interface to respond to Events fired within the
library. Interfaces are provided to "listen" to each type of Event fired and to
act as desired when a listened-to Event occurs.
Although several plugins are provided with Swift Mailer out-of-the-box, the
Events system has been specifically designed to make it easy for experienced
object-oriented developers to write their own plugins in order to achieve
goals that may not be possible with the base library.
AntiFlood Plugin
----------------
Many SMTP servers have limits on the number of messages that may be sent during
any single SMTP connection. The AntiFlood plugin provides a way to stay within
this limit while still managing a large number of emails.
A typical limit for a single connection is 100 emails. If the server you
connect to imposes such a limit, it expects you to disconnect after that number
of emails has been sent. You could manage this manually within a loop, but the
AntiFlood plugin provides the necessary wrapper code so that you don't need to
worry about this logic.
Regardless of limits imposed by the server, it's usually a good idea to be
conservative with the resources of the SMTP server. Sending will become
sluggish if the server is being over-used so using the AntiFlood plugin will
not be a bad idea even if no limits exist.
The AntiFlood plugin's logic is basically to disconnect and the immediately
re-connect with the SMTP server every X number of emails sent, where X is a
number you specify to the plugin.
You can also specify a time period in seconds that Swift Mailer should pause
for between the disconnect/re-connect process. It's a good idea to pause for a
short time (say 30 seconds every 100 emails) simply to give the SMTP server a
chance to process its queue and recover some resources.
Using the AntiFlood Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~~
The AntiFlood Plugin -- like all plugins -- is added with the Mailer class's
``registerPlugin()`` method. It takes two constructor parameters: the number of
emails to pause after, and optionally the number of seconds to pause for.
When Swift Mailer sends messages it will count the number of messages that have
been sent since the last re-connect. Once the number hits your specified
threshold it will disconnect and re-connect, optionally pausing for a specified
amount of time::
// Create the Mailer using any Transport
$mailer = new Swift_Mailer(
new Swift_SmtpTransport('smtp.example.org', 25)
);
// Use AntiFlood to re-connect after 100 emails
$mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100));
// And specify a time in seconds to pause for (30 secs)
$mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100, 30));
// Continue sending as normal
for ($lotsOfRecipients as $recipient) {
...
$mailer->send( ... );
}
Throttler Plugin
----------------
If your SMTP server has restrictions in place to limit the rate at which you
send emails, then your code will need to be aware of this rate-limiting. The
Throttler plugin makes Swift Mailer run at a rate-limited speed.
Many shared hosts don't open their SMTP servers as a free-for-all. Usually they
have policies in place (probably to discourage spammers) that only allow you to
send a fixed number of emails per-hour/day.
The Throttler plugin supports two modes of rate-limiting and with each, you
will need to do that math to figure out the values you want. The plugin can
limit based on the number of emails per minute, or the number of
bytes-transferred per-minute.
Using the Throttler Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~~
The Throttler Plugin -- like all plugins -- is added with the Mailer class'
``registerPlugin()`` method. It has two required constructor parameters that
tell it how to do its rate-limiting.
When Swift Mailer sends messages it will keep track of the rate at which
sending messages is occurring. If it realises that sending is happening too
fast, it will cause your program to ``sleep()`` for enough time to average out
the rate::
// Create the Mailer using any Transport
$mailer = new Swift_Mailer(
new Swift_SmtpTransport('smtp.example.org', 25)
);
// Rate limit to 100 emails per-minute
$mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin(
100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE
));
// Rate limit to 10MB per-minute
$mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin(
1024 * 1024 * 10, Swift_Plugins_ThrottlerPlugin::BYTES_PER_MINUTE
));
// Continue sending as normal
for ($lotsOfRecipients as $recipient) {
...
$mailer->send( ... );
}
Logger Plugin
-------------
The Logger plugins helps with debugging during the process of sending. It can
help to identify why an SMTP server is rejecting addresses, or any other
hard-to-find problems that may arise.
The Logger plugin comes in two parts. There's the plugin itself, along with one
of a number of possible Loggers that you may choose to use. For example, the
logger may output messages directly in realtime, or it may capture messages in
an array.
One other notable feature is the way in which the Logger plugin changes
Exception messages. If Exceptions are being thrown but the error message does
not provide conclusive information as to the source of the problem (such as an
ambiguous SMTP error) the Logger plugin includes the entire SMTP transcript in
the error message so that debugging becomes a simpler task.
There are a few available Loggers included with Swift Mailer, but writing your
own implementation is incredibly simple and is achieved by creating a short
class that implements the ``Swift_Plugins_Logger`` interface.
* ``Swift_Plugins_Loggers_ArrayLogger``: Keeps a collection of log messages
inside an array. The array content can be cleared or dumped out to the screen.
* ``Swift_Plugins_Loggers_EchoLogger``: Prints output to the screen in
realtime. Handy for very rudimentary debug output.
Using the Logger Plugin
~~~~~~~~~~~~~~~~~~~~~~~
The Logger Plugin -- like all plugins -- is added with the Mailer class'
``registerPlugin()`` method. It accepts an instance of ``Swift_Plugins_Logger``
in its constructor.
When Swift Mailer sends messages it will keep a log of all the interactions
with the underlying Transport being used. Depending upon the Logger that has
been used the behaviour will differ, but all implementations offer a way to get
the contents of the log::
// Create the Mailer using any Transport
$mailer = new Swift_Mailer(
new Swift_SmtpTransport('smtp.example.org', 25)
);
// To use the ArrayLogger
$logger = new Swift_Plugins_Loggers_ArrayLogger();
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
// Or to use the Echo Logger
$logger = new Swift_Plugins_Loggers_EchoLogger();
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
// Continue sending as normal
for ($lotsOfRecipients as $recipient) {
...
$mailer->send( ... );
}
// Dump the log contents
// NOTE: The EchoLogger dumps in realtime so dump() does nothing for it
echo $logger->dump();
Decorator Plugin
----------------
Often there's a need to send the same message to multiple recipients, but with
tiny variations such as the recipient's name being used inside the message
body. The Decorator plugin aims to provide a solution for allowing these small
differences.
The decorator plugin works by intercepting the sending process of Swift Mailer,
reading the email address in the To: field and then looking up a set of
replacements for a template.
While the use of this plugin is simple, it is probably the most commonly
misunderstood plugin due to the way in which it works. The typical mistake
users make is to try registering the plugin multiple times (once for each
recipient) -- inside a loop for example. This is incorrect.
The Decorator plugin should be registered just once, but containing the list of
all recipients prior to sending. It will use this list of recipients to find
the required replacements during sending.
Using the Decorator Plugin
~~~~~~~~~~~~~~~~~~~~~~~~~~
To use the Decorator plugin, simply create an associative array of replacements
based on email addresses and then use the mailer's ``registerPlugin()`` method
to add the plugin.
First create an associative array of replacements based on the email addresses
you'll be sending the message to.
.. note::
The replacements array becomes a 2-dimensional array whose keys are the
email addresses and whose values are an associative array of replacements
for that email address. The curly braces used in this example can be any
type of syntax you choose, provided they match the placeholders in your
email template::
$replacements = [];
foreach ($users as $user) {
$replacements[$user['email']] = [
'{username}'=>$user['username'],
'{password}'=>$user['password']
];
}
Now create an instance of the Decorator plugin using this array of replacements
and then register it with the Mailer. Do this only once!
::
$decorator = new Swift_Plugins_DecoratorPlugin($replacements);
$mailer->registerPlugin($decorator);
When you create your message, replace elements in the body (and/or the subject
line) with your placeholders::
$message = new Swift_Message()
->setSubject('Important notice for {username}')
->setBody(
"Hello {username}, we have reset your password to {password}\n" .
"Please log in and change it at your earliest convenience."
)
;
foreach ($users as $user) {
$message->addTo($user['email']);
}
When you send this message to each of your recipients listed in your
``$replacements`` array they will receive a message customized for just
themselves. For example, the message used above when received may appear like
this to one user:
.. code-block:: text
Subject: Important notice for smilingsunshine2009
Hello smilingsunshine2009, we have reset your password to rainyDays
Please log in and change it at your earliest convenience.
While another use may receive the message as:
.. code-block:: text
Subject: Important notice for billy-bo-bob
Hello billy-bo-bob, we have reset your password to dancingOctopus
Please log in and change it at your earliest convenience.
While the decorator plugin provides a means to solve this problem, there are
various ways you could tackle this problem without the need for a plugin. We're
trying to come up with a better way ourselves and while we have several
(obvious) ideas we don't quite have the perfect solution to go ahead and
implement it. Watch this space.
Providing Your Own Replacements Lookup for the Decorator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Filling an array with replacements may not be the best solution for providing
replacement information to the decorator. If you have a more elegant algorithm
that performs replacement lookups on-the-fly you may provide your own
implementation.
Providing your own replacements lookup implementation for the Decorator is
simply a matter of passing an instance of
``Swift_Plugins_Decorator_Replacements`` to the decorator plugin's constructor,
rather than passing in an array.
The Replacements interface is very simple to implement since it has just one
method: ``getReplacementsFor($address)``.
Imagine you want to look up replacements from a database on-the-fly, you might
provide an implementation that does this. You need to create a small class::
class DbReplacements implements Swift_Plugins_Decorator_Replacements {
public function getReplacementsFor($address) {
$sql = sprintf(
"SELECT * FROM user WHERE email = '%s'",
mysql_real_escape_string($address)
);
$result = mysql_query($sql);
if ($row = mysql_fetch_assoc($result)) {
return [
'{username}'=>$row['username'],
'{password}'=>$row['password']
];
}
}
}
Now all you need to do is pass an instance of your class into the Decorator
plugin's constructor instead of passing an array::
$decorator = new Swift_Plugins_DecoratorPlugin(new DbReplacements());
$mailer->registerPlugin($decorator);
For each message sent, the plugin will call your class'
``getReplacementsFor()`` method to find the array of replacements it needs.
.. note::
If your lookup algorithm is case sensitive, you should transform the
``$address`` argument as appropriate -- for example by passing it through
``strtolower()``.

View File

@@ -0,0 +1,446 @@
Sending Messages
================
Quick Reference for Sending a Message
-------------------------------------
Sending a message is very straightforward. You create a Transport, use it to
create the Mailer, then you use the Mailer to send the message.
When using ``send()`` the message will be sent just like it would be sent if
you used your mail client. An integer is returned which includes the number of
successful recipients. If none of the recipients could be sent to then zero
will be returned, which equates to a boolean ``false``. If you set two ``To:``
recipients and three ``Bcc:`` recipients in the message and all of the
recipients are delivered to successfully then the value 5 will be returned::
// Create the Transport
$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
->setUsername('your username')
->setPassword('your password')
;
/*
You could alternatively use a different transport such as Sendmail:
// Sendmail
$transport = new Swift_SendmailTransport('/usr/sbin/sendmail -bs');
*/
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = new Swift_Message('Wonderful Subject')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);
Transport Types
~~~~~~~~~~~~~~~
Transports are the classes in Swift Mailer that are responsible for
communicating with a service in order to deliver a Message. There are several
types of Transport in Swift Mailer, all of which implement the
``Swift_Transport`` interface::
* ``Swift_SmtpTransport``: Sends messages over SMTP; Supports Authentication;
Supports Encryption. Very portable; Pleasingly predictable results; Provides
good feedback;
* ``Swift_SendmailTransport``: Communicates with a locally installed
``sendmail`` executable (Linux/UNIX). Quick time-to-run; Provides
less-accurate feedback than SMTP; Requires ``sendmail`` installation;
* ``Swift_LoadBalancedTransport``: Cycles through a collection of the other
Transports to manage load-reduction. Provides graceful fallback if one
Transport fails (e.g. an SMTP server is down); Keeps the load on remote
services down by spreading the work;
* ``Swift_FailoverTransport``: Works in conjunction with a collection of the
other Transports to provide high-availability. Provides graceful fallback if
one Transport fails (e.g. an SMTP server is down).
The SMTP Transport
..................
The SMTP Transport sends messages over the (standardized) Simple Message
Transfer Protocol. It can deal with encryption and authentication.
The SMTP Transport, ``Swift_SmtpTransport`` is without doubt the most commonly
used Transport because it will work on 99% of web servers (I just made that
number up, but you get the idea). All the server needs is the ability to
connect to a remote (or even local) SMTP server on the correct port number
(usually 25).
SMTP servers often require users to authenticate with a username and password
before any mail can be sent to other domains. This is easily achieved using
Swift Mailer with the SMTP Transport.
SMTP is a protocol -- in other words it's a "way" of communicating a job to be
done (i.e. sending a message). The SMTP protocol is the fundamental basis on
which messages are delivered all over the internet 7 days a week, 365 days a
year. For this reason it's the most "direct" method of sending messages you can
use and it's the one that will give you the most power and feedback (such as
delivery failures) when using Swift Mailer.
Because SMTP is generally run as a remote service (i.e. you connect to it over
the network/internet) it's extremely portable from server-to-server. You can
easily store the SMTP server address and port number in a configuration file
within your application and adjust the settings accordingly if the code is
moved or if the SMTP server is changed.
Some SMTP servers -- Google for example -- use encryption for security reasons.
Swift Mailer supports using both SSL and TLS encryption settings.
Using the SMTP Transport
^^^^^^^^^^^^^^^^^^^^^^^^
The SMTP Transport is easy to use. Most configuration options can be set with
the constructor.
To use the SMTP Transport you need to know which SMTP server your code needs to
connect to. Ask your web host if you're not sure. Lots of people ask me who to
connect to -- I really can't answer that since it's a setting that's extremely
specific to your hosting environment.
A connection to the SMTP server will be established upon the first call to
``send()``::
// Create the Transport
$transport = new Swift_SmtpTransport('smtp.example.org', 25);
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
/*
It's also possible to use multiple method calls
$transport = (new Swift_SmtpTransport())
->setHost('smtp.example.org')
->setPort(25)
;
*/
Encrypted SMTP
^^^^^^^^^^^^^^
You can use SSL or TLS encryption with the SMTP Transport by specifying it as a
parameter or with a method call::
// Create the Transport
$transport = new Swift_SmtpTransport('smtp.example.org', 587, 'ssl');
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
A connection to the SMTP server will be established upon the first call to
``send()``. The connection will be initiated with the correct encryption
settings.
.. note::
For SSL or TLS encryption to work your PHP installation must have
appropriate OpenSSL transports wrappers. You can check if "tls" and/or
"ssl" are present in your PHP installation by using the PHP function
``stream_get_transports()``.
SMTP with a Username and Password
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Some servers require authentication. You can provide a username and password
with ``setUsername()`` and ``setPassword()`` methods::
// Create the Transport the call setUsername() and setPassword()
$transport = new Swift_SmtpTransport('smtp.example.org', 25)
->setUsername('username')
->setPassword('password')
;
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
Your username and password will be used to authenticate upon first connect when
``send()`` are first used on the Mailer.
If authentication fails, an Exception of type ``Swift_TransportException`` will
be thrown.
.. note::
If you need to know early whether or not authentication has failed and an
Exception is going to be thrown, call the ``start()`` method on the
created Transport.
The Sendmail Transport
......................
The Sendmail Transport sends messages by communicating with a locally installed
MTA -- such as ``sendmail``.
The Sendmail Transport, ``Swift_SendmailTransport`` does not directly connect
to any remote services. It is designed for Linux servers that have ``sendmail``
installed. The Transport starts a local ``sendmail`` process and sends messages
to it. Usually the ``sendmail`` process will respond quickly as it spools your
messages to disk before sending them.
The Transport is named the Sendmail Transport for historical reasons
(``sendmail`` was the "standard" UNIX tool for sending e-mail for years). It
will send messages using other transfer agents such as Exim or Postfix despite
its name, provided they have the relevant sendmail wrappers so that they can be
started with the correct command-line flags.
It's a common misconception that because the Sendmail Transport returns a
result very quickly it must therefore deliver messages to recipients quickly --
this is not true. It's not slow by any means, but it's certainly not faster
than SMTP when it comes to getting messages to the intended recipients. This is
because sendmail itself sends the messages over SMTP once they have been
quickly spooled to disk.
The Sendmail Transport has the potential to be just as smart of the SMTP
Transport when it comes to notifying Swift Mailer about which recipients were
rejected, but in reality the majority of locally installed ``sendmail``
instances are not configured well enough to provide any useful feedback. As
such Swift Mailer may report successful deliveries where they did in fact fail
before they even left your server.
You can run the Sendmail Transport in two different modes specified by command
line flags:
* "``-bs``" runs in SMTP mode so theoretically it will act like the SMTP
Transport
* "``-t``" runs in piped mode with no feedback, but theoretically faster,
though not advised
You can think of the Sendmail Transport as a sort of asynchronous SMTP
Transport -- though if you have problems with delivery failures you should try
using the SMTP Transport instead. Swift Mailer isn't doing the work here, it's
simply passing the work to somebody else (i.e. ``sendmail``).
Using the Sendmail Transport
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To use the Sendmail Transport you simply need to call ``new
Swift_SendmailTransport()`` with the command as a parameter.
To use the Sendmail Transport you need to know where ``sendmail`` or another
MTA exists on the server. Swift Mailer uses a default value of
``/usr/sbin/sendmail``, which should work on most systems.
You specify the entire command as a parameter (i.e. including the command line
flags). Swift Mailer supports operational modes of "``-bs``" (default) and
"``-t``".
.. note::
If you run sendmail in "``-t``" mode you will get no feedback as to whether
or not sending has succeeded. Use "``-bs``" unless you have a reason not to.
A sendmail process will be started upon the first call to ``send()``. If the
process cannot be started successfully an Exception of type
``Swift_TransportException`` will be thrown::
// Create the Transport
$transport = new Swift_SendmailTransport('/usr/sbin/exim -bs');
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
Available Methods for Sending Messages
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Mailer class offers one method for sending Messages -- ``send()``.
When a message is sent in Swift Mailer, the Mailer class communicates with
whichever Transport class you have chosen to use.
Each recipient in the message should either be accepted or rejected by the
Transport. For example, if the domain name on the email address is not
reachable the SMTP Transport may reject the address because it cannot process
it. ``send()`` will return an integer indicating the number of accepted
recipients.
.. note::
It's possible to find out which recipients were rejected -- we'll cover that
later in this chapter.
Using the ``send()`` Method
...........................
The ``send()`` method of the ``Swift_Mailer`` class sends a message using
exactly the same logic as your Desktop mail client would use. Just pass it a
Message and get a result.
The message will be sent just like it would be sent if you used your mail
client. An integer is returned which includes the number of successful
recipients. If none of the recipients could be sent to then zero will be
returned, which equates to a boolean ``false``. If you set two
``To:`` recipients and three ``Bcc:`` recipients in the message and all of the
recipients are delivered to successfully then the value 5 will be returned::
// Create the Transport
$transport = new Swift_SmtpTransport('localhost', 25);
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = new Swift_Message('Wonderful Subject')
->setFrom(['john@doe.com' => 'John Doe'])
->setTo(['receiver@domain.org', 'other@domain.org' => 'A name'])
->setBody('Here is the message itself')
;
// Send the message
$numSent = $mailer->send($message);
printf("Sent %d messages\n", $numSent);
/* Note that often that only the boolean equivalent of the
return value is of concern (zero indicates FALSE)
if ($mailer->send($message))
{
echo "Sent\n";
}
else
{
echo "Failed\n";
}
*/
Sending Emails in Batch
.......................
If you want to send a separate message to each recipient so that only their own
address shows up in the ``To:`` field, follow the following recipe:
* Create a Transport from one of the provided Transports --
``Swift_SmtpTransport``, ``Swift_SendmailTransport``,
or one of the aggregate Transports.
* Create an instance of the ``Swift_Mailer`` class, using the Transport as
it's constructor parameter.
* Create a Message.
* Iterate over the recipients and send message via the ``send()`` method on
the Mailer object.
Each recipient of the messages receives a different copy with only their own
email address on the ``To:`` field.
Make sure to add only valid email addresses as recipients. If you try to add an
invalid email address with ``setTo()``, ``setCc()`` or ``setBcc()``, Swift
Mailer will throw a ``Swift_RfcComplianceException``.
If you add recipients automatically based on a data source that may contain
invalid email addresses, you can prevent possible exceptions by validating the
addresses using ``Swift_Validate::email($email)`` and only adding addresses
that validate. Another way would be to wrap your ``setTo()``, ``setCc()`` and
``setBcc()`` calls in a try-catch block and handle the
``Swift_RfcComplianceException`` in the catch block.
Handling invalid addresses properly is especially important when sending emails
in large batches since a single invalid address might cause an unhandled
exception and stop the execution or your script early.
.. note::
In the following example, two emails are sent. One to each of
``receiver@domain.org`` and ``other@domain.org``. These recipients will
not be aware of each other::
// Create the Transport
$transport = new Swift_SmtpTransport('localhost', 25);
// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);
// Create a message
$message = new Swift_Message('Wonderful Subject')
->setFrom(['john@doe.com' => 'John Doe'])
->setBody('Here is the message itself')
;
// Send the message
$failedRecipients = [];
$numSent = 0;
$to = ['receiver@domain.org', 'other@domain.org' => 'A name'];
foreach ($to as $address => $name)
{
if (is_int($address)) {
$message->setTo($name);
} else {
$message->setTo([$address => $name]);
}
$numSent += $mailer->send($message, $failedRecipients);
}
printf("Sent %d messages\n", $numSent);
Finding out Rejected Addresses
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's possible to get a list of addresses that were rejected by the Transport by
using a by-reference parameter to ``send()``.
As Swift Mailer attempts to send the message to each address given to it, if a
recipient is rejected it will be added to the array. You can pass an existing
array, otherwise one will be created by-reference.
Collecting the list of recipients that were rejected can be useful in
circumstances where you need to "prune" a mailing list for example when some
addresses cannot be delivered to.
Getting Failures By-reference
.............................
Collecting delivery failures by-reference with the ``send()`` method is as
simple as passing a variable name to the method call::
$mailer = new Swift_Mailer( ... );
$message = (new Swift_Message( ... ))
->setFrom( ... )
->setTo([
'receiver@bad-domain.org' => 'Receiver Name',
'other@domain.org' => 'A name',
'other-receiver@bad-domain.org' => 'Other Name'
))
->setBody( ... )
;
// Pass a variable name to the send() method
if (!$mailer->send($message, $failures))
{
echo "Failures:";
print_r($failures);
}
/*
Failures:
Array (
0 => receiver@bad-domain.org,
1 => other-receiver@bad-domain.org
)
*/
If the Transport rejects any of the recipients, the culprit addresses will be
added to the array provided by-reference.
.. note::
If the variable name does not yet exist, it will be initialized as an
empty array and then failures will be added to that array. If the variable
already exists it will be type-cast to an array and failures will be added
to it.

View File

@@ -0,0 +1,79 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* General utility class in Swift Mailer, not to be instantiated.
*
*
* @author Chris Corbyn
*/
abstract class Swift
{
const VERSION = '6.0.1';
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

@@ -0,0 +1,57 @@
<?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_SimpleMessage}.
*
* @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 from a filesystem path.
*
* @param string $path
* @param string $contentType optional
*
* @return Swift_Mime_Attachment
*/
public static function fromPath($path, $contentType = null)
{
return (new self())->setFile(
new Swift_ByteStream_FileByteStream($path),
$contentType
);
}
}

View File

@@ -0,0 +1,181 @@
<?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 doCommit($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->doCommit($this->filter($bytes));
foreach ($this->mirrors as $stream) {
$stream->write($bytes);
}
$this->writeBuffer = '';
}
}

View File

@@ -0,0 +1,182 @@
<?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

@@ -0,0 +1,216 @@
<?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 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';
}
/**
* 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
*
* @return string|bool
*
* @throws Swift_IoException
*/
public function read($length)
{
$fp = $this->getReadHandle();
if (!feof($fp)) {
$bytes = fread($fp, $length);
$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 doCommit($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

@@ -0,0 +1,42 @@
<?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

@@ -0,0 +1,67 @@
<?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 int[] $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

@@ -0,0 +1,97 @@
<?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

@@ -0,0 +1,84 @@
<?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

@@ -0,0 +1,176 @@
<?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

@@ -0,0 +1,26 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,124 @@
<?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

@@ -0,0 +1,89 @@
<?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

@@ -0,0 +1,293 @@
<?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 int[]
*/
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

@@ -0,0 +1,267 @@
<?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

@@ -0,0 +1,63 @@
<?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

@@ -0,0 +1,373 @@
<?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 self
*/
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
*
* @return mixed
*
* @throws Swift_DependencyException If the dependency is not found
*/
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 $this
*/
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 $this
*/
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 $this
*/
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 $this
*/
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 $this
*/
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 $this
*/
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 $this
*/
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 $this
*/
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

@@ -0,0 +1,27 @@
<?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

@@ -0,0 +1,53 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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 from a filesystem path.
*
* @param string $path
*
* @return Swift_Mime_EmbeddedFile
*/
public static function fromPath($path)
{
return (new self())->setFile(new Swift_ByteStream_FileByteStream($path));
}
}

View File

@@ -0,0 +1,28 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,58 @@
<?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

@@ -0,0 +1,300 @@
<?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) Encoding in Swift Mailer.
*
* Possibly the most accurate RFC 2045 QP implementation found in PHP.
*
* @author Chris Corbyn
*/
class Swift_Encoder_QpEncoder implements Swift_Encoder
{
/**
* The CharacterStream used for reading characters (as opposed to bytes).
*
* @var Swift_CharacterStream
*/
protected $charStream;
/**
* A filter used if input should be canonicalized.
*
* @var Swift_StreamFilter
*/
protected $filter;
/**
* Pre-computed QP for HUGE optimization.
*
* @var string[]
*/
protected static $qpMap = array(
0 => '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04',
5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09',
10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E',
15 => '=0F', 16 => '=10', 17 => '=11', 18 => '=12', 19 => '=13',
20 => '=14', 21 => '=15', 22 => '=16', 23 => '=17', 24 => '=18',
25 => '=19', 26 => '=1A', 27 => '=1B', 28 => '=1C', 29 => '=1D',
30 => '=1E', 31 => '=1F', 32 => '=20', 33 => '=21', 34 => '=22',
35 => '=23', 36 => '=24', 37 => '=25', 38 => '=26', 39 => '=27',
40 => '=28', 41 => '=29', 42 => '=2A', 43 => '=2B', 44 => '=2C',
45 => '=2D', 46 => '=2E', 47 => '=2F', 48 => '=30', 49 => '=31',
50 => '=32', 51 => '=33', 52 => '=34', 53 => '=35', 54 => '=36',
55 => '=37', 56 => '=38', 57 => '=39', 58 => '=3A', 59 => '=3B',
60 => '=3C', 61 => '=3D', 62 => '=3E', 63 => '=3F', 64 => '=40',
65 => '=41', 66 => '=42', 67 => '=43', 68 => '=44', 69 => '=45',
70 => '=46', 71 => '=47', 72 => '=48', 73 => '=49', 74 => '=4A',
75 => '=4B', 76 => '=4C', 77 => '=4D', 78 => '=4E', 79 => '=4F',
80 => '=50', 81 => '=51', 82 => '=52', 83 => '=53', 84 => '=54',
85 => '=55', 86 => '=56', 87 => '=57', 88 => '=58', 89 => '=59',
90 => '=5A', 91 => '=5B', 92 => '=5C', 93 => '=5D', 94 => '=5E',
95 => '=5F', 96 => '=60', 97 => '=61', 98 => '=62', 99 => '=63',
100 => '=64', 101 => '=65', 102 => '=66', 103 => '=67', 104 => '=68',
105 => '=69', 106 => '=6A', 107 => '=6B', 108 => '=6C', 109 => '=6D',
110 => '=6E', 111 => '=6F', 112 => '=70', 113 => '=71', 114 => '=72',
115 => '=73', 116 => '=74', 117 => '=75', 118 => '=76', 119 => '=77',
120 => '=78', 121 => '=79', 122 => '=7A', 123 => '=7B', 124 => '=7C',
125 => '=7D', 126 => '=7E', 127 => '=7F', 128 => '=80', 129 => '=81',
130 => '=82', 131 => '=83', 132 => '=84', 133 => '=85', 134 => '=86',
135 => '=87', 136 => '=88', 137 => '=89', 138 => '=8A', 139 => '=8B',
140 => '=8C', 141 => '=8D', 142 => '=8E', 143 => '=8F', 144 => '=90',
145 => '=91', 146 => '=92', 147 => '=93', 148 => '=94', 149 => '=95',
150 => '=96', 151 => '=97', 152 => '=98', 153 => '=99', 154 => '=9A',
155 => '=9B', 156 => '=9C', 157 => '=9D', 158 => '=9E', 159 => '=9F',
160 => '=A0', 161 => '=A1', 162 => '=A2', 163 => '=A3', 164 => '=A4',
165 => '=A5', 166 => '=A6', 167 => '=A7', 168 => '=A8', 169 => '=A9',
170 => '=AA', 171 => '=AB', 172 => '=AC', 173 => '=AD', 174 => '=AE',
175 => '=AF', 176 => '=B0', 177 => '=B1', 178 => '=B2', 179 => '=B3',
180 => '=B4', 181 => '=B5', 182 => '=B6', 183 => '=B7', 184 => '=B8',
185 => '=B9', 186 => '=BA', 187 => '=BB', 188 => '=BC', 189 => '=BD',
190 => '=BE', 191 => '=BF', 192 => '=C0', 193 => '=C1', 194 => '=C2',
195 => '=C3', 196 => '=C4', 197 => '=C5', 198 => '=C6', 199 => '=C7',
200 => '=C8', 201 => '=C9', 202 => '=CA', 203 => '=CB', 204 => '=CC',
205 => '=CD', 206 => '=CE', 207 => '=CF', 208 => '=D0', 209 => '=D1',
210 => '=D2', 211 => '=D3', 212 => '=D4', 213 => '=D5', 214 => '=D6',
215 => '=D7', 216 => '=D8', 217 => '=D9', 218 => '=DA', 219 => '=DB',
220 => '=DC', 221 => '=DD', 222 => '=DE', 223 => '=DF', 224 => '=E0',
225 => '=E1', 226 => '=E2', 227 => '=E3', 228 => '=E4', 229 => '=E5',
230 => '=E6', 231 => '=E7', 232 => '=E8', 233 => '=E9', 234 => '=EA',
235 => '=EB', 236 => '=EC', 237 => '=ED', 238 => '=EE', 239 => '=EF',
240 => '=F0', 241 => '=F1', 242 => '=F2', 243 => '=F3', 244 => '=F4',
245 => '=F5', 246 => '=F6', 247 => '=F7', 248 => '=F8', 249 => '=F9',
250 => '=FA', 251 => '=FB', 252 => '=FC', 253 => '=FD', 254 => '=FE',
255 => '=FF',
);
protected static $safeMapShare = array();
/**
* A map of non-encoded ascii characters.
*
* @var string[]
*/
protected $safeMap = array();
/**
* Creates a new QpEncoder for the given CharacterStream.
*
* @param Swift_CharacterStream $charStream to use for reading characters
* @param Swift_StreamFilter $filter if input should be canonicalized
*/
public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null)
{
$this->charStream = $charStream;
if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) {
$this->initSafeMap();
self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap;
} else {
$this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()];
}
$this->filter = $filter;
}
public function __sleep()
{
return array('charStream', 'filter');
}
public function __wakeup()
{
if (!isset(self::$safeMapShare[$this->getSafeMapShareId()])) {
$this->initSafeMap();
self::$safeMapShare[$this->getSafeMapShareId()] = $this->safeMap;
} else {
$this->safeMap = self::$safeMapShare[$this->getSafeMapShareId()];
}
}
protected function getSafeMapShareId()
{
return get_class($this);
}
protected function initSafeMap()
{
foreach (array_merge(
array(0x09, 0x20), range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) {
$this->safeMap[$byte] = chr($byte);
}
}
/**
* Takes an unencoded string and produces a QP encoded string from it.
*
* 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 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)
{
if ($maxLineLength > 76 || $maxLineLength <= 0) {
$maxLineLength = 76;
}
$thisLineLength = $maxLineLength - $firstLineOffset;
$lines = array();
$lNo = 0;
$lines[$lNo] = '';
$currentLine = &$lines[$lNo++];
$size = $lineLen = 0;
$this->charStream->flushContents();
$this->charStream->importString($string);
// Fetching more than 4 chars at one is slower, as is fetching fewer bytes
// Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6
// bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes
while (false !== $bytes = $this->nextSequence()) {
// 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) {
$lines[$lNo] = '';
$currentLine = &$lines[$lNo++];
$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;
}
}
return $this->standardize(implode("=\r\n", $lines));
}
/**
* Updates the charset used.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->charStream->setCharacterSet($charset);
}
/**
* Encode the given byte array into a verbatim QP form.
*
* @param int[] $bytes
* @param int $size
*
* @return string
*/
protected function encodeByteSequence(array $bytes, &$size)
{
$ret = '';
$size = 0;
foreach ($bytes as $b) {
if (isset($this->safeMap[$b])) {
$ret .= $this->safeMap[$b];
++$size;
} else {
$ret .= self::$qpMap[$b];
$size += 3;
}
}
return $ret;
}
/**
* Get the next sequence of bytes to read from the char stream.
*
* @param int $size number of bytes to read
*
* @return int[]
*/
protected function nextSequence($size = 4)
{
return $this->charStream->readBytes($size);
}
/**
* Make sure CRLF is correct and HT/SPACE are in valid places.
*
* @param string $string
*
* @return string
*/
protected function standardize($string)
{
$string = str_replace(array("\t=0D=0A", ' =0D=0A', '=0D=0A'),
array("=09\r\n", "=20\r\n", "\r\n"), $string
);
switch ($end = ord(substr($string, -1))) {
case 0x09:
case 0x20:
$string = substr_replace($string, self::$qpMap[$end], -1);
}
return $string;
}
/**
* Make a deep copy of object.
*/
public function __clone()
{
$this->charStream = clone $this->charStream;
}
}

View File

@@ -0,0 +1,92 @@
<?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

@@ -0,0 +1,65 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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 int[]
*/
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 int[]
*/
public function getSuccessCodes()
{
return $this->successCodes;
}
}

View File

@@ -0,0 +1,24 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,38 @@
<?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

@@ -0,0 +1,83 @@
<?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_SimpleMessage
*
* @return Swift_Events_SendEvent
*/
public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $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

@@ -0,0 +1,18 @@
<?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

@@ -0,0 +1,63 @@
<?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

@@ -0,0 +1,65 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,24 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,129 @@
<?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_SimpleMessage
*/
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_SimpleMessage $message
*/
public function __construct(Swift_Transport $source, Swift_Mime_SimpleMessage $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_SimpleMessage
*/
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

@@ -0,0 +1,31 @@
<?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

@@ -0,0 +1,156 @@
<?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_SimpleMessage
*
* @return Swift_Events_SendEvent
*/
public function createSendEvent(Swift_Transport $source, Swift_Mime_SimpleMessage $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

@@ -0,0 +1,27 @@
<?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

@@ -0,0 +1,45 @@
<?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

@@ -0,0 +1,46 @@
<?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

@@ -0,0 +1,24 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,33 @@
<?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);
}
}

View File

@@ -0,0 +1,208 @@
<?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_SimpleMessage $message The message to store
*
* @throws Swift_IoException
*
* @return bool
*/
public function queueMessage(Swift_Mime_SimpleMessage $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

@@ -0,0 +1,24 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,32 @@
<?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

@@ -0,0 +1,22 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Message ID generator.
*/
interface Swift_IdGenerator
{
/**
* Returns a globally unique string to use for Message-ID or Content-ID.
*
* @return string
*/
public function generateId();
}

View File

@@ -0,0 +1,43 @@
<?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 from a filesystem path.
*
* @param string $path
*
* @return self
*/
public static function fromPath($path)
{
return (new self())->setFile(new Swift_ByteStream_FileByteStream($path));
}
}

View File

@@ -0,0 +1,75 @@
<?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

@@ -0,0 +1,29 @@
<?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

@@ -0,0 +1,105 @@
<?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

@@ -0,0 +1,206 @@
<?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

@@ -0,0 +1,298 @@
<?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();
/**
* 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;
}
/**
* 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);
$str = '';
while (!feof($fp) && false !== $bytes = fread($fp, 8192)) {
$str .= $bytes;
}
$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);
while (!feof($fp) && false !== $bytes = fread($fp, 8192)) {
$is->write($bytes);
}
$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

@@ -0,0 +1,51 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,115 @@
<?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

@@ -0,0 +1,127 @@
<?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

@@ -0,0 +1,33 @@
<?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);
}
}

View File

@@ -0,0 +1,102 @@
<?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 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_SimpleMessage $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_SimpleMessage $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

@@ -0,0 +1,55 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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

@@ -0,0 +1,32 @@
<?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

@@ -0,0 +1,110 @@
<?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_SimpleMessage $message The message to store
*
* @return bool Whether the operation has succeeded
*/
public function queueMessage(Swift_Mime_SimpleMessage $message)
{
//clone the message to make sure it is not changed while in the queue
$this->messages[] = clone $message;
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

@@ -0,0 +1,274 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* 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);
}
}
/**
* Add a MimePart to this Message.
*
* @param string|Swift_OutputByteStream $body
* @param string $contentType
* @param string $charset
*
* @return $this
*/
public function addPart($body, $contentType = null, $charset = null)
{
return $this->attach((new Swift_MimePart($body, $contentType, $charset))->setEncoder($this->getEncoder()));
}
/**
* Detach a signature handler from a message.
*
* @param Swift_Signer $signer
*
* @return $this
*/
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 $this
*/
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

@@ -0,0 +1,149 @@
<?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_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param array $mimeTypes
*/
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array())
{
parent::__construct($headers, $encoder, $cache, $idGenerator);
$this->setDisposition('attachment');
$this->setContentType('application/octet-stream');
$this->mimeTypes = $mimeTypes;
}
/**
* Get the nesting level used for this attachment.
*
* Always returns {@link LEVEL_MIXED}.
*
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_MIXED;
}
/**
* Get the Content-Disposition of this attachment.
*
* By default attachments have a disposition of "attachment".
*
* @return string
*/
public function getDisposition()
{
return $this->getHeaderFieldModel('Content-Disposition');
}
/**
* Set the Content-Disposition of this attachment.
*
* @param string $disposition
*
* @return $this
*/
public function setDisposition($disposition)
{
if (!$this->setHeaderFieldModel('Content-Disposition', $disposition)) {
$this->getHeaders()->addParameterizedHeader('Content-Disposition', $disposition);
}
return $this;
}
/**
* Get the filename of this attachment when downloaded.
*
* @return string
*/
public function getFilename()
{
return $this->getHeaderParameter('Content-Disposition', 'filename');
}
/**
* Set the filename of this attachment.
*
* @param string $filename
*
* @return $this
*/
public function setFilename($filename)
{
$this->setHeaderParameter('Content-Disposition', 'filename', $filename);
$this->setHeaderParameter('Content-Type', 'name', $filename);
return $this;
}
/**
* Get the file size of this attachment.
*
* @return int
*/
public function getSize()
{
return $this->getHeaderParameter('Content-Disposition', 'size');
}
/**
* Set the file size of this attachment.
*
* @param int $size
*
* @return $this
*/
public function setSize($size)
{
$this->setHeaderParameter('Content-Disposition', 'size', $size);
return $this;
}
/**
* Set the file that this attachment is for.
*
* @param Swift_FileStream $file
* @param string $contentType optional
*
* @return $this
*/
public function setFile(Swift_FileStream $file, $contentType = null)
{
$this->setFilename(basename($file->getPath()));
$this->setBody($file, $contentType);
if (!isset($contentType)) {
$extension = strtolower(substr($file->getPath(), strrpos($file->getPath(), '.') + 1));
if (array_key_exists($extension, $this->mimeTypes)) {
$this->setContentType($this->mimeTypes[$extension]);
}
}
return $this;
}
}

View File

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

View File

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

View File

@@ -0,0 +1,104 @@
<?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

@@ -0,0 +1,123 @@
<?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

@@ -0,0 +1,162 @@
<?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

@@ -0,0 +1,134 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Quoted Printable (QP) Transfer Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_ContentEncoder_QpContentEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_ContentEncoder
{
protected $dotEscape;
/**
* Creates a new QpContentEncoder for the given CharacterStream.
*
* @param Swift_CharacterStream $charStream to use for reading characters
* @param Swift_StreamFilter $filter if canonicalization should occur
* @param bool $dotEscape if dot stuffing workaround must be enabled
*/
public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null, $dotEscape = false)
{
$this->dotEscape = $dotEscape;
parent::__construct($charStream, $filter);
}
public function __sleep()
{
return 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

@@ -0,0 +1,98 @@
<?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

@@ -0,0 +1,64 @@
<?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

@@ -0,0 +1,45 @@
<?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_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param array $mimeTypes optional
*/
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $mimeTypes = array())
{
parent::__construct($headers, $encoder, $cache, $idGenerator, $mimeTypes);
$this->setDisposition('inline');
$this->setId($this->getId());
}
/**
* Get the nesting level of this EmbeddedFile.
*
* Returns {@see LEVEL_RELATED}.
*
* @return int
*/
public function getNestingLevel()
{
return self::LEVEL_RELATED;
}
}

View File

@@ -0,0 +1,24 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Observes changes 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

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

View File

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

View File

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

@@ -0,0 +1,65 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Handles Quoted Printable (Q) Header Encoding in Swift Mailer.
*
* @author Chris Corbyn
*/
class Swift_Mime_HeaderEncoder_QpHeaderEncoder extends Swift_Encoder_QpEncoder implements Swift_Mime_HeaderEncoder
{
/**
* Creates a new QpHeaderEncoder for the given CharacterStream.
*
* @param Swift_CharacterStream $charStream to use for reading characters
*/
public function __construct(Swift_CharacterStream $charStream)
{
parent::__construct($charStream);
}
protected function initSafeMap()
{
foreach (array_merge(
range(0x61, 0x7A), range(0x41, 0x5A),
range(0x30, 0x39), 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

@@ -0,0 +1,481 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An abstract base MIME Header.
*
* @author Chris Corbyn
*/
abstract class Swift_Mime_Headers_AbstractHeader implements Swift_Mime_Header
{
const PHRASE_PATTERN = '(?:(?:(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]+(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?)|(?:(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?"((?:(?:[ \t]*(?:\r\n))?[ \t])?(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21\x23-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])))*(?:(?:[ \t]*(?:\r\n))?[ \t])?"(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))*(?:(?:(?:(?:[ \t]*(?:\r\n))?[ \t])?(\((?:(?:(?:[ \t]*(?:\r\n))?[ \t])|(?:(?:[\x01-\x08\x0B\x0C\x0E-\x19\x7F]|[\x21-\x27\x2A-\x5B\x5D-\x7E])|(?:\\[\x00-\x08\x0B\x0C\x0E-\x7F])|(?1)))*(?:(?:[ \t]*(?:\r\n))?[ \t])?\)))|(?:(?:[ \t]*(?:\r\n))?[ \t])))?))+?)';
/**
* The name of this Header.
*
* @var string
*/
private $name;
/**
* The Encoder used to encode this Header.
*
* @var Swift_Encoder
*/
private $encoder;
/**
* The maximum length of a line in the header.
*
* @var int
*/
private $lineLength = 78;
/**
* The language used in this Header.
*
* @var string
*/
private $lang;
/**
* The character set of the text in this Header.
*
* @var string
*/
private $charset = 'utf-8';
/**
* The value of this Header, cached.
*
* @var string
*/
private $cachedValue = null;
/**
* Set the character set used in this Header.
*
* @param string $charset
*/
public function setCharset($charset)
{
$this->clearCachedValueIf($charset != $this->charset);
$this->charset = $charset;
if (isset($this->encoder)) {
$this->encoder->charsetChanged($charset);
}
}
/**
* Get the character set used in this Header.
*
* @return string
*/
public function getCharset()
{
return $this->charset;
}
/**
* Set the language used in this Header.
*
* For example, for US English, 'en-us'.
* This can be unspecified.
*
* @param string $lang
*/
public function setLanguage($lang)
{
$this->clearCachedValueIf($this->lang != $lang);
$this->lang = $lang;
}
/**
* Get the language used in this Header.
*
* @return string
*/
public function getLanguage()
{
return $this->lang;
}
/**
* Set the encoder used for encoding the header.
*
* @param Swift_Mime_HeaderEncoder $encoder
*/
public function setEncoder(Swift_Mime_HeaderEncoder $encoder)
{
$this->encoder = $encoder;
$this->setCachedValue(null);
}
/**
* Get the encoder used for encoding this Header.
*
* @return Swift_Mime_HeaderEncoder
*/
public function getEncoder()
{
return $this->encoder;
}
/**
* Get the name of this header (e.g. charset).
*
* @return string
*/
public function getFieldName()
{
return $this->name;
}
/**
* Set the maximum length of lines in the header (excluding EOL).
*
* @param int $lineLength
*/
public function setMaxLineLength($lineLength)
{
$this->clearCachedValueIf($this->lineLength != $lineLength);
$this->lineLength = $lineLength;
}
/**
* Get the maximum permitted length of lines in this Header.
*
* @return int
*/
public function getMaxLineLength()
{
return $this->lineLength;
}
/**
* Get this Header rendered as a RFC 2822 compliant string.
*
* @return string
*
* @throws Swift_RfcComplianceException
*/
public function toString()
{
return $this->tokensToString($this->toTokens());
}
/**
* Returns a string representation of this object.
*
* @return string
*
* @see toString()
*/
public function __toString()
{
return $this->toString();
}
/**
* 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('/^'.self::PHRASE_PATTERN.'$/D', $phraseStr)) {
// .. but it is just ascii text, try escaping some characters
// and make it a quoted-string
if (preg_match('/^[\x00-\x08\x0B\x0C\x0E-\x7F]*$/D', $phraseStr)) {
$phraseStr = $this->escapeSpecials($phraseStr, array('"'));
$phraseStr = '"'.$phraseStr.'"';
} else {
// ... otherwise it needs encoding
// Determine space remaining on line if first line
if ($shorten) {
$usedLength = strlen($header->getFieldName().': ');
} else {
$usedLength = 0;
}
$phraseStr = $this->encodeWords($header, $string, $usedLength);
}
}
return $phraseStr;
}
/**
* Escape special characters in a string (convert to quoted-pairs).
*
* @param string $token
* @param string[] $include additional chars to escape
*
* @return string
*/
private function escapeSpecials($token, $include = array())
{
foreach (array_merge(array('\\'), $include) as $char) {
$token = str_replace($char, '\\'.$char, $token);
}
return $token;
}
/**
* Encode needed word tokens within a string of input.
*
* @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 (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

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

View File

@@ -0,0 +1,184 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
/**
* 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();
/**
* The strict EmailValidator.
*
* @var EmailValidator
*/
private $emailValidator;
/**
* Creates a new IdentificationHeader with the given $name and $id.
*
* @param string $name
* @param EmailValidator $emailValidator
*/
public function __construct($name, EmailValidator $emailValidator)
{
$this->setFieldName($name);
$this->emailValidator = $emailValidator;
}
/**
* 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 (!$this->emailValidator->isValid($id, new RFCValidation())) {
throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>');
}
}
}

View File

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

View File

@@ -0,0 +1,133 @@
<?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

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

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

View File

@@ -0,0 +1,110 @@
<?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
*/
public function __construct($name, Swift_Mime_HeaderEncoder $encoder)
{
$this->setFieldName($name);
$this->setEncoder($encoder);
}
/**
* Get the type of Header that this instance represents.
*
* @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
* @see TYPE_DATE, TYPE_ID, TYPE_PATH
*
* @return int
*/
public function getFieldType()
{
return self::TYPE_TEXT;
}
/**
* Set the model for the field body.
*
* This method takes a string for the field value.
*
* @param string $model
*/
public function setFieldBodyModel($model)
{
$this->setValue($model);
}
/**
* Get the model for the field body.
*
* This method returns a string.
*
* @return string
*/
public function getFieldBodyModel()
{
return $this->getValue();
}
/**
* Get the (unencoded) value of this header.
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set the (unencoded) value of this header.
*
* @param string $value
*/
public function setValue($value)
{
$this->clearCachedValueIf($this->value != $value);
$this->value = $value;
}
/**
* Get the value of this header prepared for rendering.
*
* @return string
*/
public function getFieldBody()
{
if (!$this->getCachedValue()) {
$this->setCachedValue(
$this->encodeWords($this, $this->value)
);
}
return $this->getCachedValue();
}
}

View File

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

View File

@@ -0,0 +1,212 @@
<?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_SimpleHeaderSet $headers
* @param Swift_Mime_ContentEncoder $encoder
* @param Swift_KeyCache $cache
* @param Swift_IdGenerator $idGenerator
* @param string $charset
*/
public function __construct(Swift_Mime_SimpleHeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_IdGenerator $idGenerator, $charset = null)
{
parent::__construct($headers, $encoder, $cache, $idGenerator);
$this->setContentType('text/plain');
if (null !== $charset) {
$this->setCharset($charset);
}
}
/**
* Set the body of this entity, either as a string, or as an instance of
* {@link Swift_OutputByteStream}.
*
* @param mixed $body
* @param string $contentType optional
* @param string $charset optional
*
* @return $this
*/
public function setBody($body, $contentType = null, $charset = null)
{
if (isset($charset)) {
$this->setCharset($charset);
}
$body = $this->convertString($body);
parent::setBody($body, $contentType);
return $this;
}
/**
* Get the character set of this entity.
*
* @return string
*/
public function getCharset()
{
return $this->getHeaderParameter('Content-Type', 'charset');
}
/**
* Set the character set of this entity.
*
* @param string $charset
*
* @return $this
*/
public function setCharset($charset)
{
$this->setHeaderParameter('Content-Type', 'charset', $charset);
if ($charset !== $this->userCharset) {
$this->clearCache();
}
$this->userCharset = $charset;
parent::charsetChanged($charset);
return $this;
}
/**
* Get the format of this entity (i.e. flowed or fixed).
*
* @return string
*/
public function getFormat()
{
return $this->getHeaderParameter('Content-Type', 'format');
}
/**
* Set the format of this entity (flowed or fixed).
*
* @param string $format
*
* @return $this
*/
public function setFormat($format)
{
$this->setHeaderParameter('Content-Type', 'format', $format);
$this->userFormat = $format;
return $this;
}
/**
* Test if delsp is being used for this entity.
*
* @return bool
*/
public function getDelSp()
{
return 'yes' == $this->getHeaderParameter('Content-Type', 'delsp') ? true : false;
}
/**
* Turn delsp on or off for this entity.
*
* @param bool $delsp
*
* @return $this
*/
public function setDelSp($delsp = true)
{
$this->setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null);
$this->userDelSp = $delsp;
return $this;
}
/**
* Get the nesting level of this entity.
*
* @see LEVEL_TOP, LEVEL_ALTERNATIVE, LEVEL_MIXED, LEVEL_RELATED
*
* @return int
*/
public function getNestingLevel()
{
return $this->nestingLevel;
}
/**
* Receive notification that the charset has changed on this document, or a
* parent document.
*
* @param string $charset
*/
public function charsetChanged($charset)
{
$this->setCharset($charset);
}
/** Fix the content-type and encoding of this entity */
protected function fixHeaders()
{
parent::fixHeaders();
if (count($this->getChildren())) {
$this->setHeaderParameter('Content-Type', 'charset', null);
$this->setHeaderParameter('Content-Type', 'format', null);
$this->setHeaderParameter('Content-Type', 'delsp', null);
} else {
$this->setCharset($this->userCharset);
$this->setFormat($this->userFormat);
$this->setDelSp($this->userDelSp);
}
}
/** Set the nesting level of this entity */
protected function setNestingLevel($level)
{
$this->nestingLevel = $level;
}
/** Encode charset when charset is not utf-8 */
protected function convertString($string)
{
$charset = strtolower($this->getCharset());
if (!in_array($charset, 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

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

View File

@@ -0,0 +1,409 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2004-2009 Chris Corbyn
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A collection of MIME headers.
*
* @author Chris Corbyn
*/
class Swift_Mime_SimpleHeaderSet implements Swift_Mime_CharsetObserver
{
/** HeaderFactory */
private $factory;
/** Collection of set Headers */
private $headers = 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_SimpleHeaderFactory $factory
* @param string $charset
*/
public function __construct(Swift_Mime_SimpleHeaderFactory $factory, $charset = null)
{
$this->factory = $factory;
if (isset($charset)) {
$this->setCharset($charset);
}
}
public function newInstance()
{
return new self($this->factory);
}
/**
* Set the charset used by these headers.
*
* @param string $charset
*/
public function setCharset($charset)
{
$this->charset = $charset;
$this->factory->charsetChanged($charset);
$this->notifyHeadersOfCharset($charset);
}
/**
* Add a new Mailbox Header with a list of $addresses.
*
* @param string $name
* @param array|string $addresses
*/
public function addMailboxHeader($name, $addresses = null)
{
$this->storeHeader($name,
$this->factory->createMailboxHeader($name, $addresses));
}
/**
* Add a new Date header using $dateTime.
*
* @param string $name
* @param DateTimeInterface $dateTime
*/
public function addDateHeader($name, DateTimeInterface $dateTime = null)
{
$this->storeHeader($name,
$this->factory->createDateHeader($name, $dateTime));
}
/**
* Add a new basic text header with $name and $value.
*
* @param string $name
* @param string $value
*/
public function addTextHeader($name, $value = null)
{
$this->storeHeader($name,
$this->factory->createTextHeader($name, $value));
}
/**
* Add a new ParameterizedHeader with $name, $value and $params.
*
* @param string $name
* @param string $value
* @param array $params
*/
public function addParameterizedHeader($name, $value = null, $params = 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]);
}
/**
* 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;
}
}
}
}

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