v1.2.7.416

This commit is contained in:
RainLoop Team 2013-09-30 21:01:08 +04:00
parent 54e2645fcf
commit 3b27abbe9a
434 changed files with 51 additions and 72 deletions

View file

@ -0,0 +1,183 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
abstract class Collection
{
/**
* @var array
*/
protected $aItems;
/**
* @access protected
*/
protected function __construct()
{
$this->aItems = array();
}
/**
* @param mixed $mItem
* @param bool $bToTop = false
* @return self
*/
public function Add($mItem, $bToTop = false)
{
if ($bToTop)
{
\array_unshift($this->aItems, $mItem);
}
else
{
\array_push($this->aItems, $mItem);
}
return $this;
}
/**
* @param array $aItems
* @return self
*
* @throws \MailSo\Base\Exceptions\InvalidArgumentException
*/
public function AddArray($aItems)
{
if (!\is_array($aItems))
{
throw new \MailSo\Base\Exceptions\InvalidArgumentException();
}
foreach ($aItems as $mItem)
{
$this->Add($mItem);
}
return $this;
}
/**
* @return self
*/
public function Clear()
{
$this->aItems = array();
return $this;
}
/**
* @return array
*/
public function CloneAsArray()
{
return $this->aItems;
}
/**
* @return int
*/
public function Count()
{
return \count($this->aItems);
}
/**
* @return array
*/
public function &GetAsArray()
{
return $this->aItems;
}
/**
* @param mixed $mCallback
*/
public function MapList($mCallback)
{
$aResult = array();
if (\is_callable($mCallback))
{
foreach ($this->aItems as $oItem)
{
$aResult[] = \call_user_func($mCallback, $oItem);
}
}
return $aResult;
}
/**
* @param mixed $mCallback
* @return array
*/
public function FilterList($mCallback)
{
$aResult = array();
if (\is_callable($mCallback))
{
foreach ($this->aItems as $oItem)
{
if (\call_user_func($mCallback, $oItem))
{
$aResult[] = $oItem;
}
}
}
return $aResult;
}
/**
* @param mixed $mCallback
* @return void
*/
public function ForeachList($mCallback)
{
if (\is_callable($mCallback))
{
foreach ($this->aItems as $oItem)
{
\call_user_func($mCallback, $oItem);
}
}
}
/**
* @return mixed | null
* @return mixed
*/
public function &GetByIndex($iIndex)
{
$mResult = null;
if (\key_exists($iIndex, $this->aItems))
{
$mResult = $this->aItems[$iIndex];
}
return $mResult;
}
/**
* @param array $aItems
* @return self
*
* @throws \MailSo\Base\Exceptions\InvalidArgumentException
*/
public function SetAsArray($aItems)
{
if (!\is_array($aItems))
{
throw new \MailSo\Base\Exceptions\InvalidArgumentException();
}
$this->aItems = $aItems;
return $this;
}
}

View file

