Вход Регистрация
Файл: apih.php
Строк: 689
<?

$mtime 
microtime(); $mtime explode(" ",$mtime); $mtime $mtime[1] + $mtime[0]; $tstart $mtime

$full_home_path dirname(__FILE__);
require_once(
$full_home_path.'/_rootload.php');

EnableLanguages(1);

if (
mconnect(1)) {
    if (
$login) {
        
$login strtolower($login);

        if (
$login != "test") {
            
$queryParametersForLog = @serialize($queryParametersForLog);
            
$APILogId AddAPILog($login,$command,'',$queryParametersForLog);
        } else {
            
$APILogId "";
        }


        if (
$login == "test" and $pass == "test") { 
            
$isTest 1

            
$user->id 9999;
            
$user->apih 1;
            
$user->money 999999;
            
$user->currency "";
        } else { 
            
$isTest 0

            
$user GetUserByLogin($login);
        }

        if (
$user->id) {
            if (
$user->apih) {
                if (
$pass and $apikey) {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "9";
                    
$res[errorMsg] = "Запрещено использовать пароль и ключ API в одном запросе.";
                }
                else if (
$pass or $apikey) {

                    
$isAPI 1;

                    
$curr LoadCurrencyToVariable($user->currency);

                    
$company_name=GetSetting('company_name',1);
                    
$company_url=GetSetting('company_url',1);
                    
$billing_url=GetSetting('billing_url',1);
                    
$support_url=GetSetting('support_url',1);
                    
$manager_email=GetSetting('manager_email',1);

                    if (
$isTest or crypt($pass,$user->password) == $user->password or ($apikey == $user->apikey and $user->apikey) and !$user->banned) {



#############################################################################
#
# Получение списка тарифных планов

#############################################################################

if ($command == "getTarifs") {
    if (
$vid and $vid != "hosting" and $vid != "vds" and $vid != "dedicated") {
        
$res[status] = "ERROR";
        
$res[errorCode] = "24";
        
$res[errorMsg] = "Тип тарифного плана указан неверно.";
    }
    else {
        if (!
$vid) { $vid "hosting"; }

        
$tarifs = @mysql_query("select * from tarifs where vid='$vid' and active='1' and enableSlots<>'1' and onlyWithDomain<>'1' order by cost");
        if (@
mysql_num_rows($tarifs) == 0) {
            
$res[status] = "ERROR";
            
$res[errorCode] = "10";
            
$res[errorMsg] = "Тарифные планы отсутствуют.";
        } 
        else {
            
$res[status] = "SUCCESS";

            
$i 0;
            while (
$tarif = @mysql_fetch_object($tarifs)) {
                
$i++;

                
$res[tarifs][$i][id] = $tarif->id;
                
$res[tarifs][$i][vid] = $tarif->vid;
                
$res[tarifs][$i][name] = $tarif->name;

                
$tarifSpecCost GetSpecialCost($user->id,"tarif",$tarif->id);
                if (
$tarifSpecCost) {
                    
$tarif->cost_setup round($tarifSpecCost["cost1"]*$curr["CURK"],2);
                    
$tarif->cost round($tarifSpecCost["cost2"]*$curr["CURK"],2);
                } 
                else {
                    
$tarif->cost $tarif->cost GetCurrencyKoeficientByCode($tarif->costCurrency); $tarif->cost round($tarif->cost*$curr["CURK"],2);
                    
$tarif->cost_setup $tarif->cost_setup GetCurrencyKoeficientByCode($tarif->cost_setupCurrency); $tarif->cost_setup round($tarif->cost_setup*$curr["CURK"],2);
                }

                
$res[tarifs][$i][costMonthly] = $tarif->cost;
                
$res[tarifs][$i][costSetup] = $tarif->cost_setup;

                
$res[tarifs][$i][currency] = $curr["CURC"];
                
$res[tarifs][$i][allowWithoutDomain] = $tarif->allowWithoutDomain;

                
$months = @mysql_query("select * from tarifs_sroki where tarif_id='$tarif->id' order by months");
                if (@
mysql_num_rows($months) > 0) {
                    
$j 0;
                    while (
$month = @mysql_fetch_object($months)) {
                        
$j++;
                        
$res[tarifs][$i][months][$j][months] = $month->months;
                        
$res[tarifs][$i][months][$j][discount] = $month->discount;
                        
$res[tarifs][$i][months][$j][allowForNewOrder] = $month->order;
                        
$res[tarifs][$i][months][$j][allowForRenew] = $month->renew;
                    }
                }
                else {
                    
$res[tarifs][$i][months] = "";
                }

                
$addonsForTarif = @mb_split(":x:",$tarif->addons);
                
$addonsCnt 0;
                
$j 0;
                while (list(
$k,$v) = @each($addonsForTarif)) {
                    if (
$v) {
                        
$oneAddon GetAddonById($v);
                        if (
$oneAddon->active and !$oneAddon->onlyifrenew) {
                            
$j++;

                            
$res[tarifs][$i][addons][$j][id] = $oneAddon->id;
                            
$res[tarifs][$i][addons][$j][name] = $oneAddon->name;

                            
$addonSpecCost GetSpecialCost($user->id,"addon",$oneAddon->id);
                            if (
$addonSpecCost) {
                                
$oneAddon->cost_start round($addonSpecCost["cost1"]*$curr["CURK"],2);
                                
$oneAddon->cost_monthly round($addonSpecCost["cost2"]*$curr["CURK"],2);
                            } else {
                                
$oneAddon->cost_start $oneAddon->cost_start GetCurrencyKoeficientByCode($oneAddon->cost_startCurrency); $oneAddon->cost_start round($oneAddon->cost_start*$curr["CURK"],2);
                                
$oneAddon->cost_monthly $oneAddon->cost_monthly GetCurrencyKoeficientByCode($oneAddon->cost_monthlyCurrency); $oneAddon->cost_monthly round($oneAddon->cost_monthly*$curr["CURK"],2);
                            }

                            
$res[tarifs][$i][addons][$j][costMonthly] = $oneAddon->cost_monthly;
                            
$res[tarifs][$i][addons][$j][costSetup] = $oneAddon->cost_start;
                        }
                    }
                }
                if (!
$j) {
                    
$res[tarifs][$i][addons] = "";
                }

            }
        }
    }
}


#############################################################################
#
# Создание заказа

#############################################################################

else if ($command == "createOrder") {
    
$tarifid = @intval($tarifid);
    
$period = @intval($period);
    
$domain mb_strtolower($domain); $domain preg_replace("/^www./ui","",$domain);

    if (!
$tarifid) {
        
$res[status] = "ERROR";
        
$res[errorCode] = "11";
        
$res[errorMsg] = "Не указан идентификатор тарифного плана.";
    }
    else if (
$vid and $vid != "hosting" and $vid != "vds" and $vid != "dedicated") {
        
$res[status] = "ERROR";
        
$res[errorCode] = "24";
        
$res[errorMsg] = "Тип тарифного плана указан неверно.";
    }
    else {
        if (!
$vid) { $vid "hosting"; }

        
$tarif = @mysql_query("select * from tarifs where vid='$vid' and active='1' and enableSlots<>'1' and onlyWithDomain<>'1' and id='$tarifid'");
        if (@
mysql_num_rows($tarif) == 0) {
            
$res[status] = "ERROR";
            
$res[errorCode] = "12";
            
$res[errorMsg] = "Тарифный план не найден.";
        } 
        else {
            
$tarif = @mysql_fetch_object($tarif);

            if (!
$tarif->allowWithoutDomain and !preg_match("/^[a-zа-яёЁїЇіІєЄӘәҒғҚқҢңӨөҮүҰұҺһ0-9]{1}[a-zа-яёЁїЇіІєЄӘәҒғҚқҢңӨөҮүҰұҺһ0-9-]*[a-zа-яёЁїЇіІєЄӘәҒғҚқҢңӨөҮүҰұҺһ0-9]{1}.[a-zа-яёЁїЇіІєЄӘәҒғҚқҢңӨөҮүҰұҺһ0-9-.]*[a-zа-яёЁїЇіІєЄӘәҒғҚқҢңӨөҮүҰұҺһ0-9]{1}$/u",$domain)) {
                
$res[status] = "ERROR";
                
$res[errorCode] = "13";
                
$res[errorMsg] = "Не указано доменное имя.";
            }
            else {
                
$o = @mysql_query("select * from orders where archived=0 and domain='$domain' and todate>NOW()");
                
$tsroki = @mysql_query("select * from tarifs_sroki where tarif_id='$tarifid' and months='$period' and `order`='1'");

                
$addonsCost 0;
                
$addonsToSave "";
                
$addonsToSaveText "";
                
$addonsError 0;
                if (
$addons) {
                    
$addonsForTarif = @mb_split(":x:",$tarif->addons);
                    
$addonsInput = @mb_split(",",$addons);
                    while (list(
$k,$v) = @each($addonsInput)) {
                        if (
$v) {
                            if (!@
in_array($v,$addonsForTarif)) { $addonsError 1; break; }

                            
$selectedAddon = @mysql_query("select * from addons where id='$v' and active='1' and onlyifrenew<>'1'");
                            if (@
mysql_num_rows($selectedAddon) == "0") { $addonsError 1; break; }

                            
$selectedAddon = @mysql_fetch_object($selectedAddon);

                            if (
$addonsToSaveText) {
                                
$addonsToSaveText $addonsToSaveText.", ".$selectedAddon->name." - 1 ".$_lang[FakturaSokraschenieShtuka];
                            } else {
                                
$addonsToSaveText $selectedAddon->name." - 1 ".$_lang[FakturaSokraschenieShtuka];
                            }
                            if (
$addonsToSave) {
                                
$addonsToSave $addonsToSave.":x:$selectedAddon->id";
                            } else {
                                
$addonsToSave $selectedAddon->id;
                            }

                            
#Устанавливаем спец. цену, если она указана для данной доп. услуги и данного пользователя
                            #
                            
$addonSpecCost GetSpecialCost($user->id,"addon",$selectedAddon->id);
                            if (
$addonSpecCost) {
                                
$addonsCost += $addonSpecCost["cost1"];
                                
$addonsCost += $addonSpecCost["cost2"]*$period;
                            } else {
                                
$selectedAddon->cost_start $selectedAddon->cost_start GetCurrencyKoeficientByCode($selectedAddon->cost_startCurrency);
                                
$selectedAddon->cost_monthly $selectedAddon->cost_monthly GetCurrencyKoeficientByCode($selectedAddon->cost_monthlyCurrency);

                                
$addonsCost += $selectedAddon->cost_start;
                                
$addonsCost += $selectedAddon->cost_monthly*$period;
                            }
                        }
                    }
                }
                if (!
$addonsToSaveText) { $addonsToSaveText $_lang[No]; }


                if (!
$isTest and !$tarif->allowWithoutDomain and @mysql_num_rows($o) > 0) {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "14";
                    
$res[errorMsg] = "Тарифный план для указанного доменного имени уже заказан.";
                }
                else if (!
$period or $period <= 0) {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "15";
                    
$res[errorMsg] = "Не указан срок заказа.";
                }
                else if (@
mysql_num_rows($tsroki) == 0) {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "16";
                    
$res[errorMsg] = "Указан недопустимый срок заказа.";
                }
                else if (!
$isTest and $addonsError) {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "17";
                    
$res[errorMsg] = "Указана недопустимая дополнительная услуга.";
                }
                else {
                    
$tsroki=mysql_fetch_object($tsroki);

                    
$tarifSpecCost GetSpecialCost($user->id,"tarif",$tarif->id);
                    if (
$tarifSpecCost) {
                        
$tarif->cost_setup $tarifSpecCost["cost1"];
                        
$tarif->cost $tarifSpecCost["cost2"];
                    } 
                    else {
                        
$tarif->cost $tarif->cost GetCurrencyKoeficientByCode($tarif->costCurrency);
                        
$tarif->cost_setup $tarif->cost_setup GetCurrencyKoeficientByCode($tarif->cost_setupCurrency);
                    }

                    if (
$tarif->serverid) { $serverid $tarif->serverid; } else { $serverid 0; }
                    if (
$serverid) {
                        
$srv GetServers($serverid);
                        if (
$srv->nacenka) { $srvNacenka $srv->nacenka; }
                    }
                    if (
$srvNacenka) {
                        
$tarif->cost $tarif->cost + ($tarif->cost/100)*$srvNacenka;
                    }

                    
$hostCost $tarif->cost*$period;
                    
$hostCost $hostCost - ($hostCost/100)*$tsroki->discount $tarif->cost_setup;
                    
$hostCost round($hostCost,2);

                    
$addonsCost round($addonsCost,2);

                    
$allCost $hostCost $addonsCost;

                    if (
$domain) { $domain_reg 0; } else { $domain_reg 2; }

                    
$history "<B>Тариф:</B> $tarif->name";
                    if (
$domain) { $history .= ", <B>домен:</b> $domain"; }

                    if (
$isTest or @mysql_query("insert into orders (uid,tarif,domain,domain_reg,orderdate,serverid,addons,history) values('$user->id','$tarifid','$domain','$domain_reg',NOW(),'$serverid','$addonsToSave','$history')")) {
                        
$host_id = @mysql_insert_id();
                        if (
$isTest) { $host_id mt_rand(10,500); }

                        
$history "Тариф: $tarif->name$period мес.";
                        if (
$addonsToSaveText and $addonsToSaveText != $_lang[No]) { $history .= " + $addonsToSaveText";}

                        if (
$isTest or @mysql_query("insert into bills (uid,host_id,host_srok,money_host,money_addons,created,history) values('$user->id','$host_id','$period','$hostCost','$addonsCost',NOW(),'$history')")) {
                            
$bill_id=mysql_insert_id();

                            if (
$user->money >= $allCost) {
                                if (
$isTest or @mysql_query("UPDATE users set money=money-$allCost WHERE id='$user->id'")) {
                                    if (
$isTest or @mysql_query("update bills set payed=NOW(),payeddt=NOW(),status='1' where id='$bill_id'")) {
                                        if (
$isTest or @mysql_query("update orders set startdate=NOW(), todate=DATE_ADD(NOW(),INTERVAL ".$period." MONTH) where id='$host_id'")) {
                                            
$balanceRounded round(($user->money-$allCost)*$curr["CURK"],2);
                                            
$costRounded round($allCost*$curr["CURK"],2);
                                            
$hostCostRounded round($hostCost*$curr["CURK"],2);
                                            
$addonsCostRounded round($addonsCost*$curr["CURK"],2);

                                            if (!
$isTest) { MakePartnersProcentsByBillId($bill_id); }

                                            if (
$isTest or createUser($host_id)) {
                                                
$order = @mysql_query("SELECT * from orders where id='$host_id'");
                                                
$order = @mysql_fetch_object($order);

                                                
$res[status] = "SUCCESS";
                                                
$res[orderid] = "$host_id";
                                                
$res[vid] = "$vid";
                                                
$res[tarifid] = "$tarifid";
                                                
$res[domain] = "$domain";
                                                
$res[period] = "$period";
                                                
$res[addons] = "$addons";
                                                
$res[balance] = "$balanceRounded";
                                                
$res[cost] = "$costRounded";
                                                
$res[currency] = $curr["CURC"];
                                                
$res[serverlogin] = "$order->serverlogin";
                                                
$res[serverpassword] = decodePwd($order->serverpassword);
                                                
$res[remark] = "$order->remarkUser";
                                            }
                                            else {
                                                
$res[status] = "SUCCESS";
                                                
$res[errorCode] = "30";
                                                
$res[errorMsg] = "Заявка принята, но по техническим причинам будет обработана в ручном режиме.";
                                                
$res[orderid] = "$host_id";
                                                
$res[vid] = "$vid";
                                                
$res[tarifid] = "$tarifid";
                                                
$res[domain] = "$domain";
                                                
$res[period] = "$period";
                                                
$res[addons] = "$addons";
                                                
$res[balance] = "$balanceRounded";
                                                
$res[cost] = "$costRounded";
                                                
$res[currency] = $curr["CURC"];
                                                
$res[serverlogin] = "";
                                                
$res[serverpassword] = "";
                                                
$res[remark] = "";
                                            }
                                        }
                                        else {
                                            
$res[status] = "ERROR";
                                            
$res[errorCode] = "2";
                                            
$res[errorMsg] = "Ошибка сохранения данных статуса заказа в БД: ".mysql_error().".";

                                            @
mysql_query("UPDATE users set money=money+$allCost WHERE id='$user->id'");
                                            @
mysql_query("DELETE FROM bills WHERE id='$bill_id'");
                                            @
mysql_query("DELETE FROM orders WHERE id='$host_id'");
                                        }
                                    }
                                    else {
                                        
$res[status] = "ERROR";
                                        
$res[errorCode] = "2";
                                        
$res[errorMsg] = "Ошибка сохранения данных статуса счета в БД: ".mysql_error().".";

                                        @
mysql_query("UPDATE users set money=money+$allCost WHERE id='$user->id'");
                                        @
mysql_query("DELETE FROM bills WHERE id='$bill_id'");
                                        @
mysql_query("DELETE FROM orders WHERE id='$host_id'");
                                    }
                                } 
                                else {
                                    
$res[status] = "ERROR";
                                    
$res[errorCode] = "2";
                                    
$res[errorMsg] = "Ошибка сохранения данных баланса пользователя в БД: ".mysql_error().".";

                                    @
mysql_query("DELETE FROM bills WHERE id='$bill_id'");
                                    @
mysql_query("DELETE FROM orders WHERE id='$host_id'");
                                }
                            }
                            else {
                                
$res[status] = "ERROR";
                                
$res[errorCode] = "31";
                                
$res[errorMsg] = "Недостаточно среств на внутреннем балансе.";

                                @
mysql_query("DELETE FROM bills WHERE id='$bill_id'");
                                @
mysql_query("DELETE FROM orders WHERE id='$host_id'");
                            }

                            if (!
$isTest and $res[status] == "SUCCESS") {
                                
$sid=sprintf("%04d"$bill_id);

                                
addUserLog($user->id,'order',"$tarif->name$period мес., $domain [".$_newreg[$domain_reg]."]");
                                     
addUserLog($user->id"pay""Bill № $sid via API");

                                
$tpl GetTpl('email_touser_'.$vid.'_order'$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('{tarif}',$tarif->name,$template);
                                         
$template str_replace('{srok}',$period,$template);
                                         
$template str_replace('{domain}',$domain,$template);
                                         
$template str_replace('{bonus}','',$template);
                                         
$template str_replace('{addons}',$addonsToSaveText,$template);
                                         
$template str_replace('{newreg}',$_newreg[$domain_reg],$template);
                                         
$template str_replace('{login}',$user->login,$template);
                                         
$template str_replace('{password}','******',$template);
                                         
$template str_replace('{schet}',$sid,$template);
                                         
$template str_replace('{hostcost}',$hostCostRounded." ".$curr["CURS"],$template);
                                         
$template str_replace('{domaincost}',"0 ".$curr["CURS"],$template);
                                         
$template str_replace('{addonscost}',$addonsCostRounded." ".$curr["CURS"],$template);
                                         
$template str_replace('{cost}',$costRounded." ".$curr["CURS"],$template);
                                         
$template str_replace('{paymethod}','',$template);
                                         
$template str_replace('{comment}',$comment,$template);
                                         
$template str_replace('{userid}',$user->id,$template);
                                         
$template str_replace('{slots}',"",$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]);

                                    
$subject "Duplicate: ".$subject;

                                    
$admEmails=GetAdminEmailsWhereTrueParam("sendneworder");
                                    if (
count($admEmails) > 0) {
                                        
WriteMailLog($subject,$template);
                                    }
                                    while (list(
$i,$em) = @each($admEmails)) {
                                        
sendmail($em,'',$manager_email,$subject,$template,'','',$tpl[type]);
                                    }
                                }

                            }

                        }
                        else {
                            
$res[status] = "ERROR";
                            
$res[errorCode] = "2";
                            
$res[errorMsg] = "Ошибка сохранения данных счета в БД: ".mysql_error().".";

                            @
mysql_query("DELETE FROM orders WHERE id='$host_id'");
                        }
                    }
                    else {
                        
$res[status] = "ERROR";
                        
$res[errorCode] = "2";
                        
$res[errorMsg] = "Ошибка сохранения данных заказа в БД: ".mysql_error().".";
                    }
                }
            }
        }

    }
}


#############################################################################
#
# Продление заказа

#############################################################################

else if ($command == "renewOrder") {
    
$orderid = @intval($orderid);
    
$period = @intval($period);

    if (!
$orderid) {
        
$res[status] = "ERROR";
        
$res[errorCode] = "18";
        
$res[errorMsg] = "Не указан идентификатор заказа.";
    }
    else {
        
$order = @mysql_query("select * from orders where id='$orderid' and todate<>'0000-00-00' and testPeriod<>'1' and status<>'0' archived=0");
        if (!
$isTest and @mysql_num_rows($order) == 0) {
            
$res[status] = "ERROR";
            
$res[errorCode] = "19";
            
$res[errorMsg] = "Заказ не найден.";
        } 
        else {
            
$order = @mysql_fetch_object($order);

            
$bills = @mysql_query("select * from bills where archived=0 and host_id = '$orderid' and uid='$user->id'");
            
$bills = @mysql_num_rows($bills);
            
$billspayed = @mysql_query("select * from bills where archived=0 and host_id = '$orderid' and uid='$user->id' and status<>'0'");
            
$billspayed = @mysql_num_rows($billspayed);
            
$billsNonPayed $bills-$billspayed;

            if (
$billsNonPayed != 0) {
                
$res[status] = "ERROR";
                
$res[errorCode] = "20";
                
$res[errorMsg] = "Для заказа есть неоплаченные счета.";
            }
            else {
                
$tarif GetTarifById($order->tarif);
                
$tsroki = @mysql_query("select * from tarifs_sroki where tarif_id='$tarif->id' and months='$period' and renew='1'");

                if (!
$isTest and !$tarif->id) {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "12";
                    
$res[errorMsg] = "Тарифный план не найден.";
                } 
                else if (!
$period or $period <= 0) {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "15";
                    
$res[errorMsg] = "Не указан срок заказа.";
                }
                else if (!
$isTest and @mysql_num_rows($tsroki) == 0) {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "16";
                    
$res[errorMsg] = "Указан недопустимый срок заказа.";
                }
                else {
                    
$tsroki=mysql_fetch_object($tsroki);

                    
$tarifSpecCost GetSpecialCost($user->id,"tarif",$tarif->id);
                    if (
$tarifSpecCost) {
                        
$tarif->cost $tarifSpecCost["cost2"];
                    } 
                    else {
                        
$tarif->cost $tarif->cost GetCurrencyKoeficientByCode($tarif->costCurrency);
                    }

                    if (
$tarif->serverid) { $serverid $tarif->serverid; } else { $serverid 0; }
                    if (
$serverid) {
                        
$srv GetServers($serverid);
                        if (
$srv->nacenka) { $srvNacenka $srv->nacenka; }
                    }
                    if (
$srvNacenka) {
                        
$tarif->cost $tarif->cost + ($tarif->cost/100)*$srvNacenka;
                    }

                    
$hostCost $tarif->cost*$period;
                    
$hostCost $hostCost - ($hostCost/100)*($tsroki->discount $order->discount);
                    if (
$order->discount == '100') {$hostCost 0;}
                    
$hostCost round($hostCost,2);

                    
$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"]*$period;
                                } else {
                                    
$oneAddon->cost_monthly $oneAddon->cost_monthly GetCurrencyKoeficientByCode($oneAddon->cost_monthlyCurrency);

                                    
$addonsCost += $oneAddon->cost_monthly*$period;
                                }
                            }
                        }
                    }
                    if (!
$addonsToSaveText) { $addonsToSaveText=$_yes[0]; }
                    
$addonsCost round($addonsCost,2);
                    
$allCost $hostCost $addonsCost;

                    
$history "Тариф: <B>$tarif->name</B>, $period мес.";

                    if (
$isTest or @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','$period','$hostCost','$addonsCost',NOW(),'1','$history')")) {
                        
$bill_id=mysql_insert_id();

                        if (
$user->money >= $allCost) {
                            if (
$isTest or @mysql_query("UPDATE users set money=money-$allCost WHERE id='$user->id'")) {
                                if (
$isTest or @mysql_query("update bills set payed=NOW(),payeddt=NOW(),status='1' where id='$bill_id'")) {

                                    if (
$order->status == "1") {
                                        
$sql "update orders set todate=DATE_ADD(todate,INTERVAL ".($period*30)." DAY) where id='$order->id'";
                                    } 
                                    else if (
$order->status == "2") {
                                        
$sql "update orders set todate=DATE_ADD(NOW(),INTERVAL ".($period*30)." DAY) where id='$order->id'";
                                    }

                                    
$balanceRounded round(($user->money-$allCost)*$curr["CURK"],2);
                                    
$costRounded round($allCost*$curr["CURK"],2);
                                    
$hostCostRounded round($hostCost*$curr["CURK"],2);
                                    
$addonsCostRounded round($addonsCost*$curr["CURK"],2);

                                    if (
$isTest or @mysql_query("$sql")) {
                                        if (!
$isTest) { MakePartnersProcentsByBillId($bill_id); }

                                        if (
$isTest or $order->status == "1" or ($order->status == "2" and suspendUser($order->id)) ) {
                                            if (!
$isTest and $order->status == "2") {
                                                @
mysql_query("UPDATE orders SET status='1' where id='$order->id'");
                                            }

                                            
$res[status] = "SUCCESS";
                                            
$res[orderid] = "$orderid";
                                            
$res[period] = "$period";
                                            
$res[balance] = "$balanceRounded";
                                            
$res[cost] = "$costRounded";
                                            
$res[currency] = $curr["CURC"];
                                        }
                                        else {
                                            
$res[status] = "SUCCESS";
                                            
$res[errorCode] = "30";
                                            
$res[errorMsg] = "Заявка принята, но по техническим причинам будет обработана в ручном режиме.";
                                            
$res[orderid] = "$orderid";
                                            
$res[period] = "$period";
                                            
$res[balance] = "$balanceRounded";
                                            
$res[cost] = "$costRounded";
                                            
$res[currency] = $curr["CURC"];
                                        }
                                    }
                                    else {
                                        
$res[status] = "ERROR";
                                        
$res[errorCode] = "2";
                                        
$res[errorMsg] = "Ошибка сохранения данных статуса заказа в БД: ".mysql_error().".";

                                        @
mysql_query("UPDATE users set money=money+$allCost WHERE id='$user->id'");
                                        @
mysql_query("DELETE FROM bills WHERE id='$bill_id'");
                                    }
                                }
                                else {
                                    
$res[status] = "ERROR";
                                    
$res[errorCode] = "2";
                                    
$res[errorMsg] = "Ошибка сохранения данных статуса счета в БД: ".mysql_error().".";

                                    @
mysql_query("UPDATE users set money=money+$allCost WHERE id='$user->id'");
                                    @
mysql_query("DELETE FROM bills WHERE id='$bill_id'");
                                }
                            } 
                            else {
                                
$res[status] = "ERROR";
                                
$res[errorCode] = "2";
                                
$res[errorMsg] = "Ошибка сохранения данных баланса пользователя в БД: ".mysql_error().".";

                                @
mysql_query("DELETE FROM bills WHERE id='$bill_id'");
                            }
                        }
                        else {
                            
$res[status] = "ERROR";
                            
$res[errorCode] = "31";
                            
$res[errorMsg] = "Недостаточно среств на внутреннем балансе.";

                            @
mysql_query("DELETE FROM bills WHERE id='$bill_id'");
                        }

                        if (!
$isTest and $res[status] == "SUCCESS") {
                            
$sid=sprintf("%04d"$bill_id);

                            
$tpl=GetTpl("email_touser_".$tarif->vid."_renew"$user->lang);
                            
$subject $tpl[subject]; $template $tpl[template];

                                 
addUserLog($user->id"renew""$tarif->name$period мес., $order->domain");
                                 
addUserLog($user->id"pay""Bill № $sid via API");

                            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('{tarif}',$tarif->name,$template);
                                     
$template str_replace('{srok}',$period,$template);
                                     
$template str_replace('{domain}',$order->domain,$template);
                                     
$template str_replace('{addons}',$addonsToSaveText,$template);
                                     
$template str_replace('{newreg}',"-",$template);
                                     
$template str_replace('{login}',$user->login,$template);
                                     
$template str_replace('{password}',"******",$template);
                                     
$template str_replace('{schet}',$sid,$template);
                                     
$template str_replace('{hostcost}',$hostCostRounded." ".$curr["CURS"],$template);
                                     
$template str_replace('{domaincost}',"0 ".CURS,$template);
                                     
$template str_replace('{addonscost}',$addonsCostRounded." ".$curr["CURS"],$template);
                                     
$template str_replace('{cost}',$costRounded." ".$curr["CURS"],$template);
                                     
$template str_replace('{userid}',$user->id,$template);
                                     
$template str_replace('{slots}',"",$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]);

                                
$subject "Duplicate: ".$subject;

                                
$admEmails=GetAdminEmailsWhereTrueParam("sendneworder");
                                if (
count($admEmails) > 0) {
                                    
WriteMailLog($subject,$template);
                                }
                                while (list(
$i,$em) = @each($admEmails)) {
                                    
sendmail($em,'',$manager_email,$subject,$template,'','',$tpl[type]);
                                }
                            }
                        }
                    }
                    else {
                        
$res[status] = "ERROR";
                        
$res[errorCode] = "2";
                        
$res[errorMsg] = "Ошибка сохранения данных счета в БД: ".mysql_error().".";
                    }
                }
            }
        }

    }
}

