VirusScannerListener.php 1.81 KiB
<?php declare(strict_types=1);
/*
 * Copyright (C) 2015-2017 IRSTEA
 * All rights reserved.
 */
namespace Irstea\FileUploadBundle\Listener;
use Xenolope\Quahog\Client;
use Irstea\FileUploadBundle\Event\FileUploadCompleteEvent;
use Irstea\FileUploadBundle\Exception\RejectedFileException;
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;
        try {
            // Check clamd server's state
            $this->client->ping();
            // Reload the virus database
            $this->client->reload();
        } catch (ConnectionException $connectionException) {
            $this->client->shutdown();
            $this->client = null;
    /**
     * @param FileUploadCompleteEvent $event
    public function onFileUploadCompleted(FileUploadCompleteEvent $event)
        if ($this->client != null) {
            $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 !');
            $this->client->shutdown();
71727374
} } }