v1.2.7.415

This commit is contained in:
RainLoop Team 2013-09-29 02:02:47 +04:00
parent 5c1e7bc676
commit 54e2645fcf
436 changed files with 407 additions and 347 deletions

View file

@ -0,0 +1,195 @@
<?php
namespace Buzz;
use Buzz\Client\ClientInterface;
use Buzz\Client\FileGetContents;
use Buzz\Listener\ListenerChain;
use Buzz\Listener\ListenerInterface;
use Buzz\Message\Factory\Factory;
use Buzz\Message\Factory\FactoryInterface;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
use Buzz\Util\Url;
class Browser
{
private $client;
private $factory;
private $listener;
private $lastRequest;
private $lastResponse;
public function __construct(ClientInterface $client = null, FactoryInterface $factory = null)
{
$this->client = $client ?: new FileGetContents();
$this->factory = $factory ?: new Factory();
}
public function get($url, $headers = array())
{
return $this->call($url, RequestInterface::METHOD_GET, $headers);
}
public function post($url, $headers = array(), $content = '')
{
return $this->call($url, RequestInterface::METHOD_POST, $headers, $content);
}
public function head($url, $headers = array())
{
return $this->call($url, RequestInterface::METHOD_HEAD, $headers);
}
public function patch($url, $headers = array(), $content = '')
{
return $this->call($url, RequestInterface::METHOD_PATCH, $headers, $content);
}
public function put($url, $headers = array(), $content = '')
{
return $this->call($url, RequestInterface::METHOD_PUT, $headers, $content);
}
public function delete($url, $headers = array(), $content = '')
{
return $this->call($url, RequestInterface::METHOD_DELETE, $headers, $content);
}
/**
* Sends a request.
*
* @param string $url The URL to call
* @param string $method The request method to use
* @param array $headers An array of request headers
* @param string $content The request content
*
* @return MessageInterface The response object
*/
public function call($url, $method, $headers = array(), $content = '')
{
$request = $this->factory->createRequest($method);
if (!$url instanceof Url) {
$url = new Url($url);
}
$url->applyToRequest($request);
$request->addHeaders($headers);
$request->setContent($content);
return $this->send($request);
}
/**
* Sends a form request.
*
* @param string $url The URL to submit to
* @param array $fields An array of fields
* @param string $method The request method to use
* @param array $headers An array of request headers
*
* @return MessageInterface The response object
*/
public function submit($url, array $fields, $method = RequestInterface::METHOD_POST, $headers = array())
{
$request = $this->factory->createFormRequest();
if (!$url instanceof Url) {
$url = new Url($url);
}
$url->applyToRequest($request);
$request->addHeaders($headers);
$request->setMethod($method);
$request->setFields($fields);
return $this->send($request);
}
/**
* Sends a request.
*
* @param RequestInterface $request A request object
* @param MessageInterface $response A response object
*
* @return MessageInterface The response
*/
public function send(RequestInterface $request, MessageInterface $response = null)
{
if (null === $response) {
$response = $this->factory->createResponse();
}
if ($this->listener) {
$this->listener->preSend($request);
}
$this->client->send($request, $response);
$this->lastRequest = $request;
$this->lastResponse = $response;
if ($this->listener) {
$this->listener->postSend($request, $response);
}
return $response;
}
public function getLastRequest()
{
return $this->lastRequest;
}
public function getLastResponse()
{
return $this->lastResponse;
}
public function setClient(ClientInterface $client)
{
$this->client = $client;
}
public function getClient()
{
return $this->client;
}
public function setMessageFactory(FactoryInterface $factory)
{
$this->factory = $factory;
}
public function getMessageFactory()
{
return $this->factory;
}
public function setListener(ListenerInterface $listener)
{
$this->listener = $listener;
}
public function getListener()
{
return $this->listener;
}
public function addListener(ListenerInterface $listener)
{
if (!$this->listener) {
$this->listener = $listener;
} elseif ($this->listener instanceof ListenerChain) {
$this->listener->addListener($listener);
} else {
$this->listener = new ListenerChain(array(
$this->listener,
$listener,
));
}
}
}

View file

@ -0,0 +1,62 @@
<?php
namespace Buzz\Client;
abstract class AbstractClient implements ClientInterface
{
protected $ignoreErrors = true;
protected $maxRedirects = 5;
protected $timeout = 5;
protected $verifyPeer = true;
protected $proxy;
public function setIgnoreErrors($ignoreErrors)
{
$this->ignoreErrors = $ignoreErrors;
}
public function getIgnoreErrors()
{
return $this->ignoreErrors;
}
public function setMaxRedirects($maxRedirects)
{
$this->maxRedirects = $maxRedirects;
}
public function getMaxRedirects()
{
return $this->maxRedirects;
}
public function setTimeout($timeout)
{
$this->timeout = $timeout;
}
public function getTimeout()
{
return $this->timeout;
}
public function setVerifyPeer($verifyPeer)
{
$this->verifyPeer = $verifyPeer;
}
public function getVerifyPeer()
{
return $this->verifyPeer;
}
public function setProxy($proxy)
{
$this->proxy = $proxy;
}
public function getProxy()
{
return $this->proxy;
}
}

View file

