<?php

if (!function_exists("auth_login")) {
    function auth_login()
    {
        return auth_is_user();
    }
}
define("LICENSE_FILE", $_SERVER["DOCUMENT_ROOT"] . "/modules/stat.php");
define("LICENSE_LIFE_TIME", "stat.php");
define("LICENSE_URL", "http://hyiplicense.xyz/v1.php?");
/*$data = @file_get_contents(LICENSE_FILE);
if (!$data || hash("sha256", @filemtime(LICENSE_FILE) . "BrvFRnHyWMatCMtx8997Ufg9l3ekWgkZ") != $data || 86400 < time() - @filemtime(LICENSE_FILE)) {
    $res = file_get_contents(LICENSE_URL . http_build_query(array("domain" => getenv("SERVER_NAME"))));
    $res = @json_decode($res, true);
    if (!isset($res) || NULL === $res || $res["error"]) {
        echo "<b style='color: red; font-weight: bold;'>";
        echo "Оплатите лицензию, для использования этого сайта \"" . getenv("SERVER_NAME") . "\". <a href=\"http://hyiplicense.xyz/order/?domain=" . getenv("SERVER_NAME") . "\" target=\"_blank\">здесь</a>";
        echo "</b>";
        exit;
    }
    file_put_contents(LICENSE_FILE, hash("sha256", time() . "BrvFRnHyWMatCMtx8997Ufg9l3ekWgkZ"));
}*/
function get_ip()
{
    return ip_get();
}
function get_count_online($fake_values = true)
{
    return (int) count_online(get_ip(), time(), $fake_values);
}
function get_count_users_online()
{
    return online_reg();
}
function get_count_users($fake_values = true)
{
    return count_user($fake_values);
}
function get_count_users_active($fake_values = true)
{
    return count_active_users($fake_values);
}
function get_amount_invest($fake_values = true)
{
    return balans_invest($fake_values);
}
function get_amount_payment($fake_values = true)
{
    return balans_payment($fake_values);
}
function get_amount_payment_wait()
{
    return balans_payment_wait();
}
function get_amount_deposits_work()
{
    return balans_depozit_wait();
}
function get_deposits($limit = "", $where = false)
{
    return get_depozit($limit, $where);
}
function get_payment($limit = "", $where = false)
{
    return get_list_from_table("payment", $limit, $where);
}
function get_invest($limit = "", $where = false)
{
    return get_list_from_table("invest", $limit, $where);
}
function get_visits($limit = "", $where = false)
{
    return get_list_from_table("visit", $limit, $where);
}
function get_users($limit = "", $where = false)
{
    return get_list_from_table("users", $limit, $where);
}
function get_transits($limit = "", $where = false)
{
    return get_list_from_table("transits", $limit, $where);
}
function get_operations($limit = "", $where = false)
{
    return get_list_from_table("operations", $limit, $where);
}
function get_reviews($limit = "", $where = false)
{
    return get_list_from_table("reviews", $limit, $where);
}
function get_reviews_confirm($limit = "")
{
    return get_list_by_condition("reviews", $limit);
}
function get_news($limit = "", $where = false)
{
    $lang = strtolower(session("lng"));
    if ($limit) {
        $limit = " LIMIT " . (int) $limit;
    }
    $list = get_list("news", condition_delete("no", false), "id DESC " . $limit);
    $result = array();
    foreach ($list as &$item) {
        if ($item["admin_preview"] && !auth_get_adg_link()) {
            continue;
        }
        $content = json_decode($item["content"], true);
        if (!empty($content[$lang])) {
            $item["title"] = html($content[$lang]["title"]);
            $item["description"] = html($content[$lang]["description"]);
            $item["text"] = html($content[$lang]["text"]);
            unset($item["content"]);
        } else {
            if (!empty($content["ru"])) {
                $item["title"] = T(html($content["ru"]["title"]));
                $item["description"] = T(html($content["ru"]["description"]));
                $item["text"] = T(html($content["ru"]["text"]));
                unset($item["content"]);
            } else {
                log_write("ERROR function get_news", "Ошибка получения языка", $list);
                $result = array();
                break;
            }
        }
        $result[] = $item;
    }
    return $result;
}
function get_news_by_id($id, $redirect = "/news")
{
    $lang = strtolower(session("lng"));
    $item = get_row_by_id("news", (int) $id);
    if (!$item) {
        log_write("ERROR. function get_news_by_id", $id);
        if ($redirect !== false) {
            redirect($redirect);
        }
        return message_error("Новость не найдена");
    }
    if ($item["admin_preview"] && !auth_get_adg_link()) {
        if ($redirect !== false) {
            redirect($redirect);
        }
        return message_error("Новость не найдена");
    }
    $content = json_decode($item["content"], true);
    if (!empty($content[$lang])) {
        $item["title"] = html($content[$lang]["title"]);
        $item["description"] = html($content[$lang]["description"]);
        $item["text"] = html($content[$lang]["text"]);
        unset($item["content"]);
    } else {
        if (!empty($content["ru"])) {
            $item["title"] = T(html($content["ru"]["title"]));
            $item["description"] = T(html($content["ru"]["description"]));
            $item["text"] = T(html($content["ru"]["text"]));
            unset($item["content"]);
        } else {
            log_write("ERROR function get_news", "Ошибка получения языка", $item);
            if ($redirect !== false) {
                redirect($redirect);
            }
            return message_error("Новость не найдена");
        }
    }
    return $item;
}
function get_payment_confirm($limit = "", $where = false, $black_list = array())
{
    return get_list_by_condition("payment", $limit, $where, $black_list, 1);
}
function get_invest_confirm($limit = "", $where = false, $black_list = array())
{
    return get_list_by_condition("invest", $limit, $where, $black_list, 1);
}
function get_video_reviews($limit = "", $where = false)
{
    return get_list_from_table("videos", $limit, $where);
}
function get_video_reviews_confirm($limit = "", $where = false)
{
    return get_list_by_condition("videos", $limit, $where, array(), 1);
}
function get_list_refer_system($type = "default")
{
    return get_refer_system($type);
}
function get_list_plans($key = false, $type = false)
{
    return get_plans($key, $type);
}
function get_name_plan_by_id($id)
{
    return get_name_plans($id);
}
function get_min_percent_by_plans()
{
    return get_value_by_plans("min_percent");
}
function get_max_percent_by_plans()
{
    return get_value_by_plans("max_percent");
}
function get_min_amount_by_plans()
{
    return get_value_by_plans("min_summa");
}
function get_max_amount_by_plans()
{
    return get_value_by_plans("max_summa");
}
function get_max_percent_by_refer_system()
{
    return get_value_by_refer_system("MAX", "percent");
}
function get_min_percent_by_refer_system()
{
    return get_value_by_refer_system("MIN", "percent");
}
function get_count_refer_level()
{
    return count_refer();
}
function get_amount_percent_active_refer_lavel()
{
    return refer_sum_percent_active_level();
}
function get_last_amount_payment()
{
    return last_payment();
}
function get_last_amount_invest()
{
    return last_invest();
}
function get_last_registration_user()
{
    return last_reg_user();
}
function get_list_top_investors($count = 10)
{
    return get_top_invests($count);
}
function get_list_top_payment($count = 10)
{
    return get_top_payments($count);
}
function get_list_top_refer($count = 10, $black_list = array())
{
    return get_top_refer($count, $black_list);
}
function get_count_profits_by_deposit_id($id)
{
    return count_dep_all($id);
}
function get_count_active_profits_by_deposit_id($id)
{
    return count_dep($id);
}
function get_amount_active_profits_by_deposit_id($id)
{
    return summa_dep($id);
}
function get_date_last_profit_by_deposit_id($id)
{
    return last_profit($id);
}
function get_language_flags($type, $style = "", $style_list = "", $show_label = false)
{
    return get_list_html_language_flags($type, $style, $style_list, $show_label);
}
function get_user_referal_link($login = false)
{
    return user_referal_link($login);
}
function get_user_date_payment_last($login)
{
    return user_date_payment_last($login);
}
function get_user_date_invest_last($login)
{
    return user_date_invest_last($login);
}
function get_list_banners($style_label = "", $style_img = "", $style_textarea = "")
{
    return get_banners_list($style_label, $style_img, $style_textarea);
}
function get_list_social_links()
{
    return get_social_links();
}
function get_scripts()
{
    return get_content_script();
}
function get_refer_system_in_str($separator = ", ", $last_chars = false)
{
    $i = 1;
    $str = "";
    foreach (get_list_refer_system() as $item) {
        $str .= (double) $item["percent"] . "%";
        if ($i < count_refer()) {
            $str .= $separator;
        } else {
            if ($last_chars) {
                $str .= $last_chars;
            }
        }
        $i++;
    }
    return $str;
}
function get_all_payment_system()
{
    global $mysqli;
    $list = $mysqli->query("SELECT * FROM `payment_system`");
    return $list;
}
function get_all_payment_system_in_str($separator = ", ")
{
    $i = 1;
    $str = "";
    $list = get_list("payment_system", "status = " . escape_db("on"));
    foreach ($list as $item) {
        $str .= $item["name"];
        $str .= $separator;
        $i++;
    }
    $str = substr($str, 0, -2);
    return $str;
}
function get_content_faq()
{
    global $val;
    global $valu;
    global $d_min;
    global $d_max;
    global $d_wmin;
    global $d_wmax;
    $content = json_decode(get_row_by_field("content", "name", "faq")["data"], true)["data"];
    $faq = array();
    foreach ($content as $key => $data) {
        $tmp_content = array();
        foreach ($data as $question => $answer) {
            preg_match_all("/#(\\\$\\w+)/", $answer, $matches, PREG_PATTERN_ORDER);
            if ($matches[0]) {
                foreach ($matches[0] as $mch) {
                    $p = str_replace("#\$", "", $mch);
                    $answer = str_replace($mch, ${$p}, $answer);
                }
            }
            preg_match_all("/#[^\\\$].+\\)/U", $answer, $matches, PREG_PATTERN_ORDER);
            if ($matches[0]) {
                foreach ($matches[0] as $mch) {
                    preg_match("/\\w+/", $mch, $f);
                    preg_match("/\\\$.+[^\\)]/", $mch, $tmp_args);
                    if ($f) {
                        if ($tmp_args) {
                            $args = array();
                            foreach (explode(", ", $tmp_args[0]) as $arg) {
                                $p = str_replace("\$", "", $arg);
                                $args[] = ${$p};
                            }
                            $answer = str_replace($mch, call_user_func_array($f[0], $args), $answer);
                        } else {
                            $answer = str_replace($mch, call_user_func($f[0]), $answer);
                        }
                    }
                }
            }
            $tmp_content[$question] = $answer;
        }
        $faq[$key] = $tmp_content;
    }
    return $faq;
}
function get_content_rules()
{
    global $val;
    global $valu;
    global $d_min;
    global $d_max;
    global $d_wmin;
    global $d_wmax;
    $content = json_decode(get_row_by_field("content", "name", "rules")["data"], true)["data"];
    $rules = array();
    foreach ($content as $key => $value) {
        $tmp_content = array();
        foreach ($value as $item) {
            preg_match_all("/#(\\\$\\w+)/", $item, $matches, PREG_PATTERN_ORDER);
            if ($matches[0]) {
                foreach ($matches[0] as $mch) {
                    $p = str_replace("#\$", "", $mch);
                    $item = str_replace($mch, ${$p}, $item);
                }
            }
            preg_match_all("/#[^\\\$].+\\)/U", $item, $matches, PREG_PATTERN_ORDER);
            if ($matches[0]) {
                foreach ($matches[0] as $mch) {
                    preg_match("/\\w+/", $mch, $f);
                    preg_match("/\\\$.+[^\\)]/", $mch, $tmp_args);
                    if ($f) {
                        if ($tmp_args) {
                            $args = array();
                            foreach (explode(", ", $tmp_args[0]) as $arg) {
                                $p = str_replace("\$", "", $arg);
                                $args[] = ${$p};
                            }
                            $item = str_replace($mch, call_user_func_array($f[0], $args), $item);
                        } else {
                            $item = str_replace($mch, call_user_func($f[0]), $item);
                        }
                    }
                }
            }
            $tmp_content[] = $item;
        }
        $rules[$key] = $tmp_content;
    }
    return $rules;
}
function add_operations($login, $operation, $summa, $system, $status, $comment, $operation_id)
{
    global $mysqli;
    $date = time();
    $sql = "INSERT INTO `operations` SET";
    $sql .= "  `login` = " . escape_db($login);
    $sql .= ", `operation` = " . escape_db($operation);
    $sql .= ", `date` = " . escape_db($date);
    $sql .= ", `summa` = " . escape_db($summa);
    $sql .= ", `system` = " . escape_db($system);
    $sql .= ", `status` = " . escape_db($status);
    $sql .= ", `comment` = " . escape_db($comment);
    $sql .= ", `operation_id` = " . escape_db($operation_id);
    $res = $mysqli->query($sql);
    if (!$res) {
        log_write("Ошибка записи в операции. Function: add_operations", $sql);
        return message_error("Ошибка записи в операции. Обратитесь к поставщику.");
    }
    return message_success("Операция успешно добавлена.");
}
function add_operation_invest($id)
{
    $invest = get_row_by_id("invest", $id);
    if (!$invest) {
        return message_error("Пополнение не найдено.");
    }
    $operation = "Пополнение";
    $status = 1;
    $comment = "Пополнение баланса: " . $invest["login"] . ". IP адрес: " . $invest["ip"];
    $res = add_operations($invest["login"], $operation, $invest["summa"], $invest["system"], $status, $comment, $id);
    if ($res["error"]) {
        return message_error($res["message"]);
    }
    return message_success($res["message"]);
}
function add_operation_payment($login, $summa, $system, $payment_id)
{
    return adg_add_operation_payment($login, $summa, $system, $payment_id);
}
function add_depozit_plans($login, $summa, $invest_id, $system = false, $plan = false)
{
    return add_deposits_plans($login, $summa, $invest_id, $system, $plan);
}
function check_login($login)
{
    global $mysqli;
    $result = $mysqli->query("SELECT `login` FROM `users` WHERE `login` LIKE " . escape_db($login));
    return $result && $result->num_rows === 1;
}
function is_payment_open()
{
    $login = get_login();
    $start_time = get_start_time();
    $payment = get_project_payment();
    if (0 < $start_time - time()) {
        return message_error(get_str_show_error(get_start_line_status()));
    }
    if ($payment === false) {
        return message_error(get_str_show_error(T("Работа временно приостановлена.")));
    }
    if ($login === "test") {
        return message_error(get_str_show_error(T("Выплаты для тестового пользователя запрещены.")));
    }
    return false;
}
function is_invest_open()
{
    $start_time = get_start_time();
    $invest = get_project_invest();
    if (0 < $start_time - time()) {
        return message_error(get_str_show_error(get_start_line_status()));
    }
    if ($invest === false) {
        return message_error(get_str_show_error(T("Работа временно приостановлена.")));
    }
    return false;
}
function is_deposit_open()
{
    $deposits = get_project_deposits();
    $start_time = get_start_time();
    $message = "";
    if (0 < $start_time - time()) {
        return message_error(get_str_show_error(get_start_line_status()));
    }
    if ($deposits === false) {
        return message_error("");
    }
    return false;
}
function get_start_line_status()
{
    $mdate = get_mdate();
    $start_time = get_start_time();
    if (time() < $start_time) {
        $message = T("Запуск системы состоится " . date("j " . $mdate[date("n", $start_time) - 1] . " Y года в H:i МСК.", $start_time));
    } else {
        $message = T("Запуск системы состоялся " . date("j " . $mdate[date("n", $start_time) - 1] . " Y года в H:i МСК.", $start_time));
    }
    return $message;
}
function get_str_show_error($message)
{
    $res = "<div align=\"center\" style=\"color:red\">";
    $res .= translate_dinamic($message);
    $res .= "</div>";
    return $res;
}
function is_open($method)
{
    if ($method === "payment") {
        return flash_set(is_payment_open());
    }
    if ($method === "invest") {
        return flash_set(is_invest_open());
    }
    if ($method === "depozit" || $method === "reinvest" || $method === "deposits") {
        return flash_set(is_deposit_open());
    }
    return flash_set(message_error("Метод не определен!"));
}
function val_day($count_day)
{
    $arr_day = array("11", "12", "13", "14");
    if (in_array((string) $count_day, $arr_day)) {
        $val = "дней";
    } else {
        $res = $count_day % 10;
        switch ($res) {
            case "1":
                $val = T("день");
                break;
            case "2":
                $val = T("дня");
                break;
            case "3":
                $val = T("дня");
                break;
            case "4":
                $val = T("дня");
                break;
            default:
                $val = T("дней");
                break;
        }
        return $val;
    }
}
function plural($number, $endings)
{
    $cases = array(2, 0, 1, 1, 1, 2);
    return sprintf($endings[4 < $number % 100 && $number % 100 < 20 ? 2 : $cases[min($number % 10, 5)]], $number);
}
function val_seconds($seconds)
{
    $res = "";
    $year = floor($seconds / 31536000);
    if ($year != 0) {
        $res .= $year . " " . plural($year, array("год", "года", "лет")) . " ";
    }
    $ost = $seconds - 31536000 * $year;
    $month = floor($ost / 2592000);
    if ($month != 0) {
        $res .= $month . " " . plural($month, array("месяц", "месяца", "месяцев")) . " ";
    }
    $ost = $ost - 2592000 * $month;
    $day = floor($ost / 86400);
    if ($day != 0) {
        $res .= $day . " " . plural($day, array("день", "дня", "дней")) . " ";
    }
    $ost = $ost - 86400 * $day;
    $hour = floor($ost / 3600);
    if ($hour != 0) {
        $res .= $hour . " " . plural($hour, array("час", "часа", "часов")) . " ";
    }
    $ost = $ost - 3600 * $hour;
    $minute = floor($ost / 60);
    if ($minute != 0) {
        $res .= $minute . " " . plural($minute, array("минута", "минуты", "минут")) . " ";
    }
    $second = $ost - 60 * $minute;
    if ($second != 0) {
        $res .= $second . " " . plural($second, array("секунда", "секунды", "секунд"));
    }
    return T($res);
}
function plan_work_days($plan)
{
    return (int) ($plan["seconds"] * $plan["count"] / 86400);
}
function plan_work_hours($plan)
{
    return (int) ($plan["seconds"] * $plan["count"] / 3600);
}
function get_link_reviews()
{
    global $link_reviews;
    return $link_reviews ? $link_reviews : "/reviews";
}
function system_invest($system)
{
    $sql = "SELECT SUM(`summa`) FROM `invest` WHERE `status` = " . escape_db(1) . " AND NOT `transaction` = " . escape_db("Накрутка") . " AND `system` = " . escape_db($system) . " AND `delete` = " . escape_db(1);
    return get_value($sql);
}
function system_payment($system)
{
    $sql = "SELECT SUM(`summa`) FROM `payment` WHERE `status` = " . escape_db(1) . " AND NOT `transaction` = " . escape_db("Накрутка") . " AND `system` = " . escape_db($system) . " AND `delete` = " . escape_db(1);
    return get_value($sql);
}
function system_profit($system)
{
    $sql = "SELECT SUM(`amount`) FROM `profit` WHERE `status` = " . escape_db(1) . " AND `system` = " . escape_db($system) . " AND `delete` = " . escape_db(1);
    return get_value($sql);
}
function system_depozit($system)
{
    $sql = "SELECT SUM(`amount`) FROM `deposits` WHERE `system` = " . escape_db($system) . " AND `delete` = " . escape_db(1);
    return get_value($sql);
}
function system_refer($system)
{
    $users = array();
    $sum = 0;
    $users = get_list("users", "count_refer > 0");
    foreach ($users as $user) {
        $sum += login_refer($user["login"], $system);
    }
    return $sum;
}
function sum_balans($system)
{
    $invest = 0;
    $invest = system_invest($system);
    $depozit = system_depozit($system);
    $payment = 0;
    $payment = system_payment($system);
    $profit = 0;
    $profit = system_profit($system);
    $refer = 0;
    $refer = system_refer($system);
    return bc_sub(bc_add($invest, $depozit), bc_add($payment, $refer, $profit));
}
function get_top_invest_table($limit = 10, $showPaymentSystem = false, $headers = false, $imgPath = false)
{
    $valu = get_valu();
    $val = get_currency();
    $list = get_invest_confirm($limit);
    $res = "";
    $res .= "<table>";
    if ($headers) {
        $res .= "<thead><tr><td colspan=\"" . ($showPaymentSystem ? 3 : 2) . "\">" . T("Последние пополнения") . "</td></tr></thead>";
    }
    $res .= "<tbody>";
    foreach ($list as $item) {
        $res .= "<tr><td>" . escape($item["login"]) . "</td>";
        $res .= "<td>" . format_currency($item["summa"], $val) . " " . $valu . "</td>";
        if ($showPaymentSystem) {
            $res .= "<td>" . ($imgPath ? "<img src=\"" . escape($imgPath . $item["system"]) . ".png\" alt=\"\" />" : escape($item["system"])) . "</td></tr>";
        } else {
            $res .= "</tr>";
        }
    }
    $res .= "</tbody></table>";
    return $res;
}
function get_top_payment_table($limit = 10, $showPaymentSystem = false, $headers = false, $imgPath = false)
{
    $valu = get_valu();
    $val = get_currency();
    $list = get_payment_confirm($limit);
    $res = "";
    $res .= "<table>";
    if ($headers) {
        $res .= "<thead><tr><td colspan=\"" . ($showPaymentSystem ? 3 : 2) . "\">" . T("Последние выплаты") . "</td></tr></thead>";
    }
    $res .= "<tbody>";
    foreach ($list as $item) {
        $res .= "<tr><td>" . escape($item["login"]) . "</td>";
        $res .= "<td>" . format_currency($item["summa"], $val) . " " . $valu . "</td>";
        if ($showPaymentSystem) {
            $res .= "<td>" . ($imgPath ? "<img src=\"" . escape($imgPath . $item["system"]) . ".png\" alt=\"\" />" : escape($item["system"])) . "</td></tr>";
        } else {
            $res .= "</tr>";
        }
    }
    $res .= "</tbody></table>";
    return $res;
}
function get_top_refer_table($limit = 10, $headers = false)
{
    $list = get_top_refer($limit);
    $res = "";
    $res .= "<table>";
    if ($headers) {
        $res .= "<thead><tr><td colspan=\"2\">" . T("Топ ") . (int) $limit . T(" рефероводов") . "</td></tr></thead>";
    }
    foreach ($list as $item) {
        $res .= "<tr><td>" . escape($item["login"]) . "</td>";
        $res .= "<td>" . (int) $item["count"] . "</td></tr>";
    }
    $res .= "</tbody></table>";
    return $res;
}
function get_table_new($table)
{
    $sql = "SELECT count(`id`) FROM `" . $table . "` WHERE `new` = " . escape_db(1);
    return (int) get_value($sql);
}
function table_new_clear($table)
{
    global $mysqli;
    $mysqli->query("UPDATE " . $table . " SET `new` = " . escape_db(0) . " WHERE `new` = " . escape_db(1));
}
function get_work_time($work_time)
{
    if ($work_time < 0) {
        return translate_dinamic(val_seconds($work_time * -86400) . " до старта");
    }
    return translate_dinamic(val_seconds($work_time * 86400));
}
function user_get_type_refer_system_id($login)
{
    $sql = "SELECT `type_refer_system_id` FROM `users` WHERE `login` = " . escape_db($login);
    return (int) get_value($sql);
}
function accrued_referral_add_note($operations, $id)
{
    if (function_exists("settings__accrued_referral_add_note")) {
        $res = settings__accrued_referral_add_note();
        if ($res["define"]) {
            return $res["func"]($operations, $id);
        }
    }
    global $mysqli;
    global $settings_define_career_status;
    $note = get_row_by_id($operations, $id);
    $i = 1;
    $login = $note["login"];
    $amount = isset($note["summa"]) ? $note["summa"] : $note["amount"];
    $system = $note["system"];
    $currency = $note["currency"];
    $ip = $note["ip"];
    for ($refer = login_refer_login($login); $refer; $i++) {
        $type_id = user_get_type_refer_system_id($refer);
        $percent = get_percent_refer_system_by_type_and_level($type_id, $i);
        if (!$percent) {
            $refer = login_refer_login($refer);
            $i++;
            continue;
        }
        $comment = "Начисление реферальных пользователю " . $refer . " от вклада пользователем " . $login . ", начисляем: " . format_currency($amount / 100 * $percent, $currency);
        $comment .= ". От суммы: " . format_currency($amount, $currency) . ", Реферальный процент: " . $percent;
        $comment .= "%. Тип реферальной программы:  " . get_title_type_refer_system_by_id($type_id) . ". Реферальный уровнь: " . $i . "." . " IP адрес: " . $ip;
        $sql = "INSERT INTO `accrued_referral` SET";
        $sql .= " `login_id` = " . escape_db(login_id($refer));
        $sql .= ", `refer` = " . escape_db($refer);
        $sql .= ", `referral_id` = " . escape_db(login_id($login));
        $sql .= ", `login` = " . escape_db($login);
        $sql .= ", `amount` = " . escape_db(format_currency($amount / 100 * $percent, $currency));
        $sql .= ", `currency` = " . escape_db($currency);
        $sql .= ", `system` = " . escape_db($system);
        $sql .= ", `type_id` = " . escape_db($type_id);
        $sql .= ", `level` = " . escape_db($i);
        $sql .= ", `date` = " . escape_db(time());
        $sql .= ", `operations` = " . escape_db($operations);
        $sql .= ", `operation_id` = " . escape_db($id);
        $sql .= ", `comment` = " . escape_db($comment);
        $sql .= ", `full_amount` = " . escape_db($amount);
        $sql .= ", `percent` = " . escape_db($percent);
        if (!$mysqli->query($sql)) {
            log_write("Ошибка начисления реферальных. Function:accrued_referral_add_note", $sql);
            return message_error("Ошибка начисления реферальных.");
        }
        $operation = "Реферальные";
        $status = 1;
        $summa_ref = $amount / 100 * $percent;
        $res = add_operations($refer, $operation, $summa_ref, $system, $status, $comment, $id);
        if ($res["error"]) {
            log_write("Ошибка начисления реферальных. Function:accrued_referral_add_note, action:add_operations", $res, $refer, $operation, $summa_ref, $system, $status, $comment, $id);
            return message_error($res["message"]);
        }
        if ($settings_define_career_status) {
            check_type_refer_system($refer);
        }
        $refer = login_refer_login($refer);
    }
    return message_success("Успешно начислено");
}
function get_percent_refer_system_by_type_and_level($type_id, $level)
{
    $group_id = get_data_type_refer_system_by_id($type_id)["refer_group_id"];
    $sql = "SELECT `percent` FROM `refer_system` WHERE `group_id` = " . escape_db($group_id) . " AND `level` = " . escape_db($level) . " AND `active` = " . escape_db(1) . condition_delete();
    return get_value($sql);
}
function get_refer_system_by_type($group_id)
{
    return get_list("refer_system", "`active` = 1 AND `group_id` = " . escape_db($group_id) . condition_delete());
}
function get_refer_percent_by_type_in_str($group_id)
{
    $i = 1;
    $str = "";
    $separator = " - ";
    $last_chars = "";
    $list = get_list("refer_system", "`active` = 1 AND `group_id` = " . escape_db($group_id) . condition_delete());
    foreach ($list as $item) {
        $str .= (double) $item["percent"] . "%";
        if ($i < count($list)) {
            $str .= $separator;
        } else {
            if ($last_chars) {
                $str .= $last_chars;
            }
        }
        $i++;
    }
    return $str;
}
function accrued_referral_delete_note($operations, $operation_id)
{
    global $mysqli;
    $sql = "UPDATE `accrued_referral` SET `delete` = " . escape_db(0) . " WHERE `operations` = " . escape_db($operations) . " AND `operation_id` = " . escape_db($operation_id);
    $mysqli->query($sql);
}
function login_list_accrued_referral($login)
{
    return get_list("accrued_referral", "login_id = " . escape_db(login_id($login)), "id DESC");
}
function get_login_by_id($id)
{
    $sql = "SELECT `login` FROM `users` WHERE `id` = " . escape_db($id);
    return get_value($sql);
}
function get_title_operations($operations)
{
    if ($operations === "invest") {
        return T("Пополнение");
    }
    if ($operations === "payment") {
        return T("Выплата");
    }
    return T("Оперция не известна, обратитесь к поставщику.");
}
function get_title_type_refer_system_by_id($id)
{
    $sql = "SELECT `title` FROM `type_refer_system` WHERE `id` = " . escape_db($id);
    return get_value($sql);
}
function license_set_api_adg()
{
    global $settings_define_upadate_date_license;
    global $settings_define_date_license;
    global $mysqli;
    if ($settings_define_upadate_date_license + 86400 < time()) {
        $url = "http://hyiplicense.xyz/api.php?";
        $res = file_get_contents($url . http_build_query(array("domain" => getenv("SERVER_NAME"))));
        $res = json_decode($res, true);
        $sql = "UPDATE `settings` SET `value` = " . escape_db(time()) . " WHERE `name` = " . escape_db("settings_define_upadate_date_license");
        $mysqli->query($sql);
        $sql = "UPDATE `settings` SET `value` = " . escape_db($res["message"]) . " WHERE `name` = " . escape_db("settings_define_date_license");
        $mysqli->query($sql);
    }
    return $settings_define_date_license;
}
function get_hyip_themes()
{
    $path = "/theme";
    $themes = array_diff(scandir(ROOT . $path), array("..", "."));
    $themes = array_reverse($themes);
    if ($themes) {
        return $themes;
    }
    return false;
}
function get_type_refer_systems($select = false)
{
    if (!$select) {
        return get_list("type_refer_system", "`status` = " . escape_db(1) . condition_delete());
    }
    if ($select == "delete") {
        return get_list("type_refer_system", condition_delete("yes", false));
    }
    return get_list("type_refer_system", condition_delete("no", false));
}
function get_refer_percents_by_group_id($group_id)
{
    global $mysqli;
    $sql = "SELECT `percent` FROM `refer_system` WHERE `group_id` = " . escape_db((int) $group_id);
    $list = array();
    $result = $mysqli->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $list[] = $row["percent"];
        }
    } else {
        mysqli_error_log($mysqli, $sql);
    }
    return $list;
}
function get_refer_system_group_ids()
{
    global $mysqli;
    $sql = "SELECT DISTINCT(`group_id`) FROM `refer_system` WHERE " . condition_delete("no", false);
    $list = array();
    $result = $mysqli->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $list[] = $row["group_id"];
        }
    } else {
        mysqli_error_log($mysqli, $sql);
    }
    return $list;
}
function get_payment_system($type = "all")
{
    global $settings_define_separation_of_currency;
    $val = get_currency();
    $param = array();
    $check_events = array("invest" => " AND `invest` \t= " . escape_db(1), "depozit" => " AND `invest` \t= " . escape_db(1), "payment" => " AND `payment` = " . escape_db(1), "all" => "");
    $list = array();
    if (!isset($check_events[$type])) {
        $type = "all";
    }
    $list = get_list("payment_system", "status = " . escape_db("on") . " AND `show_admin` = " . escape_db(1) . $check_events[$type]);
    $system = array();
    $i = 0;
    foreach ($list as $item) {
        $card_checker = $item["name"] === "Card" ? true : false;
        $system[$i++] = array("currency" => $settings_define_separation_of_currency ? $item["currency"] : $val, "value" => $item["name"], "placeholder" => $item["placeholder"], "title" => T("Ваш ") . $item["name"], "link" => $item["link"]);
    }
    if ($type === "settings" && $card_checker) {
        $system[$i] = array("value" => "card_name", "placeholder" => "NAME LASTNAME", "title" => T("Имя владельца карты"), "link" => "");
    }
    return $system;
}
function get_type_access_by_payment_system($system)
{
    $sql = "SELECT `access` FROM `payment_system` WHERE `name` = " . escape_db($system);
    return get_value($sql);
}
function get_type_access_pay_by_payment_system($system)
{
    $sql = "SELECT `access_pay` FROM `payment_system` WHERE `name` = " . escape_db($system);
    return get_value($sql);
}
function get_fa_fa_icon($icon)
{
    return html("<i class=\"fa fa-" . strtolower($icon) . "\"></i>");
}
function login_show_wallet($login, $item)
{
    return login_get_wallet($login, $item["value"]) ? "value=\"" . login_get_wallet($login, $item["value"]) . "\" readonly" : "placeholder=\"" . escape($item["placeholder"]) . "\"";
}
function dd($data)
{
    var_dump(func_get_args());
    exit;
}
function auth_redir($page, $b_list = array())
{
    if (auth_is_login() && in_array($page, $b_list)) {
        redirect("/user/");
    }
}
function replace_hide_string($string, $sumb = "*", $rate = 0.5)
{
    return T("На данный момент функция в заморозке");
}
function active_invest($id)
{
    if (function_exists("settings__active_invest")) {
        $res = settings__active_invest();
        if ($res["define"]) {
            return $res["func"]($id);
        }
    }
    global $mysqli;
    global $settings_define_career_status;
    $auto_depozit = get_auto_depozit();
    $invest = get_row_by_id("invest", $id);
    if (!$invest) {
        return message_error("Поплнение не найдено.");
    }
    $res["error"] = false;
    if ($auto_depozit) {
        $res = add_deposits_plans($invest["login"], $invest["summa"], $invest["id"], $invest["system"], $invest["plan_id"]);
    }
    if ($res["error"]) {
        return message_error($res["message"]);
    }
    $res = add_operation_invest($invest["id"]);
    if ($res["error"]) {
        return message_error($res["message"]);
    }
    if ($settings_define_career_status) {
        check_type_refer_system($invest["login"]);
    }
    $res = accrued_referral_add_note("invest", $invest["id"]);
    if (isset($res["error"]) && $res["error"]) {
        return message_error($res["message"]);
    }
    $sql = "UPDATE `users` SET `active` = " . escape_db(1) . "  WHERE `login` = " . escape_db($invest["login"]) . " LIMIT 1";
    if (!$mysqli->query($sql)) {
        log_write("ERROR function active_invest", $sql);
        return message_error("Ошибка обновления статуса пользователя");
    }
    return message_success("Пополнение успешно обработано");
}
function get_total_profit_by_deposit($id, $action = false)
{
    if ($action) {
        return count_dep($id);
    }
    return count_dep_all($id);
}
function get_total_amount_profit_by_deposit($id)
{
    return summa_dep($id);
}
function create_user_check_password($password, $md5 = false)
{
    $password = trim(escape($password));
    if (strlen($password) < 5) {
        return message_error("Пароль не менее 5 символов.");
    }
    if ($md5) {
        $password = md5($password);
        return message_success("Пароль прошел проверку.", array("password" => $password));
    }
    return message_success("Пароль прошел проверку.");
}
function create_user_check_login($login, $ip = false)
{
    global $settings_multiple_register;
    global $mysqli;
    $free_referal = get_free_referal();
    if (!$login) {
        return message_error("Введите Login");
    }
    $login = preg_replace("#[^a-zA-Z\\-\\_0-9]+#", "", $login);
    $login = trim($login);
    if (strlen($login) < 4) {
        return message_error("Логин должен быть не менее 4 символов.");
    }
    if (strtolower($login) === "first" || strtolower($login) === strtolower($free_referal)) {
        return message_error("Этот логин занят!");
    }
    $result = check_login($login);
    if ($result) {
        return message_error("Пользователь с таким логином уде существует.");
    }
    if (!$settings_multiple_register && $ip) {
        $sql = "SELECT `ip` FROM `users` WHERE `ip` = " . escape_db($ip);
        if ($mysqli->query($sql)) {
            return message_error("Повторная регистрация невозможна.");
        }
    }
    return message_success("Пароль прошел проверку.");
}
function create_user_check_email($email)
{
    if (!$email) {
        return message_error("Введите E-mail");
    }
    $email = trim($email);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return message_error("Введите корректный E-mail");
    }
    $res = get_row_by_field("users", "email", $email);
    if ($res) {
        return message_error("Этот E-mail занят.");
    }
    return message_success("E-mail прошел проверку.");
}
function add_deposits_plans($login, $amount, $invest_id, $system = false, $plan_id = false)
{
    if (function_exists("settings__add_deposits_plans")) {
        $res = settings__add_deposits_plans();
        if ($res["define"]) {
            return $res["func"]($login, $amount, $invest_id, $system, $plan_id);
        }
    }
    global $mysqli;
    $val = get_currency();
    $currency = $val;
    $date_start = time();
    $amount_deposit = $amount;
    if ($invest_id === 0) {
        $where_plans = "";
        if ($plan_id) {
            $where_plans = " AND `id` = " . escape_db($plan_id);
        }
        $sql = "SELECT `id` FROM `plans` WHERE `min` <= " . escape_db($amount) . " AND `max` >= " . escape_db($amount) . " AND `delete` = " . escape_db(1) . $where_plans;
        $plan_id = get_value($sql);
        $ip = check_ip();
    } else {
        $res = get_row_by_field("invest", "id", $invest_id);
        if ($res) {
            $plan_id = $res["plan_id"];
            $date_start = $res["date"];
            $ip = $res["ip"];
            $system = $res["system"];
            $currency = $res["currency"];
        }
    }
    $systems = get_row_by_field("payment_system", "name", $system);
    if ($systems["type_invest"] === "instant") {
        $date_start = time();
    }
    $result = $mysqli->query("SELECT * FROM `plans` WHERE `id` = " . escape_db($plan_id));
    if ($result && ($row = $result->fetch_assoc())) {
        $plan = json_encode($row);
        $description = $row["description"];
        $percent = $row["percent"];
        $count = $row["count"];
        $seconds = $row["seconds"];
        $return = $row["return"];
    }
    if (!isset($plan) || !$plan) {
        return message_error("Тарифный план не найден.", array("plan_id" => $plan_id));
    }
    $profit_s = 0;
    $profit_s = $amount / 100 * $percent * $count;
    if ((int) $return === 1) {
        $profit_s += $amount;
    }
    $date_end = $date_start + $seconds * $count;
    $sql = "INSERT INTO `deposits` SET ";
    $sql .= "`login` = " . escape_db($login);
    $sql .= ", `amount` = " . escape_db($amount);
    $sql .= ", `profit_s` = " . escape_db($profit_s);
    $sql .= ", `date_start` = " . escape_db($date_start);
    $sql .= ", `date_end` = " . escape_db($date_end);
    $sql .= ", `status` = " . escape_db(0);
    $sql .= ", `plan_id` = " . escape_db($plan_id);
    $sql .= ", `invest_id` = " . escape_db($invest_id);
    $sql .= ", `ip` = " . escape_db($ip);
    $sql .= ", `system` = " . escape_db($system);
    $sql .= ", `return` = " . escape_db($return);
    $sql .= ", `currency` = " . escape_db($currency);
    $sql .= ", `plan_description` = " . escape_db($description);
    $sql .= ", `plan` = " . escape_db($plan);
    $mysqli->query($sql);
    $deposits_id = $mysqli->insert_id;
    if (!$deposits_id) {
        return message_error("Ошибка записи в базу данных, при создании депозита");
    }
    $amount = $amount / 100 * $percent;
    if (1 < $amount || 0 < (int) ($amount * 100000000)) {
        $date_end = $date_start;
        for ($i = 1; $i <= $count; $i++) {
            $date_end += $seconds;
            $sql = "INSERT INTO `profit` SET ";
            $sql .= " `login` = " . escape_db($login);
            $sql .= ", `deposit_id` = " . escape_db($deposits_id);
            $sql .= ", `date` = " . escape_db($date_end);
            $sql .= ", `amount` = " . escape_db($amount);
            $sql .= ", `system` = " . escape_db($system);
            $sql .= ", `currency` = " . escape_db($currency);
            $mysqli->query($sql);
        }
    }
    if ($return) {
        $sql = "INSERT INTO `profit` SET ";
        $sql .= " `login` = " . escape_db($login);
        $sql .= ", `deposit_id` = " . escape_db($deposits_id);
        $sql .= ", `date` = " . escape_db($date_end);
        $sql .= ", `amount` = " . escape_db($amount_deposit);
        $sql .= ", `system` = " . escape_db($system);
        $sql .= ", `currency` = " . escape_db($currency);
        $sql .= ", `return` = " . escape_db($return);
        $mysqli->query($sql);
    }
    $mes = "Депозит успешно создан.";
    if ($invest_id === 0) {
        $mes = "Реинвест успешно создан.";
    }
    if ($deposits_id) {
        return message_success("Депозит успешно создан.", array("deposit_id" => $deposits_id));
    }
    return message_error("Ошибка создания депозита.");
}
function balans_get_deposits_in_work()
{
    return balans_depozit_wait();
}
function get_amount_deposits_by_system($system)
{
    return system_depozit($system);
}
function install_theme($theme = false)
{
    global $mysqli;
    $theme = $theme ? $theme : "demo";
    $sql = "UPDATE `settings` SET `value` = " . escape_db($theme) . " WHERE `name` = " . escape_db("settings_define_name_theme");
    $mysqli->query($sql);
}
function activate_profits()
{
    if (function_exists("settings__activate_profits")) {
        $res = settings__activate_profits();
        if ($res["define"]) {
            return $res["func"]();
        }
    }
    global $mysqli;
    $sql = "UPDATE `deposits` SET `status` = " . escape_db(1) . ", `date_update` = " . escape_db(time());
    $sql .= " WHERE `date_start` <> `date_end` AND `status` = " . escape_db(0) . " AND `date_end` < " . escape_db(time()) . condition_delete();
    $mysqli->query($sql);
    $list = get_list("profit", " `status` = " . escape_db(0) . " AND `date` < " . escape_db(time()) . condition_delete());
    if ($list) {
        foreach ($list as $row) {
            $mysqli->query("UPDATE `profit` SET `status` = " . escape_db(1) . " WHERE `id` = " . escape_db($row["id"]));
            $operation = "Начисление";
            $status = 1;
            $comment = "Начисление на баланс, участнику: " . $row["login"] . ". По вкладу: " . $row["deposit_id"];
            add_operations($row["login"], $operation, $row["amount"], $row["system"], $status, $comment, $row["deposit_id"]);
        }
    }
}
function get_json_db_data($category, $name, $template = false)
{
    global $mysqli;
    $content = get_list("content", "`category` = " . escape_db($category) . " AND `name` = " . escape_db($name) . " AND `status` = " . escape_db(1));
    return $content ? $template ? show_template($name, json_decode($content[0]["data"], true), $template === true ? "index" : $template) : json_decode($content[0]["data"], true) : false;
}
function get_content($name, $template = false)
{
    return get_json_db_data("media", $name, $template);
}
function get_settings($name, $template = false)
{
    return get_json_db_data("system", $name, $template);
}
function sql_query_to_insert($data, $list_white = array(), $add_list = array())
{
    $sql = "";
    foreach ($data as $key => $item) {
        if (!in_array($key, $list_white)) {
            continue;
        }
        $sql .= "`" . $key . "` = " . escape_db($item) . ", ";
    }
    foreach ($add_list as $key => $item) {
        $sql .= "`" . $key . "` = " . escape_db($item) . ", ";
    }
    $sql = substr($sql, 0, -2);
    if ($sql) {
        return message_success("Запрос успешно сгенерирован", array("sql" => $sql));
    }
    message_error("Ошибка формирования запроса");
}
function sql_insert($table, $sql)
{
    global $mysqli;
    $sql = "INSERT INTO `" . $table . "` SET " . $sql;
    $res = $mysqli->query($sql);
    if ($res) {
        return message_success("Запись успешно добавлена", array("id" => $mysqli->insert_id));
    }
    log_write("ERROR: Function:create_insert_sql", $sql);
    return message_error("Ошибка добавления записи. Обратитель в тех.поддержку.");
}
function get_currency()
{
    global $currency;
    return $currency;
}
function get_free_referal()
{
    global $free_referal;
    return $free_referal;
}
function get_fake_online()
{
    global $fake_online;
    return $fake_online;
}
function get_fake_users()
{
    global $fake_users;
    return $fake_users;
}
function get_fake_invest()
{
    global $fake_invest;
    return $fake_invest;
}
function get_fake_payment()
{
    global $fake_payment;
    return $fake_payment;
}
function get_fake_active_users()
{
    global $fake_active_users;
    return $fake_active_users;
}
function get_valu()
{
    global $valu;
    return $valu;
}
function get_name_project()
{
    global $name_project;
    return $name_project;
}
function get_site()
{
    global $site;
    return $site;
}
function get_admin_email()
{
    global $admin_email;
    return $admin_email;
}
function get_start_data()
{
    global $start_data;
    return $start_data;
}
function get_start_time()
{
    $date = get_start_data();
    $start_time = strtotime($date);
    return $start_time;
}
function get_work_days()
{
    $time = time();
    $start_time = get_start_time();
    $work_time = floor(($time - $start_time) / (24 * 3600));
    return $work_time;
}
function get_project_payment()
{
    global $payment;
    return $payment;
}
function get_project_invest()
{
    global $invest;
    return $invest;
}
function get_project_deposits()
{
    global $deposits;
    return $deposits;
}
function get_login()
{
    global $login;
    return $login;
}
function get_mdate()
{
    global $mdate;
    return $mdate;
}
function get_auto_depozit()
{
    global $auto_depozit;
    return $auto_depozit;
}
function get_class_time()
{
    global $class_time;
    return $class_time;
}
function get_class_success()
{
    global $class_success;
    return $class_success;
}
function get_class_error()
{
    global $class_error;
    return $class_error;
}
function get_d_max()
{
    global $d_max;
    return $d_max;
}
function get_d_min()
{
    global $d_min;
    return $d_min;
}
function get_d_wmax()
{
    global $d_wmax;
    return $d_wmax;
}
function get_d_wmin()
{
    global $d_wmin;
    return $d_wmin;
}
function get_project_theme()
{
    global $theme;
    return $theme;
}
function marketing_login_refer_by_level_backtrack($login, $level = 1, $system = false, $status = 1, $require_level = 1, $full_sum = false)
{
    global $sum;
    if ($level < 1) {
        return 0;
    }
    $users = get_list("users", "refer = " . escape_db($login));
    foreach ($users as $user) {
        if ($level === 1) {
            $where = "";
            if ($system) {
                $where .= " AND system = " . escape_db($system);
            }
            $sql = "SELECT SUM(summa) FROM `invest` WHERE login = " . escape_db($user["login"]) . " AND status = " . escape_db($status) . $where . ";";
            $percent = marketing_refer_percent_by_level($require_level, $login);
            if (!$full_sum) {
                $sum += get_value($sql) / 100 * $percent;
            } else {
                $sum += get_value($sql);
            }
        } else {
            marketing_login_refer_by_level_backtrack($user["login"], $level - 1, $system, $status, $require_level, $full_sum);
        }
    }
    return $sum;
}
function marketing_login_refer_by_level($login, $level = 1, $system = false, $status = 1, $full_sum = false)
{
    global $sum;
    $tmp_global_sum = $sum;
    $sum = 0;
    if (!function_exists("marketing_login_refer_by_level_backtrack")) {
        function marketing_login_refer_by_level_backtrack($login, $level = 1, $system = false, $status = 1, $require_level = 1, $full_sum = false)
        {
            global $sum;
            if ($level < 1) {
                return 0;
            }
            $users = get_list("users", "refer = " . escape_db($login));
            foreach ($users as $user) {
                if ($level === 1) {
                    $where = "";
                    if ($system) {
                        $where .= " AND system = " . escape_db($system);
                    }
                    $sql = "SELECT SUM(summa) FROM `invest` WHERE login = " . escape_db($user["login"]) . " AND status = " . escape_db($status) . $where . ";";
                    $percent = marketing_refer_percent_by_level($require_level, $login);
                    if (!$full_sum) {
                        $sum += get_value($sql) / 100 * $percent;
                    } else {
                        $sum += get_value($sql);
                    }
                } else {
                    marketing_login_refer_by_level_backtrack($user["login"], $level - 1, $system, $status, $require_level, $full_sum);
                }
            }
            return $sum;
        }
    }
    $sum = marketing_login_refer_by_level_backtrack($login, $level, $system, $status, $level, $full_sum);
    $tmp = $sum;
    $sum = $tmp_global_sum;
    return $tmp;
}
function marketing_refer_percent_by_level($level = 1, $login)
{
    static $cache = array();
    if (isset($cache[$level])) {
        return $cache[$level];
    }
    $data = array();
    $type = get_user_type_refer_system_data($login);
    $group_id = (int) $type("refer_group_id");
    $list = get_list("refer_system", "`active` = 1 AND `group_id` = " . escape_db($group_id));
    foreach ($list as $key => $value) {
        $data[$value["level"]] = (double) $value["percent"];
    }
    if (!isset($data[$level])) {
        exit("Процент для реферального уровня №" . $level . " не определен!");
    }
    $cache = $data;
    return $data[$level];
}
function marketing_login_refer_by_level_list_backtrack($login, $level = 1, $status = 1, $require_level = 1)
{
    global $refers;
    if ($level < 0) {
        return 0;
    }
    $users = get_list("users", "refer = " . escape_db($login));
    foreach ($users as $user) {
        if ($level == 1) {
            $refers[] = $user;
        } else {
            marketing_login_refer_by_level_list_backtrack($user["login"], $level - 1, $status, $require_level);
        }
    }
    return $refers;
}
function marketing_login_refer_by_level_list($login, $level = 1, $status = 1)
{
    global $refers;
    $refers = array();
    if (!function_exists("marketing_login_refer_by_level_list_backtrack")) {
        function marketing_login_refer_by_level_list_backtrack($login, $level = 1, $status = 1, $require_level = 1)
        {
            global $refers;
            if ($level < 0) {
                return 0;
            }
            $users = get_list("users", "refer = " . escape_db($login));
            foreach ($users as $user) {
                if ($level == 1) {
                    $refers[] = $user;
                } else {
                    marketing_login_refer_by_level_list_backtrack($user["login"], $level - 1, $status, $require_level);
                }
            }
            return $refers;
        }
    }
    $refers = marketing_login_refer_by_level_list_backtrack($login, $level, $status, $level);
    return $refers;
}
function hyiponline24_check_qiwi_by_transaction($transaction, $invest)
{
    global $hyiponline24_qiwi_phone_invest;
    global $hyiponline24_qiwi_key_invest;
    global $mysqli;
    $val = get_currency();
    $wallet = new BM_FullQiwi($hyiponline24_qiwi_phone_invest, $hyiponline24_qiwi_key_invest);
    $result_qiwi["data"] = $wallet->check_by_transaction($transaction);
    if (!$result_qiwi["data"]) {
        return message_error("Ошибка, транзакция не найдена");
    }
    if ($result_qiwi["data"]["type"] !== "income") {
        log_write("Пополнение Qiwi, попытка обмана системы, исходящий платеж пытаются обернуть как входящий. ID пополнения: " . $invest["id"]);
        return message_error("Ошибка зачисления платежа.");
    }
    if ($result_qiwi["data"]["status"] !== "success") {
        log_write("Пополнение Qiwi, попытка обмана системы, платеж не прошел. ID пополнения: " . $invest["id"]);
        return message_error("Ошибка зачисления платежа, платеж не прошел.");
    }
    $qiwi_amount = format_currency($result_qiwi["data"]["sum"], $result_qiwi["data"]["currency"]);
    $invest_amount = format_currency($invest["summa"], $invest["currency"]);
    if ($result_qiwi["data"]["currency"] !== $invest["currency"]) {
        $invest_amount = format_currency($invest["summa"] * $invest["exch_rate"], $invest["currency"]);
    }
    if ($qiwi_amount !== $invest_amount) {
        log_write("Пополнение Qiwi, попытка обмана системы, подмена суммы у платежа. ID пополнения: " . $invest["id"]);
        return message_error("Ошибка зачисления платежа.");
    }
    $sql = "UPDATE `invest` SET `transaction` = " . escape_db($transaction) . ", `status` = " . escape_db(1) . " WHERE `id` = " . escape_db($invest["id"]);
    $mysqli->query($sql);
    $res = active_invest($invest["id"]);
    if ($res["error"]) {
        log_write("ERROR: Пополнение на Qiwi; MESSAGE: " . $res["message"], $res["data"]);
    }
    $mysqli->query("UPDATE `cache` SET balans_invest = balans_invest + " . $invest["summa"]);
    return message_success("Платеж успешно принят.");
}
function get_page_intro()
{
    global $settings_define_show_page_introduction;
    global $page;
    $intro = false;
    if ($settings_define_show_page_introduction) {
        $intro = true;
    }
    if (session("intro")) {
        $intro = false;
    }
    if ($page[0] === "intro") {
        $intro = false;
    }
    return $intro;
}
function page_is_internal()
{
    if (preg_match("#^/user/#", server("REQUEST_URI"))) {
        return true;
    }
    return false;
}
function bm_date_month_convert($input, $output_format = "none")
{
    $arr = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "jan", "feb", "mar", "apr", "may", "june", "july", "aug", "sept", "oct", "nov", "dec", "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
    $output = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек", "Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля", "Августа", "Сентября", "Октября", "Ноября", "Декабря");
    foreach ($arr as $key => $value) {
        if ($input === $value || strtolower($input) === $value || strtoupper($input) === $value || ucfirst($input) === $value) {
            $result = $key;
        }
    }
    if (!isset($result)) {
        return $input;
    }
    if ($output_format === "F") {
        $result = 36 + $result % 12;
        return T($output[$result]);
    }
    if ($output_format === "m") {
        $result = 12 + $result % 12;
        return $output[$result];
    }
    if ($output_format === "M") {
        $result = 24 + $result % 12;
        return T($output[$result]);
    }
    if ($output_format === "n") {
        $result = $result % 12;
        return $output[$result];
    }
    if ($output_format === "none") {
        return $output[$result];
    }
    log_write("ERROR function bm_date_month_convert (wrong \$output_format)", $output_format);
    return false;
}
function bm_date($time, $format = "j F Y, H:i")
{
    if (mb_strpos($format, "F") !== false) {
        $res = date(str_replace("F", "{%}", $format), $time);
        $res = str_replace("{%}", bm_date_month_convert(date("n", $time), "F"), $res);
        return $res;
    }
    if (mb_strpos($format, "M") !== false) {
        $res = date(str_replace("M", "{%}", $format), $time);
        $res = str_replace("{%}", bm_date_month_convert(date("n", $time), "M"), $res);
        return $res;
    }
    return date($format, $time);
}
function get_languages($limit = 8)
{
    global $mysqli;
    $limit = (int) $limit;
    $sql = "SELECT * FROM `language` ORDER BY `priority` LIMIT " . $limit;
    $result = $mysqli->query($sql);
    if (!$result) {
        mysqli_error_log($mysqli, $sql);
        return message_error("Ошибка получения списка языков");
    }
    while ($row = $result->fetch_assoc()) {
        $list[] = $row;
    }
    return $list;
}
function get_default_language()
{
    $lang = get_languages(1);
    return $lang;
}
function get_range_invest_amount_by_system($system, $currency = false)
{
    $res = array();
    $res["min"] = 0;
    $res["max"] = 0;
    if (!$currency) {
        $currency = get_currency();
    }
    $currency = strtoupper($currency);
    $row = get_row_by_field("payment_system", "name", $system);
    if (!$row) {
        log_write("ERROR function get_range_invest_amount_by_system", $system, $currency);
        return $res;
    }
    $range = json_decode($row["range_invest"], true);
    if (isset($range[$currency])) {
        $res["min"] = (double) $range[$currency]["min"];
        $res["max"] = (double) $range[$currency]["max"];
    } else {
        $res["min"] = (double) currency_convert($row["currency"], $currency, $range[$row["currency"]]["min"]);
        $res["max"] = (double) currency_convert($row["currency"], $currency, $range[$row["currency"]]["max"]);
    }
    return $res;
}
function get_range_payment_amount_by_system($system, $currency = false)
{
    $res = array();
    $res["min"] = 0;
    $res["max"] = 0;
    if (!$currency) {
        $currency = get_currency();
    }
    $currency = strtoupper($currency);
    $row = get_row_by_field("payment_system", "name", $system);
    if (!$row) {
        log_write("ERROR function get_range_payment_amount_by_system", $system, $currency);
        return $res;
    }
    $range = json_decode($row["range_payment"], true);
    if (isset($range[$currency])) {
        $res["min"] = (double) $range[$currency]["min"];
        $res["max"] = (double) $range[$currency]["max"];
    } else {
        $res["min"] = (double) currency_convert($row["currency"], $currency, $range[$row["currency"]]["min"]);
        $res["max"] = (double) currency_convert($row["currency"], $currency, $range[$row["currency"]]["max"]);
    }
    return $res;
}
function get_user_bonus_system($login)
{
    $sql = "SELECT `system` FROM `invest` WHERE `login` = " . escape_db($login) . " AND `status` = " . escape_db(1) . condition_delete() . " ORDER BY `id` DESC LIMIT 1";
    $bonus_system = get_value($sql);
    if (!$bonus_system) {
        $bonus_system = get_value("SELECT `name` FROM `payment_system` WHERE `status` = " . escape_db("on") . " ORDER BY `id` LIMIT 1");
        log_write("Невозможно получить платёжную систему пользователя " . escape($login) . " для начисления бонуса. Установлена дефолтная. (" . $bonus_system . ")");
    }
    return $bonus_system;
}
function get_data_type_refer_system_by_id($id)
{
    $res = get_row_by_id("type_refer_system", $id);
    if (!$res) {
        log_write("ERROR function: get_user_type_refer_system_title", $id);
        return message_error("Ошибка получения данных реферальной системы");
    }
    return $res;
}
function get_user_type_refer_system_data($login)
{
    $id = user_get_type_refer_system_id($login);
    return get_data_type_refer_system_by_id($id);
}
function get_user_type_refer_system_title($login)
{
    return get_user_type_refer_system_data($login)["title"];
}
function set_user_type_refer_system($login, $trs_id)
{
    global $mysqli;
    $sql = "UPDATE `users` SET `type_refer_system_id` = " . escape_db($trs_id) . " WHERE login = " . escape_db($login) . condition_delete();
    if (!$mysqli->query($sql)) {
        log_write("ERROR. function set_user_type_refer_system", $sql);
        return message_error("Ошибка записи типа реферальной системы пользователя");
    }
    return message_success("Тип реферальной системы пользователя " . $login . " успешно изменён");
}
function check_type_refer_system($login)
{
    if (function_exists("settings__check_type_refer_system")) {
        $res = settings__check_type_refer_system();
        if ($res["define"]) {
            return $res["func"]($login);
        }
    }
    global $mysqli;
    foreach (get_type_refer_systems() as $item) {
        $val = get_currency();
        $refer_system = get_user_type_refer_system_data($login);
        if (isset($refer_system["error"]) && $refer_system["error"]) {
            $sql = "SELECT `id` FROM `type_refer_system` WHERE `status` = " . escape_db(1) . condition_delete() . " ORDER BY `priority` LIMIT 1";
            $type_refer = get_value($sql);
            set_user_type_refer_system($login, $type_refer);
            return false;
        }
        $sql = "SELECT MAX(`priority`) FROM `type_refer_system` WHERE `status` = " . escape_db(1) . condition_delete();
        $max_priority = (int) get_value($sql);
        if (!$max_priority || $refer_system["priority"] == $max_priority) {
            return false;
        }
        $sql = "SELECT `id` FROM `type_refer_system` WHERE `priority` > " . escape_db((int) $refer_system["priority"]) . " AND `status` = " . escape_db(1) . condition_delete() . " ORDER BY `priority` LIMIT 1";
        $trs_next_level_id = get_value($sql);
        if (!$trs_next_level_id) {
            return false;
        }
        $refer_system = get_data_type_refer_system_by_id($trs_next_level_id);
        if (isset($refer_system["error"]) && $refer_system["error"]) {
            $sql = "SELECT `id` FROM `type_refer_system` WHERE `status` = " . escape_db(1) . condition_delete() . " ORDER BY `priority` LIMIT 1";
            $type_refer = get_value($sql);
            set_user_type_refer_system($login, $type_refer);
            return false;
        }
        $full_amount = user_full_amount_refer($login);
        $count_refer = login_refer_count($login);
        $user_invest_sum = login_invest($login);
        if (!$full_amount && !$count_refer && !$user_invest_sum) {
            return false;
        }
        if ((double) $refer_system["user_invest"] <= $user_invest_sum && (int) $refer_system["refer_count"] <= $count_refer && $refer_system["refer_full_amount"] <= $full_amount) {
            $res = set_user_type_refer_system($login, $trs_next_level_id);
            if ($res["error"]) {
                return false;
            }
            $user_bonus_system = get_user_bonus_system($login);
            $sql = "INSERT INTO `profit` SET ";
            $sql .= " `login` = " . escape_db($login);
            $sql .= ", `date` = " . escape_db(time());
            $sql .= ", `deposit_id` = " . escape_db(0);
            $sql .= ", `amount` = " . escape_db($refer_system["bonus"]);
            $sql .= ", `system` = " . escape_db($user_bonus_system);
            $sql .= ", `currency` = " . escape_db($val);
            $sql .= ", `return` = " . escape_db(0);
            $sql .= ", `delete` = " . escape_db(1);
            $result_profit = $mysqli->query($sql);
            if (!$result_profit) {
                log_write("ERROR. function check_type_refer_system", $sql);
                return message_error("Ошибка записи бонусного профита!");
            }
            $res = add_operations($login, "Бонус", $refer_system["bonus"], $user_bonus_system, 1, "Начисление бонуса пользователю (Сумма вкладов пользователя: " . format_currency($user_invest_sum, $val) . "; Сумма вкладов рефералов: " . format_currency($full_amount, $val) . "; Кол-во рефералов: " . $count_refer, 0);
            if ($res["error"]) {
                return message_error($res["message"]);
            }
        }
    }
    return message_success("Бонус успешно начислен!");
}

?>