#!/usr/bin/php
<?php

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

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

	if ($node != '1') { exit(0); }
	if (get_ini_opt('cron','mail-quota-web') === '0') { exit(0); }

	check_live();

### read configuration options

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

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

	$perc='91';

### Collect FTP accounts

	$sql="	SELECT
			`client`.`name` AS `login`,
			`client`.`id` AS `cliid`,
			`client`.`email` AS `clientmail`,
			`client`.`node` AS `node`,
			`client`.`quota` AS `quota`,
			IFNULL(`stats_ftp`.`usage`, 0) AS `ftp_data`,
			(SUM(IFNULL(stats_mysql.data, 0)+IFNULL(stats_mysql.idx,0))) AS `mysql_data`

		FROM `client`
		LEFT JOIN `stats_ftp` ON `client`.`id`=`stats_ftp`.`clientid`
		LEFT JOIN `stats_mysql` ON `client`.`id`=`stats_mysql`.`clientid`

		WHERE `client`.`active`=1
		AND `stats_ftp`.`ftpid` IS NULL

		GROUP BY `client`.`id`

		HAVING ((`ftp_data` + `mysql_data`)/`quota`*100) > ".$perc."
		;";


	$res=DBquery($sql);

	$client_list=array();

	while ($row=$res->fetch_assoc()) {

		$usage=intval($row['ftp_data'])+intval($row['mysql_data']);
		$percent=ceil(($usage/intval($row['quota']))*100);

		$mail_subject='Webtárhely '.$percent.'% felett ('.$row['login'].')';

		$sendbody=str_replace('#LOGIN#', $row['login'], $msgbody);
		$sendbody=str_replace('#QUOTA#', $row['quota'], $sendbody);
		$sendbody=str_replace('#USAGE#', $usage, $sendbody);
		$sendbody=str_replace('#USAGE_FTP#', $row['ftp_data'], $sendbody);
		$sendbody=str_replace('#USAGE_MYSQL#', $row['mysql_data'], $sendbody);
		$sendbody=str_replace('#USAGEP#', $percent, $sendbody);

#		echo "***\n$row[clientmail] - $mail_subject\n";
#		echo "$sendbody";
		mailsend($mail_fromname, $mail_fromaddr, $row['clientmail'], $mail_subject, $sendbody);
		sleep(1);

	}

	DBclose();