#############################################################################
#
# Остановка заказа

#############################################################################

else if ($command == "suspendOrder") {
    
$orderid = @intval($orderid);

    if (!
$orderid) {
        
$res[status] = "ERROR";
        
$res[errorCode] = "18";
        
$res[errorMsg] = "Не указан идентификатор заказа.";
    }
    else {
        
$order = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where id='$orderid' and todate<>'0000-00-00' and testPeriod<>'1' and status<>'0' and archived=0");
        if (!
$isTest and @mysql_num_rows($order) == 0) {
            
$res[status] = "ERROR";
            
$res[errorCode] = "19";
            
$res[errorMsg] = "Заказ не найден.";
        } 
        else {
            
$order = @mysql_fetch_object($order);

            if (!
$isTest and $order->status != 1) {
                
$res[status] = "ERROR";
                
$res[errorCode] = "21";
                
$res[errorMsg] = "Заказ уже приостановлен.";
            }
            else {
                if (
$isTest or suspendUser($order->id,1)) {
                    if (!
$isTest) {
                        @
mysql_query("UPDATE orders SET status='2' where id='$order->id'");
                    }

                    
$res[status] = "SUCCESS";
                    
$res[orderid] = "$orderid";
                }
                else {
                    
$res[status] = "SUCCESS";
                    
$res[errorCode] = "30";
                    
$res[errorMsg] = "Заявка принята, но по техническим причинам будет обработана в ручном режиме.";
                    
$res[orderid] = "$orderid";
                }
            }
        }

    }
}


