diff options
author | Robin Appelman <robin@icewind.nl> | 2021-12-17 17:50:48 +0300 |
---|---|---|
committer | Carl Schwan <carl@carlschwan.eu> | 2022-04-19 11:20:38 +0300 |
commit | d1a75dc6ad344d6174e7d9bf17f8159154c5a46a (patch) | |
tree | a8c6b56d126deff7e0f7a668a7dfebdc18a93409 /lib | |
parent | 100273b5959d3a7fb7583d986705422e80bead5c (diff) |
psalm analysis and fixespsalm
Signed-off-by: Robin Appelman <robin@icewind.nl>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/Activity/Provider.php | 9 | ||||
-rw-r--r-- | lib/AppConfig.php | 63 | ||||
-rw-r--r-- | lib/AppInfo/Application.php | 61 | ||||
-rw-r--r-- | lib/AvirWrapper.php | 16 | ||||
-rw-r--r-- | lib/CallbackReadDataWrapper.php | 13 | ||||
-rw-r--r-- | lib/Controller/RuleController.php | 24 | ||||
-rw-r--r-- | lib/Db/Rule.php | 16 | ||||
-rw-r--r-- | lib/Db/RuleMapper.php | 57 | ||||
-rw-r--r-- | lib/Event/ScanStateEvent.php | 5 | ||||
-rw-r--r-- | lib/Item.php | 64 | ||||
-rw-r--r-- | lib/Migration/CleanupCronTask.php | 3 | ||||
-rw-r--r-- | lib/Migration/Install.php | 3 | ||||
-rw-r--r-- | lib/Sabre/PropfindPlugin.php | 6 | ||||
-rw-r--r-- | lib/Scanner/ExternalClam.php | 25 | ||||
-rw-r--r-- | lib/Scanner/ExternalKaspersky.php | 11 | ||||
-rw-r--r-- | lib/Scanner/LocalClam.php | 6 | ||||
-rw-r--r-- | lib/Scanner/ScannerBase.php | 22 | ||||
-rw-r--r-- | lib/Scanner/ScannerFactory.php | 4 | ||||
-rw-r--r-- | lib/Status.php | 4 |
19 files changed, 250 insertions, 162 deletions
diff --git a/lib/Activity/Provider.php b/lib/Activity/Provider.php index 78b2a99..15f446a 100644 --- a/lib/Activity/Provider.php +++ b/lib/Activity/Provider.php @@ -117,7 +117,7 @@ class Provider implements IProvider { return $event; } - private function setSubjects(IEvent $event, $subject, array $parameters) { + private function setSubjects(IEvent $event, string $subject, array $parameters): void { $placeholders = $replacements = []; foreach ($parameters as $placeholder => $parameter) { $placeholders[] = '{' . $placeholder . '}'; @@ -138,7 +138,12 @@ class Provider implements IProvider { return $res; } - private function getFileDeleted(IEvent $event) { + /** + * @return (int|string)[] + * + * @psalm-return array{type: 'file', id: int, name: string, path: string} + */ + private function getFileDeleted(IEvent $event): array { return [ 'type' => 'file', 'id' => $event->getObjectId(), diff --git a/lib/AppConfig.php b/lib/AppConfig.php index febd702..cc99d9a 100644 --- a/lib/AppConfig.php +++ b/lib/AppConfig.php @@ -11,18 +11,18 @@ namespace OCA\Files_Antivirus; use OCP\IConfig; /** - * @method string getAvMode() - * @method string getAvSocket() - * @method string getAvHost() - * @method string getAvPort() - * @method string getAvCmdOptions() - * @method string getAvPath() - * @method string getAvInfectedAction() - * @method string getAvIcapRequestService() - * @method string getAvIcapResponseHeader() - * @method string getAvIcapChunkSize() - * @method string getAvIcapConnectTimeout() - * + * @method ?string getAvMode() + * @method ?string getAvSocket() + * @method ?string getAvHost() + * @method ?string getAvPort() + * @method ?string getAvCmdOptions() + * @method ?string getAvPath() + * @method ?string getAvInfectedAction() + * @method ?string getAvStreamMaxLength() + * @method ?string getAvIcapRequestService() + * @method ?string getAvIcapResponseHeader() + * @method ?string getAvIcapChunkSize() + * @method ?string getAvIcapConnectTimeout() * @method null setAvMode(string $avMode) * @method null setAvSocket(string $avsocket) * @method null setAvHost(string $avHost) @@ -39,6 +39,7 @@ use OCP\IConfig; class AppConfig { /** @var string */ private $appName = 'files_antivirus'; + /** @var IConfig */ private $config; @@ -80,6 +81,7 @@ class AppConfig { /** * Get full commandline + * * @return string */ public function getCmdline(): string { @@ -104,6 +106,7 @@ class AppConfig { /** * Get all setting values as an array + * * @return array */ public function getAllValues(): array { @@ -115,10 +118,11 @@ class AppConfig { /** * Get a value by key + * * @param string $key - * @return string + * @return ?string */ - public function getAppValue(string $key): string { + public function getAppValue(string $key): ?string { $defaultValue = null; if (array_key_exists($key, $this->defaults)) { $defaultValue = $this->defaults[$key]; @@ -127,21 +131,26 @@ class AppConfig { } /** - * Set a value by key + * * Set a value by key + * * + * * @param string $key * @param string $value */ - public function setAppValue(string $key, string $value) { + public function setAppValue(string $key, string $value): void { $this->config->setAppValue($this->appName, $key, $value); } /** - * Set a value with magic __call invocation + * * Set a value with magic __call invocation + * * + * * @param string $key * @param array $args + * * @throws \BadFunctionCallException */ - protected function setter(string $key, array $args) { + protected function setter(string $key, array $args): void { if (array_key_exists($key, $this->defaults)) { $this->setAppValue($key, $args[0]); } else { @@ -151,11 +160,12 @@ class AppConfig { /** * Get a value with magic __call invocation + * * @param string $key - * @return string + * @return ?string * @throws \BadFunctionCallException */ - protected function getter(string $key): string { + protected function getter(string $key): ?string { if (array_key_exists($key, $this->defaults)) { return $this->getAppValue($key); } @@ -165,6 +175,7 @@ class AppConfig { /** * Translates property_name into propertyName + * * @param string $property * @return string */ @@ -176,15 +187,16 @@ class AppConfig { /** * Does all the someConfig to some_config magic + * * @param string $property * @return string */ protected function propertyToKey(string $property): string { $parts = preg_split('/(?=[A-Z])/', $property); - $column = null; + $column = ''; foreach ($parts as $part) { - if ($column === null) { + if ($column === '') { $column = $part; } else { $column .= '_' . lcfirst($part); @@ -199,19 +211,20 @@ class AppConfig { * * @param string $methodName * @param array $args - * @return string|void + * @return ?string * @throws \BadFunctionCallException */ - public function __call(string $methodName, array $args) { + public function __call(string $methodName, array $args): ?string { $attr = lcfirst(substr($methodName, 3)); $key = $this->propertyToKey($attr); if (strpos($methodName, 'set') === 0) { $this->setter($key, $args); + return null; } elseif (strpos($methodName, 'get') === 0) { return $this->getter($key); } else { throw new \BadFunctionCallException($methodName . - ' does not exist'); + ' does not exist'); } } } diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index f399181..4b3da89 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -8,57 +8,62 @@ namespace OCA\Files_Antivirus\AppInfo; +use OC\Files\Filesystem; use OC\Files\Storage\Wrapper\Jail; use OCA\Files_Antivirus\AvirWrapper; use OCA\Files_Antivirus\Scanner\ScannerFactory; use OCP\Activity\IManager; use OCP\AppFramework\App; +use OCP\AppFramework\Bootstrap\IBootContext; +use OCP\AppFramework\Bootstrap\IBootstrap; +use OCP\AppFramework\Bootstrap\IRegistrationContext; use OCP\Files\IHomeStorage; +use OCP\Files\Storage\IStorage; use OCP\IL10N; use OCP\ILogger; use Symfony\Component\EventDispatcher\EventDispatcherInterface; -class Application extends App { +class Application extends App implements IBootstrap { public const APP_NAME = 'files_antivirus'; public function __construct(array $urlParams = []) { parent::__construct(self::APP_NAME, $urlParams); } - + + public function register(IRegistrationContext $context): void { + } + + public function boot(IBootContext $context): void { + \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $this, 'setupWrapper'); + } + /** - * Add wrapper for local storages + * * Add wrapper for local storages */ - public function setupWrapper() { - \OC\Files\Filesystem::addStorageWrapper( + public function setupWrapper(): void { + Filesystem::addStorageWrapper( 'oc_avir', - function ($mountPoint, $storage) { - /** - * @var \OC\Files\Storage\Storage $storage - */ + function (string $mountPoint, IStorage $storage) { if ($storage->instanceOfStorage(Jail::class)) { // No reason to wrap jails again return $storage; } - if ($storage instanceof \OC\Files\Storage\Storage) { - $container = $this->getContainer(); - $scannerFactory = $container->query(ScannerFactory::class); - $l10n = $container->query(IL10N::class); - $logger = $container->query(ILogger::class); - $activityManager = $container->query(IManager::class); - $eventDispatcher = $container->query(EventDispatcherInterface::class); - return new AvirWrapper([ - 'storage' => $storage, - 'scannerFactory' => $scannerFactory, - 'l10n' => $l10n, - 'logger' => $logger, - 'activityManager' => $activityManager, - 'isHomeStorage' => $storage->instanceOfStorage(IHomeStorage::class), - 'eventDispatcher' => $eventDispatcher, - ]); - } - - return $storage; + $container = $this->getContainer(); + $scannerFactory = $container->query(ScannerFactory::class); + $l10n = $container->query(IL10N::class); + $logger = $container->query(ILogger::class); + $activityManager = $container->query(IManager::class); + $eventDispatcher = $container->query(EventDispatcherInterface::class); + return new AvirWrapper([ + 'storage' => $storage, + 'scannerFactory' => $scannerFactory, + 'l10n' => $l10n, + 'logger' => $logger, + 'activityManager' => $activityManager, + 'isHomeStorage' => $storage->instanceOfStorage(IHomeStorage::class), + 'eventDispatcher' => $eventDispatcher, + ]); }, 1 ); diff --git a/lib/AvirWrapper.php b/lib/AvirWrapper.php index 6cfa3fd..c232b01 100644 --- a/lib/AvirWrapper.php +++ b/lib/AvirWrapper.php @@ -22,19 +22,19 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface; use OCA\Files_Trashbin\Trash\ITrashManager; class AvirWrapper extends Wrapper { - + /** * Modes that are used for writing * @var array */ private $writingModes = ['r+', 'w', 'w+', 'a', 'a+', 'x', 'x+', 'c', 'c+']; - + /** @var ScannerFactory */ protected $scannerFactory; - + /** @var IL10N */ protected $l10n; - + /** @var ILogger */ protected $logger; @@ -64,12 +64,12 @@ class AvirWrapper extends Wrapper { $this->shouldScan = $event->getState(); }); } - + /** * Asynchronously scan data that are written to the file * @param string $path * @param string $mode - * @return resource | bool + * @return resource | false */ public function fopen($path, $mode) { $stream = $this->storage->fopen($path, $mode); @@ -132,7 +132,7 @@ class AvirWrapper extends Wrapper { $trashManager = \OC::$server->query(ITrashManager::class); $trashManager->resumeTrash(); } - + $this->logger->warning( 'Infected file deleted. ' . $status->getDetails() . ' Account: ' . $owner . ' Path: ' . $path, @@ -165,7 +165,7 @@ class AvirWrapper extends Wrapper { } return $stream; } - + /** * Checks whether passed mode is suitable for writing * @param string $mode diff --git a/lib/CallbackReadDataWrapper.php b/lib/CallbackReadDataWrapper.php index 6a411fc..16d85ca 100644 --- a/lib/CallbackReadDataWrapper.php +++ b/lib/CallbackReadDataWrapper.php @@ -15,19 +15,19 @@ class CallbackReadDataWrapper extends CallbackWrapper { * Wraps a stream with the provided callbacks * * @param resource $source - * @param callable $readData (optional) + * @param callable $read (optional) * @param callable $write (optional) * @param callable $close (optional) * @param callable $readDir (optional) - * @return resource + * @return resource|bool * * @throws \BadMethodCallException */ - public static function wrap($source, $readData = null, $write = null, $close = null, $readDir = null, $preClose = null) { + public static function wrap($source, $read = null, $write = null, $close = null, $readDir = null, $preClose = null) { $context = stream_context_create([ 'callbackReadData' => [ 'source' => $source, - 'readData' => $readData, + 'readData' => $read, 'write' => $write, 'close' => $close, 'readDir' => $readDir, @@ -37,6 +37,9 @@ class CallbackReadDataWrapper extends CallbackWrapper { return Wrapper::wrapSource($source, $context, 'callbackReadData', self::class); } + /** + * @return true + */ protected function open() { $context = $this->loadContext('callbackReadData'); @@ -50,7 +53,7 @@ class CallbackReadDataWrapper extends CallbackWrapper { public function stream_read($count) { $result = parent::stream_read($count); if (is_callable($this->readDataCallback)) { - call_user_func($this->readDataCallback, strlen($count), $result); + call_user_func($this->readDataCallback, strlen($result), $result); } return $result; } diff --git a/lib/Controller/RuleController.php b/lib/Controller/RuleController.php index 8bab700..c388c2b 100644 --- a/lib/Controller/RuleController.php +++ b/lib/Controller/RuleController.php @@ -16,15 +16,15 @@ use \OCA\Files_Antivirus\Db\Rule; use \OCA\Files_Antivirus\Db\RuleMapper; class RuleController extends Controller { - + /** @var RuleMapper */ private $ruleMapper; - + public function __construct($appName, IRequest $request, RuleMapper $ruleMapper) { parent::__construct($appName, $request); $this->ruleMapper = $ruleMapper; } - + /** * Returns all rules * @return JSONResponse @@ -33,7 +33,7 @@ class RuleController extends Controller { $statuses = $this->ruleMapper->findAll(); return new JSONResponse(['statuses' => $statuses]); } - + /** * Removes all rules * @return JSONResponse @@ -42,7 +42,7 @@ class RuleController extends Controller { $this->ruleMapper->deleteAll(); return new JSONResponse(); } - + /** * Resets a table to initial state * @return JSONResponse @@ -52,7 +52,7 @@ class RuleController extends Controller { $this->ruleMapper->populate(); return new JSONResponse(); } - + /** * Adds/Updates a rule * @param int $id @@ -68,26 +68,26 @@ class RuleController extends Controller { } else { $rule = new Rule(); } - + $rule->setStatusType($statusType); $rule->setDescription($description); $rule->setStatus($status); - + if ($statusType === Rule::RULE_TYPE_CODE) { - $rule->setResult($match); + $rule->setResult((int)$match); } else { $rule->setMatch($match); } - + if ($id) { $newRule = $this->ruleMapper->update($rule); } else { $newRule = $this->ruleMapper->insert($rule); } - + return new JSONResponse($newRule); } - + /** * Deletes a rule * @param int $id diff --git a/lib/Db/Rule.php b/lib/Db/Rule.php index 5c1b763..272503a 100644 --- a/lib/Db/Rule.php +++ b/lib/Db/Rule.php @@ -16,6 +16,8 @@ use JsonSerializable; * * @package OCA\Files_Antivirus\Db * + * @method string getMatch() + * @method int getStatus() * @method setStatusType(int $type) * @method setDescription(string $description) * @method setStatus(int $status) @@ -23,12 +25,12 @@ use JsonSerializable; * @method setMatch(string $mach) */ class Rule extends Entity implements JsonSerializable { - + /* * Rule needs to be validated by the exit code returned by scanner */ public const RULE_TYPE_CODE = 1; - + /* * Rule needs to be validated by parsing the output returned by scanner with regexp */ @@ -39,35 +41,35 @@ class Rule extends Entity implements JsonSerializable { * @var int groupId - used for sorting */ protected $groupId; - + /** * * @var int statusType - RULE_TYPE_CODE or RULE_TYPE_MATCH defines whether * rule should be checked by the shell exit code or regexp */ protected $statusType; - + /** * * @var int result - shell exit code for rules * of the type RULE_TYPE_CODE, 0 otherwise */ protected $result; - + /** * * @var string match - regexp to match for rules * of the type RULE_TYPE_MATCH, '' otherwise */ protected $match; - + /** * * @var string description - shell exit code meaning for rules * of the type RULE_TYPE_CODE, '' otherwise */ protected $description; - + /** * * @var int status - file check status. SCANRESULT_UNCHECKED, SCANRESULT_INFECTED, diff --git a/lib/Db/RuleMapper.php b/lib/Db/RuleMapper.php index 6512e33..535f04c 100644 --- a/lib/Db/RuleMapper.php +++ b/lib/Db/RuleMapper.php @@ -15,16 +15,17 @@ class RuleMapper extends Mapper { public function __construct(IDBConnection $db) { parent::__construct($db, 'files_avir_status', Rule::class); } - + /** * Empty the table * @return bool */ public function deleteAll() { $sql = 'DELETE FROM `*PREFIX*files_avir_status`'; - return $this->execute($sql); + $this->execute($sql); + return true; } - + /** * Find rule by id * @param int $id @@ -34,11 +35,11 @@ class RuleMapper extends Mapper { $sql = 'SELECT * FROM *PREFIX*files_avir_status WHERE id = ?'; return $this->findEntity($sql, [$id]); } - + /** - * Get all rules + * * Get all rules */ - public function findAll() { + public function findAll(): array { $sql = 'SELECT * FROM `*PREFIX*files_avir_status`'; return $this->findEntities($sql); } @@ -52,7 +53,7 @@ class RuleMapper extends Mapper { $sql = 'SELECT * FROM `*PREFIX*files_avir_status` WHERE `status_type`=? and `result`=?'; return $this->findEntities($sql, [Rule::RULE_TYPE_CODE, $result]); } - + /** * Get collection of rules of type Match * @param int $status @@ -62,11 +63,11 @@ class RuleMapper extends Mapper { $sql = 'SELECT * FROM `*PREFIX*files_avir_status` WHERE `status_type`=? and `status`=?'; return $this->findEntities($sql, [Rule::RULE_TYPE_MATCH, $status]); } - + /** - * Fill the table with rules used with clamav + * * Fill the table with rules used with clamav */ - public function populate() { + public function populate(): void { $descriptions = [ [ 'groupId' => 0, @@ -85,7 +86,7 @@ class RuleMapper extends Mapper { 'description' => '', 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_INFECTED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -94,7 +95,7 @@ class RuleMapper extends Mapper { 'description' => 'Unknown option passed.', 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -103,7 +104,7 @@ class RuleMapper extends Mapper { 'description' => 'Database initialization error.', 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -112,7 +113,7 @@ class RuleMapper extends Mapper { 'description' => 'Not supported file type.', 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -121,7 +122,7 @@ class RuleMapper extends Mapper { 'description' => "Can't open directory.", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -130,7 +131,7 @@ class RuleMapper extends Mapper { 'description' => "Can't open file. (ofm)", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -139,7 +140,7 @@ class RuleMapper extends Mapper { 'description' => 'Error reading file. (ofm)', 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -148,7 +149,7 @@ class RuleMapper extends Mapper { 'description' => "Can't stat input file / directory.", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -157,7 +158,7 @@ class RuleMapper extends Mapper { 'description' => "Can't get absolute path name of current working directory.", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -166,7 +167,7 @@ class RuleMapper extends Mapper { 'description' => 'I/O error, please check your file system.', 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -175,7 +176,7 @@ class RuleMapper extends Mapper { 'description' => "Can't initialize logger.", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -184,7 +185,7 @@ class RuleMapper extends Mapper { 'description' => "Can't create temporary files/directories (check permissions).", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -193,7 +194,7 @@ class RuleMapper extends Mapper { 'description' => "Can't write to temporary directory (please specify another one).", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -202,7 +203,7 @@ class RuleMapper extends Mapper { 'description' => "Can't allocate memory (calloc).", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_CODE, @@ -211,7 +212,7 @@ class RuleMapper extends Mapper { 'description' => "Can't allocate memory (malloc).", 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_MATCH, @@ -220,7 +221,7 @@ class RuleMapper extends Mapper { 'description' => '', 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_CLEAN ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_MATCH, @@ -229,7 +230,7 @@ class RuleMapper extends Mapper { 'description' => '', 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_INFECTED ], - + [ 'groupId' => 0, 'statusType' => Rule::RULE_TYPE_MATCH, @@ -239,7 +240,7 @@ class RuleMapper extends Mapper { 'status' => \OCA\Files_Antivirus\Status::SCANRESULT_UNCHECKED ], ]; - + foreach ($descriptions as $description) { $rule = Rule::fromParams($description); $this->insert($rule); diff --git a/lib/Event/ScanStateEvent.php b/lib/Event/ScanStateEvent.php index 06a21e7..77bbf87 100644 --- a/lib/Event/ScanStateEvent.php +++ b/lib/Event/ScanStateEvent.php @@ -23,7 +23,7 @@ namespace OCA\Files_Antivirus\Event; -use Symfony\Component\EventDispatcher\Event; +use OCP\EventDispatcher\Event; class ScanStateEvent extends Event { @@ -31,10 +31,11 @@ class ScanStateEvent extends Event { private $state; public function __construct(bool $state) { + parent::__construct(); $this->state = $state; } - public function getState() { + public function getState(): bool { return $this->state; } } diff --git a/lib/Item.php b/lib/Item.php index 13f5764..a6da6c8 100644 --- a/lib/Item.php +++ b/lib/Item.php @@ -22,6 +22,7 @@ use OCP\ILogger; class Item { /** * file handle, user to read from the file + * * @var resource */ protected $fileHandle; @@ -56,13 +57,15 @@ class Item { * @param File $file * @param bool $isCron */ - public function __construct(AppConfig $appConfig, - ActivityManager $activityManager, - ItemMapper $itemMapper, - ILogger $logger, - IRootFolder $rootFolder, - File $file, - $isCron) { + public function __construct( + AppConfig $appConfig, + ActivityManager $activityManager, + ItemMapper $itemMapper, + ILogger $logger, + IRootFolder $rootFolder, + File $file, + $isCron + ) { $this->config = $appConfig; $this->activityManager = $activityManager; $this->itemMapper = $itemMapper; @@ -74,7 +77,8 @@ class Item { /** * Reads a file portion by portion until the very end - * @return string|boolean + * + * @return string|false */ public function fread() { if (!($this->file->getSize() > 0)) { @@ -92,9 +96,9 @@ class Item { } /** - * Action to take if this item is infected + * * Action to take if this item is infected */ - public function processInfected(Status $status) { + public function processInfected(Status $status): void { $infectedAction = $this->config->getAvInfectedAction(); $shouldDelete = $infectedAction === 'delete'; @@ -133,25 +137,27 @@ class Item { } /** - * Action to take if this item status is unclear + * * Action to take if this item status is unclear + * * + * * @param Status $status */ - public function processUnchecked(Status $status) { + public function processUnchecked(Status $status): void { //TODO: Show warning to the user: The file can not be checked $this->logError('Not Checked. ' . $status->getDetails()); } /** - * Action to take if this item status is not infected + * * Action to take if this item status is not infected */ - public function processClean() { + public function processClean(): void { $this->updateCheckTime(); } /** - * Update the check-time of this item to current time + * * Update the check-time of this item to current time */ - private function updateCheckTime() { + private function updateCheckTime(): void { try { try { $item = $this->itemMapper->findByFileId($this->file->getId()); @@ -165,29 +171,33 @@ class Item { $item->setCheckTime(time()); $this->itemMapper->insert($item); } catch (\Exception $e) { - $this->logger->error(__METHOD__.', exception: '.$e->getMessage(), ['app' => 'files_antivirus']); + $this->logger->error(__METHOD__ . ', exception: ' . $e->getMessage(), ['app' => 'files_antivirus']); } } /** * Check if the end of file is reached + * * @return boolean */ private function feof() { $isDone = feof($this->fileHandle); if ($isDone) { $this->logDebug('Scan is done'); - fclose($this->fileHandle); + $handle = $this->fileHandle; + fclose($handle); $this->fileHandle = null; } return $isDone; } /** - * Opens a file for reading + * * Opens a file for reading + * * + * * @throws \RuntimeException */ - private function getFileHandle() { + private function getFileHandle(): void { $fileHandle = $this->file->fopen('r'); if ($fileHandle === false) { $this->logError('Can not open for reading.'); @@ -199,24 +209,24 @@ class Item { } /** - * Delete infected file + * * Delete infected file */ - private function deleteFile() { + private function deleteFile(): void { //prevent from going to trashbin if (App::isEnabled('files_trashbin')) { /** @var ITrashManager $trashManager */ - $trashManager = \OC::$server->query(ITrashManager::class); + $trashManager = \OC::$server->get(ITrashManager::class); $trashManager->pauseTrash(); } $this->file->delete(); if (App::isEnabled('files_trashbin')) { /** @var ITrashManager $trashManager */ - $trashManager = \OC::$server->query(ITrashManager::class); + $trashManager = \OC::$server->get(ITrashManager::class); $trashManager->resumeTrash(); } } - private function generateExtraInfo() { + private function generateExtraInfo(): string { $owner = $this->file->getOwner(); if ($owner === null) { @@ -235,14 +245,14 @@ class Item { /** * @param string $message */ - public function logDebug($message) { + public function logDebug($message): void { $this->logger->debug($message . $this->generateExtraInfo(), ['app' => 'files_antivirus']); } /** * @param string $message */ - public function logError($message) { + public function logError($message): void { $this->logger->error($message . $this->generateExtraInfo(), ['app' => 'files_antivirus']); } } diff --git a/lib/Migration/CleanupCronTask.php b/lib/Migration/CleanupCronTask.php index 6e20701..10aba57 100644 --- a/lib/Migration/CleanupCronTask.php +++ b/lib/Migration/CleanupCronTask.php @@ -39,6 +39,9 @@ class CleanupCronTask implements IRepairStep { return 'Cleanup cron task'; } + /** + * @return void + */ public function run(IOutput $output) { $this->jobList->remove('OCA\Files_Antivirus\Cron\Task'); } diff --git a/lib/Migration/Install.php b/lib/Migration/Install.php index 68a5ed1..74eb49c 100644 --- a/lib/Migration/Install.php +++ b/lib/Migration/Install.php @@ -44,6 +44,9 @@ class Install implements IRepairStep { return 'Populare default rules'; } + /** + * @return void + */ public function run(IOutput $output) { $rules = $this->ruleMapper->findAll(); diff --git a/lib/Sabre/PropfindPlugin.php b/lib/Sabre/PropfindPlugin.php index 23871a6..7e7588a 100644 --- a/lib/Sabre/PropfindPlugin.php +++ b/lib/Sabre/PropfindPlugin.php @@ -47,6 +47,9 @@ class PropfindPlugin extends ServerPlugin { $this->eventDispatcher = $eventDispatcher; } + /** + * @return void + */ public function initialize(Server $server) { $server->on('beforeMove', [$this, 'beforeMove'], 90); $this->server = $server; @@ -55,6 +58,8 @@ class PropfindPlugin extends ServerPlugin { /** * @param string $sourcePath source path * @param string $destination destination path + * + * @return void */ public function beforeMove($sourcePath, $destination) { $sourceNode = $this->server->tree->getNodeForPath($sourcePath); @@ -66,7 +71,6 @@ class PropfindPlugin extends ServerPlugin { $avMaxFileSize = $this->appConfig->getAvMaxFileSize(); if ($avMaxFileSize > -1 && $sourceNode->getSize() > $avMaxFileSize) { $this->eventDispatcher->dispatch( - ScanStateEvent::class, new ScanStateEvent(false) ); } diff --git a/lib/Scanner/ExternalClam.php b/lib/Scanner/ExternalClam.php index fa49e36..6cf34bd 100644 --- a/lib/Scanner/ExternalClam.php +++ b/lib/Scanner/ExternalClam.php @@ -14,7 +14,7 @@ use OCA\Files_Antivirus\StatusFactory; use OCP\ILogger; class ExternalClam extends ScannerBase { - + /** * Daemon/socket mode * @var bool @@ -32,10 +32,13 @@ class ExternalClam extends ScannerBase { parent::__construct($config, $logger, $statusFactory); $this->useSocket = $this->appConfig->getAvMode() === 'socket'; } - + + /** + * @return void + */ public function initScanner() { parent::initScanner(); - + if ($this->useSocket) { $avSocket = $this->appConfig->getAvSocket(); $this->writeHandle = stream_socket_client('unix://' . $avSocket, $errno, $errstr, 5); @@ -44,11 +47,11 @@ class ExternalClam extends ScannerBase { } } else { $avHost = $this->appConfig->getAvHost(); - $avPort = $this->appConfig->getAvPort(); + $avPort = (int)$this->appConfig->getAvPort(); if (!($avHost && $avPort)) { throw new \RuntimeException('The ClamAV port and host are not set up.'); } - $this->writeHandle = ($avHost && $avPort) ? @fsockopen($avHost, $avPort) : false; + $this->writeHandle = @fsockopen($avHost, $avPort); if (!$this->getWriteHandle()) { throw new \RuntimeException('The ClamAV module is not in daemon mode.'); } @@ -57,7 +60,10 @@ class ExternalClam extends ScannerBase { // request scan from the daemon @fwrite($this->getWriteHandle(), "nINSTREAM\n"); } - + + /** + * @return void + */ protected function shutdownScanner() { @fwrite($this->getWriteHandle(), pack('N', 0)); $response = fgets($this->getWriteHandle()); @@ -65,11 +71,12 @@ class ExternalClam extends ScannerBase { 'Response :: ' . $response, ['app' => 'files_antivirus'] ); - @fclose($this->getWriteHandle()); - + $handle = $this->getWriteHandle(); + @fclose($handle); + $this->status->parseResponse($response); } - + protected function prepareChunk($data) { $chunkLength = pack('N', strlen($data)); return $chunkLength . $data; diff --git a/lib/Scanner/ExternalKaspersky.php b/lib/Scanner/ExternalKaspersky.php index 34f4d46..f7c2487 100644 --- a/lib/Scanner/ExternalKaspersky.php +++ b/lib/Scanner/ExternalKaspersky.php @@ -45,6 +45,9 @@ class ExternalKaspersky extends ScannerBase { $this->chunkSize = 10 * 1024 * 1024; } + /** + * @return void + */ public function initScanner() { parent::initScanner(); @@ -57,6 +60,9 @@ class ExternalKaspersky extends ScannerBase { $this->writeHandle = fopen("php://temp", 'w+'); } + /** + * @return void + */ protected function writeChunk($chunk) { if (ftell($this->writeHandle) > $this->chunkSize) { $this->scanBuffer(); @@ -65,7 +71,7 @@ class ExternalKaspersky extends ScannerBase { parent::writeChunk($chunk); } - protected function scanBuffer() { + protected function scanBuffer(): void { rewind($this->writeHandle); $avHost = $this->appConfig->getAvHost(); @@ -111,6 +117,9 @@ class ExternalKaspersky extends ScannerBase { } } + /** + * @return void + */ protected function shutdownScanner() { $this->scanBuffer(); } diff --git a/lib/Scanner/LocalClam.php b/lib/Scanner/LocalClam.php index 89460c2..2d314a9 100644 --- a/lib/Scanner/LocalClam.php +++ b/lib/Scanner/LocalClam.php @@ -44,6 +44,9 @@ class LocalClam extends ScannerBase { } } + /** + * @return void + */ public function initScanner() { parent::initScanner(); @@ -61,6 +64,9 @@ class LocalClam extends ScannerBase { $this->writeHandle = $this->pipes[0]; } + /** + * @return void + */ protected function shutdownScanner() { @fclose($this->pipes[0]); $output = stream_get_contents($this->pipes[1]); diff --git a/lib/Scanner/ScannerBase.php b/lib/Scanner/ScannerBase.php index 5bd91ca..65d1ae3 100644 --- a/lib/Scanner/ScannerBase.php +++ b/lib/Scanner/ScannerBase.php @@ -89,6 +89,9 @@ abstract class ScannerBase implements IScanner { abstract protected function shutdownScanner(); + /** + * @return Status + */ public function getStatus() { if ($this->infectedStatus instanceof Status) { return $this->infectedStatus; @@ -126,9 +129,12 @@ abstract class ScannerBase implements IScanner { } /** - * Async scan - new portion of data is available + * * Async scan - new portion of data is available + * * * * @param string $data + * + * @return void */ public function onAsyncData($data) { $this->writeChunk($data); @@ -145,7 +151,9 @@ abstract class ScannerBase implements IScanner { } /** - * Open write handle. etc + * * Open write handle. etc + * + * @return void */ public function initScanner() { $this->byteCount = 0; @@ -157,6 +165,8 @@ abstract class ScannerBase implements IScanner { /** * @param string $chunk + * + * @return void */ protected function writeChunk($chunk) { $this->fwrite( @@ -166,6 +176,8 @@ abstract class ScannerBase implements IScanner { /** * @param string $data + * + * @return void */ final protected function fwrite($data) { if ($this->isAborted) { @@ -175,7 +187,7 @@ abstract class ScannerBase implements IScanner { $dataLength = strlen($data); $streamSizeLimit = (int)$this->appConfig->getAvStreamMaxLength(); if ($this->byteCount + $dataLength > $streamSizeLimit) { - \OC::$server->getLogger()->debug( + $this->logger->debug( 'reinit scanner', ['app' => 'files_antivirus'] ); @@ -188,7 +200,7 @@ abstract class ScannerBase implements IScanner { if (!$isReopenSuccessful || !$this->writeRaw($data)) { if (!$this->isLogUsed) { $this->isLogUsed = true; - \OC::$server->getLogger()->warning( + $this->logger->warning( 'Failed to write a chunk. Check if Stream Length matches StreamMaxLength in anti virus daemon settings', ['app' => 'files_antivirus'] ); @@ -214,7 +226,7 @@ abstract class ScannerBase implements IScanner { * @param $data * @return bool */ - protected function writeRaw($data) { + protected function writeRaw(string $data) { $dataLength = strlen($data); $bytesWritten = @fwrite($this->getWriteHandle(), $data); if ($bytesWritten === $dataLength) { diff --git a/lib/Scanner/ScannerFactory.php b/lib/Scanner/ScannerFactory.php index 74eafe1..c4a1500 100644 --- a/lib/Scanner/ScannerFactory.php +++ b/lib/Scanner/ScannerFactory.php @@ -45,6 +45,8 @@ class ScannerFactory { throw new \InvalidArgumentException('Application is misconfigured. Please check the settings at the admin page. Invalid mode: ' . $avMode); } - return $this->serverContainer->resolve($scannerClass); + /** @var IScanner $scanner */ + $scanner = $this->serverContainer->resolve($scannerClass); + return $scanner; } } diff --git a/lib/Status.php b/lib/Status.php index 9b9767a..688eb51 100644 --- a/lib/Status.php +++ b/lib/Status.php @@ -83,6 +83,8 @@ class Status { /** * @param string $rawResponse * @param integer $result + * + * @return void */ public function parseResponse($rawResponse, $result = null) { $matches = []; @@ -157,7 +159,7 @@ class Status { return array_merge($cleanRules, $infectedRules, $uncheckedRules); } - public function dispatch(Item $item) { + public function dispatch(Item $item): void { switch ($this->getNumericStatus()) { case self::SCANRESULT_UNCHECKED: $item->processUnchecked($this); |