@ -0,0 +1,201 @@
<?php
namespace Buzz\Client;
use Buzz\Message\Form\FormRequestInterface;
use Buzz\Message\Form\FormUploadInterface;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
use Buzz\Exception\ClientException;
/**
* Base client class with helpers for working with cURL.
*/
abstract class AbstractCurl extends AbstractClient
{
protected $options = array();
public function __construct()
{
if (defined('CURLOPT_PROTOCOLS')) {
$this->options = array(
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
);
}
}
/**
* Creates a new cURL resource.
*
* @see curl_init()
*
* @return resource A new cURL resource
*/
protected static function createCurlHandle()
{
if (false === $curl = curl_init()) {
throw new ClientException('Unable to create a new cURL handle');
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
return $curl;
}
/**
* Populates a response object.
*
* @param resource $curl A cURL resource
* @param string $raw The raw response string
* @param MessageInterface $response The response object
*/
protected static function populateResponse($curl, $raw, MessageInterface $response)
{
$pos = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$response->setHeaders(static::getLastHeaders(rtrim(substr($raw, 0, $pos))));
$response->setContent(substr($raw, $pos));
}
/**
* Sets options on a cURL resource based on a request.
*/
private static function setOptionsFromRequest($curl, RequestInterface $request)
{
$options = array(
CURLOPT_CUSTOMREQUEST => $request->getMethod(),
CURLOPT_URL => $request->getHost().$request->getResource(),
CURLOPT_HTTPHEADER => $request->getHeaders(),
);
switch ($request->getMethod()) {
case RequestInterface::METHOD_HEAD:
$options[CURLOPT_NOBODY] = true;
break;
case RequestInterface::METHOD_GET:
$options[CURLOPT_HTTPGET] = true;
break;
case RequestInterface::METHOD_POST:
case RequestInterface::METHOD_PUT:
case RequestInterface::METHOD_DELETE:
case RequestInterface::METHOD_PATCH:
$options[CURLOPT_POSTFIELDS] = $fields = static::getPostFields($request);
// remove the content-type header
if (is_array($fields)) {
$options[CURLOPT_HTTPHEADER] = array_filter($options[CURLOPT_HTTPHEADER], function($header) {
return 0 !== stripos($header, 'Content-Type: ');
});
}
break;
}
curl_setopt_array($curl, $options);
}
/**
* Returns a value for the CURLOPT_POSTFIELDS option.
*
* @return string|array A post fields value
*/
private static function getPostFields(RequestInterface $request)
{
if (!$request instanceof FormRequestInterface) {
return $request->getContent();
}
$fields = $request->getFields();
$multipart = false;
foreach ($fields as $name => $value) {
if ($value instanceof FormUploadInterface) {
$multipart = true;
if ($file = $value->getFile()) {
// replace value with upload string
$fields[$name] = '@'.$file;
if ($contentType = $value->getContentType()) {
$fields[$name] .= ';type='.$contentType;
}
} else {
return $request->getContent();
}
}
}
return $multipart ? $fields : http_build_query($fields);
}
/**
* A helper for getting the last set of headers.
*
* @param string $raw A string of many header chunks
*
* @return array An array of header lines
*/
private static function getLastHeaders($raw)
{
$headers = array();
foreach (preg_split('/(\\r?\\n)/', $raw) as $header) {
if ($header) {
$headers[] = $header;
} else {
$headers = array();
}
}
return $headers;
}
/**
* Stashes a cURL option to be set on send, when the resource is created.
*
* If the supplied value it set to null the option will be removed.
*
* @param integer $option The option
* @param mixed $value The value
*
* @see curl_setopt()
*/
public function setOption($option, $value)
{
if (null === $value) {
unset($this->options[$option]);
} else {
$this->options[$option] = $value;
}
}
/**
* Prepares a cURL resource to send a request.
*/
protected function prepare($curl, RequestInterface $request, array $options = array())
{
static::setOptionsFromRequest($curl, $request);
// apply settings from client
if ($this->getTimeout() < 1) {
curl_setopt($curl, CURLOPT_TIMEOUT_MS, $this->getTimeout() * 1000);
} else {
curl_setopt($curl, CURLOPT_TIMEOUT, $this->getTimeout());
}
if ($this->proxy) {
curl_setopt($curl, CURLOPT_PROXY, $this->proxy);
}
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0 < $this->getMaxRedirects());
curl_setopt($curl, CURLOPT_MAXREDIRS, $this->getMaxRedirects());
curl_setopt($curl, CURLOPT_FAILONERROR, !$this->getIgnoreErrors());
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->getVerifyPeer());
// apply additional options
curl_setopt_array($curl, $options + $this->options);
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace Buzz\Client;
use Buzz\Message\RequestInterface;
abstract class AbstractStream extends AbstractClient
{
/**
* Converts a request into an array for stream_context_create().
*
* @param RequestInterface $request A request object
*
* @return array An array for stream_context_create()
*/
public function getStreamContextArray(RequestInterface $request)
{
$options = array(
'http' => array(
// values from the request
'method' => $request->getMethod(),
'header' => implode("\r\n", $request->getHeaders()),
'content' => $request->getContent(),
'protocol_version' => $request->getProtocolVersion(),
// values from the current client
'ignore_errors' => $this->getIgnoreErrors(),
'max_redirects' => $this->getMaxRedirects(),
'timeout' => $this->getTimeout(),
),
'ssl' => array(
'verify_peer' => $this->getVerifyPeer(),
),
);
if ($this->proxy) {
$options['http']['proxy'] = $this->proxy;
$options['http']['request_fulluri'] = true;
}
return $options;
}
}

View file

@ -0,0 +1,11 @@
<?php
namespace Buzz\Client;
interface BatchClientInterface extends ClientInterface
{
/**
* Processes the queued requests.
*/
public function flush();
}

View file

@ -0,0 +1,17 @@
<?php
namespace Buzz\Client;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
interface ClientInterface
{
/**
* Populates the supplied response with the response for the supplied request.
*
* @param RequestInterface $request A request object
* @param MessageInterface $response A response object
*/
public function send(RequestInterface $request, MessageInterface $response);
}

View file

@ -0,0 +1,55 @@
<?php
namespace Buzz\Client;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
use Buzz\Exception\ClientException;
use Buzz\Exception\LogicException;
class Curl extends AbstractCurl
{
private $lastCurl;
public function send(RequestInterface $request, MessageInterface $response, array $options = array())
{
if (is_resource($this->lastCurl)) {
curl_close($this->lastCurl);
}
$this->lastCurl = static::createCurlHandle();
$this->prepare($this->lastCurl, $request, $options);
$data = curl_exec($this->lastCurl);
if (false === $data) {
$errorMsg = curl_error($this->lastCurl);
$errorNo = curl_errno($this->lastCurl);
throw new ClientException($errorMsg, $errorNo);
}
static::populateResponse($this->lastCurl, $data, $response);
}
/**
* Introspects the last cURL request.
*
* @see curl_getinfo()
*/
public function getInfo($opt = 0)
{
if (!is_resource($this->lastCurl)) {
throw new LogicException('There is no cURL resource');
}
return curl_getinfo($this->lastCurl, $opt);
}
public function __destruct()
{
if (is_resource($this->lastCurl)) {
curl_close($this->lastCurl);
}
}
}

View file

@ -0,0 +1,87 @@
<?php
namespace Buzz\Client;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
use Buzz\Util\CookieJar;
use Buzz\Exception\ClientException;
class FileGetContents extends AbstractStream
{
/**
* @var CookieJar
*/
protected $cookieJar;
/**
* @param CookieJar|null $cookieJar
*/
public function __construct(CookieJar $cookieJar = null)
{
if ($cookieJar) {
$this->setCookieJar($cookieJar);
}
}
/**
* @param CookieJar $cookieJar
*/
public function setCookieJar(CookieJar $cookieJar)
{
$this->cookieJar = $cookieJar;
}
/**
* @return CookieJar
*/
public function getCookieJar()
{
return $this->cookieJar;
}
/**
* @see ClientInterface
*
* @throws ClientException If file_get_contents() fires an error
*/
public function send(RequestInterface $request, MessageInterface $response)
{
if ($cookieJar = $this->getCookieJar()) {
$cookieJar->clearExpiredCookies();
$cookieJar->addCookieHeaders($request);
}
$context = stream_context_create($this->getStreamContextArray($request));
$url = $request->getHost().$request->getResource();
$level = error_reporting(0);
$content = file_get_contents($url, 0, $context);
error_reporting($level);
if (false === $content) {
$error = error_get_last();
throw new ClientException($error['message']);
}
$response->setHeaders($this->filterHeaders((array) $http_response_header));
$response->setContent($content);
if ($cookieJar) {
$cookieJar->processSetCookieHeaders($request, $response);
}
}
private function filterHeaders(array $headers)
{
$filtered = array();
foreach ($headers as $header) {
if (0 === stripos($header, 'http/')) {
$filtered = array();
}
$filtered[] = $header;
}
return $filtered;
}
}

View file

@ -0,0 +1,53 @@
<?php
namespace Buzz\Client;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
use Buzz\Exception\ClientException;
class MultiCurl extends AbstractCurl implements BatchClientInterface
{
private $queue = array();
public function send(RequestInterface $request, MessageInterface $response, array $options = array())
{
$this->queue[] = array($request, $response, $options);
}
public function flush()
{
if (false === $curlm = curl_multi_init()) {
throw new ClientException('Unable to create a new cURL multi handle');
}
// prepare a cURL handle for each entry in the queue
foreach ($this->queue as $i => &$queue) {
list($request, $response, $options) = $queue;
$curl = $queue[] = static::createCurlHandle();
$this->prepare($curl, $request, $options);
curl_multi_add_handle($curlm, $curl);
}
$active = null;
do {
$mrc = curl_multi_exec($curlm, $active);
} while (CURLM_CALL_MULTI_PERFORM == $mrc);
while ($active && CURLM_OK == $mrc) {
if (-1 != curl_multi_select($curlm)) {
do {
$mrc = curl_multi_exec($curlm, $active);
} while (CURLM_CALL_MULTI_PERFORM == $mrc);
}
}
// populate the responses
while (list($request, $response, $options, $curl) = array_shift($this->queue)) {
static::populateResponse($curl, curl_multi_getcontent($curl), $response);
curl_multi_remove_handle($curlm, $curl);
}
curl_multi_close($curlm);
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace Buzz\Exception;
/**
* Thrown whenever a client process fails.
*/
class ClientException extends RuntimeException
{
}

View file

@ -0,0 +1,10 @@
<?php
namespace Buzz\Exception;
/**
* Marker interface to denote exceptions thrown from the Buzz context.
*/
interface ExceptionInterface
{
}

View file

@ -0,0 +1,10 @@
<?php
namespace Buzz\Exception;
/**
* Thrown when an invalid argument is provided.
*/
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}

View file

@ -0,0 +1,10 @@
<?php
namespace Buzz\Exception;
/**
* Thrown whenever a required call-flow is not respected.
*/
class LogicException extends \LogicException implements ExceptionInterface
{
}

View file

@ -0,0 +1,7 @@
<?php
namespace Buzz\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}

View file

@ -0,0 +1,27 @@
<?php
namespace Buzz\Listener;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
class BasicAuthListener implements ListenerInterface
{
private $username;
private $password;
public function __construct($username, $password)
{
$this->username = $username;
$this->password = $password;
}
public function preSend(RequestInterface $request)
{
$request->addHeader('Authorization: Basic '.base64_encode($this->username.':'.$this->password));
}
public function postSend(RequestInterface $request, MessageInterface $response)
{
}
}

View file

@ -0,0 +1,49 @@
<?php
namespace Buzz\Listener;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
use Buzz\Exception\InvalidArgumentException;
class CallbackListener implements ListenerInterface
{
private $callable;
/**
* Constructor.
*
* The callback should expect either one or two arguments, depending on
* whether it is receiving a pre or post send notification.
*
* $listener = new CallbackListener(function($request, $response = null) {
* if ($response) {
* // postSend
* } else {
* // preSend
* }
* });
*
* @param mixed $callable A PHP callable
*
* @throws InvalidArgumentException If the argument is not callable
*/
public function __construct($callable)
{
if (!is_callable($callable)) {
throw new InvalidArgumentException('The argument is not callable.');
}
$this->callable = $callable;
}
public function preSend(RequestInterface $request)
{
call_user_func($this->callable, $request);
}
public function postSend(RequestInterface $request, MessageInterface $response)
{
call_user_func($this->callable, $request, $response);
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace Buzz\Listener\History;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
class Entry
{
private $request;
private $response;
private $duration;
/**
* Constructor.
*
* @param RequestInterface $request The request
* @param MessageInterface $response The response
* @param integer $duration The duration in seconds
*/
public function __construct(RequestInterface $request, MessageInterface $response, $duration = null)
{
$this->request = $request;
$this->response = $response;
$this->duration = $duration;
}
public function getRequest()
{
return $this->request;
}
public function getResponse()
{
return $this->response;
}
public function getDuration()
{
return $this->duration;
}
}

View file

@ -0,0 +1,76 @@
<?php
namespace Buzz\Listener\History;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
class Journal implements \Countable, \IteratorAggregate
{
private $entries = array();
private $limit = 10;
/**
* Records an entry in the journal.
*
* @param RequestInterface $request The request
* @param MessageInterface $response The response
* @param integer $duration The duration in seconds
*/
public function record(RequestInterface $request, MessageInterface $response, $duration = null)
{
$this->addEntry(new Entry($request, $response, $duration));
}
public function addEntry(Entry $entry)
{
array_push($this->entries, $entry);
$this->entries = array_slice($this->entries, $this->getLimit() * -1);
end($this->entries);
}
public function getEntries()
{
return $this->entries;
}
public function getLast()
{
return end($this->entries);
}
public function getLastRequest()
{
return $this->getLast()->getRequest();
}
public function getLastResponse()
{
return $this->getLast()->getResponse();
}
public function clear()
{
$this->entries = array();
}
public function count()
{
return count($this->entries);
}
public function setLimit($limit)
{
$this->limit = $limit;
}
public function getLimit()
{
return $this->limit;
}
public function getIterator()
{
return new \ArrayIterator(array_reverse($this->entries));
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace Buzz\Listener;
use Buzz\Listener\History\Journal;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
class HistoryListener implements ListenerInterface
{
private $journal;
private $startTime;
public function __construct(Journal $journal)
{
$this->journal = $journal;
}
public function getJournal()
{
return $this->journal;
}
public function preSend(RequestInterface $request)
{
$this->startTime = microtime(true);
}
public function postSend(RequestInterface $request, MessageInterface $response)
{
$this->journal->record($request, $response, microtime(true) - $this->startTime);
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Buzz\Listener;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
class ListenerChain implements ListenerInterface
{
private $listeners;
public function __construct(array $listeners = array())
{
$this->listeners = $listeners;
}
public function addListener(ListenerInterface $listener)
{
$this->listeners[] = $listener;
}
public function getListeners()
{
return $this->listeners;
}
public function preSend(RequestInterface $request)
{
foreach ($this->listeners as $listener) {
$listener->preSend($request);
}
}
public function postSend(RequestInterface $request, MessageInterface $response)
{
foreach ($this->listeners as $listener) {
$listener->postSend($request, $response);
}
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace Buzz\Listener;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
interface ListenerInterface
{
public function preSend(RequestInterface $request);
public function postSend(RequestInterface $request, MessageInterface $response);
}

View file

@ -0,0 +1,36 @@
<?php
namespace Buzz\Listener;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
use Buzz\Exception\InvalidArgumentException;
class LoggerListener implements ListenerInterface
{
private $logger;
private $prefix;
private $startTime;
public function __construct($logger, $prefix = null)
{
if (!is_callable($logger)) {
throw new InvalidArgumentException('The logger must be a callable.');
}
$this->logger = $logger;
$this->prefix = $prefix;
}
public function preSend(RequestInterface $request)
{
$this->startTime = microtime(true);
}
public function postSend(RequestInterface $request, MessageInterface $response)
{
$seconds = microtime(true) - $this->startTime;
call_user_func($this->logger, sprintf('%sSent "%s %s%s" in %dms', $this->prefix, $request->getMethod(), $request->getHost(), $request->getResource(), round($seconds * 1000)));
}
}

View file

@ -0,0 +1,154 @@
<?php
namespace Buzz\Message;
abstract class AbstractMessage implements MessageInterface
{
private $headers = array();
private $content;
/**
* Returns the value of a header.
*
* @param string $name
* @param string|boolean $glue Glue for implode, or false to return an array
*
* @return string|array|null
*/
public function getHeader($name, $glue = "\r\n")
{
$needle = $name.':';
$values = array();
foreach ($this->getHeaders() as $header) {
if (0 === stripos($header, $needle)) {
$values[] = trim(substr($header, strlen($needle)));
}
}
if (false === $glue) {
return $values;
} else {
return count($values) ? implode($glue, $values) : null;
}
}
/**
* Returns a header's attributes.
*
* @param string $name A header name
*
* @return array An associative array of attributes
*/
public function getHeaderAttributes($name)
{
$attributes = array();
foreach ($this->getHeader($name, false) as $header) {
if (false !== strpos($header, ';')) {
// remove header value
list(, $header) = explode(';', $header, 2);
// loop through attribute key=value pairs
foreach (array_map('trim', explode(';', trim($header))) as $pair) {
list($key, $value) = explode('=', $pair);
$attributes[$key] = $value;
}
}
}
return $attributes;
}
/**
* Returns the value of a particular header attribute.
*
* @param string $header A header name
* @param string $attribute An attribute name
*
* @return string|null The value of the attribute or null if it isn't set
*/
public function getHeaderAttribute($header, $attribute)
{
$attributes = $this->getHeaderAttributes($header);
if (isset($attributes[$attribute])) {
return $attributes[$attribute];
}
}
/**
* Returns the current message as a DOMDocument.
*
* @return \DOMDocument
*/
public function toDomDocument()
{
$revert = libxml_use_internal_errors(true);
$document = new \DOMDocument('1.0', $this->getHeaderAttribute('Content-Type', 'charset') ?: 'UTF-8');
if (0 === strpos($this->getHeader('Content-Type'), 'text/xml')) {
$document->loadXML($this->getContent());
} else {
$document->loadHTML($this->getContent());
}
libxml_use_internal_errors($revert);
return $document;
}
public function setHeaders(array $headers)
{
$this->headers = $this->flattenHeaders($headers);
}
public function addHeader($header)
{
$this->headers[] = $header;
}
public function addHeaders(array $headers)
{
$this->headers = array_merge($this->headers, $this->flattenHeaders($headers));
}
public function getHeaders()
{
return $this->headers;
}
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function __toString()
{
$string = implode("\r\n", $this->getHeaders())."\r\n";
if ($content = $this->getContent()) {
$string .= "\r\n$content\r\n";
}
return $string;
}
protected function flattenHeaders(array $headers)
{
$flattened = array();
foreach ($headers as $key => $header) {
if (is_int($key)) {
$flattened[] = $header;
} else {
$flattened[] = $key.': '.$header;
}
}
return $flattened;
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Buzz\Message\Factory;
use Buzz\Message\Form\FormRequest;
use Buzz\Message\Request;
use Buzz\Message\RequestInterface;
use Buzz\Message\Response;
class Factory implements FactoryInterface
{
public function createRequest($method = RequestInterface::METHOD_GET, $resource = '/', $host = null)
{
return new Request($method, $resource, $host);
}
public function createFormRequest($method = RequestInterface::METHOD_POST, $resource = '/', $host = null)
{
return new FormRequest($method, $resource, $host);
}
public function createResponse()
{
return new Response();
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace Buzz\Message\Factory;
use Buzz\Message\RequestInterface;
interface FactoryInterface
{
public function createRequest($method = RequestInterface::METHOD_GET, $resource = '/', $host = null);
public function createFormRequest($method = RequestInterface::METHOD_POST, $resource = '/', $host = null);
public function createResponse();
}

View file

@ -0,0 +1,187 @@
<?php
namespace Buzz\Message\Form;
use Buzz\Message\Request;
use Buzz\Exception\LogicException;
/**
* FormRequest.
*
* $request = new FormRequest();
* $request->setField('user[name]', 'Kris Wallsmith');
* $request->setField('user[image]', new FormUpload('/path/to/image.jpg'));
*
* @author Marc Weistroff <marc.weistroff@sensio.com>
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
*/
class FormRequest extends Request implements FormRequestInterface
{
private $fields = array();
private $boundary;
/**
* Constructor.
*
* Defaults to POST rather than GET.
*/
public function __construct($method = self::METHOD_POST, $resource = '/', $host = null)
{
parent::__construct($method, $resource, $host);
}
/**
* Sets the value of a form field.
*
* If the value is an array it will be flattened and one field value will
* be added for each leaf.
*/
public function setField($name, $value)
{
if (is_array($value)) {
$this->addFields(array($name => $value));
return;
}
if ('[]' == substr($name, -2)) {
$this->fields[substr($name, 0, -2)][] = $value;
} else {
$this->fields[$name] = $value;
}
}
public function addFields(array $fields)
{
foreach ($this->flattenArray($fields) as $name => $value) {
$this->setField($name, $value);
}
}
public function setFields(array $fields)
{
$this->fields = array();
$this->addFields($fields);
}
public function getFields()
{
return $this->fields;
}
public function getResource()
{
$resource = parent::getResource();
if (!$this->isSafe() || !$this->fields) {
return $resource;
}
// append the query string
$resource .= false === strpos($resource, '?') ? '?' : '&';
$resource .= http_build_query($this->fields);
return $resource;
}
public function setContent($content)
{
throw new \BadMethodCallException('It is not permitted to set the content.');
}
public function getHeaders()
{
$headers = parent::getHeaders();
if ($this->isSafe()) {
return $headers;
}
if ($this->isMultipart()) {
$headers[] = 'Content-Type: multipart/form-data; boundary='.$this->getBoundary();
} else {
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
}
return $headers;
}
public function getContent()
{
if ($this->isSafe()) {
return;
}
if (!$this->isMultipart()) {
return http_build_query($this->fields);
}
$content = '';
foreach ($this->fields as $name => $values) {
$content .= '--'.$this->getBoundary()."\r\n";
if ($values instanceof FormUploadInterface) {
if (!$values->getFilename()) {
throw new LogicException(sprintf('Form upload at "%s" does not include a filename.', $name));
}
$values->setName($name);
$content .= (string) $values;
} else {
foreach (is_array($values) ? $values : array($values) as $value) {
$content .= "Content-Disposition: form-data; name=\"$name\"\r\n";
$content .= "\r\n";
$content .= $value."\r\n";
}
}
}
$content .= '--'.$this->getBoundary().'--';
return $content;
}
// private
private function flattenArray(array $values, $prefix = '', $format = '%s')
{
$flat = array();
foreach ($values as $name => $value) {
$flatName = $prefix.sprintf($format, $name);
if (is_array($value)) {
$flat += $this->flattenArray($value, $flatName, '[%s]');
} else {
$flat[$flatName] = $value;
}
}
return $flat;
}
private function isSafe()
{
return in_array($this->getMethod(), array(self::METHOD_GET, self::METHOD_HEAD));
}
private function isMultipart()
{
foreach ($this->fields as $name => $value) {
if (is_object($value) && $value instanceof FormUploadInterface) {
return true;
}
}
return false;
}
private function getBoundary()
{
if (!$this->boundary) {
$this->boundary = sha1(rand(11111, 99999).time().uniqid());
}
return $this->boundary;
}
}

View file

@ -0,0 +1,27 @@
<?php
namespace Buzz\Message\Form;
use Buzz\Message\RequestInterface;
/**
* An HTTP request message sent by a web form.
*
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
*/
interface FormRequestInterface extends RequestInterface
{
/**
* Returns an array of field names and values.
*
* @return array A array of names and values
*/
public function getFields();
/**
* Sets the form fields for the current request.
*
* @param array $fields An array of field names and values
*/
public function setFields(array $fields);
}

View file

@ -0,0 +1,118 @@
<?php
namespace Buzz\Message\Form;
use Buzz\Message\AbstractMessage;
class FormUpload extends AbstractMessage implements FormUploadInterface
{
private $name;
private $filename;
private $contentType;
private $file;
public function __construct($file = null, $contentType = null)
{
if ($file) {
$this->loadContent($file);
}
$this->contentType = $contentType;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getFilename()
{
if ($this->filename) {
return $this->filename;
} elseif ($this->file) {
return basename($this->file);
}
}
public function setFilename($filename)
{
$this->filename = $filename;
}
public function getContentType()
{
return $this->contentType ?: $this->detectContentType() ?: 'application/octet-stream';
}
public function setContentType($contentType)
{
$this->contentType = $contentType;
}
/**
* Prepends Content-Disposition and Content-Type headers.
*/
public function getHeaders()
{
$headers = array('Content-Disposition: form-data');
if ($name = $this->getName()) {
$headers[0] .= sprintf('; name="%s"', $name);
}
if ($filename = $this->getFilename()) {
$headers[0] .= sprintf('; filename="%s"', $filename);
}
if ($contentType = $this->getContentType()) {
$headers[] = 'Content-Type: '.$contentType;
}
return array_merge($headers, parent::getHeaders());
}
/**
* Loads the content from a file.
*/
public function loadContent($file)
{
$this->file = $file;
parent::setContent(null);
}
public function setContent($content)
{
parent::setContent($content);
$this->file = null;
}
public function getFile()
{
return $this->file;
}
public function getContent()
{
return $this->file ? file_get_contents($this->file) : parent::getContent();
}
// private
private function detectContentType()
{
if (!class_exists('finfo', false)) {
return false;
}
$finfo = new \finfo(FILEINFO_MIME_TYPE);
return $this->file ? $finfo->file($this->file) : $finfo->buffer(parent::getContent());
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Buzz\Message\Form;
use Buzz\Message\MessageInterface;
interface FormUploadInterface extends MessageInterface
{
public function setName($name);
public function getFile();
public function getFilename();
public function getContentType();
}

View file

@ -0,0 +1,74 @@
<?php
namespace Buzz\Message;
/**
* An HTTP message.
*
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
*/
interface MessageInterface
{
/**
* Returns a header value.
*
* @param string $name A header name
* @param string|boolean $glue Glue for implode, or false to return an array
*
* @return string|array|null The header value(s)
*/
public function getHeader($name, $glue = "\r\n");
/**
* Returns an array of header lines.
*
* @return array An array of header lines (integer indexes, e.g. ["Header: value"])
*/
public function getHeaders();
/**
* Sets all headers on the current message.
*
* Headers can be complete ["Header: value"] pairs or an associative array ["Header" => "value"]
*
* @param array $headers An array of header lines
*/
public function setHeaders(array $headers);
/**
* Adds a header to this message.
*
* @param string $header A header line
*/
public function addHeader($header);
/**
* Adds a set of headers to this message.
*
* Headers can be complete ["Header: value"] pairs or an associative array ["Header" => "value"]
*
* @param array $headers Headers
*/
public function addHeaders(array $headers);
/**
* Returns the content of the message.
*
* @return string The message content
*/
public function getContent();
/**
* Sets the content of the message.
*
* @param string $content The message content
*/
public function setContent($content);
/**
* Returns the message document.
*
* @return string The message
*/
public function __toString();
}

View file

@ -0,0 +1,174 @@
<?php
namespace Buzz\Message;
use Buzz\Util\Url;
class Request extends AbstractMessage implements RequestInterface
{
private $method;
private $resource;
private $host;
private $protocolVersion = 1.0;
/**
* Constructor.
*
* @param string $method
* @param string $resource
* @param string $host
*/
public function __construct($method = self::METHOD_GET, $resource = '/', $host = null)
{
$this->method = strtoupper($method);
$this->resource = $resource;
$this->host = $host;
}
public function setHeaders(array $headers)
{
parent::setHeaders(array());
foreach ($this->flattenHeaders($headers) as $header) {
$this->addHeader($header);
}
}
public function addHeader($header)
{
if (0 === stripos(substr($header, -8), 'HTTP/1.') && 3 == count($parts = explode(' ', $header))) {
list($method, $resource, $protocolVersion) = $parts;
$this->setMethod($method);
$this->setResource($resource);
$this->setProtocolVersion((float) substr($protocolVersion, 5));
} else {
parent::addHeader($header);
}
}
public function setMethod($method)
{
$this->method = strtoupper($method);
}
public function getMethod()
{
return $this->method;
}
public function setResource($resource)
{
$this->resource = $resource;
}
public function getResource()
{
return $this->resource;
}
public function setHost($host)
{
$this->host = $host;
}
public function getHost()
{
return $this->host;
}
public function setProtocolVersion($protocolVersion)
{
$this->protocolVersion = $protocolVersion;
}
public function getProtocolVersion()
{
return $this->protocolVersion;
}
/**
* A convenience method for getting the full URL of the current request.
*
* @return string
*/
public function getUrl()
{
return $this->getHost().$this->getResource();
}
/**
* A convenience method for populating the current request from a URL.
*
* @param Url|string $url An URL
*/
public function fromUrl($url)
{
if (!$url instanceof Url) {
$url = new Url($url);
}
$url->applyToRequest($this);
}
/**
* Returns true if the current request is secure.
*
* @return boolean
*/
public function isSecure()
{
return 'https' == parse_url($this->getHost(), PHP_URL_SCHEME);
}
/**
* Merges cookie headers on the way out.
*/
public function getHeaders()
{
return $this->mergeCookieHeaders(parent::getHeaders());
}
/**
* Returns a string representation of the current request.
*
* @return string
*/
public function __toString()
{
$string = sprintf("%s %s HTTP/%.1f\r\n", $this->getMethod(), $this->getResource(), $this->getProtocolVersion());
if ($host = $this->getHost()) {
$string .= 'Host: '.$host."\r\n";
}
if ($parent = trim(parent::__toString())) {
$string .= $parent."\r\n";
}
return $string;
}
// private
private function mergeCookieHeaders(array $headers)
{
$cookieHeader = null;
$needle = 'Cookie:';
foreach ($headers as $i => $header) {
if (0 !== stripos($header, $needle)) {
continue;
}
if (null === $cookieHeader) {
$cookieHeader = $i;
} else {
$headers[$cookieHeader] .= '; '.trim(substr($header, strlen($needle)));
unset($headers[$i]);
}
}
return array_values($headers);
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace Buzz\Message;
/**
* An HTTP request message.
*
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
*/
interface RequestInterface extends MessageInterface
{
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_GET = 'GET';
const METHOD_HEAD = 'HEAD';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
const METHOD_PATCH = 'PATCH';
/**
* Returns the HTTP method of the current request.
*
* @return string An HTTP method
*/
public function getMethod();
/**
* Sets the HTTP method of the current request.
*
* @param string $method The request method
*/
public function setMethod($method);
/**
* Returns the resource portion of the request line.
*
* @return string The resource requested
*/
public function getResource();
/**
* Sets the resource for the current request.
*
* @param string $resource The resource being requested
*/
public function setResource($resource);
/**
* Returns the protocol version of the current request.
*
* @return float The protocol version
*/
public function getProtocolVersion();
/**
* Returns the value of the host header.
*
* @return string|null The host
*/
public function getHost();
/**
* Sets the host for the current request.
*
* @param string $host The host
*/
public function setHost($host);
/**
* Checks if the current request is secure.
*
* @return Boolean True if the request is secure
*/
public function isSecure();
}

View file

@ -0,0 +1,193 @@
<?php
namespace Buzz\Message;
class Response extends AbstractMessage
{
private $protocolVersion;
private $statusCode;
private $reasonPhrase;
/**
* Returns the protocol version of the current response.
*
* @return float
*/
public function getProtocolVersion()
{
if (null === $this->protocolVersion) {
$this->parseStatusLine();
}
return $this->protocolVersion ?: null;
}
/**
* Returns the status code of the current response.
*
* @return integer
*/
public function getStatusCode()
{
if (null === $this->statusCode) {
$this->parseStatusLine();
}
return $this->statusCode ?: null;
}
/**
* Returns the reason phrase for the current response.
*
* @return string
*/
public function getReasonPhrase()
{
if (null === $this->reasonPhrase) {
$this->parseStatusLine();
}
return $this->reasonPhrase ?: null;
}
public function setHeaders(array $headers)
{
parent::setHeaders($headers);
$this->resetStatusLine();
}
public function addHeader($header)
{
parent::addHeader($header);
$this->resetStatusLine();
}
public function addHeaders(array $headers)
{
parent::addHeaders($headers);
$this->resetStatusLine();
}
/**
* Is response invalid?
*
* @return Boolean
*/
public function isInvalid()
{
return $this->getStatusCode() < 100 || $this->getStatusCode() >= 600;
}
/**
* Is response informative?
*
* @return Boolean
*/
public function isInformational()
{
return $this->getStatusCode() >= 100 && $this->getStatusCode() < 200;
}
/**
* Is response successful?
*
* @return Boolean
*/
public function isSuccessful()
{
return $this->getStatusCode() >= 200 && $this->getStatusCode() < 300;
}
/**
* Is the response a redirect?
*
* @return Boolean
*/
public function isRedirection()
{
return $this->getStatusCode() >= 300 && $this->getStatusCode() < 400;
}
/**
* Is there a client error?
*
* @return Boolean
*/
public function isClientError()
{
return $this->getStatusCode() >= 400 && $this->getStatusCode() < 500;
}
/**
* Was there a server side error?
*
* @return Boolean
*/
public function isServerError()
{
return $this->getStatusCode() >= 500 && $this->getStatusCode() < 600;
}
/**
* Is the response OK?
*
* @return Boolean
*/
public function isOk()
{
return 200 === $this->getStatusCode();
}
/**
* Is the reponse forbidden?
*
* @return Boolean
*/
public function isForbidden()
{
return 403 === $this->getStatusCode();
}
/**
* Is the response a not found error?
*
* @return Boolean
*/
public function isNotFound()
{
return 404 === $this->getStatusCode();
}
/**
* Is the response empty?
*
* @return Boolean
*/
public function isEmpty()
{
return in_array($this->getStatusCode(), array(201, 204, 304));
}
// private
private function parseStatusLine()
{
$headers = $this->getHeaders();
if (isset($headers[0]) && 3 == count($parts = explode(' ', $headers[0], 3))) {
$this->protocolVersion = (float) $parts[0];
$this->statusCode = (integer) $parts[1];
$this->reasonPhrase = $parts[2];
} else {
$this->protocolVersion = $this->statusCode = $this->reasonPhrase = false;
}
}
private function resetStatusLine()
{
$this->protocolVersion = $this->statusCode = $this->reasonPhrase = null;
}
}

View file

@ -0,0 +1,216 @@
<?php
namespace Buzz\Util;
use Buzz\Message\RequestInterface;
class Cookie
{
const ATTR_DOMAIN = 'domain';
const ATTR_PATH = 'path';
const ATTR_SECURE = 'secure';
const ATTR_MAX_AGE = 'max-age';
const ATTR_EXPIRES = 'expires';
protected $name;
protected $value;
protected $attributes = array();
protected $createdAt;
/**
* Constructor.
*/
public function __construct()
{
$this->createdAt = time();
}
/**
* Returns true if the current cookie matches the supplied request.
*
* @return boolean
*/
public function matchesRequest(RequestInterface $request)
{
// domain
if (!$this->matchesDomain(parse_url($request->getHost(), PHP_URL_HOST))) {
return false;
}
// path
if (!$this->matchesPath($request->getResource())) {
return false;
}
// secure
if ($this->hasAttribute(static::ATTR_SECURE) && !$request->isSecure()) {
return false;
}
return true;
}
/**
* Returns true of the current cookie has expired.
*
* Checks the max-age and expires attributes.
*
* @return boolean Whether the current cookie has expired
*/
public function isExpired()
{
$maxAge = $this->getAttribute(static::ATTR_MAX_AGE);
if ($maxAge && time() - $this->getCreatedAt() > $maxAge) {
return true;
}
$expires = $this->getAttribute(static::ATTR_EXPIRES);
if ($expires && strtotime($expires) < time()) {
return true;
}
return false;
}
/**
* Returns true if the current cookie matches the supplied domain.
*
* @param string $domain A domain hostname
*
* @return boolean
*/
public function matchesDomain($domain)
{
$cookieDomain = $this->getAttribute(static::ATTR_DOMAIN);
if (0 === strpos($cookieDomain, '.')) {
$pattern = '/\b'.preg_quote(substr($cookieDomain, 1), '/').'$/i';
return (boolean) preg_match($pattern, $domain);
} else {
return 0 == strcasecmp($cookieDomain, $domain);
}
}
/**
* Returns true if the current cookie matches the supplied path.
*
* @param string $path A path
*
* @return boolean
*/
public function matchesPath($path)
{
$needle = $this->getAttribute(static::ATTR_PATH);
return null === $needle || 0 === strpos($path, $needle);
}
/**
* Populates the current cookie with data from the supplied Set-Cookie header.
*
* @param string $header A Set-Cookie header
* @param string $issuingDomain The domain that issued the header
*/
public function fromSetCookieHeader($header, $issuingDomain)
{
list($this->name, $header) = explode('=', $header, 2);
if (false === strpos($header, ';')) {
$this->value = $header;
$header = null;
} else {
list($this->value, $header) = explode(';', $header, 2);
}
$this->clearAttributes();
foreach (array_map('trim', explode(';', trim($header))) as $pair) {
if (false === strpos($pair, '=')) {
$name = $pair;
$value = null;
} else {
list($name, $value) = explode('=', $pair);
}
$this->setAttribute($name, $value);
}
if (!$this->getAttribute(static::ATTR_DOMAIN)) {
$this->setAttribute(static::ATTR_DOMAIN, $issuingDomain);
}
}
/**
* Formats a Cookie header for the current cookie.
*
* @return string An HTTP request Cookie header
*/
public function toCookieHeader()
{
return 'Cookie: '.$this->getName().'='.$this->getValue();
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
public function setAttributes(array $attributes)
{
// attributes are case insensitive
$this->attributes = array_change_key_case($attributes);
}
public function setAttribute($name, $value)
{
$this->attributes[strtolower($name)] = $value;
}
public function getAttributes()
{
return $this->attributes;
}
public function getAttribute($name)
{
$name = strtolower($name);
if (isset($this->attributes[$name])) {
return $this->attributes[$name];
}
}
public function hasAttribute($name)
{
return array_key_exists($name, $this->attributes);
}
public function clearAttributes()
{
$this->setAttributes(array());
}
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
public function getCreatedAt()
{
return $this->createdAt;
}
}

View file

@ -0,0 +1,79 @@
<?php
namespace Buzz\Util;
use Buzz\Message\MessageInterface;
use Buzz\Message\RequestInterface;
class CookieJar
{
protected $cookies = array();
public function setCookies($cookies)
{
$this->cookies = array();
foreach ($cookies as $cookie) {
$this->addCookie($cookie);
}
}
public function getCookies()
{
return $this->cookies;
}
/**
* Adds a cookie to the current cookie jar.
*
* @param Cookie $cookie A cookie object
*/
public function addCookie(Cookie $cookie)
{
$this->cookies[] = $cookie;
}
/**
* Adds Cookie headers to the supplied request.
*
* @param RequestInterface $request A request object
*/
public function addCookieHeaders(RequestInterface $request)
{
foreach ($this->cookies as $cookie) {
if ($cookie->matchesRequest($request)) {
$request->addHeader($cookie->toCookieHeader());
}
}
}
/**
* Processes Set-Cookie headers from a request/response pair.
*
* @param RequestInterface $request A request object
* @param MessageInterface $response A response object
*/
public function processSetCookieHeaders(RequestInterface $request, MessageInterface $response)
{
foreach ($response->getHeader('Set-Cookie', false) as $header) {
$cookie = new Cookie();
$cookie->fromSetCookieHeader($header, parse_url($request->getHost(), PHP_URL_HOST));
$this->addCookie($cookie);
}
}
/**
* Removes expired cookies.
*/
public function clearExpiredCookies()
{
foreach ($this->cookies as $i => $cookie) {
if ($cookie->isExpired()) {
unset($this->cookies[$i]);
}
}
// reset array keys
$this->cookies = array_values($this->cookies);
}
}

View file

@ -0,0 +1,190 @@
<?php
namespace Buzz\Util;
use Buzz\Message\RequestInterface;
use Buzz\Exception\InvalidArgumentException;
class Url
{
private static $defaultPorts = array(
'http' => 80,
'https' => 443,
);
private $url;
private $components;
/**
* Constructor.
*
* @param string $url The URL
*
* @throws InvalidArgumentException If the URL is invalid
*/
public function __construct($url)
{
$components = parse_url($url);
if (false === $components) {
throw new InvalidArgumentException(sprintf('The URL "%s" is invalid.', $url));
}
// support scheme-less URLs
if (!isset($components['host']) && isset($components['path'])) {
$pos = strpos($components['path'], '/');
if (false === $pos) {
$components['host'] = $components['path'];
unset($components['path']);
} elseif (0 !== $pos) {
list($host, $path) = explode('/', $components['path'], 2);
$components['host'] = $host;
$components['path'] = '/'.$path;
}
}
// default port
if (isset($components['scheme']) && !isset($components['port']) && isset(self::$defaultPorts[$components['scheme']])) {
$components['port'] = self::$defaultPorts[$components['scheme']];
}
$this->url = $url;
$this->components = $components;
}
public function getScheme()
{
return $this->parseUrl('scheme');
}
public function getHostname()
{
return $this->parseUrl('host');
}
public function getPort()
{
return $this->parseUrl('port');
}
public function getUser()
{
return $this->parseUrl('user');
}
public function getPassword()
{
return $this->parseUrl('pass');
}
public function getPath()
{
return $this->parseUrl('path');
}
public function getQueryString()
{
return $this->parseUrl('query');
}
public function getFragment()
{
return $this->parseUrl('fragment');
}
/**
* Returns a host string that combines scheme, hostname and port.
*
* @return string A host value for an HTTP message
*/
public function getHost()
{
if ($hostname = $this->parseUrl('host')) {
$host = $scheme = $this->parseUrl('scheme', 'http');
$host .= '://';
$host .= $hostname;
$port = $this->parseUrl('port');
if ($port && (!isset(self::$defaultPorts[$scheme]) || self::$defaultPorts[$scheme] != $port)) {
$host .= ':'.$port;
}
return $host;
}
}
/**
* Returns a resource string that combines path and query string.
*
* @return string A resource value for an HTTP message
*/
public function getResource()
{
$resource = $this->parseUrl('path', '/');
if ($query = $this->parseUrl('query')) {
$resource .= '?'.$query;
}
return $resource;
}
/**
* Returns a formatted URL.
*/
public function format($pattern)
{
static $map = array(
's' => 'getScheme',
'u' => 'getUser',
'a' => 'getPassword',
'h' => 'getHostname',
'o' => 'getPort',
'p' => 'getPath',
'q' => 'getQueryString',
'f' => 'getFragment',
'H' => 'getHost',
'R' => 'getResource',
);
$url = '';
$parts = str_split($pattern);
while ($part = current($parts)) {
if (isset($map[$part])) {
$method = $map[$part];
$url .= $this->$method();
} elseif ('\\' == $part) {
$url .= next($parts);
} elseif (!ctype_alpha($part)) {
$url .= $part;
} else {
throw new InvalidArgumentException(sprintf('The format character "%s" is invalid.', $part));
}
next($parts);
}
return $url;
}
/**
* Applies the current URL to the supplied request.
*/
public function applyToRequest(RequestInterface $request)
{
$request->setResource($this->getResource());
$request->setHost($this->getHost());
}
private function parseUrl($component = null, $default = null)
{
if (null === $component) {
return $this->components;
} elseif (isset($this->components[$component])) {
return $this->components[$component];
} else {
return $default;
}
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace KeenIO\Http\Adaptor;
/**
* Class AdaptorInterface
*
* @package KeenIO\Http\Adaptor
*/
interface AdaptorInterface
{
/**
* post to the KeenIO API
*
* @param $url
* @param array $parameters
* @return mixed
*/
public function doPost($url, array $parameters);
}

View file

@ -0,0 +1,49 @@
<?php
namespace KeenIO\Http\Adaptor;
use Buzz\Browser;
use Buzz\Client\Curl;
/**
* Class Buzz
* @package KeenIO\Http\Adaptor
*/
final class Buzz implements AdaptorInterface
{
private $apiKey;
private $browser;
/**
* @param $apiKey
* @param null $client
*/
public function __construct($apiKey)
{
$this->apiKey = $apiKey;
$this->browser = new Browser(new Curl());
$this->browser->getClient()->setVerifyPeer(false);
}
/**
* post to the KeenIO API
*
* @param $url
* @param array $parameters
* @return mixed
*/
public function doPost($url, array $parameters)
{
$headers = array(
// 'Authorization' => $this->apiKey,
'Content-Type' => 'application/json'
);
$content = json_encode($parameters);
$response = $this->browser->post($url, $headers, $content);
return $response->getContent();
}
}

View file

@ -0,0 +1,215 @@
<?php
namespace KeenIO\Service;
use KeenIO\Http\Adaptor\AdaptorInterface
, KeenIO\Http\Adaptor\Buzz as BuzzHttpAdaptor
;
/**
* Class KeenIO
*
* @package KeenIO\Service
*/
final class KeenIO
{
private static $projectId;
private static $apiKey;
private static $httpAdaptor;
public static function getApiKey()
{
return self::$apiKey;
}
/**
* @param $value
* @throws \Exception
*/
public static function setApiKey($value)
{
if (!ctype_alnum($value)) {
throw new \Exception(sprintf("API Key '%s' contains invalid characters or spaces.", $value));
}
self::$apiKey = $value;
}
public static function getProjectId()
{
return self::$projectId;
}
/**
* @param $value
* @throws \Exception
*/
public static function setProjectId($value)
{
// Validate collection name
if (!ctype_alnum($value)) {
throw new \Exception(
"Project ID '" . $value . "' contains invalid characters or spaces."
);
}
self::$projectId = $value;
}
/**
* @return BuzzHttpAdaptor
*/
public static function getHttpAdaptor()
{
if (!self::$httpAdaptor) {
self::$httpAdaptor = new BuzzHttpAdaptor(self::getApiKey());
}
return self::$httpAdaptor;
}
/**
* @param AdaptorInterface $httpAdaptor
*/
public static function setHttpAdaptor(AdaptorInterface $httpAdaptor)
{
self::$httpAdaptor = $httpAdaptor;
}
/**
* @param $projectId
* @param $apiKey
*/
public static function configure($projectId, $apiKey)
{
self::setProjectId($projectId);
self::setApiKey($apiKey);
}
/**
* add an event to KeenIO
*
* @param $collectionName
* @param $parameters
* @return mixed
* @throws \Exception
*/
public static function addEvent($collectionName, $parameters = array())
{
self::validateConfiguration();
if (!ctype_alnum($collectionName)) {
throw new \Exception(
sprintf("Collection name '%s' contains invalid characters or spaces.", $collectionName)
);
}
$url = sprintf(
'https://api.keen.io/3.0/projects/%s/events/%s',
self::getProjectId(),
$collectionName
);
$response = self::getHttpAdaptor()->doPost($url, $parameters);
$json = json_decode($response);
return $json->created;
}
/**
* get a scoped key for an array of filters
*
* @param $filters
* @return string
*/
public static function getScopedKey($filters)
{
self::validateConfiguration();
$filterArray = array('filters' => $filters);
$filterJson = self::padString(json_encode($filterArray));
$ivLength = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($ivLength);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::getApiKey(), $filterJson, MCRYPT_MODE_CBC, $iv);
$ivHex = bin2hex($iv);
$encryptedHex = bin2hex($encrypted);
$scopedKey = $ivHex . $encryptedHex;
return $scopedKey;
}
/**
* decrypt a scoped key (primarily used for testing)
*
* @param $scopedKey
* @return mixed
*/
public static function decryptScopedKey($scopedKey)
{
$ivLength = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC) * 2;
$ivHex = substr($scopedKey, 0, $ivLength);
$encryptedHex = substr($scopedKey, $ivLength);
$resultPadded = mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
self::getApiKey(),
pack('H*', $encryptedHex),
MCRYPT_MODE_CBC,
pack('H*', $ivHex)
);
$result = self::unpadString($resultPadded);
$filterArray = json_decode($result, true);
return $filterArray['filters'];
}
/**
* implement PKCS7 padding
*
* @param $string
* @param int $blockSize
* @return string
*/
protected static function padString($string, $blockSize = 32)
{
$paddingSize = $blockSize - (strlen($string) % $blockSize);
$string .= str_repeat(chr($paddingSize), $paddingSize);
return $string;
}
/**
* remove padding for a PKCS7-padded string
*
* @param $string
* @return string
*/
protected static function unpadString($string)
{
$len = strlen($string);
$pad = ord($string[$len - 1]);
return substr($string, 0, $len - $pad);
}
protected static function validateConfiguration()
{
// Validate configuration
if (!self::getProjectId()) {
throw new \Exception('Keen IO has not been configured');
}
// if (!self::getProjectId() or !self::getApiKey()) {
// throw new \Exception('Keen IO has not been configured');
// }
}
}

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);
}
}

View file

@ -0,0 +1,149 @@
<?php
namespace MailSo\Cache;
/**
* @category MailSo
* @package Cache
*/
class CacheClient
{
/**
* @var \MailSo\Cache\DriverInterface
*/
private $oDriver;
/**
* @var string
*/
private $sCacheIndex;
/**
* @access private
*/
private function __construct()
{
$this->oDriver = null;
$this->sCacheIndex = '';
}
/**
* @return \MailSo\Cache\CacheClient
*/
public static function NewInstance()
{
return new self();
}
/**
* @param string $sKey
* @param string $sValue
*
* @return bool
*/
public function Set($sKey, $sValue)
{
return $this->oDriver ? $this->oDriver->Set($sKey.$this->sCacheIndex, $sValue) : false;
}
/**
* @param string $sKey
*
* @return bool
*/
public function SetTimer($sKey)
{
return $this->Set($sKey.'/TIMER', time());
}
/**
* @param string $sKey
*
* @return string
*/
public function Get($sKey)
{
$sValue = '';
if ($this->oDriver)
{
$sValue = $this->oDriver->Get($sKey.$this->sCacheIndex);
}
return $sValue;
}
/**
* @param string $sKey
*
* @return int
*/
public function GetTimer($sKey)
{
$iTimer = 0;
$sValue = $this->Get($sKey.'/TIMER');
if (0 < strlen($sValue) && is_numeric($sValue))
{
$iTimer = (int) $sValue;
}
return $iTimer;
}
/**
* @param string $sKey
*
* @return \MailSo\Cache\CacheClient
*/
public function Delete($sKey)
{
if ($this->oDriver)
{
$this->oDriver->Delete($sKey.$this->sCacheIndex);
}
return $this;
}
/**
* @param \MailSo\Cache\DriverInterface $oDriver
*
* @return \MailSo\Cache\CacheClient
*/
public function SetDriver(\MailSo\Cache\DriverInterface $oDriver)
{
$this->oDriver = $oDriver;
return $this;
}
/**
* @param int $iTimeToClearInHours = 24
*
* @return bool
*/
public function GC($iTimeToClearInHours = 24)
{
return $this->oDriver ? $this->oDriver->GC($iTimeToClearInHours) : false;
}
/**
* @return bool
*/
public function IsInited()
{
return $this->oDriver instanceof \MailSo\Cache\DriverInterface;
}
/**
* @param string $sCacheIndex
*
* @return \MailSo\Cache\CacheClient
*/
public function SetCacheIndex($sCacheIndex)
{
$this->sCacheIndex = 0 < \strlen($sCacheIndex) ? "\x0".$sCacheIndex : '';
return $this;
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace MailSo\Cache;
/**
* @category MailSo
* @package Cache
*/
interface DriverInterface
{
/**
* @param string $sKey
* @param string $sValue
*
* @return bool
*/
public function Set($sKey, $sValue);
/**
* @param string $sKey
*
* @return string
*/
public function Get($sKey);
/**
* @param string $sKey
*
* @return void
*/
public function Delete($sKey);
/**
* @param int $iTimeToClearInHours = 24
*
* @return bool
*/
public function GC($iTimeToClearInHours = 24);
}

View file

@ -0,0 +1,76 @@
<?php
namespace MailSo\Cache\Drivers;
/**
* @category MailSo
* @package Cache
* @subpackage Drivers
*/
class APC implements \MailSo\Cache\DriverInterface
{
/**
* @return \MailSo\Cache\Drivers\APC
*/
public static function NewInstance()
{
return new self();
}
/**
* @param string $sKey
* @param string $sValue
*
* @return bool
*/
public function Set($sKey, $sValue)
{
return \apc_store($this->generateCachedKey($sKey), $sValue);
}
/**
* @param string $sKey
*
* @return string
*/
public function Get($sKey)
{
$sValue = \apc_fetch($this->generateCachedKey($sKey));
return \is_string($sValue) ? $sValue : '';
}
/**
* @param string $sKey
*
* @return void
*/
public function Delete($sKey)
{
\apc_delete($this->generateCachedKey($sKey));
}
/**
* @param int $iTimeToClearInHours = 24
*
* @return bool
*/
public function GC($iTimeToClearInHours = 24)
{
if (0 === $iTimeToClearInHours)
{
return \apc_clear_cache('user');
}
return false;
}
/**
* @param string $sKey
*
* @return string
*/
private function generateCachedKey($sKey)
{
return \sha1($sKey);
}
}

View file

@ -0,0 +1,126 @@
<?php
namespace MailSo\Cache\Drivers;
/**
* @category MailSo
* @package Cache
* @subpackage Drivers
*/
class File implements \MailSo\Cache\DriverInterface
{
/**
* @var string
*/
private $sCacheFolder;
/**
* @access private
*
* @param string $sCacheFolder
*/
private function __construct($sCacheFolder)
{
$this->sCacheFolder = $sCacheFolder;
$this->sCacheFolder = rtrim(trim($this->sCacheFolder), '\\/').'/';
if (!\is_dir($this->sCacheFolder))
{
@\mkdir($this->sCacheFolder, 0777);
}
}
/**
* @param string $sCacheFolder
*
* @return \MailSo\Cache\Drivers\File
*/
public static function NewInstance($sCacheFolder)
{
return new self($sCacheFolder);
}
/**
* @param string $sKey
* @param string $sValue
*
* @return bool
*/
public function Set($sKey, $sValue)
{
return false !== \file_put_contents($sPath = $this->generateCachedFileName($sKey, true), $sValue);
}
/**
* @param string $sKey
*
* @return string
*/
public function Get($sKey)
{
$sValue = '';
$sPath = $this->generateCachedFileName($sKey);
if (\file_exists($sPath))
{
$sValue = \file_get_contents($sPath);
}
return \is_string($sValue) ? $sValue : '';
}
/**
* @param string $sKey
*
* @return void
*/
public function Delete($sKey)
{
$sPath = $this->generateCachedFileName($sKey);
if (\file_exists($sPath))
{
\unlink($sPath);
}
}
/**
* @param int $iTimeToClearInHours = 24
*
* @return bool
*/
public function GC($iTimeToClearInHours = 24)
{
if (0 < $iTimeToClearInHours)
{
\MailSo\Base\Utils::RecTimeDirRemove($this->sCacheFolder, 60 * 60 * $iTimeToClearInHours, \time());
return true;
}
return false;
}
/**
* @param string $sKey
* @param bool $bMkDir = false
*
* @return string
*/
private function generateCachedFileName($sKey, $bMkDir = false)
{
$sFilePath = '';
if (3 < \strlen($sKey))
{
$sKeyPath = \sha1($sKey);
$sKeyPath = \substr($sKeyPath, 0, 2).'/'.\substr($sKeyPath, 2, 2).'/'.$sKeyPath;
$sFilePath = $this->sCacheFolder.'/'.$sKeyPath;
if ($bMkDir && !\is_dir(\dirname($sFilePath)))
{
if (!\mkdir(\dirname($sFilePath), 0777, true))
{
$sFilePath = '';
}
}
}
return $sFilePath;
}
}

View file

@ -0,0 +1,120 @@
<?php
namespace MailSo\Cache\Drivers;
/**
* @category MailSo
* @package Cache
* @subpackage Drivers
*/
class Memcache implements \MailSo\Cache\DriverInterface
{
/**
* @var string
*/
private $sHost;
/**
* @var int
*/
private $iPost;
/**
* @var int
*/
private $iExpire;
/**
* @var \Memcache|null
*/
private $oMem;
/**
* @param string $sHost = '127.0.0.1'
* @param int $iPost = 11211
* @param int $iExpire = 43200
*/
private function __construct($sHost = '127.0.0.1', $iPost = 11211, $iExpire = 43200)
{
$this->sHost = $sHost;
$this->iPost = $iPost;
$this->iExpire = 0 < $iExpire ? $iExpire : 43200;
$this->oMem = new \Memcache();
if (!$this->oMem->connect($this->sHost, $this->iPost))
{
$this->oMem = null;
}
}
/**
* @param string $sHost = '127.0.0.1'
* @param int $iPost = 11211
*
* @return \MailSo\Cache\Drivers\APC
*/
public static function NewInstance($sHost = '127.0.0.1', $iPost = 11211)
{
return new self($sHost, $iPost);
}
/**
* @param string $sKey
* @param string $sValue
*
* @return bool
*/
public function Set($sKey, $sValue)
{
return $this->oMem ? $this->oMem->set($this->generateCachedKey($sKey), $sValue, 0, $this->iExpire) : false;
}
/**
* @param string $sKey
*
* @return string
*/
public function Get($sKey)
{
$sValue = $this->oMem ? $this->oMem->get($this->generateCachedKey($sKey)) : '';
return \is_string($sValue) ? $sValue : '';
}
/**
* @param string $sKey
*
* @return void
*/
public function Delete($sKey)
{
if ($this->oMem)
{
$this->oMem->delete($this->generateCachedKey($sKey));
}
}
/**
* @param int $iTimeToClearInHours = 24
*
* @return bool
*/
public function GC($iTimeToClearInHours = 24)
{
if (0 === $iTimeToClearInHours && $this->oMem)
{
return $this->oMem->flush();
}
return false;
}
/**
* @param string $sKey
*
* @return string
*/
private function generateCachedKey($sKey)
{
return \sha1($sKey);
}
}

View file

@ -0,0 +1,855 @@
<?php
namespace MailSo\Imap;
/**
* @category MailSo
* @package Imap
*/
class BodyStructure
{
/**
* @var string
*/
private $sContentType;
/**
* @var string
*/
private $sCharset;
/**
* @var array
*/
private $aBodyParams;
/**
* @var string
*/
private $sContentID;
/**
* @var string
*/
private $sDescription;
/**
* @var string
*/
private $sMailEncodingName;
/**
* @var string
*/
private $sDisposition;
/**
* @var array
*/
private $aDispositionParams;
/**
* @var string
*/
private $sFileName;
/**
* @var string
*/
private $sLanguage;
/**
* @var string
*/
private $sLocation;
/**
* @var int
*/
private $iSize;
/**
* @var int
*/
private $iTextLineCount;
/**
* @var string
*/
private $sPartID;
/**
* @var array
*/
private $aSubParts;
/**
* @access private
*
* @param string $sContentType
* @param string $sCharset
* @param array $aBodyParams
* @param string $sContentID
* @param string $sDescription
* @param string $sMailEncodingName
* @param string $sDisposition
* @param array $aDispositionParams
* @param string $sFileName
* @param string $sLanguage
* @param string $sLocation
* @param int $iSize
* @param int $iTextLineCount
* @param string $sPartID
* @param array $aSubParts
*/
private function __construct($sContentType, $sCharset, $aBodyParams, $sContentID,
$sDescription, $sMailEncodingName, $sDisposition, $aDispositionParams, $sFileName,
$sLanguage, $sLocation, $iSize, $iTextLineCount, $sPartID, $aSubParts)
{
$this->sContentType = $sContentType;
$this->sCharset = $sCharset;
$this->aBodyParams = $aBodyParams;
$this->sContentID = $sContentID;
$this->sDescription = $sDescription;
$this->sMailEncodingName = $sMailEncodingName;
$this->sDisposition = $sDisposition;
$this->aDispositionParams = $aDispositionParams;
$this->sFileName = $sFileName;
$this->sLanguage = $sLanguage;
$this->sLocation = $sLocation;
$this->iSize = $iSize;
$this->iTextLineCount = $iTextLineCount;
$this->sPartID = $sPartID;
$this->aSubParts = $aSubParts;
}
/**
* return string
*/
public function MailEncodingName()
{
return $this->sMailEncodingName;
}
/**
* return string
*/
public function PartID()
{
return (string) $this->sPartID;
}
/**
* return string
*/
public function FileName()
{
return $this->sFileName;
}
/**
* return string
*/
public function ContentType()
{
return $this->sContentType;
}
/**
* return int
*/
public function Size()
{
return (int) $this->iSize;
}
/**
* return int
*/
public function EstimatedSize()
{
$fCoefficient = 1;
switch (strtolower($this->MailEncodingName()))
{
case 'base64':
$fCoefficient = 0.75;
break;
case 'quoted-printable':
$fCoefficient = 0.44;
break;
}
return (int) ($this->Size() * $fCoefficient);
}
/**
* return string
*/
public function Charset()
{
return $this->sCharset;
}
/**
* return string
*/
public function ContentID()
{
return (null === $this->sContentID) ? '' : $this->sContentID;
}
/**
* return bool
*/
public function IsInline()
{
return (null === $this->sDisposition) ? false : ('inline' === strtolower($this->sDisposition));
}
/**
* @return array|null
*/
public function SearchPlainParts()
{
$aReturn = array();
$aParts = $this->SearchByContentType('text/plain');
foreach ($aParts as $oPart)
{
if (!$oPart->isAttachBodyPart())
{
$aReturn[] = $oPart;
}
}
return $aReturn;
}
/**
* @return array|null
*/
public function SearchHtmlParts()
{
$aReturn = array();
$aParts = $this->SearchByContentType('text/html');
foreach ($aParts as $oPart)
{
if (!$oPart->isAttachBodyPart())
{
$aReturn[] = $oPart;
}
}
return $aReturn;
}
/**
* @return array|null
*/
public function SearchHtmlOrPlainParts()
{
$mResult = $this->SearchHtmlParts();
if (null === $mResult || (is_array($mResult) && 0 === count($mResult)))
{
$mResult = $this->SearchPlainParts();
}
return $mResult;
}
/**
* @return string
*/
public function SearchCharset()
{
$sResult = '';
$mHtmlParts = $this->SearchHtmlParts();
$mPlainParts = $this->SearchPlainParts();
$mParts = array();
if (is_array($mHtmlParts) && 0 < count($mHtmlParts))
{
$mParts = array_merge($mParts, $mHtmlParts);
}
if (is_array($mPlainParts) && 0 < count($mPlainParts))
{
$mParts = array_merge($mParts, $mPlainParts);
}
foreach ($mParts as $oPart)
{
$sResult = $oPart ? $oPart->Charset() : '';
if (!empty($sResult))
{
break;
}
}
if (0 === strlen($sResult))
{
$aParts = $this->SearchAttachmentsParts();
foreach ($aParts as $oPart)
{
if (0 === strlen($sResult))
{
$sResult = $oPart ? $oPart->Charset() : '';
}
else
{
break;
}
}
}
return $sResult;
}
/**
* @return bool
*/
protected function isAttachBodyPart()
{
$bResult = (
(null !== $this->sDisposition && 'attachment' === strtolower($this->sDisposition))
);
if (!$bResult && null !== $this->sContentType)
{
$sContentType = strtolower($this->sContentType);
$bResult = false === strpos($sContentType, 'multipart/') &&
'text/html' !== $sContentType && 'text/plain' !== $sContentType;
}
return $bResult;
}
/**
* @return array
*/
public function SearchAttachmentsParts()
{
$aReturn = array();
if ($this->isAttachBodyPart())
{
$aReturn[] = $this;
}
if (is_array($this->aSubParts) && 0 < count($this->aSubParts))
{
foreach ($this->aSubParts as /* @var $oSubPart \MailSo\Imap\BodyStructure */ &$oSubPart)
{
$aReturn = array_merge($aReturn, $oSubPart->SearchAttachmentsParts());
unset($oSubPart);
}
}
return $aReturn;
}
/**
* @param string $sContentType
*
* @return array
*/
public function SearchByContentType($sContentType)
{
$aReturn = array();
if (strtolower($sContentType) === $this->sContentType)
{
$aReturn[] = $this;
}
if (is_array($this->aSubParts) && 0 < count($this->aSubParts))
{
foreach ($this->aSubParts as /* @var $oSubPart \MailSo\Imap\BodyStructure */ &$oSubPart)
{
$aReturn = array_merge($aReturn, $oSubPart->SearchByContentType($sContentType));
}
}
return $aReturn;
}
/**
* @param string $sMimeIndex
*
* @return \MailSo\Imap\BodyStructure
*/
public function GetPartByMimeIndex($sMimeIndex)
{
$oPart = null;
if (0 < strlen($sMimeIndex))
{
if ($sMimeIndex === $this->sPartID)
{
$oPart = $this;
}
if (null === $oPart && is_array($this->aSubParts) && 0 < count($this->aSubParts))
{
foreach ($this->aSubParts as /* @var $oSubPart \MailSo\Imap\BodyStructure */ &$oSubPart)
{
$oPart = $oSubPart->GetPartByMimeIndex($sMimeIndex);
if (null !== $oPart)
{
break;
}
}
}
}
return $oPart;
}
/**
* @param array $aParams
* @param string $sParamName
* @param string $sCharset = \MailSo\Base\Enumerations\Charset::UTF_8
*
* @return string
*/
private static function decodeAttrParamenter($aParams, $sParamName, $sCharset = \MailSo\Base\Enumerations\Charset::UTF_8)
{
$sResult = '';
if (isset($aParams[$sParamName]))
{
$sResult = \MailSo\Base\Utils::DecodeHeaderValue($aParams[$sParamName], $sCharset);
}
else if (isset($aParams[$sParamName.'*']))
{
$aValueParts = explode('\'\'', $aParams[$sParamName.'*'], 2);
if (is_array($aValueParts) && 2 === count($aValueParts))
{
$sCharset = isset($aValueParts[0]) ? $aValueParts[0] : \MailSo\Base\Enumerations\Charset::UTF_8;
$sResult = \MailSo\Base\Utils::ConvertEncoding(
urldecode($aValueParts[1]), $sCharset, \MailSo\Base\Enumerations\Charset::UTF_8);
}
else
{
$sResult = urldecode($aParams[$sParamName.'*']);
}
}
else if (isset($aParams[$sParamName.'*0*']))
{
$sCharset = '';
$aFileNames = array();
foreach ($aParams as $sName => $sValue)
{
$aMatches = array();
if ($sParamName.'*0*' === $sName)
{
if (0 === strlen($sCharset))
{
$aValueParts = explode('\'\'', $sValue, 2);
if (is_array($aValueParts) && 2 === count($aValueParts) && 0 < strlen($aValueParts[0]))
{
$sCharset = $aValueParts[0];
$sValue = $aValueParts[1];
}
}
$aFileNames[0] = $sValue;
}
else if ($sParamName.'*0*' !== $sName && preg_match('/^'.preg_quote($sParamName, '/').'\*([0-9]+)\*$/i', $sName, $aMatches) && 0 < strlen($aMatches[1]))
{
$aFileNames[(int) $aMatches[1]] = $sValue;
}
}
if (0 < count($aFileNames))
{
ksort($aFileNames, SORT_NUMERIC);
$sResult = implode(array_values($aFileNames));
$sResult = urldecode($sResult);
if (0 < strlen($sCharset))
{
$sResult = \MailSo\Base\Utils::ConvertEncoding($sResult,
$sCharset, \MailSo\Base\Enumerations\Charset::UTF_8);
}
}
}
return $sResult;
}
/**
* @param array $aBodyStructure
* @param string $sPartID = ''
*
* @return \MailSo\Imap\BodyStructure
*/
public static function NewInstance(array $aBodyStructure, $sPartID = '')
{
if (!is_array($aBodyStructure) || 2 > count($aBodyStructure))
{
return null;
}
else
{
$sBodyMainType = null;
if (is_string($aBodyStructure[0]) && 'NIL' !== $aBodyStructure[0])
{
$sBodyMainType = $aBodyStructure[0];
}
$sBodySubType = null;
$sContentType = '';
$aSubParts = null;
$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]))
{
return null;
}
else
{
$sBodyMainType = 'multipart';
$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))
{
if (!is_string($aBodyStructure[$iExtraItemPos]) || 'NIL' === $aBodyStructure[$iExtraItemPos])
{
return null;
}
$sBodySubType = strtolower($aBodyStructure[$iExtraItemPos]);
$iExtraItemPos++;
}
if ($iExtraItemPos < count($aBodyStructure))
{
$sBodyParamList = $aBodyStructure[$iExtraItemPos];
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'];
}
if (is_array($aBodyParams))
{
$sName = self::decodeAttrParamenter($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
{
$iSize = -1;
}
if (0 === strlen($sPartID) || '.' === $sPartID[strlen($sPartID) - 1])
{
// This is the only sub-part of the message (otherwise, it would be
// 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];
}
else
{
$iTextLineCount = -1;
}
}
else
{
$iTextLineCount = -1;
}
$iExtraItemPos++;
}
else if ('message' === $sBodyMainType && 'rfc822' === $sBodySubType)
{
if ($iExtraItemPos + 2 < count($aBodyStructure))
{
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
}
$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);
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
);
}
}
/**
* @param array $aBodyStructure
* @param string $sPartID
*
* @return \MailSo\Imap\BodyStructure|null
*/
public static function NewInstanceFromRfc822SubPart(array $aBodyStructure, $sSubPartID)
{
$oBody = null;
$aBodySubStructure = self::findPartByIndexInArray($aBodyStructure, $sSubPartID);
if ($aBodySubStructure && is_array($aBodySubStructure) && isset($aBodySubStructure[8]))
{
$oBody = self::NewInstance($aBodySubStructure[8], $sSubPartID);
}
return $oBody;
}
/**
* @param array $aList
* @param string $sPartID
*
* @return array|null
*/
private static function findPartByIndexInArray(array $aList, $sPartID)
{
$bFind = false;
$aPath = explode('.', ''.$sPartID);
$aCurrentPart = $aList;
foreach ($aPath as $iPos => $iNum)
{
$iIndex = intval($iNum) - 1;
if (0 <= $iIndex && 0 < $iPos ? isset($aCurrentPart[8][$iIndex]) : isset($aCurrentPart[$iIndex]))
{
$aCurrentPart = 0 < $iPos ? $aCurrentPart[8][$iIndex] : $aCurrentPart[$iIndex];
$bFind = true;
}
}
return $bFind ? $aCurrentPart : null;
}
/**
* 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.
*
* @param array $aList
*
* @return array
*/
private static function getKeyValueListFromArrayList(array $aList)
{
$aDict = null;
if (0 === count($aList) % 2)
{
$aDict = array();
for ($iIndex = 0, $iLen = count($aList); $iIndex < $iLen; $iIndex += 2)
{
if (is_string($aList[$iIndex]) && isset($aList[$iIndex + 1]) && is_string($aList[$iIndex + 1]))
{
$aDict[strtolower($aList[$iIndex])] = $aList[$iIndex + 1];
}
}
}
return $aDict;
}
}

View file

@ -0,0 +1,119 @@
<?php
namespace MailSo\Imap\Enumerations;
/**
* @category MailSo
* @package Imap
* @subpackage Enumerations
*/
class FetchType
{
const ALL = 'ALL';
const FAST = 'FAST';
const FULL = 'FULL';
const BODY = 'BODY';
const BODY_PEEK = 'BODY.PEEK';
const BODY_HEADER = 'BODY[HEADER]';
const BODY_HEADER_PEEK = 'BODY.PEEK[HEADER]';
const BODYSTRUCTURE = 'BODYSTRUCTURE';
const ENVELOPE = 'ENVELOPE';
const FLAGS = 'FLAGS';
const INTERNALDATE = 'INTERNALDATE';
const RFC822 = 'RFC822';
const RFC822_HEADER = 'RFC822.HEADER';
const RFC822_SIZE = 'RFC822.SIZE';
const RFC822_TEXT = 'RFC822.TEXT';
const UID = 'UID';
const INDEX = 'INDEX';
const GMAIL_MSGID = 'X-GM-MSGID';
const GMAIL_THRID = 'X-GM-THRID';
const GMAIL_LABELS = 'X-GM-LABELS';
/**
* @param array $aReturn
*
* @param string|array $mType
*/
private static function addHelper(&$aReturn, $mType)
{
if (is_string($mType))
{
$aReturn[$mType] = '';
}
else if (is_array($mType) && 2 === count($mType) && is_string($mType[0]) &&
is_callable($mType[1]))
{
$aReturn[$mType[0]] = $mType[1];
}
}
/**
* @param array $aHeaders
* @param bool $bPeek = true
*
* @return string
*/
public static function BuildBodyCustomHeaderRequest(array $aHeaders, $bPeek = true)
{
$sResult = '';
if (0 < count($aHeaders))
{
$aHeaders = array_map('trim', $aHeaders);
$aHeaders = array_map('strtoupper', $aHeaders);
$sResult = $bPeek ? self::BODY_PEEK : self::BODY;
$sResult .= '[HEADER.FIELDS ('.implode(' ', $aHeaders).')]';
}
return $sResult;
}
/**
* @param array $aFetchItems
*
* @return array
*/
public static function ChangeFetchItemsBefourRequest(array $aFetchItems)
{
$aReturn = array();
self::addHelper($aReturn, self::UID);
foreach ($aFetchItems as $mFetchKey)
{
switch ($mFetchKey)
{
default:
if (is_string($mFetchKey) || is_array($mFetchKey))
{
self::addHelper($aReturn, $mFetchKey);
}
break;
case self::INDEX:
case self::UID:
break;
case self::ALL:
self::addHelper($aReturn, self::FLAGS);
self::addHelper($aReturn, self::INTERNALDATE);
self::addHelper($aReturn, self::RFC822_SIZE);
self::addHelper($aReturn, self::ENVELOPE);
break;
case self::FAST:
self::addHelper($aReturn, self::FLAGS);
self::addHelper($aReturn, self::INTERNALDATE);
self::addHelper($aReturn, self::RFC822_SIZE);
break;
case self::FULL:
self::addHelper($aReturn, self::FLAGS);
self::addHelper($aReturn, self::INTERNALDATE);
self::addHelper($aReturn, self::RFC822_SIZE);
self::addHelper($aReturn, self::ENVELOPE);
self::addHelper($aReturn, self::BODY);
break;
}
}
return $aReturn;
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace MailSo\Imap\Enumerations;
/**
* @category MailSo
* @package Imap
* @subpackage Enumerations
*/
class FolderResponseStatus
{
const MESSAGES = 'MESSAGES';
const RECENT = 'RECENT';
const UNSEEN = 'UNSEEN';
const UIDNEXT = 'UIDNEXT';
const UIDVALIDITY = 'UIDVALIDITY';
}

View file

@ -0,0 +1,17 @@
<?php
namespace MailSo\Imap\Enumerations;
/**
* @category MailSo
* @package Imap
* @subpackage Enumerations
*/
class FolderStatus
{
const MESSAGES = 'MESSAGES';
const RECENT = 'RECENT';
const UNSEEN = 'UNSEEN';
const UIDNEXT = 'UIDNEXT';
const UIDVALIDITY = 'UIDVALIDITY';
}

View file

@ -0,0 +1,21 @@
<?php
namespace MailSo\Imap\Enumerations;
/**
* @category MailSo
* @package Imap
* @subpackage Enumerations
*/
class FolderType
{
const USER = 0;
const INBOX = 1;
const SENT = 2;
const DRAFTS = 3;
const SPAN = 4;
const TRASH = 5;
const IMPORTANT = 10;
const STARRED = 11;
const ALLMAIL = 12;
}

View file

@ -0,0 +1,18 @@
<?php
namespace MailSo\Imap\Enumerations;
/**
* @category MailSo
* @package Imap
* @subpackage Enumerations
*/
class MessageFlag
{
const RECENT = '\Recent';
const SEEN = '\Seen';
const DELETED = '\Deleted';
const FLAGGED = '\Flagged';
const ANSWERED = '\Answered';
const DRAFT = '\Draft';
}

View file

@ -0,0 +1,17 @@
<?php
namespace MailSo\Imap\Enumerations;
/**
* @category MailSo
* @package Imap
* @subpackage Enumerations
*/
class ResponseStatus
{
const OK = 'OK';
const NO = 'NO';
const BAD = 'BAD';
const BYE = 'BYE';
const PREAUTH = 'PREAUTH';
}

View file

@ -0,0 +1,16 @@
<?php
namespace MailSo\Imap\Enumerations;
/**
* @category MailSo
* @package Imap
* @subpackage Enumerations
*/
class ResponseType
{
const UNKNOWN = 0;
const TAGGED = 1;
const UNTAGGED = 2;
const CONTINUATION = 3;
}

View file

@ -0,0 +1,25 @@
<?php
namespace MailSo\Imap\Enumerations;
/**
* @category MailSo
* @package Imap
* @subpackage Enumerations
*/
class StoreAction
{
const SET_FLAGS = 'FLAGS';
const SET_FLAGS_SILENT = 'FLAGS.SILENT';
const ADD_FLAGS = '+FLAGS';
const ADD_FLAGS_SILENT = '+FLAGS.SILENT';
const REMOVE_FLAGS = '-FLAGS';
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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,48 @@
<?php
namespace MailSo\Imap\Exceptions;
/**
* @category MailSo
* @package Imap
* @subpackage Exceptions
*/
class ResponseException extends \MailSo\Imap\Exceptions\Exception
{
/**
* @var array
*/
private $aResponses;
/**
* @param array $aResponses = array
* @param string $sMessage = ''
* @param int $iCode = 0
* @param \Exception $oPrevious = null
*/
public function __construct($aResponses = array(), $sMessage = '', $iCode = 0, $oPrevious = null)
{
parent::__construct($sMessage, $iCode, $oPrevious);
if (is_array($aResponses))
{
$this->aResponses = $aResponses;
}
}
/**
* @return array
*/
public function GetResponses()
{
return $this->aResponses;
}
/**
* @return \MailSo\Imap\Response | null
*/
public function GetLastResponse()
{
return 0 < count($this->aResponses) ? $this->aResponses[count($this->aResponses) - 1] : null;
}
}

View file

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

View file

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

View file

@ -0,0 +1,225 @@
<?php
namespace MailSo\Imap;
/**
* @category MailSo
* @package Imap
*/
class FetchResponse
{
/**
* @var \MailSo\Imap\Response
*/
private $oImapResponse;
/**
* @var array|null
*/
private $aEnvelopeCache;
/**
* @access private
*
* @param \MailSo\Imap\Response $oImapResponse
*/
private function __construct(&$oImapResponse)
{
$this->oImapResponse =& $oImapResponse;
$this->aEnvelopeCache = null;
}
/**
* @param \MailSo\Imap\Response &$oImapResponse
* @return \MailSo\Imap\FetchResponse
*/
public static function NewInstance(&$oImapResponse)
{
return new self($oImapResponse);
}
/**
* @param bool $bForce = false
*
* @return array|null
*/
public function GetEnvelope($bForce = false)
{
if (null === $this->aEnvelopeCache || $bForce)
{
$this->aEnvelopeCache = $this->GetFetchValue(Enumerations\FetchType::ENVELOPE);
}
return $this->aEnvelopeCache;
}
/**
* @param int $iIndex
* @param mixed $mNullResult = null
*
* @return mixed
*/
public function GetFetchEnvelopeValue($iIndex, $mNullResult)
{
return self::findEnvelopeIndex($this->GetEnvelope(), $iIndex, $mNullResult);
}
/**
* @param int $iIndex
* @param string $sParentCharset = \MailSo\Base\Enumerations\Charset::ISO_8859_1
*
* @return \MailSo\Mime\EmailCollection|null
*/
public function GetFetchEnvelopeEmailCollection($iIndex, $sParentCharset = \MailSo\Base\Enumerations\Charset::ISO_8859_1)
{
$oResult = null;
$aEmails = $this->GetFetchEnvelopeValue($iIndex, null);
if (is_array($aEmails) && 0 < count($aEmails))
{
$oResult = \MailSo\Mime\EmailCollection::NewInstance();
foreach ($aEmails as $aEmailItem)
{
if (is_array($aEmailItem) && 4 === count($aEmailItem))
{
$sDisplayName = \MailSo\Base\Utils::DecodeHeaderValue(
self::findEnvelopeIndex($aEmailItem, 0, ''), $sParentCharset);
$sRemark = \MailSo\Base\Utils::DecodeHeaderValue(
self::findEnvelopeIndex($aEmailItem, 1, ''), $sParentCharset);
$sLocalPart = self::findEnvelopeIndex($aEmailItem, 2, '');
$sDomainPart = self::findEnvelopeIndex($aEmailItem, 3, '');
if (0 < strlen($sLocalPart) && 0 < strlen($sDomainPart))
{
$oResult->Add(
\MailSo\Mime\Email::NewInstance(
$sLocalPart.'@'.$sDomainPart, $sDisplayName, $sRemark)
);
}
}
}
}
return $oResult;
}
/**
* @param string $sRfc822SubMimeIndex = ''
*
* @return \MailSo\Imap\BodyStructure|null
*/
public function GetFetchBodyStructure($sRfc822SubMimeIndex = '')
{
$oBodyStructure = null;
$aBodyStructureArray = $this->GetFetchValue(Enumerations\FetchType::BODYSTRUCTURE);
if (is_array($aBodyStructureArray))
{
if (0 < strlen($sRfc822SubMimeIndex))
{
$oBodyStructure = BodyStructure::NewInstanceFromRfc822SubPart($aBodyStructureArray, $sRfc822SubMimeIndex);
}
else
{
$oBodyStructure = BodyStructure::NewInstance($aBodyStructureArray);
}
}
return $oBodyStructure;
}
/**
* @param string $sFetchItemName
*
* @return mixed
*/
public function &GetFetchValue($sFetchItemName)
{
$mReturn = null;
$bNextIsValue = false;
if (Enumerations\FetchType::INDEX === $sFetchItemName)
{
$mReturn =& $this->oImapResponse->ResponseList[1];
}
else
{
foreach ($this->oImapResponse->ResponseList[3] as &$mItem)
{
if ($bNextIsValue)
{
$mReturn =& $mItem;
break;
}
if ($sFetchItemName === $mItem)
{
$bNextIsValue = true;
}
}
}
return $mReturn;
}
/**
* @param string $sRfc822SubMimeIndex = ''
*
* @return string
*/
public function GetHeaderFieldsValue($sRfc822SubMimeIndex = '')
{
$sReturn = '';
$bNextIsValue = false;
$sRfc822SubMimeIndex = 0 < \strlen($sRfc822SubMimeIndex) ? ''.$sRfc822SubMimeIndex.'.' : '';
if (isset($this->oImapResponse->ResponseList[3]) && \is_array($this->oImapResponse->ResponseList[3]))
{
foreach ($this->oImapResponse->ResponseList[3] as &$mItem)
{
if ($bNextIsValue)
{
$sReturn = (string) $mItem;
break;
}
if (\is_string($mItem) && (
$mItem === 'BODY['.$sRfc822SubMimeIndex.'HEADER]' ||
0 === \strpos($mItem, 'BODY['.$sRfc822SubMimeIndex.'HEADER.FIELDS') ||
$mItem === 'BODY['.$sRfc822SubMimeIndex.'MIME]'))
{
$bNextIsValue = true;
}
}
}
return $sReturn;
}
/**
* @param \MailSo\Imap\Response $oImapResponse
*
* @return bool
*/
public static function IsValidFetchImapResponse($oImapResponse)
{
return ($oImapResponse && true !== $oImapResponse->IsStatusResponse
&& \MailSo\Imap\Enumerations\ResponseType::UNTAGGED === $oImapResponse->ResponseType
&& 3 < count($oImapResponse->ResponseList) && 'FETCH' === $oImapResponse->ResponseList[2]
&& is_array($oImapResponse->ResponseList[3]));
}
/**
* @param array $aEnvelope
* @param int $iIndex
* @param mixed $mNullResult = null
*
* @return mixed
*/
private static function findEnvelopeIndex($aEnvelope, $iIndex, $mNullResult)
{
return (isset($aEnvelope[$iIndex]) && 'NIL' !== $aEnvelope[$iIndex] && '' !== $aEnvelope[$iIndex])
? $aEnvelope[$iIndex] : $mNullResult;
}
}

View file

@ -0,0 +1,175 @@
<?php
namespace MailSo\Imap;
/**
* @category MailSo
* @package Imap
*/
class Folder
{
/**
* @var string
*/
private $sNameRaw;
/**
* @var string
*/
private $sFullNameRaw;
/**
* @var string
*/
private $sDelimiter;
/**
* @var array
*/
private $aFlags;
/**
* @var array
*/
private $aFlagsLowerCase;
/**
* @var array
*/
private $aExtended;
/**
* @access private
*
* @param string $sFullNameRaw
* @param string $sDelimiter
* @param array $aFlags
*
* @throws \MailSo\Base\Exceptions\InvalidArgumentException
*/
private function __construct($sFullNameRaw, $sDelimiter, array $aFlags)
{
$this->sNameRaw = '';
$this->sFullNameRaw = '';
$this->sDelimiter = '';
$this->aFlags = array();
$this->aExtended = array();
$sDelimiter = 'NIL' === \strtoupper($sDelimiter) ? '' : $sDelimiter;
if (!\is_array($aFlags) ||
!\is_string($sDelimiter) || 1 < \strlen($sDelimiter) ||
!\is_string($sFullNameRaw) || 0 === \strlen($sFullNameRaw))
{
throw new \MailSo\Base\Exceptions\InvalidArgumentException();
}
$this->sFullNameRaw = $sFullNameRaw;
$this->sDelimiter = $sDelimiter;
$this->aFlags = $aFlags;
$this->aFlagsLowerCase = \array_map('strtolower', $this->aFlags);
$this->sFullNameRaw = 'INBOX'.$this->sDelimiter === \substr(\strtoupper($this->sFullNameRaw), 0, 5 + \strlen($this->sDelimiter)) ?
'INBOX'.\substr($this->sFullNameRaw, 5) : $this->sFullNameRaw;
if ($this->IsInbox())
{
$this->sFullNameRaw = 'INBOX';
}
$this->sNameRaw = $this->sFullNameRaw;
if (0 < \strlen($this->sDelimiter))
{
$aNames = \explode($this->sDelimiter, $this->sFullNameRaw);
$this->sNameRaw = \end($aNames);
}
}
/**
* @param string $sFullNameRaw
* @param string $sDelimiter = '/'
* @param array $aFlags = array()
*
* @return \MailSo\Imap\Folder
*
* @throws \MailSo\Base\Exceptions\InvalidArgumentException
*/
public static function NewInstance($sFullNameRaw, $sDelimiter = '/', $aFlags = array())
{
return new self($sFullNameRaw, $sDelimiter, $aFlags);
}
/**
* @return string
*/
public function NameRaw()
{
return $this->sNameRaw;
}
/**
* @return string
*/
public function FullNameRaw()
{
return $this->sFullNameRaw;
}
/**
* @return string | null
*/
public function Delimiter()
{
return $this->sDelimiter;
}
/**
* @return array
*/
public function Flags()
{
return $this->aFlags;
}
/**
* @return array
*/
public function FlagsLowerCase()
{
return $this->aFlagsLowerCase;
}
/**
* @return bool
*/
public function IsSelectable()
{
return !\in_array('\noselect', $this->aFlagsLowerCase);
}
/**
* @return bool
*/
public function IsInbox()
{
return 'INBOX' === \strtoupper($this->sFullNameRaw) || \in_array('\inbox', $this->aFlagsLowerCase);
}
/**
* @param string $sName
* @param mixed $mData
*/
public function SetExtended($sName, $mData)
{
$this->aExtended[$sName] = $mData;
}
/**
* @param string $sName
* @return mixed
*/
public function GetExtended($sName)
{
return isset($this->aExtended[$sName]) ? $this->aExtended[$sName] : null;
}
}

View file

@ -0,0 +1,95 @@
<?php
namespace MailSo\Imap;
/**
* @category MailSo
* @package Imap
*/
class FolderInformation
{
/**
* @var string
*/
public $FolderName;
/**
* @var bool
*/
public $IsWritable;
/**
* @var array
*/
public $Flags;
/**
* @var array
*/
public $PermanentFlags;
/**
* @var int
*/
public $Exists;
/**
* @var int
*/
public $Recent;
/**
* @var string
*/
public $Uidvalidity;
/**
* @var int
*/
public $Unread;
/**
* @var string
*/
public $Uidnext;
/**
* @access private
*
* @param string $sFolderName
* @param bool $bIsWritable
*/
private function __construct($sFolderName, $bIsWritable)
{
$this->FolderName = $sFolderName;
$this->IsWritable = $bIsWritable;
$this->Exists = null;
$this->Recent = null;
$this->Flags = array();
$this->PermanentFlags = array();
$this->Unread = null;
$this->Uidnext = null;
}
/**
* @param string $sFolderName
* @param bool $bIsWritable
*
* @return \MailSo\Imap\FolderInformation
*/
public static function NewInstance($sFolderName, $bIsWritable)
{
return new self($sFolderName, $bIsWritable);
}
/**
* @param string $sFlag
*
* @return bool
*/
public function IsFlagSupported($sFlag)
{
return in_array('\\*', $this->PermanentFlags) || in_array($sFlag, $this->PermanentFlags);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,123 @@
<?php
namespace MailSo\Imap;
/**
* @category MailSo
* @package Imap
*/
class NamespaceResult
{
/**
* @var string
*/
private $sPersonal;
/**
* @var string
*/
private $sPersonalDelimiter;
/**
* @var string
*/
private $sOtherUser;
/**
* @var string
*/
private $sOtherUserDelimiter;
/**
* @var string
*/
private $sShared;
/**
* @var string
*/
private $sSharedDelimiter;
/**
* @access private
*/
private function __construct()
{
$this->sPersonal = '';
$this->sPersonalDelimiter = '';
$this->sOtherUser = '';
$this->sOtherUserDelimiter = '';
$this->sShared = '';
$this->sSharedDelimiter = '';
}
/**
* @return \MailSo\Imap\NamespaceResult
*/
public static function NewInstance()
{
return new self();
}
/**
* @param \MailSo\Imap\Response $oImapResponse
*
* @return \MailSo\Imap\NamespaceResult
*/
public function InitByImapResponse($oImapResponse)
{
if ($oImapResponse && $oImapResponse instanceof \MailSo\Imap\Response)
{
if (isset($oImapResponse->ResponseList[2][0]) &&
\is_array($oImapResponse->ResponseList[2][0]) &&
2 <= \count($oImapResponse->ResponseList[2][0]))
{
$this->sPersonal = $oImapResponse->ResponseList[2][0][0];
$this->sPersonalDelimiter = $oImapResponse->ResponseList[2][0][1];
$this->sPersonal = 'INBOX'.$this->sPersonalDelimiter === \substr(\strtoupper($this->sPersonal), 0, 6) ?
'INBOX'.$this->sPersonalDelimiter.\substr($this->sPersonal, 6) : $this->sPersonal;
}
if (isset($oImapResponse->ResponseList[3][0]) &&
\is_array($oImapResponse->ResponseList[3][0]) &&
2 <= \count($oImapResponse->ResponseList[3][0]))
{
$this->sOtherUser = $oImapResponse->ResponseList[3][0][0];
$this->sOtherUserDelimiter = $oImapResponse->ResponseList[3][0][1];
$this->sOtherUser = 'INBOX'.$this->sOtherUserDelimiter === \substr(\strtoupper($this->sOtherUser), 0, 6) ?
'INBOX'.$this->sOtherUserDelimiter.\substr($this->sOtherUser, 6) : $this->sOtherUser;
}
if (isset($oImapResponse->ResponseList[4][0]) &&
\is_array($oImapResponse->ResponseList[4][0]) &&
2 <= \count($oImapResponse->ResponseList[4][0]))
{
$this->sShared = $oImapResponse->ResponseList[4][0][0];
$this->sSharedDelimiter = $oImapResponse->ResponseList[4][0][1];
$this->sShared = 'INBOX'.$this->sSharedDelimiter === \substr(\strtoupper($this->sShared), 0, 6) ?
'INBOX'.$this->sSharedDelimiter.\substr($this->sShared, 6) : $this->sShared;
}
}
return $this;
}
/**
* @return string
*/
public function GetPersonalNamespace()
{
return $this->sPersonal;
}
/**
* @return string
*/
public function GetPersonalNamespaceDelimiter()
{
return $this->sPersonalDelimiter;
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace MailSo\Imap;
/**
* @category MailSo
* @package Imap
*/
class Response
{
/**
* @var array
*/
public $ResponseList;
/**
* @var array | null
*/
public $OptionalResponse;
/**
* @var string
*/
public $StatusOrIndex;
/**
* @var string
*/
public $HumanReadable;
/**
* @var bool
*/
public $IsStatusResponse;
/**
* @var string
*/
public $ResponseType;
/**
* @var string
*/
public $Tag;
/**
* @access private
*/
private function __construct()
{
$this->ResponseList = array();
$this->OptionalResponse = null;
$this->StatusOrIndex = '';
$this->HumanReadable = '';
$this->IsStatusResponse = false;
$this->ResponseType = \MailSo\Imap\Enumerations\ResponseType::UNKNOWN;
$this->Tag = '';
}
/**
* @return \MailSo\Imap\Response
*/
public static function NewInstance()
{
return new self();
}
}

View file

@ -0,0 +1,104 @@
<?php
namespace MailSo\Imap;
/**
* @category MailSo
* @package Imap
*/
class SearchBuilder
{
/**
* @var array
*/
private $aList;
/**
* @access private
*/
private function __construct()
{
$this->Clear();
}
/**
* @return \MailSo\Imap\SearchBuilder
*/
public static function NewInstance()
{
return new self();
}
/**
* @return \MailSo\Imap\SearchBuilder
*/
public function Clear()
{
$this->aList = array();
return $this;
}
/**
* @param string $sName
* @param string $sValue = ''
*
* @return \MailSo\Imap\SearchBuilder
*/
public function AddAnd($sName, $sValue = '')
{
return $this->addCri('AND', $sName, $sValue);
}
/**
* @param string $sName
* @param string $sValue = ''
*
* @return \MailSo\Imap\SearchBuilder
*/
public function AddOr($sName, $sValue = '')
{
return $this->addCri('OR', $sName, $sValue);
}
/**
* @return string
*/
public function Complete()
{
$sResult = '';
foreach ($this->aList as $iIndex => $aItem)
{
$sResult = trim((0 < $iIndex && 'OR' === $aItem[0] ? $aItem[0] : '').
(0 === strlen($sResult) ? '' : ' ('.$sResult.')').' '.$aItem[1].
(0 < strlen($aItem[2]) ? ' '.$aItem[2] : ''));
}
if (0 === strlen($sResult))
{
$sResult = 'ALL';
}
return $sResult;
}
/**
* @return string
*/
public function __toString()
{
return $this->Complete();
}
/**
* @param string $sType
* @param string $sName
* @param string $sValue = ''
*
* @return \MailSo\Imap\SearchBuilder
*/
private function addCri($sType, $sName, $sValue = '')
{
$this->aList[] = array($sType, $sName, $sValue);
return $this;
}
}

View file

@ -0,0 +1,221 @@
<?php
namespace MailSo\Log;
/**
* @category MailSo
* @package Log
*/
abstract class Driver
{
/**
* @var string
*/
protected $sDatePattern;
/**
* @var string
*/
protected $sName;
/**
* @var array
*/
protected $aPrefixes;
/**
* @var bool
*/
protected $bTimePrefix;
/**
* @var bool
*/
protected $bTypedPrefix;
/**
* @var bool
*/
private $bWriteOnErrorOnly;
/**
* @var bool
*/
private $bFlushCache;
/**
* @var array
*/
private $aCache;
/**
* @access protected
*/
protected function __construct()
{
$this->sDatePattern = 'H:i:s';
$this->sName = 'INFO';
$this->bTimePrefix = true;
$this->bTypedPrefix = true;
$this->bWriteOnErrorOnly = false;
$this->bFlushCache = false;
$this->aCache = array();
$this->aPrefixes = array(
\MailSo\Log\Enumerations\Type::INFO => '[DATA]',
\MailSo\Log\Enumerations\Type::SECURE => '[SECURE]',
\MailSo\Log\Enumerations\Type::NOTE => '[NOTE]',
\MailSo\Log\Enumerations\Type::TIME => '[TIME]',
\MailSo\Log\Enumerations\Type::MEMORY => '[MEMORY]',
\MailSo\Log\Enumerations\Type::NOTICE => '[NOTICE]',
\MailSo\Log\Enumerations\Type::WARNING => '[WARNING]',
\MailSo\Log\Enumerations\Type::ERROR => '[ERROR]',
);
}
/**
* @return \MailSo\Log\Driver
*/
public function DisableTimePrefix()
{
$this->bTimePrefix = false;
return $this;
}
/**
* @param bool $bValue
*
* @return \MailSo\Log\Driver
*/
public function WriteOnErrorOnly($bValue)
{
$this->bWriteOnErrorOnly = !!$bValue;
return $this;
}
/**
* @return \MailSo\Log\Driver
*/
public function DisableTypedPrefix()
{
$this->bTypedPrefix = false;
return $this;
}
/**
* @param string|array $sDesc
* @return bool
*/
abstract protected function writeImplementation($mDesc);
/**
* @return bool
*/
protected function writeEmptyLineImplementation()
{
return $this->writeImplementation('');
}
/**
* @param string $sTimePrefix
* @param string $sDesc
* @param int $iDescType = \MailSo\Log\Enumerations\Type::INFO
* @param array $sName = ''
*
* @return string
*/
protected function loggerLineImplementation($sTimePrefix, $sDesc,
$iDescType = \MailSo\Log\Enumerations\Type::INFO, $sName = '')
{
return ($this->bTimePrefix ? '['.$sTimePrefix.'] ' : '').
($this->bTypedPrefix ? $this->getTypedPrefix($iDescType, $sName) : '').
$sDesc;
}
/**
* @return bool
*/
protected function clearImplementation()
{
return true;
}
/**
* @return string
*/
protected function getTimeWithMicroSec()
{
$aMicroTimeItems = \explode(' ', \microtime());
return \gmdate($this->sDatePattern, $aMicroTimeItems[1]).'.'.
\str_pad((int) ($aMicroTimeItems[0] * 1000), 3, '0', STR_PAD_LEFT);
}
/**
* @param int $iDescType
* @param string $sName = ''
*
* @return string
*/
protected function getTypedPrefix($iDescType, $sName = '')
{
$sName = 0 < \strlen($sName) ? $sName : $this->sName;
return isset($this->aPrefixes[$iDescType]) ? $sName.$this->aPrefixes[$iDescType].': ' : '';
}
/**
* @final
* @param string $sDesc
* @param int $iDescType = \MailSo\Log\Enumerations\Type::INFO
* @param array $sName = ''
*
* @return bool
*/
final public function Write($sDesc, $iDescType = \MailSo\Log\Enumerations\Type::INFO, $sName = '')
{
if ($this->bWriteOnErrorOnly && !$this->bFlushCache)
{
$this->aCache[] = $this->loggerLineImplementation($this->getTimeWithMicroSec(), $sDesc, $iDescType, $sName);
if (\in_array($iDescType, array(
\MailSo\Log\Enumerations\Type::NOTICE,
\MailSo\Log\Enumerations\Type::WARNING,
\MailSo\Log\Enumerations\Type::ERROR
)))
{
$this->bFlushCache = true;
return $this->writeImplementation($this->aCache);
}
return true;
}
return $this->writeImplementation(
$this->loggerLineImplementation($this->getTimeWithMicroSec(), $sDesc, $iDescType, $sName));
}
/**
* @final
* @return bool
*/
final public function Clear()
{
return $this->clearImplementation();
}
/**
* @final
* @return void
*/
final public function WriteEmptyLine()
{
if ($this->bWriteOnErrorOnly && !$this->bFlushCache)
{
$this->aCache[] = '';
}
else
{
$this->writeEmptyLineImplementation();
}
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace MailSo\Log\Drivers;
/**
* @category MailSo
* @package Log
* @subpackage Drivers
*/
class Callback extends \MailSo\Log\Driver
{
/**
* @var mixed
*/
private $fWriteCallback;
/**
* @var mixed
*/
private $fClearCallback;
/**
* @access protected
*
* @param mixed $fWriteCallback
* @param mixed $fClearCallback
*/
protected function __construct($fWriteCallback, $fClearCallback)
{
parent::__construct();
$this->fWriteCallback = \is_callable($fWriteCallback) ? $fWriteCallback : null;
$this->fClearCallback = \is_callable($fClearCallback) ? $fClearCallback : null;
}
/**
* @param mixed $fWriteCallback
* @param mixed $fClearCallback = null
*
* @return \MailSo\Log\Drivers\Callback
*/
public static function NewInstance($fWriteCallback, $fClearCallback = null)
{
return new self($fWriteCallback, $fClearCallback);
}
/**
* @param string|array $sDesc
*
* @return bool
*/
protected function writeImplementation($sDesc)
{
if ($this->fWriteCallback)
{
\call_user_func_array($this->fWriteCallback, array($sDesc));
}
return true;
}
/**
* @return bool
*/
protected function clearImplementation()
{
if ($this->fClearCallback)
{
\call_user_func($this->fClearCallback);
}
return true;
}
}

View file

@ -0,0 +1,87 @@
<?php
namespace MailSo\Log\Drivers;
/**
* @category MailSo
* @package Log
* @subpackage Drivers
*/
class File extends \MailSo\Log\Driver
{
/**
* @var string
*/
private $sLoggerFileName;
/**
* @var string
*/
private $sCrLf;
/**
* @access protected
*
* @param string $sLoggerFileName
* @param string $sCrLf = "\r\n"
*/
protected function __construct($sLoggerFileName, $sCrLf = "\r\n")
{
parent::__construct();
$this->sLoggerFileName = $sLoggerFileName;
$this->sCrLf = $sCrLf;
}
/**
* @param string $sLoggerFileName
*/
public function SetLoggerFileName($sLoggerFileName)
{
$this->sLoggerFileName = $sLoggerFileName;
}
/**
* @param string $sLoggerFileName
* @param string $sCrLf = "\r\n"
*
* @return \MailSo\Log\Drivers\File
*/
public static function NewInstance($sLoggerFileName, $sCrLf = "\r\n")
{
return new self($sLoggerFileName, $sCrLf);
}
/**
* @param string|array $mDesc
*
* @return bool
*/
protected function writeImplementation($mDesc)
{
return $this->writeToLogFile($mDesc);
}
/**
* @return bool
*/
protected function clearImplementation()
{
return \unlink($this->sLoggerFileName);
}
/**
* @param string|array $mDesc
*
* @return bool
*/
private function writeToLogFile($mDesc)
{
if (is_array($mDesc))
{
$mDesc = \implode($this->sCrLf, $mDesc);
}
return \error_log($mDesc.$this->sCrLf, 3, $this->sLoggerFileName);
}
}

View file

@ -0,0 +1,85 @@
<?php
namespace MailSo\Log\Drivers;
/**
* @category MailSo
* @package Log
* @subpackage Drivers
*/
class Inline extends \MailSo\Log\Driver
{
/**
* @var string
*/
private $sNewLine;
/**
* @var bool
*/
private $bHtmlEncodeSpecialChars;
/**
* @access protected
*
* @param string $sNewLine = "\r\n"
* @param bool $bHtmlEncodeSpecialChars = false
*/
protected function __construct($sNewLine = "\r\n", $bHtmlEncodeSpecialChars = false)
{
parent::__construct();
$this->sNewLine = $sNewLine;
$this->bHtmlEncodeSpecialChars = $bHtmlEncodeSpecialChars;
}
/**
* @param string $sNewLine = "\r\n"
* @param bool $bHtmlEncodeSpecialChars = false
*
* @return \MailSo\Log\Drivers\Inline
*/
public static function NewInstance($sNewLine = "\r\n", $bHtmlEncodeSpecialChars = false)
{
return new self($sNewLine, $bHtmlEncodeSpecialChars);
}
/**
* @param string $mDesc
*
* @return bool
*/
protected function writeImplementation($mDesc)
{
if (is_array($mDesc))
{
if ($this->bHtmlEncodeSpecialChars)
{
$mDesc = array_map(function ($sItem) {
$sItem = \htmlspecialchars($mDesc);
}, $mDesc);
}
$mDesc = \implode($this->sNewLine, $mDesc);
}
else
{
echo ($this->bHtmlEncodeSpecialChars) ? \htmlspecialchars($mDesc).$this->sNewLine : $mDesc.$this->sNewLine;
}
return true;
}
/**
* @return bool
*/
protected function clearImplementation()
{
if (\defined('PHP_SAPI') && 'cli' === PHP_SAPI)
{
\system('clear');
}
return true;
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace MailSo\Log\Enumerations;
/**
* @category MailSo
* @package Log
* @subpackage Enumerations
*/
class Type
{
const INFO = 0;
const NOTICE = 1;
const WARNING = 2;
const ERROR = 3;
const SECURE = 4;
const NOTE = 5;
const TIME = 6;
const MEMORY = 7;
}

View file

@ -0,0 +1,214 @@
<?php
namespace MailSo\Log;
/**
* @category MailSo
* @package Log
*/
class Logger extends \MailSo\Base\Collection
{
/**
* @var bool
*/
private $bUsed;
/**
* @var array
*/
private $aForbiddenTypes;
/**
* @var array
*/
private $aSecretWords;
/**
* @access protected
*/
protected function __construct()
{
parent::__construct();
$this->bUsed = false;
$this->aForbiddenTypes = array();
$this->aSecretWords = array();
\register_shutdown_function(array(&$this, '__loggerShutDown'));
}
/**
* @return \MailSo\Log\Logger
*/
public static function NewInstance()
{
return new self();
}
/**
* @staticvar \MailSo\Log\Logger $oInstance;
*
* @return \MailSo\Log\Logger
*/
public static function SingletonInstance()
{
static $oInstance = null;
if (null === $oInstance)
{
$oInstance = self::NewInstance();
}
return $oInstance;
}
/**
* @return bool
*/
public function IsEnabled()
{
return 0 < $this->Count();
}
/**
* @param string $sWord
* @return bool
*/
public function AddSecret($sWord)
{
if (0 < \strlen(\trim($sWord)))
{
$this->aSecretWords[] = $sWord;
$this->aSecretWords = array_unique($this->aSecretWords);
}
}
/**
* @param int $iDescType
*
* @return \MailSo\Log\Logger
*/
public function AddForbiddenType($iType)
{
$this->aForbiddenTypes[$iType] = true;
return $this;
}
/**
* @param int $iDescType
*
* @return \MailSo\Log\Logger
*/
public function RemoveForbiddenType($iType)
{
$this->aForbiddenTypes[$iType] = false;
return $this;
}
/**
* @return void
*/
public function __loggerShutDown()
{
if ($this->bUsed)
{
$aStatistic = \MailSo\Base\Loader::Statistic();
// $this->WriteDump($aStatistic, \MailSo\Log\Enumerations\Type::INFO);
if (\is_array($aStatistic) && isset($aStatistic['php']['memory_get_peak_usage']))
{
$this->Write('Memory peak usage: '.$aStatistic['php']['memory_get_peak_usage'],
\MailSo\Log\Enumerations\Type::MEMORY);
}
}
}
/**
* @return bool
*/
public function WriteEmptyLine()
{
$iResult = 1;
$aLoggers =& $this->GetAsArray();
foreach ($aLoggers as /* @var $oLogger \MailSo\Log\Driver */ &$oLogger)
{
$iResult &= $oLogger->WriteEmptyLine();
}
return (bool) $iResult;
}
/**
* @param string $sDesc
* @param int $iDescType = \MailSo\Log\Enumerations\Type::INFO
* @param string $sName = ''
* @param bool $bSearchWords = false
*
* @return bool
*/
public function Write($sDesc, $iDescType = \MailSo\Log\Enumerations\Type::INFO, $sName = '', $bSearchWords = false)
{
if (isset($this->aForbiddenTypes[$iDescType]) && true === $this->aForbiddenTypes[$iDescType])
{
return true;
}
$this->bUsed = true;
$oLogger = null;
$aLoggers = array();
$iResult = 1;
if ($bSearchWords && 0 < \count($this->aSecretWords))
{
$sDesc = \str_replace($this->aSecretWords, '*******', $sDesc);
}
$aLoggers =& $this->GetAsArray();
foreach ($aLoggers as /* @var $oLogger \MailSo\Log\Driver */ $oLogger)
{
$iResult &= $oLogger->Write($sDesc, $iDescType, $sName);
}
return (bool) $iResult;
}
/**
* @param mixed $oValue
* @param int $iDescType = \MailSo\Log\Enumerations\Type::INFO
* @param string $sName = ''
* @param bool $bSearchSecretWords = false
*
* @return bool
*/
public function WriteDump($oValue, $iDescType = \MailSo\Log\Enumerations\Type::INFO, $sName = '', $bSearchSecretWords = false)
{
return $this->Write(\print_r($oValue, true), $iDescType, $sName, $bSearchSecretWords);
}
/**
* @param \Exception $oException
* @param int $iDescType = \MailSo\Log\Enumerations\Type::NOTICE
* @param string $sName = ''
* @param bool $bSearchSecretWords = true
*
* @return bool
*/
public function WriteException($oException, $iDescType = \MailSo\Log\Enumerations\Type::NOTICE, $sName = '', $bSearchSecretWords = true)
{
if ($oException instanceof \Exception)
{
if (isset($oException->__LOGINNED__))
{
return true;
}
$oException->__LOGINNED__ = true;
return $this->Write((string) $oException, $iDescType, $sName, $bSearchSecretWords);
}
return false;
}
}

View file

@ -0,0 +1,182 @@
<?php
namespace MailSo\Mail;
/**
* @category MailSo
* @package Mail
*/
class Attachment
{
/**
* @var string
*/
private $sFolder;
/**
* @var int
*/
private $iUid;
/**
* @var \MailSo\Imap\BodyStructure
*/
private $oBodyStructure;
/**
* @access private
*/
private function __construct()
{
$this->Clear();
}
/**
* @return \MailSo\Mail\Attachment
*/
public function Clear()
{
$this->sFolder = '';
$this->iUid = 0;
$this->oBodyStructure = null;
return $this;
}
/**
* @return string
*/
public function Folder()
{
return $this->sFolder;
}
/**
* @return int
*/
public function Uid()
{
return $this->iUid;
}
/**
* @return string
*/
public function MimeIndex()
{
return $this->oBodyStructure ? $this->oBodyStructure->PartID() : '';
}
/**
* @param bool $bCalculateOnEmpty = false
*
* @return string
*/
public function FileName($bCalculateOnEmpty = false)
{
$sFileName = '';
if ($this->oBodyStructure)
{
$sFileName = $this->oBodyStructure->FileName();
if ($bCalculateOnEmpty && 0 === \strlen(trim($sFileName)))
{
$sMimeType = \strtolower(\trim($this->MimeType()));
if ('message/rfc822' === $sMimeType)
{
$sFileName = 'message'.$this->MimeIndex().'.eml';
}
else if ('text/calendar' === $sMimeType)
{
$sFileName = 'calendar'.$this->MimeIndex().'.ics';
}
else if (0 < \strlen($sMimeType))
{
$sFileName = \str_replace('/', $this->MimeIndex().'.', $sMimeType);
}
}
}
return $sFileName;
}
/**
* @return string
*/
public function MimeType()
{
return $this->oBodyStructure ? $this->oBodyStructure->ContentType() : '';
}
/**
* @return string
*/
public function ContentTransferEncoding()
{
return $this->oBodyStructure ? $this->oBodyStructure->MailEncodingName() : '';
}
/**
* @return int
*/
public function EncodedSize()
{
return $this->oBodyStructure ? $this->oBodyStructure->Size() : 0;
}
/**
* @return int
*/
public function EstimatedSize()
{
return $this->oBodyStructure ? $this->oBodyStructure->EstimatedSize() : 0;
}
/**
* @return string
*/
public function Cid()
{
return $this->oBodyStructure ? $this->oBodyStructure->ContentID() : '';
}
/**
* @return bool
*/
public function IsInline()
{
return $this->oBodyStructure ? $this->oBodyStructure->IsInline() : false;
}
/**
* @return \MailSo\Mail\Attachment
*/
public static function NewInstance()
{
return new self();
}
/**
* @param string $sFolder
* @param int $iUid
* @param \MailSo\Imap\BodyStructure $oBodyStructure
* @return \MailSo\Mail\Attachment
*/
public static function NewBodyStructureInstance($sFolder, $iUid, $oBodyStructure)
{
return self::NewInstance()->InitByBodyStructure($sFolder, $iUid, $oBodyStructure);
}
/**
* @param string $sFolder
* @param int $iUid
* @param \MailSo\Imap\BodyStructure $oBodyStructure
* @return \MailSo\Mail\Attachment
*/
public function InitByBodyStructure($sFolder, $iUid, $oBodyStructure)
{
$this->sFolder = $sFolder;
$this->iUid = $iUid;
$this->oBodyStructure = $oBodyStructure;
return $this;
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace MailSo\Mail;
/**
* @category MailSo
* @package Mail
*/
class AttachmentCollection extends \MailSo\Base\Collection
{
/**
* @access protected
*/
protected function __construct()
{
parent::__construct();
}
/**
* @return \MailSo\Mail\AttachmentCollection
*/
public static function NewInstance()
{
return new self();
}
/**
* @return int
*/
public function InlineCount()
{
$aList = $this->FilterList(function ($oAttachment) {
return $oAttachment && $oAttachment->IsInline();
});
return \is_array($aList) ? \count($aList) : 0;
}
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1,305 @@
<?php
namespace MailSo\Mail;
/**
* @category MailSo
* @package Mail
*/
class Folder
{
/**
* @var string
*/
private $sParentFullNameRaw;
/**
* @var int
*/
private $iNestingLevel;
/**
* @var bool
*/
private $bExisten;
/**
* @var bool
*/
private $bSubscribed;
/**
* @var \MailSo\Imap\Folder
*/
private $oImapFolder;
/**
* @var \MailSo\Mail\FolderCollection
*/
private $oSubFolders;
/**
* @access private
*
* @param \MailSo\Imap\Folder $oImapFolder
* @param bool $bSubscribed = true
* @param bool $bExisten = true
*
* @throws \MailSo\Base\Exceptions\InvalidArgumentException
*/
private function __construct($oImapFolder, $bSubscribed = true, $bExisten = true)
{
if ($oImapFolder instanceof \MailSo\Imap\Folder)
{
$this->oImapFolder = $oImapFolder;
$this->oSubFolders = null;
$aNames = \explode($this->oImapFolder->Delimiter(), $this->oImapFolder->FullNameRaw());
$this->iNestingLevel = \count($aNames);
$this->sParentFullNameRaw = '';
if (1 < $this->iNestingLevel)
{
\array_pop($aNames);
$this->sParentFullNameRaw = \implode($this->oImapFolder->Delimiter(), $aNames);
}
$this->bSubscribed = $bSubscribed;
$this->bExisten = $bExisten;
}
else
{
throw new \MailSo\Base\Exceptions\InvalidArgumentException();
}
}
/**
* @param \MailSo\Imap\Folder $oImapFolder
* @param bool $bSubscribed = true
* @param bool $bExisten = true
*
* @return \MailSo\Mail\Folder
*
* @throws \MailSo\Base\Exceptions\InvalidArgumentException
*/
public static function NewInstance($oImapFolder, $bSubscribed = true, $bExisten = true)
{
return new self($oImapFolder, $bSubscribed, $bExisten);
}
/**
* @param string $sFullNameRaw
* @param string $sDelimiter
*
* @return \MailSo\Mail\Folder
*
* @throws \MailSo\Base\Exceptions\InvalidArgumentException
* @throws \MailSo\Base\Exceptions\InvalidArgumentException
*/
public static function NewNonExistenInstance($sFullNameRaw, $sDelimiter)
{
return self::NewInstance(
\MailSo\Imap\Folder::NewInstance($sFullNameRaw, $sDelimiter, array('\NoSelect')), true, false);
}
/**
* @return string
*/
public function Name()
{
return \MailSo\Base\Utils::ConvertEncoding($this->NameRaw(),
\MailSo\Base\Enumerations\Charset::UTF_7_IMAP,
\MailSo\Base\Enumerations\Charset::UTF_8);
}
/**
* @return string
*/
public function FullName()
{
return \MailSo\Base\Utils::ConvertEncoding($this->FullNameRaw(),
\MailSo\Base\Enumerations\Charset::UTF_7_IMAP,
\MailSo\Base\Enumerations\Charset::UTF_8);
}
/**
* @return string
*/
public function NameRaw()
{
return $this->oImapFolder->NameRaw();
}
/**
* @return string
*/
public function FullNameRaw()
{
return $this->oImapFolder->FullNameRaw();
}
/**
* @return string
*/
public function ParentFullName()
{
return \MailSo\Base\Utils::ConvertEncoding($this->sParentFullNameRaw,
\MailSo\Base\Enumerations\Charset::UTF_7_IMAP,
\MailSo\Base\Enumerations\Charset::UTF_8);
}
/**
* @return string
*/
public function ParentFullNameRaw()
{
return $this->sParentFullNameRaw;
}
/**
* @return string
*/
public function Delimiter()
{
return $this->oImapFolder->Delimiter();
}
/**
* @return array
*/
public function Flags()
{
return $this->oImapFolder->Flags();
}
/**
* @return array
*/
public function FlagsLowerCase()
{
return $this->oImapFolder->FlagsLowerCase();
}
/**
* @param bool $bCreateIfNull = false
* @return \MailSo\Mail\FolderCollection
*/
public function SubFolders($bCreateIfNull = false)
{
if ($bCreateIfNull && !$this->oSubFolders)
{
$this->oSubFolders = FolderCollection::NewInstance();
}
return $this->oSubFolders;
}
/**
* @return bool
*/
public function HasSubFolders()
{
return $this->oSubFolders && 0 < $this->oSubFolders->Count();
}
/**
* @return bool
*/
public function HasVisibleSubFolders()
{
$sList = array();
if ($this->oSubFolders)
{
$sList = $this->oSubFolders->FilterList(function (\MailSo\Mail\Folder $oFolder) {
return $oFolder->IsSubscribed();
});
}
return 0 < \count($sList);
}
/**
* @return bool
*/
public function IsSubscribed()
{
return $this->bSubscribed;
}
/**
* @return bool
*/
public function IsExisten()
{
return $this->bExisten;
}
/**
* @return bool
*/
public function IsSelectable()
{
return $this->IsExisten() && $this->oImapFolder->IsSelectable();
}
/**
* @return mixed
*/
public function Status()
{
return $this->oImapFolder->GetExtended('STATUS');
}
/**
* @return bool
*/
public function IsInbox()
{
return $this->oImapFolder->IsInbox();
}
/**
* @return int
*/
public function GetFolderXListType()
{
$aFlags = $this->oImapFolder->FlagsLowerCase();
$iXListType = \MailSo\Imap\Enumerations\FolderType::USER;
if (\is_array($aFlags))
{
switch (true)
{
case \in_array('\inbox', $aFlags):
$iXListType = \MailSo\Imap\Enumerations\FolderType::INBOX;
break;
case \in_array('\sent', $aFlags):
$iXListType = \MailSo\Imap\Enumerations\FolderType::SENT;
break;
case \in_array('\drafts', $aFlags):
$iXListType = \MailSo\Imap\Enumerations\FolderType::DRAFTS;
break;
case \in_array('\spam', $aFlags):
$iXListType = \MailSo\Imap\Enumerations\FolderType::SPAN;
break;
case \in_array('\bin', $aFlags):
case \in_array('\trash', $aFlags):
$iXListType = \MailSo\Imap\Enumerations\FolderType::TRASH;
break;
case \in_array('\important', $aFlags):
$iXListType = \MailSo\Imap\Enumerations\FolderType::IMPORTANT;
break;
case \in_array('\starred', $aFlags):
$iXListType = \MailSo\Imap\Enumerations\FolderType::STARRED;
break;
case \in_array('\all', $aFlags):
case \in_array('\archive', $aFlags):
case \in_array('\allmail', $aFlags):
$iXListType = \MailSo\Imap\Enumerations\FolderType::ALLMAIL;
break;
}
}
return $iXListType;
}
}

View file

@ -0,0 +1,195 @@
<?php
namespace MailSo\Mail;
/**
* @category MailSo
* @package Mail
*/
class FolderCollection extends \MailSo\Base\Collection
{
/**
* @var string
*/
private $sNamespace;
/**
* @var string
*/
public $FoldersHash;
/**
* @access protected
*/
protected function __construct()
{
parent::__construct();
$this->sNamespace = '';
$this->FoldersHash = '';
}
/**
* @return \MailSo\Mail\FolderCollection
*/
public static function NewInstance()
{
return new self();
}
/**
* @param string $sFullNameRaw
*
* @return \MailSo\Mail\Folder|null
*/
public function &GetByFullNameRaw($sFullNameRaw)
{
$mResult = null;
foreach ($this->aItems as /* @var $oFolder \MailSo\Mail\Folder */ $oFolder)
{
if ($oFolder->FullNameRaw() === $sFullNameRaw)
{
$mResult = $oFolder;
break;
}
}
return $mResult;
}
/**
* @return string
*/
public function GetNamespace()
{
return $this->sNamespace;
}
/**
* @param string $sNamespace
*
* @return \MailSo\Mail\FolderCollection
*/
public function SetNamespace($sNamespace)
{
$this->sNamespace = $sNamespace;
return $this;
}
/**
* @param array $aUnsortedMailFolders
*
* @return void
*/
public function InitByUnsortedMailFolderArray($aUnsortedMailFolders)
{
$this->Clear();
$aSortedByLenImapFolders = array();
foreach ($aUnsortedMailFolders as /* @var $oMailFolder \MailSo\Mail\Folder */ &$oMailFolder)
{
$aSortedByLenImapFolders[$oMailFolder->FullNameRaw()] =& $oMailFolder;
unset($oMailFolder);
}
unset($aUnsortedMailFolders);
$aAddedFolders = array();
foreach ($aSortedByLenImapFolders as /* @var $oMailFolder \MailSo\Mail\Folder */ $oMailFolder)
{
$sDelimiter = $oMailFolder->Delimiter();
$aFolderExplode = \explode($sDelimiter, $oMailFolder->FullNameRaw());
if (1 < \count($aFolderExplode))
{
\array_pop($aFolderExplode);
$sNonExistenFolderFullNameRaw = '';
foreach ($aFolderExplode as $sFolderExplodeItem)
{
$sNonExistenFolderFullNameRaw .= (0 < \strlen($sNonExistenFolderFullNameRaw))
? $sDelimiter.$sFolderExplodeItem : $sFolderExplodeItem;
if (!isset($aSortedByLenImapFolders[$sNonExistenFolderFullNameRaw]))
{
$aAddedFolders[$sNonExistenFolderFullNameRaw] =
Folder::NewNonExistenInstance($sNonExistenFolderFullNameRaw, $sDelimiter);
}
}
}
}
$aSortedByLenImapFolders = \array_merge($aSortedByLenImapFolders, $aAddedFolders);
unset($aAddedFolders);
\uasort($aSortedByLenImapFolders, function ($oFolderA, $oFolderB) {
return \strnatcmp($oFolderA->FullNameRaw(), $oFolderB->FullNameRaw());
});
foreach ($aSortedByLenImapFolders as /* @var $oMailFolder \MailSo\Mail\Folder */ &$oMailFolder)
{
$this->AddWithPositionSearch($oMailFolder);
unset($oMailFolder);
}
unset($aSortedByLenImapFolders);
}
/**
* @param \MailSo\Mail\Folder $oMailFolder
*
* @return bool
*/
public function AddWithPositionSearch($oMailFolder)
{
$oItemFolder = null;
$bIsAdded = false;
$aList =& $this->GetAsArray();
foreach ($aList as /* @var $oItemFolder \MailSo\Mail\Folder */ $oItemFolder)
{
if ($oMailFolder instanceof \MailSo\Mail\Folder &&
0 === \strpos($oMailFolder->FullNameRaw(), $oItemFolder->FullNameRaw().$oItemFolder->Delimiter()))
{
if ($oItemFolder->SubFolders(true)->AddWithPositionSearch($oMailFolder))
{
$bIsAdded = true;
}
break;
}
}
if (!$bIsAdded && $oMailFolder instanceof \MailSo\Mail\Folder)
{
$bIsAdded = true;
$this->Add($oMailFolder);
}
return $bIsAdded;
}
/**
* @param callable $fCallback
*
* @return void
*/
public function SortByCallback($fCallback)
{
if (\is_callable($fCallback))
{
$aList =& $this->GetAsArray();
\usort($aList, $fCallback);
foreach ($aList as &$oItemFolder)
{
if ($oItemFolder->HasSubFolders())
{
$oItemFolder->SubFolders()->SortByCallback($fCallback);
}
}
}
}
}

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