VirusScannerListener.php 1.76 KiB
<?php declare(strict_types=1);
/*
 * Copyright (C) 2015-2017 IRSTEA
 * All rights reserved.
 */
namespace Irstea\FileUploadBundle\Listener;
use Irstea\FileUploadBundle\Event\FileUploadCompleteEvent;
use Irstea\FileUploadBundle\Exception\RejectedFileException;
use Xenolope\Quahog\Client;
use Xenolope\Quahog\Exception\ConnectionException;
/**
 * Description of AntivirusListener.
class VirusScannerListener
    /**
     * @var Client
    private $client;
    /**
     * @param Client $client
    public function __construct(Client $client)
        $this->client = $client;
    /**
     * @param FileUploadCompleteEvent $event
    public function onFileUploadCompleted(FileUploadCompleteEvent $event)
        $this->client = $this->getClient();
        $file = $event->getUploadedFile();
        $path = $file->getLocalPath();
        $result = $this->client->scanFile($path);
        $hasVirus = $result['status'] === Client::RESULT_FOUND;
        $meta = $file->getMetadata();
        $meta['virus_scanner'] = ['has_virus' => $hasVirus];
        if ($hasVirus) {
            $desc = $result['reason'];
            $meta['virus_scanner']['detected'] = $result['reason'];
        $file->setMetadata($meta);
        if ($hasVirus) {
            throw new RejectedFileException($file, $desc ? sprintf('Found the %s virus !', $desc) : 'Virus found !');
    /**
     * @throws ConnectionException
     * @return Client
    private function getClient(): Client
        try {
            // Check clamd server's state
            $this->client->ping();
71727374757677
return $this->client; } catch (ConnectionException $connectionException) { throw $connectionException; } } }