#############################################################################
#
# Запуск остановленного заказа

#############################################################################

else if ($command == "unSuspendOrder") {
    
$orderid = @intval($orderid);

    if (!
$orderid) {
        
$res[status] = "ERROR";
        
$res[errorCode] = "18";
        
$res[errorMsg] = "Не указан идентификатор заказа.";
    }
    else {
        
$order = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where id='$orderid' and todate<>'0000-00-00' and testPeriod<>'1' and status<>'0' and archived=0");
        if (!
$isTest and @mysql_num_rows($order) == 0) {
            
$res[status] = "ERROR";
            
$res[errorCode] = "19";
            
$res[errorMsg] = "Заказ не найден.";
        } 
        else {
            
$order = @mysql_fetch_object($order);

            if (!
$isTest and $order->status != 2) {
                
$res[status] = "ERROR";
                
$res[errorCode] = "22";
                
$res[errorMsg] = "Заказ уже запущен.";
            }
            else if (!
$isTest and $order->leftdays 0) {
                
$res[status] = "ERROR";
                
$res[errorCode] = "23";
                
$res[errorMsg] = "Заказ просрочен.";
            }
            else {
                if (
$isTest or suspendUser($order->id,0)) {
                    if (!
$isTest) {
                        @
mysql_query("UPDATE orders SET status='1' where id='$order->id'");
                    }

                    
$res[status] = "SUCCESS";
                    
$res[orderid] = "$orderid";
                }
                else {
                    
$res[status] = "SUCCESS";
                    
$res[errorCode] = "30";
                    
$res[errorMsg] = "Заявка принята, но по техническим причинам будет обработана в ручном режиме.";
                    
$res[orderid] = "$orderid";
                }
            }
        }

    }
}


