<commit_before><?php

namespace Athorrent\Application;

use Athorrent\Controller\AccountController;
use Athorrent\Controller\AdministrationController;
use Athorrent\Controller\CacheController;
use Athorrent\Controller\DefaultController;
use Athorrent\Controller\FileController;
use Athorrent\Controller\SearchController;
use Athorrent\Controller\SharingController;
use Athorrent\Controller\SharingFileController;
use Athorrent\Controller\TorrentController;
use Athorrent\Controller\UserController;
use Athorrent\Database\Entity\User;
use Athorrent\Filesystem\UserFilesystem;
use Athorrent\Routing\ControllerMounterTrait;
use Athorrent\Routing\RoutingServiceProvider;
use Athorrent\Security\Csrf\CsrfServiceProvider;
use Athorrent\Security\SecurityServiceProvider;
use Athorrent\Utils\TorrentManager;
use Athorrent\View\TwigServiceProvider;
use Silex\Application;
use Silex\Application\UrlGeneratorTrait;
use Silex\Provider\LocaleServiceProvider;
use Silex\Provider\RememberMeServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

class WebApplication extends BaseApplication implements EventSubscriberInterface
{
    use ControllerMounterTrait;
    use UrlGeneratorTrait;

    public function __construct()
    {
        parent::__construct();

        $this['torrent_manager'] = $this->protect(function (User $user) {
            static $instances = [];

            $userId = $user->getId();

            if (!isset($instances[$userId])) {
                $instances[$userId] = new TorrentManager($user);
            }

            return $instances[$userId];
        });

//        $this['fs'] = function () {
//            return new Filesystem();
//        };

        $this['user.fs'] = function (Application $app) {
            return new UserFilesystem($app, $app['user']);
        };

        $this['dispatcher']->addSubscriber($this);

        $this->register(new TwigServiceProvider(), [
            'twig.path' => TEMPLATES_DIR,
            'twig.options' => ['cache' => CACHE_DIR . DIRECTORY_SEPARATOR . 'twig']
        ]);

        $this->register(new SecurityServiceProvider());

        $this->register(new SessionServiceProvider());
        $this->register(new RememberMeServiceProvider());
        $this->register(new CsrfServiceProvider());

        $this->register(new RoutingServiceProvider());
        $this->register(new LocaleServiceProvider());
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => 'onKernelView',
            KernelEvents::RESPONSE => [
                ['addHeaders', 0],
                ['saveSession', -512]
            ],
            KernelEvents::EXCEPTION => 'onKernelException'
        ];
    }

    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $request = $event->getRequest();

        if (!$request->attributes->get('_ajax')) {
            $result = $event->getControllerResult();
            $flashBag = $this['session']->getFlashBag();

            if ($flashBag->has('notifications')) {
                $result->set('notifications', $flashBag->get('notifications'));
            }

            $result->addTemplate('modal');

            $vars = [
                'debug' => $this['debug'],
                'staticHost' => STATIC_HOST
            ];

            $result->setJsVars($vars);
        }
    }

    public function saveSession(FilterResponseEvent $event)
    {
        $session = $event->getRequest()->getSession();

        if ($session->isStarted()) {
            $session->save();
        }
    }

    public function addHeaders(FilterResponseEvent $event)
    {
        $response = $event->getResponse();
        $response->headers->set('X-Content-Type-Options', 'nosniff');

        if ($response->headers->has('Content-Disposition')) {
            return;
        }

        $request = $event->getRequest();

        if (strpos($request->get('_route'), ':ajax') === false) {
            $response->headers->set('Content-Security-Policy', "script-src 'unsafe-inline' " . $request->getScheme() . '://' . STATIC_HOST);
            $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
            $response->headers->set('Strict-Transport-Security', 'max-age=63072000; includeSubdomains');
            $response->headers->set('X-Frame-Options', 'DENY');
            $response->headers->set('X-XSS-Protection', '1; mode=block');
        }
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $response = $this->handleError($event->getException());
        $event->setResponse($response);
    }

    public function handleError(\Exception $exception)
    {
        if ($exception instanceof HttpException) {
            $statusCode = $exception->getStatusCode();
        } else {
            $statusCode = 500;
        }<commit_msg>during exception handling we assign response only if there is one<commit_after><?php

namespace Athorrent\Application;

use Athorrent\Controller\AccountController;
use Athorrent\Controller\AdministrationController;
use Athorrent\Controller\CacheController;
use Athorrent\Controller\DefaultController;
use Athorrent\Controller\FileController;
use Athorrent\Controller\SearchController;
use Athorrent\Controller\SharingController;
use Athorrent\Controller\SharingFileController;
use Athorrent\Controller\TorrentController;
use Athorrent\Controller\UserController;
use Athorrent\Database\Entity\User;
use Athorrent\Filesystem\UserFilesystem;
use Athorrent\Routing\ControllerMounterTrait;
use Athorrent\Routing\RoutingServiceProvider;
use Athorrent\Security\Csrf\CsrfServiceProvider;
use Athorrent\Security\SecurityServiceProvider;
use Athorrent\Utils\TorrentManager;
use Athorrent\View\TwigServiceProvider;
use Silex\Application;
use Silex\Application\UrlGeneratorTrait;
use Silex\Provider\LocaleServiceProvider;
use Silex\Provider\RememberMeServiceProvider;
use Silex\Provider\SessionServiceProvider;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

class WebApplication extends BaseApplication implements EventSubscriberInterface
{
    use ControllerMounterTrait;
    use UrlGeneratorTrait;

    public function __construct()
    {
        parent::__construct();

        $this['torrent_manager'] = $this->protect(function (User $user) {
            static $instances = [];

            $userId = $user->getId();

            if (!isset($instances[$userId])) {
                $instances[$userId] = new TorrentManager($user);
            }

            return $instances[$userId];
        });

//        $this['fs'] = function () {
//            return new Filesystem();
//        };

        $this['user.fs'] = function (Application $app) {
            return new UserFilesystem($app, $app['user']);
        };

        $this['dispatcher']->addSubscriber($this);

        $this->register(new TwigServiceProvider(), [
            'twig.path' => TEMPLATES_DIR,
            'twig.options' => ['cache' => CACHE_DIR . DIRECTORY_SEPARATOR . 'twig']
        ]);

        $this->register(new SecurityServiceProvider());

        $this->register(new SessionServiceProvider());
        $this->register(new RememberMeServiceProvider());
        $this->register(new CsrfServiceProvider());

        $this->register(new RoutingServiceProvider());
        $this->register(new LocaleServiceProvider());
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => 'onKernelView',
            KernelEvents::RESPONSE => [
                ['addHeaders', 0],
                ['saveSession', -512]
            ],
            KernelEvents::EXCEPTION => 'onKernelException'
        ];
    }

    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $request = $event->getRequest();

        if (!$request->attributes->get('_ajax')) {
            $result = $event->getControllerResult();
            $flashBag = $this['session']->getFlashBag();

            if ($flashBag->has('notifications')) {
                $result->set('notifications', $flashBag->get('notifications'));
            }

            $result->addTemplate('modal');

            $vars = [
                'debug' => $this['debug'],
                'staticHost' => STATIC_HOST
            ];

            $result->setJsVars($vars);
        }
    }

    public function saveSession(FilterResponseEvent $event)
    {
        $session = $event->getRequest()->getSession();

        if ($session->isStarted()) {
            $session->save();
        }
    }

    public function addHeaders(FilterResponseEvent $event)
    {
        $response = $event->getResponse();
        $response->headers->set('X-Content-Type-Options', 'nosniff');

        if ($response->headers->has('Content-Disposition')) {
            return;
        }

        $request = $event->getRequest();

        if (strpos($request->get('_route'), ':ajax') === false) {
            $response->headers->set('Content-Security-Policy', "script-src 'unsafe-inline' " . $request->getScheme() . '://' . STATIC_HOST);
            $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
            $response->headers->set('Strict-Transport-Security', 'max-age=63072000; includeSubdomains');
            $response->headers->set('X-Frame-Options', 'DENY');
            $response->headers->set('X-XSS-Protection', '1; mode=block');
        }
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $response = $this->handleError($event->getException());

        if ($response) {
            $event->setResponse($response);
        }
    }

    public function handleError(\Exception $exception)
    {
        if ($exception instanceof HttpException) {
            $statusCode = $exception->getStatusCode();
        } else {
            $statusCode = 500;
        }
{'fraction_non_alphanumeric': 0.13212910324591967, 'fraction_numerical': 0.0029341646799926646, 'mean_word_length': 3.0396296296296295, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 111, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2628928', 'n_tokens_mistral': 3007, 'n_tokens_neox': 2905, 'n_words': 470}