<commit_before><?php
namespace Concrete\Core\Http\Middleware;

use Concrete\Core\Application\ApplicationAwareInterface;
use Concrete\Core\Application\ApplicationAwareTrait;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\Entity\File\File;
use Concrete\Core\File\Image\BasicThumbnailer;
use Concrete\Core\File\Image\Thumbnail\Type\CustomThumbnail;
use Concrete\Core\File\Image\Thumbnail\Type\Version;
use Concrete\Core\File\StorageLocation\StorageLocationInterface;
use Concrete\Core\Http\ResponseFactoryInterface;
use Doctrine\DBAL\Exception\InvalidFieldNameException;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use InvalidArgumentException;
use League\Flysystem\FileExistsException;
use League\Flysystem\Filesystem;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class ThumbnailMiddleware
 * Middleware used to populate thumbnails at the end of each request.
 *
 * This middleware requires the following to be defined on the Application:
 * "database" DatabaseManager
 * "BasicThumbnailer::class" Basic thumbnailer
 */
class ThumbnailMiddleware implements MiddlewareInterface, ApplicationAwareInterface
{
    use ApplicationAwareTrait;

    /**
     * @var Filesystem
     */
    protected $baseFileSystem;

    /**
     * @var \Concrete\Core\File\Image\BasicThumbnailer
     */
    private $thumbnailer;

    /**
     * @var \Doctrine\ORM\EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var Connection
     */
    private $connection;

    /**
     * Process the request and return a response.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param DelegateInterface $frame
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function process(Request $request, DelegateInterface $frame)
    {
        $response = $frame->next($request);

        if ($this->app->isInstalled()) {
            $responseStatusCode = (int) $response->getStatusCode();
            if ($responseStatusCode === 200 || $responseStatusCode === 404) {
                $database = $this->tryGetConnection();
                if ($database !== null) {
                    if ($responseStatusCode === 404) {
                        $searchThumbnailPath = $request->getRequestUri();
                    } else {
                        $searchThumbnailPath = null;
                    }
                    $thumbnail = $this->getThumbnailToGenerate($database, $searchThumbnailPath);
                    if ($thumbnail !== null) {
                        $this->markThumbnailAsBuilt($database, $thumbnail);
                        if ($this->generateThumbnail($database, $thumbnail)) {
                            if ($this->couldBeTheRequestedThumbnail($thumbnail, $searchThumbnailPath)) {
                                $response = $this->buildRedirectToThumbnailResponse($request);
                            }
                        }
                    }
                }
            }
        }

        return $response;
    }

    /**
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    private function buildRedirectToThumbnailResponse(Request $request)
    {
        $redirectTo = (string) $request->getUri();
        $redirectTo .= ((strpos($redirectTo, '?') === false) ? '?' : '&') . mt_rand();
        $responseFactory = $this->app->make(ResponseFactoryInterface::class);
        $response = $responseFactory->redirect($redirectTo);

        return $response;
    }

    /**
     * @param Connection $database
     * @param string|null $searchThumbnailPath
     *
     * @return array|null
     */
    private function getThumbnailToGenerate(Connection $database, $searchThumbnailPath = null)
    {
        try {
            if ($searchThumbnailPath === null) {
                $rs = $database->executeQuery('SELECT * FROM FileImageThumbnailPaths WHERE isBuilt = 0 LIMIT 1');
            } else {
                $rs = $database->executeQuery('SELECT * FROM FileImageThumbnailPaths WHERE isBuilt = 0 ORDER BY ' . $database->getDatabasePlatform()->getLocateExpression('?', 'path') . ' DESC LIMIT 1', [$searchThumbnailPath]);
            }
        } catch (InvalidFieldNameException $e) {
            // Ignore this, user probably needs to run an upgrade.
            return null;
        }

        return $rs->fetch() ?: null;
    }

    /**
     * Generate a thumbnail.
     *
     * @param Connection $database
     * @param array $thumbnail
     *
     * @return bool Returns true if success, false on failure
     */
    private function generateThumbnail(Connection $database, array $thumbnail)
    {
        $file = $this->getEntityManager()->find(File::class, $thumbnail['fileID']);

        if ($this->attemptBuild($file, $thumbnail)) {
            $result = true;
        } else {
            $this->failBuild($file, $thumbnail);
            $result = false;
        }

        return $result;
    }