#############################################################################
#
# Перезагрузка заказа

#############################################################################

else if ($command == "restartOrder") {
    
$orderid = @intval($orderid);

    if (!
$orderid) {
        
$res[status] = "ERROR";
        
$res[errorCode] = "18";
        
$res[errorMsg] = "Не указан идентификатор заказа.";
    }
    else {
        
$order = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where id='$orderid' and todate<>'0000-00-00' and status=='1' and archived=0");
        if (!
$isTest and @mysql_num_rows($order) == 0) {
            
$res[status] = "ERROR";
            
$res[errorCode] = "19";
            
$res[errorMsg] = "Заказ не найден.";
        } 
        else {
            
$order = @mysql_fetch_object($order);
            
$server GetServerById($order->serverid);
            
$tarif GetTarifById($order->tarif);

            if (!
$isTest and !($server->type == "shellscript" and $tarif->scriptRestart) and $server->type != "hypervm" and $server->type != "hypervmxen" and $server->type != "vdsmanager" and $server->type != "solusvmopenvz" and $server->type != "solusvmxen" and $server->type != "solusvmxenhvm" and $server->type != "solusvmkvm" and !($server->type == "rootpanel" and ($tarif->vid == "vds" or $tarif->vid == "dedicated"))) {
                
$res[status] = "ERROR";
                
$res[errorCode] = "25";
                
$res[errorMsg] = "Операция не поддерживается для заказов данного типа ($server->type).";
            }
            else {
                if (
$isTest or restartUser($order->id,1)) {
                    
$res[status] = "SUCCESS";
                    
$res[orderid] = "$orderid";
                }
                else {
                    
$res[status] = "SUCCESS";
                    
$res[errorCode] = "30";
                    
$res[errorMsg] = "Заявка принята, но по техническим причинам будет обработана в ручном режиме.";
                    
$res[orderid] = "$orderid";
                }
            }
        }

    }
}


