This commit is contained in:
Simon Vieille 2016-03-30 21:15:06 +02:00
parent c7d277fc9d
commit 9f0686c679
7 changed files with 1482 additions and 6 deletions

57
LICENSE
View File

@ -1,10 +1,55 @@
Copyright (c) <year> <owner> . All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
1. Definitions
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
"Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with one or more other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
"Creative Commons Compatible License" means a license that is listed at https://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of derivatives of works made available under that license under this License or either a Creative Commons unported license or a Creative Commons jurisdiction license with the same License Elements as this License.
"Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
"License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.
"Licensor" means the individual, individuals, entity or entities that offers the Work under the terms of this License.
"Original Author" means the individual, individuals, entity or entities who created the Work.
"Work" means the copyrightable work of authorship offered under the terms of this License.
"You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.
3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
to create and reproduce Derivative Works provided that any such Derivative Work, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified.";
to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
For the avoidance of doubt, where the Work is a musical composition:
Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or, in the event that Licensor is a member of a performance rights society (e.g. ASCAP, BMI, SESAC), via that society, royalties for the public performance or public digital performance (e.g. webcast) of the Work.
Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).
The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.
4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of a recipient of the Work to exercise of the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. When You distribute, publicly display, publicly perform, or publicly digitally perform the Work, You may not impose any technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise of the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by Section 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by Section 4(c), as requested.
You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under: (i) the terms of this License; (ii) a later version of this License with the same License Elements as this License; (iii) either the Creative Commons (Unported) license or a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g. Attribution-ShareAlike 3.0 (Unported)); (iv) a Creative Commons Compatible License. If you license the Derivative Work under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Derivative Work under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and with the following provisions: (I) You must include a copy of, or the Uniform Resource Identifier for, the Applicable License with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform; (II) You may not offer or impose any terms on the Derivative Works that restrict the terms of the Applicable License or the ability of a recipient of the Work to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties; and, (IV) when You distribute, publicly display, publicly perform, or publicly digitally perform the Work, You may not impose any technological measures on the Derivative Work that restrict the ability of a recipient of the Derivative Work from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of the Applicable License.
If You distribute, publicly display, publicly perform, or publicly digitally perform the Work (as defined in Section 1 above) or any Derivative Works (as defined in Section 1 above) or Collective Works (as defined in Section 1 above), You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and, consistent with Section 3(b) in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear, if a credit for all contributing authors of the Derivative Work or Collective Work appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.
5. Representations, Warranties and Disclaimer
UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND ONLY TO THE EXTENT OF ANY RIGHTS HELD IN THE LICENSED WORK BY THE LICENSOR. THE LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MARKETABILITY, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. Termination
This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
8. Miscellaneous
Each time You distribute or publicly digitally perform the Work (as defined in Section 1 above) or a Collective Work (as defined in Section 1 above), the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.

20
composer.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "deblan/php-mail-client",
"licence": "BY-SA",
"authors": [
{
"name": "Simon Vieille",
"email": "simon@deblan.fr"
}
],
"autoload": {
"psr-4": {
"Deblan\\MailClient\\": "src/Deblan/MailClient/"
}
},
"require": {
},
"extra": {
}
}

View File

