#!/usr/bin/php
<?php

/// init
    global $ini;
    global $node;

    require(dirname(__FILE__)."/../include/functions.php");
    init();

    if (get_ini_opt('cron','mail-installmode-off') === '0') { exit(0); }

    check_live();

### read configuration options

	$mail_tpl = $ini['global']['template_dir']."/installmode-off.txt";
	$msgbody=file_get_contents($mail_tpl);

	$mail_fromaddr = $ini['global']['email'];
	$mail_fromname = $ini['global']['name'];

	$firstuid=$ini['global']['firstuid'];
	$webroot=$ini['global']['webroot'];

	$node=$ini['global']['node'];
	if (!(is_numeric($node))) { $node=1; }

### get vhosts

	$sql ="SELECT
		`vhosts`.`id` AS vhid,
		`vhosts`.`host` AS hostname,
		`vhosts`.`token` AS token,
		`domain`.`name` AS domname,
		`client`.`name` AS cliname,
		`client`.`email` AS climail,
		`vhosts`.`writable` AS writable,
		`vhosts`.`rights` AS rights,
		`client`.`email` AS email
		FROM `vhosts`
		LEFT JOIN `domain` ON `vhosts`.`domainid`=`domain`.`id`
		LEFT JOIN `client` ON `domain`.`clientid`=`client`.`id`
		WHERE `client`.`node`='$node'
		AND DATE_ADD(`vhosts`.`modified`, INTERVAL 3 DAY ) < NOW()
		AND `vhosts`.`redirect` IS NULL
		AND `vhosts`.`active`=1
		AND `vhosts`.`rights`=1
		AND `domain`.`active`=1
		AND `client`.`active`=1
	";

$result=DBquery($sql);

while ($row=$result->fetch_assoc())
{
	$vhdir=$webroot.'/'.$row['cliname'].'/'.$row['domname'].'/'.$row['hostname'];
	$vhname=$row['hostname'].'.'.$row['domname'];

	if (is_dir($vhdir))
	{
		$mail_subject="A Malware védelmet újra aktiváltuk a(z) $vhname weboldalon";

		$sendbody=str_replace('#VHOST#', $vhname, $msgbody);
		$sendbody=str_replace('#VHID#', $row['vhid'], $sendbody);
		$sendbody=str_replace('#VHTOKEN#', $row['token'], $sendbody);
		$sendbody=str_replace('#WRITABLE#', $row['writable'], $sendbody);

		$email=$row['climail'];

#		echo "$email\n";
#		echo "$vhname\n";
#		echo "$sendbody\n";

		if ($email != "")
		{
			mailsend($mail_fromname, $mail_fromaddr, $email, $mail_subject, $sendbody);
			sleep(1);
		}
	}
}

if ($result->num_rows > 0)
{
	// update mode in db
	$fixsql ="UPDATE `vhosts`
			LEFT JOIN `domain` ON `vhosts`.`domainid`=`domain`.`id`
			LEFT JOIN `client` ON `domain`.`clientid`=`client`.`id`
			SET `vhosts`.`rights`='2'
			WHERE `client`.`node`='$node'
			AND DATE_ADD(`vhosts`.`modified`, INTERVAL 3 DAY ) < NOW()
			AND `vhosts`.`redirect` IS NULL
			AND `vhosts`.`active`=1
			AND `vhosts`.`rights`=1
			AND `domain`.`active`=1
			AND `client`.`active`=1
			";
	$fixresult=DBquery($fixsql);

	// trigger rights fix
	DBquery("UPDATE `var` SET `value`='1' WHERE `key` = 'rights_update' AND `node` = '".$node."';");
}

DBclose();

?>