#############################################################################
#
# Переустановка заказа

#############################################################################

else if ($command == "reinstallOrder") {
    
$orderid = @intval($orderid);

    if (!
$orderid) {
        
$res[status] = "ERROR";
        
$res[errorCode] = "18";
        
$res[errorMsg] = "Не указан идентификатор заказа.";
    }
    else {
        
$order = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where id='$orderid' and todate<>'0000-00-00' and status=='1' and archived=0");
        if (!
$isTest and @mysql_num_rows($order) == 0) {
            
$res[status] = "ERROR";
            
$res[errorCode] = "19";
            
$res[errorMsg] = "Заказ не найден.";
        } 
        else {
            
$order = @mysql_fetch_object($order);
            
$server GetServerById($order->serverid);
            
$tarif GetTarifById($order->tarif);

            if (!
$isTest and !($server->type == "shellscript" and $tarif->scriptReinstall) and $server->type != "vdsmanager" and $server->type != "solusvmopenvz" and $server->type != "solusvmxen" and $server->type != "solusvmxenhvm" and $server->type != "solusvmkvm" and !($server->type == "rootpanel" and ($tarif->vid == "vds" or $tarif->vid == "dedicated"))) {
                
$res[status] = "ERROR";
                
$res[errorCode] = "25";
                
$res[errorMsg] = "Операция не поддерживается для заказов данного типа ($server->type).";
            }
            else {
                if (
$isTest or reinstallUser($order->id,1)) {
                    
$res[status] = "SUCCESS";
                    
$res[orderid] = "$orderid";
                }
                else {
                    
$res[status] = "SUCCESS";
                    
$res[errorCode] = "30";
                    
$res[errorMsg] = "Заявка принята, но по техническим причинам будет обработана в ручном режиме.";
                    
$res[orderid] = "$orderid";
                }
            }
        }

    }
}


