Файл: cron.php
Строк: 1796
<?
$full_home_path = dirname(__FILE__);
require_once($full_home_path.'/_rootload.php');
mconnect();
EnableLanguages(1);
if (!GetCurrentCurrency()) { print $_lang[ErrorGetCurrentCurrency]; mclose(); exit; }
@set_time_limit(0);
$company_name=GetSetting('company_name');
$company_url=GetSetting('company_url');
$billing_url=GetSetting('billing_url');
$support_url=GetSetting('support_url');
$manager_email=GetSetting('manager_email');
$cronAutoSuspend = GetSetting('cronAutoSuspend');
$cronAutoSuspendDay = GetSetting('cronAutoSuspendDay');
$cronSendAdminEndOrder = GetSetting('cronSendAdminEndOrder');
$cronSendClientBillRemind = GetSetting('cronSendClientBillRemind');
$cronSendClientBillRemindDays = GetSetting('cronSendClientBillRemindDays');
$cronSendClientEndOrderRemind = GetSetting('cronSendClientEndOrderRemind');
$cronSendClientEndOrderRemindDays = GetSetting('cronSendClientEndOrderRemindDays');
$cronSendClientEndOrderDomainRemind = GetSetting('cronSendClientEndOrderDomainRemind');
$cronSendClientEndOrderDomainRemindDays = GetSetting('cronSendClientEndOrderDomainRemindDays');
$cronDeleteBill = GetSetting('cronDeleteBill');
$cronDeleteBillDay = GetSetting('cronDeleteBillDay');
$cronDeleteNeobrabOrdersWithoutBills = GetSetting('cronDeleteNeobrabOrdersWithoutBills');
$cronDeleteNeobrabOrdersDomainsWithoutBills = GetSetting('cronDeleteNeobrabOrdersDomainsWithoutBills');
$cronDeleteOrder = GetSetting('cronDeleteOrder');
$cronDeleteOrderDay = GetSetting('cronDeleteOrderDay');
$cronAutoDelete = GetSetting('cronAutoDelete');
$cronDeleteOrderDomain = GetSetting('cronDeleteOrderDomain');
$cronDeleteOrderDomainDay = GetSetting('cronDeleteOrderDomainDay');
$cronCloseTickets = GetSetting('cronCloseTickets');
$cronCloseTicketsDay = GetSetting('cronCloseTicketsDay');
$cronDeleteTickets = GetSetting('cronDeleteTickets');
$cronDeleteTicketsDay = GetSetting('cronDeleteTicketsDay');
$cronDeleteUserLogs = GetSetting('cronDeleteUserLogs');
$cronDeleteUserLogsDay = GetSetting('cronDeleteUserLogsDay');
$cronDeleteAdminLogs = GetSetting('cronDeleteAdminLogs');
$cronDeleteAdminLogsDay = GetSetting('cronDeleteAdminLogsDay');
$cronSendClientEndOrderShopRemind = GetSetting('cronSendClientEndOrderShopRemind');
$cronSendClientEndOrderShopRemindDays = GetSetting('cronSendClientEndOrderShopRemindDays');
$cronDeleteNeobrabOrdersShopWithoutBills = GetSetting('cronDeleteNeobrabOrdersShopWithoutBills');
$cronDeleteOrderShop = GetSetting('cronDeleteOrderShop');
$cronDeleteOrderShopDay = GetSetting('cronDeleteOrderShopDay');
$cronSendClientEndTestRemind = GetSetting('cronSendClientEndTestRemind');
$cronSendClientEndTestRemindDays = GetSetting('cronSendClientEndTestRemindDays');
$autoRenewEnable=GetSetting("autoRenewEnable");
$autoRenewClientChange=GetSetting("autoRenewClientChange");
$autoRenewDay=GetSetting("autoRenewDay");
$autoRenewDomainDay=GetSetting("autoRenewDomainDay");
$autoRenewShopDay=GetSetting("autoRenewShopDay");
$attachPDFtoBill = GetSetting("attachPDFtoBill");
$cronSendClientEndTestRemind = GetSetting('cronSendClientEndTestRemind');
$cronSendClientEndTestRemindDays = GetSetting('cronSendClientEndTestRemindDays');
$cronAutoDeleteTest = GetSetting('cronAutoDeleteTest');
$smsGateway = GetSetting("smsGateway");
$smsUserBillRemind = GetSetting("smsUserBillRemind");
$smsUserBillRemindDay = GetSetting("smsUserBillRemindDay");
$smsUserOrderRemind = GetSetting("smsUserOrderRemind");
$smsUserOrderRemindDay = GetSetting("smsUserOrderRemindDay");
$smsUserOrderDomainRemind = GetSetting("smsUserOrderDomainRemind");
$smsUserOrderDomainRemindDay = GetSetting("smsUserOrderDomainRemindDay");
$smsUserOrderShopRemind = GetSetting("smsUserOrderShopRemind");
$smsUserOrderShopRemindDay = GetSetting("smsUserOrderShopRemindDay");
$smsUserOrderSuspend = GetSetting("smsUserOrderSuspend");
# Закрываем открытые тикеты
if ($cronCloseTickets and intval($cronCloseTicketsDay) > 0) {
$error = "";
$tickets=@mysql_query("select * from tickets where parentid=0 and status='open' and NOT(userid=0)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($tickets) > 0) {
while ($ticket = mysql_fetch_object($tickets)) {
$last = @mysql_query("select *,TO_DAYS(NOW())-TO_DAYS(dt) as days from tickets where id=$ticket->id OR parentid=$ticket->id order by dt desc LIMIT 0,1") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$last = mysql_fetch_object($last);
if ($last->days >= $cronCloseTicketsDay) {
$user = GetUserById($ticket->userid);
$varLng = LoadLanguageToVariable($user->lang);
@mysql_query("update tickets set status='closed' where id='$ticket->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("insert into tickets (parentid,dt,message) values('$ticket->id',NOW(),'".htmlEncode($varLng[TicketsClosedByCron])."')") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
}
}
# Удаляем закрытые тикеты
if ($cronDeleteTickets and intval($cronDeleteTicketsDay) > 0) {
$error = "";
$tickets=@mysql_query("select * from tickets where parentid=0 and status='closed'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($tickets) > 0) {
while ($ticket = mysql_fetch_object($tickets)) {
$last = @mysql_query("select *,TO_DAYS(NOW())-TO_DAYS(dt) as days from tickets where id=$ticket->id OR parentid=$ticket->id order by dt desc LIMIT 0,1") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$last = mysql_fetch_object($last);
if ($last->days >= $cronDeleteTicketsDay) {
@mysql_query("delete from tickets where id='$ticket->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("delete from tickets where parentid='$ticket->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
}
}
# Удаляем логи клиентов
if ($cronDeleteUserLogs and intval($cronDeleteUserLogsDay) > 0) {
$error = "";
@mysql_query("delete from users_logs where TO_DAYS(NOW())-TO_DAYS(dt) >= $cronDeleteUserLogsDay") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
# Удаляем логи админов
if ($cronDeleteAdminLogs and intval($cronDeleteAdminLogsDay) > 0) {
$error = "";
@mysql_query("delete from admin_logs where TO_DAYS(NOW())-TO_DAYS(dt) >= $cronDeleteAdminLogsDay") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
# Уведомление менеджеру об окончании оплаченно периода (домен) у клиента
if ($cronSendAdminEndOrder) {
$error = "";
$orders = @mysql_query("select * from orders_domains where startdate <> '0000-00-00' AND TO_DAYS(todate)-TO_DAYS(NOW())=-1") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
if ($order->status == "1") {
$registrator = GetRegistratorById($order->autoregby);
if ($registrator->type == "hostmasterepp" or $registrator->type == "nicdpua") {
if (suspendDomain($order->id, 1, 1)) {
@mysql_query("update orders_domains set status='2' where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$error = $error . "+ домен $order->domain успешно остановлен у регистратора.rn";
} else {
$error = $error . "- домен $order->domain не остановлен у регистратора. Сделайте это вручную.rn";
}
}
}
$template="У клиента $user->login закончился оплаченный период по домену $order->domain.rnrn--rnRootPanel";
$subject="Уведомление об окончании оплаченного периода (домен)";
$admEmails=GetAdminEmailsWhereTrueParam("sendremind");
if (count($admEmails) > 0) {
WriteMailLog($subject,$template);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$template);
}
}
}
if ($error) {
$errormsg = $error."rnrnВнимание! Домены, не остановленные автоматически у регистратора, необходимо остановить вручную.";
$subject = "Cron: отчет об остановке доменов (окончание оплаченного периода)";
$admEmails=GetAdminEmailsWhereTrueParam("sendcron");
if (count($admEmails) > 0) {
WriteMailLog($subject,$errormsg);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$errormsg);
}
}
}
# Уведомление менеджеру об окончании оплаченно периода (товар) у клиента
if ($cronSendAdminEndOrder) {
$error = "";
$orders = @mysql_query("select * from orders_shop where startdate <> '0000-00-00' AND NOT(todate='0000-00-00') AND TO_DAYS(todate)-TO_DAYS(NOW())=0") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$shopItem = GetShopItemById($order->item);
if ($shopItem->costtype != "one") {
if ($shopItem->type == "avdesk" or $shopItem->type == "avdesk6" or $shopItem->type == "ispmanagerlite" or $shopItem->type == "ispmanagerlitefull" or $shopItem->type == "ispmanagerlitetrial" or $shopItem->type == "ispmanagerpro" or $shopItem->type == "ispmanagerprofull" or $shopItem->type == "ispmanagerprotrial" or $shopItem->type == "vdsmanagerlinux" or $shopItem->type == "vdsmanagerlinuxfull" or $shopItem->type == "vdsmanagerfreebsd" or $shopItem->type == "vdsmanagerfreebsdfull" or $shopItem->type == "billmanagerstandart" or $shopItem->type == "billmanageradvanced" or $shopItem->type == "billmanagercorporate" or $shopItem->type == "dsmanager" or $shopItem->type == "dsmanagerfull" or $shopItem->type == "dnsmanagerfull" or $shopItem->type == "ipmanagerfull") {
@mysql_query("update orders_shop set status='2' where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
$template="У клиента $user->login закончился оплаченный период по товару $shopItem->name.rnrn--rnRootPanel";
$subject="Уведомление об окончании оплаченного периода (товар)";
$admEmails=GetAdminEmailsWhereTrueParam("sendremind");
if (count($admEmails) > 0) {
WriteMailLog($subject,$template);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$template);
}
}
}
}
# Напоминаем о неоплаченных счетах
if ($cronSendClientBillRemind) {
$error = "";
$days = @mb_split(',',$cronSendClientBillRemindDays);
$daysQuery = array();
if (count($days) > 0) {
while (list($index,$value) = each($days)) {
if (intval($value) > 0) {
$daysQuery[] = '(TO_DAYS(NOW())-TO_DAYS(created)='.intval($value).')';
}
}
}
if (count($daysQuery) > 0) {
$queryAddon = @join(' OR ',$daysQuery);
$bills = @mysql_query("select * from bills where payed='0000-00-00' AND status='0' AND ($queryAddon)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bills) > 0) {
while ($bill = mysql_fetch_object($bills)) {
$user = GetUserById($bill->uid);
$tpl=GetTpl('remind_notpayed_bill',$user->lang);
$subject=$tpl[subject]; $template=$tpl[template];
if ($subject and $template) {
$curr = LoadCurrencyToVariable($user->currency);
$subject = str_replace('{id}',sprintf("%04d", $bill->id),$subject);
$subject = str_replace('{date}',mydate($bill->created),$subject);
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{bill_date}',mydate($bill->created),$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{schet}',sprintf("%04d", $bill->id),$template);
$template = str_replace('{hostcost}',round($bill->money_host*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{domaincost}',round($bill->money_domain*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{addonscost}',round($bill->money_addons*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{shopcost}',round($bill->money_shop*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{cost}',round(($bill->money_host+$bill->money_domain+$bill->money_addons+$bill->money_shop+$bill->money)*$curr["CURK"],2)." ".$curr["CURS"],$template);
$subject = str_replace('{login}',$user->login,$subject);
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
}
}
}
}
}
# Напоминаем о неоплаченных счетах (SMS)
if ($smsGateway and $smsUserBillRemind and intval($smsUserBillRemindDay) > 0) {
$bills = @mysql_query("select * from bills where payed='0000-00-00' AND status='0' AND TO_DAYS(NOW())-TO_DAYS(created)='".intval($smsUserBillRemindDay)."'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bills) > 0) {
while ($bill = mysql_fetch_object($bills)) {
$user = GetUserById($bill->uid);
$tpl=GetTpl('remind_notpayed_bill_sms',$user->lang);
$template=$tpl[template];
if ($template and $user->mobile and $user->smsUserBillRemind) {
$curr = LoadCurrencyToVariable($user->currency);
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{bill_date}',mydate($bill->created),$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{schet}',sprintf("%04d", $bill->id),$template);
$template = str_replace('{hostcost}',round($bill->money_host*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{domaincost}',round($bill->money_domain*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{addonscost}',round($bill->money_addons*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{shopcost}',round($bill->money_shop*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{cost}',round(($bill->money_host+$bill->money_domain+$bill->money_addons+$bill->money_shop+$bill->money)*$curr["CURK"],2)." ".$curr["CURS"],$template);
sendSMS($user->id,'',$template);
}
}
}
}
# Напоминаем об окончании оплаченного периода
if ($cronSendClientEndOrderRemind) {
$error = "";
$days = @mb_split(',',$cronSendClientEndOrderRemindDays);
$daysQuery = array();
if (count($days) > 0) {
while (list($index,$value) = each($days)) {
if (intval($value) > 0) {
$daysQuery[] = '(TO_DAYS(todate)-TO_DAYS(NOW())='.intval($value).')';
}
}
}
if (count($daysQuery) > 0) {
$queryAddon = @join(' OR ',$daysQuery);
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where archived=0 and startdate <> '0000-00-00' AND ($queryAddon)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tarif = GetTarifById($order->tarif);
$tpl=GetTpl('remind_end',$user->lang);
$subject=$tpl[subject]; $template=$tpl[template];
if ($subject and $template) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{tarif}',$tarif->name,$template);
$template = str_replace('{domain}',$order->domain,$template);
$template = str_replace('{days}',$order->leftdays,$template);
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
}
}
}
}
}
# Напоминаем об окончании оплаченного периода (SMS)
if ($smsGateway and $smsUserOrderRemind and intval($smsUserOrderRemindDay) > 0) {
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where archived=0 and startdate <> '0000-00-00' AND TO_DAYS(todate)-TO_DAYS(NOW())='".intval($smsUserOrderRemindDay)."'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tarif = GetTarifById($order->tarif);
$tpl=GetTpl('remind_end_sms',$user->lang);
$template=$tpl[template];
if ($template and $user->mobile and $user->smsUserOrderRemind) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{tarif}',$tarif->name,$template);
$template = str_replace('{domain}',$order->domain,$template);
$template = str_replace('{days}',$order->leftdays,$template);
sendSMS($user->id,'',$template);
}
}
}
}
# Напоминаем об окончании тестового периода
if ($cronSendClientEndTestRemind) {
$error = "";
$days = @mb_split(',',$cronSendClientEndTestRemindDays);
$daysQuery = array();
if (count($days) > 0) {
while (list($index,$value) = each($days)) {
if (intval($value) > 0) {
$daysQuery[] = '(TO_DAYS(todate)-TO_DAYS(NOW())='.intval($value).')';
}
}
}
if (count($daysQuery) > 0) {
$queryAddon = @join(' OR ',$daysQuery);
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where archived=0 and todate <> '0000-00-00' AND testPeriod='1' AND ($queryAddon)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tarif = GetTarifById($order->tarif);
$tpl=GetTpl('remind_end_test',$user->lang);
$subject=$tpl[subject]; $template=$tpl[template];
if ($subject and $template) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{tarif}',$tarif->name,$template);
$template = str_replace('{domain}',$order->domain,$template);
$template = str_replace('{days}',$order->leftdays,$template);
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
}
}
}
}
}
# Напоминаем об окончании оплаченного периода (домены)
if ($cronSendClientEndOrderDomainRemind) {
$error = "";
$days = @mb_split(',',$cronSendClientEndOrderDomainRemindDays);
$daysQuery = array();
if (count($days) > 0) {
while (list($index,$value) = each($days)) {
if (intval($value) > 0) {
$daysQuery[] = '(TO_DAYS(todate)-TO_DAYS(NOW())='.intval($value).')';
}
}
}
if (count($daysQuery) > 0) {
$queryAddon = @join(' OR ',$daysQuery);
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders_domains where startdate <> '0000-00-00' AND ($queryAddon)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tarif = GetTarifById($order->tarif);
$tpl=GetTpl('remind_end_domain',$user->lang);
$subject=$tpl[subject]; $template=$tpl[template];
if ($subject and $template) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{domain}',$order->domain,$template);
$template = str_replace('{days}',$order->leftdays,$template);
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
}
}
}
}
}
# Напоминаем об окончании оплаченного периода (домены) (SMS)
if ($smsGateway and $smsUserOrderDomainRemind and intval($smsUserOrderDomainRemindDay) > 0) {
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders_domains where startdate <> '0000-00-00' AND TO_DAYS(todate)-TO_DAYS(NOW())='".intval($smsUserOrderDomainRemindDay)."'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tpl=GetTpl('remind_end_domain_sms',$user->lang);
$template=$tpl[template];
if ($template and $user->mobile and $user->smsUserOrderDomainRemind) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{domain}',$order->domain,$template);
$template = str_replace('{days}',$order->leftdays,$template);
sendSMS($user->id,'',$template);
}
}
}
}
# Напоминаем об окончании оплаченного периода (товар)
if ($cronSendClientEndOrderShopRemind) {
$error = "";
$days = @mb_split(',',$cronSendClientEndOrderShopRemindDays);
$daysQuery = array();
if (count($days) > 0) {
while (list($index,$value) = each($days)) {
if (intval($value) > 0) {
$daysQuery[] = '(TO_DAYS(todate)-TO_DAYS(NOW())='.intval($value).')';
}
}
}
if (count($daysQuery) > 0) {
$queryAddon = @join(' OR ',$daysQuery);
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders_shop where startdate <> '0000-00-00' AND NOT(todate='0000-00-00') AND ($queryAddon)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$shopItem = GetShopItemById($order->item);
$tpl=GetTpl('remind_end_shop',$user->lang);
$subject=$tpl[subject]; $template=$tpl[template];
if ($subject and $template) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{item}',$shopItem->name,$template);
$template = str_replace('{days}',$order->leftdays,$template);
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
}
}
}
}
}
# Напоминаем об окончании оплаченного периода (товар) (SMS)
if ($smsGateway and $smsUserOrderShopRemind and intval($smsUserOrderShopRemindDay) > 0) {
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders_shop where startdate <> '0000-00-00' AND NOT(todate='0000-00-00') AND TO_DAYS(todate)-TO_DAYS(NOW())='".intval($smsUserOrderShopRemindDay)."'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$shopItem = GetShopItemById($order->item);
$tpl=GetTpl('remind_end_shop_sms',$user->lang);
$template=$tpl[template];
if ($template and $user->mobile and $user->smsUserOrderShopRemind) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{item}',$shopItem->name,$template);
$template = str_replace('{days}',$order->leftdays,$template);
sendSMS($user->id,'',$template);
}
}
}
}
# Удаляем неоплаченные счета, которым более 30 дней
if ($cronDeleteBill) {
$error = "";
$bills = @mysql_query("select * from bills where payed='0000-00-00' AND status='0' AND TO_DAYS(NOW())-TO_DAYS(created)>$cronDeleteBillDay") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bills) > 0) {
while ($bill = mysql_fetch_object($bills)) {
@mysql_query("delete from bills where id='$bill->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
}
# Удаляем необработанные заказы, для которых нет ни одного счёта
if ($cronDeleteNeobrabOrdersWithoutBills) {
$error = "";
$orders = @mysql_query("select * from orders where archived=0 and startdate='0000-00-00' and status='0'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$bills = @mysql_query("select * from bills where host_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bills) == 0) {
@mysql_query("delete from orders where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if ($order->domain_reg == "1" or $order->domain_reg == "3") {
$dm = GetDomainByDomain($order->domain);
@mysql_query("delete from orders_domains where host_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("delete from orders_domainscert where domain_id='$dm->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
}
}
}
# Удаляем необработанные заказы (домены), для которых нет ни одного счёта
if ($cronDeleteNeobrabOrdersDomainsWithoutBills) {
$error = "";
$orders = @mysql_query("select * from orders_domains where startdate='0000-00-00' and status='0'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$bills = @mysql_query("select * from bills where archived=0 and domain_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bills) == 0) {
@mysql_query("delete from orders_domains where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("delete from orders_domainscert where domain_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
}
}
# Удаляем необработанные заказы (товары), для которых нет ни одного счёта
if ($cronDeleteNeobrabOrdersShopWithoutBills) {
$error = "";
$orders = @mysql_query("select * from orders_shop where startdate='0000-00-00' and status='0'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$bills = @mysql_query("select * from bills where archived=0 and shop_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bills) == 0) {
@mysql_query("delete from orders_shop where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
}
}
# Отправка запроса на удаление для доменов, которые истекают через 5 дней и зарегистрированы через internetx.de, epag.net или networking4all.com
$domains = @mysql_query("select d.*,TO_DAYS(d.todate)-TO_DAYS(NOW()) as leftdays from orders_domains as d, registrators as r where NOT(d.status='0') and d.autoregby=r.id and ((d.internetxDeleted='0' and r.type='internetx') OR (d.epagExpire='0' and r.type='epag') OR (d.networking4allNoAutoRenew='0' and r.type='networking4all'))") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($domains) > 0) {
$error = "";
while ($domain = mysql_fetch_object($domains)) {
if ($domain->leftdays <= 5) {
$registrator = GetRegistratorById($domain->autoregby);
if ($registrator->type == "internetx") {
$internetx_url = $registrator->url;
$internetx_user = $registrator->text1;
$internetx_password = decodePwd($registrator->text2);
$internetx_context = $registrator->text3;
if ($internetx_url and $internetx_user and $internetx_password and $internetx_context) {
$internetx = new INTERNETX;
$internetx->init($internetx_url,$internetx_user,$internetx_password,$internetx_context);
$result = $internetx->domainCancelCreate($domain->domain, $manager_email);
if ($result) {
@mysql_query("update orders_domains set internetxDeleted='1' where id='$domain->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$error = $error . "+ заявка для $domain->domain успешно выполненаrn";
} else {
$error = $error . "- ошибка: " . $internetx->error."rn";
}
} else {
$error = $error . "- ошибка: " . $_lang[DomainsErrorNoLoginForReg]." $registrator->namern";
}
}
else if ($registrator->type == "epag") {
$epag_url = $registrator->url;
$epag_port = $registrator->port;
$epag_user = $registrator->text1;
$epag_password = decodePwd($registrator->text2);
$epag_customerid = $registrator->text3;
if ($epag_url and $epag_user and $epag_password and $epag_customerid) {
$epag = new EPAG;
$epag->init($epag_url,$epag_port,$epag_user,$epag_password,$epag_customerid);
$result = $epag->expire($domain->domain);
if ($result) {
@mysql_query("update orders_domains set epagExpire='1' where id='$domain->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$error = $error . "+ заявка для $domain->domain успешно выполненаrn";
} else {
$error = $error . "- ошибка: " . $epag->error."rn";
}
} else {
$error = $error . "- ошибка: " . $_lang[DomainsErrorNoLoginForReg]." $registrator->namern";
}
}
else if ($registrator->type == "networking4all") {
$n4all_url = $registrator->url;
$n4all_user = $registrator->text1;
$n4all_password = decodePwd($registrator->text2);
$n4all_handle = $registrator->text3;
if ($n4all_url and $n4all_user and $n4all_password and $n4all_handle) {
$n4all = new NETWORKING4ALL;
$n4all->init($n4all_url,$n4all_user,$n4all_password,$n4all_handle);
$result = $n4all->disableAutoRenew($domain->domain);
if ($result) {
@mysql_query("update orders_domains set networking4allNoAutoRenew='1' where id='$domain->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$error = $error . "+ заявка для $domain->domain успешно выполненаrn";
} else {
$error = $error . "- ошибка: " . $n4all->error."rn";
}
} else {
$error = $error . "- ошибка: " . $_lang[DomainsErrorNoLoginForReg]." $registrator->namern";
}
}
}
}
if ($error) {
$errormsg = $error."rnrnВнимание! Домены, для которых автоматически не создана заявка на удаление либо отмену продления, необходимо обработать вручную и установить значение 1 в поле internetxDeleted, epagExpire или networking4allNoAutoRenew в редактировании заказа на домен в биллинге, иначе они будут автоматически продлены.";
$subject = "Cron: отчет об отправке заявки на удаление/отмену продления доменов истекающих через 5 дней";
$admEmails=GetAdminEmailsWhereTrueParam("sendcron");
if (count($admEmails) > 0) {
WriteMailLog($subject,$errormsg);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$errormsg);
}
}
}
# Уведомление менеджеру об окончании оплаченно периода у клиента
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where archived=0 and startdate <> '0000-00-00' AND TO_DAYS(todate)-TO_DAYS(NOW())<=-1") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
print "<BR><B>Suspend expired accounts... </b>";
if (mysql_num_rows($orders) > 0) {
$error = "";
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tarif = GetTarifById($order->tarif);
$server = GetServers($order->serverid);
print "<BR>ID $order->id, $order->serverlogin [$order->leftdays] [$order->domain] [$server->name]... ";
if ($cronSendAdminEndOrder and $order->leftdays == "-1" and $order->status == "1") {
print "send expiration notify to manager, ";
$template="У клиента $user->login закончился оплаченный период по тарифному плану $tarif->name для домена $order->domain.rnrn--rnRootPanel";
$subject="Уведомление об окончании оплаченного периода";
$admEmails=GetAdminEmailsWhereTrueParam("sendremind");
if (count($admEmails) > 0) {
WriteMailLog($subject,$template);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$template);
}
}
if ($order->status == "1" and $order->leftdays <= $cronAutoSuspendDay) {
if ($order->serverlogin and $order->serverid) {
if ($tarif->autosuspend and $cronAutoSuspend and !$order->noSuspend and !$user->noSuspend) {
if (suspendUser($order->id, 1, 1)) {
print "suspended.";
@mysql_query("update orders set status='2' where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$error = $error . "+ Аккаунт $order->serverlogin [$order->leftdays] для заказа ID #$order->id ($order->domain) автоматически остановлен на сервере ($server->name).rn";
$tpl=GetTpl('account_suspend',$user->lang);
$subject=$tpl[subject]; $template=$tpl[template];
if ($subject and $template) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{tarif}',$tarif->name,$template);
$template = str_replace('{domain}',$order->domain,$template);
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,'','',$tpl[type]);
}
$tpl=GetTpl('account_suspend_sms',$user->lang);
$template=$tpl[template];
if ($template and $user->mobile and $smsUserOrderSuspend and $user->smsUserOrderSuspend) {
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}','******',$template);
$template = str_replace('{tarif}',$tarif->name,$template);
$template = str_replace('{domain}',$order->domain,$template);
sendSMS($user->id,'',$template);
}
} else {
print "suspend error.";
$error = $error . "- Аккаунт $order->serverlogin [$order->leftdays] для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name). Сделайте это вручную.rn";
}
} else if (!$cronAutoSuspend) {
print "suspend disabled in Cron settings.";
$error = $error . "- Аккаунт $order->serverlogin [$order->leftdays] для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name), т.к. эта возможность отключена в настройках Cron'а.rn";
} else if (!$tarif->autosuspend) {
print "suspend disabled in Tarif settings.";
$error = $error . "- Аккаунт $order->serverlogin [$order->leftdays] для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name), т.к. эта возможность отключена в настройках тарифного плана.rn";
} else if ($order->noSuspend) {
print "suspend disabled in Order settings.";
$error = $error . "- Аккаунт $order->serverlogin [$order->leftdays] для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name), т.к. эта возможность отключена в настройках заказа.rn";
} else if ($user->noSuspend) {
print "suspend disabled in User settings.";
$error = $error . "- Аккаунт $order->serverlogin [$order->leftdays] для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name), т.к. эта возможность отключена в настройках пользователя.rn";
}
} else {
print "suspend error (no login or server id).";
$error = $error . "- Аккаунт [$order->leftdays] для заказа ID #$order->id ($order->domain) не остановлен автоматически, т.к. не указан логин на сервере либо не указан сервер.rn";
}
} else { print "already suspended.";}
}
if ($error) {
$errormsg = $error."rnrnВнимание! Аккаунты, не остановленные автоматически на сервере, необходимо остановить вручную.";
$subject = "Cron: отчет об остановке аккаунтов (окончание оплаченного периода)";
$admEmails=GetAdminEmailsWhereTrueParam("sendcron");
if (count($admEmails) > 0) {
WriteMailLog($subject,$errormsg);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$errormsg);
}
}
print "<BR><B>...end</b>";
} else { print "<B>no expired accounts.</b>"; }
# Автоматически продляем заказы на хостинг/реселлинг/сервера
if ($autoRenewEnable) {
$orders = @mysql_query("select o.*,TO_DAYS(o.todate)-TO_DAYS(NOW()) as leftdays from orders as o, users as u where o.archived=0 and o.status = '1' AND o.startdate <> '0000-00-00' AND TO_DAYS(o.todate)-TO_DAYS(NOW()) = $autoRenewDay AND u.autoRenew <> '2' AND o.uid=u.id") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
else {
$orders = @mysql_query("select o.*,TO_DAYS(o.todate)-TO_DAYS(NOW()) as leftdays from orders as o, users as u where o.archived=0 and o.status = '1' AND o.startdate <> '0000-00-00' AND TO_DAYS(o.todate)-TO_DAYS(NOW()) = $autoRenewDay AND u.autoRenew = '1' AND o.uid=u.id") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
if (@mysql_num_rows($orders) > 0) {
$error = "";
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tarif=GetTarifById($order->tarif);
if ($user->id) {
$billn=@mysql_query("select * from bills where status=0 and newtarif='0' and NOT(host_srok='0') and newaddons='' and host_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>Function: ".__FUNCTION__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($billn) == 0) {
$bill=@mysql_query("select host_srok from bills where status=1 and newtarif='0' and NOT(host_srok='0') and newaddons='' and host_id='$order->id' order by id desc LIMIT 0,1") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>Function: ".__FUNCTION__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bill) > 0) {
$bill=mysql_fetch_object($bill);
$tsroki=@mysql_query("select months,discount from tarifs_sroki where tarif_id='$order->tarif' and months='$bill->host_srok' and renew='1'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>Function: ".__FUNCTION__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($tsroki) > 0) {
$tsroki=@mysql_fetch_object($tsroki);
$hostMonths = $tsroki->months;
$srokDiscount = $tsroki->discount;
}
}
if (!$hostMonths) {
$tsroki=@mysql_query("select months,discount from tarifs_sroki where tarif_id='$order->tarif' and renew='1' order by months LIMIT 0,1") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>Function: ".__FUNCTION__."<BR>MySQL Error: ".mysql_error());
$tsroki=@mysql_fetch_object($tsroki);
$hostMonths = $tsroki->months;
$srokDiscount = $tsroki->discount;
}
if ($hostMonths) {
$userLang = LoadLanguageToVariable($user->lang);
$orderAddons=mb_split(":x:", $order->addons);
$addonsCost=0;
$addonsToSave="";
$addonsToSaveText="";
while (list($k,$v) = @each($orderAddons)) {
if ($v) {
$oneAddon = GetAddonById($v);
if ($oneAddon->id) {
$addonSpecCost = GetSpecialCost($user->id,"addon",$oneAddon->id);
if ($addonsToSaveText) {
$addonsToSaveText = $addonsToSaveText.", ".$oneAddon->name;
} else {
$addonsToSaveText = $oneAddon->name;
}
if ($addonSpecCost) {
$addonsCost += $addonSpecCost["cost2"]*$hostMonths;
} else {
$oneAddon->cost_monthly = $oneAddon->cost_monthly / GetCurrencyKoeficientByCode($oneAddon->cost_monthlyCurrency);
$addonsCost += $oneAddon->cost_monthly*$hostMonths;
}
}
}
}
if (!$addonsToSaveText) { $addonsToSaveText=$userLang[No]; }
$addonsCost=round($addonsCost,2);
if ($order->costId) {
$tc = GetTarifsCostById($order->costId);
$hostCost = $tc->cost / GetCurrencyKoeficientByCode($tc->costCurrency);
$hostCost = $hostCost * $hostMonths;
} else {
$tarifSpecCost = GetSpecialCost($user->id,"tarif",$tarif->id);
if ($tarifSpecCost) {
$hostCost=$tarifSpecCost["cost2"]*$hostMonths;
} else {
$tarif->cost = $tarif->cost / GetCurrencyKoeficientByCode($tarif->costCurrency);
$hostCost=$tarif->cost*$hostMonths;
}
}
if ($tarif->enableSlots and $order->slots > 0) {
$hostCost = $hostCost*$order->slots;
}
if ($order->serverid) {
$srv = GetServers($order->serverid);
if ($srv->nacenka) { $srvNacenka = $srv->nacenka; }
}
if ($srvNacenka) {
$hostCost=$hostCost+($hostCost/100)*$srvNacenka;
}
$orderDiscount=$order->discount;
$host=$hostCost-($hostCost/100)*($srokDiscount+$orderDiscount);
if ($orderDiscount == '100') {$host = 0;}
$host=round($host,2);
$history = "Тариф: <B>$tarif->name</B>, $hostMonths мес.";
if ($addonsToSaveText and $addonsToSaveText != $userLang[No]) { $history .= " + $addonsToSaveText"; }
@mysql_query("insert into bills (uid,tarif,host_id,host_srok,money_host,money_addons,created,renew,history) values('$user->id','$tarif->id','$order->id','$hostMonths','$host','$addonsCost',NOW(),'1','$history')") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$bill_id=mysql_insert_id();
$sid=sprintf("%04d", $bill_id);
$tpl=GetTpl("email_touser_".$tarif->vid."_renew", $user->lang);
$subject = $tpl[subject]; $template = $tpl[template];
addUserLog($user->id, "renew", "[auto] $tarif->name, $hostMonths ".$userLang[OrderSokraschenieMonth].", $order->domain [".$userLang[DomainWithoutRenew]."]");
if ($subject and $template) {
if (($attachPDFtoBill and $user->attachPDFtoBill != "2") or (!$attachPDFtoBill and $user->attachPDFtoBill == "1")) {
$profile=GetUserProfileByUserId($user->id);
if ($profile->org == "3" and $profile->firma and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
$attachFile2 = "";
} else if ($profile->org == "2" and $profile->name and $profile->surname and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
$attachFile2 = "";
} else if ($profile->org == "1") {
$attachFile = createKvitanciya('', $bill_id, 2);
if ($profile->name and $profile->surname and $profile->phone) {
$attachFile2 = createFaktura('', $bill_id, 2);
}
}
if (!$attachFile) {$attachFile="";}
if (!$attachFile2) {$attachFile2="";}
}
$curr = LoadCurrencyToVariable($user->currency);
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{tarif}',$tarif->name,$template);
$template = str_replace('{srok}',$hostMonths,$template);
$template = str_replace('{domain}',$order->domain,$template);
$template = str_replace('{addons}',$addonsToSaveText,$template);
$template = str_replace('{newreg}',$userLang[DomainWithoutRenew],$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}',"******",$template);
$template = str_replace('{schet}',$sid,$template);
$template = str_replace('{hostcost}',round($host*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{domaincost}',"0 ".$curr["CURS"],$template);
$template = str_replace('{addonscost}',round($addonsCost*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{cost}',round(($host+$addonsCost)*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{userid}',$user->id,$template);
$subject = "[auto] ".$subject;
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,$attachFile,$attachFile2,$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,$attachFile,$attachFile2,$tpl[type]);
$admEmails=GetAdminEmailsWhereTrueParam("sendneworder");
if (count($admEmails) > 0) {
WriteMailLog("Duplicate: ".$subject,$template);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,"Duplicate: ".$subject,$template,$attachFile,$attachFile2,$tpl[type]);
}
@unlink($attachFile);
@unlink($attachFile2);
}
$moneyTotal = $host+$addonsCost;
if ($user->money >= $moneyTotal) {
$error .= "+ Заказ ID # $order->id, $tarif->name, $order->domain продлен и оплачен автоматическиrn";
@mysql_query("update users set money=money-$moneyTotal where id='$user->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
MakeBillPayed($bill_id, 1, "[auto] ".$userLang[payBalance]);
} else {
$error .= "+ Заказ ID # $order->id, $tarif->name, $order->domain продлен автоматически, но не оплаченrn";
}
}
else { $error .= "- Заказ ID # $order->id, $tarif->name, $order->domain не продлен автоматически, т.к. не удалось получить срок заказаrn"; }
}
else { $error .= "- Заказ ID # $order->id, $tarif->name, $order->domain не продлен автоматически, т.к. для него есть не оплаченный счетrn"; }
}
else {$error .= "- Заказ ID # $order->id, $tarif->name, $order->domain не продлен, т.к. не найден пользователь ID # $order->uidrn"; }
}
if ($error) {
$errormsg = $error;
$subject = "Cron: отчет об автоматическом продлении заказов";
$admEmails=GetAdminEmailsWhereTrueParam("sendcron");
if (count($admEmails) > 0) {
WriteMailLog($subject,$errormsg);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$errormsg);
}
}
}
# Автоматически продляем заказы на домены
if ($autoRenewEnable) {
$orders = @mysql_query("select o.*,TO_DAYS(o.todate)-TO_DAYS(NOW()) as leftdays from orders_domains as o, users as u where o.status = '1' AND o.startdate <> '0000-00-00' AND TO_DAYS(o.todate)-TO_DAYS(NOW()) = $autoRenewDomainDay AND u.autoRenew <> '2' AND o.uid=u.id") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
else {
$orders = @mysql_query("select o.*,TO_DAYS(o.todate)-TO_DAYS(NOW()) as leftdays from orders_domains as o, users as u where o.status = '1' AND o.startdate <> '0000-00-00' AND TO_DAYS(o.todate)-TO_DAYS(NOW()) = $autoRenewDomainDay AND u.autoRenew = '1' AND o.uid=u.id") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
if (@mysql_num_rows($orders) > 0) {
$error = "";
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$zone = GetZoneById($order->zone_id);
if ($user->id) {
$billn=@mysql_query("select * from bills where status=0 and domain_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>Function: ".__FUNCTION__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($billn) == 0) {
$bill=@mysql_query("select domain_srok from bills where status=1 and domain_id='$order->id' order by id desc LIMIT 0,1") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>Function: ".__FUNCTION__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bill) > 0) {
$bill=mysql_fetch_object($bill);
if ($bill->domain_srok >= $zone->minsrok_renew) {
$domainMonths = $bill->domain_srok;
}
}
if (!$domainMonths) {
$domainMonths = $zone->minsrok_renew;
}
if ($domainMonths) {
$userLang = LoadLanguageToVariable($user->lang);
$domainCost = GetDomainCostRenewForUserByZoneId($user->id,$zone->id);
$domainCost=$domainCost * ($domainMonths/12);
$domainDiscount = $order->discount;
$domainCost = $domainCost - ($domainCost/100)*$domainDiscount;
$history = "Домен: <B>$order->domain</B>, ".($domainMonths/12)." г.";
@mysql_query("insert into bills (uid,domain_id,domain_srok,money_domain,created,renew,history) values('$user->id','$order->id','$domainMonths','$domainCost',NOW(),'1','$history')") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$bill_id=mysql_insert_id();
$sid=sprintf("%04d", $bill_id);
addUserLog($user->id, "renewdomain", "[auto] $order->domain, ".($domainMonths/12)." ".$userLang[OrderSokraschenieGod]);
$tpl=GetTpl('email_touser_domain_renew', $user->lang);
$subject = $tpl[subject]; $template = $tpl[template];
if ($subject and $template) {
if (($attachPDFtoBill and $user->attachPDFtoBill != "2") or (!$attachPDFtoBill and $user->attachPDFtoBill == "1")) {
$profile=GetUserProfileByUserId($user->id);
if ($profile->org == "3" and $profile->firma and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
$attachFile2 = "";
} else if ($profile->org == "2" and $profile->name and $profile->surname and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
$attachFile2 = "";
} else if ($profile->org == "1") {
$attachFile = createKvitanciya('', $bill_id, 2);
if ($profile->name and $profile->surname and $profile->phone) {
$attachFile2 = createFaktura('', $bill_id, 2);
}
}
if (!$attachFile) {$attachFile="";}
if (!$attachFile2) {$attachFile2="";}
}
$curr = LoadCurrencyToVariable($user->currency);
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{domain}',$order->domain,$template);
$template = str_replace('{srok}',($domainMonths/12),$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}',"******",$template);
$template = str_replace('{schet}',$sid,$template);
$template = str_replace('{domaincost}',round($domainCost*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{cost}',round($domainCost*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{userid}',$user->id,$template);
$subject = "[auto] ".$subject;
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,$attachFile,$attachFile2,$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,$attachFile,$attachFile2,$tpl[type]);
$admEmails=GetAdminEmailsWhereTrueParam("sendneworder");
if (count($admEmails) > 0) {
WriteMailLog("Duplicate: ".$subject,$template);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,"Duplicate: ".$subject,$template,$attachFile,$tpl[type]);
}
@unlink($attachFile);
@unlink($attachFile2);
}
$moneyTotal = $domainCost;
if ($user->money >= $moneyTotal) {
$error .= "+ Заказ на домен ID # $order->id, $order->domain продлен и оплачен автоматическиrn";
@mysql_query("update users set money=money-$moneyTotal where id='$user->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
MakeBillPayed($bill_id, 1, "[auto] ".$userLang[payBalance]);
} else {
$error .= "+ Заказ на домен ID # $order->id, $order->domain продлен автоматически, но не оплаченrn";
}
}
else { $error .= "- Заказ на домен ID # $order->id, $order->domain не продлен автоматически, т.к. не удалось получить срок заказаrn"; }
}
else { $error .= "- Заказ на домен ID # $order->id, $order->domain не продлен автоматически, т.к. для него есть не оплаченный счетrn"; }
}
else {$error .= "- Заказ на домен ID # $order->id, $order->domain не продлен, т.к. не найден пользователь ID # $order->uidrn"; }
}
if ($error) {
$errormsg = $error;
$subject = "Cron: отчет об автоматическом продлении заказов (домены)";
$admEmails=GetAdminEmailsWhereTrueParam("sendcron");
if (count($admEmails) > 0) {
WriteMailLog($subject,$errormsg);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$errormsg);
}
}
}
# Автоматически продляем заказы на товары/услуги
if ($autoRenewEnable) {
$orders = @mysql_query("select o.*,TO_DAYS(o.todate)-TO_DAYS(NOW()) as leftdays from orders_shop as o, users as u where o.status = '1' AND o.startdate <> '0000-00-00' AND o.todate <> '0000-00-00' AND TO_DAYS(o.todate)-TO_DAYS(NOW()) = $autoRenewShopDay AND u.autoRenew <> '2' AND o.uid=u.id") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
else {
$orders = @mysql_query("select o.*,TO_DAYS(o.todate)-TO_DAYS(NOW()) as leftdays from orders_shop as o, users as u where o.status = '1' AND o.startdate <> '0000-00-00' AND o.todate <> '0000-00-00' AND TO_DAYS(o.todate)-TO_DAYS(NOW()) = $autoRenewShopDay AND u.autoRenew = '1' AND o.uid=u.id") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
if (@mysql_num_rows($orders) > 0) {
$error = "";
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$shopItem = GetShopItemById($order->item);
if ($user->id) {
$billn=@mysql_query("select * from bills where status=0 and shop_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>Function: ".__FUNCTION__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($billn) == 0) {
$bill=@mysql_query("select shop_srok from bills where status=1 and shop_id='$order->id' order by id desc LIMIT 0,1") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>Function: ".__FUNCTION__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($bill) > 0) {
$bill=mysql_fetch_object($bill);
if ($bill->shop_srok >= $shopItem->minsrok and $bill->shop_srok <= $shopItem->maxsrok) {
$shopMonths = $bill->shop_srok;
}
}
if (!$shopMonths) {
$shopMonths = $shopItem->minsrok;
}
if ($shopMonths) {
$userLang = LoadLanguageToVariable($user->lang);
$shopCost = $shopItem->cost;
$shopSpecCost = GetSpecialCost($user->id,"shop",$shopItem->id);
if ($shopSpecCost) {
$shopCost = $shopSpecCost["cost1"];
}
if ($shopItem->costtype == "month") { $shopCost=$shopCost * $shopMonths; }
else if ($shopItem->costtype == "year") { $shopCost=$shopCost * ($shopMonths/12); }
$shopDiscount = $order->discount;
$shopCost = $shopCost - ($shopCost/100)*$shopDiscount;
$history = "Товар: <B>$shopItem->name</B>";
if ($shopItem->costtype == "month") { $history .= ", $shopMonths мес."; }
else if ($shopItem->costtype == "year") { $history .= ", ".($shopMonths/12)." г."; }
@mysql_query("insert into bills (uid,shop_id,shop_srok,money_shop,created,renew,history) values('$user->id','$order->id','$shopMonths','$shopCost',NOW(),'1','$history')") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$bill_id=mysql_insert_id();
$sid=sprintf("%04d", $bill_id);
addUserLog($user->id, "renewshop", "[auto] $shopItem->name, ".$shopMonths." ".$userLang[OrderSokraschenieMonth]);
$tpl=GetTpl('email_touser_shop_renew', $user->lang);
$subject = $tpl[subject]; $template = $tpl[template];
if ($subject and $template) {
if (($attachPDFtoBill and $user->attachPDFtoBill != "2") or (!$attachPDFtoBill and $user->attachPDFtoBill == "1")) {
$profile=GetUserProfileByUserId($user->id);
if ($profile->org == "3" and $profile->firma and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
$attachFile2 = "";
} else if ($profile->org == "2" and $profile->name and $profile->surname and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
$attachFile2 = "";
} else if ($profile->org == "1") {
$attachFile = createKvitanciya('', $bill_id, 2);
if ($profile->name and $profile->surname and $profile->phone) {
$attachFile2 = createFaktura('', $bill_id, 2);
}
}
if (!$attachFile) {$attachFile="";}
if (!$attachFile2) {$attachFile2="";}
}
$curr = LoadCurrencyToVariable($user->currency);
$template = str_replace('{company_name}',$company_name,$template);
$template = str_replace('{company_url}',$company_url,$template);
$template = str_replace('{billing_url}',$billing_url,$template);
$template = str_replace('{support_url}',$support_url,$template);
$template = str_replace('{item}',$shopItem->name,$template);
$template = str_replace('{srok}',$shopMonths,$template);
$template = str_replace('{login}',$user->login,$template);
$template = str_replace('{password}',"******",$template);
$template = str_replace('{schet}',$sid,$template);
$template = str_replace('{itemcost}',round($shopCost*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{cost}',round($shopCost*$curr["CURK"],2)." ".$curr["CURS"],$template);
$template = str_replace('{userid}',$user->id,$template);
$subject = "[auto] ".$subject;
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template,$attachFile,$attachFile2,$tpl[type]);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,$attachFile,$attachFile2,$tpl[type]);
$admEmails=GetAdminEmailsWhereTrueParam("sendneworder");
if (count($admEmails) > 0) {
WriteMailLog("Duplicate: ".$subject,$template);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,"Duplicate: ".$subject,$template,$attachFile,$attachFile2,$tpl[type]);
}
@unlink($attachFile);
@unlink($attachFile2);
}
$moneyTotal = $shopCost;
if ($user->money >= $moneyTotal) {
$error .= "+ Заказ на товар/услугу ID # $order->id, $shopItem->name продлен и оплачен автоматическиrn";
@mysql_query("update users set money=money-$moneyTotal where id='$user->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
MakeBillPayed($bill_id, 1, "[auto] ".$userLang[payBalance]);
} else {
$error .= "+ Заказ на товар/услугу ID # $order->id, $shopItem->name продлен автоматически, но не оплаченrn";
}
}
else { $error .= "- Заказ на товар/услугу ID # $order->id, $shopItem->name не продлен автоматически, т.к. не удалось получить срок заказаrn"; }
}
else { $error .= "- Заказ на товар услугу ID # $order->id, $shopItem->name не продлен автоматически, т.к. для него есть не оплаченный счетrn"; }
}
else {$error .= "- Заказ на товар/услугу ID # $order->id, $shopItem->name не продлен, т.к. не найден пользователь ID # $order->uidrn"; }
}
if ($error) {
$errormsg = $error;
$subject = "Cron: отчет об автоматическом продлении заказов (товары/услуги)";
$admEmails=GetAdminEmailsWhereTrueParam("sendcron");
if (count($admEmails) > 0) {
WriteMailLog($subject,$errormsg);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$errormsg);
}
}
}
mclose();
?>