@ -0,0 +1,180 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
class Crypt {
/**
*
* @param string $sString
* @param string $sKey
*
* @return string
*/
public static function XxteaEncrypt($sString, $sKey)
{
if (0 === \strlen($sString))
{
return '';
}
$aV = self::str2long($sString, true);
$aK = self::str2long($sKey, false);
if (\count($aK) < 4)
{
for ($iIndex = \count($aK); $iIndex < 4; $iIndex++)
{
$aK[$iIndex] = 0;
}
}
$iN = \count($aV) - 1;
$iZ = $aV[$iN];
$iY = $aV[0];
$iDelta = 0x9E3779B9;
$iQ = \floor(6 + 52 / ($iN + 1));
$iSum = 0;
while (0 < $iQ--)
{
$iSum = self::int32($iSum + $iDelta);
$iE = $iSum >> 2 & 3;
for ($iPIndex = 0; $iPIndex < $iN; $iPIndex++)
{
$iY = $aV[$iPIndex + 1];
$iMx = self::int32((($iZ >> 5 & 0x07ffffff) ^ $iY << 2) +
(($iY >> 3 & 0x1fffffff) ^ $iZ << 4)) ^ self::int32(($iSum ^ $iY) + ($aK[$iPIndex & 3 ^ $iE] ^ $iZ));
$iZ = $aV[$iPIndex] = self::int32($aV[$iPIndex] + $iMx);
}
$iY = $aV[0];
$iMx = self::int32((($iZ >> 5 & 0x07ffffff) ^ $iY << 2) +
(($iY >> 3 & 0x1fffffff) ^ $iZ << 4)) ^ self::int32(($iSum ^ $iY) + ($aK[$iPIndex & 3 ^ $iE] ^ $iZ));
$iZ = $aV[$iN] = self::int32($aV[$iN] + $iMx);
}
return self::long2str($aV, false);
}
/**
* @param string $sEncriptedString
* @param string $sKey
*
* @return string
*/
public static function XxteaDecrypt($sEncriptedString, $sKey)
{
if (0 === \strlen($sEncriptedString))
{
return '';
}
$aV = self::str2long($sEncriptedString, false);
$aK = self::str2long($sKey, false);
if (\count($aK) < 4)
{
for ($iIndex = \count($aK); $iIndex < 4; $iIndex++)
{
$aK[$iIndex] = 0;
}
}
$iN = \count($aV) - 1;
$iZ = $aV[$iN];
$iY = $aV[0];
$iDelta = 0x9E3779B9;
$iQ = \floor(6 + 52 / ($iN + 1));
$iSum = self::int32($iQ * $iDelta);
while ($iSum != 0)
{
$iE = $iSum >> 2 & 3;
for ($iPIndex = $iN; $iPIndex > 0; $iPIndex--)
{
$iZ = $aV[$iPIndex - 1];
$iMx = self::int32((($iZ >> 5 & 0x07ffffff) ^ $iY << 2) +
(($iY >> 3 & 0x1fffffff) ^ $iZ << 4)) ^ self::int32(($iSum ^ $iY) + ($aK[$iPIndex & 3 ^ $iE] ^ $iZ));
$iY = $aV[$iPIndex] = self::int32($aV[$iPIndex] - $iMx);
}
$iZ = $aV[$iN];
$iMx = self::int32((($iZ >> 5 & 0x07ffffff) ^ $iY << 2) +
(($iY >> 3 & 0x1fffffff) ^ $iZ << 4)) ^ self::int32(($iSum ^ $iY) + ($aK[$iPIndex & 3 ^ $iE] ^ $iZ));
$iY = $aV[0] = self::int32($aV[0] - $iMx);
$iSum = self::int32($iSum - $iDelta);
}
return self::long2str($aV, true);
}
/**
* @param array $aV
* @param array $aW
*
* @return string
*/
private static function long2str($aV, $aW)
{
$iLen = \count($aV);
$iN = ($iLen - 1) << 2;
if ($aW)
{
$iM = $aV[$iLen - 1];
if (($iM < $iN - 3) || ($iM > $iN))
{
return false;
}
$iN = $iM;
}
$aS = array();
for ($iIndex = 0; $iIndex < $iLen; $iIndex++)
{
$aS[$iIndex] = \pack('V', $aV[$iIndex]);
}
if ($aW)
{
return \substr(\join('', $aS), 0, $iN);
}
else
{
return \join('', $aS);
}
}
/**
* @param string $sS
* @param string $sW
*
* @return array
*/
private static function str2long($sS, $sW)
{
$aV = \unpack('V*', $sS . \str_repeat("\0", (4 - \strlen($sS) % 4) & 3));
$aV = \array_values($aV);
if ($sW)
{
$aV[\count($aV)] = \strlen($sS);
}
return $aV;
}
/**
* @param int $iN
*
* @return int
*/
private static function int32($iN)
{
while ($iN >= 2147483648)
{
$iN -= 4294967296;
}
while ($iN <= -2147483649)
{
$iN += 4294967296;
}
return (int) $iN;
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
class DateTimeHelper
{
/**
* @access private
*/
private function __construct()
{
}
/**
* @staticvar \DateTimeZone $oDateTimeZone
*
* @return \DateTimeZone
*/
public static function GetUtcTimeZoneObject()
{
static $oDateTimeZone = null;
if (null === $oDateTimeZone)
{
$oDateTimeZone = new \DateTimeZone('UTC');
}
return $oDateTimeZone;
}
/**
* Parse date string formated as "Thu, 10 Jun 2010 08:58:33 -0700 (PDT)"
* RFC2822
*
* @param string $sDateTime
*
* @return int
*/
public static function ParseRFC2822DateString($sDateTime)
{
$sDateTime = \trim(\preg_replace('/ \([a-zA-Z0-9]+\)$/', '', \trim($sDateTime)));
$oDateTime = \DateTime::createFromFormat('D, d M Y H:i:s O', $sDateTime, \MailSo\Base\DateTimeHelper::GetUtcTimeZoneObject());
return $oDateTime ? $oDateTime->getTimestamp() : 0;
}
/**
* Parse date string formated as "10-Jan-2012 01:58:17 -0800"
* IMAP INTERNALDATE Format
*
* @param string $sDateTime
*
* @return int
*/
public static function ParseInternalDateString($sDateTime)
{
$oDateTime = \DateTime::createFromFormat('d-M-Y H:i:s O', \trim($sDateTime), \MailSo\Base\DateTimeHelper::GetUtcTimeZoneObject());
return $oDateTime ? $oDateTime->getTimestamp() : 0;
}
/**
* Parse date string formated as "2011-06-14 23:59:59 +0400"
*
* @param string $sDateTime
*
* @return int
*/
public static function ParseDateStringType1($sDateTime)
{
$oDateTime = \DateTime::createFromFormat('Y-m-d H:i:s O', \trim($sDateTime), \MailSo\Base\DateTimeHelper::GetUtcTimeZoneObject());
return $oDateTime ? $oDateTime->getTimestamp() : 0;
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace MailSo\Base\Enumerations;
/**
* @category MailSo
* @package Base
* @subpackage Enumerations
*/
class Charset
{
const UTF_8 = 'utf-8';
const UTF_7 = 'utf-7';
const UTF_7_IMAP = 'utf7-imap';
const WIN_1250 = 'windows-1250';
const WIN_1251 = 'windows-1251';
const WIN_1252 = 'windows-1252';
const WIN_1253 = 'windows-1253';
const WIN_1254 = 'windows-1254';
const WIN_1255 = 'windows-1255';
const WIN_1256 = 'windows-1256';
const WIN_1257 = 'windows-1257';
const WIN_1258 = 'windows-1258';
const ISO_8859_1 = 'iso-8859-1';
const ISO_8859_8 = 'iso-8859-8';
const ISO_8859_8_I = 'iso-8859-8-i';
}

View file

@ -0,0 +1,24 @@
<?php
namespace MailSo\Base\Enumerations;
/**
* @category MailSo
* @package Base
* @subpackage Enumerations
*/
class Encoding
{
const QUOTED_PRINTABLE = 'Quoted-Printable';
const QUOTED_PRINTABLE_LOWER = 'quoted-printable';
const QUOTED_PRINTABLE_SHORT = 'Q';
const BASE64 = 'Base64';
const BASE64_LOWER = 'base64';
const BASE64_SHORT = 'B';
const SEVEN_BIT = '7bit';
const _7_BIT = '7bit';
const EIGHT_BIT = '8bit';
const _8_BIT = '8bit';
}

View file

@ -0,0 +1,24 @@
<?php
namespace MailSo\Base\Exceptions;
/**
* @category MailSo
* @package Base
* @subpackage Exceptions
*/
class Exception extends \Exception
{
/**
* @param string $sMessage
* @param int $iCode
* @param \Exception|null $oPrevious
*/
public function __construct($sMessage = '', $iCode = 0, $oPrevious = null)
{
$sMessage = 0 === strlen($sMessage) ? str_replace('\\', '-', get_class($this)).' ('.
basename($this->getFile()).' ~ '.$this->getLine().')' : $sMessage;
parent::__construct($sMessage, $iCode, $oPrevious);
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace MailSo\Base\Exceptions;
/**
* @category MailSo
* @package Base
* @subpackage Exceptions
*/
class InvalidArgumentException extends \MailSo\Base\Exceptions\Exception {}

View file

@ -0,0 +1,666 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
class HtmlUtils
{
/**
* @access private
*/
private function __construct()
{
}
/**
* @param string $sText
*
* @return \DOMDocument | bool
*/
public static function GetDomFromText($sText)
{
static $bOnce = true;
if ($bOnce)
{
$bOnce = false;
if (\MailSo\Base\Utils::FunctionExistsAndEnabled('libxml_use_internal_errors'))
{
@\libxml_use_internal_errors(true);
}
}
$oDom = new \DOMDocument('1.0', 'utf-8');
@$oDom->loadHTML('<'.'?xml version="1.0" encoding="utf-8"?'.'>'.
'<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>'.$sText.'</body></html>');
return $oDom;
}
/**
* @param string $sHtml
*
* @return string
*/
public static function ClearBodyAndHtmlTag($sHtml)
{
$sHtml = \preg_replace('/<body([^>]*)>/im', '<div\\1>', $sHtml);
$sHtml = \preg_replace('/<\/body>/im', '</div>', $sHtml);
$sHtml = \preg_replace('/<html([^>]*)>/im', '<div\\1>', $sHtml);
$sHtml = \preg_replace('/<\/html>/im', '</div>', $sHtml);
return $sHtml;
}
/**
* @param string $sHtml
*
* @return string
*/
public static function ClearTags($sHtml)
{
$aRemoveTags = array(
'head', 'link', 'base', 'meta', 'title', 'style', 'script', 'bgsound',
'object', 'embed', 'applet', 'mocha', 'iframe', 'frame', 'frameset'
);
$aToRemove = array(
'/<!doctype[^>]*>/msi',
'/<\?xml [^>]*\?>/msi'
);
foreach ($aRemoveTags as $sTag)
{
$aToRemove[] = '\'<'.$sTag.'[^>]*>.*?</[\s]*'.$sTag.'>\'msi';
$aToRemove[] = '\'<'.$sTag.'[^>]*>\'msi';
$aToRemove[] = '\'</[\s]*'.$sTag.'[^>]*>\'msi';
}
return \preg_replace($aToRemove, '', $sHtml);
}
/**
* @param string $sHtml
*
* @return string
*/
public static function ClearOn($sHtml)
{
$aToReplace = array(
'/on(Blur)/si',
'/on(Change)/si',
'/on(Click)/si',
'/on(DblClick)/si',
'/on(Error)/si',
'/on(Focus)/si',
'/on(KeyDown)/si',
'/on(KeyPress)/si',
'/on(KeyUp)/si',
'/on(Load)/si',
'/on(MouseDown)/si',
'/on(MouseEnter)/si',
'/on(MouseLeave)/si',
'/on(MouseMove)/si',
'/on(MouseOut)/si',
'/on(MouseOver)/si',
'/on(MouseUp)/si',
'/on(Move)/si',
'/on(Resize)/si',
'/on(ResizeEnd)/si',
'/on(ResizeStart)/si',
'/on(Scroll)/si',
'/on(Select)/si',
'/on(Submit)/si',
'/on(Unload)/si'
);
return \preg_replace($aToReplace, 'оn\\1', $sHtml);
}
/**
*
* @param string $sStyle
* @param \DOMElement $oElement
* @param bool $bHasExternals
* @param array $aFoundCIDs
*
* @return string
*/
public static function ClearStyle($sStyle, $oElement, &$bHasExternals, &$aFoundCIDs)
{
$sStyle = \trim($sStyle);
$aOutStyles = array();
$aStyles = \explode(';', $sStyle);
$aMatch = array();
foreach ($aStyles as $sStyleItem)
{
$aStyleValue = \explode(':', $sStyleItem, 2);
$sName = \trim(\strtolower($aStyleValue[0]));
$sValue = isset($aStyleValue[1]) ? \trim($aStyleValue[1]) : '';
if ('position' === $sName && 'fixed' === \strtolower($sValue))
{
$sValue = 'absolute';
}
if (0 === \strlen($sName) || 0 === \strlen($sValue))
{
continue;
}
$sStyleItem = $sName.': '.$sValue;
$aStyleValue = array($sName, $sValue);
/*if (\in_array($sName, array('position', 'left', 'right', 'top', 'bottom', 'behavior', 'cursor')))
{
// skip
}
else */if (\in_array($sName, array('behavior', 'cursor')) ||
('display' === $sName && 'none' === \strtolower($sValue)) ||
\preg_match('/expression/i', $sValue) ||
('text-indent' === $sName && '-' === \substr(trim($sValue), 0, 1))
)
{
// skip
}
else if (\in_array($sName, array('background-image', 'background', 'list-style-image', 'content'))
&& \preg_match('/url[\s]?\(([^)]+)\)/im', $sValue, $aMatch) && !empty($aMatch[1]))
{
$sFullUrl = \trim($aMatch[0], '"\' ');
$sUrl = \trim($aMatch[1], '"\' ');
$sStyleValue = \trim(\preg_replace('/[\s]+/', ' ', \str_replace($sFullUrl, '', $sValue)));
$sStyleItem = empty($sStyleValue) ? '' : $sName.': '.$sStyleValue;
if ('cid:' === \strtolower(\substr($sUrl, 0, 4)))
{
if ($oElement)
{
$oElement->setAttribute('data-x-style-cid-name',
'background' === $sName ? 'background-image' : $sName);
$oElement->setAttribute('data-x-style-cid', \substr($sUrl, 4));
$aFoundCIDs[] = \substr($sUrl, 4);
}
}
else
{
if ($oElement)
{
if (\preg_match('/http[s]?:\/\//i', $sUrl))
{
$bHasExternals = true;
if (\in_array($sName, array('background-image', 'list-style-image', 'content')))
{
$sStyleItem = '';
}
$sTemp = '';
if ($oElement->hasAttribute('data-x-style-url'))
{
$sTemp = \trim($oElement->getAttribute('data-x-style-url'));
}
$sTemp = empty($sTemp) ? '' : (';' === \substr($sTemp, -1) ? $sTemp.' ' : $sTemp.'; ');
$oElement->setAttribute('data-x-style-url', \trim($sTemp.
('background' === $sName ? 'background-image' : $sName).': '.$sFullUrl, ' ;'));
}
else if ('data:image/' !== \strtolower(\substr(\trim($sUrl), 0, 11)))
{
$oElement->setAttribute('data-x-broken-style-src', $sFullUrl);
}
}
}
if (!empty($sStyleItem))
{
$aOutStyles[] = $sStyleItem;
}
}
else if ('height' === $sName)
{
// $aOutStyles[] = 'min-'.ltrim($sStyleItem);
$aOutStyles[] = $sStyleItem;
}
else
{
$aOutStyles[] = $sStyleItem;
}
}
return \implode(';', $aOutStyles);
}
/**
* @param string $sHtml
* @param bool $bHasExternals
* @param array $aFoundCIDs
*
* @return string
*/
public static function ClearHtml($sHtml, &$bHasExternals = false, &$aFoundCIDs = array())
{
$sHtml = null === $sHtml ? '' : (string) $sHtml;
$sHtml = \trim($sHtml);
if (0 === \strlen($sHtml))
{
return '';
}
$bHasExternals = false;
$sHtml = \MailSo\Base\HtmlUtils::ClearTags($sHtml);
$sHtml = \MailSo\Base\HtmlUtils::ClearOn($sHtml);
$sHtml = \MailSo\Base\HtmlUtils::ClearBodyAndHtmlTag($sHtml);
// Dom Part
$oDom = \MailSo\Base\HtmlUtils::GetDomFromText($sHtml);
unset($sHtml);
if ($oDom)
{
$aNodes = $oDom->getElementsByTagName('*');
foreach ($aNodes as /* @var $oElement \DOMElement */ $oElement)
{
$sTagNameLower = \strtolower($oElement->tagName);
if ('iframe' === $sTagNameLower || 'frame' === $sTagNameLower)
{
$oElement->setAttribute('src', 'javascript:false');
}
if (\in_array($sTagNameLower, array('a', 'form', 'area')))
{
$oElement->setAttribute('target', '_blank');
}
if (\in_array($sTagNameLower, array('a', 'form', 'area', 'input', 'button', 'textarea')))
{
$oElement->setAttribute('tabindex', '-1');
}
// if ('blockquote' === $sTagNameLower)
// {
// $oElement->removeAttribute('style');
// }
@$oElement->removeAttribute('id');
@$oElement->removeAttribute('class');
@$oElement->removeAttribute('contenteditable');
@$oElement->removeAttribute('designmode');
@$oElement->removeAttribute('data-bind');
if ($oElement->hasAttribute('src'))
{
$sSrc = \trim($oElement->getAttribute('src'));
$oElement->removeAttribute('src');
if ('cid:' === \strtolower(\substr($sSrc, 0, 4)))
{
$oElement->setAttribute('data-x-src-cid', \substr($sSrc, 4));
$aFoundCIDs[] = \substr($sSrc, 4);
}
else
{
if (\preg_match('/http[s]?:\/\//i', $sSrc))
{
$oElement->setAttribute('data-x-src', $sSrc);
$bHasExternals = true;
}
else if ('data:image/' === \strtolower(\substr(\trim($sSrc), 0, 11)))
{
$oElement->setAttribute('src', $sSrc);
}
else
{
$oElement->setAttribute('data-x-broken-src', $sSrc);
}
}
}
$sBackground = $oElement->hasAttribute('background')
? \trim($oElement->getAttribute('background')) : '';
$sBackgroundColor = $oElement->hasAttribute('bgcolor')
? \trim($oElement->getAttribute('bgcolor')) : '';
if (!empty($sBackground) || !empty($sBackgroundColor))
{
$aStyles = array();
$sStyles = $oElement->hasAttribute('style')
? $oElement->getAttribute('style') : '';
if (!empty($sBackground))
{
$aStyles[] = 'background-image: url(\''.$sBackground.'\')';
$oElement->removeAttribute('background');
}
if (!empty($sBackgroundColor))
{
$aStyles[] = 'background-color: '.$sBackgroundColor;
$oElement->removeAttribute('bgcolor');
}
$oElement->setAttribute('style', (empty($sStyles) ? '' : $sStyles.'; ').\implode('; ', $aStyles));
}
if ($oElement->hasAttribute('style'))
{
$oElement->setAttribute('style',
\MailSo\Base\HtmlUtils::ClearStyle($oElement->getAttribute('style'), $oElement, $bHasExternals, $aFoundCIDs));
}
}
$sResult = $oDom->saveHTML();
}
unset($oDom);
$sResult = \MailSo\Base\HtmlUtils::ClearTags($sResult);
$sResult = \MailSo\Base\HtmlUtils::ClearBodyAndHtmlTag($sResult);
return \trim($sResult);
}
/**
* @param string $sHtml
* @param array $aFoundCids = array()
*
* @return string
*/
public static function BuildHtml($sHtml, &$aFoundCids = array())
{
$oDom = \MailSo\Base\HtmlUtils::GetDomFromText($sHtml);
unset($sHtml);
$aNodes = $oDom->getElementsByTagName('*');
foreach ($aNodes as /* @var $oElement \DOMElement */ $oElement)
{
if ($oElement->hasAttribute('data-x-src-cid'))
{
$sCid = $oElement->getAttribute('data-x-src-cid');
$oElement->removeAttribute('data-x-src-cid');
if (!empty($sCid))
{
$aFoundCids[] = $sCid;
@$oElement->removeAttribute('src');
$oElement->setAttribute('src', 'cid:'.$sCid);
}
}
if ($oElement->hasAttribute('data-x-broken-src'))
{
$oElement->setAttribute('src', $oElement->getAttribute('data-x-broken-src'));
$oElement->removeAttribute('data-x-broken-src');
}
if ($oElement->hasAttribute('data-x-src'))
{
$oElement->setAttribute('src', $oElement->getAttribute('data-x-src'));
$oElement->removeAttribute('data-x-src');
}
if ($oElement->hasAttribute('data-x-href'))
{
$oElement->setAttribute('href', $oElement->getAttribute('data-x-href'));
$oElement->removeAttribute('data-x-href');
}
if ($oElement->hasAttribute('data-x-style-cid-name') && $oElement->hasAttribute('data-x-style-cid'))
{
$sCidName = $oElement->getAttribute('data-x-style-cid-name');
$sCid = $oElement->getAttribute('data-x-style-cid');
$oElement->removeAttribute('data-x-style-cid-name');
$oElement->removeAttribute('data-x-style-cid');
if (!empty($sCidName) && !empty($sCid) && \in_array($sCidName,
array('background-image', 'background', 'list-style-image', 'content')))
{
$sStyles = '';
if ($oElement->hasAttribute('style'))
{
$sStyles = \trim(\trim($oElement->getAttribute('style')), ';');
}
$sBack = $sCidName.': url(cid:'.$sCid.')';
$sStyles = \preg_replace('/'.\preg_quote($sCidName, '/').':\s?[^;]+/i', $sBack, $sStyles);
if (false === \strpos($sStyles, $sBack))
{
$sStyles .= empty($sStyles) ? '': '; ';
$sStyles .= $sBack;
}
$oElement->setAttribute('style', $sStyles);
$aFoundCids[] = $sCid;
}
}
if ($oElement->hasAttribute('data-x-style-url'))
{
$sAddStyles = $oElement->getAttribute('data-x-style-url');
$oElement->removeAttribute('data-x-style-url');
if (!empty($sAddStyles))
{
$sStyles = '';
if ($oElement->hasAttribute('style'))
{
$sStyles = \trim(\trim($oElement->getAttribute('style')), ';');
}
$oElement->setAttribute('style', (empty($sStyles) ? '' : $sStyles.'; ').$sAddStyles);
}
}
}
$sResult = $oDom->saveHTML();
unset($oDom);
$sResult = \MailSo\Base\HtmlUtils::ClearTags($sResult);
$sResult = \MailSo\Base\HtmlUtils::ClearBodyAndHtmlTag($sResult);
return '<!DOCTYPE html><html'.(\MailSo\Base\Utils::IsRTL($sResult) ? ' dir="rtl"' : ' dir="ltr"').'><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><head>'.
'<body>'.\trim($sResult).'</body></html>';
}
/**
* @param string $sText
* @param bool $bLinksWithTargetBlank = true
*
* @return string
*/
public static function ConvertPlainToHtml($sText, $bLinksWithTargetBlank = true)
{
$sText = \trim($sText);
if (0 === \strlen($sText))
{
return '';
}
$sText = \MailSo\Base\LinkFinder::NewInstance()
->Text($sText)
->UseDefaultWrappers($bLinksWithTargetBlank)
// ->CompileText(true, false);
->CompileText(true, true);
$sText = \str_replace("\r", '', $sText);
$aText = \explode("\n", $sText);
unset($sText);
$bIn = false;
$bDo = true;
do
{
$bDo = false;
$aNextText = array();
foreach ($aText as $sTextLine)
{
$bStart = 0 === \strpos(\ltrim($sTextLine), '&gt;');
if ($bStart && !$bIn)
{
$bDo = true;
$bIn = true;
$aNextText[] = '<blockquote>';
$aNextText[] = \substr(\ltrim($sTextLine), 4);
}
else if (!$bStart && $bIn)
{
$bIn = false;
$aNextText[] = '</blockquote>';
$aNextText[] = $sTextLine;
}
else if ($bStart && $bIn)
{
$aNextText[] = \substr(\ltrim($sTextLine), 4);
}
else
{
$aNextText[] = $sTextLine;
}
}
if ($bIn)
{
$bIn = false;
$aNextText[] = '</blockquote>';
}
$aText = $aNextText;
}
while ($bDo);
$sText = \join("\n", $aText);
unset($aText);
$sText = \preg_replace('/[\n][ ]+/', "\n", $sText);
// $sText = \preg_replace('/[\s]+([\s])/', '\\1', $sText);
$sText = \preg_replace('/<blockquote>[\s]+/i', '<blockquote>', $sText);
$sText = \preg_replace('/[\s]+<\/blockquote>/i', '</blockquote>', $sText);
$sText = \preg_replace('/<\/blockquote>([\n]{0,2})<blockquote>/i', '\\1', $sText);
$sText = \preg_replace('/[\n]{3,}/', "\n\n", $sText);
$sText = \strtr($sText, array(
"\n" => "<br />",
"\t" => '&nbsp;&nbsp;&nbsp;',
' ' => '&nbsp;&nbsp;'
));
return $sText;
}
/**
* @param string $sText
*
* @return string
*/
public static function ConvertHtmlToPlain($sText)
{
$sText = trim(stripslashes($sText));
$sText = preg_replace('/[\s]+/', ' ', $sText);
$sText = preg_replace(array(
"/\r/",
"/[\n\t]+/",
'/<script[^>]*>.*?<\/script>/i',
'/<style[^>]*>.*?<\/style>/i',
'/<title[^>]*>.*?<\/title>/i',
'/<h[123][^>]*>(.+?)<\/h[123]>/i',
'/<h[456][^>]*>(.+?)<\/h[456]>/i',
'/<p[^>]*>/i',
'/<br[^>]*>/i',
'/<b[^>]*>(.+?)<\/b>/i',
'/<i[^>]*>(.+?)<\/i>/i',
'/(<ul[^>]*>|<\/ul>)/i',
'/(<ol[^>]*>|<\/ol>)/i',
'/<li[^>]*>/i',
'/<a[^>]*href="([^"]+)"[^>]*>(.+?)<\/a>/i',
'/<hr[^>]*>/i',
'/(<table[^>]*>|<\/table>)/i',
'/(<tr[^>]*>|<\/tr>)/i',
'/<td[^>]*>(.+?)<\/td>/i',
'/<th[^>]*>(.+?)<\/th>/i',
'/&nbsp;/i',
'/&quot;/i',
'/&gt;/i',
'/&lt;/i',
'/&amp;/i',
'/&copy;/i',
'/&trade;/i',
'/&#8220;/',
'/&#8221;/',
'/&#8211;/',
'/&#8217;/',
'/&#38;/',
'/&#169;/',
'/&#8482;/',
'/&#151;/',
'/&#147;/',
'/&#148;/',
'/&#149;/',
'/&reg;/i',
'/&bull;/i',
'/&[&;]+;/i',
'/&#39;/',
'/&#160;/'
), array(
'',
' ',
'',
'',
'',
"\n\n\\1\n\n",
"\n\n\\1\n\n",
"\n\n\t",
"\n",
'\\1',
'\\1',
"\n\n",
"\n\n",
"\n\t* ",
'\\2 (\\1)',
"\n------------------------------------\n",
"\n",
"\n",
"\t\\1\n",
"\t\\1\n",
' ',
'"',
'>',
'<',
'&',
'(c)',
'(tm)',
'"',
'"',
'-',
"'",
'&',
'(c)',
'(tm)',
'--',
'"',
'"',
'*',
'(R)',
'*',
'',
'\'',
''
), $sText);
$sText = str_ireplace('<div>',"\n<div>", $sText);
$sText = strip_tags($sText, '');
$sText = preg_replace("/\n\\s+\n/", "\n", $sText);
$sText = preg_replace("/[\n]{3,}/", "\n\n", $sText);
return trim($sText);
}
}

View file

@ -0,0 +1,583 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
class Http
{
/**
* @var bool
*/
private $bIsMagicQuotesOn;
/**
* @access private
*/
private function __construct()
{
$this->bIsMagicQuotesOn = (bool) @\ini_get('magic_quotes_gpc');
}
/**
* @return \MailSo\Base\Http
*/
public static function NewInstance()
{
return new self();
}
/**
* @staticvar \MailSo\Base\Http $oInstance;
*
* @return \MailSo\Base\Http
*/
public static function SingletonInstance()
{
static $oInstance = null;
if (null === $oInstance)
{
$oInstance = self::NewInstance();
}
return $oInstance;
}
/**
* @param string $sKey
*
* @return bool
*/
public function HasQuery($sKey)
{
return isset($_GET[$sKey]);
}
/**
* @param string $sKey
* @param mixed $mDefault = null
* @param bool $bClearPercZeroZero = true
*
* @return mixed
*/
public function GetQuery($sKey, $mDefault = null, $bClearPercZeroZero = true)
{
return isset($_GET[$sKey]) ? \MailSo\Base\Utils::StripSlashesValue($_GET[$sKey], $bClearPercZeroZero) : $mDefault;
}
/**
* @return array|null
*/
public function GetQueryAsArray()
{
return isset($_GET) && \is_array($_GET) ? \MailSo\Base\Utils::StripSlashesValue($_GET, true) : null;
}
/**
* @param string $sKey
*
* @return bool
*/
public function HasPost($sKey)
{
return isset($_POST[$sKey]);
}
/**
* @param string $sKey
* @param mixed $mDefault = null
* @param bool $bClearPercZeroZero = false
*
* @return mixed
*/
public function GetPost($sKey, $mDefault = null, $bClearPercZeroZero = false)
{
return isset($_POST[$sKey]) ? \MailSo\Base\Utils::StripSlashesValue($_POST[$sKey], $bClearPercZeroZero) : $mDefault;
}
/**
* @return array|null
*/
public function GetPostAsArray()
{
return isset($_POST) && \is_array($_POST) ? \MailSo\Base\Utils::StripSlashesValue($_POST, false) : null;
}
/**
* @param string $sKey
*
* @return bool
*/
public function HasRequest($sKey)
{
return isset($_REQUEST[$sKey]);
}
/**
* @param string $sKey
* @param mixed $mDefault = null
*
* @return mixed
*/
public function GetRequest($sKey, $mDefault = null)
{
return isset($_REQUEST[$sKey]) ? \MailSo\Base\Utils::StripSlashesValue($_REQUEST[$sKey]) : $mDefault;
}
/**
* @param string $sKey
*
* @return bool
*/
public function HasServer($sKey)
{
return isset($_SERVER[$sKey]);
}
/**
* @param string $sKey
* @param mixed $mDefault = null
*
* @return mixed
*/
public function GetServer($sKey, $mDefault = null)
{
return isset($_SERVER[$sKey]) ? $_SERVER[$sKey] : $mDefault;
}
/**
* @param string $sKey
*
* @return bool
*/
public function HasEnv($sKey)
{
return isset($_ENV[$sKey]);
}
/**
* @param string $sKey
* @param mixed $mDefault = null
*
* @return mixed
*/
public function GetEnv($sKey, $mDefault = null)
{
return isset($_ENV[$sKey]) ? $_ENV[$sKey] : $mDefault;
}
/**
* @return string
*/
public function ServerProtocol()
{
return $this->GetServer('SERVER_PROTOCOL', 'HTTP/1.0');
}
/**
* @return string
*/
public function GetMethod()
{
return $this->GetServer('REQUEST_METHOD', '');
}
/**
* @return bool
*/
public function IsPost()
{
return ('POST' === $this->GetMethod());
}
/**
* @return bool
*/
public function IsGet()
{
return ('GET' === $this->GetMethod());
}
/**
* @return string
*/
public function GetQueryString()
{
return $this->GetServer('QUERY_STRING', '');
}
/**
* @return bool
*/
public function CheckLocalhost($sServer)
{
return \in_array(\strtolower(\trim($sServer)), array(
'localhost', '127.0.0.1', '::1', '::1/128', '0:0:0:0:0:0:0:1'
));
}
/**
* @return bool
*/
public function IsLocalhost()
{
return $this->CheckLocalhost($this->GetServer('REMOTE_ADDR', ''));
}
/**
* @return string
*/
public function GetRawBody()
{
static $sRawBody = null;
if (null === $sRawBody)
{
$sBody = @\file_get_contents('php://input');
$sRawBody = (false !== $sBody) ? $sBody : '';
}
return $sRawBody;
}
/**
* @param string $sHeader
*
* @return string
*/
public function GetHeader($sHeader)
{
$sResultHeader = '';
$sServerKey = 'HTTP_'.\strtoupper(\str_replace('-', '_', $sHeader));
$sResultHeader = $this->GetServer($sServerKey, '');
if (0 === \strlen($sResultHeader) &&
\MailSo\Base\Utils::FunctionExistsAndEnabled('apache_request_headers'))
{
$sHeaders = \apache_request_headers();
if (isset($sHeaders[$sHeader]))
{
$sResultHeader = $sHeaders[$sHeader];
}
}
return $sResultHeader;
}
/**
* @return string
*/
public function GetScheme()
{
return ('on' === \strtolower($this->GetServer('HTTPS'))) ? 'https' : 'http';
}
/**
* @return bool
*/
public function IsSecure()
{
return ('https' === $this->GetScheme());
}
/**
* @param bool $bWithRemoteUserData = false
* @param bool $bRemoveWWW = true
*
* @return string
*/
public function GetHost($bWithRemoteUserData = false, $bRemoveWWW = true)
{
$sHost = $this->GetServer('HTTP_HOST', '');
if (0 === \strlen($sHost))
{
$sScheme = $this->GetScheme();
$sName = $this->GetServer('SERVER_NAME');
$iPort = (int) $this->GetServer('SERVER_PORT');
$sHost = (('http' === $sScheme && 80 === $iPort) || ('https' === $sScheme && 443 === $iPort))
? $sName : $sName.':'.$iPort;
}
if ($bRemoveWWW)
{
$sHost = 'www.' === \substr(\strtolower($sHost), 0, 4) ? \substr($sHost, 0, 4) : $sHost;
}
if ($bWithRemoteUserData)
{
$sUser = \trim($this->HasServer('REMOTE_USER') ? $this->GetServer('REMOTE_USER', '') : '');
$sHost = (0 < \strlen($sUser) ? $sUser.'@' : '').$sHost;
}
return $sHost;
}
/**
* @param bool $bCheckProxy = true
*
* @return string
*/
public function GetClientIp($bCheckProxy = true)
{
$sIp = '';
if ($bCheckProxy && null !== $this->GetServer('HTTP_CLIENT_IP', null))
{
$sIp = $this->GetServer('HTTP_CLIENT_IP', '');
}
else if ($bCheckProxy && null !== $this->GetServer('HTTP_X_FORWARDED_FOR', null))
{
$sIp = $this->GetServer('HTTP_X_FORWARDED_FOR', '');
}
else
{
$sIp = $this->GetServer('REMOTE_ADDR', '');
}
return $sIp;
}
/**
* @param string $sUrl
* @param array $aPost = array()
* @param string $sCustomUserAgent = 'MaiSo Http User Agent (v1)'
* @param int $iCode = 0
* @param \MailSo\Log\Logger $oLogger = null
*
* @return string|bool
*/
public function SendPostRequest($sUrl, $aPost = array(), $sCustomUserAgent = 'MaiSo Http User Agent (v1)', &$iCode = 0, $oLogger = null)
{
$aOptions = array(
CURLOPT_URL => $sUrl,
CURLOPT_HEADER => false,
CURLOPT_FAILONERROR => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $aPost,
CURLOPT_TIMEOUT => 20
);
if (0 < \strlen($sCustomUserAgent))
{
$aOptions[CURLOPT_USERAGENT] = $sCustomUserAgent;
}
$oCurl = \curl_init();
\curl_setopt_array($oCurl, $aOptions);
if ($oLogger)
{
$oLogger->Write('cURL: Send post request: '.$sUrl);
}
$mResult = \curl_exec($oCurl);
$iCode = (int) \curl_getinfo($oCurl, CURLINFO_HTTP_CODE);
$sContentType = (string) \curl_getinfo($oCurl, CURLINFO_CONTENT_TYPE);
if ($oLogger)
{
$oLogger->Write('cURL: Post request result: (Status: '.$iCode.', ContentType: '.$sContentType.')');
if (false === $mResult || 200 !== $iCode)
{
$oLogger->Write('cURL: Error: '.\curl_error($oCurl), \MailSo\Log\Enumerations\Type::WARNING);
}
}
if (\is_resource($oCurl))
{
\curl_close($oCurl);
}
return $mResult;
}
/**
* @param string $sUrl
* @param resource $rFile
* @param string $sCustomUserAgent = 'MaiSo Http User Agent (v1)'
* @param string $sContentType = ''
* @param int $iCode = 0
* @param \MailSo\Log\Logger $oLogger = null
*
* @return bool
*/
public function SaveUrlToFile($sUrl, $rFile, $sCustomUserAgent = 'MaiSo Http User Agent (v1)', &$sContentType = '', &$iCode = 0, $oLogger = null)
{
if (!is_resource($rFile))
{
if ($oLogger)
{
$oLogger->Write('cURL: input resource invalid.', \MailSo\Log\Enumerations\Type::WARNING);
}
return false;
}
$aOptions = array(
CURLOPT_URL => $sUrl,
CURLOPT_HEADER => false,
CURLOPT_FAILONERROR => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FILE => $rFile,
CURLOPT_TIMEOUT => 10
);
if (0 < \strlen($sCustomUserAgent))
{
$aOptions[CURLOPT_USERAGENT] = $sCustomUserAgent;
}
$oCurl = \curl_init();
\curl_setopt_array($oCurl, $aOptions);
if ($oLogger)
{
$oLogger->Write('cURL: Send request: '.$sUrl);
}
$bResult = \curl_exec($oCurl);
$iCode = (int) \curl_getinfo($oCurl, CURLINFO_HTTP_CODE);
$sContentType = (string) \curl_getinfo($oCurl, CURLINFO_CONTENT_TYPE);
if ($oLogger)
{
$oLogger->Write('cURL: Request result: '.($bResult ? 'true' : 'false').' (Status: '.$iCode.', ContentType: '.$sContentType.')');
if (!$bResult || 200 !== $iCode)
{
$oLogger->Write('cURL: Error: '.\curl_error($oCurl), \MailSo\Log\Enumerations\Type::WARNING);
}
}
if (\is_resource($oCurl))
{
\curl_close($oCurl);
}
return $bResult;
}
/**
* @param string $sUrl
* @param string $sCustomUserAgent = 'MaiSo Http User Agent (v1)'
* @param string $sContentType = ''
* @param int $iCode = 0
* @param \MailSo\Log\Logger $oLogger = null
*
* @return string|bool
*/
public function GetUrlAsString($sUrl, $sCustomUserAgent = 'MaiSo Http User Agent (v1)', &$sContentType = '', &$iCode = 0, $oLogger = null)
{
$rMemFile = \MailSo\Base\ResourceRegistry::CreateMemoryResource();
if ($this->SaveUrlToFile($sUrl, $rMemFile, $sCustomUserAgent, $sContentType, $iCode, $oLogger) && \is_resource($rMemFile))
{
\rewind($rMemFile);
return \stream_get_contents($rMemFile);
}
return false;
}
/**
* @param int $iExpireTime
* @param bool $bSetCacheHeader = true
* @param string $sEtag = ''
*
* @return bool
*/
public function ServerNotModifiedCache($iExpireTime, $bSetCacheHeader = true, $sEtag = '')
{
$bResult = false;
if (0 < $iExpireTime)
{
$iUtcTimeStamp = \time();
$sIfModifiedSince = $this->GetHeader('If-Modified-Since', '');
if (0 === \strlen($sIfModifiedSince))
{
if ($bSetCacheHeader)
{
\header('Cache-Control: public', true);
\header('Pragma: public', true);
\header('Last-Modified: '.\gmdate('D, d M Y H:i:s', $iUtcTimeStamp - $iExpireTime).' UTC', true);
\header('Expires: '.\gmdate('D, j M Y H:i:s', $iUtcTimeStamp + $iExpireTime).' UTC', true);
if (0 < strlen($sEtag))
{
\header('Etag: '.$sEtag, true);
}
}
}
else
{
$this->StatusHeader(304);
$bResult = true;
}
}
return $bResult;
}
/**
* @param int $iStatus
*
* @return void
*/
public function StatusHeader($iStatus, $sCustomStatusText = '')
{
switch ($iStatus)
{
default:
\header('Status: '.$iStatus, true, $iStatus);
break;
case 304:
\header($this->ServerProtocol().' 304 '.(0 === \strlen($sCustomStatusText) ? 'Not Modified' : $sCustomStatusText), true, $iStatus);
break;
case 200:
\header($this->ServerProtocol().' 200 '.(0 === \strlen($sCustomStatusText) ? 'OK' : $sCustomStatusText), true, $iStatus);
break;
case 401:
\header($this->ServerProtocol().' 401 '.(0 === \strlen($sCustomStatusText) ? 'Please sign in' : $sCustomStatusText), true, $iStatus);
break;
case 404:
\header($this->ServerProtocol().' 404 '.(0 === \strlen($sCustomStatusText) ? 'Not Found' : $sCustomStatusText), true, $iStatus);
break;
}
}
/**
* @return string
*/
public function GetPath()
{
$sUrl = \ltrim(\substr($this->GetServer('SCRIPT_NAME', ''), 0, \strrpos($this->GetServer('SCRIPT_NAME', ''), '/')), '/');
return '' === $sUrl ? '/' : '/'.$sUrl.'/';
}
/**
* @return string
*/
public function GetUrl()
{
return '/'.$this->GetServer('REQUEST_URI', '');
}
/**
* @return string
*/
public function GetFullUrl()
{
return $this->GetScheme().'://'.$this->GetHost(true, false).$this->GetPath();
}
/**
* @return string
*/
public function GetFullUrlWithQuery()
{
return $this->GetScheme().'://'.$this->GetHost(true, false).$this->GetUrl();
}
}

View file

@ -0,0 +1,323 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
class LinkFinder
{
/**
* @const
*/
const OPEN_LINK = '@#@link{';
const CLOSE_LINK = '}link@#@';
/**
* @var array
*/
private $aPrepearPlainStringUrls;
/**
* @var string
*/
private $sText;
/**
* @var mixed
*/
private $fLinkWrapper;
/**
* @var int
*/
private $iHtmlSpecialCharsFlags;
/**
* @var mixed
*/
private $fMailWrapper;
/**
* @access private
*/
private function __construct()
{
$this->iHtmlSpecialCharsFlags = (\defined('ENT_QUOTES') && \defined('ENT_SUBSTITUTE') && \defined('ENT_HTML401'))
? ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 : ENT_QUOTES;
if (\defined('ENT_IGNORE'))
{
$this->iHtmlSpecialCharsFlags |= ENT_IGNORE;
}
$this->Clear();
}
/**
* @return \MailSo\Base\LinkFinder
*/
public static function NewInstance()
{
return new self();
}
/**
* @return \MailSo\Base\LinkFinder
*/
public function Clear()
{
$this->aPrepearPlainStringUrls = array();
$this->fLinkWrapper = null;
$this->fMailWrapper = null;
$this->sText = '';
return $this;
}
/**
* @param string $sText
*
* @return \MailSo\Base\LinkFinder
*/
public function Text($sText)
{
$this->sText = $sText;
return $this;
}
/**
* @param mixed $fLinkWrapper
*
* @return \MailSo\Base\LinkFinder
*/
public function LinkWrapper($fLinkWrapper)
{
$this->fLinkWrapper = $fLinkWrapper;
return $this;
}
/**
* @param mixed $fMailWrapper
*
* @return \MailSo\Base\LinkFinder
*/
public function MailWrapper($fMailWrapper)
{
$this->fMailWrapper = $fMailWrapper;
return $this;
}
/**
* @param bool $bAddTargetBlank = false
*
* @return \MailSo\Base\LinkFinder
*/
public function UseDefaultWrappers($bAddTargetBlank = false)
{
$this->fLinkWrapper = function ($sLink, $bShortLink = false) use ($bAddTargetBlank) {
if ($bShortLink && \in_array(\strtolower($sLink), array('asp.net', 'vb.net', 'mailbee.net')))
{
return $sLink;
}
$sNameLink = $sLink;
if (!\preg_match('/^[a-z]{3,5}\:\/\//i', \ltrim($sLink)))
{
$sLink = 'http://'.\ltrim($sLink);
}
return '<a '.($bAddTargetBlank ? 'target="_blank" ': '').'href="'.$sLink.'">'.$sNameLink.'</a>';
};
$this->fMailWrapper = function ($sEmail) use ($bAddTargetBlank) {
return '<a '.($bAddTargetBlank ? 'target="_blank" ': '').'href="mailto:'.$sEmail.'">'.$sEmail.'</a>';
};
return $this;
}
/**
* @param bool $bUseHtmlSpecialChars = true
* @param bool $bFindShortLinks = true
*
* @return string
*/
public function CompileText($bUseHtmlSpecialChars = true, $bFindShortLinks = true)
{
$sText = $this->sText;
$this->aPrepearPlainStringUrls = array();
if (null !== $this->fLinkWrapper && \is_callable($this->fLinkWrapper))
{
$sText = $this->findLinks($sText, $this->fLinkWrapper);
}
if (null !== $this->fMailWrapper && \is_callable($this->fMailWrapper))
{
$sText = $this->findMails($sText, $this->fMailWrapper);
}
if ($bFindShortLinks && null !== $this->fLinkWrapper && \is_callable($this->fLinkWrapper))
{
$sText = $this->findShortLinks($sText, $this->fLinkWrapper);
}
if ($bUseHtmlSpecialChars)
{
$sText = @\htmlentities($sText, $this->iHtmlSpecialCharsFlags, 'UTF-8');
}
if (0 < \count($this->aPrepearPlainStringUrls))
{
for ($iIndex = 0, $iLen = \count($this->aPrepearPlainStringUrls); $iIndex < $iLen; $iIndex++)
{
$sText = \str_replace(\MailSo\Base\LinkFinder::OPEN_LINK.$iIndex.
\MailSo\Base\LinkFinder::CLOSE_LINK, $this->aPrepearPlainStringUrls[$iIndex], $sText);
}
$this->aPrepearPlainStringUrls = array();
}
return $sText;
}
/**
* @param string $sText
* @param mixed $fWrapper
*
* @return string
*/
private function findLinks($sText, $fWrapper)
{
$sPattern = '/([\W]|^)((?:https?:\/\/)|(?:svn:\/\/)|(?:git:\/\/)|(?:s?ftps?:\/\/)|(?:www\.))'.
'((\S+?)(\\/)?)((?:&gt;)?|[^\w\=\\/;\(\)\[\]]*?)(?=<|\s|$)/imu';
$aPrepearPlainStringUrls = $this->aPrepearPlainStringUrls;
$sText = \preg_replace_callback($sPattern, function ($aMatch) use ($fWrapper, &$aPrepearPlainStringUrls) {
if (\is_array($aMatch) && 6 < \count($aMatch))
{
while (\in_array($sChar = \substr($aMatch[3], -1), array(']', ')')))
{
if (\substr_count($aMatch[3], ']' === $sChar ? '[': '(') - \substr_count($aMatch[3], $sChar) < 0)
{
$aMatch[3] = \substr($aMatch[3], 0, -1);
$aMatch[6] = (']' === $sChar ? ']': ')').$aMatch[6];
}
else
{
break;
}
}
$sLinkWithWrap = \call_user_func($fWrapper, $aMatch[2].$aMatch[3]);
if (\is_string($sLinkWithWrap) && 0 < \strlen($sLinkWithWrap))
{
$aPrepearPlainStringUrls[] = \stripslashes($sLinkWithWrap);
return $aMatch[1].
\MailSo\Base\LinkFinder::OPEN_LINK.
(\count($aPrepearPlainStringUrls) - 1).
\MailSo\Base\LinkFinder::CLOSE_LINK.
$aMatch[6];
}
return $aMatch[0];
}
return '';
}, $sText);
if (0 < \count($aPrepearPlainStringUrls))
{
$this->aPrepearPlainStringUrls = $aPrepearPlainStringUrls;
}
return $sText;
}
/**
* @param string $sText
* @param mixed $fWrapper
*
* @return string
*/
private function findShortLinks($sText, $fWrapper)
{
$sPattern = '/([a-z0-9-\.]+\.(?:com|org|net|ru))([^a-z0-9-\.])/i';
$aPrepearPlainStringUrls = $this->aPrepearPlainStringUrls;
$sText = \preg_replace_callback($sPattern, function ($aMatch) use ($fWrapper, &$aPrepearPlainStringUrls) {
if (\is_array($aMatch) && 2 < \count($aMatch) && isset($aMatch[1]) && 0 < \strlen($aMatch[1]))
{
$sLinkWithWrap = \call_user_func_array($fWrapper, array($aMatch[1], true));
if (\is_string($sLinkWithWrap))
{
$aPrepearPlainStringUrls[] = \stripslashes($sLinkWithWrap);
return \MailSo\Base\LinkFinder::OPEN_LINK.
(\count($aPrepearPlainStringUrls) - 1).
\MailSo\Base\LinkFinder::CLOSE_LINK.
$aMatch[2];
}
return $aMatch[0];
}
return '';
}, $sText);
if (0 < \count($aPrepearPlainStringUrls))
{
$this->aPrepearPlainStringUrls = $aPrepearPlainStringUrls;
}
return $sText;
}
/**
* @param string $sText
* @param mixed $fWrapper
*
* @return string
*/
private function findMails($sText, $fWrapper)
{
$sPattern = '/([\w\.!#\$%\-+.]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)+)/';
$aPrepearPlainStringUrls = $this->aPrepearPlainStringUrls;
$sText = \preg_replace_callback($sPattern, function ($aMatch) use ($fWrapper, &$aPrepearPlainStringUrls) {
if (\is_array($aMatch) && isset($aMatch[1]))
{
$sMailWithWrap = \call_user_func($fWrapper, $aMatch[1]);
if (\is_string($sMailWithWrap) && 0 < \strlen($sMailWithWrap))
{
$aPrepearPlainStringUrls[] = \stripslashes($sMailWithWrap);
return \MailSo\Base\LinkFinder::OPEN_LINK.
(\count($aPrepearPlainStringUrls) - 1).
\MailSo\Base\LinkFinder::CLOSE_LINK;
}
return $aMatch[1];
}
return '';
}, $sText);
if (0 < \count($aPrepearPlainStringUrls))
{
$this->aPrepearPlainStringUrls = $aPrepearPlainStringUrls;
}
return $sText;
}
}

View file

@ -0,0 +1,112 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
class Loader
{
/**
* @var bool
*/
public static $StoreStatistic = true;
/**
* @var array
*/
private static $aIncStatistic = array();
/**
* @var array
*/
private static $aSetStatistic = array();
/**
* @staticvar bool $bIsInited
*
* @return void
*/
public static function Init()
{
static $bIsInited = false;
if (!$bIsInited)
{
$bIsInited = true;
self::SetStatistic('Inited', \microtime(true));
}
}
/**
* @param string $sName
* @param int $iIncSize = 1
*
* @return void
*/
public static function IncStatistic($sName, $iIncSize = 1)
{
if (self::$StoreStatistic)
{
self::$aIncStatistic[$sName] = isset(self::$aIncStatistic[$sName])
? self::$aIncStatistic[$sName] + $iIncSize : $iIncSize;
}
}
/**
* @param string $sName
* @param mixed $mValue
*
* @return void
*/
public static function SetStatistic($sName, $mValue)
{
if (self::$StoreStatistic)
{
self::$aSetStatistic[$sName] = $mValue;
}
}
/**
* @param string $sName
*
* @return mixed
*/
public static function GetStatistic($sName)
{
return self::$StoreStatistic && isset(self::$aSetStatistic[$sName]) ? self::$aSetStatistic[$sName] : null;
}
/**
* @return array|null
*/
public static function Statistic()
{
$aResult = null;
if (self::$StoreStatistic)
{
$aResult = array(
'php' => array(
'phpversion' => \phpversion(),
'ssl' => (int) \function_exists('openssl_open'),
'iconv' => (int) \function_exists('iconv')
));
if (\MailSo\Base\Utils::FunctionExistsAndEnabled('memory_get_usage') &&
\MailSo\Base\Utils::FunctionExistsAndEnabled('memory_get_peak_usage'))
{
$aResult['php']['memory_get_usage'] =
Utils::FormatFileSize(\memory_get_usage(true), 2);
$aResult['php']['memory_get_peak_usage'] =
Utils::FormatFileSize(\memory_get_peak_usage(true), 2);
}
self::SetStatistic('TimeDelta', \microtime(true) - self::GetStatistic('Inited'));
$aResult['statistic'] = self::$aSetStatistic;
$aResult['counts'] = self::$aIncStatistic;
}
return $aResult;
}
}

View file

@ -0,0 +1,116 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
class ResourceRegistry
{
/**
* @var array
*/
public static $Resources = array();
/**
* @access private
*/
private function __construct()
{
}
/**
* @staticvar bool $bInited
*
* @return void
*/
private static function regResourcesShutdownFunc()
{
static $bInited = false;
if (!$bInited)
{
$bInited = true;
\register_shutdown_function(function () {
if (\is_array(\MailSo\Base\ResourceRegistry::$Resources))
{
foreach (\array_keys(\MailSo\Base\ResourceRegistry::$Resources) as $sKey)
{
if (\is_resource(\MailSo\Base\ResourceRegistry::$Resources[$sKey]))
{
\MailSo\Base\Loader::IncStatistic('CloseMemoryResource');
\fclose(\MailSo\Base\ResourceRegistry::$Resources[$sKey]);
}
\MailSo\Base\ResourceRegistry::$Resources[$sKey] = null;
}
}
\MailSo\Base\ResourceRegistry::$Resources = array();
});
}
}
/**
* @param int $iMemoryMaxInMb = 5
*
* @return resource | bool
*/
public static function CreateMemoryResource($iMemoryMaxInMb = 5)
{
self::regResourcesShutdownFunc();
$oResult = @\fopen('php://temp/maxmemory:'.($iMemoryMaxInMb * 1024 * 1024), 'r+b');
if (\is_resource($oResult))
{
\MailSo\Base\Loader::IncStatistic('CreateMemoryResource');
\MailSo\Base\ResourceRegistry::$Resources[(string) $oResult] = $oResult;
return $oResult;
}
return false;
}
/**
* @param string $sString
*
* @return resource | bool
*/
public static function CreateMemoryResourceFromString($sString)
{
$oResult = self::CreateMemoryResource();
if (\is_resource($oResult))
{
\fwrite($oResult, $sString);
\rewind($oResult);
}
return $oResult;
}
/**
* @param resource $rResource
*
* @return void
*/
public static function CloseMemoryResource(&$rResource)
{
if (\is_resource($rResource))
{
$sKey = (string) $rResource;
if (isset(\MailSo\Base\ResourceRegistry::$Resources[$sKey]))
{
\fclose(\MailSo\Base\ResourceRegistry::$Resources[$sKey]);
\MailSo\Base\ResourceRegistry::$Resources[$sKey] = null;
unset(\MailSo\Base\ResourceRegistry::$Resources[$sKey]);
\MailSo\Base\Loader::IncStatistic('CloseMemoryResource');
}
if (\is_resource($rResource))
{
\fclose($rResource);
}
$rResource = null;
}
}
}

View file

@ -0,0 +1,368 @@
<?php
namespace MailSo\Base\StreamWrappers;
/**
* @category MailSo
* @package Base
* @subpackage StreamWrappers
*/
class Binary
{
/**
* @var string
*/
const STREAM_NAME = 'mailsobinary';
/**
* @var array
*/
private static $aStreams = array();
/**
* @var resource
*/
private $rStream;
/**
* @var string
*/
private $sFromEncoding;
/**
* @var string
*/
private $sToEncoding;
/**
* @var string
*/
private $sFunctionName;
/**
* @var int
*/
private $iPos;
/**
* @var string
*/
private $sBuffer;
/**
* @var string
*/
private $sReadEndBuffer;
/**
* @param string $sContentTransferEncoding
* @param bool $bDecode = true
*
* @return string
*/
public static function GetInlineDecodeOrEncodeFunctionName($sContentTransferEncoding, $bDecode = true)
{
$sFunctionName = '';
switch (strtolower($sContentTransferEncoding))
{
case \MailSo\Base\Enumerations\Encoding::BASE64_LOWER:
// InlineBase64Decode
$sFunctionName = $bDecode ? 'InlineBase64Decode' : 'convert.base64-encode';
break;
case \MailSo\Base\Enumerations\Encoding::QUOTED_PRINTABLE_LOWER:
// InlineQuotedPrintableDecode
$sFunctionName = $bDecode ? 'convert.quoted-printable-decode' : 'convert.quoted-printable-encode';
break;
}
return $sFunctionName;
}
/**
* @param string $sBodyString
* @param string $sEndBuffer
*
* @return string
*/
public static function InlineNullDecode($sBodyString, &$sEndBuffer)
{
$sEndBuffer = '';
return $sBodyString;
}
/**
* @param string $sBaseString
* @param string $sEndBuffer
*
* @return string
*/
public static function InlineBase64Decode($sBaseString, &$sEndBuffer)
{
$sEndBuffer = '';
$sBaseString = str_replace(array("\r", "\n", "\t"), '', $sBaseString);
$iBaseStringLen = strlen($sBaseString);
$iBaseStringNormFloorLen = floor($iBaseStringLen / 4) * 4;
if ($iBaseStringNormFloorLen < $iBaseStringLen)
{
$sEndBuffer = substr($sBaseString, $iBaseStringNormFloorLen);
$sBaseString = substr($sBaseString, 0, $iBaseStringNormFloorLen);
}
return \MailSo\Base\Utils::Base64Decode($sBaseString);
}
/**
* @param string $sQuotedPrintableString
* @param string $sEndBuffer
*
* @return string
*/
public static function InlineQuotedPrintableDecode($sQuotedPrintableString, &$sEndBuffer)
{
$sEndBuffer = '';
$sQuotedPrintableLen = strlen($sQuotedPrintableString);
$iLastSpace = strrpos($sQuotedPrintableString, ' ');
if (false !== $iLastSpace && $iLastSpace + 1 < $sQuotedPrintableLen)
{
$sEndBuffer = substr($sQuotedPrintableString, $iLastSpace + 1);
$sQuotedPrintableString = substr($sQuotedPrintableString, 0, $iLastSpace + 1);
}
return quoted_printable_decode($sQuotedPrintableString);
}
/**
* @param string $sEncodedString
* @param string $sEndBuffer
*
* @return string
*/
public static function InlineConvertDecode($sEncodedString, &$sEndBuffer, $sFromEncoding, $sToEncoding)
{
$sEndBuffer = '';
$sQuotedPrintableLen = strlen($sEncodedString);
$iLastSpace = strrpos($sEncodedString, ' ');
if (false !== $iLastSpace && $iLastSpace + 1 < $sQuotedPrintableLen)
{
$sEndBuffer = substr($sEncodedString, $iLastSpace + 1);
$sEncodedString = substr($sEncodedString, 0, $iLastSpace + 1);
}
return \MailSo\Base\Utils::ConvertEncoding($sEncodedString, $sFromEncoding, $sToEncoding);
}
/**
* @param resource $rStream
* @param string $sUtilsDecodeOrEncodeFunctionName = null
* @param string $sFromEncoding = null
* @param string $sToEncoding = null
*
* @return resource|bool
*/
public static function CreateStream($rStream,
$sUtilsDecodeOrEncodeFunctionName = null, $sFromEncoding = null, $sToEncoding = null)
{
if (!in_array(self::STREAM_NAME, stream_get_wrappers()))
{
stream_wrapper_register(self::STREAM_NAME, '\MailSo\Base\StreamWrappers\Binary');
}
if (null === $sUtilsDecodeOrEncodeFunctionName || 0 === strlen($sUtilsDecodeOrEncodeFunctionName))
{
$sUtilsDecodeOrEncodeFunctionName = 'InlineNullDecode';
}
$sHashName = md5(microtime(true).rand(1000, 9999));
if (null !== $sFromEncoding && null !== $sToEncoding && $sFromEncoding !== $sToEncoding)
{
$rStream = self::CreateStream($rStream, $sUtilsDecodeOrEncodeFunctionName);
$sUtilsDecodeOrEncodeFunctionName = 'InlineConvertDecode';
}
if (in_array($sUtilsDecodeOrEncodeFunctionName, array(
'convert.base64-decode', 'convert.base64-encode',
'convert.quoted-printable-decode', 'convert.quoted-printable-encode'
)))
{
$rFilter = \stream_filter_append($rStream, $sUtilsDecodeOrEncodeFunctionName,
STREAM_FILTER_READ, array(
'line-length' => \MailSo\Mime\Enumerations\Constants::LINE_LENGTH,
'line-break-chars' => \MailSo\Mime\Enumerations\Constants::CRLF
));
return \is_resource($rFilter) ? $rStream : false;
}
self::$aStreams[$sHashName] =
array($rStream, $sUtilsDecodeOrEncodeFunctionName, $sFromEncoding, $sToEncoding);
\MailSo\Base\Loader::IncStatistic('CreateStream/Binary');
return \fopen(self::STREAM_NAME.'://'.$sHashName, 'rb');
}
/**
* @param string $sPath
*
* @return bool
*/
public function stream_open($sPath)
{
$this->iPos = 0;
$this->sBuffer = '';
$this->sReadEndBuffer = '';
$this->rStream = false;
$this->sFromEncoding = null;
$this->sToEncoding = null;
$this->sFunctionName = null;
$bResult = false;
$aPath = parse_url($sPath);
if (isset($aPath['host']) && isset($aPath['scheme']) &&
0 < strlen($aPath['host']) && 0 < strlen($aPath['scheme']) &&
self::STREAM_NAME === $aPath['scheme'])
{
$sHashName = $aPath['host'];
if (isset(self::$aStreams[$sHashName]) &&
is_array(self::$aStreams[$sHashName]) &&
4 === count(self::$aStreams[$sHashName]))
{
$this->rStream = self::$aStreams[$sHashName][0];
$this->sFunctionName = self::$aStreams[$sHashName][1];
$this->sFromEncoding = self::$aStreams[$sHashName][2];
$this->sToEncoding = self::$aStreams[$sHashName][3];
}
$bResult = is_resource($this->rStream);
}
return $bResult;
}
/**
* @param int $iCount
*
* @return string
*/
public function stream_read($iCount)
{
$sReturn = '';
$sFunctionName = $this->sFunctionName;
if ($iCount > 0)
{
if ($iCount < strlen($this->sBuffer))
{
$sReturn = substr($this->sBuffer, 0, $iCount);
$this->sBuffer = substr($this->sBuffer, $iCount);
}
else
{
$sReturn = $this->sBuffer;
while ($iCount > 0)
{
if (feof($this->rStream))
{
if (0 === strlen($this->sBuffer.$sReturn))
{
return false;
}
if (0 < strlen($this->sReadEndBuffer))
{
$sReturn .= self::$sFunctionName($this->sReadEndBuffer,
$this->sReadEndBuffer, $this->sFromEncoding, $this->sToEncoding);
$iDecodeLen = strlen($sReturn);
}
$iCount = 0;
$this->sBuffer = '';
}
else
{
$sReadResult = fread($this->rStream, 8192);
if (false === $sReadResult)
{
return false;
}
$sReturn .= self::$sFunctionName($this->sReadEndBuffer.$sReadResult,
$this->sReadEndBuffer, $this->sFromEncoding, $this->sToEncoding);
$iDecodeLen = strlen($sReturn);
if ($iCount < $iDecodeLen)
{
$this->sBuffer = substr($sReturn, $iCount);
$sReturn = substr($sReturn, 0, $iCount);
$iCount = 0;
}
else
{
$iCount -= $iDecodeLen;
}
}
}
}
$this->iPos += strlen($sReturn);
return $sReturn;
}
return false;
}
/**
* @return int
*/
public function stream_write()
{
return 0;
}
/**
* @return int
*/
public function stream_tell()
{
return $this->iPos;
}
/**
* @return bool
*/
public function stream_eof()
{
return 0 === strlen($this->sBuffer) && feof($this->rStream);
}
/**
*
* @return array
*/
public function stream_stat()
{
return array(
'dev' => 2,
'ino' => 0,
'mode' => 33206,
'nlink' => 1,
'uid' => 0,
'gid' => 0,
'rdev' => 2,
'size' => 0,
'atime' => 1061067181,
'mtime' => 1056136526,
'ctime' => 1056136526,
'blksize' => -1,
'blocks' => -1
);
}
/**
* @return bool
*/
public function stream_seek()
{
return false;
}
}

View file

@ -0,0 +1,185 @@
<?php
namespace MailSo\Base\StreamWrappers;
/**
* @category MailSo
* @package Base
* @subpackage StreamWrappers
*/
class Literal
{
/**
* @var string
*/
const STREAM_NAME = 'mailsoliteral';
/**
* @var array
*/
private static $aStreams = array();
/**
* @var resource
*/
private $rStream;
/**
* @var int
*/
private $iSize;
/**
* @var int
*/
private $iPos;
/**
* @param resource $rStream
* @param int $iLiteralLen
*
* @return resource|bool
*/
public static function CreateStream($rStream, $iLiteralLen)
{
if (!in_array(self::STREAM_NAME, stream_get_wrappers()))
{
stream_wrapper_register(self::STREAM_NAME, '\MailSo\Base\StreamWrappers\Literal');
}
$sHashName = md5(microtime(true).rand(1000, 9999));
self::$aStreams[$sHashName] = array($rStream, $iLiteralLen);
\MailSo\Base\Loader::IncStatistic('CreateStream/Literal');
return fopen(self::STREAM_NAME.'://'.$sHashName, 'rb');
}
/**
* @param string $sPath
*
* @return bool
*/
public function stream_open($sPath)
{
$this->iPos = 0;
$this->iSize = 0;
$this->rStream = false;
$bResult = false;
$aPath = parse_url($sPath);
if (isset($aPath['host']) && isset($aPath['scheme']) &&
0 < strlen($aPath['host']) && 0 < strlen($aPath['scheme']) &&
self::STREAM_NAME === $aPath['scheme'])
{
$sHashName = $aPath['host'];
if (isset(self::$aStreams[$sHashName]) &&
is_array(self::$aStreams[$sHashName]) &&
2 === count(self::$aStreams[$sHashName]))
{
$this->rStream = self::$aStreams[$sHashName][0];
$this->iSize = self::$aStreams[$sHashName][1];
}
$bResult = is_resource($this->rStream);
}
return $bResult;
}
/**
* @param int $iCount
*
* @return string
*/
public function stream_read($iCount)
{
$sResult = false;
if ($this->iSize < $this->iPos + $iCount)
{
$iCount = $this->iSize - $this->iPos;
}
if ($iCount > 0)
{
$sReadResult = '';
$iRead = $iCount;
while (0 < $iRead)
{
$sAddRead = @fread($this->rStream, $iRead);
if (false === $sAddRead)
{
$sReadResult = false;
break;
}
$sReadResult .= $sAddRead;
$iRead -= strlen($sAddRead);
$this->iPos += strlen($sAddRead);
}
if (false !== $sReadResult)
{
$sResult = $sReadResult;
}
}
return $sResult;
}
/**
* @return int
*/
public function stream_write()
{
return 0;
}
/**
* @return int
*/
public function stream_tell()
{
return $this->iPos;
}
/**
* @return bool
*/
public function stream_eof()
{
return $this->iPos >= $this->iSize;
}
/**
* @return array
*/
public function stream_stat()
{
return array(
'dev' => 2,
'ino' => 0,
'mode' => 33206,
'nlink' => 1,
'uid' => 0,
'gid' => 0,
'rdev' => 2,
'size' => $this->iSize,
'atime' => 1061067181,
'mtime' => 1056136526,
'ctime' => 1056136526,
'blksize' => -1,
'blocks' => -1
);
}
/**
* @return bool
*/
public function stream_seek()
{
return false;
}
}

View file

@ -0,0 +1,257 @@
<?php
namespace MailSo\Base\StreamWrappers;
/**
* @category MailSo
* @package Base
* @subpackage StreamWrappers
*/
class SubStreams
{
/**
* @var string
*/
const STREAM_NAME = 'mailsosubstreams';
/**
* @var array
*/
private static $aStreams = array();
/**
* @var array
*/
private $aSubStreams;
/**
* @var int
*/
private $iIndex;
/**
* @var string
*/
private $sBuffer;
/**
* @var bool
*/
private $bIsEnd;
/**
* @var int
*/
private $iPos;
/**
* @param array $aSubStreams
*
* @return resource|bool
*/
public static function CreateStream($aSubStreams)
{
if (!in_array(self::STREAM_NAME, stream_get_wrappers()))
{
stream_wrapper_register(self::STREAM_NAME, '\MailSo\Base\StreamWrappers\SubStreams');
}
$sHashName = md5(microtime(true).rand(1000, 9999));
self::$aStreams[$sHashName] = $aSubStreams;
\MailSo\Base\Loader::IncStatistic('CreateStream/SubStreams');
return fopen(self::STREAM_NAME.'://'.$sHashName, 'rb');
}
/**
* @return resource|null
*/
protected function &getPart()
{
$nNull = null;
if (isset($this->aSubStreams[$this->iIndex]));
{
return $this->aSubStreams[$this->iIndex];
}
return $nNull;
}
/**
* @param string $sPath
*
* @return bool
*/
public function stream_open($sPath)
{
$this->aSubStreams = array();
$bResult = false;
$aPath = parse_url($sPath);
if (isset($aPath['host']) && isset($aPath['scheme']) &&
0 < strlen($aPath['host']) && 0 < strlen($aPath['scheme']) &&
self::STREAM_NAME === $aPath['scheme'])
{
$sHashName = $aPath['host'];
if (isset(self::$aStreams[$sHashName]) &&
is_array(self::$aStreams[$sHashName]) &&
0 < count(self::$aStreams[$sHashName]))
{
$this->iIndex = 0;
$this->iPos = 0;
$this->bIsEnd = false;
$this->sBuffer = '';
$this->aSubStreams = self::$aStreams[$sHashName];
}
$bResult = 0 < count($this->aSubStreams);
}
return $bResult;
}
/**
* @param int $iCount
*
* @return string
*/
public function stream_read($iCount)
{
$sReturn = '';
$mCurrentPart = null;
if ($iCount > 0)
{
if ($iCount < strlen($this->sBuffer))
{
$sReturn = substr($this->sBuffer, 0, $iCount);
$this->sBuffer = substr($this->sBuffer, $iCount);
}
else
{
$sReturn = $this->sBuffer;
while ($iCount > 0)
{
$mCurrentPart =& $this->getPart();
if (null === $mCurrentPart)
{
$this->bIsEnd = true;
$this->sBuffer = '';
$iCount = 0;
break;
}
if (is_resource($mCurrentPart))
{
if (!feof($mCurrentPart))
{
$sReadResult = fread($mCurrentPart, 8192);
if (false === $sReadResult)
{
return false;
}
$sReturn .= $sReadResult;
$iLen = strlen($sReturn);
if ($iCount < $iLen)
{
$this->sBuffer = substr($sReturn, $iCount);
$sReturn = substr($sReturn, 0, $iCount);
$iCount = 0;
}
else
{
$iCount -= $iLen;
}
}
else
{
$this->iIndex++;
}
}
else if (is_string($mCurrentPart))
{
$sReadResult = substr($mCurrentPart, 0, $iCount);
$sReturn .= $sReadResult;
$iLen = strlen($sReadResult);
if ($iCount < $iLen)
{
$this->sBuffer = substr($sReturn, $iCount);
$sReturn = substr($sReturn, 0, $iCount);
$iCount = 0;
}
else
{
$iCount -= $iLen;
}
$this->iIndex++;
}
}
}
$this->iPos += strlen($sReturn);
return $sReturn;
}
return false;
}
/**
* @return int
*/
public function stream_write()
{
return 0;
}
/**
* @return int
*/
public function stream_tell()
{
return $this->iPos;
}
/**
* @return bool
*/
public function stream_eof()
{
return $this->bIsEnd;
}
/**
* @return array
*/
public function stream_stat()
{
return array(
'dev' => 2,
'ino' => 0,
'mode' => 33206,
'nlink' => 1,
'uid' => 0,
'gid' => 0,
'rdev' => 2,
'size' => 0,
'atime' => 1061067181,
'mtime' => 1056136526,
'ctime' => 1056136526,
'blksize' => -1,
'blocks' => -1
);
}
/**
* @return bool
*/
public function stream_seek()
{
return false;
}
}

View file

@ -0,0 +1,129 @@
<?php
namespace MailSo\Base\StreamWrappers;
/**
* @category MailSo
* @package Base
* @subpackage StreamWrappers
*/
class Test
{
/**
* @var string
*/
const STREAM_NAME = 'mailsotest';
/**
* @var array
*/
private static $aStreams = array();
/**
* @var resource
*/
private $rReadSream;
/**
* @param string $sRawResponse
*
* @return resource|bool
*/
public static function CreateStream($sRawResponse)
{
if (!in_array(self::STREAM_NAME, stream_get_wrappers()))
{
stream_wrapper_register(self::STREAM_NAME, '\MailSo\Base\StreamWrappers\Test');
}
$sHashName = md5(microtime(true).rand(1000, 9999));
$rConnect = fopen('php://memory', 'r+b');
fwrite($rConnect, $sRawResponse);
fseek($rConnect, 0);
self::$aStreams[$sHashName] = $rConnect;
\MailSo\Base\Loader::IncStatistic('CreateStream/Test');
return fopen(self::STREAM_NAME.'://'.$sHashName, 'r+b');
}
/**
* @param string $sPath
*
* @return bool
*/
public function stream_open($sPath)
{
$bResult = false;
$aPath = parse_url($sPath);
if (isset($aPath['host']) && isset($aPath['scheme']) &&
0 < strlen($aPath['host']) && 0 < strlen($aPath['scheme']) &&
self::STREAM_NAME === $aPath['scheme'])
{
$sHashName = $aPath['host'];
if (isset(self::$aStreams[$sHashName]) &&
is_resource(self::$aStreams[$sHashName]))
{
$this->rReadSream = self::$aStreams[$sHashName];
$bResult = true;
}
}
return $bResult;
}
/**
* @param int $iCount
*
* @return string
*/
public function stream_read($iCount)
{
return fread($this->rReadSream, $iCount);
}
/**
* @param string $sInputString
*
* @return int
*/
public function stream_write($sInputString)
{
return strlen($sInputString);
}
/**
* @return int
*/
public function stream_tell()
{
return ftell($this->rReadSream);
}
/**
* @return bool
*/
public function stream_eof()
{
return feof($this->rReadSream);
}
/**
* @return array
*/
public function stream_stat()
{
return fstat($this->rReadSream);
}
/**
* @return bool
*/
public function stream_seek()
{
return false;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,95 @@
<?php
namespace MailSo\Base;
/**
* @category MailSo
* @package Base
*/
class Validator
{
/**
* @param string $sEmail
*
* @return bool
*/
public static function EmailString($sEmail)
{
$bResult = false;
if (self::NotEmptyString($sEmail))
{
$bResult = (bool) \preg_match('/^[a-zA-Z0-9][a-zA-Z0-9\.\+\-_]*@[a-zA-Z0-9][a-zA-Z0-9\.\+\-_]*$/', $sEmail);
}
return $bResult;
}
/**
* @param string $sString
* @param bool $bTrim = false
*
* @return bool
*/
public static function NotEmptyString($sString, $bTrim = false)
{
$bResult = false;
if (\is_string($sString))
{
if ($bTrim)
{
$sString = \trim($sString);
}
$bResult = 0 < \strlen($sString);
}
return $bResult;
}
/**
* @param array $aList
*
* @return bool
*/
public static function NotEmptyArray($aList)
{
return \is_array($aList) && 0 < \count($aList);
}
/**
* @param int $iNumber
* @param int $iMin = null
* @param int $iMax = null
*
* @return bool
*/
public static function RangeInt($iNumber, $iMin = null, $iMax = null)
{
$bResult = false;
if (\is_int($iNumber))
{
$bResult = true;
if ($bResult && null !== $iMin)
{
$bResult = $iNumber >= $iMin;
}
if ($bResult && null !== $iMax)
{
$bResult = $iNumber <= $iMax;
}
}
return $bResult;
}
/**
* @param int $iPort
*
* @return bool
*/
public static function PortInt($iPort)
{
return self::RangeInt($iPort, 0, 65535);
}
}