#############################################################################
#
# Получение списка заказов

#############################################################################

else if ($command == "getOrders") {
    
$orders = @mysql_query("select *,TO_DAYS(todate)-TO_DAYS(NOW()) as leftdays from orders where uid='$user->id' and archived='0' order by id");
    if (@
mysql_num_rows($orders) == 0) {
        
$res[status] = "ERROR";
        
$res[errorCode] = "26";
        
$res[errorMsg] = "Заказы отсутствуют.";
    } 
    else {
        
$res[status] = "SUCCESS";

        
$i 0;
        while (
$order = @mysql_fetch_object($orders)) {
            
$i++;
            
$tarif GetTarifById($order->tarif);

            
$res[orders][$i][orderid] = $order->id;
            if (
$order->domain) {
                
$res[orders][$i][domain] = $order->domain;
                
$res[orders][$i][domain_reg] = $order->domain_reg;
            }
            
$res[orders][$i][vid] = $tarif->vid;
            
$res[orders][$i][tarifid] = $tarif->id;
            
$res[orders][$i][tarifname] = $tarif->name;
            
$res[orders][$i][orderdate] = $order->orderdate;
            if (
$order->status) {
                
$res[orders][$i][startdate] = $order->startdate;
                
$res[orders][$i][todate] = $order->todate;
                
$res[orders][$i][leftdays] = $order->leftdays;
            }
            
$res[orders][$i][status] = $order->status;
        }
    }
}


