More functions without type hinting found and fixt

Use PECL yaml (else Spyc)
Upgrade Spyc (with removed dump code)
This commit is contained in:
djmaze 2020-04-03 11:32:07 +02:00
parent cd3d8b94b2
commit 75b4b64118
43 changed files with 893 additions and 1482 deletions

View file

@ -40,9 +40,14 @@ if (\class_exists('RainLoop\Api'))
{ {
\MailSo\Base\Loader::Init(); \MailSo\Base\Loader::Init();
if (!\function_exists('spyc_load_file')) if (!\function_exists('yaml_parse')) {
{ include RAINLOOP_APP_LIBRARIES_PATH.'spyc/Spyc.php';
include APP_VERSION_ROOT_PATH.'app/libraries/spyc/Spyc.php'; function yaml_parse(string $input) {
return \Spyc::YAMLLoadString($input);
}
function yaml_parse_file(string $filename) {
return \Spyc::YAMLLoad($filename);
}
} }
if (RAINLOOP_INCLUDE_AS_API_DEF) if (RAINLOOP_INCLUDE_AS_API_DEF)

View file

@ -456,7 +456,7 @@ class Http
} }
} }
if (\is_array($aHttpHeaders) && 0 < \count($aHttpHeaders)) if (0 < \count($aHttpHeaders))
{ {
$aOptions[CURLOPT_HTTPHEADER] = $aHttpHeaders; $aOptions[CURLOPT_HTTPHEADER] = $aHttpHeaders;
} }

View file