    /**
     * Try building an unbuilt thumbnail.
     *
     * @param \Concrete\Core\Entity\File\File $file
     * @param array $thumbnail
     *
     * @return bool
     */
    private function attemptBuild(File $file, array $thumbnail)
    {
        try {<commit_msg>Remove unused parameter<commit_after><?php
namespace Concrete\Core\Http\Middleware;

use Concrete\Core\Application\ApplicationAwareInterface;
use Concrete\Core\Application\ApplicationAwareTrait;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\Entity\File\File;
use Concrete\Core\File\Image\BasicThumbnailer;
use Concrete\Core\File\Image\Thumbnail\Type\CustomThumbnail;
use Concrete\Core\File\Image\Thumbnail\Type\Version;
use Concrete\Core\File\StorageLocation\StorageLocationInterface;
use Concrete\Core\Http\ResponseFactoryInterface;
use Doctrine\DBAL\Exception\InvalidFieldNameException;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use InvalidArgumentException;
use League\Flysystem\FileExistsException;
use League\Flysystem\Filesystem;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class ThumbnailMiddleware
 * Middleware used to populate thumbnails at the end of each request.
 *
 * This middleware requires the following to be defined on the Application:
 * "database" DatabaseManager
 * "BasicThumbnailer::class" Basic thumbnailer
 */
class ThumbnailMiddleware implements MiddlewareInterface, ApplicationAwareInterface
{
    use ApplicationAwareTrait;

    /**
     * @var Filesystem
     */
    protected $baseFileSystem;

    /**
     * @var \Concrete\Core\File\Image\BasicThumbnailer
     */
    private $thumbnailer;

    /**
     * @var \Doctrine\ORM\EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var Connection
     */
    private $connection;

    /**
     * Process the request and return a response.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param DelegateInterface $frame
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function process(Request $request, DelegateInterface $frame)
    {
        $response = $frame->next($request);

        if ($this->app->isInstalled()) {
            $responseStatusCode = (int) $response->getStatusCode();
            if ($responseStatusCode === 200 || $responseStatusCode === 404) {
                $database = $this->tryGetConnection();
                if ($database !== null) {
                    if ($responseStatusCode === 404) {
                        $searchThumbnailPath = $request->getRequestUri();
                    } else {
                        $searchThumbnailPath = null;
                    }
                    $thumbnail = $this->getThumbnailToGenerate($database, $searchThumbnailPath);
                    if ($thumbnail !== null) {
                        $this->markThumbnailAsBuilt($database, $thumbnail);
                        if ($this->generateThumbnail($thumbnail)) {
                            if ($this->couldBeTheRequestedThumbnail($thumbnail, $searchThumbnailPath)) {
                                $response = $this->buildRedirectToThumbnailResponse($request);
                            }
                        }
                    }
                }
            }
        }

        return $response;
    }

    /**
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    private function buildRedirectToThumbnailResponse(Request $request)
    {
        $redirectTo = (string) $request->getUri();
        $redirectTo .= ((strpos($redirectTo, '?') === false) ? '?' : '&') . mt_rand();
        $responseFactory = $this->app->make(ResponseFactoryInterface::class);
        $response = $responseFactory->redirect($redirectTo);

        return $response;
    }

    /**
     * @param Connection $database
     * @param string|null $searchThumbnailPath
     *
     * @return array|null
     */
    private function getThumbnailToGenerate(Connection $database, $searchThumbnailPath = null)
    {
        try {
            if ($searchThumbnailPath === null) {
                $rs = $database->executeQuery('SELECT * FROM FileImageThumbnailPaths WHERE isBuilt = 0 LIMIT 1');
            } else {
                $rs = $database->executeQuery('SELECT * FROM FileImageThumbnailPaths WHERE isBuilt = 0 ORDER BY ' . $database->getDatabasePlatform()->getLocateExpression('?', 'path') . ' DESC LIMIT 1', [$searchThumbnailPath]);
            }
        } catch (InvalidFieldNameException $e) {
            // Ignore this, user probably needs to run an upgrade.
            return null;
        }

        return $rs->fetch() ?: null;
    }

    /**
     * Generate a thumbnail.
     *
     * @param array $thumbnail
     *
     * @return bool Returns true if success, false on failure
     */
    private function generateThumbnail(array $thumbnail)
    {
        $file = $this->getEntityManager()->find(File::class, $thumbnail['fileID']);

        if ($this->attemptBuild($file, $thumbnail)) {
            $result = true;
        } else {
            $this->failBuild($file, $thumbnail);
            $result = false;
        }

        return $result;
    }

    /**
     * Try building an unbuilt thumbnail.
     *
     * @param \Concrete\Core\Entity\File\File $file
     * @param array $thumbnail
     *
     * @return bool
     */
    private function attemptBuild(File $file, array $thumbnail)
    {
        try {
{'fraction_non_alphanumeric': 0.1148430066603235, 'fraction_numerical': 0.0024738344433872504, 'mean_word_length': 2.335766423357664, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 51, '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': '6434564', 'n_tokens_mistral': 2880, 'n_tokens_neox': 2791, 'n_words': 584}