1
0

version fonctionnelle

This commit is contained in:
Daniel Tartavel 2021-06-17 18:35:51 +02:00
parent 3c303efeb9
commit ab2f9b87a7
243 changed files with 23955 additions and 100 deletions

View File

@ -10,11 +10,11 @@
//test();
$_SERVER["PHP_AUTH_USER"] = "cron";
//peripetieDatee();
print "envoi des courriers en attente" . EOL;
print "envoi des courriers en attente" . EOLH;
envoiCourrielEnattente();
print "envoi des péripéties" . EOL;
print "envoi des péripéties" . EOLH;
peripeties();
print "Envoi des arrivées" . EOL;
print "Envoi des arrivées" . EOLH;
arrivee();
function peripetieDatee()
@ -38,8 +38,8 @@
$indexObjet = "Objet_" . $p['indexText'];
$objetMail = $dicoExpe["Objet_" . $p['indexText']];
$mailText = $dicoExpe[$p['indexText']] .EOL .EOL ;
print $objetMail .EOLH;
print $mailText .EOLH;
print $objetMail . EOLH;
print $mailText . EOLH;
envoiMail( $result['destMail'], $objetMail, $mailText, false);
sleep(1);
envoiMail( $result['expeMail'], $objetMail, $mailText, true);
@ -51,6 +51,8 @@
function peripeties() //recherche des péripéties non datées
{
global $db, $base_url;
$r = 0;
$s = 0;
// ouverture DB peripéties
$dbPeripetie = new db();
// requête Mysql
@ -58,11 +60,18 @@
$dbPeripetie->query($query);
$peripeties = $dbPeripetie->result->fetch_all(MYSQLI_ASSOC);
$dbPeripetie->close();
foreach ( $peripeties as $peripetie)
{
print "avion poème n° " . $peripetie['idAvion'] .EOL;
print "péripétie " . $peripetie["idAP"] . " - avion poème n° " . $peripetie['idAvion'] .EOLH;
$db->getPlane($peripetie['idAvion']);
if ($db->connect->affected_rows == 0)
{
log_error("Péripétie " . $peripetie["idAP"] . "n'a pas d'avion associé idAvion=>" . $peripetie['idAvion']);
print "Péripétie " . $peripetie["idAP"] . "n'a pas d'avion associé idAvion=>" . $peripetie['idAvion'];
}
else
{
//print_r($db);
$dicoExpe = getLang( $db->expeLang );
$dicoDest = getLang( $db->destLang );
// TODO calcul de la nouvelle date d'arrivée
@ -84,14 +93,14 @@
$mailText = $result["text"];
//$html = $result['html'];
sleep(1);
print "envoi courriel à l'expéditeur" .EOL;
print "envoi courriel à l'expéditeur : " . $db->expeMail . EOLH . $mailText .EOLH;
$r = envoiMail( $db->expeMail, $objetMail, $mailText);
$db->datePeripetie = formatteDate($db->destLang, $db->deliveryTime, $db->deliveryTZ);
$result = replaceVariables($db, $dicoDest["Objet_" . $peripetie['indexText']], $dicoDest);
$objetMail = $result["text"];
$result = replaceVariables($db, $dicoDest[$peripetie['indexText']], $dicoDest);
$mailText = $result["text"] .EOLH .EOLH;
print "envoi courriel au destinataire" .EOL;
$mailText = $result["text"] . EOLH . EOLH;
print "envoi courriel au destinataire : " . $db->destMail . EOLH . $mailText .EOLH;
$s = envoiMail( $db->destMail, $objetMail, $mailText);
sleep(1);
//print "r=" . $r ." => s=" .$s .EOLH;
@ -103,46 +112,52 @@
}else
{
print "table avion péripétie non mise à jour" .EOL;
print "UPDATE avionPeripetie SET mailSent=true WHERE idAP='" . $peripetie['idAP'] ."'" .EOL;
print "UPDATE avionPeripetie SET mailSent=true WHERE idAP='" . $peripetie['idAP'] ."'" .EOLH;
}
sleep(1);
}
}
}
function arrivee()
{
global $db;
$r = 0;
$s = 0;
//recherche des avions atteris
$query = "SELECT * FROM avionpoeme WHERE atteri = 0 AND TIMEDIFF(CONCAT_WS(' ',CURDATE(),CURTIME()),deliveryTimeServer) > '00:00'";
$db->query($query);
$avionArrive = $db->result->fetch_all(MYSQLI_ASSOC);
var_dump($avionArrive);
foreach ($avionArrive as $avion)
{
print "avion poème n° " . $avion['idAvion'] . EOLH;
print "avion poème n° " . $avion['idAvion'] . "a atterri" . EOLH;
$dicoExpe = getLang( $avion['expeLang'] );
$dicoDest = getLang( $avion['destLang'] );
$index = "Notification_Arrivee_Expediteur";
$indexObjet = "Objet_";
$objetMail = replaceVariables($db, $dicoExpe[$indexObjet . $index], $dicoExpe);
$result = replaceVariables($db, $dicoExpe[$index], $dicoExpe);
$mailText= $result["text"];
print "envoi courriel à l'expéditeur". EOLH;
$r = envoiMail( $avion['expeMail'], $objetMail["text"], $mailText);
sleep(1);
$index = "Notification_Arrivee_Destinataire";
$objetMail = replaceVariables($db, $dicoDest[$indexObjet . $index], $dicoDest);
$result = replaceVariables($db, $dicoDest[$index], $dicoDest);
log_write(__FILE__ . EOL . __LINE__ . EOL . "#" .print_r($result, true) . "#", INFO);
//envoi notification arrivée expéditeur
$indexObjet = "Objet_";
$index = "Notification_Arrivee_Expediteur";
$objetMail = replaceVariables( (object)$avion, $dicoExpe[$indexObjet . $index], $dicoExpe);
$result = replaceVariables((object)$avion, $dicoExpe[$index], $dicoExpe);
$mailText= $result["text"];
print "envoi courriel à l'expéditeur : " . $avion['expeMail'] . EOLH . $mailText .EOLH;
$r = envoiMail( $avion['expeMail'], $objetMail["text"], $mailText);
//envoi notification arrivée destinataire
$index = "Notification_Arrivee_Destinataire";
$objetMail = replaceVariables((object)$avion, $dicoDest[$indexObjet . $index], $dicoDest);
$result = replaceVariables((object)$avion, $dicoDest[$index], $dicoDest);
$mailText = $result["text"];
$html = $result['html'];
if ( $html )
{
$mailText = "<html><head></head>\n<body>" . $mailText . "</body></html>";
}
print "envoi courriel au destinataire" . EOLH;
print "envoi courriel au destinataire : " . $avion['destMail'] . EOLH . $mailText .EOLH;
sleep(1);
$s = envoiMail( $avion['destMail'], $objetMail["text"], $mailText, $html);
if ($r AND $s)
{

View File

@ -7,8 +7,8 @@
if ( isset($_GET["ok"] ))
{
$fisrt_line = false;
$fh = fopen("../lang/9mfo-traduction.csv", "r") or die("Can't open csv");
$fhIndex = fopen("../lang/lang.json", "w") or die("Can't open lang/lang.json");
$fh = fopen("../lang/9mfo-traduction.csv", "r") or die( __FILE__ ." ligne: " . __LINE__ . " Can't open csv");
$fhIndex = fopen("../lang/lang.json", "w") or die( __FILE__ ." ligne: " . __LINE__ . " Can't open lang/lang.json");
fwrite($fhIndex, '{');
$first_line = true;
$first_column_line = true;
@ -36,7 +36,7 @@
$index = explode("/",$column);
echo "opening ../lang/" . $index[0] . EOLH;
$fhl[++$i] = fopen("../lang/" . $index[0], "wb") or die("can't open lang/" . $index[0]);
$fhl[++$i] = fopen("../lang/" . $index[0], "wb") or die( __FILE__ ." ligne: " . __LINE__ . " can't open lang/" . $index[0]);
fwrite($fhl[$i], '{');
if ( $first_column == true )
{
@ -92,19 +92,21 @@
fwrite($fhx, '}');
fclose($fhx);
}
$fh = fopen("../lang/lang.json","r");
$fh = fopen("../lang/lang.json","r") or die("Can't open ../lang/lang.json" . __FILE__ ." ligne: " . __LINE__);
$str = fgets($fh);
fclose($fh);
$lang = json_decode( $str, true);
foreach ($lang as $key => $value)
$langArray = json_decode( $str, true);
foreach ($langArray as $key => $value)
{
$lang = getLang($key, true);
if ( $lang != false )
{
print $key ." : ";
if ( getLang($key, true) !== false )
{
print json_last_error_msg() . EOLH;
}else
{
print "erreur à l'ouverture du fichier";
print __FILE__ ." ligne: " . __LINE__ . " erreur à l'ouverture du fichier";
}
}
}

83
gestion/gestionDB.php Normal file
View File

@ -0,0 +1,83 @@
<?php
/*if ( !isset($site) )
{
require_once( "../include/config.inc.php" );
print "accueil =>" . $accueil;
header( 'Location: ' . $accueil );
}*/
require_once '../session_init.php';
require_once 'config.inc.php';
require_once 'db.class.php';
require_once 'envoi_courriel.inc.php';
require_once 'log.php';
print '
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Administration</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<!-- CSS -->
<link href="../src/app.css" rel="stylesheet">
<!-- navbar -->
<nav class="navbar navbar-expand-md fixed-top navbar-light bg-light">
<a class="navbar-brand" href="#">Avions Poèmes</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="#">Anthologie</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#" data-toggle="modal" data-target="#aboutModal" >À propos</a>
</li>
</ul>
</div>
</nav>
</head>
<body>';
verifPeripetieAvion();
function verifAvionpoeme()
{
$query = "SELECT * FROM avionpoeme";
$db->query($query);
$avions = $db->result->fetch_all(MYSQLI_ASSOC);
foreach($avions as $avion)
{
}
return $fresult;
}
function verifPeripetieAvion()
{
print "Vérification des liens péripétie/avionpoème" . EOLH;
$db = new db();
// requête Mysql
$query = "SELECT * FROM avionPeripetie";
$db->query($query);
$peripeties = $db->result->fetch_all(MYSQLI_ASSOC);
$query = "SELECT * FROM avionpoeme";
$db->query($query);
$avions = $db->result->fetch_all(MYSQLI_ASSOC);
$avionsId = array_column($avions, 'expeMail', 'idAvion');
print_r($avionsId);
foreach($peripeties as $peripetie)
{
print "Péripétie " . $peripetie["idAP"] . EOLH;
$idAvion = $peripetie["idAvion"];
if ( empty($avionsId[$idAvion]) )
{
print "Péripétie " . $peripetie["idAP"] . " n'a pas d'avion poème idAvion=>" . $idAvion . EOLH;
}
}
$db->close();
}
print "</body></html>";
?>

View File

@ -1,4 +1,7 @@
<?php
require_once '../session_init.php';
require_once 'config.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
@ -27,5 +30,9 @@
</head>
<body>
<a href="lang.php">Générer les fichiers de langue</a>
<a href="logs.php">Lire les logs</a>
<a href="lang.php">Générer les fichiers de langue</a><br>
<a href="logs.php">Lire les logs</a><br>
<a href="gestionDB.php">Vérifier la base de données</a><br>
</body>
</html>

View File

@ -169,6 +169,7 @@ class db
$this->query($query);
$planes = $this->result->fetch_all(MYSQLI_ASSOC);
print json_encode($planes);
//log_write(json_encode($planes), INFO);
return $planes;
}
@ -203,7 +204,7 @@ class db
log_write("savePeripetie " . $query);
//$query .= $this->protect($this->effetPeripetie) . "', '";
//$query .= $this->protect($this->expeMail) . "', '";
//$query .= $this->protect($this->destMail) . "')"; echo $query . EOL;
//$query .= $this->protect($this->destMail) . "')";
$this->query($query);
}

View File

@ -19,20 +19,22 @@ function courrielEnvoi( $db )
log_write("indexObjet" .EOLH . print_r($result, true));
$mailText = $result['text'];
$html = $result['html'];
if ( $html )
{
$mailText = "<html><head></head>\n<body>" . $mailText . "</body></html>";
}
if ( $db->expeKnown == false )
saveMail( $db, $db->expeMail, $objetMail, $mailText, $html);
//log_write(print_r($db,true));
// message au destinataire
if ( $db->expeKnown == 'true' )
{
$destinataireIndex = "Notification_denvoi_Destinataire_ExpediteurConnu";
//log_write("Expéditeur connu => ");
}else
{
$destinataireIndex = "Notification_denvoi_Destinataire_ExpediteurAnonyme";
//log_write("Expéditeur inconnu => ");
}
saveMail( $db, $db->expeMail, $objetMail, $mailText, $html);
// message au destinataire
$indexObjet = "Objet_" . $destinataireIndex;
$result = replaceVariables($db, $dicoDest[$indexObjet], $dicoDest);
log_write("indexObjet" .EOLH . print_r($result, true));
@ -56,32 +58,42 @@ function saveMail( $db, $destinataire, $objet, $text, $html=false)
function envoiMail($destinataire, $sujet, $text, $html=false, $cc='', $bcc='')
{
$headers = "From: contact@avion-poe.me" . LF;
if ( !empty($cc)) $headers .= "Cc: " . $cc . LF;
if ( !empty($bcc)) $headers .= "Bcc: " . $bcc . LF;
require_once 'include/swiftmailer/autoload.php';
//require_once 'include/swiftmailer/swiftmailer/lib/swift_init.php';
$transport = (new Swift_SmtpTransport('smtpauth.online.net', 465, 'ssl'))
->setUsername('contact@avion-poe.me')
->setPassword('AvionPoème*27juillet');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message($sujet))
->setFrom(["contact@avion-poe.me"])
->setTo([$destinataire])
->setCharset('utf-8');
$type = $message->getHeaders()->get('Content-Type');
if ($html)
{
$headers .= "Content-type: text/html; charset=UTF-8" . LF;
nl2br($text);
// setParameters() takes an associative array
$type->setValue('text/html');
$type->setParameter('charset', 'utf-8');
$str = nl2br($text);
$text = "<html><head></head>\n<body>" . $str . "</body></html>";
log_write(__FILE__ . EOL . __LINE__ . EOL . wordwrap($text, 1000, "\r\n"), INFO);
}else
{
$headers .= "Content-type: text/plain; charset=UTF-8" . LF;
$type->setValue('text/plain');
$type->setParameter('charset', 'utf-8');
$text = str_replace("\n","\r\n", $text);
}
$headers .= "DATE: " . date( 'r' ) . LF . LF;
$destinataire = "dtux@free.fr";
log_write(__FILE__ . __LINE__ . " Envoi d'un courriel à " . $destinataire . "sujet:" . $sujet, INFO);
if( !mail($destinataire, $sujet, wordwrap($text, 1000 , "\r\n"), $headers) ) //Sending mail
$message->setBody($text);
//add date header
$headers = $message->getHeaders();
$headers->addDateHeader('Your-Header', new DateTimeImmutable('3 days ago'));
if (!$mailer->send($message, $failures))
{
$error = error_get_last();
log_write(__FILE__ . EOL . __LINE__ . EOL . "Le courriel n'est pas parti:" .$destinataire . EOL . $sujet . EOL . print_r($error, true) . EOL . wordwrap($text, 1000 , "\r\n"), ERROR);
echo "Failures:";
print_r($failures);
log_write(__FILE__ . EOL . __LINE__ . EOL . "Le courriel n'est pas parti:" . $destinataire . EOL . $sujet . EOL . print_r($failure, true) . EOL . wordwrap($text, 1000 , "\r\n"), ERROR);
return false;
}else
{
log_write(__FILE__ . EOL . __LINE__ . EOL . "Le courriel est parti: " . $destinataire . EOL . "text:" . $text, INFO);
return true;
}
return true;
}
?>

View File

@ -0,0 +1,14 @@
<?php
/*
* Bootstrap the library.
*/
namespace Egulias;
require_once __DIR__ . '/egulias/email-validator/AutoLoader.php';
require_once __DIR__ . '/lib/swift_required.php';
require_once __DIR__ . '/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
$autoloader = new EguliasAutoLoader(__NAMESPACE__, dirname(__DIR__));
$autoloader->register();

View File

@ -0,0 +1,13 @@
<?php
/*
* Bootstrap the library.
*/
namespace Egulias;
require_once __DIR__ . '/egulias/email-validator/AutoLoader.php';
require_once __DIR__ . '/lib/swift_required.php';
$autoloader = new EguliasAutoLoader(__NAMESPACE__, dirname(__DIR__));
$autoloader->register();

View File

@ -0,0 +1,82 @@
<?php
namespace Egulias;
/**
* PSR-0 Autoloader
*
* @author ieter Hordijk <info@pieterhordijk.com>
*/
class EguliasAutoLoader
{
/**
* @var string The namespace prefix for this instance.
*/
protected $namespace = '';
/**
* @var string The filesystem prefix to use for this instance
*/
protected $path = '';
/**
* Build the instance of the autoloader
*
* @param string $namespace The prefixed namespace this instance will load
* @param string $path The filesystem path to the root of the namespace
*/
public function __construct($namespace, $path)
{
$this->namespace = ltrim($namespace, '\\');
$this->path = rtrim($path, '/\\') . DIRECTORY_SEPARATOR;
}
/**
* Try to load a class
*
* @param string $class The class name to load
*
* @return boolean If the loading was successful
*/
public function load($class)
{
$class = ltrim($class, '\\');
if (strpos($class, $this->namespace) === 0) {
$nsparts = explode('\\', $class);
$class = array_pop($nsparts);
$path = $this->path . 'swiftmailer/egulias/email-validator/EmailValidator/';
$max=count($nsparts);
for ($i=2; $i<$max;$i++) {
$path .= $nsparts[$i].'/';
}
$nsparts = array();
$path .= str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
if (file_exists($path)) {
require $path;
return true;
}
}
return false;
}
/**
* Register the autoloader to PHP
*
* @return boolean The status of the registration
*/
public function register()
{
return spl_autoload_register(array($this, 'load'));
}
/**
* Unregister the autoloader to PHP
*
* @return boolean The status of the unregistration
*/
public function unregister()
{
return spl_autoload_unregister(array($this, 'load'));
}
}

View File

@ -0,0 +1,221 @@
<?php
namespace Egulias\EmailValidator;
use Doctrine\Common\Lexer\AbstractLexer;
class EmailLexer extends AbstractLexer
{
//ASCII values
const C_DEL = 127;
const C_NUL = 0;
const S_AT = 64;
const S_BACKSLASH = 92;
const S_DOT = 46;
const S_DQUOTE = 34;
const S_OPENPARENTHESIS = 49;
const S_CLOSEPARENTHESIS = 261;
const S_OPENBRACKET = 262;
const S_CLOSEBRACKET = 263;
const S_HYPHEN = 264;
const S_COLON = 265;
const S_DOUBLECOLON = 266;
const S_SP = 267;
const S_HTAB = 268;
const S_CR = 269;
const S_LF = 270;
const S_IPV6TAG = 271;
const S_LOWERTHAN = 272;
const S_GREATERTHAN = 273;
const S_COMMA = 274;
const S_SEMICOLON = 275;
const S_OPENQBRACKET = 276;
const S_CLOSEQBRACKET = 277;
const S_SLASH = 278;
const S_EMPTY = null;
const GENERIC = 300;
const CRLF = 301;
const INVALID = 302;
const ASCII_INVALID_FROM = 127;
const ASCII_INVALID_TO = 199;
/**
* US-ASCII visible characters not valid for atext (@link http://tools.ietf.org/html/rfc5322#section-3.2.3)
*
* @var array
*/
protected $charValue = array(
'(' => self::S_OPENPARENTHESIS,
')' => self::S_CLOSEPARENTHESIS,
'<' => self::S_LOWERTHAN,
'>' => self::S_GREATERTHAN,
'[' => self::S_OPENBRACKET,
']' => self::S_CLOSEBRACKET,
':' => self::S_COLON,
';' => self::S_SEMICOLON,
'@' => self::S_AT,
'\\' => self::S_BACKSLASH,
'/' => self::S_SLASH,
',' => self::S_COMMA,
'.' => self::S_DOT,
'"' => self::S_DQUOTE,
'-' => self::S_HYPHEN,
'::' => self::S_DOUBLECOLON,
' ' => self::S_SP,
"\t" => self::S_HTAB,
"\r" => self::S_CR,
"\n" => self::S_LF,
"\r\n" => self::CRLF,
'IPv6' => self::S_IPV6TAG,
'{' => self::S_OPENQBRACKET,
'}' => self::S_CLOSEQBRACKET,
'' => self::S_EMPTY,
'\0' => self::C_NUL,
);
protected $hasInvalidTokens = false;
protected $previous;
public function reset()
{
$this->hasInvalidTokens = false;
parent::reset();
}
public function hasInvalidTokens()
{
return $this->hasInvalidTokens;
}
/**
* @param $type
* @throws \UnexpectedValueException
* @return boolean
*/
public function find($type)
{
$search = clone $this;
$search->skipUntil($type);
if (!$search->lookahead) {
throw new \UnexpectedValueException($type . ' not found');
}
return true;
}
/**
* getPrevious
*
* @return array token
*/
public function getPrevious()
{
return $this->previous;
}
/**
* moveNext
*
* @return boolean
*/
public function moveNext()
{
$this->previous = $this->token;
return parent::moveNext();
}
/**
* Lexical catchable patterns.
*
* @return string[]
*/
protected function getCatchablePatterns()
{
return array(
'[a-zA-Z_]+[46]?', //ASCII and domain literal
'[^\x00-\x7F]', //UTF-8
'[0-9]+',
'\r\n',
'::',
'\s+?',
'.',
);
}
/**
* Lexical non-catchable patterns.
*
* @return string[]
*/
protected function getNonCatchablePatterns()
{
return array('[\xA0-\xff]+');
}
/**
* Retrieve token type. Also processes the token value if necessary.
*
* @param string $value
* @throws \InvalidArgumentException
* @return integer
*/
protected function getType(&$value)
{
if ($this->isNullType($value)) {
return self::C_NUL;
}
if ($this->isValid($value)) {
return $this->charValue[$value];
}
if ($this->isUTF8Invalid($value)) {
$this->hasInvalidTokens = true;
return self::INVALID;
}
return self::GENERIC;
}
protected function isValid($value)
{
if (isset($this->charValue[$value])) {
return true;
}
return false;
}
/**
* @param $value
* @return bool
*/
protected function isNullType($value)
{
if ($value === "\0") {
return true;
}
return false;
}
/**
* @param $value
* @return bool
*/
protected function isUTF8Invalid($value)
{
if (preg_match('/\p{Cc}+/u', $value)) {
return true;
}
return false;
}
protected function getModifiers()
{
return 'iu';
}
}

View File

@ -0,0 +1,104 @@
<?php
namespace Egulias\EmailValidator;
use Egulias\EmailValidator\Exception\ExpectingATEXT;
use Egulias\EmailValidator\Exception\NoLocalPart;
use Egulias\EmailValidator\Parser\DomainPart;
use Egulias\EmailValidator\Parser\LocalPart;
use Egulias\EmailValidator\Warning\EmailTooLong;
/**
* EmailParser
*
* @author Eduardo Gulias Davis <me@egulias.com>
*/
class EmailParser
{
const EMAIL_MAX_LENGTH = 254;
protected $warnings;
protected $domainPart = '';
protected $localPart = '';
protected $lexer;
protected $localPartParser;
protected $domainPartParser;
public function __construct(EmailLexer $lexer)
{
$this->lexer = $lexer;
$this->localPartParser = new LocalPart($this->lexer);
$this->domainPartParser = new DomainPart($this->lexer);
$this->warnings = new \SplObjectStorage();
}
/**
* @param $str
* @return array
*/
public function parse($str)
{
$this->lexer->setInput($str);
if (!$this->hasAtToken()) {
throw new NoLocalPart();
}
$this->localPartParser->parse($str);
$this->domainPartParser->parse($str);
$this->setParts($str);
if ($this->lexer->hasInvalidTokens()) {
throw new ExpectingATEXT();
}
return array('local' => $this->localPart, 'domain' => $this->domainPart);
}
public function getWarnings()
{
$localPartWarnings = $this->localPartParser->getWarnings();
$domainPartWarnings = $this->domainPartParser->getWarnings();
$this->warnings = array_merge($localPartWarnings, $domainPartWarnings);
$this->addLongEmailWarning($this->localPart, $this->domainPart);
return $this->warnings;
}
public function getParsedDomainPart()
{
return $this->domainPart;
}
protected function setParts($email)
{
$parts = explode('@', $email);
$this->domainPart = $this->domainPartParser->getDomainPart();
$this->localPart = $parts[0];
}
protected function hasAtToken()
{
$this->lexer->moveNext();
$this->lexer->moveNext();
if ($this->lexer->token['type'] === EmailLexer::S_AT) {
return false;
}
return true;
}
/**
* @param string $localPart
* @param string $parsedDomainPart
*/
protected function addLongEmailWarning($localPart, $parsedDomainPart)
{
if (strlen($localPart . '@' . $parsedDomainPart) > self::EMAIL_MAX_LENGTH) {
$this->warnings[EmailTooLong::CODE] = new EmailTooLong();
}
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace Egulias\EmailValidator;
use Egulias\EmailValidator\Exception\InvalidEmail;
use Egulias\EmailValidator\Validation\EmailValidation;
class EmailValidator
{
/**
* @var EmailLexer
*/
private $lexer;
/**
* @var array
*/
protected $warnings;
/**
* @var InvalidEmail
*/
protected $error;
public function __construct()
{
$this->lexer = new EmailLexer();
}
/**
* @param $email
* @param EmailValidation $emailValidation
* @return bool
*/
public function isValid($email, EmailValidation $emailValidation)
{
$isValid = $emailValidation->isValid($email, $this->lexer);
$this->warnings = $emailValidation->getWarnings();
$this->error = $emailValidation->getError();
return $isValid;
}
/**
* @return boolean
*/
public function hasWarnings()
{
return !empty($this->warnings);
}
/**
* @return array
*/
public function getWarnings()
{
return $this->warnings;
}
/**
* @return InvalidEmail
*/
public function getError()
{
return $this->error;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class AtextAfterCFWS extends InvalidEmail
{
const CODE = 133;
const REASON = "ATEXT found after CFWS";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class CRLFAtTheEnd extends InvalidEmail
{
const CODE = 149;
const REASON = "CRLF at the end";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class CRLFX2 extends InvalidEmail
{
const CODE = 148;
const REASON = "Folding whitespace CR LF found twice";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class CRNoLF extends InvalidEmail
{
const CODE = 150;
const REASON = "Missing LF after CR";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class CharNotAllowed extends InvalidEmail
{
const CODE = 201;
const REASON = "Non allowed character in domain";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class CommaInDomain extends InvalidEmail
{
const CODE = 200;
const REASON = "Comma ',' is not allowed in domain part";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class ConsecutiveAt extends InvalidEmail
{
const CODE = 128;
const REASON = "Consecutive AT";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class ConsecutiveDot extends InvalidEmail
{
const CODE = 132;
const REASON = "Consecutive DOT";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class DomainHyphened extends InvalidEmail
{
const CODE = 144;
const REASON = "Hyphen found in domain";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class DotAtEnd extends InvalidEmail
{
const CODE = 142;
const REASON = "Dot at the end";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class DotAtStart extends InvalidEmail
{
const CODE = 141;
const REASON = "Found DOT at start";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class ExpectingAT extends InvalidEmail
{
const CODE = 202;
const REASON = "Expecting AT '@' ";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class ExpectingATEXT extends InvalidEmail
{
const CODE = 137;
const REASON = "Expecting ATEXT";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class ExpectingCTEXT extends InvalidEmail
{
const CODE = 139;
const REASON = "Expecting CTEXT";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class ExpectingDTEXT extends InvalidEmail
{
const CODE = 129;
const REASON = "Expected DTEXT";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class ExpectingDomainLiteralClose extends InvalidEmail
{
const CODE = 137;
const REASON = "Closing bracket ']' for domain literal not found";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class ExpectedQPair extends InvalidEmail
{
const CODE = 136;
const REASON = "Expecting QPAIR";
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Exception;
abstract class InvalidEmail extends \InvalidArgumentException
{
const REASON = "Invalid email";
const CODE = 0;
public function __construct()
{
parent::__construct(static::REASON, static::CODE);
}
}

View File

@ -0,0 +1,11 @@
<?php
namespace Egulias\EmailValidator\Exception;
use Egulias\EmailValidator\Exception\InvalidEmail;
class NoDNSRecord extends InvalidEmail
{
const CODE = 5;
const REASON = 'No MX or A DSN record was found for this email';
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class NoDomainPart extends InvalidEmail
{
const CODE = 131;
const REASON = "No Domain part";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class NoLocalPart extends InvalidEmail
{
const CODE = 130;
const REASON = "No local part";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class UnclosedComment extends InvalidEmail
{
const CODE = 146;
const REASON = "No colosing comment token found";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class UnclosedQuotedString extends InvalidEmail
{
const CODE = 145;
const REASON = "Unclosed quoted string";
}

View File

@ -0,0 +1,9 @@
<?php
namespace Egulias\EmailValidator\Exception;
class UnopenedComment extends InvalidEmail
{
const CODE = 152;
const REASON = "No opening comment token found";
}

View File

@ -0,0 +1,368 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Exception\CharNotAllowed;
use Egulias\EmailValidator\Exception\CommaInDomain;
use Egulias\EmailValidator\Exception\ConsecutiveAt;
use Egulias\EmailValidator\Exception\CRLFAtTheEnd;
use Egulias\EmailValidator\Exception\CRNoLF;
use Egulias\EmailValidator\Exception\DomainHyphened;
use Egulias\EmailValidator\Exception\DotAtEnd;
use Egulias\EmailValidator\Exception\DotAtStart;
use Egulias\EmailValidator\Exception\ExpectingATEXT;
use Egulias\EmailValidator\Exception\ExpectingDomainLiteralClose;
use Egulias\EmailValidator\Exception\ExpectingDTEXT;
use Egulias\EmailValidator\Exception\NoDomainPart;
use Egulias\EmailValidator\Exception\UnopenedComment;
use Egulias\EmailValidator\Warning\AddressLiteral;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Warning\DeprecatedComment;
use Egulias\EmailValidator\Warning\DomainLiteral;
use Egulias\EmailValidator\Warning\DomainTooLong;
use Egulias\EmailValidator\Warning\IPV6BadChar;
use Egulias\EmailValidator\Warning\IPV6ColonEnd;
use Egulias\EmailValidator\Warning\IPV6ColonStart;
use Egulias\EmailValidator\Warning\IPV6Deprecated;
use Egulias\EmailValidator\Warning\IPV6DoubleColon;
use Egulias\EmailValidator\Warning\IPV6GroupCount;
use Egulias\EmailValidator\Warning\IPV6MaxGroups;
use Egulias\EmailValidator\Warning\LabelTooLong;
use Egulias\EmailValidator\Warning\ObsoleteDTEXT;
use Egulias\EmailValidator\Warning\TLD;
class DomainPart extends Parser
{
const DOMAIN_MAX_LENGTH = 254;
protected $domainPart = '';
public function parse($domainPart)
{
$this->lexer->moveNext();
if ($this->lexer->token['type'] === EmailLexer::S_DOT) {
throw new DotAtStart();
}
if ($this->lexer->token['type'] === EmailLexer::S_EMPTY) {
throw new NoDomainPart();
}
if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN) {
throw new DomainHyphened();
}
if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) {
$this->warnings[DeprecatedComment::CODE] = new DeprecatedComment();
$this->parseDomainComments();
}
$domain = $this->doParseDomainPart();
$prev = $this->lexer->getPrevious();
$length = strlen($domain);
if ($prev['type'] === EmailLexer::S_DOT) {
throw new DotAtEnd();
}
if ($prev['type'] === EmailLexer::S_HYPHEN) {
throw new DomainHyphened();
}
if ($length > self::DOMAIN_MAX_LENGTH) {
$this->warnings[DomainTooLong::CODE] = new DomainTooLong();
}
if ($prev['type'] === EmailLexer::S_CR) {
throw new CRLFAtTheEnd();
}
$this->domainPart = $domain;
}
public function getDomainPart()
{
return $this->domainPart;
}
public function checkIPV6Tag($addressLiteral, $maxGroups = 8)
{
$prev = $this->lexer->getPrevious();
if ($prev['type'] === EmailLexer::S_COLON) {
$this->warnings[IPV6ColonEnd::CODE] = new IPV6ColonEnd();
}
$IPv6 = substr($addressLiteral, 5);
//Daniel Marschall's new IPv6 testing strategy
$matchesIP = explode(':', $IPv6);
$groupCount = count($matchesIP);
$colons = strpos($IPv6, '::');
if (count(preg_grep('/^[0-9A-Fa-f]{0,4}$/', $matchesIP, PREG_GREP_INVERT)) !== 0) {
$this->warnings[IPV6BadChar::CODE] = new IPV6BadChar();
}
if ($colons === false) {
// We need exactly the right number of groups
if ($groupCount !== $maxGroups) {
$this->warnings[IPV6GroupCount::CODE] = new IPV6GroupCount();
}
return;
}
if ($colons !== strrpos($IPv6, '::')) {
$this->warnings[IPV6DoubleColon::CODE] = new IPV6DoubleColon();
return;
}
if ($colons === 0 || $colons === (strlen($IPv6) - 2)) {
// RFC 4291 allows :: at the start or end of an address
//with 7 other groups in addition
++$maxGroups;
}
if ($groupCount > $maxGroups) {
$this->warnings[IPV6MaxGroups::CODE] = new IPV6MaxGroups();
} elseif ($groupCount === $maxGroups) {
$this->warnings[IPV6Deprecated::CODE] = new IPV6Deprecated();
}
}
protected function doParseDomainPart()
{
$domain = '';
$openedParenthesis = 0;
do {
$prev = $this->lexer->getPrevious();
$this->checkNotAllowedChars($this->lexer->token);
if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) {
$this->parseComments();
$openedParenthesis += $this->getOpenedParenthesis();
$this->lexer->moveNext();
$tmpPrev = $this->lexer->getPrevious();
if ($tmpPrev['type'] === EmailLexer::S_CLOSEPARENTHESIS) {
$openedParenthesis--;
}
}
if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) {
if ($openedParenthesis === 0) {
throw new UnopenedComment();
} else {
$openedParenthesis--;
}
}
$this->checkConsecutiveDots();
$this->checkDomainPartExceptions($prev);
if ($this->hasBrackets()) {
$this->parseDomainLiteral();
}
$this->checkLabelLength($prev);
if ($this->isFWS()) {
$this->parseFWS();
}
$domain .= $this->lexer->token['value'];
$this->lexer->moveNext();
} while ($this->lexer->token);
return $domain;
}
private function checkNotAllowedChars($token)
{
$notAllowed = [EmailLexer::S_BACKSLASH => true, EmailLexer::S_SLASH=> true];
if (isset($notAllowed[$token['type']])) {
throw new CharNotAllowed();
}
}
protected function parseDomainLiteral()
{
if ($this->lexer->isNextToken(EmailLexer::S_COLON)) {
$this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart();
}
if ($this->lexer->isNextToken(EmailLexer::S_IPV6TAG)) {
$lexer = clone $this->lexer;
$lexer->moveNext();
if ($lexer->isNextToken(EmailLexer::S_DOUBLECOLON)) {
$this->warnings[IPV6ColonStart::CODE] = new IPV6ColonStart();
}
}
return $this->doParseDomainLiteral();
}
protected function doParseDomainLiteral()
{
$IPv6TAG = false;
$addressLiteral = '';
do {
if ($this->lexer->token['type'] === EmailLexer::C_NUL) {
throw new ExpectingDTEXT();
}
if ($this->lexer->token['type'] === EmailLexer::INVALID ||
$this->lexer->token['type'] === EmailLexer::C_DEL ||
$this->lexer->token['type'] === EmailLexer::S_LF
) {
$this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT();
}
if ($this->lexer->isNextTokenAny(array(EmailLexer::S_OPENQBRACKET, EmailLexer::S_OPENBRACKET))) {
throw new ExpectingDTEXT();
}
if ($this->lexer->isNextTokenAny(
array(EmailLexer::S_HTAB, EmailLexer::S_SP, $this->lexer->token['type'] === EmailLexer::CRLF)
)) {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
$this->parseFWS();
}
if ($this->lexer->isNextToken(EmailLexer::S_CR)) {
throw new CRNoLF();
}
if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH) {
$this->warnings[ObsoleteDTEXT::CODE] = new ObsoleteDTEXT();
$addressLiteral .= $this->lexer->token['value'];
$this->lexer->moveNext();
$this->validateQuotedPair();
}
if ($this->lexer->token['type'] === EmailLexer::S_IPV6TAG) {
$IPv6TAG = true;
}
if ($this->lexer->token['type'] === EmailLexer::S_CLOSEQBRACKET) {
break;
}
$addressLiteral .= $this->lexer->token['value'];
} while ($this->lexer->moveNext());
$addressLiteral = str_replace('[', '', $addressLiteral);
$addressLiteral = $this->checkIPV4Tag($addressLiteral);
if (false === $addressLiteral) {
return $addressLiteral;
}
if (!$IPv6TAG) {
$this->warnings[DomainLiteral::CODE] = new DomainLiteral();
return $addressLiteral;
}
$this->warnings[AddressLiteral::CODE] = new AddressLiteral();
$this->checkIPV6Tag($addressLiteral);
return $addressLiteral;
}
protected function checkIPV4Tag($addressLiteral)
{
$matchesIP = array();
// Extract IPv4 part from the end of the address-literal (if there is one)
if (preg_match(
'/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/',
$addressLiteral,
$matchesIP
) > 0
) {
$index = strrpos($addressLiteral, $matchesIP[0]);
if ($index === 0) {
$this->warnings[AddressLiteral::CODE] = new AddressLiteral();
return false;
}
// Convert IPv4 part to IPv6 format for further testing
$addressLiteral = substr($addressLiteral, 0, $index) . '0:0';
}
return $addressLiteral;
}
protected function checkDomainPartExceptions($prev)
{
$invalidDomainTokens = array(
EmailLexer::S_DQUOTE => true,
EmailLexer::S_SEMICOLON => true,
EmailLexer::S_GREATERTHAN => true,
EmailLexer::S_LOWERTHAN => true,
);
if (isset($invalidDomainTokens[$this->lexer->token['type']])) {
throw new ExpectingATEXT();
}
if ($this->lexer->token['type'] === EmailLexer::S_COMMA) {
throw new CommaInDomain();
}
if ($this->lexer->token['type'] === EmailLexer::S_AT) {
throw new ConsecutiveAt();
}
if ($this->lexer->token['type'] === EmailLexer::S_OPENQBRACKET && $prev['type'] !== EmailLexer::S_AT) {
throw new ExpectingATEXT();
}
if ($this->lexer->token['type'] === EmailLexer::S_HYPHEN && $this->lexer->isNextToken(EmailLexer::S_DOT)) {
throw new DomainHyphened();
}
if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH
&& $this->lexer->isNextToken(EmailLexer::GENERIC)) {
throw new ExpectingATEXT();
}
}
protected function hasBrackets()
{
if ($this->lexer->token['type'] !== EmailLexer::S_OPENBRACKET) {
return false;
}
try {
$this->lexer->find(EmailLexer::S_CLOSEBRACKET);
} catch (\RuntimeException $e) {
throw new ExpectingDomainLiteralClose();
}
return true;
}
protected function checkLabelLength($prev)
{
if ($this->lexer->token['type'] === EmailLexer::S_DOT &&
$prev['type'] === EmailLexer::GENERIC &&
strlen($prev['value']) > 63
) {
$this->warnings[LabelTooLong::CODE] = new LabelTooLong();
}
}
protected function parseDomainComments()
{
$this->isUnclosedComment();
while (!$this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) {
$this->warnEscaping();
$this->lexer->moveNext();
}
$this->lexer->moveNext();
if ($this->lexer->isNextToken(EmailLexer::S_DOT)) {
throw new ExpectingATEXT();
}
}
protected function addTLDWarnings()
{
if ($this->warnings[DomainLiteral::CODE]) {
$this->warnings[TLD::CODE] = new TLD();
}
}
}

View File

@ -0,0 +1,138 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\Exception\DotAtEnd;
use Egulias\EmailValidator\Exception\DotAtStart;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Exception\ExpectingAT;
use Egulias\EmailValidator\Exception\ExpectingATEXT;
use Egulias\EmailValidator\Exception\UnclosedQuotedString;
use Egulias\EmailValidator\Exception\UnopenedComment;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Warning\LocalTooLong;
class LocalPart extends Parser
{
public function parse($localPart)
{
$parseDQuote = true;
$closingQuote = false;
$openedParenthesis = 0;
while ($this->lexer->token['type'] !== EmailLexer::S_AT && $this->lexer->token) {
if ($this->lexer->token['type'] === EmailLexer::S_DOT && !$this->lexer->getPrevious()) {
throw new DotAtStart();
}
$closingQuote = $this->checkDQUOTE($closingQuote);
if ($closingQuote && $parseDQuote) {
$parseDQuote = $this->parseDoubleQuote();
}
if ($this->lexer->token['type'] === EmailLexer::S_OPENPARENTHESIS) {
$this->parseComments();
$openedParenthesis += $this->getOpenedParenthesis();
}
if ($this->lexer->token['type'] === EmailLexer::S_CLOSEPARENTHESIS) {
if ($openedParenthesis === 0) {
throw new UnopenedComment();
} else {
$openedParenthesis--;
}
}
$this->checkConsecutiveDots();
if ($this->lexer->token['type'] === EmailLexer::S_DOT &&
$this->lexer->isNextToken(EmailLexer::S_AT)
) {
throw new DotAtEnd();
}
$this->warnEscaping();
$this->isInvalidToken($this->lexer->token, $closingQuote);
if ($this->isFWS()) {
$this->parseFWS();
}
$this->lexer->moveNext();
}
$prev = $this->lexer->getPrevious();
if (strlen($prev['value']) > LocalTooLong::LOCAL_PART_LENGTH) {
$this->warnings[LocalTooLong::CODE] = new LocalTooLong();
}
}
protected function parseDoubleQuote()
{
$parseAgain = true;
$special = array(
EmailLexer::S_CR => true,
EmailLexer::S_HTAB => true,
EmailLexer::S_LF => true
);
$invalid = array(
EmailLexer::C_NUL => true,
EmailLexer::S_HTAB => true,
EmailLexer::S_CR => true,
EmailLexer::S_LF => true
);
$setSpecialsWarning = true;
$this->lexer->moveNext();
while ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE && $this->lexer->token) {
$parseAgain = false;
if (isset($special[$this->lexer->token['type']]) && $setSpecialsWarning) {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
$setSpecialsWarning = false;
}
if ($this->lexer->token['type'] === EmailLexer::S_BACKSLASH && $this->lexer->isNextToken(EmailLexer::S_DQUOTE)) {
$this->lexer->moveNext();
}
$this->lexer->moveNext();
if (!$this->escaped() && isset($invalid[$this->lexer->token['type']])) {
throw new ExpectingATEXT();
}
}
$prev = $this->lexer->getPrevious();
if ($prev['type'] === EmailLexer::S_BACKSLASH) {
if (!$this->checkDQUOTE(false)) {
throw new UnclosedQuotedString();
}
}
if (!$this->lexer->isNextToken(EmailLexer::S_AT) && $prev['type'] !== EmailLexer::S_BACKSLASH) {
throw new ExpectingAT();
}
return $parseAgain;
}
protected function isInvalidToken($token, $closingQuote)
{
$forbidden = array(
EmailLexer::S_COMMA,
EmailLexer::S_CLOSEBRACKET,
EmailLexer::S_OPENBRACKET,
EmailLexer::S_GREATERTHAN,
EmailLexer::S_LOWERTHAN,
EmailLexer::S_COLON,
EmailLexer::S_SEMICOLON,
EmailLexer::INVALID
);
if (in_array($token['type'], $forbidden) && !$closingQuote) {
throw new ExpectingATEXT();
}
}
}

View File

@ -0,0 +1,215 @@
<?php
namespace Egulias\EmailValidator\Parser;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Exception\AtextAfterCFWS;
use Egulias\EmailValidator\Exception\ConsecutiveDot;
use Egulias\EmailValidator\Exception\CRLFAtTheEnd;
use Egulias\EmailValidator\Exception\CRLFX2;
use Egulias\EmailValidator\Exception\CRNoLF;
use Egulias\EmailValidator\Exception\ExpectedQPair;
use Egulias\EmailValidator\Exception\ExpectingATEXT;
use Egulias\EmailValidator\Exception\ExpectingCTEXT;
use Egulias\EmailValidator\Exception\UnclosedComment;
use Egulias\EmailValidator\Exception\UnclosedQuotedString;
use Egulias\EmailValidator\Warning\CFWSNearAt;
use Egulias\EmailValidator\Warning\CFWSWithFWS;
use Egulias\EmailValidator\Warning\Comment;
use Egulias\EmailValidator\Warning\QuotedPart;
use Egulias\EmailValidator\Warning\QuotedString;
abstract class Parser
{
protected $warnings = [];
protected $lexer;
protected $openedParenthesis = 0;
public function __construct(EmailLexer $lexer)
{
$this->lexer = $lexer;
}
public function getWarnings()
{
return $this->warnings;
}
abstract public function parse($str);
/** @return int */
public function getOpenedParenthesis()
{
return $this->openedParenthesis;
}
/**
* validateQuotedPair
*/
protected function validateQuotedPair()
{
if (!($this->lexer->token['type'] === EmailLexer::INVALID
|| $this->lexer->token['type'] === EmailLexer::C_DEL)) {
throw new ExpectedQPair();
}
$this->warnings[QuotedPart::CODE] =
new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']);
}
protected function parseComments()
{
$this->openedParenthesis = 1;
$this->isUnclosedComment();
$this->warnings[Comment::CODE] = new Comment();
while (!$this->lexer->isNextToken(EmailLexer::S_CLOSEPARENTHESIS)) {
if ($this->lexer->isNextToken(EmailLexer::S_OPENPARENTHESIS)) {
$this->openedParenthesis++;
}
$this->warnEscaping();
$this->lexer->moveNext();
}
$this->lexer->moveNext();
if ($this->lexer->isNextTokenAny(array(EmailLexer::GENERIC, EmailLexer::S_EMPTY))) {
throw new ExpectingATEXT();
}
if ($this->lexer->isNextToken(EmailLexer::S_AT)) {
$this->warnings[CFWSNearAt::CODE] = new CFWSNearAt();
}
}
protected function isUnclosedComment()
{
try {
$this->lexer->find(EmailLexer::S_CLOSEPARENTHESIS);
return true;
} catch (\RuntimeException $e) {
throw new UnclosedComment();
}
}
protected function parseFWS()
{
$previous = $this->lexer->getPrevious();
$this->checkCRLFInFWS();
if ($this->lexer->token['type'] === EmailLexer::S_CR) {
throw new CRNoLF();
}
if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] !== EmailLexer::S_AT) {
throw new AtextAfterCFWS();
}
if ($this->lexer->token['type'] === EmailLexer::S_LF || $this->lexer->token['type'] === EmailLexer::C_NUL) {
throw new ExpectingCTEXT();
}
if ($this->lexer->isNextToken(EmailLexer::S_AT) || $previous['type'] === EmailLexer::S_AT) {
$this->warnings[CFWSNearAt::CODE] = new CFWSNearAt();
} else {
$this->warnings[CFWSWithFWS::CODE] = new CFWSWithFWS();
}
}
protected function checkConsecutiveDots()
{
if ($this->lexer->token['type'] === EmailLexer::S_DOT && $this->lexer->isNextToken(EmailLexer::S_DOT)) {
throw new ConsecutiveDot();
}
}
protected function isFWS()
{
if ($this->escaped()) {
return false;
}
if ($this->lexer->token['type'] === EmailLexer::S_SP ||
$this->lexer->token['type'] === EmailLexer::S_HTAB ||
$this->lexer->token['type'] === EmailLexer::S_CR ||
$this->lexer->token['type'] === EmailLexer::S_LF ||
$this->lexer->token['type'] === EmailLexer::CRLF
) {
return true;
}
return false;
}
protected function escaped()
{
$previous = $this->lexer->getPrevious();
if ($previous['type'] === EmailLexer::S_BACKSLASH
&&
$this->lexer->token['type'] !== EmailLexer::GENERIC
) {
return true;
}
return false;
}
protected function warnEscaping()
{
if ($this->lexer->token['type'] !== EmailLexer::S_BACKSLASH) {
return false;
}
if ($this->lexer->isNextToken(EmailLexer::GENERIC)) {
throw new ExpectingATEXT();
}
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB, EmailLexer::C_DEL))) {
return false;
}
$this->warnings[QuotedPart::CODE] =
new QuotedPart($this->lexer->getPrevious()['type'], $this->lexer->token['type']);
return true;
}
protected function checkDQUOTE($hasClosingQuote)
{
if ($this->lexer->token['type'] !== EmailLexer::S_DQUOTE) {
return $hasClosingQuote;
}
if ($hasClosingQuote) {
return $hasClosingQuote;
}
$previous = $this->lexer->getPrevious();
if ($this->lexer->isNextToken(EmailLexer::GENERIC) && $previous['type'] === EmailLexer::GENERIC) {
throw new ExpectingATEXT();
}
try {
$this->lexer->find(EmailLexer::S_DQUOTE);
$hasClosingQuote = true;
} catch (\Exception $e) {
throw new UnclosedQuotedString();
}
$this->warnings[QuotedString::CODE] = new QuotedString($previous['value'], $this->lexer->token['value']);
return $hasClosingQuote;
}
protected function checkCRLFInFWS()
{
if ($this->lexer->token['type'] !== EmailLexer::CRLF) {
return;
}
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) {
throw new CRLFX2();
}
if (!$this->lexer->isNextTokenAny(array(EmailLexer::S_SP, EmailLexer::S_HTAB))) {
throw new CRLFAtTheEnd();
}
}
}

View File

@ -0,0 +1,61 @@
<?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Exception\InvalidEmail;
use Egulias\EmailValidator\Warning\NoDNSMXRecord;
use Egulias\EmailValidator\Exception\NoDNSRecord;
class DNSCheckValidation implements EmailValidation
{
/**
* @var array
*/
private $warnings = [];
/**
* @var InvalidEmail
*/
private $error;
public function isValid($email, EmailLexer $emailLexer)
{
// use the input to check DNS if we cannot extract something similar to a domain
$host = $email;
// Arguable pattern to extract the domain. Not aiming to validate the domain nor the email
if (false !== $lastAtPos = strrpos($email, '@')) {
$host = substr($email, $lastAtPos + 1);
}
return $this->checkDNS($host);
}
public function getError()
{
return $this->error;
}
public function getWarnings()
{
return $this->warnings;
}
protected function checkDNS($host)
{
$host = rtrim($host, '.') . '.';
$Aresult = true;
$MXresult = checkdnsrr($host, 'MX');
if (!$MXresult) {
$this->warnings[NoDNSMXRecord::CODE] = new NoDNSMXRecord();
$Aresult = checkdnsrr($host, 'A') || checkdnsrr($host, 'AAAA');
if (!$Aresult) {
$this->error = new NoDNSRecord();
}
}
return $MXresult || $Aresult;
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Exception\InvalidEmail;
use Egulias\EmailValidator\Warning\Warning;
interface EmailValidation
{
/**
* Returns true if the given email is valid.
*
* @param string $email The email you want to validate.
* @param EmailLexer $emailLexer The email lexer.
*
* @return bool
*/
public function isValid($email, EmailLexer $emailLexer);
/**
* Returns the validation error.
*
* @return InvalidEmail|null
*/
public function getError();
/**
* Returns the validation warnings.
*
* @return Warning[]
*/
public function getWarnings();
}

View File

@ -0,0 +1,11 @@
<?php
namespace Egulias\EmailValidator\Validation\Error;
use Egulias\EmailValidator\Exception\InvalidEmail;
class RFCWarnings extends InvalidEmail
{
const CODE = 997;
const REASON = 'Warnings were found.';
}

View File

@ -0,0 +1,11 @@
<?php
namespace Egulias\EmailValidator\Validation\Error;
use Egulias\EmailValidator\Exception\InvalidEmail;
class SpoofEmail extends InvalidEmail
{
const CODE = 998;
const REASON = "The email contains mixed UTF8 chars that makes it suspicious";
}

View File

@ -0,0 +1,13 @@
<?php
namespace Egulias\EmailValidator\Validation\Exception;
use Exception;
class EmptyValidationList extends \InvalidArgumentException
{
public function __construct($code = 0, Exception $previous = null)
{
parent::__construct("Empty validation list is not allowed", $code, $previous);
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\Exception\InvalidEmail;
class MultipleErrors extends InvalidEmail
{
const CODE = 999;
const REASON = "Accumulated errors for multiple validations";
/**
* @var array
*/
private $errors = [];
public function __construct(array $errors)
{
$this->errors = $errors;
parent::__construct();
}
public function getErrors()
{
return $this->errors;
}
}

View File

@ -0,0 +1,110 @@
<?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Validation\Exception\EmptyValidationList;
class MultipleValidationWithAnd implements EmailValidation
{
/**
* If one of validations gets failure skips all succeeding validation.
* This means MultipleErrors will only contain a single error which first found.
*/
const STOP_ON_ERROR = 0;
/**
* All of validations will be invoked even if one of them got failure.
* So MultipleErrors will contain all causes.
*/
const ALLOW_ALL_ERRORS = 1;
/**
* @var EmailValidation[]
*/
private $validations = [];
/**
* @var array
*/
private $warnings = [];
/**
* @var MultipleErrors
*/
private $error;
/**
* @var bool
*/
private $mode;
/**
* @param EmailValidation[] $validations The validations.
* @param int $mode The validation mode (one of the constants).
*/
public function __construct(array $validations, $mode = self::ALLOW_ALL_ERRORS)
{
if (count($validations) == 0) {
throw new EmptyValidationList();
}
$this->validations = $validations;
$this->mode = $mode;
}
/**
* {@inheritdoc}
*/
public function isValid($email, EmailLexer $emailLexer)
{
$result = true;
$errors = [];
foreach ($this->validations as $validation) {
$emailLexer->reset();
$result = $result && $validation->isValid($email, $emailLexer);
$this->warnings = array_merge($this->warnings, $validation->getWarnings());
$errors = $this->addNewError($validation->getError(), $errors);
if ($this->shouldStop($result)) {
break;
}
}
if (!empty($errors)) {
$this->error = new MultipleErrors($errors);
}
return $result;
}
private function addNewError($possibleError, array $errors)
{
if (null !== $possibleError) {
$errors[] = $possibleError;
}
return $errors;
}
private function shouldStop($result)
{
return !$result && $this->mode === self::STOP_ON_ERROR;
}
/**
* {@inheritdoc}
*/
public function getError()
{
return $this->error;
}
/**
* {@inheritdoc}
*/
public function getWarnings()
{
return $this->warnings;
}
}

View File

@ -0,0 +1,42 @@
<?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Exception\InvalidEmail;
use Egulias\EmailValidator\Validation\Error\RFCWarnings;
class NoRFCWarningsValidation extends RFCValidation
{
/**
* @var InvalidEmail
*/
private $error;
/**
* {@inheritdoc}
*/
public function isValid($email, EmailLexer $emailLexer)
{
if (!parent::isValid($email, $emailLexer)) {
return false;
}
$ret = $this->getWarnings();
if (empty($ret)) {
return true;
}
$this->error = new RFCWarnings();
return false;
}
/**
* {@inheritdoc}
*/
public function getError()
{
return $this->error ?: parent::getError();
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\EmailParser;
use Egulias\EmailValidator\Exception\InvalidEmail;
class RFCValidation implements EmailValidation
{
/**
* @var EmailParser
*/
private $parser;
/**
* @var array
*/
private $warnings = [];
/**
* @var InvalidEmail
*/
private $error;
public function isValid($email, EmailLexer $emailLexer)
{
$this->parser = new EmailParser($emailLexer);
try {
$this->parser->parse((string)$email);
} catch (InvalidEmail $invalid) {
$this->error = $invalid;
return false;
}
$this->warnings = $this->parser->getWarnings();
return true;
}
public function getError()
{
return $this->error;
}
public function getWarnings()
{
return $this->warnings;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace Egulias\EmailValidator\Validation;
use Egulias\EmailValidator\EmailLexer;
use Egulias\EmailValidator\Exception\InvalidEmail;
use Egulias\EmailValidator\Validation\Error\SpoofEmail;
use \Spoofchecker;
class SpoofCheckValidation implements EmailValidation
{
/**
* @var InvalidEmail
*/
private $error;
public function __construct()
{
if (!extension_loaded('intl')) {
throw new \LogicException(sprintf('The %s class requires the Intl extension.', __CLASS__));
}
}
public function isValid($email, EmailLexer $emailLexer)
{
$checker = new Spoofchecker();
$checker->setChecks(Spoofchecker::SINGLE_SCRIPT);
if ($checker->isSuspicious($email)) {
$this->error = new SpoofEmail();
}
return $this->error === null;
}
public function getError()
{
return $this->error;
}
public function getWarnings()
{
return [];
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class AddressLiteral extends Warning
{
const CODE = 12;
public function __construct()
{
$this->message = 'Address literal in domain part';
$this->rfcNumber = 5321;
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Egulias\EmailValidator\Warning;
class CFWSNearAt extends Warning
{
const CODE = 49;
public function __construct()
{
$this->message = "Deprecated folding white space near @";
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Egulias\EmailValidator\Warning;
class CFWSWithFWS extends Warning
{
const CODE = 18;
public function __construct()
{
$this->message = 'Folding whites space followed by folding white space';
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Egulias\EmailValidator\Warning;
class Comment extends Warning
{
const CODE = 17;
public function __construct()
{
$this->message = "Comments found in this email";
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Egulias\EmailValidator\Warning;
class DeprecatedComment extends Warning
{
const CODE = 37;
public function __construct()
{
$this->message = 'Deprecated comments';
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class DomainLiteral extends Warning
{
const CODE = 70;
public function __construct()
{
$this->message = 'Domain Literal';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class DomainTooLong extends Warning
{
const CODE = 255;
public function __construct()
{
$this->message = 'Domain is too long, exceeds 255 chars';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Egulias\EmailValidator\Warning;
use Egulias\EmailValidator\EmailParser;
class EmailTooLong extends Warning
{
const CODE = 66;
public function __construct()
{
$this->message = 'Email is too long, exceeds ' . EmailParser::EMAIL_MAX_LENGTH;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class IPV6BadChar extends Warning
{
const CODE = 74;
public function __construct()
{
$this->message = 'Bad char in IPV6 domain literal';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class IPV6ColonEnd extends Warning
{
const CODE = 77;
public function __construct()
{
$this->message = ':: found at the end of the domain literal';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class IPV6ColonStart extends Warning
{
const CODE = 76;
public function __construct()
{
$this->message = ':: found at the start of the domain literal';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class IPV6Deprecated extends Warning
{
const CODE = 13;
public function __construct()
{
$this->message = 'Deprecated form of IPV6';
$this->rfcNumber = 5321;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class IPV6DoubleColon extends Warning
{
const CODE = 73;
public function __construct()
{
$this->message = 'Double colon found after IPV6 tag';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class IPV6GroupCount extends Warning
{
const CODE = 72;
public function __construct()
{
$this->message = 'Group count is not IPV6 valid';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class IPV6MaxGroups extends Warning
{
const CODE = 75;
public function __construct()
{
$this->message = 'Reached the maximum number of IPV6 groups allowed';
$this->rfcNumber = 5321;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class LabelTooLong extends Warning
{
const CODE = 63;
public function __construct()
{
$this->message = 'Label too long';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace Egulias\EmailValidator\Warning;
class LocalTooLong extends Warning
{
const CODE = 64;
const LOCAL_PART_LENGTH = 64;
public function __construct()
{
$this->message = 'Local part is too long, exceeds 64 chars (octets)';
$this->rfcNumber = 5322;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class NoDNSMXRecord extends Warning
{
const CODE = 6;
public function __construct()
{
$this->message = 'No MX DSN record was found for this email';
$this->rfcNumber = 5321;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Egulias\EmailValidator\Warning;
class ObsoleteDTEXT extends Warning
{
const CODE = 71;
public function __construct()
{
$this->rfcNumber = 5322;
$this->message = 'Obsolete DTEXT in domain literal';
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Egulias\EmailValidator\Warning;
class QuotedPart extends Warning
{
const CODE = 36;
public function __construct($prevToken, $postToken)
{
$this->message = "Deprecated Quoted String found between $prevToken and $postToken";
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Egulias\EmailValidator\Warning;
class QuotedString extends Warning
{
const CODE = 11;
public function __construct($prevToken, $postToken)
{
$this->message = "Quoted String found between $prevToken and $postToken";
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Egulias\EmailValidator\Warning;
class TLD extends Warning
{
const CODE = 9;
public function __construct()
{
$this->message = "RFC5321, TLD";
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Egulias\EmailValidator\Warning;
abstract class Warning
{
const CODE = 0;
protected $message;
protected $rfcNumber;
public function message()
{
return $this->message;
}
public function code()
{
return self::CODE;
}
public function RFCNumber()
{
return $this->rfcNumber;
}
public function __toString()
{
return $this->message() . " rfc: " . $this->rfcNumber . "interal code: " . static::CODE;
}
}

View File

@ -0,0 +1,19 @@
Copyright (c) 2013-2016 Eduardo Gulias Davis
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,79 @@
# EmailValidator
[![Build Status](https://travis-ci.org/egulias/EmailValidator.png?branch=master)](https://travis-ci.org/egulias/EmailValidator) [![Coverage Status](https://coveralls.io/repos/egulias/EmailValidator/badge.png?branch=master)](https://coveralls.io/r/egulias/EmailValidator?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/egulias/EmailValidator/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/egulias/EmailValidator/?branch=master) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/22ba6692-9c02-42e5-a65d-1c5696bfffc6/small.png)](https://insight.sensiolabs.com/projects/22ba6692-9c02-42e5-a65d-1c5696bfffc6)
=============================
With the help of [PHPStorm](https://www.jetbrains.com/phpstorm/)
## Requirements ##
* [Composer](https://getcomposer.org) is required for installation
* [Spoofchecking](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/SpoofCheckValidation.php) validation requires that your PHP system have the [PHP Internationalization Libraries](http://php.net/manual/en/book.intl.php) (also known as PHP Intl)
## Installation ##
Run the command below to install via Composer
```shell
composer require egulias/email-validator "~2.1"
```
## Getting Started ##
`EmailValidator`requires you to decide which (or combination of them) validation/s strategy/ies you'd like to follow for each [validation](#available-validations).
A basic example with the RFC validation
```php
<?php
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
$validator = new EmailValidator();
$validator->isValid("example@example.com", new RFCValidation()); //true
```
### Available validations ###
1. [RFCValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/RFCValidation.php)
2. [NoRFCWarningsValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/NoRFCWarningsValidation.php)
3. [DNSCheckValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/DNSCheckValidation.php)
4. [SpoofCheckValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/SpoofCheckValidation.php)
5. [MultipleValidationWithAnd](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/MultipleValidationWithAnd.php)
6. [Your own validation](#how-to-extend)
`MultipleValidationWithAnd`
It is a validation that operates over other validations performing a logical and (&&) over the result of each validation.
```php
<?php
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\DNSCheckValidation;
use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
use Egulias\EmailValidator\Validation\RFCValidation;
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
new RFCValidation(),
new DNSCheckValidation()
]);
$validator->isValid("example@example.com", $multipleValidations); //true
```
### How to extend ###
It's easy! You just need to extend [EmailValidation](https://github.com/egulias/EmailValidator/blob/master/EmailValidator/Validation/EmailValidation.php) and you can use your own validation.
## Other Contributors ##
(You can find current contributors [here](https://github.com/egulias/EmailValidator/graphs/contributors))
As this is a port from another library and work, here are other people related to the previous one:
* Ricard Clau [@ricardclau](http://github.com/ricardclau): Performance against PHP built-in filter_var
* Josepf Bielawski [@stloyd](http://github.com/stloyd): For its first re-work of Dominic's lib
* Dominic Sayers [@dominicsayers](http://github.com/dominicsayers): The original isemail function
## License ##
Released under the MIT License attached with this code.

View File

@ -0,0 +1,19 @@
Copyright (c) 2006-2013 Doctrine Project
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,5 @@
# Doctrine Lexer
Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.
This lexer is used in Doctrine Annotations and in Doctrine ORM (DQL).

View File

@ -0,0 +1,24 @@
{
"name": "doctrine/lexer",
"type": "library",
"description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.",
"keywords": ["lexer", "parser"],
"homepage": "http://www.doctrine-project.org",
"license": "MIT",
"authors": [
{"name": "Guilherme Blanco", "email": "guilhermeblanco@gmail.com"},
{"name": "Roman Borschel", "email": "roman@code-factory.org"},
{"name": "Johannes Schmitt", "email": "schmittjoh@gmail.com"}
],
"require": {
"php": ">=5.3.2"
},
"autoload": {
"psr-0": { "Doctrine\\Common\\Lexer\\": "lib/" }
},
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
}
}

View File

@ -0,0 +1,327 @@
<?php
/*
* 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
* OWNER 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\Lexer;
/**
* Base class for writing simple lexers, i.e. for creating small DSLs.
*
* @since 2.0
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
*/
abstract class AbstractLexer
{
/**
* Lexer original input string.
*
* @var string
*/
private $input;
/**
* Array of scanned tokens.
*
* Each token is an associative array containing three items:
* - 'value' : the string value of the token in the input string
* - 'type' : the type of the token (identifier, numeric, string, input
* parameter, none)
* - 'position' : the position of the token in the input string
*
* @var array
*/
private $tokens = array();
/**
* Current lexer position in input string.
*
* @var integer
*/
private $position = 0;
/**
* Current peek of current lexer position.
*
* @var integer
*/
private $peek = 0;
/**
* The next token in the input.
*
* @var array
*/
public $lookahead;
/**
* The last matched/seen token.
*
* @var array
*/
public $token;
/**
* Sets the input data to be tokenized.
*
* The Lexer is immediately reset and the new input tokenized.
* Any unprocessed tokens from any previous input are lost.
*
* @param string $input The input to be tokenized.
*
* @return void
*/
public function setInput($input)
{
$this->input = $input;
$this->tokens = array();
$this->reset();
$this->scan($input);
}
/**
* Resets the lexer.
*
* @return void
*/
public function reset()
{
$this->lookahead = null;
$this->token = null;
$this->peek = 0;
$this->position = 0;
}
/**
* Resets the peek pointer to 0.
*
* @return void
*/
public function resetPeek()
{
$this->peek = 0;
}
/**
* Resets the lexer position on the input to the given position.
*
* @param integer $position Position to place the lexical scanner.
*
* @return void
*/
public function resetPosition($position = 0)
{
$this->position = $position;
}
/**
* Retrieve the original lexer's input until a given position.
*
* @param integer $position
*
* @return string
*/
public function getInputUntilPosition($position)
{
return substr($this->input, 0, $position);
}
/**
* Checks whether a given token matches the current lookahead.
*
* @param integer|string $token
*
* @return boolean
*/
public function isNextToken($token)
{
return null !== $this->lookahead && $this->lookahead['type'] === $token;
}
/**
* Checks whether any of the given tokens matches the current lookahead.
*
* @param array $tokens
*
* @return boolean
*/
public function isNextTokenAny(array $tokens)
{
return null !== $this->lookahead && in_array($this->lookahead['type'], $tokens, true);
}
/**
* Moves to the next token in the input string.
*
* @return boolean
*/
public function moveNext()
{
$this->peek = 0;
$this->token = $this->lookahead;
$this->lookahead = (isset($this->tokens[$this->position]))
? $this->tokens[$this->position++] : null;
return $this->lookahead !== null;
}
/**
* Tells the lexer to skip input tokens until it sees a token with the given value.
*
* @param string $type The token type to skip until.
*
* @return void
*/
public function skipUntil($type)
{
while ($this->lookahead !== null && $this->lookahead['type'] !== $type) {
$this->moveNext();
}
}
/**
* Checks if given value is identical to the given token.
*
* @param mixed $value
* @param integer $token
*
* @return boolean
*/
public function isA($value, $token)
{
return $this->getType($value) === $token;
}
/**
* Moves the lookahead token forward.
*
* @return array|null The next token or NULL if there are no more tokens ahead.
*/
public function peek()
{
if (isset($this->tokens[$this->position + $this->peek])) {
return $this->tokens[$this->position + $this->peek++];
} else {
return null;
}
}
/**
* Peeks at the next token, returns it and immediately resets the peek.
*
* @return array|null The next token or NULL if there are no more tokens ahead.
*/
public function glimpse()
{
$peek = $this->peek();
$this->peek = 0;
return $peek;
}
/**
* Scans the input string for tokens.
*
* @param string $input A query string.
*
* @return void
*/
protected function scan($input)
{
static $regex;
if ( ! isset($regex)) {
$regex = sprintf(
'/(%s)|%s/%s',
implode(')|(', $this->getCatchablePatterns()),
implode('|', $this->getNonCatchablePatterns()),
$this->getModifiers()
);
}
$flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_OFFSET_CAPTURE;
$matches = preg_split($regex, $input, -1, $flags);
foreach ($matches as $match) {
// Must remain before 'value' assignment since it can change content
$type = $this->getType($match[0]);
$this->tokens[] = array(
'value' => $match[0],
'type' => $type,
'position' => $match[1],
);
}
}
/**
* Gets the literal for a given token.
*
* @param integer $token
*
* @return string
*/
public function getLiteral($token)
{
$className = get_class($this);
$reflClass = new \ReflectionClass($className);
$constants = $reflClass->getConstants();
foreach ($constants as $name => $value) {
if ($value === $token) {
return $className . '::' . $name;
}
}
return $token;
}
/**
* Regex modifiers
*
* @return string
*/
protected function getModifiers()
{
return 'i';
}
/**
* Lexical catchable patterns.
*
* @return array
*/
abstract protected function getCatchablePatterns();
/**
* Lexical non-catchable patterns.
*
* @return array
*/
abstract protected function getNonCatchablePatterns();
/**
* Retrieve token type. Also processes the token value if necessary.
*
* @param string $value
*
* @return integer
*/
abstract protected function getType(&$value);
}

View File

@ -0,0 +1,78 @@
<?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.2.7';
public static $initialized = false;
public static $inits = [];
/**
* 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(['Swift', 'autoload']);
}
}

View File

@ -0,0 +1,25 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2018 Christian Schmidt
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Email address encoder.
*
* @author Christian Schmidt
*/
interface Swift_AddressEncoder
{
/**
* Encodes an email address.
*
* @throws Swift_AddressEncoderException if the email cannot be represented in
* the encoding implemented by this class
*/
public function encodeString(string $address): string;
}

View File

@ -0,0 +1,50 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2018 Christian Schmidt
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* An IDN email address encoder.
*
* Encodes the domain part of an address using IDN. This is compatible will all
* SMTP servers.
*
* This encoder does not support email addresses with non-ASCII characters in
* local-part (the substring before @). To send to such addresses, use
* Swift_AddressEncoder_Utf8AddressEncoder together with
* Swift_Transport_Esmtp_SmtpUtf8Handler. Your outbound SMTP server must support
* the SMTPUTF8 extension.
*
* @author Christian Schmidt
*/
class Swift_AddressEncoder_IdnAddressEncoder implements Swift_AddressEncoder
{
/**
* Encodes the domain part of an address using IDN.
*
* @throws Swift_AddressEncoderException If local-part contains non-ASCII characters
*/
public function encodeString(string $address): string
{
$i = strrpos($address, '@');
if (false !== $i) {
$local = substr($address, 0, $i);
$domain = substr($address, $i + 1);
if (preg_match('/[^\x00-\x7F]/', $local)) {
throw new Swift_AddressEncoderException('Non-ASCII characters not supported in local-part', $address);
}
if (preg_match('/[^\x00-\x7F]/', $domain)) {
$address = sprintf('%s@%s', $local, idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46));
}
}
return $address;
}
}

View File

@ -0,0 +1,36 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2018 Christian Schmidt
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* A UTF-8 email address encoder.
*
* Returns the email address verbatimly in UTF-8 as permitted by RFC 6531 and
* RFC 6532. It supports addresses containing non-ASCII characters in both
* local-part and domain (i.e. on both sides of @).
*
* This encoder must be used together with Swift_Transport_Esmtp_SmtpUtf8Handler
* and requires that the outbound SMTP server supports the SMTPUTF8 extension.
*
* If your outbound SMTP server does not support SMTPUTF8, use
* Swift_AddressEncoder_IdnAddressEncoder instead. This allows sending to email
* addresses with non-ASCII characters in the domain, but not in local-part.
*
* @author Christian Schmidt
*/
class Swift_AddressEncoder_Utf8AddressEncoder implements Swift_AddressEncoder
{
/**
* Returns the address verbatimly.
*/
public function encodeString(string $address): string
{
return $address;
}
}

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of SwiftMailer.
* (c) 2018 Christian Schmidt
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* AddressEncoderException when the specified email address is in a format that
* cannot be encoded by a given address encoder.
*
* @author Christian Schmidt
*/
class Swift_AddressEncoderException extends Swift_RfcComplianceException
{
protected $address;
public function __construct(string $message, string $address)
{
parent::__construct($message);
$this->address = $address;
}
public function getAddress(): string
{
return $this->address;
}
}

View File

@ -0,0 +1,54 @@
<?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(
[$this, 'Swift_Mime_Attachment::__construct'],
Swift_DependencyContainer::getInstance()
->createDependenciesFor('mime.attachment')
);
$this->setBody($data, $contentType);
$this->setFilename($filename);
}
/**
* Create a new Attachment from a filesystem path.
*
* @param string $path
* @param string $contentType optional
*
* @return self
*/
public static function fromPath($path, $contentType = null)
{
return (new self())->setFile(
new Swift_ByteStream_FileByteStream($path),
$contentType
);
}
}

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.
*/
/**
* 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 = [];
/**
* A buffer for writing.
*/
private $writeBuffer = '';
/**
* Bound streams.
*
* @var Swift_InputByteStream[]
*/
private $mirrors = [];
/**
* 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 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.
*/
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.
*/
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,178 @@
<?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 = [];
/**
* 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 = [];
/**
* 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 = [];
}
}
/**
* 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.
*/
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.
*/
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 = [];
$this->arraySize = 0;
foreach ($this->mirrors as $stream) {
$stream->flushBuffers();
}
}
}

View File

@ -0,0 +1,214 @@
<?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 ((false === $bytes || '' === $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 (0 != $this->offset) {
$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 (null === $this->seekable) {
$this->getReadStreamSeekableStatus();
}
if (false === $this->seekable) {
$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,52 @@
<?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 (false === $filePath) {
throw new Swift_IoException('Failed to retrieve temporary file name.');
}
parent::__construct($filePath, true);
}
public function getContent()
{
if (false === ($content = file_get_contents($this->getPath()))) {
throw new Swift_IoException('Failed to get temporary file content.');
}
return $content;
}
public function __destruct()
{
if (file_exists($this->getPath())) {
@unlink($this->getPath());
}
}
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
}

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 = [
// 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 = [
"\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'] = [];
}
$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 (0 == $size) {
/* char is invalid, we must wait for a resync */
$invalid = true;
continue;
} else {
if (true === $invalid) {
/* 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 = [];
/**
* Factories which have already been loaded.
*
* @var Swift_CharacterReaderFactory[]
*/
private static $loaded = [];
/**
* 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 = [
'class' => $prefix.'GenericFixedWidthReader',
'constructor' => [1],
];
$doubleByte = [
'class' => $prefix.'GenericFixedWidthReader',
'constructor' => [2],
];
$fourBytes = [
'class' => $prefix.'GenericFixedWidthReader',
'constructor' => [4],
];
// Utf-8
self::$map['utf-?8'] = [
'class' => $prefix.'Utf8Reader',
'constructor' => [],
];
//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 = strtolower(trim($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,87 @@
<?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.
*/
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,291 @@
<?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 = [];
/** Size of the array of character */
private $array_size = [];
/** 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.
*/
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 = [];
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 = [];
$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 = [];
$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 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 = [0];
$buf_pos = 1;
$buf_len = 1;
$has_datas = true;
do {
$bytes = [];
// 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 = [];
$this->array_size = 0;
}
private function reloadBuffer($fp, $len)
{
if (!feof($fp) && false !== ($bytes = fread($fp, $len))) {
$buf = [];
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 = [];
for ($byte = 0; $byte < 256; ++$byte) {
self::$charMap[$byte] = \chr($byte);
}
self::$byteMap = array_flip(self::$charMap);
}
}
}

View File

@ -0,0 +1,262 @@
<?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 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.
*/
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()
*/
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 (false !== $read) {
$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 = [];
$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 (false !== $ignored) {
$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,387 @@
<?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 = 0x00001;
/** Constant for new instance types */
const TYPE_INSTANCE = 0x00010;
/** Constant for shared instance types */
const TYPE_SHARED = 0x00100;
/** Constant for aliases */
const TYPE_ALIAS = 0x01000;
/** Constant for arrays */
const TYPE_ARRAY = 0x10000;
/** Singleton instance */
private static $instance = null;
/** The data container */
private $store = [];
/** 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);
case self::TYPE_ARRAY:
return $this->createDependenciesFor($itemName);
}
}
/**
* Create an array of arguments passed to the constructor of $itemName.
*
* @param string $itemName
*
* @return array
*/
public function createDependenciesFor($itemName)
{
$args = [];
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] = [];
$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 the previously registered item as array of dependencies.
*
* {@link register()} must be called before this will work.
*
* @return $this
*/
public function asArray()
{
$endPoint = &$this->getEndPoint();
$endPoint['lookupType'] = self::TYPE_ARRAY;
return $this;
}
/**
* Specify a list of injected dependencies for the previously registered item.
*
* This method takes an array of lookup names.
*
* @see addConstructorValue(), addConstructorLookup()
*
* @return $this
*/
public function withDependencies(array $lookups)
{
$endPoint = &$this->getEndPoint();
$endPoint['args'] = [];
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'] = [];
}
$endPoint['args'][] = ['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'] = [];
}
$endPoint['args'][] = ['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 = [];
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 = [];
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);
}
}

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