<?php
namespace App\EventSubscriber;
use App\Application\Application;
use App\Controller\App\TokenAuthenticatedController;
use App\Entity\Artigo;
use App\Entity\Audit;
use App\Entity\Company;
use App\Entity\Factura;
use App\Entity\User;
use App\Entity\WareHouse;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ControllerEvent as FilterControllerEvent;
class AuditSubscriber implements EventSubscriberInterface
{
private $tokens;
/** @var EntityManagerInterface */
private $em;
/**
* AuditSubscriber constructor.
* @param EntityManagerInterface $entityManager
*/
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
/**
* @param FilterControllerEvent $event
*/
public function onKernelController(FilterControllerEvent $event)
{
// return true;
$company = $this->em->getRepository(Company::class)->findAll()[0];
$controller = $event->getController();
$rs = $event->getRequest();
/* if (!str_contains($rs->getRequestUri(), 'account')) {
$_SESSION["domain"] = null;
//return $this->redirect($this->generateUrl('accounting_homepage'));
}
*/
if (explode('/access/license/', $rs->getRequestUri()) > 1 and $rs->getMethod() === 'POST')
if ($rs->get('license'))
if (strlen($rs->get('license')) > 500)
return;
// $user=$rs->getUser();
// $http=$rs->getRequestUri();
$to = $rs->server->get('HTTP_REFERER');
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
$action = "";
$function = '';
if (is_array($controller)) {
$action = $controller[1];
$array = explode("\\", get_class($controller[0]));
$function = str_replace('Controller', '', end($array));
$controller = $controller[0];
if ($controller instanceof Controller) {
//$user = $controller->getUser();
} else {
// return;
}
}
$final = $this->planControl($company, $function, $action);
//$r=$this->auditLog($controller);
$this->accessControll($controller, 1);
if (!$final) {
$redirectUrl = str_replace('?youCantGoThere=true', '', $to) . '?youCantGoThere=true';
//TODO: Fixit
// $event->setController(function () use ($redirectUrl) {
// return new RedirectResponse($redirectUrl);
//});
}
/*if ($company->getName() == '..' and sizeof(explode('definicoes/company/identidade', $rs->getRequestUri()))<2) {
$event->setController(function () use ($company) {
return new RedirectResponse('/definicoes/company/identidade/'.$company->getId());
});
}*/
#return;
$exe=$rs->getRequestUri();
if (!str_contains($exe, '/access')) {
$isValidLicense = Application::validLicense($this->em);
if (!$isValidLicense) {
$redirectUrl = '/access/402';
$event->setController(function () use ($redirectUrl) {
return new RedirectResponse($redirectUrl);
});
}
}
return;
/* */
}
/**
* @param $controller
*/
protected function auditLog($controller)
{
$ua = $this->getBrowser();
//$user = $controller->getUser();
$log = new Audit();
$log->setServerUser($_SERVER['USER'])
->setRequestMethod($_SERVER['REQUEST_METHOD'])
->setRequestUri($_SERVER['REQUEST_URI'])
->setRemoteAdrress($_SERVER['REMOTE_ADDR'])
->setServerProtocol($_SERVER['SERVER_PROTOCOL'])
->setServerHost($_SERVER['HTTP_HOST'])
//->setUser($user)
->setRequestData(json_encode($_REQUEST))
->setBrowserName($ua['name'])
->setBrowserVersion($ua['version'])
->setBrowserPlatform($ua['platform'])
->setBrowserData($ua['userAgent'])
->setClientOS($this->getOS());
$this->em->persist($log);
$this->em->flush();
}
/**
* @param $controller
* @param $u
* @param string $target
* @return bool
*/
private function accessControll($controller, $u, $target = '')
{
return;
if ($controller instanceof Controller) {
try {
$user = $controller->getUser();
} catch (\Exception $exception) {
return true;
}
if ($user->getRole() === 'ROLE_ADMIN')
return true;
$target = is_array($target) ? $target : [$target];
foreach ($user->getProfiles() as $profile)
if (in_array($profile->getName(), $target))
return true;
return false;
}
return true;
}
/**
* @param Company $company
* @param string $function
* @param string $action
* @return bool
*/
private function planControl(Company $company, $function, $action = '')
{
$final = true;
$date = new \DateTime();
switch ($function) {
case "Factura":
if ($action !== 'newAction') return true;
$f = $company->getPlan()->getInvoices();
if (is_null($f) or $f == 0) return true;
$d = $this->em->getRepository(Factura::class)->findByDate($date);
$d = sizeof($d);
$final = $d < $f;
break;
case "WareHouse":
if ($action !== 'newAction') return true;
$f = $company->getPlan()->getWarehouses();
if (is_null($f) or $f == 0) return true;
$d = $this->em->getRepository(WareHouse::class)->findAll();
$d = sizeof($d);
$final = $d <= $f;
break;
/*case "Item":
$d=$this->em->getRepository(Artigo::class)->findAll();
$f=$company->getPlan()->get;
$final=$d<$f;
break;*/
case "User":
if ($action !== 'newAction') return true;
$f = $company->getPlan()->getUsers();
if (is_null($f) or $f == 0) return true;
$d = $this->em->getRepository(Artigo::class)->findAll();
$final = $d < $f;
break;
case "Reports":
$final = $company->getPlan()->isReports();
break;
case "Accounting":
$final = $company->getPlan()->isAccounting();
break;
case "Audit":
$final = $company->getPlan()->isAuditing();
break;
case "x":
break;
}
return $final;
}
/**
* @param FilterResponseEvent $event
*/
public function onKernelResponse(FilterResponseEvent $event)
{
// check to see if onKernelController marked this as a token "auth'ed" request
if (!$token = $event->getRequest()->attributes->get('auth_token')) {
return;
}
$response = $event->getResponse();
// create a hash and set it as a response header
$hash = sha1($response->getContent() . $token);
$response->headers->set('X-CONTENT-HASH', $hash);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
//***********************************
public function getOS()
{
global $user_agent;
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 10/i' => 'Windows 10',
'/windows nt 6.3/i' => 'Windows 8.1',
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value)
if (preg_match($regex, $user_agent))
$os_platform = $value;
return $os_platform;
}
public function getBrowser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version = "";
//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
} elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
} elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
$ub = '';
// Next get the name of the useragent yes seperately and for good reason
if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) {
$bname = 'Internet Explorer';
$ub = "MSIE";
} elseif (preg_match('/Firefox/i', $u_agent)) {
$bname = 'Mozilla Firefox';
$ub = "Firefox";
} elseif (preg_match('/OPR/i', $u_agent)) {
$bname = 'Opera';
$ub = "Opera";
} elseif (preg_match('/Chrome/i', $u_agent)) {
$bname = 'Google Chrome';
$ub = "Chrome";
} elseif (preg_match('/Safari/i', $u_agent)) {
$bname = 'Apple Safari';
$ub = "Safari";
} elseif (preg_match('/Netscape/i', $u_agent)) {
$bname = 'Netscape';
$ub = "Netscape";
}
// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) {
$version = $matches['version'][0];
} else {
$version = $matches['version'][1];
}
} else {
$version = $matches['version'][0];
}
// check if we have a number
if ($version == null || $version == "") {
$version = "?";
}
return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}
}