@ -0,0 +1,453 @@
<?php
namespace Deblan\MailClient;
use Deblan\MailClient\Parser\Parser;
/**
* Class Client
* @author Simon Vieille <simon@deblan.fr>
*/
class Client
{
/**
* @var string
*/
protected $host;
/**
* @var string
*/
protected $port;
/**
* @var string
*/
protected $protocol;
/**
* @var boolean
*/
protected $ssl;
/**
* @var boolean
*/
protected $validateCertificate;
/**
* @var string
*/
protected $inbox;
/**
* @var string
*/
protected $username;
/**
* @var string
*/
protected $password;
/**
* @var resource
*/
protected $conn;
/**
* @var Parser
*/
protected $parser;
/**
* Constructor.
*/
public function __construct(Parser $parser)
{
$this->setSsl(true);
$this->setValidateCertificate(false);
$this->setInbox('INBOX');
$this->setProtocol('imap');
$this->setParser($parser);
}
/**
* @param Parser $parser
* @return Client
*/
public function setParser(Parser $parser)
{
$this->parser = $parser;
return $this;
}
/**
* @return Parser $parser
*/
public function getParser()
{
return $this->parser;
}
/**
* Connect to mail server.
*
* @return boolean Successfull connection
*/
public function connect()
{
if ($this->conn !== null) {
return true;
}
$this->conn = @imap_open(
$this->getMailbox(),
$this->getUsername(),
$this->getPassword()
);
return $this->conn !== false;
}
/**
* @return resource|null The connection
*/
public function getLink()
{
return $this->getConnection();
}
/**
* @return resource|null The connection
*/
public function getConnection()
{
return $this->conn;
}
/**
* Close connection.
*
* @return boolean Successfull closing
*/
public function close()
{
if ($this->conn) {
return imap_close($this->conn);
}
return true;
}
/**
* Search mails
*
* @param string $criteria Search criteria
* @see https://secure.php.net/manual/fr/function.imap-search.php
* @return array $mails
*/
public function search(Criteria $criteria = null)
{
if (null === $criteria) {
$criteria = Criteria::create();
}
$mails = imap_search($this->conn, $criteria->build());
if (!is_array($mails)) {
$mails = [];
} else {
foreach ($mails as $k => $v) {
$mails[$k] = $this->fetchMail($v);
}
}
return $mails;
}
/**
* Fetch and parse an mail by resource
*
* @param resource $resource
* @param int $option The optional options are a bit mask with one or more of the following: FT_UID, FT_PEEK, FT_INTERNAL
* @return MimeMailParser
*/
public function fetchMail($resource, $options = 0)
{
$header = imap_fetchheader($this->conn, $resource);
$body = imap_body($this->conn, $resource, (int) $options);
$text = implode("\r\n", [$header, $body]);
$text = iconv(mb_detect_encoding($text, 'UTF-8, ASCII, ISO-8859-1, ISO-8859-15'), 'UTF-8', $text);
$mail = clone $this->parser;
$mail->setText($text);
$mail->setResource($resource);
$mail->setOverview(imap_fetch_overview($this->conn, $resource)[0]);
return $mail;
}
/**
* Sets flags on messages
*
* @param string $sequence A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax
* @param string $flag The flags which you can set are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by » RFC2060.
* @param int $options The optional options are a bit mask with one or more of the following: FT_UID, FT_PEEK, FT_INTERNAL
* @return Client
*/
public function setFlag($sequence, $flag, $options = 0)
{
imap_setflag_full($this->conn, $sequence, $flag, $options);
return $this;
}
/**
* Sets flags on message
*
* @param string $number The message number.
* @param string $flag The flags which you can set are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by » RFC2060.
* @param int $options The optional options are a bit mask with one or more of the following: FT_UID, FT_PEEK, FT_INTERNAL
* @return Client
*/
public function setFlagOnMessage($number, $flag, $options = 0)
{
return $this->setFlag((int) $number, $flag, $options);
}
/**
* Unsets flags on messages
*
* @param string $sequence A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax
* @param string $flag The flags which you can unset are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by » RFC2060.
* @param int $options The optional options are a bit mask with one or more of the following: ST_UID
* @return Client
*/
public function unsetFlag($sequence, $flag, $options = 0)
{
imap_clearflag_full($this->conn, $sequence, $flag, $options);
return $this;
}
/**
* Unsets flags on message
*
* @param string $number The message number.
* @param string $flag The flags which you can unset are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by » RFC2060.
* @param int $options The optional options are a bit mask with one or more of the following: ST_UID
* @return Client
*/
public function unsetFlagOnMessage($number, $flag, $options = 0)
{
return $this->unsetFlag((int) $number, $flag, $options);
}
/**
* Generates the mailbox path
*
* @return string Mailbox path
*/
public function getMailbox()
{
$mailbox = sprintf(
'{%1$s%5$s/%2$s/%3$s}%4$s',
$this->getHost(),
$this->getProtocol(),
$this->getMailboxSsl(),
$this->getInbox(),
$this->getPort() ? ':'.$this->getPort() : ''
);
return $mailbox;
}
/**
* Generates the mailbox ssl path
*
* @return string
*/
public function getMailboxSsl()
{
$data = [];
if ($this->getSsl()) {
$data[] = 'ssl';
$data[] = $this->getValidateCertificate() ? 'validate-cert' : 'novalidate-cert';
}
return implode('/', $data);
}
/**
* @param string $host
* @return Client
*/
public function setHost($host)
{
$this->host = (string) $host;
return $this;
}
/**
* @return string $host
*/
public function getHost()
{
return $this->host;
}
/**
* @param string $protocol
* @return Client
* @throws InvalidArgumentException Protocol not implemented
*/
public function setProtocol($protocol)
{
$protocol = (string) $protocol;
if (!in_array($protocol, self::getSupportedProtocols())) {
throw new InvalidArgumentException(sprintf('The protocol "%s" is not supported', $protocol));
}
$this->protocol = $protocol;
return $this;
}
/**
* Returns the list of the supported procotols
*
* @return array Supported protocols
*/
public static function getSupportedProtocols()
{
return ['imap', 'imap2', 'imap2bis', 'imap4', 'imap4rev1', 'pop3'];
}
/**
* @param int $port
* @return Client
*/
public function setPort($port)
{
$this->port = (int) $port;
return $this;
}
/**
* @return int $port
*/
public function getPort()
{
return $this->port;
}
/**
* @return string $protocol
*/
public function getProtocol()
{
return $this->protocol;
}
/**
* @param bool $ssl
* @return Client
*/
public function setSsl($ssl)
{
$this->ssl = (bool) $ssl;
return $this;
}
/**
* @return bool $ssl
*/
public function getSsl()
{
return $this->ssl;
}
/**
* @param bool $validateCertificate
* @return Client
*/
public function setValidateCertificate($validateCertificate)
{
$this->validateCertificate = (bool) $validateCertificate;
return $this;
}
/**
* @return bool $validateCertificate
*/
public function getValidateCertificate()
{
return $this->validateCertificate;
}
/**
* @param string $inbox
* @return Client
*/
public function setInbox($inbox)
{
$this->inbox = (string) $inbox;
return $this;
}
/**
* @return string $inbox
*/
public function getInbox()
{
return $this->inbox;
}
/**
* @param string $username
* @return Client
*/
public function setUsername($username)
{
$this->username = (string) $username;
return $this;
}
/**
* @return string $username
*/
public function getUsername()
{
return $this->username;
}
/**
* @param string $password
* @return Client
*/
public function setPassword($password)
{
$this->password = (string) $password;
return $this;
}
/**
* @return string $password
*/
public function getPassword()
{
return $this->password;
}
}