#############################################################################
#
# Команда не задана

#############################################################################

else {
    
$res[status] = "ERROR";
    
$res[errorCode] = "8";
    
$res[errorMsg] = "Неизвестная команда.";
}




#############################################################################




                    
}
                    else {
                        
$res[status] = "ERROR";
                        
$res[errorCode] = "7";
                        
$res[errorMsg] = "Указан неправильный пароль или ключ API.";
                    }
                }
                else {
                    
$res[status] = "ERROR";
                    
$res[errorCode] = "6";
                    
$res[errorMsg] = "Не указан пароль или ключ API.";
                }
            }
            else {
                
$res[status] = "ERROR";
                
$res[errorCode] = "5";
                
$res[errorMsg] = "Доступ к API отключен.";
            }
        }
        else {
            
$res[status] = "ERROR";
            
$res[errorCode] = "4";
            
$res[errorMsg] = "Пользователь не найден.";
        }
    }
    else {
        
$res[status] = "ERROR";
        
$res[errorCode] = "3";
        
$res[errorMsg] = "Не указан логин пользователя.";
    }

else {
    
$res[status] = "ERROR";
    
$res[errorCode] = "1";
    
$res[errorMsg] = "Ошибка подключения к БД: $GLOBALerror.";
}

$status $res[status];
$res serialize($res);

$mtime microtime(); $mtime explode(" ",$mtime); $mtime $mtime[1] + $mtime[0]; $tend $mtime;
$totaltime = ($tend $tstart);
$querySeconds sprintf("%f"$totaltime); 

if (
$APILogId) {
    
AddAPILog($login,$command,$status,$res,$APILogId,$querySeconds);
}

header("Content-Type: text/html; charset=utf-8");
print 
$res;

mclose();
?>
Онлайн: 4
Реклама