src/EventSubscriber/AuditSubscriber.php line 42

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Application\Application;
  4. use App\Controller\App\TokenAuthenticatedController;
  5. use App\Entity\Artigo;
  6. use App\Entity\Audit;
  7. use App\Entity\Company;
  8. use App\Entity\Factura;
  9. use App\Entity\User;
  10. use App\Entity\WareHouse;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  15. use Symfony\Component\HttpKernel\KernelEvents;
  16. use Symfony\Component\HttpKernel\Event\ControllerEvent as FilterControllerEvent;
  17. class AuditSubscriber implements EventSubscriberInterface
  18. {
  19.     private $tokens;
  20.     /** @var EntityManagerInterface  */
  21.     private $em;
  22.     /**
  23.      * AuditSubscriber constructor.
  24.      * @param EntityManagerInterface $entityManager
  25.      */
  26.     public function __construct(EntityManagerInterface $entityManager)
  27.     {
  28.         $this->em $entityManager;
  29.     }
  30.     /**
  31.      * @param FilterControllerEvent $event
  32.      */
  33.     public function onKernelController(FilterControllerEvent $event)
  34.     {
  35.        // return true;
  36.         $company $this->em->getRepository(Company::class)->findAll()[0];
  37.         $controller $event->getController();
  38.         $rs $event->getRequest();
  39.         /* if (!str_contains($rs->getRequestUri(), 'account')) {
  40.             $_SESSION["domain"] = null;
  41.             //return $this->redirect($this->generateUrl('accounting_homepage'));
  42.         }
  43. */
  44.         if (explode('/access/license/'$rs->getRequestUri()) > and $rs->getMethod() === 'POST')
  45.             if ($rs->get('license'))
  46.                 if (strlen($rs->get('license')) > 500)
  47.                     return;
  48.         // $user=$rs->getUser();
  49.         // $http=$rs->getRequestUri();
  50.         $to $rs->server->get('HTTP_REFERER');
  51.         // when a controller class defines multiple action methods, the controller
  52.         // is returned as [$controllerInstance, 'methodName']
  53.         $action "";
  54.         $function '';
  55.         if (is_array($controller)) {
  56.             $action $controller[1];
  57.             $array explode("\\"get_class($controller[0]));
  58.             $function str_replace('Controller'''end($array));
  59.             $controller $controller[0];
  60.             if ($controller instanceof Controller) {
  61.                 //$user = $controller->getUser();
  62.             } else {
  63.                // return;
  64.             }
  65.         }
  66.         $final $this->planControl($company$function$action);
  67.         //$r=$this->auditLog($controller);
  68.         $this->accessControll($controller1);
  69.         if (!$final) {
  70.             $redirectUrl str_replace('?youCantGoThere=true'''$to) . '?youCantGoThere=true';
  71.             //TODO: Fixit
  72.            // $event->setController(function () use ($redirectUrl) {
  73.               //  return new RedirectResponse($redirectUrl);
  74.             //});
  75.         }
  76.         /*if ($company->getName() == '..' and sizeof(explode('definicoes/company/identidade', $rs->getRequestUri()))<2) {
  77.             $event->setController(function () use ($company) {
  78.                 return new RedirectResponse('/definicoes/company/identidade/'.$company->getId());
  79.             });
  80.         }*/
  81.         #return;
  82.         $exe=$rs->getRequestUri();
  83.         if (!str_contains($exe'/access')) {
  84.             $isValidLicense Application::validLicense($this->em);
  85.             if (!$isValidLicense) {
  86.                 $redirectUrl '/access/402';
  87.                 $event->setController(function () use ($redirectUrl) {
  88.                     return new RedirectResponse($redirectUrl);
  89.                 });
  90.             }
  91.         }
  92.         return;
  93.         /* */
  94.     }
  95.     /**
  96.      * @param $controller
  97.      */
  98.     protected function auditLog($controller)
  99.     {
  100.         $ua $this->getBrowser();
  101.         //$user = $controller->getUser();
  102.         $log = new Audit();
  103.         $log->setServerUser($_SERVER['USER'])
  104.             ->setRequestMethod($_SERVER['REQUEST_METHOD'])
  105.             ->setRequestUri($_SERVER['REQUEST_URI'])
  106.             ->setRemoteAdrress($_SERVER['REMOTE_ADDR'])
  107.             ->setServerProtocol($_SERVER['SERVER_PROTOCOL'])
  108.             ->setServerHost($_SERVER['HTTP_HOST'])
  109.             //->setUser($user)
  110.             ->setRequestData(json_encode($_REQUEST))
  111.             ->setBrowserName($ua['name'])
  112.             ->setBrowserVersion($ua['version'])
  113.             ->setBrowserPlatform($ua['platform'])
  114.             ->setBrowserData($ua['userAgent'])
  115.             ->setClientOS($this->getOS());
  116.         $this->em->persist($log);
  117.         $this->em->flush();
  118.     }
  119.     /**
  120.      * @param $controller
  121.      * @param $u
  122.      * @param string $target
  123.      * @return bool
  124.      */
  125.     private function accessControll($controller$u$target '')
  126.     {
  127.         return;
  128.         if ($controller instanceof Controller) {
  129.             try {
  130.                 $user $controller->getUser();
  131.             } catch (\Exception $exception) {
  132.                 return true;
  133.             }
  134.             if ($user->getRole() === 'ROLE_ADMIN')
  135.                 return true;
  136.             $target is_array($target) ? $target : [$target];
  137.             foreach ($user->getProfiles() as $profile)
  138.                 if (in_array($profile->getName(), $target))
  139.                     return true;
  140.             return false;
  141.         }
  142.         return true;
  143.     }
  144.     /**
  145.      * @param Company $company
  146.      * @param string $function
  147.      * @param string $action
  148.      * @return bool
  149.      */
  150.     private function planControl(Company $company$function$action '')
  151.     {
  152.         $final true;
  153.         $date = new \DateTime();
  154.         switch ($function) {
  155.             case "Factura":
  156.                 if ($action !== 'newAction') return true;
  157.                 $f $company->getPlan()->getInvoices();
  158.                 if (is_null($f) or $f == 0) return true;
  159.                 $d $this->em->getRepository(Factura::class)->findByDate($date);
  160.                 $d sizeof($d);
  161.                 $final $d $f;
  162.                 break;
  163.             case "WareHouse":
  164.                 if ($action !== 'newAction') return true;
  165.                 $f $company->getPlan()->getWarehouses();
  166.                 if (is_null($f) or $f == 0) return true;
  167.                 $d $this->em->getRepository(WareHouse::class)->findAll();
  168.                 $d sizeof($d);
  169.                 $final $d <= $f;
  170.                 break;
  171.                 /*case "Item":
  172.                 $d=$this->em->getRepository(Artigo::class)->findAll();
  173.                 $f=$company->getPlan()->get;
  174.                 $final=$d<$f;
  175.                 break;*/
  176.             case "User":
  177.                 if ($action !== 'newAction') return true;
  178.                 $f $company->getPlan()->getUsers();
  179.                 if (is_null($f) or $f == 0) return true;
  180.                 $d $this->em->getRepository(Artigo::class)->findAll();
  181.                 $final $d $f;
  182.                 break;
  183.             case "Reports":
  184.                 $final $company->getPlan()->isReports();
  185.                 break;
  186.             case "Accounting":
  187.                 $final $company->getPlan()->isAccounting();
  188.                 break;
  189.             case "Audit":
  190.                 $final $company->getPlan()->isAuditing();
  191.                 break;
  192.             case "x":
  193.                 break;
  194.         }
  195.         return $final;
  196.     }
  197.     /**
  198.      * @param FilterResponseEvent $event
  199.      */
  200.     public function onKernelResponse(FilterResponseEvent $event)
  201.     {
  202.         // check to see if onKernelController marked this as a token "auth'ed" request
  203.         if (!$token $event->getRequest()->attributes->get('auth_token')) {
  204.             return;
  205.         }
  206.         $response $event->getResponse();
  207.         // create a hash and set it as a response header
  208.         $hash sha1($response->getContent() . $token);
  209.         $response->headers->set('X-CONTENT-HASH'$hash);
  210.     }
  211.     public static function getSubscribedEvents()
  212.     {
  213.         return [
  214.             KernelEvents::CONTROLLER => 'onKernelController',
  215.         ];
  216.     }
  217.     //***********************************
  218.     public function getOS()
  219.     {
  220.         global $user_agent;
  221.         $user_agent $_SERVER['HTTP_USER_AGENT'];
  222.         $os_platform "Unknown OS Platform";
  223.         $os_array = array(
  224.             '/windows nt 10/i' => 'Windows 10',
  225.             '/windows nt 6.3/i' => 'Windows 8.1',
  226.             '/windows nt 6.2/i' => 'Windows 8',
  227.             '/windows nt 6.1/i' => 'Windows 7',
  228.             '/windows nt 6.0/i' => 'Windows Vista',
  229.             '/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
  230.             '/windows nt 5.1/i' => 'Windows XP',
  231.             '/windows xp/i' => 'Windows XP',
  232.             '/windows nt 5.0/i' => 'Windows 2000',
  233.             '/windows me/i' => 'Windows ME',
  234.             '/win98/i' => 'Windows 98',
  235.             '/win95/i' => 'Windows 95',
  236.             '/win16/i' => 'Windows 3.11',
  237.             '/macintosh|mac os x/i' => 'Mac OS X',
  238.             '/mac_powerpc/i' => 'Mac OS 9',
  239.             '/linux/i' => 'Linux',
  240.             '/ubuntu/i' => 'Ubuntu',
  241.             '/iphone/i' => 'iPhone',
  242.             '/ipod/i' => 'iPod',
  243.             '/ipad/i' => 'iPad',
  244.             '/android/i' => 'Android',
  245.             '/blackberry/i' => 'BlackBerry',
  246.             '/webos/i' => 'Mobile'
  247.         );
  248.         foreach ($os_array as $regex => $value)
  249.             if (preg_match($regex$user_agent))
  250.                 $os_platform $value;
  251.         return $os_platform;
  252.     }
  253.     public function getBrowser()
  254.     {
  255.         $u_agent $_SERVER['HTTP_USER_AGENT'];
  256.         $bname 'Unknown';
  257.         $platform 'Unknown';
  258.         $version "";
  259.         //First get the platform?
  260.         if (preg_match('/linux/i'$u_agent)) {
  261.             $platform 'linux';
  262.         } elseif (preg_match('/macintosh|mac os x/i'$u_agent)) {
  263.             $platform 'mac';
  264.         } elseif (preg_match('/windows|win32/i'$u_agent)) {
  265.             $platform 'windows';
  266.         }
  267.         $ub '';
  268.         // Next get the name of the useragent yes seperately and for good reason
  269.         if (preg_match('/MSIE/i'$u_agent) && !preg_match('/Opera/i'$u_agent)) {
  270.             $bname 'Internet Explorer';
  271.             $ub "MSIE";
  272.         } elseif (preg_match('/Firefox/i'$u_agent)) {
  273.             $bname 'Mozilla Firefox';
  274.             $ub "Firefox";
  275.         } elseif (preg_match('/OPR/i'$u_agent)) {
  276.             $bname 'Opera';
  277.             $ub "Opera";
  278.         } elseif (preg_match('/Chrome/i'$u_agent)) {
  279.             $bname 'Google Chrome';
  280.             $ub "Chrome";
  281.         } elseif (preg_match('/Safari/i'$u_agent)) {
  282.             $bname 'Apple Safari';
  283.             $ub "Safari";
  284.         } elseif (preg_match('/Netscape/i'$u_agent)) {
  285.             $bname 'Netscape';
  286.             $ub "Netscape";
  287.         }
  288.         // finally get the correct version number
  289.         $known = array('Version'$ub'other');
  290.         $pattern '#(?<browser>' join('|'$known) .
  291.             ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
  292.         if (!preg_match_all($pattern$u_agent$matches)) {
  293.             // we have no matching number just continue
  294.         }
  295.         // see how many we have
  296.         $i count($matches['browser']);
  297.         if ($i != 1) {
  298.             //we will have two since we are not using 'other' argument yet
  299.             //see if version is before or after the name
  300.             if (strripos($u_agent"Version") < strripos($u_agent$ub)) {
  301.                 $version $matches['version'][0];
  302.             } else {
  303.                 $version $matches['version'][1];
  304.             }
  305.         } else {
  306.             $version $matches['version'][0];
  307.         }
  308.         // check if we have a number
  309.         if ($version == null || $version == "") {
  310.             $version "?";
  311.         }
  312.         return array(
  313.             'userAgent' => $u_agent,
  314.             'name' => $bname,
  315.             'version' => $version,
  316.             'platform' => $platform,
  317.             'pattern' => $pattern
  318.         );
  319.     }
  320. }