<?php

/**
 * This file is part of the Froxlor project.
 * Copyright (c) 2010 the Froxlor Team (see authors).
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you can also view it online at
 * https://files.froxlor.org/misc/COPYING.txt
 *
 * @copyright  the authors
 * @author     Froxlor team <team@froxlor.org>
 * @license    https://files.froxlor.org/misc/COPYING.txt GPLv2
 */

namespace Froxlor\Cron\Http;

use Froxlor\Database\Database;
use Froxlor\FileDir;
use Froxlor\Froxlor;
use Froxlor\Settings;
use PDO;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class ConfigIO
{

	/**
	 * clean up former created configs, including (if enabled)
	 * awstats, fcgid, php-fpm and of course automatically created
	 * webserver vhost and diroption files
	 *
	 * @return null
	 */
	public function cleanUp()
	{
		// old error logs
		$this->cleanErrLogs();

		// awstats files
		$this->cleanAwstatsFiles();

		// fcgid files
		$this->cleanFcgidFiles();

		// php-fpm files
		$this->cleanFpmFiles();

		// clean webserver-configs
		$this->cleanWebserverConfigs();

		// old htpasswd files
		$this->cleanHtpasswdFiles();

		// customer-specified ssl-certificates
		$this->cleanCustomerSslCerts();
	}

	private function cleanErrLogs()
	{
		$err_dir = FileDir::makeCorrectDir(Froxlor::getInstallDir() . "/logs/");
		if (@is_dir($err_dir)) {
			// now get rid of old stuff
			// (but append /*.log so we don't delete the directory)
			$err_dir .= '/*.log';
			FileDir::safe_exec('rm -f ' . FileDir::makeCorrectFile($err_dir));
		}
	}

	/**
	 * remove awstats related configuration files before regeneration
	 *
	 * @return null
	 */
	private function cleanAwstatsFiles()
	{
		if (Settings::Get('system.traffictool') != 'awstats') {
			return;
		}

		// dhr: cleanout froxlor-generated awstats configs prior to re-creation
		$awstatsclean = [];
		$awstatsclean['header'] = "## GENERATED BY FROXLOR\n";
		$awstatsclean['headerold'] = "## GENERATED BY SYSCP\n";
		$awstatsclean['path'] = $this->getFile('system', 'awstats_conf');

		/**
		 * don't do anything if the directory does not exist
		 * (e.g.
		 * awstats not installed yet or whatever)
		 * fixes #45
		 */
		if ($awstatsclean['path'] !== false && is_dir($awstatsclean['path'])) {
			$awstatsclean['dir'] = dir($awstatsclean['path']);
			while ($awstatsclean['entry'] = $awstatsclean['dir']->read()) {
				$awstatsclean['fullentry'] = FileDir::makeCorrectFile($awstatsclean['path'] . '/' . $awstatsclean['entry']);
				/**
				 * don't do anything if the file does not exist
				 */
				if (@file_exists($awstatsclean['fullentry']) && $awstatsclean['entry'] != '.' && $awstatsclean['entry'] != '..') {
					$awstatsclean['fh'] = fopen($awstatsclean['fullentry'], 'r');
					$awstatsclean['headerRead'] = fgets($awstatsclean['fh'], strlen($awstatsclean['header']) + 1);
					fclose($awstatsclean['fh']);

					if ($awstatsclean['headerRead'] == $awstatsclean['header'] || $awstatsclean['headerRead'] == $awstatsclean['headerold']) {
						$awstats_conf_file = FileDir::makeCorrectFile($awstatsclean['fullentry']);
						@unlink($awstats_conf_file);
					}
				}
			}
		}
		unset($awstatsclean);
		// end dhr
	}

	/**
	 * returns a file/directory from the settings and checks whether it exists
	 *
	 * @param string $group
	 *            settings-group
	 * @param string $varname
	 *            var-name
	 * @param boolean $check_exists
	 *            check if the file exists
	 *
	 * @return string|boolean complete path including filename if any or false on error
	 */
	private function getFile($group, $varname, $check_exists = true)
	{
		// read from settings
		$file = Settings::Get($group . '.' . $varname);

		// check whether it exists
		if ($check_exists && @file_exists($file) == false) {
			return false;
		}
		return $file;
	}

	/**
	 * remove fcgid related configuration files before regeneration
	 *
	 * @return null
	 */
	private function cleanFcgidFiles()
	{
		if (Settings::Get('system.mod_fcgid') == '0') {
			return;
		}

		// get correct directory
		$configdir = $this->getFile('system', 'mod_fcgid_configdir');
		if ($configdir !== false) {
			$configdir = FileDir::makeCorrectDir($configdir);

			if (@is_dir($configdir)) {
				// create directory iterator
				$its = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configdir));

				// iterate through all subdirs,
				// look for php-fcgi-starter files
				// and take immutable-flag away from them
				// so we can delete them :)
				foreach ($its as $it) {
					if ($it->isFile() && $it->getFilename() == 'php-fcgi-starter') {
						// set chattr -i
						FileDir::removeImmutable($its->getPathname());
					}
				}

				// now get rid of old stuff
				// (but append /* so we don't delete the directory)
				$configdir .= '/*';
				FileDir::safe_exec('rm -rf ' . FileDir::makeCorrectFile($configdir));
			}
		}
	}

	/**
	 * remove php-fpm related configuration files before regeneration
	 *
	 * @return null
	 */
	private function cleanFpmFiles()
	{
		if (Settings::Get('phpfpm.enabled') == '0') {
			return;
		}

		// get all fpm config paths
		$fpmconf_sel = Database::prepare("SELECT config_dir FROM `" . TABLE_PANEL_FPMDAEMONS . "`");
		Database::pexecute($fpmconf_sel);
		$fpmconf_paths = $fpmconf_sel->fetchAll(PDO::FETCH_ASSOC);
		// clean all php-fpm config-dirs
		foreach ($fpmconf_paths as $configdir) {
			$configdir = FileDir::makeCorrectDir($configdir['config_dir']);
			if (@is_dir($configdir)) {
				// now get rid of old stuff
				// (but append /*.conf so we don't delete the directory)
				$configdir .= '/*.conf';
				FileDir::safe_exec('rm -f ' . FileDir::makeCorrectFile($configdir));
			} else {
				FileDir::safe_exec('mkdir -p ' . $configdir);
			}
		}

		// also remove aliasconfigdir #1273
		$aliasconfigdir = $this->getFile('phpfpm', 'aliasconfigdir');
		if ($aliasconfigdir !== false) {
			$aliasconfigdir = FileDir::makeCorrectDir($aliasconfigdir);
			if (@is_dir($aliasconfigdir)) {
				$aliasconfigdir .= '/*';
				FileDir::safe_exec('rm -rf ' . FileDir::makeCorrectFile($aliasconfigdir));
			}
		}
	}

	/**
	 * remove webserver related configuration files before regeneration
	 *
	 * @return null
	 */
	private function cleanWebserverConfigs()
	{
		// get directories
		$configdirs = [];
		$dir = $this->getFile('system', 'apacheconf_vhost');
		if ($dir !== false) {
			$configdirs[] = FileDir::makeCorrectDir($dir);
		}

		$dir = $this->getFile('system', 'apacheconf_diroptions');
		if ($dir !== false) {
			$configdirs[] = FileDir::makeCorrectDir($dir);
		}

		// file pattern
		$pattern = "/^([0-9]){2}_(froxlor|syscp)_(.+)\.conf$/";

		// check ALL the folders
		foreach ($configdirs as $config_dir) {
			// check directory
			if (@is_dir($config_dir)) {
				// create directory iterator
				$its = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($config_dir));

				// iterate through all subdirs,
				// look for vhost/diroption files
				// and delete them
				foreach ($its as $it) {
					if ($it->isFile() && preg_match($pattern, $it->getFilename())) {
						// remove file
						FileDir::safe_exec('rm -f ' . escapeshellarg(FileDir::makeCorrectFile($its->getPathname())));
					}
				}
			}
		}
	}

	/**
	 * remove htpasswd files before regeneration
	 *
	 * @return null
	 */
	private function cleanHtpasswdFiles()
	{
		// get correct directory
		$configdir = $this->getFile('system', 'apacheconf_htpasswddir');

		if ($configdir !== false) {
			$configdir = FileDir::makeCorrectDir($configdir);

			if (@is_dir($configdir)) {
				// now get rid of old stuff
				// (but append /* so we don't delete the directory)
				$configdir .= '/*';
				FileDir::safe_exec('rm -f ' . FileDir::makeCorrectFile($configdir));
			}
		}
	}

	/**
	 * remove customer-specified auto-generated ssl-certificates
	 * (they are being regenerated)
	 *
	 * @return null
	 */
	private function cleanCustomerSslCerts()
	{
		/*
		 * only clean up if we're actually using SSL
		 */
		if (Settings::Get('system.use_ssl') == '1') {
			// get correct directory
			$configdir = $this->getFile('system', 'customer_ssl_path');
			if ($configdir !== false) {
				$configdir = FileDir::makeCorrectDir($configdir);

				if (@is_dir($configdir)) {
					// now get rid of old stuff
					// (but append /* so we don't delete the directory)
					$configdir .= '/*';
					FileDir::safe_exec('rm -f ' . FileDir::makeCorrectFile($configdir));
				}
			}
		}
	}
}
