Файл: billing/cron.php
Строк: 1490
<?
$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');
$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');
# Закрываем открытые тикеты
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())=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);
$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 ($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") {
@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 = @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) {
$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*CURK,2)." ".CURS,$template);
$template = str_replace('{domaincost}',round($bill->money_domain*CURK,2)." ".CURS,$template);
$template = str_replace('{addonscost}',round($bill->money_addons*CURK,2)." ".CURS,$template);
$template = str_replace('{cost}',round(($bill->money_host+$bill->money_domain+$bill->money_addons)*CURK,2)." ".CURS,$template);
WriteMailLog($subject,$template,$user->id);
sendmail($user->email,$company_name,$manager_email,$subject,$template);
sendmail($user->email2,$company_name,$manager_email,$subject,$template);
}
}
}
}
}
# Напоминаем об окончании оплаченного периода
if ($cronSendClientEndOrderRemind) {
$error = "";
$days = @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 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);
sendmail($user->email2,$company_name,$manager_email,$subject,$template);
}
}
}
}
}
# Напоминаем об окончании тестового периода
if ($cronSendClientEndTestRemind) {
$error = "";
$days = @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 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);
sendmail($user->email2,$company_name,$manager_email,$subject,$template);
}
}
}
}
}
# Напоминаем об окончании оплаченного периода (домены)
if ($cronSendClientEndOrderDomainRemind) {
$error = "";
$days = @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);
sendmail($user->email2,$company_name,$manager_email,$subject,$template);
}
}
}
}
}
# Напоминаем об окончании оплаченного периода (товар)
if ($cronSendClientEndOrderShopRemind) {
$error = "";
$days = @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);
sendmail($user->email2,$company_name,$manager_email,$subject,$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 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());
@mysql_query("delete from orders_domains where host_id='$order->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 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());
}
}
}
}
# Удаляем необработанные заказы (товары), для которых нет ни одного счёта
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 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());
}
}
}
}
# Удаляем заказы (домены) у которых истек оплаченный срок истек и они не продлены.
if ($cronDeleteOrderDomain and intval($cronDeleteOrderDomainDay) > 0) {
$error = "";
$domains = @mysql_query("select * from orders_domains where startdate <> '0000-00-00' AND (TO_DAYS(todate)-TO_DAYS(NOW())<=-$cronDeleteOrderDomainDay)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($domains) > 0) {
while ($domain = mysql_fetch_object($domains)) {
@mysql_query("update orders set domain_reg='0' where domain='$domain->domain'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("update bills set domain_id='0', domain_srok='0', money_domain='0' where domain_id='$domain->id' and NOT(host_id='0')") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("delete from bills where domain_id='$domain->id' and host_id='0'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("delete from orders_domains where id='$domain->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
}
# Отправка запроса на удаление для доменов, которые истекают через 5 дней и зарегистрированы через internetx.de
$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.internetxDeleted='0' and d.autoregby=r.id and r.type='internetx'") 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);
$internetx_url = $registrator->url;
$internetx_user = $registrator->text1;
$internetx_password = $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";
}
}
}
if ($error) {
$errormsg = $error."rnrnВнимание! Домены, для которых автоматически не создана заявка на удаление, необходимо обработать вручную (в панели управления необходимо сделать Cancel/Delete домена с датой удаления At Expiration Date) и установить значение 1 в поле internetxDeleted в редактировании заказа на домен в биллинге, иначе они будут автоматически продлены.";
$subject = "Cron: отчет об отправке заявки на удаление доменов истекающих через 5 дней [internetx.de]";
$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 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) {
$error = "";
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tarif = GetTarifById($order->tarif);
if ($cronSendAdminEndOrder and $order->leftdays == "-1") {
$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") {
if ($order->serverlogin and $order->serverid) {
$server = GetServers($order->serverid);
if ($tarif->autosuspend and $cronAutoSuspend and !$order->noSuspend and !$user->noSuspend) {
if (suspendUser($order->id, 1, 1)) {
@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 для заказа ID #$order->id ($order->domain) автоматически остановлен на сервере ($server->name).rn";
} else {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name). Сделайте это вручную.rn";
}
} else if (!$cronAutoSuspend) {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name), т.к. эта возможность отключена в настройках Cron'а.rn";
} else if (!$tarif->autosuspend) {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name), т.к. эта возможность отключена в настройках тарифного плана.rn";
} else if ($order->noSuspend) {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name), т.к. эта возможность отключена в настройках заказа.rn";
} else if ($user->noSuspend) {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не остановлен на сервере ($server->name), т.к. эта возможность отключена в настройках пользователя.rn";
}
} else {
$error = $error . "- Аккаунт для заказа ID #$order->id ($order->domain) не остановлен автоматически, т.к. не указан логин на сервере либо не указан сервер.rn";
}
}
}
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);
}
}
}
# Уведомление менеджеру об окончании тестового периода у клиента
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where todate <> '0000-00-00' AND testPeriod='1' 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) {
$error = "";
while ($order = mysql_fetch_object($orders)) {
$user = GetUserById($order->uid);
$tarif = GetTarifById($order->tarif);
if ($cronSendAdminEndOrder and $order->leftdays == "-1") {
$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->serverlogin and $order->serverid) {
$server = GetServers($order->serverid);
if ($tarif->autodeletetest and $cronAutoDeleteTest) {
if (deleteUser($order->id)) {
@mysql_query("update orders set testPeriod='0',todate='0000-00-00',serverlogin='',serverpassword='',serverid='' where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
$error = $error . "+ Тестовый аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) автоматически удален на сервере ($server->name).rn";
} else {
$error = $error . "- Тестовый аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не удален на сервере ($server->name). Сделайте это вручную.rn";
}
} else if (!$cronAutoDeleteTest) {
$error = $error . "- Тестовый аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не удален на сервере ($server->name), т.к. эта возможность отключена в настройках Cron'а.rn";
} else if (!$tarif->autodeletetest) {
$error = $error . "- Тестовый аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не удален на сервере ($server->name), т.к. эта возможность отключена в настройках тарифного плана.rn";
}
} else {
$error = $error . "- Тестовый аккаунт для заказа ID #$order->id ($order->domain) не удален автоматически, т.к. не указан логин на сервере либо не указан сервер.rn";
}
}
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 ($cronDeleteOrderShop and intval($cronDeleteOrderShopDay) > 0) {
$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())<=-$cronDeleteOrderShopDay)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
$shopItem = GetShopItemById($order->item);
if ($shopItem->costtype != "one") {
if ($shopItem->type == "avdesk") {
if ($order->field1) {
if (deleteShopOrder($order->id, 0)) {
$error = $error . "+ Аккаунт $order->field1 для заказа на товар ID #$order->id ($shopItem->name) автоматически удален на сервере.rn";
} else {
$error = $error . "- Аккаунт $order->field1 для заказа на товар ID #$order->id ($shopItem->name) не удален на сервере. Сделайте это вручную.rn";
}
} else {
$error = $error . "- Аккаунт $order->field1 для заказа на товар ID #$order->id ($shopItem->name) не был удалён автоматически, т.к. не указан логин на сервере.rn";
}
$error = $error . " Заказ и все счета, относящиеся к нему, удалены.rn";
@mysql_query("delete from bills where shop_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("delete from orders_shop where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
}
}
if ($error) {
$errormsg = $error."nnВнимание! Аккаунты, не удаленные автоматически на сервере, необходимо удалить вручную.";
$subject = "Cron: отчет об удалении заказов на товары, истекших 60 дней назад";
$admEmails=GetAdminEmailsWhereTrueParam("sendcron");
if (count($admEmails) > 0) {
WriteMailLog($subject,$errormsg);
}
while (list($i,$em) = @each($admEmails)) {
sendmail($em,'',$manager_email,$subject,$errormsg);
}
}
}
}
# Удаляем заказы у которых оплаченный срок истек и они не продлены. Если вместе с хостингом заказан домен, то заказ на домен оставляем.
if ($cronDeleteOrder and intval($cronDeleteOrderDay) > 0) {
$error = "";
$orders = @mysql_query("select * from orders where startdate <> '0000-00-00' AND (TO_DAYS(todate)-TO_DAYS(NOW())<=-$cronDeleteOrderDay)") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
if (mysql_num_rows($orders) > 0) {
while ($order = mysql_fetch_object($orders)) {
if ($order->serverlogin and $order->serverid) {
$server = GetServers($order->serverid);
$tarif = GetTarifById($order->tarif);
if ($tarif->autodelete and $cronAutoDelete) {
if (deleteUser($order->id, 0)) {
$error = $error . "+ Аккаунт $order->serverlogin автоматически удален на сервере ($server->name).rn";
} else {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не удален на сервере ($server->name). Сделайте это вручную.rn";
}
} else if (!$cronAutoDelete) {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не удалён на сервере ($server->name), т.к. эта возможность отключена в настройках Cron'а.rn";
} else if (!$tarif->autodelete) {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не удалён на сервере ($server->name), т.к. эта возможность отключена для тарифного плана.rn";
}
} else {
$error = $error . "- Аккаунт $order->serverlogin для заказа ID #$order->id ($order->domain) не был удалён автоматически, т.к. не указан логин на сервере либо не указан сервер.rn";
}
$error = $error . " Заказ и все счета, относящиеся к нему, удалены. rn";
if ($order->domain_reg == "1") {
$domain = GetDomainByDomain("$order->domain");
@mysql_query("update orders_domains set host_id='0' where host_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("update bills set host_id='0', host_srok='0', money_host='0', money_addons='0' where host_id='$order->id' and domain_id='$domain->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
@mysql_query("delete from bills where host_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("delete from orders where id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
@mysql_query("update servers_ips set order_id='0',isMain='0' where order_id='$order->id'") or die("File: ".__FILE__."<BR>Line: ".__LINE__."<BR>MySQL Error: ".mysql_error());
}
if ($error) {
$errormsg = $error."nnВнимание! Аккаунты, не удаленные автоматически на сервере, необходимо удалить вручную.";
$subject = "Cron: отчет об удалении заказов, истекших 60 дней назад";
$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 as o, users as u where 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.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'") 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' 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=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 {
$addonsCost += $oneAddon->cost_monthly*$hostMonths;
}
}
}
}
if (!$addonsToSaveText) { $addonsToSaveText=$userLang[No]; }
$addonsCost=round($addonsCost,2);
$tarifSpecCost = GetSpecialCost($user->id,"tarif",$tarif->id);
if ($tarifSpecCost) {
$hostCost=$tarifSpecCost["cost2"]*$hostMonths;
} else {
$hostCost=$tarif->cost*$hostMonths;
}
$orderDiscount=$order->discount;
$host=$hostCost-($hostCost/100)*($srokDiscount+$orderDiscount);
if ($orderDiscount == '100') {$host = 0;}
$host=round($host,2);
@mysql_query("insert into bills (uid,host_id,host_srok,money_host,money_addons,created,renew) values('$user->id','$order->id','$hostMonths','$host','$addonsCost',NOW(),'1')") 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);
} else if ($profile->org == "2" and $profile->name and $profile->surname and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
} else if ($profile->org == "1") {
$attachFile = createKvitanciya('', $bill_id, 2);
}
if (!$attachFile) {$attachFile="";}
}
$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);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,$attachFile);
$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);
}
@unlink($attachFile);
}
$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 = GetDomainCostForUserByZoneId($user->id,$zone->id);
$domainCost=$domainCost * ($domainMonths/12);
$domainDiscount = $order->discount;
$domainCost = $domainCost - ($domainCost/100)*$domainDiscount;
@mysql_query("insert into bills (uid,domain_id,domain_srok,money_domain,created,renew) values('$user->id','$order->id','$domainMonths','$domainCost',NOW(),'1')") 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);
} else if ($profile->org == "2" and $profile->name and $profile->surname and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
} else if ($profile->org == "1") {
$attachFile = createKvitanciya('', $bill_id, 2);
}
if (!$attachFile) {$attachFile="";}
}
$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);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,$attachFile);
$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);
}
@unlink($attachFile);
}
$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;
@mysql_query("insert into bills (uid,shop_id,shop_srok,money_shop,created,renew) values('$user->id','$order->id','$shopMonths','$shopCost',NOW(),'1')") 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);
} else if ($profile->org == "2" and $profile->name and $profile->surname and $profile->phone) {
$attachFile = createFaktura('', $bill_id, 2);
} else if ($profile->org == "1") {
$attachFile = createKvitanciya('', $bill_id, 2);
}
if (!$attachFile) {$attachFile="";}
}
$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);
sendmail($user->email2,$company_name,$manager_email,$subject,$template,$attachFile);
$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);
}
@unlink($attachFile);
}
$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();
?>