View File

@ -0,0 +1,180 @@
<?php
namespace Deblan\MailClient;
/**
* Class Criteria
* @author Simon Vieille <simon@deblan.fr>
*/
class Criteria
{
/**
* @const string
*/
const ALL = "ALL";
/**
* @const string
*/
const ANSWERED = "ANSWERED";
/**
* @const string
*/
const BCC = "BCC";
/**
* @const string
*/
const BEFORE = "BEFORE";
/**
* @const string
*/
const BODY = "BODY";
/**
* @const string
*/
const CC = "CC";
/**
* @const string
*/
const DELETED = "DELETED";
/**
* @const string
*/
const FLAGGED = "FLAGGED";
/**
* @const string
*/
const FROM = "FROM";
/**
* @const string
*/
const KEYWORD = "KEYWORD";
/**
* @const string
*/
const INGOING = "NEW";
/**
* @const string
*/
const OLD = "OLD";
/**
* @const string
*/
const ON = "ON";
/**
* @const string
*/
const RECENT = "RECENT";
/**
* @const string
*/
const SEEN = "SEEN";
/**
* @const string
*/
const SINCE = "SINCE";
/**
* @const string
*/
const SUBJECT = "SUBJECT";
/**
* @const string
*/
const TEXT = "TEXT";
/**
* @const string
*/
const TO = "TO";
/**
* @const string
*/
const UNANSWERED = "UNANSWERED";
/**
* @const string
*/
const UNDELETED = "UNDELETED";
/**
* @const string
*/
const UNFLAGGED = "UNFLAGGED";
/**
* @const string
*/
const UNKEYWORD = "UNKEYWORD";
/**
* @const string
*/
const UNSEEN = "UNSEEN";
/**
* @var array
*/
protected $filters = [];
/**
* Create a new instance of Criteria
*
* @return Criteria
*/
public static function create()
{
return new self();
}
/**
* Append a filter
*
* @return Criteria
* @param string $criteria
* @param string $value
*/
public function filterBy($criteria, $value = null)
{
$filter = $criteria;
$in = in_array(
$criteria,
[self::UNKEYWORD, self::TEXT, self::SINCE, self::SUBJECT, self::ON, self::KEYWORD, self::FROM, self::CC, self::BEFORE, self::BCC]
);
if ($in) {
$filter.= ' "'.str_replace('"', '\\"', (string) $value).'"';
}
$this->filters[] = $filter;
return $this;
}
/**
* Get a valid string for filtering
*
* @return string
*/
public function build()
{
return implode(' ', $this->filters);
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace Deblan\MailClient;
/**
* Class Flag
* @author Simon Vieille <simon@deblan.fr>
*/
class Flag
{
/**
* @const string
*/
const SEEN = '\\Seen';
/**
* @const string
*/
const ANSWERED = '\\Answered';
/**
* @const string
*/
const FLAGGED = '\\Flagged';
/**
* @const string
*/
const DELETED = '\\Deleted';
/**
* @const string
*/
const DRAFT = '\\Draft';
}

View File

@ -0,0 +1,148 @@
<?php
namespace Deblan\MailClient\Parser;
/**
* Model of an Attachment
*/
class Attachment
{
/**
* @var $filename Filename
*/
public $filename;
/**
* @var $content_type Mime Type
*/
public $content_type;
/**
* @var $content File Content
*/
private $content;
/**
* @var $extension Filename extension
*/
private $extension;
/**
* @var $content_disposition Content-Disposition (attachment or inline)
*/
public $content_disposition;
/**
* @var $headers An Array of the attachment headers
*/
public $headers;
private $stream;
public function __construct($filename, $content_type, $stream, $content_disposition = 'attachment', $headers = array())
{
$this->filename = $filename;
$this->content_type = $content_type;
$this->stream = $stream;
$this->content = null;
$this->content_disposition = $content_disposition;
$this->headers = $headers;
}
/**
* retrieve the attachment filename
* @return String
*/
public function getFilename()
{
return $this->filename;
}
/**
* Retrieve the Attachment Content-Type
* @return String
*/
public function getContentType()
{
return $this->content_type;
}
/**
* Retrieve the Attachment Content-Disposition
* @return String
*/
public function getContentDisposition()
{
return $this->content_disposition;
}
/**
* Retrieve the Attachment Headers
* @return String
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Retrieve the file extension
* @return String
*/
public function getFileExtension()
{
if (!$this->extension) {
$ext = substr(strrchr($this->filename, '.'), 1);
if ($ext == 'gz') {
// special case, tar.gz
// todo: other special cases?
$ext = preg_match("/\.tar\.gz$/i", $ext) ? 'tar.gz' : 'gz';
}
$this->extension = $ext;
}
return $this->extension;
}
/**
* Read the contents a few bytes at a time until completed
* Once read to completion, it always returns false
* @return String
* @param $bytes Int[optional]
*/
public function read($bytes = 2082)
{
return feof($this->stream) ? false : fread($this->stream, $bytes);
}
/**
* Retrieve the file content in one go
* Once you retreive the content you cannot use Attachment::read()
* @return String
*/
public function getContent()
{
if ($this->content === null) {
fseek($this->stream, 0);
while (($buf = $this->read()) !== false) {
$this->content .= $buf;
}
}
return $this->content;
}
/**
* Allow the properties
* Attachment::$name,
* Attachment::$extension
* to be retrieved as public properties
* @param $name Object
*/
public function __get($name)
{
if ($name == 'content') {
return $this->getContent();
} elseif ($name == 'extension') {
return $this->getFileExtension();
}
return null;
}
}

View File

@ -0,0 +1,595 @@
<?php
namespace Deblan\MailClient\Parser;
use Exception;
/**
* Fast Mime Mail parser Class using PHP's MailParse Extension
* @author gabe@fijiwebdesign.com
* @url http://www.fijiwebdesign.com/
* @license http://creativecommons.org/licenses/by-sa/3.0/us/
* @version $Id: MimeMailParser.class.php 28 2014-03-25 10:32:17Z m.valinskis@gmail.com $
*/
class Parser
{
/**
* PHP MimeParser Resource ID
*
* @var resource
*/
protected $resource;
/**
* A file pointer to email
*
* @var resource
*/
protected $stream;
/**
* A text of an email
*
* @var string
*/
protected $data;
/**
* Stream Resources for Attachments
*
* @var mixed
*/
protected $attachment_streams;
/**
* @var stdClass
*/
protected $overview;
/**
* Inialize some stuff
* @return
*/
public function __construct()
{
$this->attachment_streams = array();
}
/**
* @return resource
*/
public function getResource()
{
return $this->resource;
}
/**
* @return stdObject
*/
public function getOverview()
{
return $this->overview;
}
/**
* @param $overview stdClass
* @return Client
*/
public function setOverview($overview)
{
$this->overview = $overview;
return $this;
}
/**
* Free the held resouces
* @return void
*/
public function __destruct()
{
// clear the email file resource
if (is_resource($this->stream)) {
fclose($this->stream);
}
// clear the MailParse resource
if (is_resource($this->resource)) {
mailparse_msg_free($this->resource);
}
// remove attachment resources
foreach ($this->attachment_streams as $stream) {
fclose($stream);
}
}
/**
* Set the file path we use to get the email text
* @return Object MimeMailParser Instance
* @param $mail_path Object
*/
public function setPath($path)
{
// should parse message incrementally from file
$this->resource = mailparse_msg_parse_file($path);
$this->stream = fopen($path, 'r');
$this->parse();
return $this;
}
/**
* Set the Stream resource we use to get the email text
* @return Object MimeMailParser Instance
* @param $stream Resource
*/
public function setStream($stream)
{
// streams have to be cached to file first
if (get_resource_type($stream) == 'stream') {
$tmp_fp = tmpfile();
if ($tmp_fp) {
while (!feof($stream)) {
fwrite($tmp_fp, fread($stream, 2028));
}
fseek($tmp_fp, 0);
$this->stream =& $tmp_fp;
} else {
throw new Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.');
return false;
}
fclose($stream);
} else {
$this->stream = $stream;
}
$this->resource = mailparse_msg_create();
// parses the message incrementally low memory usage but slower
while (!feof($this->stream)) {
mailparse_msg_parse($this->resource, fread($this->stream, 2082));
}
$this->parse();
return $this;
}
/**
* Set the email text
* @return Object MimeMailParser Instance
* @param $data String
*/
public function setText($data)
{
$this->resource = mailparse_msg_create();
// does not parse incrementally, fast memory hog might explode
mailparse_msg_parse($this->resource, $data);
$this->data = $data;
$this->parse();
return $this;
}
/**
* @return string
*/
public function getSubject()
{
return utf8_encode(iconv_mime_decode($this->getHeader('subject')));
}
/**
* Parse the Message into parts
* @return void
* @private
*/
private function parse()
{
$structure = mailparse_msg_get_structure($this->resource);
$this->parts = array();
foreach ($structure as $part_id) {
$part = mailparse_msg_get_part($this->resource, $part_id);
$this->parts[$part_id] = mailparse_msg_get_part_data($part);
}
}
/**
* Retrieve the Email Headers
* @return Array
*/
public function getHeaders()
{
if (isset($this->parts[1])) {
return $this->getPartHeaders($this->parts[1]);
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
}
return false;
}
/**
* Retrieve the raw Email Headers
* @return string
*/
public function getHeadersRaw()
{
if (isset($this->parts[1])) {
return $this->getPartHeaderRaw($this->parts[1]);
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
}
return false;
}
/**
* Retrieve a specific Email Header
* @return String
* @param $name String Header name
*/
public function getHeader($name)
{
if (isset($this->parts[1])) {
$headers = $this->getPartHeaders($this->parts[1]);
if (isset($headers[$name])) {
return $headers[$name];
}
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email headers.');
}
return false;
}
/**
* Returns the email message body in the specified format
* @return Mixed String Body or False if not found
* @param $type Object[optional]
*/
public function getMessageBody($type = 'text')
{
$body = false;
$mime_types = array(
'text'=> 'text/plain',
'html'=> 'text/html'
);
if (in_array($type, array_keys($mime_types))) {
foreach ($this->parts as $part) {
if ($this->getPartContentType($part) == $mime_types[$type]) {
$headers = $this->getPartHeaders($part);
$body = $this->decode($this->getPartBody($part), array_key_exists('content-transfer-encoding', $headers) ? $headers['content-transfer-encoding'] : '');
break;
}
}
} else {
throw new Exception('Invalid type specified for MimeMailParser::getMessageBody. "type" can either be text or html.');
}
return $body;
}
/**
* get the headers for the message body part.
* @return Array
* @param $type Object[optional]
*/
public function getMessageBodyHeaders($type = 'text')
{
$headers = false;
$mime_types = array(
'text'=> 'text/plain',
'html'=> 'text/html'
);
if (in_array($type, array_keys($mime_types))) {
foreach ($this->parts as $part) {
if ($this->getPartContentType($part) == $mime_types[$type]) {
$headers = $this->getPartHeaders($part);
break;
}
}
} else {
throw new Exception('Invalid type specified for MimeMailParser::getMessageBody. "type" can either be text or html.');
}
return $headers;
}
/**
* Returns inline content files.
* @return Array
*/
public function getInlineContent()
{
$content = array();
foreach ($this->parts as $part) {
$content_id = $this->getPartContentId($part);
if ($content_id !== FALSE) {
$content[] = new Attachment(
$this->getPartContentName($part),
$this->getPartContentType($part),
$this->getAttachmentStream($part),
$this->getPartContentDisposition($part),
$this->getPartHeaders($part)
);
}
}
return $content;
}
/**
* Returns the attachments contents in order of appearance
* @return Array
* @param $type Object[optional]
*/
public function getAttachments($dispositions = null)
{
$attachments = array();
if($dispositions == null) $dispositions = array("attachment","inline");
foreach ($this->parts as $part) {
$disposition = $this->getPartContentDisposition($part);
$content_name = $this->getPartContentName($part);
if (in_array($disposition, $dispositions) === TRUE || $content_name !== FALSE) {
if ($content_name === FALSE) {
$content_name = isset($part['disposition-filename'])
? $part['disposition-filename'] : md5(uniqid());
}
if ($disposition === FALSE && $content_name !== FALSE) {
$disposition = $dispositions[0];
}
$attachments[] = new Attachment(
$content_name,
$this->getPartContentType($part),
$this->getAttachmentStream($part),
$disposition,
$this->getPartHeaders($part)
);
}
}
return $attachments;
}
/**
* Return the Headers for a MIME part
* @return Array
* @param $part Array
*/
private function getPartHeaders($part)
{
if (isset($part['headers'])) {
return $part['headers'];
}
return false;
}
/**
* Return a Specific Header for a MIME part
* @return Array
* @param $part Array
* @param $header String Header Name
*/
private function getPartHeader($part, $header)
{
if (isset($part['headers'][$header])) {
return $part['headers'][$header];
}
return false;
}
/**
* Return the ContentType of the MIME part
* @return String
* @param $part Array
*/
private function getPartContentType($part)
{
if (isset($part['content-type'])) {
return $part['content-type'];
}
return false;
}
/**
* Return the ContentName of the MIME part
* @return String
* @param $part Array
*/
private function getPartContentName($part)
{
if (isset($part['content-name'])) {
return $part['content-name'];
}
return false;
}
/**
* Return the Content Disposition
* @return String
* @param $part Array
*/
private function getPartContentDisposition($part)
{
if (isset($part['content-disposition'])) {
return $part['content-disposition'];
}
return false;
}
/**
* Return the Content id
* @return String
* @param $part Array
*/
private function getPartContentId($part)
{
if (isset($part['content-id'])) {
return $part['content-id'];
}
return false;
}
/**
* Retrieve the raw Header of a MIME part
* @return String
* @param $part Object
*/
private function getPartHeaderRaw(&$part)
{
$header = '';
if ($this->stream) {
$header = $this->getPartHeaderFromFile($part);
} elseif ($this->data) {
$header = $this->getPartHeaderFromText($part);
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email parts.');
}
return $header;
}
/**
* Retrieve the Body of a MIME part
* @return String
* @param $part Object
*/
private function getPartBody(&$part)
{
$body = '';
if ($this->stream) {
$body = $this->getPartBodyFromFile($part);
} elseif ($this->data) {
$body = $this->getPartBodyFromText($part);
} else {
throw new Exception('MimeMailParser::setPath() or MimeMailParser::setText() must be called before retrieving email parts.');
}
return $body;
}
/**
* Retrieve the Header from a MIME part from file
* @return String Mime Header Part
* @param $part Array
*/
private function getPartHeaderFromFile(&$part)
{
$start = $part['starting-pos'];
$end = $part['starting-pos-body'];
fseek($this->stream, $start, SEEK_SET);
$header = fread($this->stream, $end-$start);
return $header;
}
/**
* Retrieve the Body from a MIME part from file
* @return String Mime Body Part
* @param $part Array
*/
private function getPartBodyFromFile(&$part)
{
$start = $part['starting-pos-body'];
$end = $part['ending-pos-body'];
fseek($this->stream, $start, SEEK_SET);
$body = fread($this->stream, $end-$start);
return $body;
}
/**
* Retrieve the Header from a MIME part from text
* @return String Mime Header Part
* @param $part Array
*/
private function getPartHeaderFromText(&$part)
{
$start = $part['starting-pos'];
$end = $part['starting-pos-body'];
$header = substr($this->data, $start, $end-$start);
return $header;
}
/**
* Retrieve the Body from a MIME part from text
* @return String Mime Body Part
* @param $part Array
*/
private function getPartBodyFromText(&$part)
{
$start = $part['starting-pos-body'];
$end = $part['ending-pos-body'];
$body = substr($this->data, $start, $end-$start);
return $body;
}
/**
* Read the attachment Body and save temporary file resource
* @return String Mime Body Part
* @param $part Array
*/
private function getAttachmentStream(&$part)
{
$temp_fp = tmpfile();
array_key_exists('content-transfer-encoding', $part['headers']) ? $encoding = $part['headers']['content-transfer-encoding'] : $encoding = '';
if ($temp_fp) {
if ($this->stream) {
$start = $part['starting-pos-body'];
$end = $part['ending-pos-body'];
fseek($this->stream, $start, SEEK_SET);
$len = $end-$start;
$written = 0;
$write = 2028;
$body = '';
while ($written < $len) {
if (($written+$write < $len )) {
$write = $len - $written;
}
$part = fread($this->stream, $write);
fwrite($temp_fp, $this->decode($part, $encoding));
$written += $write;
}
} elseif ($this->data) {
$attachment = $this->decode($this->getPartBodyFromText($part), $encoding);
fwrite($temp_fp, $attachment, strlen($attachment));
}
fseek($temp_fp, 0, SEEK_SET);
} else {
throw new Exception('Could not create temporary files for attachments. Your tmp directory may be unwritable by PHP.');
return false;
}
return $temp_fp;
}
/**
* Decode the string depending on encoding type.
* @return String the decoded string.
* @param $encodedString The string in its original encoded state.
* @param $encodingType The encoding type from the Content-Transfer-Encoding header of the part.
*/
private function decode($encodedString, $encodingType)
{
if (strtolower($encodingType) == 'base64') {
return base64_decode($encodedString);
} elseif (strtolower($encodingType) == 'quoted-printable') {
return quoted_printable_decode($encodedString);
} else {
return $encodedString;
}
}
}