<?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\Http;

use Froxlor\FileDir;
use Froxlor\Froxlor;
use Froxlor\Settings;

class Statistics
{

	/**
	 * Create or modify the AWStats configuration file for the given domain.
	 * Modified by Berend Dekens to allow custom configurations.
	 *
	 * @param string $logFile
	 * @param string $siteDomain
	 * @param string $hostAliases
	 * @param string $customerDocroot
	 * @param array $domain_data
	 *
	 * @return null
	 * @throws \Exception
	 */
	public static function createAWStatsConf(
		string $logFile,
		string $siteDomain,
		string $hostAliases,
		string $customerDocroot,
		array $domain_data = []
	) {
		// Generation header
		$header = "## GENERATED BY FROXLOR\n";
		$header2 = "## Do not remove the line above! This tells Froxlor to update this configuration\n## If you wish to manually change this configuration file, remove the first line to make sure Froxlor won't rebuild this file\n## Generated for domain {SITE_DOMAIN} on " . date('l dS \of F Y h:i:s A') . "\n";

		$awstats_dir = FileDir::makeCorrectDir($customerDocroot . '/awstats/' . $siteDomain . '/');
		if (!is_dir($awstats_dir)) {
			FileDir::safe_exec('mkdir -p ' . escapeshellarg($awstats_dir));
		}
		// chown created folder, #258
		self::makeChownWithNewStats($domain_data);

		// weird but could happen...
		if (!is_dir(Settings::Get('system.awstats_conf'))) {
			FileDir::safe_exec('mkdir -p ' . escapeshellarg(Settings::Get('system.awstats_conf')));
		}

		$logformat = Settings::Get('system.awstats_logformat');
		if (!is_numeric($logformat)) {
			// if LogFormat is NOT numeric (e.g. 1,2,3,4), we quote it.
			// 1-4 are pre-defined formats by awstats which must not be quoted to work properly. So if
			// it is not a integer, it is something customized and we simply quote it.
			// Only escaping double-quote should be fine, as we only put the whole string under double-quote.
			$logformat = '"' . str_replace('"', '\"', Settings::Get('system.awstats_logformat')) . '"';
		}

		// These are the variables we will replace
		$regex = [
			'/\{LOG_FILE\}/',
			'/\{SITE_DOMAIN\}/',
			'/\{HOST_ALIASES\}/',
			'/\{CUSTOMER_DOCROOT\}/',
			'/\{AWSTATS_CONF\}/',
			'/\{AWSTATS_LOGFORMAT\}/'
		];
		$replace = [
			FileDir::makeCorrectFile($logFile),
			$siteDomain,
			$hostAliases,
			$awstats_dir,
			FileDir::makeCorrectDir(Settings::Get('system.awstats_conf')),
			$logformat
		];

		// File names
		$domain_file = FileDir::makeCorrectFile(Settings::Get('system.awstats_conf') . '/awstats.' . $siteDomain . '.conf');
		$model_file = Froxlor::getInstallDir() . '/templates/misc/awstats/awstats.froxlor.model.conf';
		$model_file = FileDir::makeCorrectFile($model_file);

		// Test if the file exists
		if (file_exists($domain_file)) {
			// Check for the generated header - if this is a manual modification we won't update
			$awstats_domain_conf = fopen($domain_file, 'r');

			if (fgets($awstats_domain_conf, strlen($header)) != $header) {
				fclose($awstats_domain_conf);
				return;
			}

			// Close the file
			fclose($awstats_domain_conf);
		}

		$awstats_domain_conf = fopen($domain_file, 'w');
		$awstats_model_conf = fopen($model_file, 'r');

		// Write the header
		fwrite($awstats_domain_conf, $header);
		fwrite($awstats_domain_conf, preg_replace($regex, $replace, $header2));

		// Write the configuration file
		while (($line = fgets($awstats_model_conf, 4096)) !== false) {
			if (!preg_match('/^#/', $line) && trim($line) != '') {
				fwrite($awstats_domain_conf, preg_replace($regex, $replace, $line));
			}
		}

		fclose($awstats_domain_conf);
		fclose($awstats_model_conf);
	}

	/**
	 * chowns stats-tools folder, either with webserver-user or
	 * if fcgid/php-fpm is used, the customers name, #258
	 *
	 * @param array $row array of panel_customers
	 *
	 * @return void
	 * @throws \Exception
	 */
	public static function makeChownWithNewStats(array $row)
	{
		// get correct user
		if ((Settings::Get('system.mod_fcgid') == '1' || Settings::Get('phpfpm.enabled') == '1') && isset($row['deactivated']) && $row['deactivated'] == '0') {
			$user = $row['loginname'];
			$group = $row['loginname'];
		} else {
			$user = $row['guid'];
			$group = $row['guid'];
		}

		// get correct directory
		$dir = $row['documentroot'] . '/' . Settings::Get('system.traffictool') . '/';

		// only run chown if directory exists
		if (file_exists($dir)) {
			// run chown
			FileDir::safe_exec('chown -R ' . escapeshellarg($user) . ':' . escapeshellarg($group) . ' ' . escapeshellarg(FileDir::makeCorrectDir($dir)));
		}
	}
}
