<?php
require_once(dirname(__FILE__).'/vendor/PHPMailer/class.phpmailer.php');
require_once(dirname(__FILE__).'/vendor/PHPMailer/class.smtp.php');

$smtpConfDefault = array('host' => "smtp.1und1.de", 'secure' => true, 'auth' => true, 'port' => 465, 'from' => "smtp@global-cube.de", 'username' => "smtp@global-cube.de", 'password' => "gcbssmtp");

$config = parse_ini_file(dirname(__FILE__) . "/../../GAPS.ini");
$smtpConfXml = getSmtpConfFromIni($config);

function checkProtocolDirectory($path, $all = false)
{
	$result = array();

	$protDir = dir($path);
	while ($filename = $protDir->read()) {
		if (!preg_match('/\.log$/i', $filename))
			continue;
		$log = new Logfile("{$path}\\{$filename}");
		if ($all || $log->ErrorLevel < 3 || $log->LastChangedDays >= 4) {
			$result[] = $log;
		}
	}
	return $result;
}

function getSmtpConfFromIni($config) {
	$conf = array();
	$conf['host'] = (@$config['SMTP_FEHLERBERICHT'] != "N") ? $config['SMTP_HOST'] : "";
	$conf['port'] = $config['SMTP_PORT'];
	$conf['from'] = $config['SMTP_FROM'];
	$conf['username'] = $config['SMTP_USER'];
	$conf['password'] = $config['SMTP_PW'];
	$conf['secure'] = ($config['SMTP_SSL'] == "J");
	$conf['auth'] = ($conf['username'] != "");
	return $conf;
}

/**
 * @param $mail PHPMailer
 * @param $conf array
 * @param $mailFrom string
 * @return bool
 */
function setSmtpConf($mail, $conf, $mailFrom) {
	$mail->IsSMTP();
	$mail->Host = $conf['host'];
	$mail->SMTPAuth = $conf['auth'];
	$mail->Port = $conf['port'];
	$mail->Username = $conf['username'];
	$mail->Password = $conf['password'];
	$mail->SMTPSecure = ($conf['secure']) ? "ssl" : false;
	$mail->Sender = '';
	$mail->SetFrom($conf['from'], $mailFrom);
	//$mail->SMTPDebug = true;
	return true;
}

function mailFormat($list) {
	$result = "";
	$addresses = explode(";", $list);

	foreach ($addresses as $address) {
		$result .= "<a href=\"mailto:{$address}\">{$address}</a><br/>";
	}
	return $result;
}

function sendMail($logs, $mailFrom)
{
	$today = date("d.m.Y");
	$total = count($logs);

	ob_start();
	include('fehlerbericht_template.php');
	$body = ob_get_clean();

	$mail = new PHPMailer();

	$mail->AddAddress('fehlerbericht@global-cube.de', 'Global Cube');
	$mail->Subject = "{$mailFrom}: Fehlerbericht vom {$today}, {$total} Fehler";
	$mail->AltBody = json_encode($logs);
	$mail->MsgHTML($body);

	foreach ($logs as $logfile) {
		if ($logfile->Type == "Modell") {
			$mail->AddAttachment($logfile->Filename);
		}
	}

	if (send($mail, $mailFrom)) {
		echo "  Fehlerbericht gesendet!\r\n";
	}
}

/**
 * @param $mail PHPMailer
 * @param $mailFrom string
 * @return bool
 */
function send ($mail, $mailFrom) {
	global $smtpConfDefault;
	global $smtpConfXml;
	setSmtpConf($mail, $smtpConfDefault, $mailFrom);		
	if ($mail->Send()) {
		$mail->SmtpClose();
		return true;
	}
	$mail->SmtpClose();
	sleep(10);
	$mail->Port = 25;
	$mail->SMTPSecure = false;
	if ($mail->Send()) {
		$mail->SmtpClose();
		return true;
	}
	$mail->SmtpClose();
	sleep(10);
	if ($smtpConfXml['host']!="") {
		setSmtpConf($mail, $smtpConfXml, $mailFrom);
		if ($mail->Send()) {
			$mail->SmtpClose();
			return true;
		}
		$mail->SmtpClose();
	}
	echo "  Fehler im Mailversand: " . $mail->ErrorInfo . "\r\n";
	return false;
}

function sendStatusMail($mailFrom, $startTime, $endTime, $errorCount, $batchFile, $attachments) {
    global $config;

	$mail = new PHPMailer();
	$mail->AddAddress('status@global-cube.de', 'Global Cube');
	$today = date("Y-m-d");
	
	$content = array('subject' => "{$mailFrom};{$startTime};{$endTime};{$today};{$errorCount};{$batchFile}");
	$mail->Subject = $content['subject'];
	$mail->isHTML(false); 
	$mail->Body = "[]";
	foreach($attachments as $key => $file) {
		if (file_exists($file)) {
			$content[$key] = file_get_contents($file);
			$mail->AddAttachment($file);
		}
	}
	
	if (send($mail, $mailFrom)) {
		echo "  Statusbericht gesendet!\r\n";
	} else {
		$opts = array('http' =>
			array(
				'method'  => 'POST',
				'header'  => "Content-type: application/json\r\n",
				'content' => json_encode($content),
				'timeout' => 60
			 )
		);
		if (isset($config['PROXY'])) {
			$opt['http']['proxy'] = $config['PROXY'];
			$opt['http']['request_fulluri'] = true;
		}
		$context  = stream_context_create($opts);
		$result = file_get_contents('http://dev.global-cube.de/statusmail/', false, $context, -1, 40000);
		echo "  " . $result;
	}
	return true;
}

function checkStarterLogs($path, $dirMatch)
{
	$today = date("d.m.Y");
	$result = array();

	$protDir = dir($path);
	while ($filename = $protDir->read()) {
		if (!preg_match('/\.' . $dirMatch . '\.log$/i', $filename))
			continue;

		foreach (file("{$path}\\{$filename}") as $line) {
			if (strpos($line, $today)) {
				$result[] = json_decode($line);
			}
		}
	}
	return $result;
}

function checkStarter($path)
{
	$result = array();
	$logPath = $path . "\\logs";
	
	$protDir = dir($logPath);
	while ($filename = $protDir->read()) {
		if (!preg_match('/\.log$/i', $filename) || $filename == "gcstarter.log") {
			continue;
		}
		$result[$filename] = json_decode("[" . implode(",", file("{$logPath}\\{$filename}")) . "]");
	}
	$result['gcstarter.xml'] = file_get_contents($path . "\\config\gcstarter.xml");
	return $result;
}

function sendUpdateMail($logs)
{
	global $smtpConfDefault;
	global $smtpConfXml;
	global $config;

	$today = date("d.m.Y");

	ob_start();
	include('statusbericht_template.php');
	$body = ob_get_clean();

	$mail = new PHPMailer();
	$mail->AddAddress($config['STATUSBERICHT']);
	$mail->Subject = "{$config['KUNDE']} - Kontenaktualisierung GAPS";
	$mail->MsgHTML($body);

	if (send($mail, "Global Cube")) {
		echo "  Updatebericht gesendet!\r\n";
		return true;
	}
	return false;
}