<?php

declare(strict_types=1);
/**
 * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
 * SPDX-License-Identifier: AGPL-3.0-only
 */
namespace OC\IntegrityCheck\Iterator;

class ExcludeFoldersByPathFilterIterator extends \RecursiveFilterIterator {
	private $excludedFolders;

	public function __construct(\RecursiveIterator $iterator, $root = '') {
		parent::__construct($iterator);

		$appFolders = \OC::$APPSROOTS;
		foreach ($appFolders as $key => $appFolder) {
			$appFolders[$key] = rtrim($appFolder['path'], '/');
		}

		$excludedFolders = [
			rtrim($root . '/data', '/'),
			rtrim($root . '/themes', '/'),
			rtrim($root . '/config', '/'),
			rtrim($root . '/apps', '/'),
			rtrim($root . '/assets', '/'),
			rtrim($root . '/lost+found', '/'),
			// Ignore folders generated by updater since the updater is replaced
			// after the integrity check is run.
			// See https://github.com/owncloud/updater/issues/318#issuecomment-212497846
			rtrim($root . '/updater', '/'),
			rtrim($root . '/_oc_upgrade', '/'),
		];
		$customDataDir = \OC::$server->getConfig()->getSystemValueString('datadirectory', '');
		if ($customDataDir !== '') {
			$excludedFolders[] = rtrim($customDataDir, '/');
		}

		$this->excludedFolders = array_merge($excludedFolders, $appFolders);
	}

	public function accept(): bool {
		return !\in_array(
			$this->current()->getPathName(),
			$this->excludedFolders,
			true
		);
	}
}