@ -556,7 +556,7 @@ END;
{ {
$sResultHeaders = $sIncHeaders; $sResultHeaders = $sIncHeaders;
if (\is_array($aHeadersToRemove) && 0 < \count($aHeadersToRemove)) if ($aHeadersToRemove)
{ {
$aHeadersToRemove = \array_map('strtolower', $aHeadersToRemove); $aHeadersToRemove = \array_map('strtolower', $aHeadersToRemove);
@ -1016,19 +1016,16 @@ END;
public static function ClearArrayUtf8Values(array &$aInput) public static function ClearArrayUtf8Values(array &$aInput)
{ {
if (\is_array($aInput)) foreach ($aInput as $mKey => $mItem)
{ {
foreach ($aInput as $mKey => $mItem) if (\is_string($mItem))
{ {
if (\is_string($mItem)) $aInput[$mKey] = static::Utf8Clear($mItem);
{ }
$aInput[$mKey] = static::Utf8Clear($mItem); else if (\is_array($mItem))
} {
else if (\is_array($mItem)) static::ClearArrayUtf8Values($mItem);
{ $aInput[$mKey] = $mItem;
static::ClearArrayUtf8Values($mItem);
$aInput[$mKey] = $mItem;
}
} }
} }
} }
@ -1046,11 +1043,6 @@ END;
$oLogger = \MailSo\Config::$SystemLogger; $oLogger = \MailSo\Config::$SystemLogger;
} }
if (!($oLogger instanceof \MailSo\Log\Logger))
{
$oLogger = null;
}
if ($oLogger) if ($oLogger)
{ {
$oLogger->Write('json_encode: '.\trim( $oLogger->Write('json_encode: '.\trim(
@ -1355,7 +1347,7 @@ END;
public static function PrepareFetchSequence(array $aSequence) : string public static function PrepareFetchSequence(array $aSequence) : string
{ {
$aResult = array(); $aResult = array();
if (\is_array($aSequence) && 0 < \count($aSequence)) if (0 < \count($aSequence))
{ {
$iStart = null; $iStart = null;
$iPrev = null; $iPrev = null;
@ -1431,7 +1423,7 @@ END;
public static function MultipleStreamWriter($rRead, array $aWrite, int $iBufferLen = 8192, bool $bResetTimeLimit = true, bool $bFixCrLf = false, bool $bRewindOnComplete = false) : int public static function MultipleStreamWriter($rRead, array $aWrite, int $iBufferLen = 8192, bool $bResetTimeLimit = true, bool $bFixCrLf = false, bool $bRewindOnComplete = false) : int
{ {
$mResult = false; $mResult = false;
if ($rRead && \is_array($aWrite) && 0 < \count($aWrite)) if ($rRead && 0 < \count($aWrite))
{ {
$mResult = 0; $mResult = 0;
while (!\feof($rRead)) while (!\feof($rRead))
@ -1792,18 +1784,16 @@ END;
if (null === $aCache) if (null === $aCache)
{ {
$sDisableFunctions = \ini_get('disable_functions'); $sDisableFunctions = \ini_get('disable_functions');
$sDisableFunctions = \is_string($sDisableFunctions) && 0 < \strlen($sDisableFunctions) ? $sDisableFunctions : ''; $sDisableFunctions = \is_string($sDisableFunctions) ? $sDisableFunctions : '';
$aCache = \explode(',', $sDisableFunctions); $aCache = \explode(',', $sDisableFunctions);
$aCache = \is_array($aCache) && 0 < \count($aCache) ? $aCache : array();
if (\extension_loaded('suhosin')) if (\extension_loaded('suhosin'))
{ {
$sSuhosin = \ini_get('suhosin.executor.func.blacklist'); $sSuhosin = \ini_get('suhosin.executor.func.blacklist');
$sSuhosin = \is_string($sSuhosin) && 0 < \strlen($sSuhosin) ? $sSuhosin : ''; $sSuhosin = \is_string($sSuhosin) ? $sSuhosin : '';
$aSuhosinCache = \explode(',', $sSuhosin); $aSuhosinCache = \explode(',', $sSuhosin);
$aSuhosinCache = \is_array($aSuhosinCache) && 0 < \count($aSuhosinCache) ? $aSuhosinCache : array();
if (0 < \count($aSuhosinCache)) if (0 < \count($aSuhosinCache))
{ {

View file

@ -63,7 +63,7 @@ class CacheClient
return '1' === $this->Get($sKey.'/LOCK'); return '1' === $this->Get($sKey.'/LOCK');
} }
public function Get($sKey, $bClearAfterGet = false) public function Get(string $sKey, bool $bClearAfterGet = false)
{ {
$sValue = ''; $sValue = '';

View file

@ -94,7 +94,7 @@ class BodyStructure
private function __construct(string $sContentType, ?string $sCharset, array $aBodyParams, ?string $sContentID, private function __construct(string $sContentType, ?string $sCharset, array $aBodyParams, ?string $sContentID,
?string $sDescription, ?string $sMailEncodingName, ?string $sDisposition, ?array $aDispositionParams, string $sFileName, ?string $sDescription, ?string $sMailEncodingName, ?string $sDisposition, ?array $aDispositionParams, string $sFileName,
?string $sLanguage, ?string $sLocation, int $iSize, int $iTextLineCount, string $sPartID, ?array $aSubParts) ?string $sLanguage, ?string $sLocation, int $iSize, int $iTextLineCount, string $sPartID, array $aSubParts)
{ {
$this->sContentType = $sContentType; $this->sContentType = $sContentType;
$this->sCharset = $sCharset; $this->sCharset = $sCharset;
@ -113,50 +113,32 @@ class BodyStructure
$this->aSubParts = $aSubParts; $this->aSubParts = $aSubParts;
} }
/** public function MailEncodingName() : ?string
* return string
*/
public function MailEncodingName()
{ {
return $this->sMailEncodingName; return $this->sMailEncodingName;
} }
/** public function PartID() : string
* return string
*/
public function PartID()
{ {
return (string) $this->sPartID; return (string) $this->sPartID;
} }
/** public function FileName() : string
* return string
*/
public function FileName()
{ {
return $this->sFileName; return $this->sFileName;
} }
/** public function ContentType() : string
* return string
*/
public function ContentType()
{ {
return $this->sContentType; return $this->sContentType;
} }
/** public function Size() : int
* return int
*/
public function Size()
{ {
return (int) $this->iSize; return $this->iSize;
} }
/** public function EstimatedSize() : int
* return int
*/
public function EstimatedSize()
{ {
$fCoefficient = 1; $fCoefficient = 1;
switch (\strtolower($this->MailEncodingName())) switch (\strtolower($this->MailEncodingName()))
@ -172,52 +154,33 @@ class BodyStructure
return (int) ($this->Size() * $fCoefficient); return (int) ($this->Size() * $fCoefficient);
} }
/** public function Charset() : ?string
* return string
*/
public function Charset()
{ {
return $this->sCharset; return $this->sCharset;
} }
public function ContentID() : string
/**
* return string
*/
public function ContentID()
{ {
return (null === $this->sContentID) ? '' : $this->sContentID; return (null === $this->sContentID) ? '' : $this->sContentID;
} }
/** public function ContentLocation() : string
* return string
*/
public function ContentLocation()
{ {
return (null === $this->sLocation) ? '' : $this->sLocation; return (null === $this->sLocation) ? '' : $this->sLocation;
} }
/** public function IsInline() : bool
* return bool
*/
public function IsInline()
{ {
return (null === $this->sDisposition) ? return (null === $this->sDisposition) ?
(0 < \strlen($this->ContentID())) : ('inline' === strtolower($this->sDisposition)); (0 < \strlen($this->ContentID())) : ('inline' === strtolower($this->sDisposition));
} }
/** public function IsImage() : bool
* return bool
*/
public function IsImage()
{ {
return 'image' === \MailSo\Base\Utils::ContentTypeType($this->ContentType(), $this->FileName()); return 'image' === \MailSo\Base\Utils::ContentTypeType($this->ContentType(), $this->FileName());
} }
/** public function IsArchive() : bool
* return bool
*/
public function IsArchive()
{ {
return 'archive' === \MailSo\Base\Utils::ContentTypeType($this->ContentType(), $this->FileName()); return 'archive' === \MailSo\Base\Utils::ContentTypeType($this->ContentType(), $this->FileName());
} }
@ -305,7 +268,7 @@ class BodyStructure
return $oItem->IsInline(); return $oItem->IsInline();
}); });
if (is_array($aSearchParts) && 1 === \count($aSearchParts) && isset($aSearchParts[0])) if (1 === \count($aSearchParts) && isset($aSearchParts[0]))
{ {
return $aSearchParts[0]; return $aSearchParts[0];
} }
@ -364,7 +327,6 @@ class BodyStructure
/** /**
* @param mixed $fCallback * @param mixed $fCallback
*
*/ */
public function SearchByCallback($fCallback) : array public function SearchByCallback($fCallback) : array
{ {
@ -374,12 +336,9 @@ class BodyStructure
$aReturn[] = $this; $aReturn[] = $this;
} }
if (\is_array($this->aSubParts) && 0 < \count($this->aSubParts)) foreach ($this->aSubParts as /* @var $oSubPart \MailSo\Imap\BodyStructure */ $oSubPart)
{ {
foreach ($this->aSubParts as /* @var $oSubPart \MailSo\Imap\BodyStructure */ $oSubPart) $aReturn = \array_merge($aReturn, $oSubPart->SearchByCallback($fCallback));
{
$aReturn = \array_merge($aReturn, $oSubPart->SearchByCallback($fCallback));
}
} }
return $aReturn; return $aReturn;
@ -410,7 +369,7 @@ class BodyStructure
$oPart = $this; $oPart = $this;
} }
if (null === $oPart && is_array($this->aSubParts) && 0 < count($this->aSubParts)) if (null === $oPart)
{ {
foreach ($this->aSubParts as /* @var $oSubPart \MailSo\Imap\BodyStructure */ $oSubPart) foreach ($this->aSubParts as /* @var $oSubPart \MailSo\Imap\BodyStructure */ $oSubPart)
{ {
@ -426,7 +385,7 @@ class BodyStructure
return $oPart; return $oPart;
} }
private static function decodeAttrParamenter(array $aParams, string $sParamName, string $sCharset = \MailSo\Base\Enumerations\Charset::UTF_8) : string private static function decodeAttrParameter(array $aParams, string $sParamName, string $sCharset = \MailSo\Base\Enumerations\Charset::UTF_8) : string
{ {
$sResult = ''; $sResult = '';
if (isset($aParams[$sParamName])) if (isset($aParams[$sParamName]))
@ -436,7 +395,7 @@ class BodyStructure
else if (isset($aParams[$sParamName.'*'])) else if (isset($aParams[$sParamName.'*']))
{ {
$aValueParts = \explode("''", $aParams[$sParamName.'*'], 2); $aValueParts = \explode("''", $aParams[$sParamName.'*'], 2);
if (\is_array($aValueParts) && 2 === \count($aValueParts)) if (2 === \count($aValueParts))
{ {
$sCharset = isset($aValueParts[0]) ? $aValueParts[0] : \MailSo\Base\Enumerations\Charset::UTF_8; $sCharset = isset($aValueParts[0]) ? $aValueParts[0] : \MailSo\Base\Enumerations\Charset::UTF_8;
@ -463,7 +422,7 @@ class BodyStructure
if ($sCharsetIndex < $iIndex && false !== \strpos($sValue, "''")) if ($sCharsetIndex < $iIndex && false !== \strpos($sValue, "''"))
{ {
$aValueParts = \explode("''", $sValue, 2); $aValueParts = \explode("''", $sValue, 2);
if (\is_array($aValueParts) && 2 === \count($aValueParts) && 0 < \strlen($aValueParts[0])) if (2 === \count($aValueParts) && 0 < \strlen($aValueParts[0]))
{ {
$sCharsetIndex = $iIndex; $sCharsetIndex = $iIndex;
$sCharset = $aValueParts[0]; $sCharset = $aValueParts[0];
@ -492,322 +451,308 @@ class BodyStructure
return $sResult; return $sResult;
} }
public static function NewInstance(array $aBodyStructure, string $sPartID = '') : self public static function NewInstance(array $aBodyStructure, string $sPartID = '') : ?self
{ {
if (!\is_array($aBodyStructure) || 2 > \count($aBodyStructure)) if (2 > \count($aBodyStructure))
{ {
return null; return null;
} }
else
$sBodyMainType = null;
if (\is_string($aBodyStructure[0]) && 'NIL' !== $aBodyStructure[0])
{ {
$sBodyMainType = null; $sBodyMainType = $aBodyStructure[0];
if (\is_string($aBodyStructure[0]) && 'NIL' !== $aBodyStructure[0]) }
$sBodySubType = null;
$sContentType = '';
$aSubParts = array();
$aBodyParams = array();
$sName = null;
$sCharset = null;
$sContentID = null;
$sDescription = null;
$sMailEncodingName = null;
$iSize = 0;
$iTextLineCount = 0; // valid for rfc822/message and text parts
$iExtraItemPos = 0; // list index of items which have no well-established position (such as 0, 1, 5, etc).
if (null === $sBodyMainType)
{
// Process multipart body structure
if (!\is_array($aBodyStructure[0]))
{ {
$sBodyMainType = $aBodyStructure[0]; return null;
} }
$sBodySubType = null; $sBodyMainType = 'multipart';
$sContentType = ''; $sSubPartIDPrefix = '';
$aSubParts = null; if (0 === \strlen($sPartID) || '.' === $sPartID[\strlen($sPartID) - 1])
$aBodyParams = array();
$sName = null;
$sCharset = null;
$sContentID = null;
$sDescription = null;
$sMailEncodingName = null;
$iSize = 0;
$iTextLineCount = 0; // valid for rfc822/message and text parts
$iExtraItemPos = 0; // list index of items which have no well-established position (such as 0, 1, 5, etc).
if (null === $sBodyMainType)
{ {
// Process multipart body structure // This multi-part is root part of message.
if (!\is_array($aBodyStructure[0])) $sSubPartIDPrefix = $sPartID;
$sPartID .= 'TEXT';
}
else if (0 < \strlen($sPartID))
{
// This multi-part is a part of another multi-part.
$sSubPartIDPrefix = $sPartID.'.';
}
$iIndex = 1;
while ($iExtraItemPos < \count($aBodyStructure) && \is_array($aBodyStructure[$iExtraItemPos]))
{
$oPart = self::NewInstance($aBodyStructure[$iExtraItemPos], $sSubPartIDPrefix.$iIndex);
if (null === $oPart)
{ {
return null; return null;
} }
else
// For multipart, we have no charset info in the part itself. Thus,
// obtain charset from nested parts.
if ($sCharset == null)
{ {
$sBodyMainType = 'multipart'; $sCharset = $oPart->Charset();
$sSubPartIDPrefix = '';
if (0 === \strlen($sPartID) || '.' === $sPartID[\strlen($sPartID) - 1])
{
// This multi-part is root part of message.
$sSubPartIDPrefix = $sPartID;
$sPartID .= 'TEXT';
}
else if (0 < \strlen($sPartID))
{
// This multi-part is a part of another multi-part.
$sSubPartIDPrefix = $sPartID.'.';
}
$aSubParts = array();
$iIndex = 1;
while ($iExtraItemPos < \count($aBodyStructure) && \is_array($aBodyStructure[$iExtraItemPos]))
{
$oPart = self::NewInstance($aBodyStructure[$iExtraItemPos], $sSubPartIDPrefix.$iIndex);
if (null === $oPart)
{
return null;
}
else
{
// For multipart, we have no charset info in the part itself. Thus,
// obtain charset from nested parts.
if ($sCharset == null)
{
$sCharset = $oPart->Charset();
}
$aSubParts[] = $oPart;
$iExtraItemPos++;
$iIndex++;
}
}
} }
if ($iExtraItemPos < \count($aBodyStructure)) $aSubParts[] = $oPart;
{ ++$iExtraItemPos;
if (!\is_string($aBodyStructure[$iExtraItemPos]) || 'NIL' === $aBodyStructure[$iExtraItemPos]) ++$iIndex;
{ }
return null;
}
$sBodySubType = \strtolower($aBodyStructure[$iExtraItemPos]); if ($iExtraItemPos < \count($aBodyStructure))
$iExtraItemPos++; {
if (!\is_string($aBodyStructure[$iExtraItemPos]) || 'NIL' === $aBodyStructure[$iExtraItemPos])
{
return null;
} }
if ($iExtraItemPos < \count($aBodyStructure)) $sBodySubType = \strtolower($aBodyStructure[$iExtraItemPos]);
++$iExtraItemPos;
}
if ($iExtraItemPos < \count($aBodyStructure))
{
$sBodyParamList = $aBodyStructure[$iExtraItemPos];
if (\is_array($sBodyParamList))
{ {
$sBodyParamList = $aBodyStructure[$iExtraItemPos]; $aBodyParams = self::getKeyValueListFromArrayList($sBodyParamList);
if (\is_array($sBodyParamList)) }
{ }
$aBodyParams = self::getKeyValueListFromArrayList($sBodyParamList);
} ++$iExtraItemPos;
}
else
{
// Process simple (singlepart) body structure
if (7 > \count($aBodyStructure))
{
return null;
}
$sBodyMainType = \strtolower($sBodyMainType);
if (!\is_string($aBodyStructure[1]) || 'NIL' === $aBodyStructure[1])
{
return null;
}
$sBodySubType = \strtolower($aBodyStructure[1]);
$aBodyParamList = $aBodyStructure[2];
if (\is_array($aBodyParamList))
{
$aBodyParams = self::getKeyValueListFromArrayList($aBodyParamList);
if (isset($aBodyParams['charset']))
{
$sCharset = $aBodyParams['charset'];
} }
$iExtraItemPos++; $sName = self::decodeAttrParameter($aBodyParams, 'name', $sContentType);
}
if (null !== $aBodyStructure[3] && 'NIL' !== $aBodyStructure[3])
{
if (!\is_string($aBodyStructure[3]))
{
return null;
}
$sContentID = $aBodyStructure[3];
}
if (null !== $aBodyStructure[4] && 'NIL' !== $aBodyStructure[4])
{
if (!\is_string($aBodyStructure[4]))
{
return null;
}
$sDescription = $aBodyStructure[4];
}
if (null !== $aBodyStructure[5] && 'NIL' !== $aBodyStructure[5])
{
if (!\is_string($aBodyStructure[5]))
{
return null;
}
$sMailEncodingName = $aBodyStructure[5];
}
if (\is_numeric($aBodyStructure[6]))
{
$iSize = (int) $aBodyStructure[6];
} }
else else
{ {
// Process simple (singlepart) body structure $iSize = -1;
if (7 > \count($aBodyStructure)) }
{
return null;
}
$sBodyMainType = \strtolower($sBodyMainType); if (0 === \strlen($sPartID) || '.' === $sPartID[\strlen($sPartID) - 1])
if (!\is_string($aBodyStructure[1]) || 'NIL' === $aBodyStructure[1]) {
{ // This is the only sub-part of the message (otherwise, it would be
return null; // one of sub-parts of a multi-part, and partID would already be fully set up).
} $sPartID .= '1';
}
$sBodySubType = \strtolower($aBodyStructure[1]); $iExtraItemPos = 7;
if ('text' === $sBodyMainType)
$aBodyParamList = $aBodyStructure[2]; {
if (\is_array($aBodyParamList)) if ($iExtraItemPos < \count($aBodyStructure))
{ {
$aBodyParams = self::getKeyValueListFromArrayList($aBodyParamList); if (\is_numeric($aBodyStructure[$iExtraItemPos]))
if (isset($aBodyParams['charset']))
{ {
$sCharset = $aBodyParams['charset']; $iTextLineCount = (int) $aBodyStructure[$iExtraItemPos];
} }
else
if (\is_array($aBodyParams))
{ {
$sName = self::decodeAttrParamenter($aBodyParams, 'name', $sContentType); $iTextLineCount = -1;
} }
} }
if (null !== $aBodyStructure[3] && 'NIL' !== $aBodyStructure[3])
{
if (!\is_string($aBodyStructure[3]))
{
return null;
}
$sContentID = $aBodyStructure[3];
}
if (null !== $aBodyStructure[4] && 'NIL' !== $aBodyStructure[4])
{
if (!\is_string($aBodyStructure[4]))
{
return null;
}
$sDescription = $aBodyStructure[4];
}
if (null !== $aBodyStructure[5] && 'NIL' !== $aBodyStructure[5])
{
if (!\is_string($aBodyStructure[5]))
{
return null;
}
$sMailEncodingName = $aBodyStructure[5];
}
if (\is_numeric($aBodyStructure[6]))
{
$iSize = (int) $aBodyStructure[6];
}
else else
{ {
$iSize = -1; $iTextLineCount = -1;
} }
if (0 === \strlen($sPartID) || '.' === $sPartID[\strlen($sPartID) - 1]) ++$iExtraItemPos;
}
else if ('message' === $sBodyMainType && 'rfc822' === $sBodySubType)
{
if ($iExtraItemPos + 2 < \count($aBodyStructure))
{ {
// This is the only sub-part of the message (otherwise, it would be if (\is_numeric($aBodyStructure[$iExtraItemPos + 2]))
// one of sub-parts of a multi-part, and partID would already be fully set up).
$sPartID .= '1';
}
$iExtraItemPos = 7;
if ('text' === $sBodyMainType)
{
if ($iExtraItemPos < \count($aBodyStructure))
{ {
if (\is_numeric($aBodyStructure[$iExtraItemPos])) $iTextLineCount = (int) $aBodyStructure[$iExtraItemPos + 2];
{
$iTextLineCount = (int) $aBodyStructure[$iExtraItemPos];
}
else
{
$iTextLineCount = -1;
}
} }
else else
{ {
$iTextLineCount = -1; $iTextLineCount = -1;
} }
$iExtraItemPos++;
} }
else if ('message' === $sBodyMainType && 'rfc822' === $sBodySubType) else
{ {
if ($iExtraItemPos + 2 < \count($aBodyStructure)) $iTextLineCount = -1;
{
if (\is_numeric($aBodyStructure[$iExtraItemPos + 2]))
{
$iTextLineCount = (int) $aBodyStructure[$iExtraItemPos + 2];
}
else
{
$iTextLineCount = -1;
}
}
else
{
$iTextLineCount = -1;
}
$iExtraItemPos += 3;
} }
$iExtraItemPos++; // skip MD5 digest of the body because most mail servers leave it NIL anyway $iExtraItemPos += 3;
} }
$sContentType = $sBodyMainType.'/'.$sBodySubType; ++$iExtraItemPos; // skip MD5 digest of the body because most mail servers leave it NIL anyway
$sDisposition = null;
$aDispositionParams = null;
$sFileName = null;
if ($iExtraItemPos < \count($aBodyStructure))
{
$aDispList = $aBodyStructure[$iExtraItemPos];
if (\is_array($aDispList) && 1 < \count($aDispList))
{
if (null !== $aDispList[0])
{
if (\is_string($aDispList[0]) && 'NIL' !== $aDispList[0])
{
$sDisposition = $aDispList[0];
}
else
{
return null;
}
}
}
$aDispParamList = $aDispList[1];
if (\is_array($aDispParamList))
{
$aDispositionParams = self::getKeyValueListFromArrayList($aDispParamList);
if (\is_array($aDispositionParams))
{
$sFileName = self::decodeAttrParamenter($aDispositionParams, 'filename', $sCharset ?: '');
}
}
}
$iExtraItemPos++;
$sLanguage = null;
if ($iExtraItemPos < count($aBodyStructure))
{
if (null !== $aBodyStructure[$iExtraItemPos] && 'NIL' !== $aBodyStructure[$iExtraItemPos])
{
if (\is_array($aBodyStructure[$iExtraItemPos]))
{
$sLanguage = \implode(',', $aBodyStructure[$iExtraItemPos]);
}
else if (\is_string($aBodyStructure[$iExtraItemPos]))
{
$sLanguage = $aBodyStructure[$iExtraItemPos];
}
}
$iExtraItemPos++;
}
$sLocation = null;
if ($iExtraItemPos < \count($aBodyStructure))
{
if (null !== $aBodyStructure[$iExtraItemPos] && 'NIL' !== $aBodyStructure[$iExtraItemPos])
{
if (\is_string($aBodyStructure[$iExtraItemPos]))
{
$sLocation = $aBodyStructure[$iExtraItemPos];
}
}
$iExtraItemPos++;
}
return new self(
$sContentType,
$sCharset,
$aBodyParams,
$sContentID,
$sDescription,
$sMailEncodingName,
$sDisposition,
$aDispositionParams,
\MailSo\Base\Utils::Utf8Clear((null === $sFileName || 0 === \strlen($sFileName)) ? $sName : $sFileName),
$sLanguage,
$sLocation,
$iSize,
$iTextLineCount,
$sPartID,
$aSubParts
);
} }
$sContentType = $sBodyMainType.'/'.$sBodySubType;
$sDisposition = null;
$aDispositionParams = null;
$sFileName = null;
if ($iExtraItemPos < \count($aBodyStructure))
{
$aDispList = $aBodyStructure[$iExtraItemPos];
if (\is_array($aDispList) && 1 < \count($aDispList))
{
if (null !== $aDispList[0])
{
if (\is_string($aDispList[0]) && 'NIL' !== $aDispList[0])
{
$sDisposition = $aDispList[0];
}
else
{
return null;
}
}
}
$aDispParamList = $aDispList[1];
if (\is_array($aDispParamList))
{
$aDispositionParams = self::getKeyValueListFromArrayList($aDispParamList);
$sFileName = self::decodeAttrParameter($aDispositionParams, 'filename', $sCharset ?: '');
}
}
++$iExtraItemPos;
$sLanguage = null;
if ($iExtraItemPos < count($aBodyStructure))
{
if (null !== $aBodyStructure[$iExtraItemPos] && 'NIL' !== $aBodyStructure[$iExtraItemPos])
{
if (\is_array($aBodyStructure[$iExtraItemPos]))
{
$sLanguage = \implode(',', $aBodyStructure[$iExtraItemPos]);
}
else if (\is_string($aBodyStructure[$iExtraItemPos]))
{
$sLanguage = $aBodyStructure[$iExtraItemPos];
}
}
++$iExtraItemPos;
}
$sLocation = null;
if ($iExtraItemPos < \count($aBodyStructure))
{
if (null !== $aBodyStructure[$iExtraItemPos] && 'NIL' !== $aBodyStructure[$iExtraItemPos])
{
if (\is_string($aBodyStructure[$iExtraItemPos]))
{
$sLocation = $aBodyStructure[$iExtraItemPos];
}
}
++$iExtraItemPos;
}
return new self(
$sContentType,
$sCharset,
$aBodyParams,
$sContentID,
$sDescription,
$sMailEncodingName,
$sDisposition,
$aDispositionParams,
\MailSo\Base\Utils::Utf8Clear($sFileName ?: $sName),
$sLanguage,
$sLocation,
$iSize,
$iTextLineCount,
$sPartID,
$aSubParts
);
} }
public static function NewInstanceFromRfc822SubPart(array $aBodyStructure, string $sSubPartID) : ?self public static function NewInstanceFromRfc822SubPart(array $aBodyStructure, string $sSubPartID) : ?self
{ {
$oBody = null;
$aBodySubStructure = self::findPartByIndexInArray($aBodyStructure, $sSubPartID); $aBodySubStructure = self::findPartByIndexInArray($aBodyStructure, $sSubPartID);
if ($aBodySubStructure && \is_array($aBodySubStructure) && isset($aBodySubStructure[8])) if ($aBodySubStructure && \is_array($aBodySubStructure) && isset($aBodySubStructure[8]))
{ {
$oBody = self::NewInstance($aBodySubStructure[8], $sSubPartID); return self::NewInstance($aBodySubStructure[8], $sSubPartID);
} }
return $oBody; return null;
} }
private static function findPartByIndexInArray(array $aList, string $sPartID) : ?array private static function findPartByIndexInArray(array $aList, string $sPartID) : ?array
@ -832,15 +777,12 @@ class BodyStructure
/** /**
* Returns dict with key="charset" and value="US-ASCII" for array ("CHARSET" "US-ASCII"). * Returns dict with key="charset" and value="US-ASCII" for array ("CHARSET" "US-ASCII").
* Keys are lowercased (StringDictionary itself does this), values are not altered. * Keys are lowercased (StringDictionary itself does this), values are not altered.
*
*
*/ */
private static function getKeyValueListFromArrayList(array $aList) : array private static function getKeyValueListFromArrayList(array $aList) : array
{ {
$aDict = null; $aDict = array();
if (0 === \count($aList) % 2) if (0 === \count($aList) % 2)
{ {
$aDict = array();
for ($iIndex = 0, $iLen = \count($aList); $iIndex < $iLen; $iIndex += 2) for ($iIndex = 0, $iLen = \count($aList); $iIndex < $iLen; $iIndex += 2)
{ {
if (\is_string($aList[$iIndex]) && isset($aList[$iIndex + 1]) && \is_string($aList[$iIndex + 1])) if (\is_string($aList[$iIndex]) && isset($aList[$iIndex + 1]) && \is_string($aList[$iIndex + 1]))

View file

@ -36,10 +36,6 @@ class FetchType
const UID = 'UID'; const UID = 'UID';
const INDEX = 'INDEX'; const INDEX = 'INDEX';
const GMAIL_MSGID = 'X-GM-MSGID';
const GMAIL_THRID = 'X-GM-THRID';
const GMAIL_LABELS = 'X-GM-LABELS';
private static function addHelper(array &$aReturn, $mType) private static function addHelper(array &$aReturn, $mType)
{ {
if (\is_string($mType)) if (\is_string($mType))
@ -47,7 +43,7 @@ class FetchType
$aReturn[$mType] = ''; $aReturn[$mType] = '';
} }
else if (\is_array($mType) && 2 === count($mType) && \is_string($mType[0]) && else if (\is_array($mType) && 2 === count($mType) && \is_string($mType[0]) &&
is_callable($mType[1])) \is_callable($mType[1]))
{ {
$aReturn[$mType[0]] = $mType[1]; $aReturn[$mType[0]] = $mType[1];
} }

View file

@ -24,11 +24,4 @@ class StoreAction
const ADD_FLAGS_SILENT = '+FLAGS.SILENT'; const ADD_FLAGS_SILENT = '+FLAGS.SILENT';
const REMOVE_FLAGS = '-FLAGS'; const REMOVE_FLAGS = '-FLAGS';
const REMOVE_FLAGS_SILENT = '-FLAGS.SILENT'; const REMOVE_FLAGS_SILENT = '-FLAGS.SILENT';
const SET_GMAIL_LABELS = 'X-GM-LABELS';
const SET_GMAIL_LABELS_SILENT = 'X-GM-LABELS.SILENT';
const ADD_GMAIL_LABELS = '+X-GM-LABELS';
const ADD_GMAIL_LABELS_SILENT = '+X-GM-LABELS.SILENT';
const REMOVE_GMAIL_LABELS = '-X-GM-LABELS';
const REMOVE_GMAIL_LABELS_SILENT = '-X-GM-LABELS.SILENT';
} }

View file

@ -48,11 +48,9 @@ class FetchResponse
} }
/** /**
* @param mixed $mNullResult = null
*
* @return mixed * @return mixed
*/ */
public function GetFetchEnvelopeValue(int $iIndex, $mNullResult) public function GetFetchEnvelopeValue(int $iIndex, ?string $mNullResult = null)
{ {
return self::findEnvelopeIndex($this->GetEnvelope(), $iIndex, $mNullResult); return self::findEnvelopeIndex($this->GetEnvelope(), $iIndex, $mNullResult);
} }
@ -60,7 +58,7 @@ class FetchResponse
public function GetFetchEnvelopeEmailCollection(int $iIndex, string $sParentCharset = \MailSo\Base\Enumerations\Charset::ISO_8859_1) : ?\MailSo\Mime\EmailCollection public function GetFetchEnvelopeEmailCollection(int $iIndex, string $sParentCharset = \MailSo\Base\Enumerations\Charset::ISO_8859_1) : ?\MailSo\Mime\EmailCollection
{ {
$oResult = null; $oResult = null;
$aEmails = $this->GetFetchEnvelopeValue($iIndex, null); $aEmails = $this->GetFetchEnvelopeValue($iIndex);
if (is_array($aEmails) && 0 < count($aEmails)) if (is_array($aEmails) && 0 < count($aEmails))
{ {
$oResult = \MailSo\Mime\EmailCollection::NewInstance(); $oResult = \MailSo\Mime\EmailCollection::NewInstance();
@ -92,22 +90,18 @@ class FetchResponse
public function GetFetchBodyStructure(string $sRfc822SubMimeIndex = '') : ?BodyStructure public function GetFetchBodyStructure(string $sRfc822SubMimeIndex = '') : ?BodyStructure
{ {
$oBodyStructure = null;
$aBodyStructureArray = $this->GetFetchValue(Enumerations\FetchType::BODYSTRUCTURE); $aBodyStructureArray = $this->GetFetchValue(Enumerations\FetchType::BODYSTRUCTURE);
if (is_array($aBodyStructureArray)) if (is_array($aBodyStructureArray))
{ {
if (0 < strlen($sRfc822SubMimeIndex)) if (0 < strlen($sRfc822SubMimeIndex))
{ {
$oBodyStructure = BodyStructure::NewInstanceFromRfc822SubPart($aBodyStructureArray, $sRfc822SubMimeIndex); return BodyStructure::NewInstanceFromRfc822SubPart($aBodyStructureArray, $sRfc822SubMimeIndex);
}
else
{
$oBodyStructure = BodyStructure::NewInstance($aBodyStructureArray);
} }
return BodyStructure::NewInstance($aBodyStructureArray);
} }
return $oBodyStructure; return null;
} }
/** /**
@ -144,7 +138,6 @@ class FetchResponse
public function GetHeaderFieldsValue(string $sRfc822SubMimeIndex = '') : string public function GetHeaderFieldsValue(string $sRfc822SubMimeIndex = '') : string
{ {
$sReturn = '';
$bNextIsValue = false; $bNextIsValue = false;
$sRfc822SubMimeIndex = 0 < \strlen($sRfc822SubMimeIndex) ? ''.$sRfc822SubMimeIndex.'.' : ''; $sRfc822SubMimeIndex = 0 < \strlen($sRfc822SubMimeIndex) ? ''.$sRfc822SubMimeIndex.'.' : '';
@ -155,8 +148,7 @@ class FetchResponse
{ {
if ($bNextIsValue) if ($bNextIsValue)
{ {
$sReturn = (string) $mItem; return (string) $mItem;
break;
} }
if (\is_string($mItem) && ( if (\is_string($mItem) && (
@ -169,28 +161,24 @@ class FetchResponse
} }
} }
return $sReturn; return '';
} }
private static function findFetchUidAndSize(array $aList) : bool private static function findFetchUidAndSize(array $aList) : bool
{ {
$bUid = false; $bUid = false;
$bSize = false; $bSize = false;
if (is_array($aList)) foreach ($aList as $mItem)
{ {
foreach ($aList as $mItem) if (Enumerations\FetchType::UID === $mItem)
{ {
if (Enumerations\FetchType::UID === $mItem) $bUid = true;
{ }
$bUid = true; else if (Enumerations\FetchType::RFC822_SIZE === $mItem)
} {
else if (Enumerations\FetchType::RFC822_SIZE === $mItem) $bSize = true;
{
$bSize = true;
}
} }
} }
return $bUid && $bSize; return $bUid && $bSize;
} }
@ -216,11 +204,9 @@ class FetchResponse
} }
/** /**
* @param mixed $mNullResult = null
*
* @return mixed * @return mixed
*/ */
private static function findEnvelopeIndex(array $aEnvelope, int $iIndex, $mNullResult) private static function findEnvelopeIndex(array $aEnvelope, int $iIndex, ?string $mNullResult)
{ {
return (isset($aEnvelope[$iIndex]) && 'NIL' !== $aEnvelope[$iIndex] && '' !== $aEnvelope[$iIndex]) return (isset($aEnvelope[$iIndex]) && 'NIL' !== $aEnvelope[$iIndex] && '' !== $aEnvelope[$iIndex])
? $aEnvelope[$iIndex] : $mNullResult; ? $aEnvelope[$iIndex] : $mNullResult;

View file

@ -45,28 +45,20 @@ class Folder
/** /**
* @var array * @var array
*/ */
private $aExtended; private $aExtended = array();
/** /**
* @throws \MailSo\Base\Exceptions\InvalidArgumentException * @throws \MailSo\Base\Exceptions\InvalidArgumentException
*/ */
private function __construct(string $sFullNameRaw, string $sDelimiter, array $aFlags) private function __construct(string $sFullNameRaw, string $sDelimiter, array $aFlags)
{ {
$this->sNameRaw = '';
$this->sFullNameRaw = '';
$this->sDelimiter = '';
$this->aFlags = array();
$this->aExtended = array();
$sDelimiter = 'NIL' === \strtoupper($sDelimiter) ? '' : $sDelimiter; $sDelimiter = 'NIL' === \strtoupper($sDelimiter) ? '' : $sDelimiter;
if (empty($sDelimiter)) if (empty($sDelimiter))
{ {
$sDelimiter = '.'; // default delimiter $sDelimiter = '.'; // default delimiter
} }
if (!\is_array($aFlags) || if (1 < \strlen($sDelimiter) || 0 === \strlen($sFullNameRaw))
!\is_string($sDelimiter) || 1 < \strlen($sDelimiter) ||
!\is_string($sFullNameRaw) || 0 === \strlen($sFullNameRaw))
{ {
throw new \MailSo\Base\Exceptions\InvalidArgumentException(); throw new \MailSo\Base\Exceptions\InvalidArgumentException();
} }
@ -143,7 +135,7 @@ class Folder
/** /**
* @param mixed $mData * @param mixed $mData
*/ */
public function SetExtended(string $sName, $mData) public function SetExtended(string $sName, $mData) : void
{ {
$this->aExtended[$sName] = $mData; $this->aExtended[$sName] = $mData;
} }

View file

@ -611,13 +611,13 @@ class ImapClient extends \MailSo\Net\NetClient
$sSearchCriterias = !strlen(\trim($sSearchCriterias)) || '*' === $sSearchCriterias $sSearchCriterias = !strlen(\trim($sSearchCriterias)) || '*' === $sSearchCriterias
? 'ALL' : $sSearchCriterias; ? 'ALL' : $sSearchCriterias;
if (!\is_array($aSortTypes) || 0 === \count($aSortTypes)) if (!$aSortTypes)
{ {
$this->writeLogException( $this->writeLogException(
new \MailSo\Base\Exceptions\InvalidArgumentException(), new \MailSo\Base\Exceptions\InvalidArgumentException(),
\MailSo\Log\Enumerations\Type::ERROR, true); \MailSo\Log\Enumerations\Type::ERROR, true);
} }
else if (!$this->IsSupported('SORT')) if (!$this->IsSupported('SORT'))
{ {
$this->writeLogException( $this->writeLogException(
new \MailSo\Base\Exceptions\InvalidArgumentException(), new \MailSo\Base\Exceptions\InvalidArgumentException(),
@ -647,7 +647,7 @@ class ImapClient extends \MailSo\Net\NetClient
? 'ALL' : $sSearchCriterias; ? 'ALL' : $sSearchCriterias;
$sCmd = $bSort ? 'SORT': 'SEARCH'; $sCmd = $bSort ? 'SORT': 'SEARCH';
if ($bSort && (!\is_array($aSortTypes) || 0 === \count($aSortTypes) || !$this->IsSupported('SORT'))) if ($bSort && (!$aSortTypes || !$this->IsSupported('SORT')))
{ {
$this->writeLogException( $this->writeLogException(
new \MailSo\Base\Exceptions\InvalidArgumentException(), new \MailSo\Base\Exceptions\InvalidArgumentException(),
@ -661,7 +661,7 @@ class ImapClient extends \MailSo\Net\NetClient
\MailSo\Log\Enumerations\Type::ERROR, true); \MailSo\Log\Enumerations\Type::ERROR, true);
} }
if (!\is_array($aSearchOrSortReturn) || 0 === \count($aSearchOrSortReturn)) if (!$aSearchOrSortReturn)
{ {
$aSearchOrSortReturn = array('ALL'); $aSearchOrSortReturn = array('ALL');
} }
@ -1620,18 +1620,15 @@ class ImapClient extends \MailSo\Net\NetClient
private function prepareParamLine(array $aParams = array()) : string private function prepareParamLine(array $aParams = array()) : string
{ {
$sReturn = ''; $sReturn = '';
if (\is_array($aParams) && 0 < \count($aParams)) foreach ($aParams as $mParamItem)
{ {
foreach ($aParams as $mParamItem) if (\is_array($mParamItem) && 0 < \count($mParamItem))
{ {
if (\is_array($mParamItem) && 0 < \count($mParamItem)) $sReturn .= ' ('.\trim($this->prepareParamLine($mParamItem)).')';
{ }
$sReturn .= ' ('.\trim($this->prepareParamLine($mParamItem)).')'; else if (\is_string($mParamItem))
} {
else if (\is_string($mParamItem)) $sReturn .= ' '.$mParamItem;
{
$sReturn .= ' '.$mParamItem;
}
} }
} }
return $sReturn; return $sReturn;

View file

@ -71,14 +71,10 @@ class Response
private function recToLine(array $aList) : string private function recToLine(array $aList) : string
{ {
$aResult = array(); $aResult = array();
if (\is_array($aList)) foreach ($aList as $mItem)
{ {
foreach ($aList as $mItem) $aResult[] = \is_array($mItem) ? '('.$this->recToLine($mItem).')' : (string) $mItem;
{
$aResult[] = \is_array($mItem) ? '('.$this->recToLine($mItem).')' : (string) $mItem;
}
} }
return \implode(' ', $aResult); return \implode(' ', $aResult);
} }

View file

@ -217,7 +217,7 @@ class ResponseCollection extends \MailSo\Base\Collection
return $aReturn; return $aReturn;
} }
public function getMessageSimpleThreadResult($sStatus, $bReturnUid) : array public function getMessageSimpleThreadResult(string $sStatus, bool $bReturnUid) : array
{ {
$aReturn = array(); $aReturn = array();
foreach ($this as $oResponse) { foreach ($this as $oResponse) {

View file

@ -220,7 +220,7 @@ abstract class Driver
return $this->writeImplementation($mDesc); return $this->writeImplementation($mDesc);
} }
final public function Write($sDesc, $iType = \MailSo\Log\Enumerations\Type::INFO, $sName = '', $bDiplayCrLf = false) final public function Write(string $sDesc, int $iType = \MailSo\Log\Enumerations\Type::INFO, string $sName = '', bool $bDiplayCrLf = false)
{ {
$bResult = true; $bResult = true;
if (!$this->bFlushCache && ($this->bWriteOnErrorOnly || $this->bWriteOnPhpErrorOnly || 0 < $this->iWriteOnTimeoutOnly)) if (!$this->bFlushCache && ($this->bWriteOnErrorOnly || $this->bWriteOnPhpErrorOnly || 0 < $this->iWriteOnTimeoutOnly))

View file

@ -127,7 +127,7 @@ class Logger extends \MailSo\Base\Collection
public function AddSecret(string $sWord) : void public function AddSecret(string $sWord) : void
{ {
if (\is_string($sWord) && 0 < \strlen(\trim($sWord))) if (0 < \strlen(\trim($sWord)))
{ {
$this->aSecretWords[] = $sWord; $this->aSecretWords[] = $sWord;
$this->aSecretWords = \array_unique($this->aSecretWords); $this->aSecretWords = \array_unique($this->aSecretWords);
@ -185,21 +185,17 @@ class Logger extends \MailSo\Base\Collection
public function __loggerShutDown() : void public function __loggerShutDown() : void
{ {
if ($this->bUsed) if ($this->bUsed && $aStatistic = \MailSo\Base\Loader::Statistic())
{ {
$aStatistic = \MailSo\Base\Loader::Statistic(); if (isset($aStatistic['php']['memory_get_peak_usage']))
if (\is_array($aStatistic))
{ {
if (isset($aStatistic['php']['memory_get_peak_usage'])) $this->Write('Memory peak usage: '.$aStatistic['php']['memory_get_peak_usage'],
{ \MailSo\Log\Enumerations\Type::MEMORY);
$this->Write('Memory peak usage: '.$aStatistic['php']['memory_get_peak_usage'], }
\MailSo\Log\Enumerations\Type::MEMORY);
}
if (isset($aStatistic['time'])) if (isset($aStatistic['time']))
{ {
$this->Write('Time delta: '.$aStatistic['time'], \MailSo\Log\Enumerations\Type::TIME_DELTA); $this->Write('Time delta: '.$aStatistic['time'], \MailSo\Log\Enumerations\Type::TIME_DELTA);
}
} }
} }
} }

View file

@ -32,9 +32,6 @@ class Attachment
*/ */
private $oBodyStructure; private $oBodyStructure;
/**
* @access private
*/
private function __construct() private function __construct()
{ {
$this->Clear(); $this->Clear();

View file

@ -198,41 +198,38 @@ class Folder
$aFlags = $this->oImapFolder->FlagsLowerCase(); $aFlags = $this->oImapFolder->FlagsLowerCase();
$iListType = \MailSo\Imap\Enumerations\FolderType::USER; $iListType = \MailSo\Imap\Enumerations\FolderType::USER;
if (\is_array($aFlags)) switch (true)
{ {
switch (true) case \in_array('\inbox', $aFlags) || 'INBOX' === \strtoupper($this->FullNameRaw()):
{ $iListType = \MailSo\Imap\Enumerations\FolderType::INBOX;
case \in_array('\inbox', $aFlags) || 'INBOX' === \strtoupper($this->FullNameRaw()): break;
$iListType = \MailSo\Imap\Enumerations\FolderType::INBOX; case \in_array('\sent', $aFlags):
break; case \in_array('\sentmail', $aFlags):
case \in_array('\sent', $aFlags): $iListType = \MailSo\Imap\Enumerations\FolderType::SENT;
case \in_array('\sentmail', $aFlags): break;
$iListType = \MailSo\Imap\Enumerations\FolderType::SENT; case \in_array('\drafts', $aFlags):
break; $iListType = \MailSo\Imap\Enumerations\FolderType::DRAFTS;
case \in_array('\drafts', $aFlags): break;
$iListType = \MailSo\Imap\Enumerations\FolderType::DRAFTS; case \in_array('\junk', $aFlags):
break; case \in_array('\spam', $aFlags):
case \in_array('\junk', $aFlags): $iListType = \MailSo\Imap\Enumerations\FolderType::JUNK;
case \in_array('\spam', $aFlags): break;
$iListType = \MailSo\Imap\Enumerations\FolderType::JUNK; case \in_array('\trash', $aFlags):
break; case \in_array('\bin', $aFlags):
case \in_array('\trash', $aFlags): $iListType = \MailSo\Imap\Enumerations\FolderType::TRASH;
case \in_array('\bin', $aFlags): break;
$iListType = \MailSo\Imap\Enumerations\FolderType::TRASH; case \in_array('\important', $aFlags):
break; $iListType = \MailSo\Imap\Enumerations\FolderType::IMPORTANT;
case \in_array('\important', $aFlags): break;
$iListType = \MailSo\Imap\Enumerations\FolderType::IMPORTANT; case \in_array('\flagged', $aFlags):
break; case \in_array('\starred', $aFlags):
case \in_array('\flagged', $aFlags): $iListType = \MailSo\Imap\Enumerations\FolderType::FLAGGED;
case \in_array('\starred', $aFlags): break;
$iListType = \MailSo\Imap\Enumerations\FolderType::FLAGGED; case \in_array('\all', $aFlags):
break; case \in_array('\allmail', $aFlags):
case \in_array('\all', $aFlags): case \in_array('\archive', $aFlags):
case \in_array('\allmail', $aFlags): $iListType = \MailSo\Imap\Enumerations\FolderType::ALL;
case \in_array('\archive', $aFlags): break;
$iListType = \MailSo\Imap\Enumerations\FolderType::ALL;
break;
}
} }
return $iListType; return $iListType;

View file

@ -453,7 +453,7 @@ class MailClient
*/ */
public function MessageDelete(string $sFolder, array $aIndexRange, bool $bIndexIsUid, bool $bUseExpunge = true, bool $bExpungeAll = false) : self public function MessageDelete(string $sFolder, array $aIndexRange, bool $bIndexIsUid, bool $bUseExpunge = true, bool $bExpungeAll = false) : self
{ {
if (0 === \strlen($sFolder) || !\is_array($aIndexRange) || 0 === \count($aIndexRange)) if (0 === \strlen($sFolder) || 0 === \count($aIndexRange))
{ {
throw new \MailSo\Base\Exceptions\InvalidArgumentException(); throw new \MailSo\Base\Exceptions\InvalidArgumentException();
} }
@ -482,8 +482,7 @@ class MailClient
*/ */
public function MessageMove(string $sFromFolder, string $sToFolder, array $aIndexRange, bool $bIndexIsUid, bool $bUseMoveSupported = false, bool $bExpungeAll = false) : self public function MessageMove(string $sFromFolder, string $sToFolder, array $aIndexRange, bool $bIndexIsUid, bool $bUseMoveSupported = false, bool $bExpungeAll = false) : self
{ {
if (0 === \strlen($sFromFolder) || 0 === \strlen($sToFolder) || if (!$sFromFolder || !$sToFolder || 0 === \count($aIndexRange))
!\is_array($aIndexRange) || 0 === \count($aIndexRange))
{ {
throw new \MailSo\Base\Exceptions\InvalidArgumentException(); throw new \MailSo\Base\Exceptions\InvalidArgumentException();
} }
@ -513,8 +512,7 @@ class MailClient
*/ */
public function MessageCopy(string $sFromFolder, string $sToFolder, array $aIndexRange, bool $bIndexIsUid) : self public function MessageCopy(string $sFromFolder, string $sToFolder, array $aIndexRange, bool $bIndexIsUid) : self
{ {
if (0 === \strlen($sFromFolder) || 0 === \strlen($sToFolder) || if (!$sFromFolder || !$sToFolder || 0 === \count($aIndexRange))
!\is_array($aIndexRange) || 0 === \count($aIndexRange))
{ {
throw new \MailSo\Base\Exceptions\InvalidArgumentException(); throw new \MailSo\Base\Exceptions\InvalidArgumentException();
} }
@ -603,20 +601,6 @@ class MailClient
$sHighestModSeq = isset($aFolderStatus[\MailSo\Imap\Enumerations\FolderResponseStatus::HIGHESTMODSEQ]) $sHighestModSeq = isset($aFolderStatus[\MailSo\Imap\Enumerations\FolderResponseStatus::HIGHESTMODSEQ])
? (string) $aFolderStatus[\MailSo\Imap\Enumerations\FolderResponseStatus::HIGHESTMODSEQ] : ''; ? (string) $aFolderStatus[\MailSo\Imap\Enumerations\FolderResponseStatus::HIGHESTMODSEQ] : '';
if ($this->IsGmail() &&
('INBOX' === $sFolderName || '[gmail]' === \strtolower(\substr($sFolderName, 0, 7))))
{
$oFolder = $this->oImapClient->FolderCurrentInformation();
if ($oFolder && null !== $oFolder->Exists && $oFolder->FolderName === $sFolderName)
{
$iSubCount = (int) $oFolder->Exists;
if (0 < $iSubCount && $iSubCount < $iCount)
{
$iCount = $iSubCount;
}
}
}
} }
public function GenerateImapClientHash() : string public function GenerateImapClientHash() : string
@ -656,43 +640,40 @@ class MailClient
)) ))
), $sPrevUidNext.':*', true); ), $sPrevUidNext.':*', true);
if (\is_array($aFetchResponse) && 0 < \count($aFetchResponse)) foreach ($aFetchResponse as /* @var $oFetchResponse \MailSo\Imap\FetchResponse */ $oFetchResponse)
{ {
foreach ($aFetchResponse as /* @var $oFetchResponse \MailSo\Imap\FetchResponse */ $oFetchResponse) $aFlags = \array_map('strtolower', $oFetchResponse->GetFetchValue(
\MailSo\Imap\Enumerations\FetchType::FLAGS));
if (!\in_array(\strtolower(\MailSo\Imap\Enumerations\MessageFlag::SEEN), $aFlags))
{ {
$aFlags = \array_map('strtolower', $oFetchResponse->GetFetchValue( $sUid = $oFetchResponse->GetFetchValue(\MailSo\Imap\Enumerations\FetchType::UID);
\MailSo\Imap\Enumerations\FetchType::FLAGS)); $sHeaders = $oFetchResponse->GetHeaderFieldsValue();
if (!\in_array(\strtolower(\MailSo\Imap\Enumerations\MessageFlag::SEEN), $aFlags)) $oHeaders = \MailSo\Mime\HeaderCollection::NewInstance()->Parse($sHeaders);
$sContentTypeCharset = $oHeaders->ParameterValue(
\MailSo\Mime\Enumerations\Header::CONTENT_TYPE,
\MailSo\Mime\Enumerations\Parameter::CHARSET
);
$sCharset = '';
if (0 < \strlen($sContentTypeCharset))
{ {
$sUid = $oFetchResponse->GetFetchValue(\MailSo\Imap\Enumerations\FetchType::UID); $sCharset = $sContentTypeCharset;
$sHeaders = $oFetchResponse->GetHeaderFieldsValue();
$oHeaders = \MailSo\Mime\HeaderCollection::NewInstance()->Parse($sHeaders);
$sContentTypeCharset = $oHeaders->ParameterValue(
\MailSo\Mime\Enumerations\Header::CONTENT_TYPE,
\MailSo\Mime\Enumerations\Parameter::CHARSET
);
$sCharset = '';
if (0 < \strlen($sContentTypeCharset))
{
$sCharset = $sContentTypeCharset;
}
if (0 < \strlen($sCharset))
{
$oHeaders->SetParentCharset($sCharset);
}
$aNewMessages[] = array(
'Folder' => $sFolderName,
'Uid' => $sUid,
'Subject' => $oHeaders->ValueByName(\MailSo\Mime\Enumerations\Header::SUBJECT, 0 === \strlen($sCharset)),
'From' => $oHeaders->GetAsEmailCollection(\MailSo\Mime\Enumerations\Header::FROM_, 0 === \strlen($sCharset))
);
} }
if (0 < \strlen($sCharset))
{
$oHeaders->SetParentCharset($sCharset);
}
$aNewMessages[] = array(
'Folder' => $sFolderName,
'Uid' => $sUid,
'Subject' => $oHeaders->ValueByName(\MailSo\Mime\Enumerations\Header::SUBJECT, 0 === \strlen($sCharset)),
'From' => $oHeaders->GetAsEmailCollection(\MailSo\Mime\Enumerations\Header::FROM_, 0 === \strlen($sCharset))
);
} }
} }
} }
@ -710,14 +691,8 @@ class MailClient
$aFlags = array(); $aFlags = array();
$bSelect = false; $bSelect = false;
if ($this->IsGmail() &&
('INBOX' === $sFolderName || '[gmail]' === \strtolower(\substr($sFolderName, 0, 7))))
{
$this->oImapClient->FolderSelect($sFolderName);
$bSelect = true;
}
if (\is_array($aUids) && 0 < \count($aUids)) if (0 < \count($aUids))
{ {
if (!$bSelect) if (!$bSelect)
{ {
@ -730,14 +705,11 @@ class MailClient
\MailSo\Imap\Enumerations\FetchType::FLAGS \MailSo\Imap\Enumerations\FetchType::FLAGS
), \MailSo\Base\Utils::PrepareFetchSequence($aUids), true); ), \MailSo\Base\Utils::PrepareFetchSequence($aUids), true);
if (\is_array($aFetchResponse) && 0 < \count($aFetchResponse)) foreach ($aFetchResponse as $oFetchResponse)
{ {
foreach ($aFetchResponse as $oFetchResponse) $sUid = $oFetchResponse->GetFetchValue(\MailSo\Imap\Enumerations\FetchType::UID);
{ $aFlags[(\is_numeric($sUid) ? (int) $sUid : 0)] =
$sUid = $oFetchResponse->GetFetchValue(\MailSo\Imap\Enumerations\FetchType::UID); $oFetchResponse->GetFetchValue(\MailSo\Imap\Enumerations\FetchType::FLAGS);
$aFlags[(\is_numeric($sUid) ? (int) $sUid : 0)] =
$oFetchResponse->GetFetchValue(\MailSo\Imap\Enumerations\FetchType::FLAGS);
}
} }
} }
@ -796,17 +768,10 @@ class MailClient
return 0 < $iResult ? $iResult : 0; return 0 < $iResult ? $iResult : 0;
} }
public function IsGmail() : bool private function escapeSearchString(string $sSearch) : string
{
return 'ssl://imap.gmail.com' === \strtolower($this->oImapClient->GetConnectedHost());
}
private function escapeSearchString(string $sSearch, bool $bDetectGmail = true) : string
{ {
return !\MailSo\Base\Utils::IsAscii($sSearch) return !\MailSo\Base\Utils::IsAscii($sSearch)
? '{'.\strlen($sSearch).'}'."\r\n".$sSearch : $this->oImapClient->EscapeString($sSearch); ? '{'.\strlen($sSearch).'}'."\r\n".$sSearch : $this->oImapClient->EscapeString($sSearch);
// return ($bDetectGmail && !\MailSo\Base\Utils::IsAscii($sSearch) && $this->IsGmail())
// ? '{'.\strlen($sSearch).'+}'."\r\n".$sSearch : $this->oImapClient->EscapeString($sSearch);
} }
private function parseSearchDate(string $sDate, int $iTimeZoneOffset) : int private function parseSearchDate(string $sDate, int $iTimeZoneOffset) : int
@ -867,7 +832,7 @@ class MailClient
$mMatch = array(); $mMatch = array();
\preg_match_all('/".*?(?<!\\\)"/', $sSearch, $mMatch); \preg_match_all('/".*?(?<!\\\)"/', $sSearch, $mMatch);
if (\is_array($mMatch) && isset($mMatch[0]) && \is_array($mMatch[0]) && 0 < \count($mMatch[0])) if (\is_array($mMatch) && isset($mMatch[0]) && \is_array($mMatch[0]))
{ {
foreach ($mMatch[0] as $sItem) foreach ($mMatch[0] as $sItem)
{ {
@ -883,7 +848,7 @@ class MailClient
} }
\preg_match_all('/\'.*?(?<!\\\)\'/', $sSearch, $mMatch); \preg_match_all('/\'.*?(?<!\\\)\'/', $sSearch, $mMatch);
if (\is_array($mMatch) && isset($mMatch[0]) && \is_array($mMatch[0]) && 0 < \count($mMatch[0])) if (\is_array($mMatch) && isset($mMatch[0]) && \is_array($mMatch[0]))
{ {
foreach ($mMatch[0] as $sItem) foreach ($mMatch[0] as $sItem)
{ {
@ -985,11 +950,9 @@ class MailClient
if (0 < \strlen(\trim($sSearch))) if (0 < \strlen(\trim($sSearch)))
{ {
$sGmailRawSearch = '';
$sResultBodyTextSearch = ''; $sResultBodyTextSearch = '';
$aLines = $this->parseSearchString($sSearch); $aLines = $this->parseSearchString($sSearch);
$bIsGmail = $this->oImapClient->IsSupported('X-GM-EXT-1');
if (1 === \count($aLines) && isset($aLines['OTHER'])) if (1 === \count($aLines) && isset($aLines['OTHER']))
{ {
@ -1073,19 +1036,12 @@ class MailClient
$aCompareArray = array('file', 'files', 'attach', 'attachs', 'attachment', 'attachments'); $aCompareArray = array('file', 'files', 'attach', 'attachs', 'attachment', 'attachments');
if (\count($aCompareArray) > \count(\array_diff($aCompareArray, $aValue))) if (\count($aCompareArray) > \count(\array_diff($aCompareArray, $aValue)))
{ {
if ($bIsGmail) // Simple, is not detailed search (Sometimes doesn't work)
{ $aCriteriasResult[] = 'OR OR OR';
$sGmailRawSearch .= ' has:attachment'; $aCriteriasResult[] = 'HEADER Content-Type application/';
} $aCriteriasResult[] = 'HEADER Content-Type multipart/m';
else $aCriteriasResult[] = 'HEADER Content-Type multipart/signed';
{ $aCriteriasResult[] = 'HEADER Content-Type multipart/report';
// Simple, is not detailed search (Sometimes doesn't work)
$aCriteriasResult[] = 'OR OR OR';
$aCriteriasResult[] = 'HEADER Content-Type application/';
$aCriteriasResult[] = 'HEADER Content-Type multipart/m';
$aCriteriasResult[] = 'HEADER Content-Type multipart/signed';
$aCriteriasResult[] = 'HEADER Content-Type multipart/report';
}
} }
case 'IS': case 'IS':
@ -1133,7 +1089,7 @@ class MailClient
$sDate = $sRawValue; $sDate = $sRawValue;
$aDate = \explode('/', $sDate); $aDate = \explode('/', $sDate);
if (\is_array($aDate) && 2 === \count($aDate)) if (2 === \count($aDate))
{ {
if (0 < \strlen($aDate[0])) if (0 < \strlen($aDate[0]))
{ {
@ -1176,24 +1132,10 @@ class MailClient
if ('' !== \trim($sMainText)) if ('' !== \trim($sMainText))
{ {
$sMainText = \trim(\MailSo\Base\Utils::StripSpaces($sMainText), '"'); $sMainText = \trim(\MailSo\Base\Utils::StripSpaces($sMainText), '"');
if ($bIsGmail) $sResultBodyTextSearch .= ' '.$sMainText;
{
$sGmailRawSearch .= ' '.$sMainText;
}
else
{
$sResultBodyTextSearch .= ' '.$sMainText;
}
} }
} }
$sGmailRawSearch = \trim($sGmailRawSearch);
if ($bIsGmail && 0 < \strlen($sGmailRawSearch))
{
$aCriteriasResult[] = 'X-GM-RAW';
$aCriteriasResult[] = $this->escapeSearchString($sGmailRawSearch, false);
}
$sResultBodyTextSearch = \trim($sResultBodyTextSearch); $sResultBodyTextSearch = \trim($sResultBodyTextSearch);
if (0 < \strlen($sResultBodyTextSearch)) if (0 < \strlen($sResultBodyTextSearch))
{ {
@ -1248,7 +1190,7 @@ class MailClient
else else
{ {
$mMap = $this->threadArrayMap($mItem); $mMap = $this->threadArrayMap($mItem);
if (\is_array($mMap) && 0 < \count($mMap)) if (0 < \count($mMap))
{ {
$aNew = \array_merge($aNew, $mMap); $aNew = \array_merge($aNew, $mMap);
} }
@ -1266,16 +1208,13 @@ class MailClient
if (\is_array($mItem)) if (\is_array($mItem))
{ {
$aMap = $this->threadArrayMap($mItem); $aMap = $this->threadArrayMap($mItem);
if (\is_array($aMap)) if (1 < \count($aMap))
{ {
if (1 < \count($aMap)) $aResult[] = $aMap;
{ }
$aResult[] = $aMap; else if (0 < \count($aMap))
} {
else if (0 < \count($aMap)) $aResult[] = $aMap[0];
{
$aResult[] = $aMap[0];
}
} }
} }
else else
@ -1484,7 +1423,7 @@ class MailClient
*/ */
public function MessageListByRequestIndexOrUids(MessageCollection $oMessageCollection, array $aRequestIndexOrUids, bool $bIndexAsUid, bool $bSimple = false) public function MessageListByRequestIndexOrUids(MessageCollection $oMessageCollection, array $aRequestIndexOrUids, bool $bIndexAsUid, bool $bSimple = false)
{ {
if (\is_array($aRequestIndexOrUids) && 0 < \count($aRequestIndexOrUids)) if (0 < \count($aRequestIndexOrUids))
{ {
$aFetchResponse = $this->oImapClient->Fetch(array( $aFetchResponse = $this->oImapClient->Fetch(array(
\MailSo\Imap\Enumerations\FetchType::INDEX, \MailSo\Imap\Enumerations\FetchType::INDEX,
@ -1498,7 +1437,7 @@ class MailClient
$this->getEnvelopeOrHeadersRequestString() $this->getEnvelopeOrHeadersRequestString()
), \MailSo\Base\Utils::PrepareFetchSequence($aRequestIndexOrUids), $bIndexAsUid); ), \MailSo\Base\Utils::PrepareFetchSequence($aRequestIndexOrUids), $bIndexAsUid);
if (\is_array($aFetchResponse) && 0 < \count($aFetchResponse)) if (0 < \count($aFetchResponse))
{ {
$aFetchIndexArray = array(); $aFetchIndexArray = array();
$oFetchResponseItem = null; $oFetchResponseItem = null;
@ -1703,7 +1642,6 @@ class MailClient
if ($bUseThreadSortIfSupported && 0 < $iThreadUid && \is_array($mAllThreads)) if ($bUseThreadSortIfSupported && 0 < $iThreadUid && \is_array($mAllThreads))
{ {
$aUids = array();
$iResultRootUid = 0; $iResultRootUid = 0;
if (isset($mAllThreads[$iThreadUid])) if (isset($mAllThreads[$iThreadUid]))
@ -1747,7 +1685,7 @@ class MailClient
$aSearchedUids = $this->GetUids($oCacher, $sSearch, $sFilter, $aSearchedUids = $this->GetUids($oCacher, $sSearch, $sFilter,
$oMessageCollection->FolderName, $oMessageCollection->FolderHash); $oMessageCollection->FolderName, $oMessageCollection->FolderHash);
if (\is_array($aSearchedUids) && 0 < \count($aSearchedUids)) if (0 < \count($aSearchedUids))
{ {
$aFlippedSearchedUids = \array_flip($aSearchedUids); $aFlippedSearchedUids = \array_flip($aSearchedUids);
@ -1875,13 +1813,13 @@ class MailClient
$aUids = $this->oImapClient->MessageSimpleSearch( $aUids = $this->oImapClient->MessageSimpleSearch(
'HEADER Message-ID '.$sMessageId, true); 'HEADER Message-ID '.$sMessageId, true);
return \is_array($aUids) && 1 === \count($aUids) && \is_numeric($aUids[0]) ? (int) $aUids[0] : null; return 1 === \count($aUids) && \is_numeric($aUids[0]) ? (int) $aUids[0] : null;
} }
public function folderListOptimization(array $aMailFoldersHelper, int $iOptimizationLimit = 0) : array public function folderListOptimization(array $aMailFoldersHelper, int $iOptimizationLimit = 0) : array
{ {
// optimization // optimization
if (10 < $iOptimizationLimit && \is_array($aMailFoldersHelper) && $iOptimizationLimit < \count($aMailFoldersHelper)) if (10 < $iOptimizationLimit && $iOptimizationLimit < \count($aMailFoldersHelper))
{ {
if ($this->oLogger) if ($this->oLogger)
{ {
@ -2006,16 +1944,21 @@ class MailClient
return $aMailFoldersHelper; return $aMailFoldersHelper;
} }
public function Folders(string $sParent = '', string $sListPattern = '*', bool $bUseListSubscribeStatus = true, int $iOptimizationLimit = 0) : FolderCollection public function Folders(string $sParent = '', string $sListPattern = '*', bool $bUseListSubscribeStatus = true, int $iOptimizationLimit = 0) : ?FolderCollection
{ {
$oFolderCollection = false; $oFolderCollection = null;
$aSubscribedFolders = null; $aImapSubscribedFoldersHelper = null;
if ($bUseListSubscribeStatus) if ($bUseListSubscribeStatus)
{ {
try try
{ {
$aSubscribedFolders = $this->oImapClient->FolderSubscribeList($sParent, $sListPattern); $aSubscribedFolders = $this->oImapClient->FolderSubscribeList($sParent, $sListPattern);
$aImapSubscribedFoldersHelper = array();
foreach ($aSubscribedFolders as /* @var $oImapFolder \MailSo\Imap\Folder */ $oImapFolder)
{
$aImapSubscribedFoldersHelper[] = $oImapFolder->FullNameRaw();
}
} }
catch (\Throwable $oException) catch (\Throwable $oException)
{ {
@ -2023,22 +1966,9 @@ class MailClient
} }
} }
$aImapSubscribedFoldersHelper = null;
if (\is_array($aSubscribedFolders))
{
$aImapSubscribedFoldersHelper = array();
foreach ($aSubscribedFolders as /* @var $oImapFolder \MailSo\Imap\Folder */ $oImapFolder)
{
$aImapSubscribedFoldersHelper[] = $oImapFolder->FullNameRaw();
}
}
$aFolders = $this->oImapClient->FolderList($sParent, $sListPattern); $aFolders = $this->oImapClient->FolderList($sParent, $sListPattern);
$bOptimized = false; if ($aFolders)
$aMailFoldersHelper = null;
if (\is_array($aFolders))
{ {
$aMailFoldersHelper = array(); $aMailFoldersHelper = array();
@ -2053,15 +1983,13 @@ class MailClient
$iCount = \count($aMailFoldersHelper); $iCount = \count($aMailFoldersHelper);
$aMailFoldersHelper = $this->folderListOptimization($aMailFoldersHelper, $iOptimizationLimit); $aMailFoldersHelper = $this->folderListOptimization($aMailFoldersHelper, $iOptimizationLimit);
$bOptimized = $iCount !== \count($aMailFoldersHelper); if ($aMailFoldersHelper)
} {
$oFolderCollection = FolderCollection::NewInstance();
$oFolderCollection->InitByUnsortedMailFolderArray($aMailFoldersHelper);
if (\is_array($aMailFoldersHelper)) $oFolderCollection->Optimized = $iCount !== \count($aMailFoldersHelper);
{ }
$oFolderCollection = FolderCollection::NewInstance();
$oFolderCollection->InitByUnsortedMailFolderArray($aMailFoldersHelper);
$oFolderCollection->Optimized = $bOptimized;
} }
if ($oFolderCollection) if ($oFolderCollection)
@ -2075,10 +2003,6 @@ class MailClient
return -1; return -1;
case 'INBOX' === $sB: case 'INBOX' === $sB:
return 1; return 1;
case '[GMAIL]' === $sA:
return -1;
case '[GMAIL]' === $sB:
return 1;
} }
return \strnatcasecmp($oFolderA->FullName(), $oFolderB->FullName()); return \strnatcasecmp($oFolderA->FullName(), $oFolderB->FullName());
@ -2111,7 +2035,7 @@ class MailClient
if (0 === \strlen($sDelimiter) || 0 < \strlen(\trim($sFolderParentFullNameRaw))) if (0 === \strlen($sDelimiter) || 0 < \strlen(\trim($sFolderParentFullNameRaw)))
{ {
$aFolders = $this->oImapClient->FolderList('', 0 === \strlen(\trim($sFolderParentFullNameRaw)) ? 'INBOX' : $sFolderParentFullNameRaw); $aFolders = $this->oImapClient->FolderList('', 0 === \strlen(\trim($sFolderParentFullNameRaw)) ? 'INBOX' : $sFolderParentFullNameRaw);
if (!\is_array($aFolders) || !isset($aFolders[0])) if (!$aFolders)
{ {
// TODO // TODO
throw new \MailSo\Mail\Exceptions\RuntimeException( throw new \MailSo\Mail\Exceptions\RuntimeException(
@ -2177,7 +2101,7 @@ class MailClient
} }
$aFolders = $this->oImapClient->FolderList('', $sPrevFolderFullNameRaw); $aFolders = $this->oImapClient->FolderList('', $sPrevFolderFullNameRaw);
if (!\is_array($aFolders) || !isset($aFolders[0])) if (!$aFolders)
{ {
// TODO // TODO
throw new \MailSo\Mail\Exceptions\RuntimeException('Cannot rename non-existen folder'); throw new \MailSo\Mail\Exceptions\RuntimeException('Cannot rename non-existen folder');
@ -2186,16 +2110,13 @@ class MailClient
$sDelimiter = $aFolders[0]->Delimiter(); $sDelimiter = $aFolders[0]->Delimiter();
$iLast = \strrpos($sPrevFolderFullNameRaw, $sDelimiter); $iLast = \strrpos($sPrevFolderFullNameRaw, $sDelimiter);
$mSubscribeFolders = null; $aSubscribeFolders = array();
if ($bSubscribeOnModify) if ($bSubscribeOnModify)
{ {
$mSubscribeFolders = $this->oImapClient->FolderSubscribeList($sPrevFolderFullNameRaw, '*'); $aSubscribeFolders = $this->oImapClient->FolderSubscribeList($sPrevFolderFullNameRaw, '*');
if (\is_array($mSubscribeFolders) && 0 < count($mSubscribeFolders)) foreach ($aSubscribeFolders as /* @var $oFolder \MailSo\Imap\Folder */ $oFolder)
{ {
foreach ($mSubscribeFolders as /* @var $oFolder \MailSo\Imap\Folder */ $oFolder) $this->oImapClient->FolderUnSubscribe($oFolder->FullNameRaw());
{
$this->oImapClient->FolderUnSubscribe($oFolder->FullNameRaw());
}
} }
} }
@ -2203,7 +2124,7 @@ class MailClient
\MailSo\Base\Enumerations\Charset::UTF_8, \MailSo\Base\Enumerations\Charset::UTF_8,
\MailSo\Base\Enumerations\Charset::UTF_7_IMAP); \MailSo\Base\Enumerations\Charset::UTF_7_IMAP);
if($bRenameOrMove) if ($bRenameOrMove)
{ {
if (0 < \strlen($sDelimiter) && false !== \strpos($sNewFolderFullNameRaw, $sDelimiter)) if (0 < \strlen($sDelimiter) && false !== \strpos($sNewFolderFullNameRaw, $sDelimiter))
{ {
@ -2217,18 +2138,15 @@ class MailClient
$this->oImapClient->FolderRename($sPrevFolderFullNameRaw, $sNewFolderFullNameRaw); $this->oImapClient->FolderRename($sPrevFolderFullNameRaw, $sNewFolderFullNameRaw);
if (\is_array($mSubscribeFolders) && 0 < count($mSubscribeFolders)) foreach ($aSubscribeFolders as /* @var $oFolder \MailSo\Imap\Folder */ $oFolder)
{ {
foreach ($mSubscribeFolders as /* @var $oFolder \MailSo\Imap\Folder */ $oFolder) $sFolderFullNameRawForResubscrine = $oFolder->FullNameRaw();
if (0 === \strpos($sFolderFullNameRawForResubscrine, $sPrevFolderFullNameRaw))
{ {
$sFolderFullNameRawForResubscrine = $oFolder->FullNameRaw(); $sNewFolderFullNameRawForResubscrine = $sNewFolderFullNameRaw.
if (0 === \strpos($sFolderFullNameRawForResubscrine, $sPrevFolderFullNameRaw)) \substr($sFolderFullNameRawForResubscrine, \strlen($sPrevFolderFullNameRaw));
{
$sNewFolderFullNameRawForResubscrine = $sNewFolderFullNameRaw.
\substr($sFolderFullNameRawForResubscrine, \strlen($sPrevFolderFullNameRaw));
$this->oImapClient->FolderSubscribe($sNewFolderFullNameRawForResubscrine); $this->oImapClient->FolderSubscribe($sNewFolderFullNameRawForResubscrine);
}
} }
} }

View file

@ -422,7 +422,7 @@ class Message
public function SetThreads(array $aThreads) public function SetThreads(array $aThreads)
{ {
$this->aThreads = \is_array($aThreads) ? $aThreads : array(); $this->aThreads = $aThreads;
} }
public function TextPartIsTrimmed() : bool public function TextPartIsTrimmed() : bool

View file

@ -226,7 +226,7 @@ class HeaderCollection extends \MailSo\Base\Collection
$aResult = array(); $aResult = array();
$aHeaders = $this->ValuesByName(Enumerations\Header::AUTHENTICATION_RESULTS); $aHeaders = $this->ValuesByName(Enumerations\Header::AUTHENTICATION_RESULTS);
if (\is_array($aHeaders) && 0 < \count($aHeaders)) if (0 < \count($aHeaders))
{ {
foreach ($aHeaders as $sHeaderValue) foreach ($aHeaders as $sHeaderValue)
{ {
@ -265,31 +265,28 @@ class HeaderCollection extends \MailSo\Base\Collection
{ {
// X-DKIM-Authentication-Results: signer="hostinger.com" status="pass" // X-DKIM-Authentication-Results: signer="hostinger.com" status="pass"
$aHeaders = $this->ValuesByName(Enumerations\Header::X_DKIM_AUTHENTICATION_RESULTS); $aHeaders = $this->ValuesByName(Enumerations\Header::X_DKIM_AUTHENTICATION_RESULTS);
if (\is_array($aHeaders) && 0 < \count($aHeaders)) foreach ($aHeaders as $sHeaderValue)
{ {
foreach ($aHeaders as $sHeaderValue) $sStatus = '';
$sHeader = '';
$aMatch = array();
$sHeaderValue = \preg_replace('/[\r\n\t\s]+/', ' ', $sHeaderValue);
if (\preg_match('/status[\s]?=[\s]?"([a-zA-Z0-9]+)"/i', $sHeaderValue, $aMatch) && !empty($aMatch[1]))
{ {
$sStatus = ''; $sStatus = $aMatch[1];
$sHeader = ''; }
$aMatch = array(); if (\preg_match('/signer[\s]?=[\s]?"([^";]+)"/i', $sHeaderValue, $aMatch) && !empty($aMatch[1]))
{
$sHeader = \trim($aMatch[1]);
}
$sHeaderValue = \preg_replace('/[\r\n\t\s]+/', ' ', $sHeaderValue); if (!empty($sStatus) && !empty($sHeader))
{
if (\preg_match('/status[\s]?=[\s]?"([a-zA-Z0-9]+)"/i', $sHeaderValue, $aMatch) && !empty($aMatch[1])) $aResult[] = array($sStatus, $sHeader, $sHeaderValue);
{
$sStatus = $aMatch[1];
}
if (\preg_match('/signer[\s]?=[\s]?"([^";]+)"/i', $sHeaderValue, $aMatch) && !empty($aMatch[1]))
{
$sHeader = \trim($aMatch[1]);
}
if (!empty($sStatus) && !empty($sHeader))
{
$aResult[] = array($sStatus, $sHeader, $sHeaderValue);
}
} }
} }
} }
@ -300,15 +297,13 @@ class HeaderCollection extends \MailSo\Base\Collection
public function PopulateEmailColectionByDkim(EmailCollection $oEmails) : void public function PopulateEmailColectionByDkim(EmailCollection $oEmails) : void
{ {
$aDkimStatuses = $this->DkimStatuses(); $aDkimStatuses = $this->DkimStatuses();
if (\is_array($aDkimStatuses) && 0 < \count($aDkimStatuses)) { foreach ($oEmails as $oEmail) {
foreach ($oEmails as $oEmail) { $sEmail = $oEmail->GetEmail();
$sEmail = $oEmail->GetEmail(); foreach ($aDkimStatuses as $aDkimData) {
foreach ($aDkimStatuses as $aDkimData) { if (isset($aDkimData[0], $aDkimData[1]) &&
if (isset($aDkimData[0], $aDkimData[1]) && $aDkimData[1] === \strstr($sEmail, $aDkimData[1]))
$aDkimData[1] === \strstr($sEmail, $aDkimData[1])) {
{ $oEmail->SetDkimStatusAndValue($aDkimData[0], empty($aDkimData[2]) ? '' : $aDkimData[2]);
$oEmail->SetDkimStatusAndValue($aDkimData[0], empty($aDkimData[2]) ? '' : $aDkimData[2]);
}
} }
} }
} }

View file

@ -28,7 +28,7 @@ class Message
private $aAlternativeParts; private $aAlternativeParts;
/** /**
* @var \MailSo\Mime\AttachmentCollection * @var AttachmentCollection
*/ */
private $oAttachmentCollection; private $oAttachmentCollection;
@ -73,16 +73,16 @@ class Message
public function MessageId() : string public function MessageId() : string
{ {
$sResult = ''; $sResult = '';
if (!empty($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::MESSAGE_ID])) if (!empty($this->aHeadersValue[Enumerations\Header::MESSAGE_ID]))
{ {
$sResult = $this->aHeadersValue[\MailSo\Mime\Enumerations\Header::MESSAGE_ID]; $sResult = $this->aHeadersValue[Enumerations\Header::MESSAGE_ID];
} }
return $sResult; return $sResult;
} }
public function SetMessageId(string $sMessageId) : void public function SetMessageId(string $sMessageId) : void
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::MESSAGE_ID] = $sMessageId; $this->aHeadersValue[Enumerations\Header::MESSAGE_ID] = $sMessageId;
} }
public function RegenerateMessageId(string $sHostName = '') : void public function RegenerateMessageId(string $sHostName = '') : void
@ -90,76 +90,76 @@ class Message
$this->SetMessageId($this->generateNewMessageId($sHostName)); $this->SetMessageId($this->generateNewMessageId($sHostName));
} }
public function Attachments() : \MailSo\Mime\AttachmentCollection public function Attachments() : AttachmentCollection
{ {
return $this->oAttachmentCollection; return $this->oAttachmentCollection;
} }
public function GetSubject() : string public function GetSubject() : string
{ {
return isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::SUBJECT]) ? return isset($this->aHeadersValue[Enumerations\Header::SUBJECT]) ?
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::SUBJECT] : ''; $this->aHeadersValue[Enumerations\Header::SUBJECT] : '';
} }
public function GetFrom() : ?\MailSo\Mime\Email public function GetFrom() : ?Email
{ {
$oResult = null; $oResult = null;
if (isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::FROM_]) && if (isset($this->aHeadersValue[Enumerations\Header::FROM_]) &&
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::FROM_] instanceof \MailSo\Mime\Email) $this->aHeadersValue[Enumerations\Header::FROM_] instanceof Email)
{ {
$oResult = $this->aHeadersValue[\MailSo\Mime\Enumerations\Header::FROM_]; $oResult = $this->aHeadersValue[Enumerations\Header::FROM_];
} }
return $oResult; return $oResult;
} }
public function GetTo() : \MailSo\Mime\EmailCollection public function GetTo() : EmailCollection
{ {
$oResult = \MailSo\Mime\EmailCollection::NewInstance(); $oResult = EmailCollection::NewInstance();
if (isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::TO_]) && if (isset($this->aHeadersValue[Enumerations\Header::TO_]) &&
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::TO_] instanceof \MailSo\Mime\EmailCollection) $this->aHeadersValue[Enumerations\Header::TO_] instanceof EmailCollection)
{ {
$oResult->MergeWithOtherCollection($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::TO_]); $oResult->MergeWithOtherCollection($this->aHeadersValue[Enumerations\Header::TO_]);
} }
return $oResult->Unique(); return $oResult->Unique();
} }
public function GetBcc() : ?\MailSo\Mime\EmailCollection public function GetBcc() : ?EmailCollection
{ {
$oResult = null; $oResult = null;
if (isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::BCC]) && if (isset($this->aHeadersValue[Enumerations\Header::BCC]) &&
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::BCC] instanceof \MailSo\Mime\EmailCollection) $this->aHeadersValue[Enumerations\Header::BCC] instanceof EmailCollection)
{ {
$oResult = $this->aHeadersValue[\MailSo\Mime\Enumerations\Header::BCC]; $oResult = $this->aHeadersValue[Enumerations\Header::BCC];
} }
return $oResult ? $oResult->Unique() : null; return $oResult ? $oResult->Unique() : null;
} }
public function GetRcpt() : \MailSo\Mime\EmailCollection public function GetRcpt() : EmailCollection
{ {
$oResult = \MailSo\Mime\EmailCollection::NewInstance(); $oResult = EmailCollection::NewInstance();
if (isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::TO_]) && if (isset($this->aHeadersValue[Enumerations\Header::TO_]) &&
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::TO_] instanceof \MailSo\Mime\EmailCollection) $this->aHeadersValue[Enumerations\Header::TO_] instanceof EmailCollection)
{ {
$oResult->MergeWithOtherCollection($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::TO_]); $oResult->MergeWithOtherCollection($this->aHeadersValue[Enumerations\Header::TO_]);
} }
if (isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::CC]) && if (isset($this->aHeadersValue[Enumerations\Header::CC]) &&
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::CC] instanceof \MailSo\Mime\EmailCollection) $this->aHeadersValue[Enumerations\Header::CC] instanceof EmailCollection)
{ {
$oResult->MergeWithOtherCollection($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::CC]); $oResult->MergeWithOtherCollection($this->aHeadersValue[Enumerations\Header::CC]);
} }
if (isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::BCC]) && if (isset($this->aHeadersValue[Enumerations\Header::BCC]) &&
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::BCC] instanceof \MailSo\Mime\EmailCollection) $this->aHeadersValue[Enumerations\Header::BCC] instanceof EmailCollection)
{ {
$oResult->MergeWithOtherCollection($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::BCC]); $oResult->MergeWithOtherCollection($this->aHeadersValue[Enumerations\Header::BCC]);
} }
return $oResult->Unique(); return $oResult->Unique();
@ -178,21 +178,21 @@ class Message
public function SetSubject(string $sSubject) : self public function SetSubject(string $sSubject) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::SUBJECT] = $sSubject; $this->aHeadersValue[Enumerations\Header::SUBJECT] = $sSubject;
return $this; return $this;
} }
public function SetInReplyTo(string $sInReplyTo) : self public function SetInReplyTo(string $sInReplyTo) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::IN_REPLY_TO] = $sInReplyTo; $this->aHeadersValue[Enumerations\Header::IN_REPLY_TO] = $sInReplyTo;
return $this; return $this;
} }
public function SetReferences(string $sReferences) : self public function SetReferences(string $sReferences) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::REFERENCES] = $this->aHeadersValue[Enumerations\Header::REFERENCES] =
\MailSo\Base\Utils::StripSpaces($sReferences); \MailSo\Base\Utils::StripSpaces($sReferences);
return $this; return $this;
@ -200,8 +200,8 @@ class Message
public function SetReadReceipt(string $sEmail) : self public function SetReadReceipt(string $sEmail) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::DISPOSITION_NOTIFICATION_TO] = $sEmail; $this->aHeadersValue[Enumerations\Header::DISPOSITION_NOTIFICATION_TO] = $sEmail;
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::X_CONFIRM_READING_TO] = $sEmail; $this->aHeadersValue[Enumerations\Header::X_CONFIRM_READING_TO] = $sEmail;
return $this; return $this;
} }
@ -216,20 +216,20 @@ class Message
$sResult = ''; $sResult = '';
switch ($iValue) switch ($iValue)
{ {
case \MailSo\Mime\Enumerations\MessagePriority::HIGH: case Enumerations\MessagePriority::HIGH:
$sResult = \MailSo\Mime\Enumerations\MessagePriority::HIGH.' (Highest)'; $sResult = Enumerations\MessagePriority::HIGH.' (Highest)';
break; break;
case \MailSo\Mime\Enumerations\MessagePriority::NORMAL: case Enumerations\MessagePriority::NORMAL:
$sResult = \MailSo\Mime\Enumerations\MessagePriority::NORMAL.' (Normal)'; $sResult = Enumerations\MessagePriority::NORMAL.' (Normal)';
break; break;
case \MailSo\Mime\Enumerations\MessagePriority::LOW: case Enumerations\MessagePriority::LOW:
$sResult = \MailSo\Mime\Enumerations\MessagePriority::LOW.' (Lowest)'; $sResult = Enumerations\MessagePriority::LOW.' (Lowest)';
break; break;
} }
if (0 < \strlen($sResult)) if (0 < \strlen($sResult))
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::X_PRIORITY] = $sResult; $this->aHeadersValue[Enumerations\Header::X_PRIORITY] = $sResult;
} }
return $this; return $this;
@ -240,20 +240,20 @@ class Message
$sResult = ''; $sResult = '';
switch ($iValue) switch ($iValue)
{ {
case \MailSo\Mime\Enumerations\Sensitivity::CONFIDENTIAL: case Enumerations\Sensitivity::CONFIDENTIAL:
$sResult = 'Company-Confidential'; $sResult = 'Company-Confidential';
break; break;
case \MailSo\Mime\Enumerations\Sensitivity::PERSONAL: case Enumerations\Sensitivity::PERSONAL:
$sResult = 'Personal'; $sResult = 'Personal';
break; break;
case \MailSo\Mime\Enumerations\Sensitivity::PRIVATE_: case Enumerations\Sensitivity::PRIVATE_:
$sResult = 'Private'; $sResult = 'Private';
break; break;
} }
if (0 < \strlen($sResult)) if (0 < \strlen($sResult))
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::SENSITIVITY] = $sResult; $this->aHeadersValue[Enumerations\Header::SENSITIVITY] = $sResult;
} }
return $this; return $this;
@ -261,66 +261,66 @@ class Message
public function SetXMailer(string $sXMailer) : self public function SetXMailer(string $sXMailer) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::X_MAILER] = $sXMailer; $this->aHeadersValue[Enumerations\Header::X_MAILER] = $sXMailer;
return $this; return $this;
} }
public function SetFrom(\MailSo\Mime\Email $oEmail) : self public function SetFrom(Email $oEmail) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::FROM_] = $oEmail; $this->aHeadersValue[Enumerations\Header::FROM_] = $oEmail;
return $this; return $this;
} }
public function SetTo(\MailSo\Mime\EmailCollection $oEmails) : self public function SetTo(EmailCollection $oEmails) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::TO_] = $oEmails; $this->aHeadersValue[Enumerations\Header::TO_] = $oEmails;
return $this; return $this;
} }
public function SetDate(int $iDateTime) : self public function SetDate(int $iDateTime) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::DATE] = gmdate('r', $iDateTime); $this->aHeadersValue[Enumerations\Header::DATE] = gmdate('r', $iDateTime);
return $this; return $this;
} }
public function SetReplyTo(\MailSo\Mime\EmailCollection $oEmails) : self public function SetReplyTo(EmailCollection $oEmails) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::REPLY_TO] = $oEmails; $this->aHeadersValue[Enumerations\Header::REPLY_TO] = $oEmails;
return $this; return $this;
} }
public function SetCc(\MailSo\Mime\EmailCollection $oEmails) : self public function SetCc(EmailCollection $oEmails) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::CC] = $oEmails; $this->aHeadersValue[Enumerations\Header::CC] = $oEmails;
return $this; return $this;
} }
public function SetBcc(\MailSo\Mime\EmailCollection $oEmails) : self public function SetBcc(EmailCollection $oEmails) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::BCC] = $oEmails; $this->aHeadersValue[Enumerations\Header::BCC] = $oEmails;
return $this; return $this;
} }
public function SetSender(\MailSo\Mime\EmailCollection $oEmails) : self public function SetSender(EmailCollection $oEmails) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::SENDER] = $oEmails; $this->aHeadersValue[Enumerations\Header::SENDER] = $oEmails;
return $this; return $this;
} }
public function SetDraftInfo(string $sType, string $sUid, string $sFolder) : self public function SetDraftInfo(string $sType, string $sUid, string $sFolder) : self
{ {
$this->aHeadersValue[\MailSo\Mime\Enumerations\Header::X_DRAFT_INFO] = \MailSo\Mime\ParameterCollection::NewInstance() $this->aHeadersValue[Enumerations\Header::X_DRAFT_INFO] = ParameterCollection::NewInstance()
->Add(\MailSo\Mime\Parameter::NewInstance('type', $sType)) ->Add(Parameter::NewInstance('type', $sType))
->Add(\MailSo\Mime\Parameter::NewInstance('uid', $sUid)) ->Add(Parameter::NewInstance('uid', $sUid))
->Add(\MailSo\Mime\Parameter::NewInstance('folder', base64_encode($sFolder))) ->Add(Parameter::NewInstance('folder', base64_encode($sFolder)))
; ;
return $this; return $this;
@ -329,14 +329,14 @@ class Message
public function AddPlain(string $sPlain) : self public function AddPlain(string $sPlain) : self
{ {
return $this->AddAlternative( return $this->AddAlternative(
\MailSo\Mime\Enumerations\MimeType::TEXT_PLAIN, trim($sPlain), Enumerations\MimeType::TEXT_PLAIN, trim($sPlain),
\MailSo\Base\Enumerations\Encoding::QUOTED_PRINTABLE_LOWER); \MailSo\Base\Enumerations\Encoding::QUOTED_PRINTABLE_LOWER);
} }
public function AddHtml(string $sHtml) : self public function AddHtml(string $sHtml) : self
{ {
return $this->AddAlternative( return $this->AddAlternative(
\MailSo\Mime\Enumerations\MimeType::TEXT_HTML, trim($sHtml), Enumerations\MimeType::TEXT_HTML, trim($sHtml),
\MailSo\Base\Enumerations\Encoding::QUOTED_PRINTABLE_LOWER); \MailSo\Base\Enumerations\Encoding::QUOTED_PRINTABLE_LOWER);
} }
@ -380,7 +380,7 @@ class Message
(\MailSo\Base\Utils::FunctionExistsAndEnabled('getmypid') ? \getmypid() : '')).'@'.$sHostName.'>'; (\MailSo\Base\Utils::FunctionExistsAndEnabled('getmypid') ? \getmypid() : '')).'@'.$sHostName.'>';
} }
private function createNewMessageAttachmentBody(\MailSo\Mime\Attachment $oAttachment) : \MailSo\Mime\Part private function createNewMessageAttachmentBody(Attachment $oAttachment) : Part
{ {
$oAttachmentPart = Part::NewInstance(); $oAttachmentPart = Part::NewInstance();
@ -395,22 +395,22 @@ class Message
{ {
$oContentTypeParameters = $oContentTypeParameters =
ParameterCollection::NewInstance()->Add(Parameter::NewInstance( ParameterCollection::NewInstance()->Add(Parameter::NewInstance(
\MailSo\Mime\Enumerations\Parameter::NAME, $sFileName)); Enumerations\Parameter::NAME, $sFileName));
$oContentDispositionParameters = $oContentDispositionParameters =
ParameterCollection::NewInstance()->Add(Parameter::NewInstance( ParameterCollection::NewInstance()->Add(Parameter::NewInstance(
\MailSo\Mime\Enumerations\Parameter::FILENAME, $sFileName)); Enumerations\Parameter::FILENAME, $sFileName));
} }
$oAttachmentPart->Headers->append( $oAttachmentPart->Headers->append(
Header::NewInstance(\MailSo\Mime\Enumerations\Header::CONTENT_TYPE, Header::NewInstance(Enumerations\Header::CONTENT_TYPE,
$oAttachment->ContentType().';'. $oAttachment->ContentType().';'.
(($oContentTypeParameters) ? ' '.$oContentTypeParameters->ToString() : '') (($oContentTypeParameters) ? ' '.$oContentTypeParameters->ToString() : '')
) )
); );
$oAttachmentPart->Headers->append( $oAttachmentPart->Headers->append(
Header::NewInstance(\MailSo\Mime\Enumerations\Header::CONTENT_DISPOSITION, Header::NewInstance(Enumerations\Header::CONTENT_DISPOSITION,
($oAttachment->IsInline() ? 'inline' : 'attachment').';'. ($oAttachment->IsInline() ? 'inline' : 'attachment').';'.
(($oContentDispositionParameters) ? ' '.$oContentDispositionParameters->ToString() : '') (($oContentDispositionParameters) ? ' '.$oContentDispositionParameters->ToString() : '')
) )
@ -419,14 +419,14 @@ class Message
if (0 < strlen($sCID)) if (0 < strlen($sCID))
{ {
$oAttachmentPart->Headers->append( $oAttachmentPart->Headers->append(
Header::NewInstance(\MailSo\Mime\Enumerations\Header::CONTENT_ID, $sCID) Header::NewInstance(Enumerations\Header::CONTENT_ID, $sCID)
); );
} }
if (0 < strlen($sContentLocation)) if (0 < strlen($sContentLocation))
{ {
$oAttachmentPart->Headers->append( $oAttachmentPart->Headers->append(
Header::NewInstance(\MailSo\Mime\Enumerations\Header::CONTENT_LOCATION, $sContentLocation) Header::NewInstance(Enumerations\Header::CONTENT_LOCATION, $sContentLocation)
); );
} }
@ -436,7 +436,7 @@ class Message
{ {
$oAttachmentPart->Headers->append( $oAttachmentPart->Headers->append(
Header::NewInstance( Header::NewInstance(
\MailSo\Mime\Enumerations\Header::CONTENT_TRANSFER_ENCODING, Enumerations\Header::CONTENT_TRANSFER_ENCODING,
\MailSo\Base\Enumerations\Encoding::BASE64_LOWER \MailSo\Base\Enumerations\Encoding::BASE64_LOWER
) )
); );
@ -458,17 +458,17 @@ class Message
return $oAttachmentPart; return $oAttachmentPart;
} }
private function createNewMessageAlternativePartBody(array $aAlternativeData) : \MailSo\Mime\Part private function createNewMessageAlternativePartBody(array $aAlternativeData) : ?Part
{ {
$oAlternativePart = null; $oAlternativePart = null;
if (is_array($aAlternativeData) && isset($aAlternativeData[0])) if (isset($aAlternativeData[0]))
{ {
$oAlternativePart = Part::NewInstance(); $oAlternativePart = Part::NewInstance();
$oParameters = ParameterCollection::NewInstance(); $oParameters = ParameterCollection::NewInstance();
$oParameters->append( $oParameters->append(
Parameter::NewInstance( Parameter::NewInstance(
\MailSo\Mime\Enumerations\Parameter::CHARSET, Enumerations\Parameter::CHARSET,
\MailSo\Base\Enumerations\Charset::UTF_8) \MailSo\Base\Enumerations\Charset::UTF_8)
); );
@ -481,7 +481,7 @@ class Message
} }
$oAlternativePart->Headers->append( $oAlternativePart->Headers->append(
Header::NewInstance(\MailSo\Mime\Enumerations\Header::CONTENT_TYPE, Header::NewInstance(Enumerations\Header::CONTENT_TYPE,
$aAlternativeData[0].'; '.$oParameters->ToString()) $aAlternativeData[0].'; '.$oParameters->ToString())
); );
@ -502,7 +502,7 @@ class Message
if (isset($aAlternativeData[2]) && 0 < strlen($aAlternativeData[2])) if (isset($aAlternativeData[2]) && 0 < strlen($aAlternativeData[2]))
{ {
$oAlternativePart->Headers->append( $oAlternativePart->Headers->append(
Header::NewInstance(\MailSo\Mime\Enumerations\Header::CONTENT_TRANSFER_ENCODING, Header::NewInstance(Enumerations\Header::CONTENT_TRANSFER_ENCODING,
$aAlternativeData[2] $aAlternativeData[2]
) )
); );
@ -531,7 +531,7 @@ class Message
return $oAlternativePart; return $oAlternativePart;
} }
private function createNewMessageSimpleOrAlternativeBody() : \MailSo\Mime\Part private function createNewMessageSimpleOrAlternativeBody() : Part
{ {
$oResultPart = null; $oResultPart = null;
if (1 < count($this->aAlternativeParts)) if (1 < count($this->aAlternativeParts))
@ -539,11 +539,11 @@ class Message
$oResultPart = Part::NewInstance(); $oResultPart = Part::NewInstance();
$oResultPart->Headers->append( $oResultPart->Headers->append(
Header::NewInstance(\MailSo\Mime\Enumerations\Header::CONTENT_TYPE, Header::NewInstance(Enumerations\Header::CONTENT_TYPE,
\MailSo\Mime\Enumerations\MimeType::MULTIPART_ALTERNATIVE.'; '. Enumerations\MimeType::MULTIPART_ALTERNATIVE.'; '.
ParameterCollection::NewInstance()->Add( ParameterCollection::NewInstance()->Add(
Parameter::NewInstance( Parameter::NewInstance(
\MailSo\Mime\Enumerations\Parameter::BOUNDARY, Enumerations\Parameter::BOUNDARY,
$this->generateNewBoundary()) $this->generateNewBoundary())
)->ToString() )->ToString()
) )
@ -575,13 +575,13 @@ class Message
if ($this->bAddEmptyTextPart) if ($this->bAddEmptyTextPart)
{ {
$oResultPart = $this->createNewMessageAlternativePartBody(array( $oResultPart = $this->createNewMessageAlternativePartBody(array(
\MailSo\Mime\Enumerations\MimeType::TEXT_PLAIN, null Enumerations\MimeType::TEXT_PLAIN, null
)); ));
} }
else else
{ {
$aAttachments = $this->oAttachmentCollection->getArrayCopy(); $aAttachments = $this->oAttachmentCollection->getArrayCopy();
if (\is_array($aAttachments) && 1 === count($aAttachments) && isset($aAttachments[0])) if (1 === count($aAttachments) && isset($aAttachments[0]))
{ {
$this->oAttachmentCollection->Clear(); $this->oAttachmentCollection->Clear();
@ -596,7 +596,7 @@ class Message
return $oResultPart; return $oResultPart;
} }
private function createNewMessageRelatedBody(\MailSo\Mime\Part $oIncPart) : \MailSo\Mime\Part private function createNewMessageRelatedBody(Part $oIncPart) : Part
{ {
$oResultPart = null; $oResultPart = null;
@ -606,11 +606,11 @@ class Message
$oResultPart = Part::NewInstance(); $oResultPart = Part::NewInstance();
$oResultPart->Headers->append( $oResultPart->Headers->append(
Header::NewInstance(\MailSo\Mime\Enumerations\Header::CONTENT_TYPE, Header::NewInstance(Enumerations\Header::CONTENT_TYPE,
\MailSo\Mime\Enumerations\MimeType::MULTIPART_RELATED.'; '. Enumerations\MimeType::MULTIPART_RELATED.'; '.
ParameterCollection::NewInstance()->Add( ParameterCollection::NewInstance()->Add(
Parameter::NewInstance( Parameter::NewInstance(
\MailSo\Mime\Enumerations\Parameter::BOUNDARY, Enumerations\Parameter::BOUNDARY,
$this->generateNewBoundary()) $this->generateNewBoundary())
)->ToString() )->ToString()
) )
@ -631,7 +631,7 @@ class Message
return $oResultPart; return $oResultPart;
} }
private function createNewMessageMixedBody(\MailSo\Mime\Part $oIncPart) : \MailSo\Mime\Part private function createNewMessageMixedBody(Part $oIncPart) : Part
{ {
$oResultPart = null; $oResultPart = null;
@ -640,11 +640,11 @@ class Message
{ {
$oResultPart = Part::NewInstance(); $oResultPart = Part::NewInstance();
$oResultPart->Headers->AddByName(\MailSo\Mime\Enumerations\Header::CONTENT_TYPE, $oResultPart->Headers->AddByName(Enumerations\Header::CONTENT_TYPE,
\MailSo\Mime\Enumerations\MimeType::MULTIPART_MIXED.'; '. Enumerations\MimeType::MULTIPART_MIXED.'; '.
ParameterCollection::NewInstance()->Add( ParameterCollection::NewInstance()->Add(
Parameter::NewInstance( Parameter::NewInstance(
\MailSo\Mime\Enumerations\Parameter::BOUNDARY, Enumerations\Parameter::BOUNDARY,
$this->generateNewBoundary()) $this->generateNewBoundary())
)->ToString() )->ToString()
); );
@ -664,40 +664,40 @@ class Message
return $oResultPart; return $oResultPart;
} }
private function setDefaultHeaders(\MailSo\Mime\Part $oIncPart, bool $bWithoutBcc = false) : \MailSo\Mime\Part private function setDefaultHeaders(Part $oIncPart, bool $bWithoutBcc = false) : Part
{ {
if (!isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::DATE])) if (!isset($this->aHeadersValue[Enumerations\Header::DATE]))
{ {
$oIncPart->Headers->SetByName(\MailSo\Mime\Enumerations\Header::DATE, \gmdate('r'), true); $oIncPart->Headers->SetByName(Enumerations\Header::DATE, \gmdate('r'), true);
} }
if (!isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::MESSAGE_ID])) if (!isset($this->aHeadersValue[Enumerations\Header::MESSAGE_ID]))
{ {
$oIncPart->Headers->SetByName(\MailSo\Mime\Enumerations\Header::MESSAGE_ID, $this->generateNewMessageId(), true); $oIncPart->Headers->SetByName(Enumerations\Header::MESSAGE_ID, $this->generateNewMessageId(), true);
} }
if (!isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::X_MAILER]) && $this->bAddDefaultXMailer) if (!isset($this->aHeadersValue[Enumerations\Header::X_MAILER]) && $this->bAddDefaultXMailer)
{ {
$oIncPart->Headers->SetByName(\MailSo\Mime\Enumerations\Header::X_MAILER, 'MailSo/2.0.1-djmaze', true); $oIncPart->Headers->SetByName(Enumerations\Header::X_MAILER, 'MailSo/2.0.1-djmaze', true);
} }
if (!isset($this->aHeadersValue[\MailSo\Mime\Enumerations\Header::MIME_VERSION])) if (!isset($this->aHeadersValue[Enumerations\Header::MIME_VERSION]))
{ {
$oIncPart->Headers->SetByName(\MailSo\Mime\Enumerations\Header::MIME_VERSION, '1.0', true); $oIncPart->Headers->SetByName(Enumerations\Header::MIME_VERSION, '1.0', true);
} }
foreach ($this->aHeadersValue as $sName => $mValue) foreach ($this->aHeadersValue as $sName => $mValue)
{ {
if (\is_object($mValue)) if (\is_object($mValue))
{ {
if ($mValue instanceof \MailSo\Mime\EmailCollection || $mValue instanceof \MailSo\Mime\Email || if ($mValue instanceof EmailCollection || $mValue instanceof Email ||
$mValue instanceof \MailSo\Mime\ParameterCollection) $mValue instanceof ParameterCollection)
{ {
$mValue = $mValue->ToString(); $mValue = $mValue->ToString();
} }
} }
if (!($bWithoutBcc && \strtolower(\MailSo\Mime\Enumerations\Header::BCC) === \strtolower($sName))) if (!($bWithoutBcc && \strtolower(Enumerations\Header::BCC) === \strtolower($sName)))
{ {
$oIncPart->Headers->SetByName($sName, (string) $mValue); $oIncPart->Headers->SetByName($sName, (string) $mValue);
} }
@ -706,7 +706,7 @@ class Message
return $oIncPart; return $oIncPart;
} }
public function ToPart(bool $bWithoutBcc = false) : \MailSo\Mime\Part public function ToPart(bool $bWithoutBcc = false) : Part
{ {
$oPart = $this->createNewMessageSimpleOrAlternativeBody(); $oPart = $this->createNewMessageSimpleOrAlternativeBody();
$oPart = $this->createNewMessageRelatedBody($oPart); $oPart = $this->createNewMessageRelatedBody($oPart);

View file

@ -38,7 +38,6 @@ class PartCollection extends \MailSo\Base\Collection
*/ */
public function ToStream(string $sBoundary) public function ToStream(string $sBoundary)
{ {
$rResult = null;
if (0 < \strlen($sBoundary)) if (0 < \strlen($sBoundary))
{ {
$aResult = array(); $aResult = array();
@ -57,6 +56,6 @@ class PartCollection extends \MailSo\Base\Collection
return \MailSo\Base\StreamWrappers\SubStreams::CreateStream($aResult); return \MailSo\Base\StreamWrappers\SubStreams::CreateStream($aResult);
} }
return $rResult; return null;
} }
} }

View file

@ -411,21 +411,19 @@ abstract class NetClient
} }
/** /**
* @param mixed $mReadLen = null
*
* @throws \MailSo\Net\Exceptions\SocketConnectionDoesNotAvailableException * @throws \MailSo\Net\Exceptions\SocketConnectionDoesNotAvailableException
* @throws \MailSo\Net\Exceptions\SocketReadException * @throws \MailSo\Net\Exceptions\SocketReadException
*/ */
protected function getNextBuffer($mReadLen = null, bool $bForceLogin = false) : void protected function getNextBuffer(?int $iReadLen = null, bool $bForceLogin = false) : void
{ {
if (null === $mReadLen) if (null === $iReadLen)
{ {
$this->sResponseBuffer = \fgets($this->rConnect); $this->sResponseBuffer = \fgets($this->rConnect);
} }
else else
{ {
$this->sResponseBuffer = ''; $this->sResponseBuffer = '';
$iRead = $mReadLen; $iRead = $iReadLen;
while (0 < $iRead) while (0 < $iRead)
{ {
$sAddRead = \fread($this->rConnect, $iRead); $sAddRead = \fread($this->rConnect, $iRead);
@ -465,7 +463,7 @@ abstract class NetClient
else else
{ {
$iReadedLen = \strlen($this->sResponseBuffer); $iReadedLen = \strlen($this->sResponseBuffer);
if (null === $mReadLen || $bForceLogin) if (null === $iReadLen || $bForceLogin)
{ {
$iLimit = 5000; // 5KB $iLimit = 5000; // 5KB
if ($iLimit < $iReadedLen) if ($iLimit < $iReadedLen)
@ -481,7 +479,7 @@ abstract class NetClient
} }
else else
{ {
$this->writeLog('Received '.$iReadedLen.'/'.$mReadLen.' bytes.', $this->writeLog('Received '.$iReadedLen.'/'.$iReadLen.' bytes.',
\MailSo\Log\Enumerations\Type::INFO); \MailSo\Log\Enumerations\Type::INFO);
} }
@ -507,10 +505,7 @@ abstract class NetClient
$this->writeLog($sDesc, $iDescType, true); $this->writeLog($sDesc, $iDescType, true);
} }
/** protected function writeLogException(\Throwable $oException,
* @param \Exception $oException
*/
protected function writeLogException($oException,
int $iDescType = \MailSo\Log\Enumerations\Type::NOTICE, bool $bThrowException = false) : void int $iDescType = \MailSo\Log\Enumerations\Type::NOTICE, bool $bThrowException = false) : void
{ {
if ($this->oLogger) if ($this->oLogger)

View file

@ -27,10 +27,7 @@ class ResponseException extends \MailSo\Sieve\Exceptions\Exception
{ {
parent::__construct($sMessage, $iCode, $oPrevious); parent::__construct($sMessage, $iCode, $oPrevious);
if (is_array($aResponses)) $this->aResponses = $aResponses;
{
$this->aResponses = $aResponses;
}
} }
public function GetResponses() : array public function GetResponses() : array
@ -40,6 +37,7 @@ class ResponseException extends \MailSo\Sieve\Exceptions\Exception
public function GetLastResponse() : ?\MailSo\Sieve\Response public function GetLastResponse() : ?\MailSo\Sieve\Response
{ {
return 0 < count($this->aResponses) ? $this->aResponses[count($this->aResponses) - 1] : null; $iCnt = count($this->aResponses);
return $iCnt ? $this->aResponses[$iCnt - 1] : null;
} }
} }

View file

@ -87,9 +87,9 @@ class ManageSieveClient extends \MailSo\Net\NetClient
parent::Connect($sServerName, $iPort, $iSecurityType, $bVerifySsl, $bAllowSelfSigned); parent::Connect($sServerName, $iPort, $iSecurityType, $bVerifySsl, $bAllowSelfSigned);
$mResponse = $this->parseResponse(); $aResponse = $this->parseResponse();
$this->validateResponse($mResponse); $this->validateResponse($aResponse);
$this->parseStartupResponse($mResponse); $this->parseStartupResponse($aResponse);
if (\MailSo\Net\Enumerations\ConnectionSecurityType::UseStartTLS( if (\MailSo\Net\Enumerations\ConnectionSecurityType::UseStartTLS(
$this->IsSupported('STARTTLS'), $this->iSecurityType)) $this->IsSupported('STARTTLS'), $this->iSecurityType))
@ -97,9 +97,9 @@ class ManageSieveClient extends \MailSo\Net\NetClient
$this->sendRequestWithCheck('STARTTLS'); $this->sendRequestWithCheck('STARTTLS');
$this->EnableCrypto(); $this->EnableCrypto();
$mResponse = $this->parseResponse(); $aResponse = $this->parseResponse();
$this->validateResponse($mResponse); $this->validateResponse($aResponse);
$this->parseStartupResponse($mResponse); $this->parseStartupResponse($aResponse);
} }
else if (\MailSo\Net\Enumerations\ConnectionSecurityType::STARTTLS === $this->iSecurityType) else if (\MailSo\Net\Enumerations\ConnectionSecurityType::STARTTLS === $this->iSecurityType)
{ {
@ -142,9 +142,9 @@ class ManageSieveClient extends \MailSo\Net\NetClient
$this->sendRequest($sAuth); $this->sendRequest($sAuth);
} }
$mResponse = $this->parseResponse(); $aResponse = $this->parseResponse();
$this->validateResponse($mResponse); $this->validateResponse($aResponse);
$this->parseStartupResponse($mResponse); $this->parseStartupResponse($aResponse);
$bAuth = true; $bAuth = true;
} }
else if ($this->IsAuthSupported('LOGIN')) else if ($this->IsAuthSupported('LOGIN'))
@ -158,9 +158,9 @@ class ManageSieveClient extends \MailSo\Net\NetClient
$this->sendRequest('{'.\strlen($sPassword).'+}'); $this->sendRequest('{'.\strlen($sPassword).'+}');
$this->sendRequest($sPassword); $this->sendRequest($sPassword);
$mResponse = $this->parseResponse(); $aResponse = $this->parseResponse();
$this->validateResponse($mResponse); $this->validateResponse($aResponse);
$this->parseStartupResponse($mResponse); $this->parseStartupResponse($aResponse);
$bAuth = true; $bAuth = true;
} }
} }
@ -213,22 +213,19 @@ class ManageSieveClient extends \MailSo\Net\NetClient
public function ListScripts() : array public function ListScripts() : array
{ {
$this->sendRequest('LISTSCRIPTS'); $this->sendRequest('LISTSCRIPTS');
$mResponse = $this->parseResponse(); $aResponse = $this->parseResponse();
$this->validateResponse($mResponse); $this->validateResponse($aResponse);
$aResult = array(); $aResult = array();
if (\is_array($mResponse)) foreach ($aResponse as $sLine)
{ {
foreach ($mResponse as $sLine) $aTokens = $this->parseLine($sLine);
if (false === $aTokens)
{ {
$aTokens = $this->parseLine($sLine); continue;
if (false === $aTokens)
{
continue;
}
$aResult[$aTokens[0]] = 'ACTIVE' === substr($sLine, -6);
} }
$aResult[$aTokens[0]] = 'ACTIVE' === substr($sLine, -6);
} }
return $aResult; return $aResult;
@ -241,9 +238,9 @@ class ManageSieveClient extends \MailSo\Net\NetClient
public function Capability() : array public function Capability() : array
{ {
$this->sendRequest('CAPABILITY'); $this->sendRequest('CAPABILITY');
$mResponse = $this->parseResponse(); $aResponse = $this->parseResponse();
$this->validateResponse($mResponse); $this->validateResponse($aResponse);
$this->parseStartupResponse($mResponse); $this->parseStartupResponse($aResponse);
return $this->aCapa; return $this->aCapa;
} }
@ -266,23 +263,23 @@ class ManageSieveClient extends \MailSo\Net\NetClient
public function GetScript(string $sScriptName) : string public function GetScript(string $sScriptName) : string
{ {
$this->sendRequest('GETSCRIPT "'.$sScriptName.'"'); $this->sendRequest('GETSCRIPT "'.$sScriptName.'"');
$mResponse = $this->parseResponse(); $aResponse = $this->parseResponse();
$this->validateResponse($mResponse); $this->validateResponse($aResponse);
$sScript = ''; $sScript = '';
if (\is_array($mResponse) && 0 < \count($mResponse)) if (0 < \count($aResponse))
{ {
if ('{' === $mResponse[0][0]) if ('{' === $aResponse[0][0])
{ {
\array_shift($mResponse); \array_shift($aResponse);
} }
if (\in_array(\substr($mResponse[\count($mResponse) - 1], 0, 2), array('OK', 'NO'))) if (\in_array(\substr($aResponse[\count($aResponse) - 1], 0, 2), array('OK', 'NO')))
{ {
\array_pop($mResponse); \array_pop($aResponse);
} }
$sScript = \implode("\n", $mResponse); $sScript = \implode("\n", $aResponse);
} }
return $sScript; return $sScript;
@ -341,14 +338,11 @@ class ManageSieveClient extends \MailSo\Net\NetClient
public function GetActiveScriptName() : string public function GetActiveScriptName() : string
{ {
$aList = $this->ListScripts(); $aList = $this->ListScripts();
if (\is_array($aList) && 0 < \count($aList)) foreach ($aList as $sName => $bIsActive)
{ {
foreach ($aList as $sName => $bIsActive) if ($bIsActive)
{ {
if ($bIsActive) return $sName;
{
return $sName;
}
} }
} }
@ -398,9 +392,9 @@ class ManageSieveClient extends \MailSo\Net\NetClient
* @throws \MailSo\Base\Exceptions\InvalidArgumentException * @throws \MailSo\Base\Exceptions\InvalidArgumentException
* @throws \MailSo\Net\Exceptions\Exception * @throws \MailSo\Net\Exceptions\Exception
*/ */
private function parseStartupResponse($mResponse) : void private function parseStartupResponse(array $aResponse) : void
{ {
foreach ($mResponse as $sLine) foreach ($aResponse as $sLine)
{ {
$aTokens = $this->parseLine($sLine); $aTokens = $this->parseLine($sLine);
@ -518,7 +512,7 @@ class ManageSieveClient extends \MailSo\Net\NetClient
*/ */
private function validateResponse(array $aResponse) private function validateResponse(array $aResponse)
{ {
if (!\is_array($aResponse) || 0 === \count($aResponse) || if (!$aResponse ||
'OK' !== \substr($aResponse[\count($aResponse) - 1], 0, 2)) 'OK' !== \substr($aResponse[\count($aResponse) - 1], 0, 2))
{ {
$this->writeLogException( $this->writeLogException(

View file

@ -27,10 +27,7 @@ class ResponseException extends \MailSo\Smtp\Exceptions\Exception
{ {
parent::__construct($sMessage, $iCode, $oPrevious); parent::__construct($sMessage, $iCode, $oPrevious);
if (is_array($aResponses)) $this->aResponses = $aResponses;
{
$this->aResponses = $aResponses;
}
} }
public function GetResponses() : array public function GetResponses() : array
@ -40,6 +37,7 @@ class ResponseException extends \MailSo\Smtp\Exceptions\Exception
public function GetLastResponse() : ?\MailSo\Smtp\Response public function GetLastResponse() : ?\MailSo\Smtp\Response
{ {
return 0 < count($this->aResponses) ? $this->aResponses[count($this->aResponses) - 1] : null; $iCnt = count($this->aResponses);
return $iCnt ? $this->aResponses[$iCnt - 1] : null;
} }
} }

View file

@ -289,7 +289,6 @@ class SmtpClient extends \MailSo\Net\NetClient
$sCmd = 'FROM:<'.$sFrom.'>'; $sCmd = 'FROM:<'.$sFrom.'>';
$sSizeIfSupported = (string) $sSizeIfSupported;
if (0 < \strlen($sSizeIfSupported) && \is_numeric($sSizeIfSupported) && $this->IsSupported('SIZE')) if (0 < \strlen($sSizeIfSupported) && \is_numeric($sSizeIfSupported) && $this->IsSupported('SIZE'))
{ {
$sCmd .= ' SIZE='.$sSizeIfSupported; $sCmd .= ' SIZE='.$sSizeIfSupported;
@ -577,7 +576,7 @@ class SmtpClient extends \MailSo\Net\NetClient
* @throws \MailSo\Net\Exceptions\Exception * @throws \MailSo\Net\Exceptions\Exception
* @throws \MailSo\Smtp\Exceptions\Exception * @throws \MailSo\Smtp\Exceptions\Exception
*/ */
private function ehlo($sHost) : void private function ehlo(string $sHost) : void
{ {
$this->sendRequestWithCheck('EHLO', 250, $sHost); $this->sendRequestWithCheck('EHLO', 250, $sHost);
@ -588,7 +587,7 @@ class SmtpClient extends \MailSo\Net\NetClient
{ {
$sLine = \trim($aMatch[1]); $sLine = \trim($aMatch[1]);
$aLine = \preg_split('/[ =]/', $sLine, 2); $aLine = \preg_split('/[ =]/', $sLine, 2);
if (\is_array($aLine) && 0 < \count($aLine) && !empty($aLine[0])) if (!empty($aLine[0]))
{ {
$sCapa = \strtoupper($aLine[0]); $sCapa = \strtoupper($aLine[0]);
if (('AUTH' === $sCapa || 'SIZE' === $sCapa) && !empty($aLine[1])) if (('AUTH' === $sCapa || 'SIZE' === $sCapa) && !empty($aLine[1]))
@ -646,7 +645,7 @@ class SmtpClient extends \MailSo\Net\NetClient
$this->getNextBuffer(); $this->getNextBuffer();
$aParts = \preg_split('/([\s\-]+)/', $this->sResponseBuffer, 2, PREG_SPLIT_DELIM_CAPTURE); $aParts = \preg_split('/([\s\-]+)/', $this->sResponseBuffer, 2, PREG_SPLIT_DELIM_CAPTURE);
if (\is_array($aParts) && 3 === \count($aParts) && \is_numeric($aParts[0])) if (3 === \count($aParts) && \is_numeric($aParts[0]))
{ {
if ('-' !== \substr($aParts[1], 0, 1) && !\in_array((int) $aParts[0], $mExpectCode)) if ('-' !== \substr($aParts[1], 0, 1) && !\in_array((int) $aParts[0], $mExpectCode))
{ {

View file

@ -195,7 +195,7 @@ class Actions
public function GetShortLifeSpecAuthToken(int $iLife = 60) : string public function GetShortLifeSpecAuthToken(int $iLife = 60) : string
{ {
$aAccountHash = \RainLoop\Utils::DecodeKeyValues($this->getLocalAuthToken()); $aAccountHash = \RainLoop\Utils::DecodeKeyValues($this->getLocalAuthToken());
if (!empty($aAccountHash[0]) && 'token' === $aAccountHash[0] && \is_array($aAccountHash)) if (!empty($aAccountHash[0]) && 'token' === $aAccountHash[0])
{ {
$aAccountHash[10] = \time() + $iLife; $aAccountHash[10] = \time() + $iLife;
return \RainLoop\Utils::EncodeKeyValues($aAccountHash); return \RainLoop\Utils::EncodeKeyValues($aAccountHash);
@ -487,20 +487,14 @@ class Actions
$aClear['/\{labs:([^}]*)\}/'] = 'labs'; $aClear['/\{labs:([^}]*)\}/'] = 'labs';
} }
if (\is_array($aAdditionalParams) && 0 < \count($aAdditionalParams)) foreach ($aAdditionalParams as $sKey => $sValue)
{ {
foreach ($aAdditionalParams as $sKey => $sValue) $sLine = \str_replace($sKey, $sValue, $sLine);
{
$sLine = \str_replace($sKey, $sValue, $sLine);
}
} }
if (0 < \count($aClear)) foreach ($aClear as $sKey => $sValue)
{ {
foreach ($aClear as $sKey => $sValue) $sLine = \preg_replace($sKey, $sValue, $sLine);
{
$sLine = \preg_replace($sKey, $sValue, $sLine);
}
} }
return $sLine; return $sLine;
@ -1135,7 +1129,7 @@ class Actions
if (!empty($sSignMeToken)) if (!empty($sSignMeToken))
{ {
$aTokenData = \RainLoop\Utils::DecodeKeyValuesQ($sSignMeToken); $aTokenData = \RainLoop\Utils::DecodeKeyValuesQ($sSignMeToken);
if (\is_array($aTokenData) && !empty($aTokenData['e']) && !empty($aTokenData['t'])) if (!empty($aTokenData['e']) && !empty($aTokenData['t']))
{ {
$sTokenSettings = $this->StorageProvider()->Get($aTokenData['e'], $sTokenSettings = $this->StorageProvider()->Get($aTokenData['e'],
\RainLoop\Providers\Storage\Enumerations\StorageType::CONFIG, \RainLoop\Providers\Storage\Enumerations\StorageType::CONFIG,
@ -1145,8 +1139,7 @@ class Actions
if (!empty($sTokenSettings)) if (!empty($sTokenSettings))
{ {
$aSignMeData = \RainLoop\Utils::DecodeKeyValuesQ($sTokenSettings); $aSignMeData = \RainLoop\Utils::DecodeKeyValuesQ($sTokenSettings);
if (\is_array($aSignMeData) && if (!empty($aSignMeData['AuthToken']) &&
!empty($aSignMeData['AuthToken']) &&
!empty($aSignMeData['SignMetToken']) && !empty($aSignMeData['SignMetToken']) &&
$aSignMeData['SignMetToken'] === $aTokenData['t']) $aSignMeData['SignMetToken'] === $aTokenData['t'])
{ {
@ -1347,7 +1340,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
\RainLoop\Utils::ClearCookie(self::AUTH_MAILTO_TOKEN_KEY); \RainLoop\Utils::ClearCookie(self::AUTH_MAILTO_TOKEN_KEY);
$mMailToData = \RainLoop\Utils::DecodeKeyValuesQ($sToken); $mMailToData = \RainLoop\Utils::DecodeKeyValuesQ($sToken);
if (\is_array($mMailToData) && !empty($mMailToData['MailTo']) && if (!empty($mMailToData['MailTo']) &&
'MailTo' === $mMailToData['MailTo'] && !empty($mMailToData['To'])) 'MailTo' === $mMailToData['MailTo'] && !empty($mMailToData['To']))
{ {
$aResult['MailToEmail'] = $mMailToData['To']; $aResult['MailToEmail'] = $mMailToData['To'];
@ -1699,7 +1692,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$this->SetAuthToken($oAccount); $this->SetAuthToken($oAccount);
$aAccounts = $this->GetAccounts($oAccount); $aAccounts = $this->GetAccounts($oAccount);
if (\is_array($aAccounts) && isset($aAccounts[$oAccount->Email()])) if (isset($aAccounts[$oAccount->Email()]))
{ {
$aAccounts[$oAccount->Email()] = $oAccount->GetAuthToken(); $aAccounts[$oAccount->Email()] = $oAccount->GetAuthToken();
$this->SetAccounts($oAccount, $aAccounts); $this->SetAccounts($oAccount, $aAccounts);
@ -2139,14 +2132,11 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
public function GetTemplateByID(\RainLoop\Model\Account $oAccount, string $sID) : ?\RainLoop\Model\Identity public function GetTemplateByID(\RainLoop\Model\Account $oAccount, string $sID) : ?\RainLoop\Model\Identity
{ {
$aTemplates = $this->GetTemplates($oAccount); $aTemplates = $this->GetTemplates($oAccount);
if (\is_array($aTemplates)) foreach ($aTemplates as $oIdentity)
{ {
foreach ($aTemplates as $oIdentity) if ($oIdentity && $sID === $oIdentity->Id())
{ {
if ($oIdentity && $sID === $oIdentity->Id()) return $oIdentity;
{
return $oIdentity;
}
} }
} }
@ -2239,18 +2229,15 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
{ {
$aIdentities = $this->GetIdentities($oAccount); $aIdentities = $this->GetIdentities($oAccount);
if (\is_array($aIdentities)) foreach ($aIdentities as $oIdentity)
{ {
foreach ($aIdentities as $oIdentity) if ($oIdentity && $sID === $oIdentity->Id())
{ {
if ($oIdentity && $sID === $oIdentity->Id()) return $oIdentity;
{
return $oIdentity;
}
} }
} }
return $bFirstOnEmpty && \is_array($aIdentities) && isset($aIdentities[0]) ? $aIdentities[0] : null; return $bFirstOnEmpty && isset($aIdentities[0]) ? $aIdentities[0] : null;
} }
public function GetAccountIdentity(\RainLoop\Model\Account $oAccount) : ?\RainLoop\Model\Identity public function GetAccountIdentity(\RainLoop\Model\Account $oAccount) : ?\RainLoop\Model\Identity
@ -2261,7 +2248,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
public function SetAccounts(\RainLoop\Model\Account $oAccount, array $aAccounts = array()) : void public function SetAccounts(\RainLoop\Model\Account $oAccount, array $aAccounts = array()) : void
{ {
$sParentEmail = $oAccount->ParentEmailHelper(); $sParentEmail = $oAccount->ParentEmailHelper();
if (!\is_array($aAccounts) || 0 >= \count($aAccounts) || if (!$aAccounts ||
(1 === \count($aAccounts) && !empty($aAccounts[$sParentEmail]))) (1 === \count($aAccounts) && !empty($aAccounts[$sParentEmail])))
{ {
$this->StorageProvider()->Clear($oAccount, $this->StorageProvider()->Clear($oAccount,
@ -2363,7 +2350,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$aFilters = array(); $aFilters = array();
foreach ($aIncFilters as $aFilter) foreach ($aIncFilters as $aFilter)
{ {
if ($aFilter) if (is_array($aFilter))
{ {
$oFilter = new \RainLoop\Providers\Filters\Classes\Filter(); $oFilter = new \RainLoop\Providers\Filters\Classes\Filter();
if ($oFilter->FromJSON($aFilter)) if ($oFilter->FromJSON($aFilter))
@ -2396,10 +2383,6 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$sParentEmail = $oAccount->ParentEmailHelper(); $sParentEmail = $oAccount->ParentEmailHelper();
$aAccounts = $this->GetAccounts($oAccount); $aAccounts = $this->GetAccounts($oAccount);
if (!\is_array($aAccounts))
{
$aAccounts = array();
}
$sEmail = \trim($this->GetActionParam('Email', '')); $sEmail = \trim($this->GetActionParam('Email', ''));
$sPassword = $this->GetActionParam('Password', ''); $sPassword = $this->GetActionParam('Password', '');
@ -2446,7 +2429,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$aAccounts = $this->GetAccounts($oAccount); $aAccounts = $this->GetAccounts($oAccount);
if (0 < \strlen($sEmailToDelete) && $sEmailToDelete !== $sParentEmail && \is_array($aAccounts) && isset($aAccounts[$sEmailToDelete])) if (0 < \strlen($sEmailToDelete) && $sEmailToDelete !== $sParentEmail && isset($aAccounts[$sEmailToDelete]))
{ {
unset($aAccounts[$sEmailToDelete]); unset($aAccounts[$sEmailToDelete]);
@ -2492,7 +2475,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
foreach ($aHashes as $sZipHash) foreach ($aHashes as $sZipHash)
{ {
$aResult = $this->getMimeFileByHash($oAccount, $sZipHash); $aResult = $this->getMimeFileByHash($oAccount, $sZipHash);
if (\is_array($aResult) && !empty($aResult['FileHash'])) if (!empty($aResult['FileHash']))
{ {
$aData[] = $aResult; $aData[] = $aResult;
} }
@ -2874,25 +2857,22 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
if ($this->GetCapa(false, false, \RainLoop\Enumerations\Capa::ADDITIONAL_ACCOUNTS, $oAccount)) if ($this->GetCapa(false, false, \RainLoop\Enumerations\Capa::ADDITIONAL_ACCOUNTS, $oAccount))
{ {
$iLimit = 7; $iLimit = 7;
$mAccounts = $this->GetAccounts($oAccount); $aAccounts = $this->GetAccounts($oAccount);
if (\is_array($mAccounts) && 0 < \count($mAccounts)) if ($aAccounts)
{ {
if ($iLimit > \count($mAccounts)) if ($iLimit > \count($aAccounts))
{ {
$mAccounts = \array_slice($mAccounts, 0, $iLimit); $aAccounts = \array_slice($aAccounts, 0, $iLimit);
} }
else else
{ {
$bComplete = false; $bComplete = false;
} }
if (0 < \count($mAccounts)) foreach ($aAccounts as $sEmail => $sHash)
{ {
foreach ($mAccounts as $sEmail => $sHash) $aCounts[] = array(\MailSo\Base\Utils::IdnToUtf8($sEmail),
{ $oAccount->Email() === $sEmail ? 0 : $this->getAccountUnreadCountFromHash($sHash));
$aCounts[] = array(\MailSo\Base\Utils::IdnToUtf8($sEmail),
$oAccount->Email() === $sEmail ? 0 : $this->getAccountUnreadCountFromHash($sHash));
}
} }
} }
} }
@ -3702,53 +3682,46 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$aResult = $this->getRepositoryDataByUrl($this->rainLoopRepo(), $bReal); $aResult = $this->getRepositoryDataByUrl($this->rainLoopRepo(), $bReal);
$aSub = array(); $aSub = array();
if (\is_array($aResult)) foreach ($aResult as $aItem)
{ {
foreach ($aResult as $aItem) if ('plugin' === $aItem['type'])
{ {
if ('plugin' === $aItem['type']) $aSub[] = $aItem;
{
$aSub[] = $aItem;
}
} }
$aResult = $aSub;
unset($aSub);
} }
$aResult = $aSub;
unset($aSub);
$aInstalled = $this->Plugins()->InstalledPlugins(); $aInstalled = $this->Plugins()->InstalledPlugins();
if (\is_array($aInstalled)) foreach ($aResult as &$aItem)
{ {
foreach ($aResult as &$aItem) if ('plugin' === $aItem['type'])
{ {
if ('plugin' === $aItem['type']) foreach ($aInstalled as &$aSubItem)
{ {
foreach ($aInstalled as &$aSubItem) if (\is_array($aSubItem) && isset($aSubItem[0]) && $aSubItem[0] === $aItem['id'])
{ {
if (\is_array($aSubItem) && isset($aSubItem[0]) && $aSubItem[0] === $aItem['id']) $aSubItem[2] = true;
{ $aItem['installed'] = $aSubItem[1];
$aSubItem[2] = true;
$aItem['installed'] = $aSubItem[1];
}
} }
} }
} }
}
foreach ($aInstalled as $aSubItemSec) foreach ($aInstalled as $aSubItemSec)
{
if ($aSubItemSec && !isset($aSubItemSec[2]))
{ {
if ($aSubItemSec && !isset($aSubItemSec[2])) \array_push($aResult, array(
{ 'type' => 'plugin',
\array_push($aResult, array( 'id' => $aSubItemSec[0],
'type' => 'plugin', 'name' => $aSubItemSec[0],
'id' => $aSubItemSec[0], 'installed' => $aSubItemSec[1],
'name' => $aSubItemSec[0], 'version' => '',
'installed' => $aSubItemSec[1], 'file' => '',
'version' => '', 'release' => '',
'file' => '', 'desc' => ''
'release' => '', ));
'desc' => ''
));
}
} }
} }
@ -4072,7 +4045,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$aMap = $oPlugin->ConfigMap(); $aMap = $oPlugin->ConfigMap();
$oConfig = $oPlugin->Config(); $oConfig = $oPlugin->Config();
if (is_array($aMap) && 0 < count($aMap)) if (is_array($aMap))
{ {
foreach ($aMap as $oItem) foreach ($aMap as $oItem)
{ {
@ -4109,7 +4082,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
{ {
$oConfig = $oPlugin->Config(); $oConfig = $oPlugin->Config();
$aMap = $oPlugin->ConfigMap(); $aMap = $oPlugin->ConfigMap();
if (is_array($aMap) && 0 < count($aMap)) if (is_array($aMap))
{ {
foreach ($aMap as $oItem) foreach ($aMap as $oItem)
{ {
@ -4767,7 +4740,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$sFolder, $sPrevUidNext, $aFlagsFilteredUids $sFolder, $sPrevUidNext, $aFlagsFilteredUids
); );
if (\is_array($aInboxInformation) && isset($aInboxInformation['Flags']) && \is_array($aInboxInformation['Flags'])) if (isset($aInboxInformation['Flags']) && \is_array($aInboxInformation['Flags']))
{ {
foreach ($aInboxInformation['Flags'] as $iUid => $aFlags) foreach ($aInboxInformation['Flags'] as $iUid => $aFlags)
{ {
@ -4788,10 +4761,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::MailServerError, $oException); throw new \RainLoop\Exceptions\ClientException(\RainLoop\Notifications::MailServerError, $oException);
} }
if (\is_array($aInboxInformation)) $aInboxInformation['Version'] = APP_VERSION;
{
$aInboxInformation['Version'] = APP_VERSION;
}
return $this->DefaultResponse(__FUNCTION__, $aInboxInformation); return $this->DefaultResponse(__FUNCTION__, $aInboxInformation);
} }
@ -4819,7 +4789,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
try try
{ {
$aInboxInformation = $this->MailClient()->FolderInformation($sFolder, '', array()); $aInboxInformation = $this->MailClient()->FolderInformation($sFolder, '', array());
if (\is_array($aInboxInformation) && isset($aInboxInformation['Folder'])) if (isset($aInboxInformation['Folder']))
{ {
$aResult['List'][] = $aInboxInformation; $aResult['List'][] = $aInboxInformation;
} }
@ -4854,7 +4824,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$sRawKey = $this->GetActionParam('RawKey', ''); $sRawKey = $this->GetActionParam('RawKey', '');
$aValues = $this->getDecodedClientRawKeyValue($sRawKey, 9); $aValues = $this->getDecodedClientRawKeyValue($sRawKey, 9);
if (\is_array($aValues) && 7 < \count($aValues)) if ($aValues && 7 < \count($aValues))
{ {
$sFolder =(string) $aValues[0]; $sFolder =(string) $aValues[0];
$iOffset = (int) $aValues[1]; $iOffset = (int) $aValues[1];
@ -5675,14 +5645,14 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
if (!empty($sData)) if (!empty($sData))
{ {
$mData = \RainLoop\Utils::DecodeKeyValues($sData); $aData = \RainLoop\Utils::DecodeKeyValues($sData);
if (\is_array($mData)) if ($aData)
{ {
$mResult = array( $mResult = array(
'Enable' => isset($mData['Enable']) ? !!$mData['Enable'] : false, 'Enable' => isset($aData['Enable']) ? !!$aData['Enable'] : false,
'Url' => isset($mData['Url']) ? \trim($mData['Url']) : '', 'Url' => isset($aData['Url']) ? \trim($aData['Url']) : '',
'User' => isset($mData['User']) ? \trim($mData['User']) : '', 'User' => isset($aData['User']) ? \trim($aData['User']) : '',
'Password' => isset($mData['Password']) ? $mData['Password'] : '' 'Password' => isset($aData['Password']) ? $aData['Password'] : ''
); );
} }
} }
@ -5731,7 +5701,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
if ($oAddressBookProvider && $oAddressBookProvider->IsActive()) if ($oAddressBookProvider && $oAddressBookProvider->IsActive())
{ {
$mData = $this->getContactsSyncData($oAccount); $mData = $this->getContactsSyncData($oAccount);
if (\is_array($mData) && isset($mData['Enable'], $mData['User'], $mData['Password'], $mData['Url']) && $mData['Enable']) if (isset($mData['Enable'], $mData['User'], $mData['Password'], $mData['Url']) && $mData['Enable'])
{ {
$bResult = $oAddressBookProvider->Sync( $bResult = $oAddressBookProvider->Sync(
$oAccount->ParentEmailHelper(), $oAccount->ParentEmailHelper(),
@ -5777,7 +5747,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
} }
} }
if (\is_array($mData) && !empty($aResult['User']) && if (!empty($aResult['User']) &&
!empty($mData['User']) && !empty($mData['Secret']) && !empty($mData['User']) && !empty($mData['Secret']) &&
!empty($mData['BackupCodes']) && $sEmail === $mData['User']) !empty($mData['BackupCodes']) && $sEmail === $mData['User'])
{ {
@ -5905,10 +5875,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
} }
$aResult = $this->getTwoFactorInfo($oAccount); $aResult = $this->getTwoFactorInfo($oAccount);
if (\is_array($aResult)) unset($aResult['BackupCodes']);
{
unset($aResult['BackupCodes']);
}
return $this->DefaultResponse(__FUNCTION__, $aResult); return $this->DefaultResponse(__FUNCTION__, $aResult);
} }
@ -6241,7 +6208,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$iUid = 0; $iUid = 0;
$aValues = $this->getDecodedClientRawKeyValue($sRawKey, 4); $aValues = $this->getDecodedClientRawKeyValue($sRawKey, 4);
if (\is_array($aValues) && 4 === count($aValues)) if ($aValues && 4 === count($aValues))
{ {
$sFolder = (string) $aValues[0]; $sFolder = (string) $aValues[0];
$iUid = (int) $aValues[1]; $iUid = (int) $aValues[1];
@ -6460,8 +6427,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$mResult = array(); $mResult = array();
foreach ($aAttachments as $sAttachment) foreach ($aAttachments as $sAttachment)
{ {
$aValues = \RainLoop\Utils::DecodeKeyValuesQ($sAttachment); if ($aValues = \RainLoop\Utils::DecodeKeyValuesQ($sAttachment))
if (\is_array($aValues))
{ {
$sFolder = isset($aValues['Folder']) ? $aValues['Folder'] : ''; $sFolder = isset($aValues['Folder']) ? $aValues['Folder'] : '';
$iUid = (int) isset($aValues['Uid']) ? $aValues['Uid'] : 0; $iUid = (int) isset($aValues['Uid']) ? $aValues['Uid'] : 0;
@ -6859,7 +6825,7 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
} }
} }
if (\is_array($aData) && 0 < \count($aData)) if (0 < \count($aData))
{ {
$this->Logger()->Write('Import contacts from csv'); $this->Logger()->Write('Import contacts from csv');
$iCount = $oAddressBookProvider->ImportCsvArray($oAccount->ParentEmailHelper(), $aData); $iCount = $oAddressBookProvider->ImportCsvArray($oAccount->ParentEmailHelper(), $aData);
@ -7701,34 +7667,23 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
private function getDecodedRawKeyValue(string $sRawKey) : array private function getDecodedRawKeyValue(string $sRawKey) : array
{ {
$bResult = array(); return empty($sRawKey) ? array() : \RainLoop\Utils::DecodeKeyValuesQ($sRawKey);
if (!empty($sRawKey))
{
$aValues = \RainLoop\Utils::DecodeKeyValuesQ($sRawKey);
if (is_array($aValues))
{
$bResult = $aValues;
}
}
return $bResult;
} }
private function getDecodedClientRawKeyValue(string $sRawKey, ?int $iLenCache = null) : ?array private function getDecodedClientRawKeyValue(string $sRawKey, ?int $iLenCache = null) : ?array
{ {
$mResult = null;
if (!empty($sRawKey)) if (!empty($sRawKey))
{ {
$sRawKey = \MailSo\Base\Utils::UrlSafeBase64Decode($sRawKey); $sRawKey = \MailSo\Base\Utils::UrlSafeBase64Decode($sRawKey);
$aValues = explode("\x0", $sRawKey); $aValues = explode("\x0", $sRawKey);
if (is_array($aValues) && (null === $iLenCache || $iLenCache === count($aValues))) if (null === $iLenCache || $iLenCache === count($aValues))
{ {
$mResult = $aValues; return $aValues;
} }
} }
return $mResult; return null;
} }
public function StaticCache() : string public function StaticCache() : string
@ -7762,49 +7717,46 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
$sResult = ''; $sResult = '';
$aLang = $this->GetLanguages($bAdmin); $aLang = $this->GetLanguages($bAdmin);
if (\is_array($aLang)) $aHelper = array('en' => 'en_us', 'ar' => 'ar_sa', 'cs' => 'cs_cz', 'no' => 'nb_no', 'ua' => 'uk_ua',
'cn' => 'zh_cn', 'zh' => 'zh_cn', 'tw' => 'zh_tw', 'fa' => 'fa_ir');
$sLanguage = isset($aHelper[$sLanguage]) ? $aHelper[$sLanguage] : $sLanguage;
$sDefault = isset($aHelper[$sDefault]) ? $aHelper[$sDefault] : $sDefault;
$sLanguage = \strtolower(\str_replace('-', '_', $sLanguage));
if (2 === strlen($sLanguage))
{ {
$aHelper = array('en' => 'en_us', 'ar' => 'ar_sa', 'cs' => 'cs_cz', 'no' => 'nb_no', 'ua' => 'uk_ua', $sLanguage = $sLanguage.'_'.$sLanguage;
'cn' => 'zh_cn', 'zh' => 'zh_cn', 'tw' => 'zh_tw', 'fa' => 'fa_ir'); }
$sLanguage = isset($aHelper[$sLanguage]) ? $aHelper[$sLanguage] : $sLanguage; $sDefault = \strtolower(\str_replace('-', '_', $sDefault));
$sDefault = isset($aHelper[$sDefault]) ? $aHelper[$sDefault] : $sDefault; if (2 === strlen($sDefault))
{
$sDefault = $sDefault.'_'.$sDefault;
}
$sLanguage = \strtolower(\str_replace('-', '_', $sLanguage)); $sLanguage = \preg_replace_callback('/_([a-zA-Z0-9]{2})$/', function ($aData) {
if (2 === strlen($sLanguage)) return \strtoupper($aData[0]);
{ }, $sLanguage);
$sLanguage = $sLanguage.'_'.$sLanguage;
}
$sDefault = \strtolower(\str_replace('-', '_', $sDefault)); $sDefault = \preg_replace_callback('/_([a-zA-Z0-9]{2})$/', function ($aData) {
if (2 === strlen($sDefault)) return \strtoupper($aData[0]);
{ }, $sDefault);
$sDefault = $sDefault.'_'.$sDefault;
}
$sLanguage = \preg_replace_callback('/_([a-zA-Z0-9]{2})$/', function ($aData) { if (\in_array($sLanguage, $aLang))
return \strtoupper($aData[0]); {
}, $sLanguage); $sResult = $sLanguage;
}
$sDefault = \preg_replace_callback('/_([a-zA-Z0-9]{2})$/', function ($aData) { if (empty($sResult) && !empty($sDefault) && \in_array($sDefault, $aLang))
return \strtoupper($aData[0]); {
}, $sDefault); $sResult = $sDefault;
}
if (\in_array($sLanguage, $aLang)) if (empty($sResult) && !$bAllowEmptyResult)
{ {
$sResult = $sLanguage; $sResult = $this->Config()->Get('webmail', $bAdmin ? 'language_admin' : 'language', 'en_US');
} $sResult = \in_array($sResult, $aLang) ? $sResult : 'en_US';
if (empty($sResult) && !empty($sDefault) && \in_array($sDefault, $aLang))
{
$sResult = $sDefault;
}
if (empty($sResult) && !$bAllowEmptyResult)
{
$sResult = $this->Config()->Get('webmail', $bAdmin ? 'language_admin' : 'language', 'en_US');
$sResult = \in_array($sResult, $aLang) ? $sResult : 'en_US';
}
} }
return $sResult; return $sResult;
@ -7969,12 +7921,9 @@ NewThemeLink IncludeCss LoadingDescriptionEsc TemplatesLink LangLink IncludeBack
'Result' => $this->responseObject($mResult, $sActionName) 'Result' => $this->responseObject($mResult, $sActionName)
); );
if (\is_array($aAdditionalParams)) foreach ($aAdditionalParams as $sKey => $mValue)
{ {
foreach ($aAdditionalParams as $sKey => $mValue) $aResult[$sKey] = $mValue;
{
$aResult[$sKey] = $mValue;
}
} }
return $aResult; return $aResult;

View file

@ -187,7 +187,7 @@ abstract class AbstractConfig
} }
$aData = \RainLoop\Utils::CustomParseIniFile($this->sFile, true); $aData = \RainLoop\Utils::CustomParseIniFile($this->sFile, true);
if (\is_array($aData) && 0 < \count($aData)) if (0 < \count($aData))
{ {
foreach ($aData as $sSectionKey => $aSectionValue) foreach ($aData as $sSectionKey => $aSectionValue)
{ {

View file

@ -275,12 +275,7 @@ class Account
)); ));
} }
/** public function IncConnectAndLoginHelper(\RainLoop\Plugins\Manager $oPlugins, \MailSo\Mail\MailClient $oMailClient, \RainLoop\Config\Application $oConfig, ?callable $refreshTokenCallback = null) : bool
* @param \RainLoop\Plugins\Manager $oPlugins
* @param \MailSo\Mail\MailClient $oMailClient
* @param \RainLoop\Config\Application $oConfig
*/
public function IncConnectAndLoginHelper($oPlugins, $oMailClient, $oConfig, ?callable $refreshTokenCallback = null) : bool
{ {
$bLogin = false; $bLogin = false;
@ -339,12 +334,7 @@ class Account
return $bLogin; return $bLogin;
} }
/** public function OutConnectAndLoginHelper(\RainLoop\Plugins\Manager $oPlugins, \MailSo\Smtp\SmtpClient $oSmtpClient, \RainLoop\Config\Application $oConfig, ?callable $refreshTokenCallback = null, bool &$bUsePhpMail = false) : bool
* @param \RainLoop\Plugins\Manager $oPlugins
* @param \MailSo\Smtp\SmtpClient|null $oSmtpClient
* @param \RainLoop\Config\Application $oConfig
*/
public function OutConnectAndLoginHelper($oPlugins, $oSmtpClient, $oConfig, ?callable $refreshTokenCallback = null, bool &$bUsePhpMail = false) : bool
{ {
$bLogin = false; $bLogin = false;
@ -396,12 +386,7 @@ class Account
return $bLogin; return $bLogin;
} }
/** public function SieveConnectAndLoginHelper(\RainLoop\Plugins\Manager $oPlugins, \MailSo\Sieve\ManageSieveClient $oSieveClient, \RainLoop\Config\Application $oConfig)
* @param \RainLoop\Plugins\Manager $oPlugins
* @param \MailSo\Sieve\ManageSieveClient $oSieveClient
* @param \RainLoop\Config\Application $oConfig
*/
public function SieveConnectAndLoginHelper($oPlugins, $oSieveClient, $oConfig)
{ {
$bLogin = false; $bLogin = false;

View file

@ -145,7 +145,7 @@ class Domain
{ {
$oDomain = null; $oDomain = null;
if (0 < \strlen($sName) && \is_array($aDomain) && 0 < \strlen($aDomain['imap_host']) && 0 < \strlen($aDomain['imap_port'])) if (0 < \strlen($sName) && 0 < \strlen($aDomain['imap_host']) && 0 < \strlen($aDomain['imap_port']))
{ {
$sIncHost = (string) $aDomain['imap_host']; $sIncHost = (string) $aDomain['imap_host'];
$iIncPort = (int) $aDomain['imap_port']; $iIncPort = (int) $aDomain['imap_port'];

View file

@ -124,10 +124,6 @@ abstract class AbstractPlugin
if (null === $this->aConfigMap) if (null === $this->aConfigMap)
{ {
$this->aConfigMap = $this->configMapping(); $this->aConfigMap = $this->configMapping();
if (!is_array($this->aConfigMap))
{
$this->aConfigMap = array();
}
} }
return $this->aConfigMap; return $this->aConfigMap;
@ -295,7 +291,7 @@ abstract class AbstractPlugin
public function saveUserSettings(array $aSettings) : bool public function saveUserSettings(array $aSettings) : bool
{ {
if ($this->oPluginManager && \is_array($aSettings)) if ($this->oPluginManager)
{ {
return $this->oPluginManager->SaveUserPluginSettings($this->Name(), $aSettings); return $this->oPluginManager->SaveUserPluginSettings($this->Name(), $aSettings);
} }

View file

@ -512,7 +512,7 @@ class Manager
public function SaveUserPluginSettings(string $sPluginName, array $aSettings) : bool public function SaveUserPluginSettings(string $sPluginName, array $aSettings) : bool
{ {
$oAccount = $this->oActions->GetAccount(); $oAccount = $this->oActions->GetAccount();
if ($oAccount && \is_array($aSettings)) if ($oAccount)
{ {
$oSettings = $this->oActions->SettingsProvider()->Load($oAccount); $oSettings = $this->oActions->SettingsProvider()->Load($oAccount);
if ($oSettings) if ($oSettings)

View file

@ -173,7 +173,7 @@ class AddressBook extends \RainLoop\Providers\AbstractProvider
public function ImportCsvArray(string $sEmail, array $aCsvData) : int public function ImportCsvArray(string $sEmail, array $aCsvData) : int
{ {
$iCount = 0; $iCount = 0;
if ($this->IsActive() && \is_array($aCsvData) && 0 < \count($aCsvData)) if ($this->IsActive() && 0 < \count($aCsvData))
{ {
$oContact = new \RainLoop\Providers\AddressBook\Classes\Contact(); $oContact = new \RainLoop\Providers\AddressBook\Classes\Contact();
foreach ($aCsvData as $aItem) foreach ($aCsvData as $aItem)

View file

@ -246,34 +246,31 @@ class DefaultDomain implements \RainLoop\Providers\Domain\DomainAdminInterface
// $aList = \glob($this->sDomainPath.'/*.{ini,alias}', GLOB_BRACE); // $aList = \glob($this->sDomainPath.'/*.{ini,alias}', GLOB_BRACE);
$aList = \array_diff(\scandir($this->sDomainPath), array('.', '..')); $aList = \array_diff(\scandir($this->sDomainPath), array('.', '..'));
if (\is_array($aList)) foreach ($aList as $sFile)
{ {
foreach ($aList as $sFile) $sName = $sFile;
if ('.ini' === \substr($sName, -4) || '.alias' === \substr($sName, -6))
{ {
$sName = $sFile; $bAlias = '.alias' === \substr($sName, -6);
if ('.ini' === \substr($sName, -4) || '.alias' === \substr($sName, -6))
$sName = \preg_replace('/\.(ini|alias)$/', '', $sName);
$sName = $this->codeFileName($sName, true);
if ($bAlias)
{ {
$bAlias = '.alias' === \substr($sName, -6); if ($bIncludeAliases)
$sName = \preg_replace('/\.(ini|alias)$/', '', $sName);
$sName = $this->codeFileName($sName, true);
if ($bAlias)
{ {
if ($bIncludeAliases) $aAliases[] = $sName;
{
$aAliases[] = $sName;
}
}
else if (false !== \strpos($sName, '*'))
{
$aWildCards[] = $sName;
}
else
{
$aResult[] = $sName;
} }
} }
else if (false !== \strpos($sName, '*'))
{
$aWildCards[] = $sName;
}
else
{
$aResult[] = $sName;
}
} }
} }

View file

@ -184,35 +184,30 @@ class Filter
public function FromJSON(array $aFilter) : array public function FromJSON(array $aFilter) : array
{ {
if (\is_array($aFilter)) $this->sID = isset($aFilter['ID']) ? $aFilter['ID'] : '';
{ $this->sName = isset($aFilter['Name']) ? $aFilter['Name'] : '';
$this->sID = isset($aFilter['ID']) ? $aFilter['ID'] : '';
$this->sName = isset($aFilter['Name']) ? $aFilter['Name'] : '';
$this->bEnabled = isset($aFilter['Enabled']) ? '1' === (string) $aFilter['Enabled'] : true; $this->bEnabled = isset($aFilter['Enabled']) ? '1' === (string) $aFilter['Enabled'] : true;
$this->sConditionsType = isset($aFilter['ConditionsType']) ? $aFilter['ConditionsType'] : $this->sConditionsType = isset($aFilter['ConditionsType']) ? $aFilter['ConditionsType'] :
\RainLoop\Providers\Filters\Enumerations\ConditionsType::ANY; \RainLoop\Providers\Filters\Enumerations\ConditionsType::ANY;
$this->sActionType = isset($aFilter['ActionType']) ? $aFilter['ActionType'] : $this->sActionType = isset($aFilter['ActionType']) ? $aFilter['ActionType'] :
\RainLoop\Providers\Filters\Enumerations\ActionType::MOVE_TO; \RainLoop\Providers\Filters\Enumerations\ActionType::MOVE_TO;
$this->sActionValue = isset($aFilter['ActionValue']) ? $aFilter['ActionValue'] : ''; $this->sActionValue = isset($aFilter['ActionValue']) ? $aFilter['ActionValue'] : '';
$this->sActionValueSecond = isset($aFilter['ActionValueSecond']) ? $aFilter['ActionValueSecond'] : ''; $this->sActionValueSecond = isset($aFilter['ActionValueSecond']) ? $aFilter['ActionValueSecond'] : '';
$this->sActionValueThird = isset($aFilter['ActionValueThird']) ? $aFilter['ActionValueThird'] : ''; $this->sActionValueThird = isset($aFilter['ActionValueThird']) ? $aFilter['ActionValueThird'] : '';
$this->sActionValueFourth = isset($aFilter['ActionValueFourth']) ? $aFilter['ActionValueFourth'] : ''; $this->sActionValueFourth = isset($aFilter['ActionValueFourth']) ? $aFilter['ActionValueFourth'] : '';
$this->bKeep = isset($aFilter['Keep']) ? '1' === (string) $aFilter['Keep'] : true; $this->bKeep = isset($aFilter['Keep']) ? '1' === (string) $aFilter['Keep'] : true;
$this->bStop = isset($aFilter['Stop']) ? '1' === (string) $aFilter['Stop'] : true; $this->bStop = isset($aFilter['Stop']) ? '1' === (string) $aFilter['Stop'] : true;
$this->bMarkAsRead = isset($aFilter['MarkAsRead']) ? '1' === (string) $aFilter['MarkAsRead'] : false; $this->bMarkAsRead = isset($aFilter['MarkAsRead']) ? '1' === (string) $aFilter['MarkAsRead'] : false;
$this->aConditions = \RainLoop\Providers\Filters\Classes\FilterCondition::CollectionFromJSON( $this->aConditions = \RainLoop\Providers\Filters\Classes\FilterCondition::CollectionFromJSON(
isset($aFilter['Conditions']) ? $aFilter['Conditions'] : array()); isset($aFilter['Conditions']) ? $aFilter['Conditions'] : array());
return true; return true;
}
return false;
} }
public function ToSimpleJSON(bool $bAjax = false) : array public function ToSimpleJSON(bool $bAjax = false) : array

View file

@ -59,21 +59,16 @@ class FilterCondition
public function FromJSON(array $aData) : array public function FromJSON(array $aData) : array
{ {
if (\is_array($aData)) $this->sField = isset($aData['Field']) ? $aData['Field'] :
{ \RainLoop\Providers\Filters\Enumerations\ConditionField::FROM;
$this->sField = isset($aData['Field']) ? $aData['Field'] :
\RainLoop\Providers\Filters\Enumerations\ConditionField::FROM;
$this->sType = isset($aData['Type']) ? $aData['Type'] : $this->sType = isset($aData['Type']) ? $aData['Type'] :
\RainLoop\Providers\Filters\Enumerations\ConditionType::EQUAL_TO; \RainLoop\Providers\Filters\Enumerations\ConditionType::EQUAL_TO;
$this->sValue = isset($aData['Value']) ? (string) $aData['Value'] : ''; $this->sValue = isset($aData['Value']) ? (string) $aData['Value'] : '';
$this->sValueSecond = isset($aData['ValueSecond']) ? (string) $aData['ValueSecond'] : ''; $this->sValueSecond = isset($aData['ValueSecond']) ? (string) $aData['ValueSecond'] : '';
return true; return true;
}
return false;
} }
public function ToSimpleJSON(bool $bAjax = false) : array public function ToSimpleJSON(bool $bAjax = false) : array
@ -89,21 +84,17 @@ class FilterCondition
public static function CollectionFromJSON(array $aCollection) : array public static function CollectionFromJSON(array $aCollection) : array
{ {
$aResult = array(); $aResult = array();
if (\is_array($aCollection) && 0 < \count($aCollection)) foreach ($aCollection as $aItem)
{ {
foreach ($aCollection as $aItem) if (\is_array($aItem) && 0 < \count($aItem))
{ {
if (\is_array($aItem) && 0 < \count($aItem)) $oItem = new \RainLoop\Providers\Filters\Classes\FilterCondition();
if ($oItem->FromJSON($aItem))
{ {
$oItem = new \RainLoop\Providers\Filters\Classes\FilterCondition(); $aResult[] = $oItem;
if ($oItem->FromJSON($aItem))
{
$aResult[] = $oItem;
}
} }
} }
} }
return $aResult; return $aResult;
} }
} }

View file

@ -58,7 +58,7 @@ class SieveStorage implements \RainLoop\Providers\Filters\FiltersInterface
$aModules = $oSieveClient->Modules(); $aModules = $oSieveClient->Modules();
$aList = $oSieveClient->ListScripts(); $aList = $oSieveClient->ListScripts();
if (\is_array($aList) && 0 < \count($aList)) if (0 < \count($aList))
{ {
if (isset($aList[self::SIEVE_FILE_NAME])) if (isset($aList[self::SIEVE_FILE_NAME]))
{ {
@ -252,53 +252,50 @@ class SieveStorage implements \RainLoop\Providers\Filters\FiltersInterface
// Conditions // Conditions
$aConditions = $oFilter->Conditions(); $aConditions = $oFilter->Conditions();
if (\is_array($aConditions)) if (1 < \count($aConditions))
{ {
if (1 < \count($aConditions)) if (\RainLoop\Providers\Filters\Enumerations\ConditionsType::ANY ===
$oFilter->ConditionsType())
{ {
if (\RainLoop\Providers\Filters\Enumerations\ConditionsType::ANY === $aResult[] = 'if anyof(';
$oFilter->ConditionsType())
$bTrim = false;
foreach ($aConditions as $oCond)
{ {
$aResult[] = 'if anyof('; $bTrim = true;
$sCons = $this->conditionToSieveScript($oCond, $aCapa);
$bTrim = false; if (!empty($sCons))
foreach ($aConditions as $oCond)
{ {
$bTrim = true; $aResult[] = $sTab.$sCons.',';
$sCons = $this->conditionToSieveScript($oCond, $aCapa);
if (!empty($sCons))
{
$aResult[] = $sTab.$sCons.',';
}
} }
if ($bTrim)
{
$aResult[\count($aResult) - 1] = \rtrim($aResult[\count($aResult) - 1], ',');
}
$aResult[] = ')';
} }
else if ($bTrim)
{ {
$aResult[] = 'if allof(';
foreach ($aConditions as $oCond)
{
$aResult[] = $sTab.$this->conditionToSieveScript($oCond, $aCapa).',';
}
$aResult[\count($aResult) - 1] = \rtrim($aResult[\count($aResult) - 1], ','); $aResult[\count($aResult) - 1] = \rtrim($aResult[\count($aResult) - 1], ',');
$aResult[] = ')';
} }
}
else if (1 === \count($aConditions)) $aResult[] = ')';
{
$aResult[] = 'if '.$this->conditionToSieveScript($aConditions[0], $aCapa).'';
} }
else else
{ {
$bAll = true; $aResult[] = 'if allof(';
foreach ($aConditions as $oCond)
{
$aResult[] = $sTab.$this->conditionToSieveScript($oCond, $aCapa).',';
}
$aResult[\count($aResult) - 1] = \rtrim($aResult[\count($aResult) - 1], ',');
$aResult[] = ')';
} }
} }
else if (1 === \count($aConditions))
{
$aResult[] = 'if '.$this->conditionToSieveScript($aConditions[0], $aCapa).'';
}
else
{
$bAll = true;
}
// actions // actions
if (!$bAll) if (!$bAll)

View file

@ -26,17 +26,16 @@ class DefaultSettings implements \RainLoop\Providers\Settings\ISettings
\RainLoop\Providers\Settings\DefaultSettings::FILE_NAME \RainLoop\Providers\Settings\DefaultSettings::FILE_NAME
); );
$aSettings = array();
if (\is_string($sValue)) if (\is_string($sValue))
{ {
$aData = \json_decode($sValue, true); $aData = \json_decode($sValue, true);
if (\is_array($aData)) if (\is_array($aData))
{ {
$aSettings = $aData; return $aData;
} }
} }
return $aSettings; return array();
} }
public function Save(\RainLoop\Model\Account $oAccount, array $aSettings) : bool public function Save(\RainLoop\Model\Account $oAccount, array $aSettings) : bool

View file

@ -64,7 +64,7 @@ class ServiceActions
public function SetPaths(array $aPaths) : self public function SetPaths(array $aPaths) : self
{ {
$this->aPaths = \is_array($aPaths) ? $aPaths : array(); $this->aPaths = $aPaths;
return $this; return $this;
} }
@ -104,7 +104,7 @@ class ServiceActions
$this->Logger()->Write('Action: '.$sMethodName, \MailSo\Log\Enumerations\Type::NOTE, 'AJAX'); $this->Logger()->Write('Action: '.$sMethodName, \MailSo\Log\Enumerations\Type::NOTE, 'AJAX');
$aPost = $this->oHttp->GetPostAsArray(); $aPost = $this->oHttp->GetPostAsArray();
if (\is_array($aPost) && 0 < \count($aPost)) if ($aPost)
{ {
$this->oActions->SetActionParams($aPost, $sMethodName); $this->oActions->SetActionParams($aPost, $sMethodName);
switch ($sMethodName) switch ($sMethodName)

View file

@ -22,11 +22,7 @@ class Settings
public function InitData(array $aData) : self public function InitData(array $aData) : self
{ {
if (\is_array($aData)) $this->aData = $aData;
{
$this->aData = $aData;
}
return $this; return $this;
} }

View file

@ -251,10 +251,10 @@ class Utils
{ {
if (\file_exists($sFileName)) if (\file_exists($sFileName))
{ {
$isYml = '.yml' === substr($sFileName, -4); if ('.yml' === substr($sFileName, -4))
if ($isYml)
{ {
$aLang = \spyc_load(\str_replace(array(': >-', ': |-', ': |+'), array(': >', ': |', ': |'), \file_get_contents($sFileName))); //- $aLang = \yaml_parse(\str_replace(array(': >-', ': |-', ': |+'), array(': >', ': |', ': |'), \file_get_contents($sFileName)));
$aLang = \yaml_parse_file($sFileName);
if (\is_array($aLang)) if (\is_array($aLang))
{ {
\reset($aLang); \reset($aLang);
@ -434,21 +434,16 @@ class Utils
{ {
$aResult = array(); $aResult = array();
if (is_array($aSuggestions)) foreach ($aSuggestions as $aItem)
{ {
$aCache = array(); $sLine = \implode('~~', $aItem);
foreach ($aSuggestions as $aItem) if (!isset($aResult[$sLine]))
{ {
$sLine = \implode('~~', $aItem); $aResult[$sLine] = $aItem;
if (!isset($aCache[$sLine]))
{
$aCache[$sLine] = true;
$aResult[] = $aItem;
}
} }
} }
return $aResult; return array_values($aResult);
} }
public static function CustomParseIniFile(string $sFileName, bool $bProcessSections = false) : array public static function CustomParseIniFile(string $sFileName, bool $bProcessSections = false) : array
@ -458,8 +453,7 @@ class Utils
// return \parse_ini_file($sFileName, !!$bProcessSections); // return \parse_ini_file($sFileName, !!$bProcessSections);
// } // }
$sData = \file_get_contents($sFileName); return @\parse_ini_string(\file_get_contents($sFileName), $bProcessSections) ?: array();
return \is_string($sData) ? \parse_ini_string($sData, !!$bProcessSections) : null;
} }
public static function CustomBaseConvert(string $sNumberInput, string $sFromBaseInput = '0123456789', string $sToBaseInput = '0123456789') public static function CustomBaseConvert(string $sNumberInput, string $sFromBaseInput = '0123456789', string $sToBaseInput = '0123456789')

View file

@ -776,7 +776,7 @@ class RecurrenceIterator implements \Iterator {
if ($this->byHour) { if ($this->byHour) {
if ($this->currentDate->format('G') == '23') { if ($this->currentDate->format('G') == '23') {
// to obey the interval rule // to obey the interval rule
$this->currentDate->modify('+' . $this->interval-1 . ' days'); $this->currentDate->modify('+' . ($this->interval-1) . ' days');
} }
$this->currentDate->modify('+1 hours'); $this->currentDate->modify('+1 hours');
@ -835,7 +835,7 @@ class RecurrenceIterator implements \Iterator {
// We need to roll over to the next week // We need to roll over to the next week
if ($currentDay === $firstDay && (!$this->byHour || $currentHour == '0')) { if ($currentDay === $firstDay && (!$this->byHour || $currentHour == '0')) {
$this->currentDate->modify('+' . $this->interval-1 . ' weeks'); $this->currentDate->modify('+' . ($this->interval-1) . ' weeks');
// We need to go to the first day of this week, but only if we // We need to go to the first day of this week, but only if we
// are not already on this first day of this week. // are not already on this first day of this week.

View file

@ -1,7 +1,7 @@
<?php <?php
/** /**
* Spyc -- A Simple PHP YAML Class * Spyc -- A Simple PHP YAML Class
* @version 0.5.1 * @version 0.6.2
* @author Vlad Andersen <vlad.andersen@gmail.com> * @author Vlad Andersen <vlad.andersen@gmail.com>
* @author Chris Wanstrath <chris@ozmm.org> * @author Chris Wanstrath <chris@ozmm.org>
* @link https://github.com/mustangostang/spyc/ * @link https://github.com/mustangostang/spyc/
@ -10,38 +10,7 @@
* @package Spyc * @package Spyc
*/ */
if (!function_exists('spyc_load')) { if (!class_exists('Spyc')) {
/**
* Parses YAML to array.
* @param string $string YAML string.
* @return array
*/
function spyc_load ($string) {
return Spyc::YAMLLoadString($string);
}
}
if (!function_exists('spyc_load_file')) {
/**
* Parses YAML to array.
* @param string $file Path to YAML file.
* @return array
*/
function spyc_load_file ($file) {
return Spyc::YAMLLoad($file);
}
}
if (!function_exists('spyc_dump')) {
/**
* Dumps array to YAML.
* @param array $data Array.
* @return string
*/
function spyc_dump ($data) {
return Spyc::YAMLDump($data, false, false, true);
}
}
/** /**
* The Simple PHP YAML Class. * The Simple PHP YAML Class.
@ -59,10 +28,6 @@ if (!function_exists('spyc_dump')) {
* <code> * <code>
* $array = Spyc::YAMLLoad($file); * $array = Spyc::YAMLLoad($file);
* </code> * </code>
* or:
* <code>
* $array = spyc_load_file($file);
* </code>
* @package Spyc * @package Spyc
*/ */
class Spyc { class Spyc {
@ -71,14 +36,6 @@ class Spyc {
const REMPTY = "\0\0\0\0\0"; const REMPTY = "\0\0\0\0\0";
/**
* Setting this to true will force YAMLDump to enclose any string value in
* quotes. False by default.
*
* @var bool
*/
public $setting_dump_force_quotes = false;
/** /**
* Setting this to true will forse YAMLLoad to use syck_load function when * Setting this to true will forse YAMLLoad to use syck_load function when
* possible. False by default. * possible. False by default.
@ -86,14 +43,18 @@ class Spyc {
*/ */
public $setting_use_syck_is_possible = false; public $setting_use_syck_is_possible = false;
/**
* Setting this to true will forse YAMLLoad to use syck_load function when
* possible. False by default.
* @var bool
*/
public $setting_empty_hash_as_object = false;
/**#@+ /**#@+
* @access private * @access private
* @var mixed * @var mixed
*/ */
private $_dumpIndent;
private $_dumpWordWrap;
private $_containsGroupAnchor = false; private $_containsGroupAnchor = false;
private $_containsGroupAlias = false; private $_containsGroupAlias = false;
private $path; private $path;
@ -107,19 +68,13 @@ class Spyc {
*/ */
private $delayedPath = array(); private $delayedPath = array();
/**#@+
* @access public
* @var mixed
*/
public $_nodeId;
/** /**
* Load a valid YAML string to Spyc. * Load a valid YAML string to Spyc.
* @param string $input * @param string $input
* @return array * @return array
*/ */
public function load ($input) { public function load ($input) {
return $this->__loadString($input); return $this->_loadString($input);
} }
/** /**
@ -128,7 +83,7 @@ class Spyc {
* @return array * @return array
*/ */
public function loadFile ($file) { public function loadFile ($file) {
return $this->__load($file); return $this->_load($file);
} }
/** /**
@ -145,10 +100,16 @@ class Spyc {
* @access public * @access public
* @return array * @return array
* @param string $input Path of YAML file or string containing YAML * @param string $input Path of YAML file or string containing YAML
* @param array set options
*/ */
public static function YAMLLoad($input) { public static function YAMLLoad($input, $options = []) {
$Spyc = new Spyc; $Spyc = new Spyc;
return $Spyc->__load($input); foreach ($options as $key => $value) {
if (property_exists($Spyc, $key)) {
$Spyc->$key = $value;
}
}
return $Spyc->_load($input);
} }
/** /**
@ -169,247 +130,16 @@ class Spyc {
* @access public * @access public
* @return array * @return array
* @param string $input String containing YAML * @param string $input String containing YAML
* @param array set options
*/ */
public static function YAMLLoadString($input) { public static function YAMLLoadString($input, $options = []) {
$Spyc = new Spyc; $Spyc = new Spyc;
return $Spyc->__loadString($input); foreach ($options as $key => $value) {
} if (property_exists($Spyc, $key)) {
$Spyc->$key = $value;
/** }
* Dump YAML from PHP array statically
*
* The dump method, when supplied with an array, will do its best
* to convert the array into friendly YAML. Pretty simple. Feel free to
* save the returned string as nothing.yaml and pass it around.
*
* Oh, and you can decide how big the indent is and what the wordwrap
* for folding is. Pretty cool -- just pass in 'false' for either if
* you want to use the default.
*
* Indent's default is 2 spaces, wordwrap's default is 40 characters. And
* you can turn off wordwrap by passing in 0.
*
* @access public
* @return string
* @param array $array PHP array
* @param int $indent Pass in false to use the default, which is 2
* @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
* @param int $no_opening_dashes Do not start YAML file with "---\n"
*/
public static function YAMLDump($array, $indent = false, $wordwrap = false, $no_opening_dashes = false) {
$spyc = new Spyc;
return $spyc->dump($array, $indent, $wordwrap, $no_opening_dashes);
}
/**
* Dump PHP array to YAML
*
* The dump method, when supplied with an array, will do its best
* to convert the array into friendly YAML. Pretty simple. Feel free to
* save the returned string as tasteful.yaml and pass it around.
*
* Oh, and you can decide how big the indent is and what the wordwrap
* for folding is. Pretty cool -- just pass in 'false' for either if
* you want to use the default.
*
* Indent's default is 2 spaces, wordwrap's default is 40 characters. And
* you can turn off wordwrap by passing in 0.
*
* @access public
* @return string
* @param array $array PHP array
* @param int $indent Pass in false to use the default, which is 2
* @param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
*/
public function dump($array,$indent = false,$wordwrap = false, $no_opening_dashes = false) {
// Dumps to some very clean YAML. We'll have to add some more features
// and options soon. And better support for folding.
// New features and options.
if ($indent === false or !is_numeric($indent)) {
$this->_dumpIndent = 2;
} else {
$this->_dumpIndent = $indent;
} }
return $Spyc->_loadString($input);
if ($wordwrap === false or !is_numeric($wordwrap)) {
$this->_dumpWordWrap = 40;
} else {
$this->_dumpWordWrap = $wordwrap;
}
// New YAML document
$string = "";
if (!$no_opening_dashes) $string = "---\n";
// Start at the base of the array and move through it.
if ($array) {
$array = (array)$array;
$previous_key = -1;
foreach ($array as $key => $value) {
if (!isset($first_key)) $first_key = $key;
$string .= $this->_yamlize($key,$value,0,$previous_key, $first_key, $array);
$previous_key = $key;
}
}
return $string;
}
/**
* Attempts to convert a key / value array item to YAML
* @access private
* @return string
* @param $key The name of the key
* @param $value The value of the item
* @param $indent The indent of the current node
*/
private function _yamlize($key,$value,$indent, $previous_key = -1, $first_key = 0, $source_array = null) {
if (is_array($value)) {
if (empty ($value))
return $this->_dumpNode($key, array(), $indent, $previous_key, $first_key, $source_array);
// It has children. What to do?
// Make it the right kind of item
$string = $this->_dumpNode($key, self::REMPTY, $indent, $previous_key, $first_key, $source_array);
// Add the indent
$indent += $this->_dumpIndent;
// Yamlize the array
$string .= $this->_yamlizeArray($value,$indent);
} elseif (!is_array($value)) {
// It doesn't have children. Yip.
$string = $this->_dumpNode($key, $value, $indent, $previous_key, $first_key, $source_array);
}
return $string;
}
/**
* Attempts to convert an array to YAML
* @access private
* @return string
* @param $array The array you want to convert
* @param $indent The indent of the current level
*/
private function _yamlizeArray($array,$indent) {
if (is_array($array)) {
$string = '';
$previous_key = -1;
foreach ($array as $key => $value) {
if (!isset($first_key)) $first_key = $key;
$string .= $this->_yamlize($key, $value, $indent, $previous_key, $first_key, $array);
$previous_key = $key;
}
return $string;
} else {
return false;
}
}
/**
* Returns YAML from a key and a value
* @access private
* @return string
* @param $key The name of the key
* @param $value The value of the item
* @param $indent The indent of the current node
*/
private function _dumpNode($key, $value, $indent, $previous_key = -1, $first_key = 0, $source_array = null) {
// do some folding here, for blocks
if (is_string ($value) && ((strpos($value,"\n") !== false || strpos($value,": ") !== false || strpos($value,"- ") !== false ||
strpos($value,"*") !== false || strpos($value,"#") !== false || strpos($value,"<") !== false || strpos($value,">") !== false || strpos ($value, '%') !== false || strpos ($value, ' ') !== false ||
strpos($value,"[") !== false || strpos($value,"]") !== false || strpos($value,"{") !== false || strpos($value,"}") !== false) || strpos($value,"&") !== false || strpos($value, "'") !== false || strpos($value, "!") === 0 ||
substr ($value, -1, 1) == ':')
) {
$value = $this->_doLiteralBlock($value,$indent);
} else {
$value = $this->_doFolding($value,$indent);
}
if ($value === array()) $value = '[ ]';
if ($value === "") $value = '""';
if (self::isTranslationWord($value)) {
$value = $this->_doLiteralBlock($value, $indent);
}
if (trim ($value) != $value)
$value = $this->_doLiteralBlock($value,$indent);
if (is_bool($value)) {
$value = $value ? "true" : "false";
}
if ($value === null) $value = 'null';
if ($value === "'" . self::REMPTY . "'") $value = null;
$spaces = str_repeat(' ',$indent);
//if (is_int($key) && $key - 1 == $previous_key && $first_key===0) {
if (is_array ($source_array) && array_keys($source_array) === range(0, count($source_array) - 1)) {
// It's a sequence
$string = $spaces.'- '.$value."\n";
} else {
// if ($first_key===0) throw new Exception('Keys are all screwy. The first one was zero, now it\'s "'. $key .'"');
// It's mapped
if (strpos($key, ":") !== false || strpos($key, "#") !== false) { $key = '"' . $key . '"'; }
$string = rtrim ($spaces.$key.': '.$value)."\n";
}
return $string;
}
/**
* Creates a literal block for dumping
* @access private
* @return string
* @param $value
* @param $indent int The value of the indent
*/
private function _doLiteralBlock($value,$indent) {
if ($value === "\n") return '\n';
if (strpos($value, "\n") === false && strpos($value, "'") === false) {
return sprintf ("'%s'", $value);
}
if (strpos($value, "\n") === false && strpos($value, '"') === false) {
return sprintf ('"%s"', $value);
}
$exploded = explode("\n",$value);
$newValue = '|';
if (isset($exploded[0]) && ($exploded[0] == "|" || $exploded[0] == "|-" || $exploded[0] == ">")) {
$newValue = $exploded[0];
unset($exploded[0]);
}
$indent += $this->_dumpIndent;
$spaces = str_repeat(' ',$indent);
foreach ($exploded as $line) {
$line = trim($line);
if (strpos($line, '"') === 0 && strrpos($line, '"') == (strlen($line)-1) || strpos($line, "'") === 0 && strrpos($line, "'") == (strlen($line)-1)) {
$line = substr($line, 1, -1);
}
$newValue .= "\n" . $spaces . ($line);
}
return $newValue;
}
/**
* Folds a string of text, if necessary
* @access private
* @return string
* @param $value The string you wish to fold
*/
private function _doFolding($value,$indent) {
// Don't do anything if wordwrap is set to 0
if ($this->_dumpWordWrap !== 0 && is_string ($value) && strlen($value) > $this->_dumpWordWrap) {
$indent += $this->_dumpIndent;
$indent = str_repeat(' ',$indent);
$wrapped = wordwrap($value,$this->_dumpWordWrap,"\n$indent");
$value = ">\n".$indent.$wrapped;
} else {
if ($this->setting_dump_force_quotes && is_string ($value) && $value !== self::REMPTY)
$value = '"' . $value . '"';
if (is_numeric($value) && is_string($value))
$value = '"' . $value . '"';
}
return $value;
} }
private function isTrueWord($value) { private function isTrueWord($value) {
@ -468,12 +198,12 @@ class Spyc {
// LOADING FUNCTIONS // LOADING FUNCTIONS
private function __load($input) { private function _load($input) {
$Source = $this->loadFromSource($input); $Source = $this->loadFromSource($input);
return $this->loadWithSource($Source); return $this->loadWithSource($Source);
} }
private function __loadString($input) { private function _loadString($input) {
$Source = $this->loadFromString($input); $Source = $this->loadFromString($input);
return $this->loadWithSource($Source); return $this->loadWithSource($Source);
} }
@ -571,19 +301,20 @@ class Spyc {
$line = $this->stripGroup ($line, $group); $line = $this->stripGroup ($line, $group);
} }
if ($this->startsMappedSequence($line)) if ($this->startsMappedSequence($line)) {
return $this->returnMappedSequence($line); return $this->returnMappedSequence($line);
}
if ($this->startsMappedValue($line)) if ($this->startsMappedValue($line)) {
return $this->returnMappedValue($line); return $this->returnMappedValue($line);
}
if ($this->isArrayElement($line)) if ($this->isArrayElement($line))
return $this->returnArrayElement($line); return $this->returnArrayElement($line);
if ($this->isPlainArray($line)) if ($this->isPlainArray($line))
return $this->returnPlainArray($line); return $this->returnPlainArray($line);
return $this->returnKeyValuePair($line); return $this->returnKeyValuePair($line);
} }
@ -596,6 +327,11 @@ class Spyc {
*/ */
private function _toType($value) { private function _toType($value) {
if ($value === '') return ""; if ($value === '') return "";
if ($this->setting_empty_hash_as_object && $value === '{}') {
return new stdClass();
}
$first_character = $value[0]; $first_character = $value[0];
$last_character = substr($value, -1, 1); $last_character = substr($value, -1, 1);
@ -609,7 +345,9 @@ class Spyc {
if ($is_quoted) { if ($is_quoted) {
$value = str_replace('\n', "\n", $value); $value = str_replace('\n', "\n", $value);
return strtr(substr ($value, 1, -1), array ('\\"' => '"', '\'\'' => '\'', '\\\'' => '\'')); if ($first_character == "'")
return strtr(substr ($value, 1, -1), array ('\'\'' => '\'', '\\\''=> '\''));
return strtr(substr ($value, 1, -1), array ('\\"' => '"', '\\\''=> '\''));
} }
if (strpos($value, ' #') !== false && !$is_quoted) if (strpos($value, ' #') !== false && !$is_quoted)
@ -662,12 +400,12 @@ class Spyc {
if ( is_numeric($value) && preg_match ('/^(-|)[1-9]+[0-9]*$/', $value) ){ if ( is_numeric($value) && preg_match ('/^(-|)[1-9]+[0-9]*$/', $value) ){
$intvalue = (int)$value; $intvalue = (int)$value;
if ($intvalue != PHP_INT_MAX) if ($intvalue != PHP_INT_MAX && $intvalue != ~PHP_INT_MAX)
$value = $intvalue; $value = $intvalue;
return $value; return $value;
} }
if (is_numeric($value) && preg_match('/^0[xX][0-9a-fA-F]+$/', $value)) { if ( is_string($value) && preg_match('/^0[xX][0-9a-fA-F]+$/', $value)) {
// Hexadecimal value. // Hexadecimal value.
return hexdec($value); return hexdec($value);
} }
@ -1096,6 +834,7 @@ class Spyc {
} }
// Set the type of the value. Int, string, etc // Set the type of the value. Int, string, etc
$value = $this->_toType($value); $value = $this->_toType($value);
if ($key === '0') $key = '__!YAMLZero'; if ($key === '0') $key = '__!YAMLZero';
$array[$key] = $value; $array[$key] = $value;
} else { } else {
@ -1142,14 +881,4 @@ class Spyc {
return $line; return $line;
} }
} }
}
// Enable use of Spyc from command line
// The syntax is the following: php Spyc.php spyc.yaml
do {
if (PHP_SAPI != 'cli') break;
if (empty ($_SERVER['argc']) || $_SERVER['argc'] < 2) break;
if (empty ($_SERVER['PHP_SELF']) || FALSE === strpos ($_SERVER['PHP_SELF'], 'Spyc.php') ) break;
$file = $argv[1];
echo json_encode (spyc_load_file ($file));
} while (0);