license 验证函数的文件路径是:

/usr/local/virtualizor/main/functions.php

functions.php

<?php  if( !defined("VIRTUALIZOR") ) 
{
    exit( "Hacking Attempt" );
}
class ArrayToXML 
{
    public function toXML($data, $rootNodeName = "ResultSet", $xml = NULL) 
    {
        if( ini_get("zend.ze1_compatibility_mode") == 1 ) 
        {
            ini_set("zend.ze1_compatibility_mode", 0);
        }
        if( is_null($xml) ) 
        {
            $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><" . $rootNodeName . " />");
        }
        foreach( $data as $key => $value ) 
        {
            $numeric = false;
            if( is_numeric($key) ) 
            {
                $numeric = 1;
                $key = $rootNodeName;
            }
            $key = preg_replace("/[^a-z0-9\\-\\_\\.\\:]/i", "", $key);
            if( is_array($value) ) 
            {
                $node = (ArrayToXML::isAssoc($value) || $numeric ? $xml->addChild($key) : $xml);
                if( $numeric ) 
                {
                    $key = "anon";
                }
                ArrayToXML::toXml($value, $key, $node);
            }
            else 
            {
                $value = htmlentities($value);
                $xml->addChild($key, $value);
            }
        }
        return $xml->asXML();
    }
    public function toArray($xml) 
    {
        if( is_string($xml) ) 
        {
            $xml = new SimpleXMLElement($xml);
        }
        $children = $xml->children();
        if( !$children ) 
        {
            return (string) $xml;
        }
        $arr = array( );
        foreach( $children as $key => $node ) 
        {
            $node = ArrayToXML::toArray($node);
            if( $key == "anon" ) 
            {
                $key = count($arr);
            }
            if( isset($arr[$key]) ) 
            {
                if( !is_array($arr[$key]) || $arr[$key][0] == NULL ) 
                {
                    $arr[$key] = array( $arr[$key] );
                }
                $arr[$key][] = $node;
            }
            else 
            {
                $arr[$key] = $node;
            }
        }
        return $arr;
    }
    public function isAssoc($array) 
    {
        return is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array))));
    }
}
function microtime_float() 
{
    list($usec, $sec) = explode(" ", microtime());
    return (double) $usec + (double) $sec;
}
function datify($timestamp, $today = true, $adjust = true, $format = false) 
{
    global $l;
    global $user;
    global $globals;
    if( !empty($adjust) ) 
    {
        $timestamp = max(0, $timestamp - (@date("Z", @time()) / 3600 - $globals["pgtimezone"]) * 3600);
    }
    if( !empty($format) ) 
    {
        return date($format, $timestamp);
    }
    $todaytime = max(0, time() - (@date("Z", @time()) / 3600 - $globals["pgtimezone"]) * 3600);
    if( $today && date("F j, Y", $timestamp) == date("F j, Y", $todaytime) ) 
    {
        $time = date("g:i a", $timestamp);
        return $l["today"] . $time;
    }
    return @date("F j, Y, g:i a", $timestamp);
}
function datetime($datetime) 
{
    if( empty($datetime) ) 
    {
        return NULL;
    }
    $year = substr($datetime, 0, 4);
    $month = substr($datetime, 4, 2);
    $day = substr($datetime, 6, 2);
    $ret = $day . "/" . $month . "/" . $year;
    if( 8 < strlen($datetime) ) 
    {
        $hour = substr($datetime, 8, 2);
        $min = substr($datetime, 10, 2);
        $ret = $ret . " " . $hour . ":" . $min;
    }
    return $ret;
}
function rand_num($val) 
{
    for( $i = 0; $i < $val; $i++ ) 
    {
        $number .= rand(1, 9);
    }
    return $number;
}
function generateRandStr($length) 
{
    $randstr = "";
    for( $i = 0; $i < $length; $i++ ) 
    {
        $randnum = mt_rand(0, 61);
        if( $randnum < 10 ) 
        {
            $randstr .= chr($randnum + 48);
        }
        else 
        {
            if( $randnum < 36 ) 
            {
                $randstr .= chr($randnum + 55);
            }
            else 
            {
                $randstr .= chr($randnum + 61);
            }
        }
    }
    return strtolower($randstr);
}
function inputsec($string) 
{
    if( !get_magic_quotes_gpc() ) 
    {
        $string = addslashes($string);
    }
    else 
    {
        $string = stripslashes($string);
        $string = addslashes($string);
    }
    return $string;
}
function xss($val) 
{
    return escapeshellarg($val);
}
function xsscmd($cmd) 
{
    return escapeshellcmd($cmd);
}
function htmlizer($string) 
{
    global $globals;
    $string = htmlentities($string, ENT_QUOTES, $globals["charset"]);
    preg_match_all("/(&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});)/", $string, $matches);
    foreach( $matches[1] as $mk => $mv ) 
    {
        $tmp_m = entity_check($matches[2][$mk]);
        $string = str_replace($matches[1][$mk], $tmp_m, $string);
    }
    return $string;
}
function entity_check($string) 
{
    $num = (substr($string, 0, 1) === "x" ? hexdec(substr($string, 1)) : (int) $string);
    $string = (1114111 < $num || 55296 <= $num && $num <= 57343 || $num < 32 ? "" : "&#" . $num . ";");
    return $string;
}
function cleanVARS($var) 
{
    if( is_string($var) ) 
    {
        $var = array( $var );
    }
    foreach( $var as $k => $v ) 
    {
        if( is_array($v) ) 
        {
            $var[$k] = cleanVARS($v);
            continue;
        }
        if( get_magic_quotes_gpc() ) 
        {
            $v = stripslashes($v);
        }
        $v = htmlizer($v);
        $var[$k] = $v;
    }
    return $var;
}
function cexplode($chars, $str, $int = 0, $clean = 0) 
{
    $r = explode($chars, $str);
    foreach( $r as $k => $v ) 
    {
        if( $int ) 
        {
            $r[$k] = (int) trim($v);
        }
        else 
        {
            $r[$k] = trim($v);
        }
    }
    if( !empty($clean) ) 
    {
        foreach( $r as $k => $v ) 
        {
            if( empty($v) ) 
            {
                unset($r[$k]);
            }
        }
    }
    return $r;
}
function rawGPC($v) 
{
    if( get_magic_quotes_gpc() ) 
    {
        $v = stripslashes($v);
    }
    return $v;
}
function v_ksort($a, $b) 
{
    return strlen($b) - strlen($a);
}
function makequery($query, $token_vals = array( ), $ret = 0) 
{
    global $user;
    global $globals;
    global $l;
    global $theme;
    if( class_exists("PDO") && !empty($globals["pdo_conn"]) ) 
    {
        try 
        {
            $pdo = $globals["pdo_conn"];
            $stmt = $pdo->prepare($query);
            if( !empty($token_vals) && is_array($token_vals) ) 
            {
                $token_vals = clean_pdo_vals($token_vals);
                $stmt_result = $stmt->execute($token_vals);
            }
            else 
            {
                $stmt_result = $stmt->execute();
            }
            if( !$stmt_result && empty($ret) && !empty($globals["pdo_conn"]) ) 
            {
                $errinf = $stmt->errorInfo();
                if( $errinf[1] == 2006 ) 
                {
                    try 
                    {
                        $globals["pdo_conn"] = new PDO("mysql:host=" . $globals["dbhost"] . ";dbname=" . $globals["db"] . ";charset=utf8", $globals["dbuser"], $globals["dbpass"]);
                    }
                    catch( PDOException $e ) 
                    {
                        exit( "Error!: " . $e->getMessage() );
                    }
                    return makequery($query, $token_vals, $ret);
                }
                echo "Could not make the Query.<br />" . $query;
                r_print($errinf);
                exit();
            }
            $result = $stmt;
        }
        catch( PDOException $e ) 
        {
            echo "Error : <br />" . $query;
            r_print($e->getMessage());
            exit();
        }
    }
    else 
    {
        if( !empty($token_vals) ) 
        {
            uksort($token_vals, "v_ksort");
            foreach( $token_vals as $k => $v ) 
            {
                if( strpos($v, "'") !== false ) 
                {
                    $v = addslashes($v);
                }
                $query = str_replace($k, "'" . $v . "'", $query);
            }
        }
        $result = mysql_query($query, $globals["conn"]);
        if( !$result && empty($ret) ) 
        {
            if( mysql_errno($globals["conn"]) == 2006 ) 
            {
                $globals["conn"] = @mysql_connect($globals["dbhost"], $globals["dbuser"], $globals["dbpass"], true);
                @mysql_select_db($globals["db"], $globals["conn"]) or exit( "Unable to select database" );
                return makequery($query, $token_vals, $ret);
            }
            exit( "Could not make the Query.<br /><br /><br />" . $query . "<br /><br />MySQL Error No : " . mysql_errno($globals["conn"]) . "<br /><br />MySQL Error : " . mysql_error($globals["conn"]) );
        }
    }
    return $result;
}
function insert_and_id($q, $token_vals = array( )) 
{
    global $globals;
    $res = makequery($q, $token_vals);
    if( class_exists("PDO") && !empty($globals["pdo_conn"]) ) 
    {
        return $globals["pdo_conn"]->lastInsertId();
    }
    return @mysql_insert_id($globals["conn"]);
}
function update_query($q, $token_vals = array( )) 
{
    global $globals;
    $res = makequery($q, $token_vals);
    if( class_exists("PDO") && !empty($globals["pdo_conn"]) ) 
    {
        $aff = (int) $res->rowCount();
    }
    else 
    {
        $aff = (int) @mysql_affected_rows($globals["conn"]);
    }
    if( $aff < 1 ) 
    {
        return false;
    }
    return $aff;
}
function clean_pdo_vals($token_vals) 
{
    $tmp = array( );
    foreach( $token_vals as $k => $v ) 
    {
        if( is_null($v) ) 
        {
            $token_vals[$k] = "";
        }
    }
    return $token_vals;
}
function vsql_affected_rows($res) 
{
    global $globals;
    if( class_exists("PDO") && !empty($globals["pdo_conn"]) ) 
    {
        return (int) $res->rowCount();
    }
    return (int) @mysql_affected_rows($globals["conn"]);
}
function vsql_fetch_assoc($res) 
{
    global $globals;
    if( class_exists("PDO") && !empty($globals["pdo_conn"]) ) 
    {
        return $res->fetch(PDO::FETCH_ASSOC);
    }
    return mysql_fetch_assoc($res);
}
function vsql_fetch_array($res) 
{
    global $globals;
    if( class_exists("PDO") && !empty($globals["pdo_conn"]) ) 
    {
        return $res->fetch(PDO::FETCH_NUM);
    }
    return mysql_fetch_array($res);
}
function vsql_num_rows($res) 
{
    global $globals;
    if( class_exists("PDO") && !empty($globals["pdo_conn"]) ) 
    {
        return $res->rowCount();
    }
    return mysql_num_rows($res);
}
function vsql_get_client_info() 
{
    global $globals;
    if( class_exists("PDO") && !empty($globals["pdo_conn"]) ) 
    {
        return $globals["pdo_conn"]->getAttribute(PDO::ATTR_CLIENT_VERSION);
    }
    if( function_exists("mysql_get_client_info") ) 
    {
        return mysql_get_client_info();
    }
    return "-";
}
function emailvalidation($email) 
{
    if( !preg_match("/^([a-zA-Z0-9\\+._-])*@([a-zA-Z0-9_-])+([.])+([a-zA-Z0-9\\.]+[a-zA-Z])+\$/", $email) ) 
    {
        return false;
    }
    return true;
}
function stringLimit($string, $length = 50, $ellipsis = "...") 
{
    if( $length < strlen($string) ) 
    {
        return substr($string, 0, $length - strlen($ellipsis)) . $ellipsis;
    }
    return $string;
}
function get_page($get = "page", $resperpage = 50) 
{
    $resperpage = (!empty($_REQUEST["reslen"]) && is_numeric($_REQUEST["reslen"]) ? (int) optREQ("reslen") : $resperpage);
    if( optGET($get) ) 
    {
        $pg = (int) optGET($get);
        $pg = $pg - 1;
        $page = $pg * $resperpage;
        $page = ($page <= 0 ? 0 : $page);
    }
    else 
    {
        $page = 0;
    }
    return $page;
}
function _mail($array, $mail_type = "plain") 
{
    global $user;
    global $globals;
    global $theme;
    global $conn;
    global $dbtables;
    include_once($globals["mainfiles"] . "/functions/mail_functions.php");
    return _mail_fn($array, "", $mail_type);
}
function array_insert(&$array, $position, $insert_array) 
{
    $first_array = array_splice($array, 0, $position);
    $array = array_merge($first_array, $insert_array, $array);
}
function find_pos($array, $index) 
{
    $keys = array_keys($array);
    $key = array_search($index, $keys);
    return $key + 1;
}
function unhtmlentities($string) 
{
    $string = preg_replace("~&#x([0-9a-f]+);~ei", "chr(hexdec(\"\\1\"))", $string);
    $string = preg_replace("~&#([0-9]+);~e", "chr(\"\\1\")", $string);
    $trans_tbl = get_html_translation_table(HTML_ENTITIES);
    $trans_tbl = array_flip($trans_tbl);
    return strtr($string, $trans_tbl);
}
function redirect($location, $header = true, $raw = false) 
{
    global $globals;
    global $redirect;
    $redirect = true;
    $prefix = (empty($raw) ? $globals["index"] : "");
    if( $header ) 
    {
        header("Location: " . $prefix . $location);
    }
    else 
    {
        echo "<meta http-equiv=\"Refresh\" content=\"0;url=" . $prefix . $location . "\">";
    }
}
function APIredirect($location, $raw = false) 
{
    $GLOBALS["api"]["redirect"] = ((empty($raw) ? $globals["index"] : "")) . $location;
}
function can_gzip() 
{
    global $isbot;
    if( headers_sent() || connection_aborted() || !empty($isbot) ) 
    {
        return 0;
    }
    if( strpos($_SERVER["HTTP_ACCEPT_ENCODING"], "x-gzip") !== false ) 
    {
        return "x-gzip";
    }
    if( strpos($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip") !== false ) 
    {
        return "gzip";
    }
    return 0;
}
function virtualizor_buffer($buffer) 
{
    global $globals;
    global $redirect;
    if( !empty($redirect) ) 
    {
        return NULL;
    }
    if( !empty($globals["stop_buffer_process"]) ) 
    {
        return $buffer;
    }
    if( preg_match("/\\<html(.*?)/is", $buffer) ) 
    {
        if( empty($globals["lictype"]) ) 
        {
            if( !preg_match("/" . preg_quote(unhtmlentities(strrev(";tg&a/;tl&.cnI suolucatfoS;tg&;touq&moc.suolucatfos.www//:ptth;touq&=ferh a;tl& 9002 ;ypoc;pma& ;tg&a/;tl&0.1 suolucatfoS eerF yB derewoP;tg&;touq&moc.suolucatfos.www//:ptth;touq&=ferh a;tl&")), "/") . "/", $buffer) ) 
            {
                return NULL;
            }
        }
        else 
        {
            if( !preg_match("/" . preg_quote(unhtmlentities(strrev(";tg&a/;tl&.cnI suolucatfoS;tg&;touq&moc.suolucatfos.www//:ptth;touq&=ferh a;tl& 9002 ;ypoc;pma& ;tg&a/;tl&0.1 suolucatfoS yB derewoP;tg&;touq&moc.suolucatfos.www//:ptth;touq&=ferh a;tl&")), "/") . "/", $buffer) ) 
            {
                return NULL;
            }
        }
    }
    if( $globals["gzip"] && extension_loaded("zlib") && @ini_get("zlib.output_compression") !== "1" && can_gzip() ) 
    {
        $buffer = ob_gzhandler($buffer, 1);
    }
    return $buffer;
}
function load_lang($file) 
{
    global $theme;
    global $globals;
    global $l;
    global $user;
    $file = $file . "_lang.php";
    $language = $globals["language"];
    if( !empty($user["language"]) ) 
    {
        $language = $user["language"];
    }
    $path = $globals["path"] . "/languages/" . $language . "/" . $file;
    if( (empty($file) || !include_once($path)) && !include_once($globals["path"] . "/languages/english/" . $file) ) 
    {
        reporterror("", "Unable to load the language files.");
        return false;
    }
    return true;
}
function lang_vars($str, $array) 
{
    $string = "";
    $str = preg_replace("/&soft-(\\d{1,2});/i", "&soft-\\1;", $str);
    $count = 0;
    foreach( $array as $v ) 
    {
        $count++;
        $str = str_replace("&soft-" . $count . ";", $v, $str);
    }
    return $str;
}
function lang_vars_name($str, $array) 
{
    foreach( $array as $k => $v ) 
    {
        $str = str_replace("{{" . $k . "}}", $v, $str);
    }
    return $str;
}
function parse_lang($str) 
{
    global $l;
    foreach( $l as $k => $v ) 
    {
        $v = addslashes($v);
        $str = str_replace("{{" . $k . "}}", $v, $str);
    }
    return $str;
}
function email_templates($temp = "", $langfileprefix = "") 
{
    global $globals;
    global $emailtemps;
    global $l;
    $emailtemps = array( "addvs" => array( "title" => "mail_addvs_sub", "body" => "mail_addvs" ), "admin_addvs" => array( "title" => "admin_mail_addvs_sub", "body" => "admin_mail_addvs" ), "admin_addvs_err" => array( "title" => "admin_mail_addvs_err_sub", "body" => "admin_mail_addvs_err" ), "deletevs" => array( "title" => "admin_mail_del_vs_sub", "body" => "admin_mail_del_vs" ), "admin_del_vs_err" => array( "title" => "admin_mail_del_vs_err_sub", "body" => "admin_mail_del_vs_err" ), "admin_rebuild_vs" => array( "title" => "admin_mail_rebuild_vs_sub", "body" => "admin_mail_rebuild_vs" ), "admin_rebuild_vs_err" => array( "title" => "admin_mail_rebuild_vs_err_sub", "body" => "admin_mail_rebuild_vs_err" ), "createtemplate" => array( "title" => "createtemplate_sub", "body" => "createtemplate_vs" ), "createtemplate_err" => array( "title" => "createtemplate_err_sub", "body" => "createtemplate_vs_err" ), "reset_pass" => array( "title" => "login_mail_sub", "body" => "login_mail_body" ), "suspend_vps" => array( "title" => "suspend_vps_sub", "body" => "suspend_vps_body" ), "unsuspend_vps" => array( "title" => "unsuspend_vps_sub", "body" => "unsuspend_vps_body" ), "suspend_vps_net" => array( "title" => "suspend_vps_net_sub", "body" => "suspend_vps_net_body" ), "unsuspend_vps_net" => array( "title" => "unsuspend_vps_net_sub", "body" => "unsuspend_vps_net_body" ), "suspend_users" => array( "title" => "suspend_users_sub", "body" => "suspend_users_body" ), "unsuspend_users" => array( "title" => "unsuspend_users_sub", "body" => "unsuspend_users_body" ), "billing_warn_abusers" => array( "title" => "billing_warn_abusers_sub", "body" => "billing_warn_abusers_body" ), "billing_warn_users" => array( "title" => "billing_warn_users_sub", "body" => "billing_warn_users_body" ), "billing_invoice_created" => array( "title" => "billing_invoice_created_sub", "body" => "billing_invoice_created_body" ), "rebuildvs" => array( "title" => "mail_rebuildvs_sub", "body" => "mail_rebuildvs" ), "install_webuzo" => array( "title" => "install_webuzo_sub", "body" => "install_webuzo_body" ), "admin_install_webuzo_vs" => array( "title" => "admin_install_webuzo_vs_sub", "body" => "admin_install_webuzo_vs_body" ), "admin_install_webuzo_err" => array( "title" => "admin_install_webuzo_err_sub", "body" => "admin_install_webuzo_err_body" ) );
    if( empty($temp) || empty($emailtemps[$temp]) ) 
    {
        return true;
    }
    $ll["title"] = $l[$emailtemps[$temp]["title"]];
    $ll["body"] = $l[$emailtemps[$temp]["body"]];
    if( file_exists($globals["path"] . "/conf/" . $temp . ".lang") ) 
    {
        $ser = file_get_contents($globals["path"] . "/conf/" . $temp . ".lang");
        $tmp = _unserialize($ser);
    }
    $ll["mail_type"] = "plain";
    if( !empty($tmp) ) 
    {
        $ll["title"] = $tmp["title"];
        $ll["body"] = $tmp["body"];
        $ll["mail_type"] = (!empty($tmp["mail_type"]) ? "html" : "plain");
    }
    return $ll;
}
function init_theme($file, $theme_file_name) 
{
    global $theme;
    global $globals;
    global $l;
    if( !include_once($theme["path"] . "/" . $file . "_theme.php") && !include_once($globals["themes"] . "/default/" . $file . "_theme.php") ) 
    {
        reporterror($l["init_theme_error_t"], lang_vars($l["init_theme_error"], array( $theme_file_name )));
        return false;
    }
    return true;
}
function init_theme_func($function_r, $theme_file_name) 
{
    global $theme;
    global $globals;
    global $act;
    global $load_hf;
    global $l;
    for( $i = 0; $i < count($function_r);
    $i++ ) 
    {
        if( !function_exists($function_r[$i]) ) 
        {
            reporterror($l["init_theme_func_error_t"], lang_vars($l["init_theme_func_error"], array( $theme_file_name )));
            return false;
        }
    }
    return true;
}
function load_theme_settings($folder) 
{
    global $user;
    global $conn;
    global $dbtables;
    global $logged_in;
    global $globals;
    global $l;
    global $theme;
    global $softpanel;
    global $act;
    global $load_hf;
    $skins = array( );
    $skin = array( );
    $load_hf = true;
    $theme["path"] = $globals["themes"] . "/" . $folder;
    if( !include_once($theme["path"] . "/theme_settings.php") ) 
    {
        $theme["path"] = $globals["themes"] . "/default";
        $globals["runtime_theme"] = "default";
        if( !include_once($theme["path"] . "/theme_settings.php") ) 
        {
            reporterror("", $l["load_theme_settings_error"]);
            $load_hf = false;
            return false;
        }
    }
    return true;
}
function reporterror($title, $text, $heading = "", $icon = "") 
{
    global $theme;
    global $globals;
    global $act;
    global $errortitle;
    global $errormessage;
    global $errorheading;
    global $erroricon;
    $act = "error_break";
    $errortitle = $title;
    $errormessage = $text;
    $errorheading = $heading;
    $erroricon = $icon;
    $globals["stop_buffer_process"] = true;
    return true;
}
function reportmessage($title, $heading, $icon, $text) 
{
    global $theme;
    global $globals;
    global $act;
    global $messagetitle;
    global $messagetext;
    global $messageheading;
    global $messageicon;
    $act = "error_break";
    $messagetitle = $title;
    $messagetext = $text;
    $messageheading = $heading;
    $messageicon = $icon;
    return true;
}
function copyright() 
{
    global $globals;
    if( !empty($globals["copyright"]) ) 
    {
        return unhtmlentities($globals["copyright"]);
    }
    if( empty($globals["lictype"]) ) 
    {
        return "<a href=\"https://www.virtualizor.com\">Powered By Virtualizor " . $globals["version"] . "</a> &copy; " . datify(time(), 1, 0, "Y") . " <a href=\"https://www.softaculous.com\">Softaculous Ltd.</a>";
    }
    return "<a href=\"https://www.virtualizor.com\">Powered By Virtualizor " . $globals["version"] . "</a> &copy; " . datify(time(), 1, 0, "Y") . " <a href=\"https://www.softaculous.com\">Softaculous Ltd.</a>";
}
function getallGET($notreq) 
{
    $to_return = array( );
    foreach( $_GET as $k => $v ) 
    {
        if( !in_array($k, $notreq) ) 
        {
            $to_return[] = $k . "=" . $v;
        }
    }
    return implode("&", $to_return);
}
function compress($path, $name, $method) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/compress_functions.php");
    return compress_fn($path, $name, $method);
}
function decompress($file, $destination, $overwrite = 0, $include = array( ), $exclude = array( )) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/compress_functions.php");
    return decompress_fn($file, $destination, $overwrite, $include, $exclude);
}
function unzip($file, $destination, $overwrite = 0, $include = array( ), $exclude = array( )) 
{
    global $globals;
    global $unzip_inc;
    global $unzip_exc;
    if( !empty($include) ) 
    {
        foreach( $include as $ik => $iv ) 
        {
            if( empty($iv) ) 
            {
                unset($include[$ik]);
                continue;
            }
            $include[$ik] = preg_quote($iv, "/");
            $include[$ik] = str_replace("\\*", "([a-zA-Z0-9\\._-])*", $include[$ik]);
        }
    }
    if( !empty($exclude) ) 
    {
        foreach( $exclude as $ek => $ev ) 
        {
            if( empty($ev) ) 
            {
                unset($exclude[$ek]);
                continue;
            }
            $exclude[$ek] = preg_quote($ev, "/");
            $exclude[$ek] = str_replace("\\*", "([a-zA-Z0-9\\._-])*", $exclude[$ek]);
        }
    }
    $unzip_inc = $include;
    $unzip_exc = $exclude;
    if( !class_exists("PclZip") ) 
    {
        include_once($globals["mainfiles"] . "/classes/pclzip.php");
    }
    $archive = new PclZip($file);
    $result = $archive->extract(PCLZIP_OPT_PATH, $destination, PCLZIP_CB_PRE_EXTRACT, "inc_exc", PCLZIP_OPT_REPLACE_NEWER);
    if( $result == 0 ) 
    {
        return false;
    }
    return true;
}
function inc_exc($p_event, &$v) 
{
    global $globals;
    global $unzip_inc;
    global $unzip_exc;
    $include = $unzip_inc;
    $exclude = $unzip_exc;
    if( !empty($include) ) 
    {
        foreach( $include as $ik => $iv ) 
        {
            if( !preg_match("/^" . $iv . "\$/is", $v["stored_filename"]) ) 
            {
                return 0;
            }
        }
    }
    if( !empty($exclude) ) 
    {
        foreach( $exclude as $ek => $ev ) 
        {
            if( preg_match("/^" . $ev . "\$/is", $v["stored_filename"]) ) 
            {
                return 0;
            }
        }
    }
    return 1;
}
function decompress_zip($file, $destination, $overwrite = 0, $include, $exclude) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/compress_functions.php");
    return decompress_zip_fn($file, $destination, $overwrite, $include, $exclude);
}
function decompress_tgz($file, $destination, $overwrite = 0) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/compress_functions.php");
    return decompress_tgz_fn($file, $destination, $overwrite);
}
function decompress_tar($file, $destination, $overwrite = 0) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/compress_functions.php");
    return decompress_tar_fn($file, $destination, $overwrite);
}
function decompress_tbz($file, $destination, $overwrite = 0) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/compress_functions.php");
    return decompress_tbz_fn($file, $destination, $overwrite);
}
function read_file($file) 
{
    return implode("", file($file));
}
function writefile($file, $data, $overwrite = 0, $chmod = 0, $dchmod = 0) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/file_functions.php");
    return writefile_fn($file, $data, $overwrite, $chmod, $dchmod);
}
function filelist($startdir = "./", $searchSubdirs = 1, $directoriesonly = 0, $maxlevel = "all", $level = 1) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/file_functions.php");
    return filelist_fn($startdir, $searchSubdirs, $directoriesonly, $maxlevel, $level);
}
function mkdir_recursive($pathname, $mode) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/file_functions.php");
    return mkdir_recursive_fn($pathname, $mode);
}
function rmdir_recursive($path) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/file_functions.php");
    return rmdir_recursive_fn($path);
}
function get_web_file($url, $writefilename = "") 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/file_functions.php");
    return get_web_file_fn($url, $writefilename);
}
function save_web_file($url, $path) 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/file_functions.php");
    return save_web_file_fn($url, $path);
}
function getremotesize($url) 
{
    $size = 0;
    $headers = get_headers($url, 1);
    if( $headers === false ) 
    {
        $curl = curl_init();
        curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_NOBODY => true ));
        $_headers = explode("\n", curl_exec($curl));
        foreach( $_headers as $k => $v ) 
        {
            $v = explode(":", trim($v));
            if( empty($v[1]) ) 
            {
                continue;
            }
            $headers[trim($v[0])] = trim($v[1]);
        }
        curl_close($curl);
        if( !empty($headers["Content-Length"]) ) 
        {
            $size = (double) trim($headers["Content-Length"]);
        }
    }
    else 
    {
        foreach( $headers as $k => $v ) 
        {
            if( strtolower($k) == "content-length" ) 
            {
                if( is_array($v) ) 
                {
                    $size = (double) trim(end($v));
                }
                else 
                {
                    $size = (double) trim($v);
                }
            }
        }
    }
    return $size;
}
function r_print($array) 
{
    echo "<pre>";
    print_r($array);
    echo "</pre>";
}
function _strlen($string) 
{
    global $globals;
    return strlen(utf8_decode($string));
}
function _substr($string, $start, $length = NULL) 
{
    global $globals;
    $r = preg_split("/(.)/" . (($globals["charset"] == "UTF-8" ? "u" : "")), $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    if( $length === NULL ) 
    {
        return implode("", array_slice($r, $start));
    }
    return implode("", array_slice($r, $start, $length));
}
function _strtolower($string) 
{
    global $globals;
    global $lower_upper;
    global $upper_lower;
    if( $globals["charset"] != "UTF-8" ) 
    {
        return strtolower($string);
    }
    if( function_exists("mb_strtolower") ) 
    {
        return mb_strtolower($string, $globals["charset"]);
    }
    include_once($globals["mainfiles"] . "/functions/utf8_functions.php");
    return _strtolower_fn($string);
}
function _strtoupper($string) 
{
    global $globals;
    global $upper_lower;
    global $lower_upper;
    if( $globals["charset"] != "UTF-8" ) 
    {
        return strtoupper($string);
    }
    if( function_exists("mb_strtoupper") ) 
    {
        return mb_strtoupper($string, $globals["charset"]);
    }
    include_once($globals["mainfiles"] . "/functions/utf8_functions.php");
    return _strtoupper_fn($string);
}
function _ucfirst($string) 
{
    global $globals;
    if( $globals["charset"] != "UTF-8" ) 
    {
        return ucfirst($string);
    }
    return _strtoupper(_substr($string, 0, 1)) . _substr($string, 1);
}
function _strpos($haystack, $needle, $offset = 0) 
{
    $c = 0;
    $length = NULL;
    while( is_null($length) || $length < $offset ) 
    {
        $pos = strpos($haystack, $needle, $offset + $c);
        if( $pos === false ) 
        {
            return false;
        }
        $length = _strlen(substr($haystack, 0, $pos));
        if( $length < $offset ) 
        {
            $c = $pos - $length;
        }
    }
    return $length;
}
function _unserialize($str) 
{
    $var = @unserialize($str);
    if( empty($var) ) 
    {
        preg_match_all("!s:(\\d+):\"(.*?)\";!s", $str, $matches);
        foreach( $matches[2] as $mk => $mv ) 
        {
            $tmp_str = "s:" . strlen($mv) . ":\"" . $mv . "\";";
            $str = str_replace($matches[0][$mk], $tmp_str, $str);
        }
        $var = @unserialize($str);
    }
    if( empty($var) ) 
    {
        return false;
    }
    return $var;
}
function POST($name, $e, $isset = 1) 
{
    global $error;
    if( $isset && (!isset($_POST[$name]) || strlen(trim($_POST[$name])) < 1) || empty($isset) && empty($_POST[$name]) ) 
    {
        $error[$name] = $e;
    }
    else 
    {
        return inputsec(htmlizer(trim($_POST[$name])));
    }
}
function iPOST($name, $e, $isset = 1) 
{
    global $error;
    if( $isset && (!isset($_POST[$name]) || strlen(trim($_POST[$name])) < 1) || empty($isset) && empty($_POST[$name]) ) 
    {
        $error[$name] = $e;
    }
    else 
    {
        return inputsec(trim($_POST[$name]));
    }
}
function optPOST($name, $default = "") 
{
    global $error;
    if( isset($_POST[$name]) ) 
    {
        return inputsec(htmlizer(trim($_POST[$name])));
    }
    return $default;
}
function optREQ($name, $default = "") 
{
    global $error;
    if( isset($_REQUEST[$name]) ) 
    {
        return inputsec(htmlizer(trim($_REQUEST[$name])));
    }
    return $default;
}
function REQUEST($name, $e) 
{
    global $error;
    if( !isset($_REQUEST[$name]) || strlen(trim($_REQUEST[$name])) < 1 ) 
    {
        $error[$name] = $e;
    }
    else 
    {
        return inputsec(htmlizer(trim($_REQUEST[$name])));
    }
}
function checkbox($name) 
{
    global $error;
    if( isset($_POST[$name]) ) 
    {
        return true;
    }
    return false;
}
function GET($name, $e) 
{
    global $error;
    if( !isset($_GET[$name]) || strlen(trim($_GET[$name])) < 1 ) 
    {
        $error[$name] = $e;
    }
    else 
    {
        return inputsec(htmlizer(trim($_GET[$name])));
    }
}
function optGET($name, $default = "") 
{
    global $error;
    if( isset($_GET[$name]) ) 
    {
        return inputsec(htmlizer(trim($_GET[$name])));
    }
    return $default;
}
function POSTval($name, $default = "") 
{
    return (!empty($_POST) ? (!isset($_POST[$name]) ? "" : $_POST[$name]) : $default);
}
function aPOSTval($name, $default = "") 
{
    return (!empty($_POST) ? (!isset($_POST[$name]) ? "" : inputsec(htmlizer($_POST[$name]))) : $default);
}
function POSTchecked($name, $default = false) 
{
    return (!empty($_POST) ? (isset($_POST[$name]) ? "checked=\"checked\"" : "") : (!empty($default) ? "checked=\"checked\"" : ""));
}
function POSTradio($name, $val, $default = false) 
{
    return (!empty($_POST) ? ($_POST[$name] == $val ? "checked=\"checked\"" : "") : ($default == $val ? "checked=\"checked\"" : ""));
}
function POSTselect($name, $value, $default = false) 
{
    if( empty($_POST) ) 
    {
        if( !empty($default) ) 
        {
            return "selected=\"selected\"";
        }
    }
    else 
    {
        if( isset($_POST[$name]) && trim($_POST[$name]) == $value ) 
        {
            return "selected=\"selected\"";
        }
    }
}
function ex_POSTselect($name, $value, $default = NULL) 
{
    if( empty($_POST) ) 
    {
        if( !is_null($default) ) 
        {
            return ($default == $value ? "selected=\"selected\"" : "");
        }
    }
    else 
    {
        if( isset($_POST[$name]) && trim($_POST[$name]) == $value ) 
        {
            return "selected=\"selected\"";
        }
    }
}
function REQval($name, $default = "") 
{
    return (!empty($_REQUEST) ? (!isset($_REQUEST[$name]) ? "" : $_REQUEST[$name]) : $default);
}
function load_raw_config($path) 
{
    include($path);
    return $globals;
}
function saveglobals($rawdata = array( ), $reload = false) 
{
    global $globals;
    global $user;
    $final_data = load_raw_config($globals["path"] . "/_universal.php");
    foreach( $rawdata as $k => $v ) 
    {
        if( !isset($final_data[$k]) ) 
        {
            $final_data[$k] = $v;
        }
    }
    $data = "<?php\n\n";
    foreach( $final_data as $k => $v ) 
    {
        if( isset($rawdata[$k]) ) 
        {
            $final_data[$k] = $rawdata[$k];
        }
        else 
        {
            $final_data[$k] = (isset($globals[$k]) ? $globals[$k] : "");
        }
        if( is_string($final_data[$k]) ) 
        {
            $data .= "\$globals['" . $k . "'] = '" . $final_data[$k] . "';" . "\n";
        }
        else 
        {
            if( is_int($final_data[$k]) || is_float($final_data[$k]) ) 
            {
                $data .= "\$globals['" . $k . "'] = " . $final_data[$k] . ";" . "\n";
            }
            else 
            {
                if( is_bool($final_data[$k]) ) 
                {
                    $data .= "\$globals['" . $k . "'] = " . (($final_data[$k] ? "true" : "false")) . ";" . "\n";
                }
            }
        }
    }
    $data .= "\n?>";
    $path = str_replace($globals["path"], $final_data["path"], $globals["path"]);
    writefile($path . "/universal.php", $data, 1);
    if( !empty($reload) ) 
    {
        include($path . "/universal.php");
    }
    return true;
}
function add_cron($time) 
{
    global $globals;
    global $l;
    if( empty($time) ) 
    {
        $time = $globals["cron_time"];
    }
    $emps_time = $globals["emps_cron_time"];
    if( empty($emps_time) ) 
    {
        $first_day = rand(1, 10);
        $second_day = $first_day + 15;
        $emps_time = rand(0, 59) . " " . rand(0, 23) . " " . $first_day . "," . $second_day . " * *";
    }
    $data = $time . " root " . $globals["com"]["php"] . " " . $globals["path"] . "/scripts/cron.php >> " . logdir() . "cron 2>&1" . "\n";
    $data .= "1 * * * * root " . $globals["com"]["php"] . " " . $globals["path"] . "/scripts/cronh.php >> " . logdir() . "cronh 2>&1" . "\n";
    $data .= "*/8 * * * * root " . $globals["com"]["php"] . " " . $globals["path"] . "/scripts/cronm.php >> " . logdir() . "cronm 2>&1" . "\n";
    $data .= $emps_time . " root " . $globals["com"]["php"] . " " . $globals["path"] . "/scripts/emps.php upgrade >> " . logdir() . "emps 2>&1" . "\n";
    $data .= rand(1, 59) . " " . rand(1, 23) . " */2 * * root " . $globals["com"]["php"] . " " . $globals["path"] . "/scripts/cron2.php >> " . logdir() . "cron2 2>&1" . "\n";
    $data = str_replace("\r", "", $data);
    writefile("/etc/cron.d/virtualizor", $data, 1);
    @chmod("/etc/cron.d/virtualizor", 420);
    $power_data = "* * * * * root /usr/local/emps/bin/php " . $globals["path"] . "/scripts/powercron.php >> " . logdir() . "powercron 2>&1" . "\n";
    writefile("/etc/cron.d/virtualizor-powercron", $power_data, 1);
    @chmod("/etc/cron.d/virtualizor-powercron", 420);
    return true;
}
function del_cron() 
{
    global $globals;
    global $l;
    @unlink("/etc/cron.d/softaculous");
    return true;
}
function updatevirtualizor($mode = 0) 
{
    global $globals;
    global $info;
    global $l;
    global $kernel;
    global $cluster;
    global $uerror;
    $report["status"] = false;
    $report["log"] = array( );
    $report["log"]["info"] = $l["getting_info"];
    if( empty($info) ) 
    {
        $data = get_softaculous_file("https://www.virtualizor.com/updates.php?version=" . $globals["version"] . "&tree=" . $globals["update"] . "&patch=" . $globals["patch"]);
        $info = @_unserialize($data);
    }
    if( empty($info["version"]) ) 
    {
        $report["log"]["info"] .= $l["error_getting_latest"];
        return $report;
    }
    $report["log"]["info"] .= $l["got_info"];
    if( $mode == 1 && $info["mode"] == 0 ) 
    {
        $report["log"]["mode"] = $l["manual_mode"];
        return $report;
    }
    if( empty($info["link"]) ) 
    {
        $report["log"]["no_updates"] = $l["no_updates"];
        return $report;
    }
    $report["log"]["get"] = $l["fetch_upgrade"];
    $upgradefile = $globals["path"] . "/VIRT(" . $info["version"] . ").zip";
    $data = get_softaculous_file($info["link"], $upgradefile);
    if( !is_file($upgradefile) ) 
    {
        $report["log"]["get"] .= $l["error_fetch_upgrade"];
        return $report;
    }
    $report["log"]["get"] .= $l["got_upgrade"];
    $report["log"]["unzip"] = $l["unzip_upgrade"];
    if( !unzip($upgradefile, $globals["path"] . "/", 1) ) 
    {
        $report["log"]["unzip"] .= $l["error_unzip_upgrade"];
        return $report;
    }
    $report["log"]["unzip"] .= $l["unzipped_upgrade"];
    $report["log"]["upgrade"] = $l["running_upgrade"];
    if( is_file($globals["path"] . "/upgrade.php") ) 
    {
        include_once($globals["path"] . "/upgrade.php");
        if( function_exists("_upgrade") ) 
        {
            call_user_func("_upgrade", $globals["version"]);
        }
    }
    @unlink($upgradefile);
    @unlink($globals["path"] . "/upgrade.php");
    if( !empty($uerror) ) 
    {
        $report["log"]["upgrade"] .= "\n\n" . $l["error_upgrade"] . "\n\n" . implode("\n\n", $uerror);
        return $report;
    }
    $report["log"]["upgrade"] .= $l["succ_upgrade"];
    $report["status"] = true;
    return $report;
}
function get_softaculous_file($url, $path = "") 
{
    global $globals;
    if( strstr($url, "?") ) 
    {
        $url = $url . "&license=" . $globals["license"] . "&soft_email=" . rawurlencode($globals["soft_email"]) . "&kernel=" . rawurlencode($globals["kernel"]);
    }
    else 
    {
        $url = $url . "?license=" . $globals["license"] . "&soft_email=" . rawurlencode($globals["soft_email"]) . "&kernel=" . rawurlencode($globals["kernel"]);
    }
    if( empty($path) ) 
    {
        return get_web_file($url);
    }
    return save_web_file($url, $path);
}
function fastestmirror($url = "") 
{
    global $globals;
    $lic_updated = time() - filemtime($globals["path"] . "/license.php");
    $lic_edit = time() - $globals["last_edit"];
    if( !empty($globals["override_fast_mirror"]) && $lic_updated <= 86400 && (3600 <= $lic_edit || empty($globals["last_edit"])) ) 
    {
        $mirror = $globals["override_fast_mirror"];
        return $mirror;
    }
    if( !empty($globals["fast_mirrors"]) && $lic_updated <= 86400 && (3600 <= $lic_edit || empty($globals["last_edit"])) ) 
    {
        $mirror = $globals["fast_mirrors"][array_rand($globals["fast_mirrors"])];
    }
    if( !empty($mirror) ) 
    {
        return $mirror;
    }
    if( !empty($url) ) 
    {
        return $url;
    }
    return "http://api.virtualizor.com";
}
function loadlicense($update = false) 
{
    global $globals;
    global $l;
    if( file_exists($globals["path"] . "/license2.php") ) 
    {
        vexec("chattr -i -a " . $globals["path"] . "/license2.php");
    }
    if( !defined("LIC_URL") ) 
    {
        @define("LIC_URL", "https://www.virtualizor.com/license2.php?");
    }
    if( !file_exists($globals["path"] . "/license2.php") || $update ) 
    {
        $activevps = 0;
        if( !empty($globals["conn"]) || !empty($globals["pdo_conn"]) ) 
        {
            $res = makequery("SELECT COUNT(vpsid) AS num FROM `vps`\n\t\t\t\t\t\tWHERE serid = 0");
            if( 0 < vsql_num_rows($res) ) 
            {
                $row = vsql_fetch_assoc($res);
                $activevps = $row["num"];
            }
        }
        $data = get_softaculous_file(LIC_URL . "activevps=" . $activevps . "&version=" . $globals["version"]);
        if( !empty($data) && @sm_decode($data) ) 
        {
            writefile($globals["path"] . "/license2.php", $data, 1);
        }
    }
    $license = @file_get_contents($globals["path"] . "/license2.php");
    if( empty($license) ) 
    {
        reporterror("", $l["no_license"], "");
        return false;
    }
    $license = @trim(@sm_decode($license));
    $license = json_decode($license, true);
    // print_r($globals["path"] . "/license2.php");
    // print_r($license);
    // exit();
    if( !empty($license) && is_array($license) ) 
    {
        foreach( $license as $k => $v ) 
        {
            $globals[$k] = $v;
        }
    }
    return true;
}
function soft_encode($txt) 
{
    $from = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" );
    $to = array( "!", "@", "#", "\$", "%", "^", "&", "*", "(", ")" );
    $txt = base64_encode($txt);
    $txt = str_replace($from, $to, $txt);
    $txt = gzcompress($txt);
    $txt = base64_encode($txt);
    return $txt;
}
function soft_decode($txt) 
{
    $from = array( "!", "@", "#", "\$", "%", "^", "&", "*", "(", ")" );
    $to = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" );
    $txt = base64_decode($txt);
    $txt = @gzuncompress($txt);
    $txt = str_replace($from, $to, $txt);
    $txt = base64_decode($txt);
    return $txt;
}
function sm_decode($txt) 
{
    $from = array( "!", "@", "#", "\$", "%", "^", "&", "*", "(", ")" );
    $to = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" );
    $txt = base64_decode($txt);
    for( $i = 0; $i < strlen($txt);
    $i++ ) 
    {
        $txt[$i] = sm_reverse_bits($txt[$i]);
    }
    $txt = gzuncompress($txt);
    $txt = str_replace($from, $to, $txt);
    $txt = base64_decode($txt);
    return $txt;
}
function sm_reverse_bits($orig) 
{
    $v = decbin(ord($orig));
    $pad = str_pad($v, 8, "0", STR_PAD_LEFT);
    $rev = strrev($pad);
    $bin = bindec($rev);
    $chr = chr($bin);
    return $chr;
}
function sqlsplit($data) 
{
    $ret = array( );
    $buffer = "";
    $sql = "";
    $start_pos = 0;
    $i = 0;
    $len = 0;
    $big_value = -2147483649;
    $sql_delimiter = ";";
    $finished = false;
    while( !($finished && $len <= $i) ) 
    {
        if( $data === false ) 
        {
            break;
        }
        if( $data === true ) 
        {
        }
        else 
        {
            $buffer .= $data;
            $data = false;
            if( strpos($buffer, $sql_delimiter, $i) === false && !$finished ) 
            {
                continue;
            }
        }
        $len = strlen($buffer);
        while( $i < $len ) 
        {
            $found_delimiter = false;
            $old_i = $i;
            if( preg_match("/('|\"|#|-- |\\/\\*|`|(?i)DELIMITER)/", $buffer, $matches, PREG_OFFSET_CAPTURE, $i) ) 
            {
                $first_position = $matches[1][1];
            }
            else 
            {
                $first_position = $big_value;
            }
            $first_sql_delimiter = strpos($buffer, $sql_delimiter, $i);
            if( $first_sql_delimiter === false ) 
            {
                $first_sql_delimiter = $big_value;
            }
            else 
            {
                $found_delimiter = true;
            }
            $i = min($first_position, $first_sql_delimiter);
            if( $i == $big_value ) 
            {
                $i = $old_i;
                if( !$finished ) 
                {
                    break;
                }
                if( trim($buffer) == "" ) 
                {
                    $buffer = "";
                    $len = 0;
                    break;
                }
                $i = strlen($buffer) - 1;
            }
            $ch = $buffer[$i];
            if( strpos("'\"`", $ch) !== false ) 
            {
                $quote = $ch;
                $endq = false;
                while( !$endq ) 
                {
                    $pos = strpos($buffer, $quote, $i + 1);
                    if( $pos === false ) 
                    {
                        if( $finished ) 
                        {
                            $endq = true;
                            $i = $len - 1;
                        }
                        $found_delimiter = false;
                        break;
                    }
                    for( $j = $pos - 1; $buffer[$j] == "\\"; $j-- ) 
                    {
                    }
                    $endq = ($pos - 1 - $j) % 2 == 0;
                    $i = $pos;
                    if( $first_sql_delimiter < $pos ) 
                    {
                        $found_delimiter = false;
                    }
                }
                if( !$endq ) 
                {
                    break;
                }
                $i++;
                if( $finished && $i == $len ) 
                {
                    $i--;
                }
                else 
                {
                    continue;
                }
            }
            if( ($i == $len - 1 && ($ch == "-" || $ch == "/") || $i == $len - 2 && ($ch == "-" && $buffer[$i + 1] == "-" || $ch == "/" && $buffer[$i + 1] == "*")) && !$finished ) 
            {
                break;
            }
            if( $ch == "#" || $i < $len - 1 && $ch == "-" && $buffer[$i + 1] == "-" && ($i < $len - 2 && $buffer[$i + 2] <= " " || $i == $len - 1 && $finished) || $i < $len - 1 && $ch == "/" && $buffer[$i + 1] == "*" ) 
            {
                if( $start_pos != $i ) 
                {
                    $sql .= substr($buffer, $start_pos, $i - $start_pos);
                }
                $j = $i;
                $i = strpos($buffer, ($ch == "/" ? "*/" : "\n"), $i);
                if( $i === false ) 
                {
                    if( $finished ) 
                    {
                        $i = $len - 1;
                    }
                    else 
                    {
                        break;
                    }
                }
                if( $ch == "/" ) 
                {
                    if( $buffer[$j + 2] == "!" ) 
                    {
                        $comment = substr($buffer, $j + 3, $i - $j - 3);
                        if( preg_match("/^[0-9]{5}/", $comment, $version) ) 
                        {
                            if( $version[0] <= 50000000 ) 
                            {
                                $sql .= substr($comment, 5);
                            }
                        }
                        else 
                        {
                            $sql .= $comment;
                        }
                    }
                    $i++;
                }
                $i++;
                $start_pos = $i;
                if( $i == $len ) 
                {
                    $i--;
                }
                else 
                {
                    continue;
                }
            }
            if( strtoupper(substr($buffer, $i, 9)) == "DELIMITER" && $buffer[$i + 9] <= " " && $i < $len - 11 && strpos($buffer, "\n", $i + 11) !== false ) 
            {
                $new_line_pos = strpos($buffer, "\n", $i + 10);
                $sql_delimiter = substr($buffer, $i + 10, $new_line_pos - $i - 10);
                $i = $new_line_pos + 1;
                $start_pos = $i;
                continue;
            }
            if( $found_delimiter || $finished && $i == $len - 1 ) 
            {
                $tmp_sql = $sql;
                if( $start_pos < $len ) 
                {
                    $length_to_grab = $i - $start_pos;
                    if( !$found_delimiter ) 
                    {
                        $length_to_grab++;
                    }
                    $tmp_sql .= substr($buffer, $start_pos, $length_to_grab);
                    unset($length_to_grab);
                }
                if( !preg_match("/^([\\s]*;)*\$/", trim($tmp_sql)) ) 
                {
                    $sql = $tmp_sql;
                    $ret[] = $sql;
                    $buffer = substr($buffer, $i + strlen($sql_delimiter));
                    $len = strlen($buffer);
                    $sql = "";
                    $i = 0;
                    $start_pos = 0;
                    if( strpos($buffer, $sql_delimiter) === false && !$finished ) 
                    {
                        break;
                    }
                }
                else 
                {
                    $i++;
                    $start_pos = $i;
                }
            }
        }
    }
    return $ret;
}
function chowngrp($path, $own, $grp, $rec = 0) 
{
    @chown($path, $own);
    @chgrp($path, $grp);
    if( empty($rec) ) 
    {
        return true;
    }
    if( empty($path) || $path == "/" ) 
    {
        return false;
    }
    resetfilelist();
    $path = (substr($path, -1) == "/" || substr($path, -1) == "\\" ? $path : $path . "/");
    $files = filelist($path, 1, 0, "all");
    $files = (!is_array($files) ? array( ) : $files);
    foreach( $files as $k => $v ) 
    {
        @chown($k, $own);
        @chgrp($k, $grp);
    }
    resetfilelist();
    @clearstatcache();
    return true;
}
function schmod($path, $oct, $rec = 0) 
{
    @chmod($path, $oct);
    if( empty($rec) ) 
    {
        return true;
    }
    if( empty($path) || $path == "/" ) 
    {
        return false;
    }
    resetfilelist();
    $path = (substr($path, -1) == "/" || substr($path, -1) == "\\" ? $path : $path . "/");
    $files = filelist($path, 1, 0, "all");
    $files = (!is_array($files) ? array( ) : $files);
    foreach( $files as $k => $v ) 
    {
        @chmod($k, $oct);
    }
    resetfilelist();
    @clearstatcache();
    return true;
}
function saveuserprefs($data, $UID = 0) 
{
    global $user;
    global $globals;
    global $l;
    global $theme;
    global $error;
    $UID = (empty($UID) ? $user["uid"] : $UID);
    if( empty($UID) || $UID < 1 ) 
    {
        return false;
    }
    $orig = _unserialize($user["preferences"]);
    $orig = (is_array($orig) ? $orig : array( ));
    foreach( $data as $k => $v ) 
    {
        $orig[$k] = $v;
    }
    $prefs = serialize($orig);
    update_query("UPDATE `users`\n\t\t\t\tSET preferences = :preferences\n\t\t\t\tWHERE uid = :uid", array( ":preferences" => $prefs, ":uid" => $UID ));
    return true;
}
function savevpsprefs($data) 
{
    global $user;
    global $globals;
    global $l;
    global $theme;
    global $error;
    $orig = _unserialize($user["vps"]["preferences"]);
    $orig = (is_array($orig) ? $orig : array( ));
    foreach( $data as $k => $v ) 
    {
        $orig[$k] = $v;
    }
    $prefs = serialize($orig);
    update_query("UPDATE `vps`\n\t\t\t\tSET preferences = :preferences\n\t\t\t\tWHERE vpsid = :vpsid", array( ":preferences" => $prefs, ":vpsid" => $user["vps"]["vpsid"] ));
    return true;
}
function soft_memory_limit($mb) 
{
    $bytes = $mb * 1024 * 1024;
    $mb_str = (string) $mb . "M";
    $memory_limit = @ini_get("memory_limit");
    if( empty($memory_limit) ) 
    {
        return NULL;
    }
    $memory_limit_bytes = (strpos($memory_limit, "M") ? intval($memory_limit) * 1024 * 1024 : intval($memory_limit));
    if( $memory_limit_bytes <= $bytes ) 
    {
        @ini_set("memory_limit", $mb_str);
    }
}
function soft_premium() 
{
    global $user;
    global $globals;
    global $l;
    global $theme;
    global $softpanel;
    global $iscripts;
    global $catwise;
    global $error;
    if( empty($globals["lictype"]) ) 
    {
        return false;
    }
    return true;
}
function getvps($vid, $use_cache = 1) 
{
    global $globals;
    global $oslist;
    global $ostemplates;
    global $distros;
    global $vps_cache;
    if( !empty($use_cache) && !empty($vps_cache[$vid]) ) 
    {
        return $vps_cache[$vid];
    }
    $res = makequery("SELECT v.*, u.pid FROM `vps` v\n\t\t\t\t\tLEFT JOIN users u ON (u.uid = v.uid)\n\t\t\t\t\tWHERE v.vpsid = '" . $vid . "'");
    if( vsql_num_rows($res) < 1 ) 
    {
        return false;
    }
    $vps = vsql_fetch_assoc($res);
    $res = makequery("SELECT * FROM `disks` \n\t\t\t\t\tWHERE vps_uuid = '" . $vps["uuid"] . "'\n\t\t\t\t\tORDER BY `num`");
    $vps["disks"] = array( );
    if( 0 < vsql_num_rows($res) ) 
    {
        for( $i = 1; $i <= vsql_num_rows($res);
        $i++ ) 
        {
            $row = vsql_fetch_assoc($res);
            $row["vpsid"] = $vid;
            if( !empty($row["extra"]) ) 
            {
                $row["extra"] = _unserialize($row["extra"]);
                foreach( $row["extra"] as $kk => $vv ) 
                {
                    if( !array_key_exists($kk, $row) ) 
                    {
                        $row[$kk] = $vv;
                    }
                }
            }
            if( preg_match("/block/is", $row["type"]) && empty($row["format"]) ) 
            {
                $row["format"] = "raw";
            }
            if( preg_match("/file/is", $row["type"]) && empty($row["format"]) ) 
            {
                $row["format"] = "qcow2";
            }
            $vps["disks"][$row["num"]] = $row;
        }
    }
    if( !empty($vps["ubc"]) ) 
    {
        $vps["ubc"] = _unserialize($vps["ubc"]);
    }
    if( !empty($vps["mg"]) ) 
    {
        $vps["mg"] = cexplode(",", $vps["mg"], 1);
    }
    if( !empty($vps["cached_disk"]) ) 
    {
        $vps["cached_disk"] = _unserialize($vps["cached_disk"]);
    }
    if( !empty($vps["openvz_features"]) ) 
    {
        $vps["openvz_features"] = _unserialize($vps["openvz_features"]);
    }
    if( !empty($vps["locked"]) ) 
    {
        $vps["locked"] = _unserialize($vps["locked"]);
    }
    if( !empty($vps["speed_cap"]) ) 
    {
        $vps["speed_cap"] = _unserialize($vps["speed_cap"]);
    }
    $vps_cache[$vid] = $vps;
    return $vps;
}
function is_cloud_owner($vpsid, $uid) 
{
    $vps = getvps($vpsid);
    if( empty($vps) ) 
    {
        return false;
    }
    if( $vps["uid"] == $uid || $vps["pid"] == $uid ) 
    {
        return $vps;
    }
    return false;
}
function vps_virt($vid, $vz = 0, $xen = 0, $xenhvm = 0, $kvm = 0, $xcp = 0, $virtualbox = 0) 
{
    global $globals;
    global $users;
    global $vps_cache;
    if( !empty($users["vps"]["vpsid"]) && $users["vps"]["vpsid"] == $vid ) 
    {
        $vps = $users["vps"];
    }
    else 
    {
        $vps = getvps($vid, 1);
    }
    $virt = $vps["virt"];
    if( $virt == "openvz" ) 
    {
        return $vz;
    }
    if( $virt == "xen" && !empty($vps["hvm"]) ) 
    {
        return $xenhvm;
    }
    if( $virt == "xen" ) 
    {
        return $xen;
    }
    if( $virt == "kvm" ) 
    {
        return $kvm;
    }
    if( $virt == "xcp" ) 
    {
        return $xcp;
    }
    if( $virt == "virtualbox" ) 
    {
        return $virtualbox;
    }
}
function vps_virt_text($vid = 0) 
{
    global $globals;
    global $users;
    $vid = (empty($vid) ? $globals["vpsid"] : $vid);
    if( empty($vid) ) 
    {
        return "";
    }
    $vps = getvps($vid, 1);
    return $vps["virt"];
}
function distro_find($osname) 
{
    global $globals;
    global $isos;
    global $distros;
    $distro = "";
    foreach( $distros as $k => $v ) 
    {
        if( preg_match("/" . preg_quote($k, "/") . "/is", $osname) ) 
        {
            $distro = $k;
            break;
        }
    }
    return $distro;
}
function distro_logo($distro, $size = 40) 
{
    global $globals;
    global $isos;
    global $distros;
    global $theme;
    if( empty($distros[$distro]) ) 
    {
        return $theme["images"] . "others_" . $size . ".gif";
    }
    if( !empty($size) ) 
    {
        $size = "_" . $size;
    }
    $v = $distros[$distro];
    return (!empty($v["logo"]) ? $v["logo"] : $theme["images"] . $v["distro"] . $size . ".gif");
}
function distro_list() 
{
    global $globals;
    global $isos;
    global $distros;
    global $theme;
    include($globals["path"] . "/distro_list.php");
    $res = makequery("SELECT * FROM `os_distros`\n\t\t\t\t\tORDER BY distro ASC");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $distros[$row["distro"]] = $row;
    }
    $stan = array( "centos", "fedora", "suse", "debian", "ubuntu", "windows", "scientific", "webuzo" );
    foreach( $stan as $k ) 
    {
        $distros[$k]["permanent"] = 1;
    }
}
function isolist() 
{
    global $globals;
    global $isos;
    global $distros;
    global $A;
    distro_list();
    $isos = array( );
    if( empty($distros) ) 
    {
        $stan = array( "centos", "webuzo", "fedora", "suse", "debian", "ubuntu" );
    }
    else 
    {
        $stan = array_keys($distros);
    }
    $res = makequery("SELECT * FROM iso");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $uuid = $row["uuid"];
        if( empty($uuid) ) 
        {
            $uuid = generaterandstr(16);
            $q = update_query("UPDATE `iso` \n\t\t\t\t\t\tSET uuid = :uuid \n\t\t\t\t\t\tWHERE iso = :isofile", array( ":isofile" => $row["iso"], ":uuid" => $uuid ));
        }
        $isos[$uuid] = $row;
        if( !empty($row["mg"]) ) 
        {
            $isos[$uuid]["mg"] = cexplode(",", $row["mg"], 1);
        }
        $isos[$uuid]["name"] = $row["iso"];
        $isos[$uuid]["filename"] = $row["iso"];
        $isos[$uuid]["size"] = vfilesize($globals["isos"] . "/" . $row["iso"]);
        $isos[$uuid]["isuseriso"] = 0;
        $distro = "";
        preg_replace("/(" . implode("|", $stan) . ")/ies", "\$distro = strtolower('\$1');", $row["iso"]);
        if( empty($distro) ) 
        {
            $isos[$uuid]["distro"] = "others";
        }
        else 
        {
            $isos[$uuid]["distro"] = $distro;
        }
    }
    if( !is_array($isos) ) 
    {
        return false;
    }
}
function useriso($uid = 0) 
{
    global $isos;
    global $globals;
    global $distros;
    isolist();
    if( empty($uid) ) 
    {
        return false;
    }
    $res = makequery("SELECT * FROM `enduser_iso`\n\t\t\t\t\tWHERE uid = '" . $uid . "' \n\t\t\t\t\tAND size = downloaded\n\t\t\t\t\tAND deleted = 0");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $uuid = $row["uuid"];
        $isos[$uuid]["isuseriso"] = $row["uid"];
        $isos[$uuid]["filename"] = $row["iso"];
        $isos[$uuid]["name"] = $row["iso"];
        $isos[$uuid]["size"] = $row["downloaded"];
    }
    if( !is_array($isos) ) 
    {
        return false;
    }
}
function oslist($update = 0) 
{
    global $globals;
    global $oslist;
    global $ostemplates;
    global $oses;
    global $distros;
    global $A;
    distro_list();
    if( !empty($update) || !file_exists($globals["path"] . "/ostemplates_list.json") ) 
    {
        $data = get_softaculous_file("http://api.virtualizor.com/ostemplates_list2.php");
        if( !empty($data) && @json_decode($data, true) ) 
        {
            writefile($globals["path"] . "/ostemplates_list.json", $data, 1);
        }
    }
    $oslist = $ostemplates = $oses = array( );
    $json = file_get_contents($globals["path"] . "/ostemplates_list.json");
    $vars = json_decode($json, true);
    if( !empty($json) && is_array($vars) ) 
    {
        foreach( $vars as $k => $v ) 
        {
            $GLOBALS[$k] = $v;
        }
    }
    if( empty($distros) ) 
    {
        $stan = array( "centos", "webuzo", "fedora", "suse", "debian", "ubuntu", "scientific" );
    }
    else 
    {
        $stan = array_keys($distros);
    }
    foreach( $oses as $k => $v ) 
    {
        $name = explode("-", $v["name"]);
        if( !in_array($name[0], $stan) ) 
        {
            $name[0] = "others";
        }
        $oses[$k]["distro"] = $name[0];
        if( empty($oses[$k]["Nvirt"]) ) 
        {
            $oses[$k]["Nvirt"] = $oses[$k]["type"] . ((empty($oses[$k]["hvm"]) ? "" : "hvm"));
        }
    }
    $res = makequery("SELECT * FROM `os`\n\t\t\t\t\tORDER BY osid ASC");
    $installed = array( );
    for( $i = 0; $i < vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        if( !empty($oses[$row["osid"]]) ) 
        {
            $row["osdata"] = $oses[$row["osid"]];
        }
        else 
        {
            $row["osdata"] = _unserialize($row["osdata"]);
            if( empty($row["osdata"]) ) 
            {
                continue;
            }
        }
        $name = explode("-", $row["osdata"]["name"]);
        if( !in_array($name[0], $stan) ) 
        {
            $name[0] = "others";
        }
        $row["osdata"]["distro"] = $name[0];
        if( !empty($row["mg"]) ) 
        {
            $row["osdata"]["mg"] = cexplode(",", $row["mg"], 1);
        }
        if( empty($row["Nvirt"]) ) 
        {
            $row["osdata"]["Nvirt"] = $row["osdata"]["type"] . ((empty($row["osdata"]["hvm"]) ? "" : "hvm"));
        }
        $ostemplates[$row["osid"]] = $row["osdata"];
        $oslist[$row["osdata"]["type"]][$name[0]][$row["osid"]] = $row["osdata"];
    }
}
function valid_ip($ip) 
{
    if( !preg_match("/^(\\d){1,3}\\.(\\d){1,3}\\.(\\d){1,3}\\.(\\d){1,3}\$/is", $ip) || substr_count($ip, ".") != 3 ) 
    {
        return false;
    }
    $r = explode(".", $ip);
    foreach( $r as $v ) 
    {
        if( 255 < $v ) 
        {
            return false;
        }
    }
    return true;
}
function cpuused($cmd, $speed = 100000, $times = 2) 
{
    $PREV_TOTAL = 0;
    $PREV_IDLE = 0;
    for( $i = 1; $i <= $times; $i++ ) 
    {
        $stats = array( );
        $ret = vexec($cmd, $stats);
        if( empty($stats[0]) ) 
        {
            return false;
        }
        $tmp = preg_grep("/^cpu /is", $stats);
        $tmp = preg_split("/[\\s]+/is", $tmp[0]);
        unset($tmp[0]);
        $idle = $tmp[4];
        $total = array_sum($tmp);
        $diff_total = $total - $PREV_TOTAL;
        $diff_idle = $idle - $PREV_IDLE;
        $usage = ((1000 * ($diff_total - $diff_idle)) / $diff_total + 1) / 10;
        $PREV_TOTAL = $total;
        $PREV_IDLE = $idle;
        usleep($speed);
        clearstatcache();
    }
    return $usage;
}
function iprange($start, $end) 
{
    $range = array( );
    if( empty($start) || empty($end) ) 
    {
        return false;
    }
    if( ip2long($end) < ip2long($start) ) 
    {
        return false;
    }
    for( $s = ip2long($start);
    $s <= ip2long($end);
    $s++ ) 
    {
        $tmp = long2ip($s);
        if( empty($tmp) ) 
        {
            continue;
        }
        $range[] = $tmp;
    }
    return $range;
}
function parseshadow($data, $type = 1) 
{
    if( $type == 1 ) 
    {
        $shadow = @file($data);
    }
    else 
    {
        if( is_array($data) ) 
        {
            $shadow = $data;
        }
        else 
        {
            $shadow = explode("\n", $data);
        }
    }
    if( empty($shadow) ) 
    {
        return false;
    }
    $passwd = array( );
    foreach( $shadow as $uk => $uv ) 
    {
        $uv = explode(":", trim($uv));
        $passwd[$uv[0]] = $uv;
    }
    return $passwd;
}
function allow_slave_action() 
{
    global $globals;
    if( !empty($globals["slave"]) && empty($globals["apicall"]) ) 
    {
        return true;
    }
    return false;
}
function is_slave() 
{
    global $globals;
    if( !empty($globals["slave"]) ) 
    {
        return true;
    }
    return false;
}
function is_master() 
{
    return !is_slave();
}
function make_api_call($ip, $pass, $path, $data = array( ), $post = array( )) 
{
    $key = generaterandstr(8);
    $apikey = make_apikey($key, $pass);
    $url = "https://" . $ip . ":4085/" . $path;
    $url .= (strstr($url, "?") ? "" : "?");
    $url .= "&mver=" . $GLOBALS["globals"]["version"] . "&api=serialize&apikey=" . rawurlencode($apikey);
    if( !empty($data) ) 
    {
        $url .= "&apidata=" . rawurlencode(base64_encode(serialize($data)));
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (!empty($GLOBALS["globals"]["curl_timeout"]) ? $GLOBALS["globals"]["curl_timeout"] : 3));
    curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, "Softaculous");
    if( !empty($post) ) 
    {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $resp = curl_exec($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);
    if( empty($resp) ) 
    {
        return false;
    }
    $r = _unserialize($resp);
    if( empty($r) ) 
    {
        return false;
    }
    return $r;
}
function e_make_api_call($ip, $pass, $vid, $path, $post = array( )) 
{
    $key = generaterandstr(8);
    $apikey = make_apikey($key, $pass);
    $url = "https://" . $ip . ":4083/" . $path;
    $url .= (strstr($url, "?") ? "" : "?");
    $url .= "&mver=" . $GLOBALS["globals"]["version"] . "&svs=" . $vid . "&api=serialize&apikey=" . rawurlencode($apikey);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (!empty($GLOBALS["globals"]["curl_timeout"]) ? $GLOBALS["globals"]["curl_timeout"] : 3));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, "Softaculous");
    if( !empty($post) ) 
    {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $resp = curl_exec($ch);
    curl_close($ch);
    if( empty($resp) ) 
    {
        return false;
    }
    $r = _unserialize($resp);
    if( empty($r) ) 
    {
        return false;
    }
    return $r;
}
function E_api_call($ip, $pass, $vid, $path, $post = array( )) 
{
    $key = generaterandstr(8);
    $apikey = make_apikey($key, $pass);
    $url = "https://" . $ip . ":4085/" . $path;
    $url .= (strstr($url, "?") ? "" : "?");
    $url .= "&mver=" . $GLOBALS["globals"]["version"] . "&svs=" . $vid . "&api=serialize&apikey=" . rawurlencode($apikey);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (!empty($GLOBALS["globals"]["curl_timeout"]) ? $GLOBALS["globals"]["curl_timeout"] : 3));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, "Softaculous");
    if( !empty($post) ) 
    {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $resp = curl_exec($ch);
    curl_close($ch);
    if( empty($resp) ) 
    {
        return false;
    }
    $r = _unserialize($resp);
    if( empty($r) ) 
    {
        return false;
    }
    return $r;
}
function return_apidata($data = array( )) 
{
    global $globals;
    if( empty($globals["apicall"]) ) 
    {
        return false;
    }
    if( empty($data) ) 
    {
        foreach( $GLOBALS as $k => $v ) 
        {
            if( $k == "GLOBALS" ) 
            {
                continue;
            }
            $data[$k] = $v;
        }
    }
    echo "<" . $globals["apicall"] . ">" . serialize($data) . "</" . $globals["apicall"] . ">";
    return true;
}
function apicall_validate() 
{
    global $globals;
    $apikey = optget("apikey");
    $key = substr($apikey, 0, 8);
    if( $apikey != make_apikey($key, $globals["pass"]) && $apikey != make_apikey($key, $globals["pass"], 1) ) 
    {
        return false;
    }
    if( isset($_GET["mver"]) ) 
    {
        $difference = abs(numeric_version($_GET["mver"]) - numeric_version($globals["version"]));
        if( 5 < $difference ) 
        {
            return false;
        }
    }
    $r["key"] = $key;
    $r["data"] = array( );
    if( isset($_GET["apidata"]) ) 
    {
        $tmp = @soft_decode(@optget("apidata"));
        if( empty($tmp) ) 
        {
            $tmp = base64_decode(optget("apidata"));
        }
        if( empty($tmp) ) 
        {
            return false;
        }
        $data = _unserialize($tmp);
        if( empty($data) ) 
        {
            return false;
        }
        $r["data"] = $data;
    }
    return $r;
}
function api_success() 
{
    global $globals;
    $globals["apisuccess"] = 1;
}
function apidata($k) 
{
    global $globals;
    return $globals["apidata"][$k];
}
function is_api_call($from_master = false) 
{
    global $globals;
    if( empty($globals["apicall"]) ) 
    {
        return false;
    }
    if( !empty($from_master) && $_SERVER["REMOTE_ADDR"] != $globals["masterip"] ) 
    {
        return false;
    }
    return true;
}
function make_apikey($key, $pass, $softencode = 0) 
{
    if( empty($softencode) ) 
    {
        return $key . md5($pass . $key);
    }
    return $key . soft_encode(md5($pass . $key));
}
function numeric_version($ver) 
{
    return (int) str_replace(".", "", $ver);
}
function wildsearch($txt) 
{
    return str_replace("*", "%", $txt);
}
function logdir($dir = "") 
{
    $path = V_LOG_DIR . ((empty($dir) ? "" : "/" . $dir));
    if( !is_dir($path) ) 
    {
        mkdir_recursive($path, 493);
    }
    return $path . "/";
}
function logs_vps($action, $data, $status = 1, $vpsid = 0, $uid = 0) 
{
    global $user;
    global $globals;
    global $l;
    global $error;
    $uid = (empty($uid) ? 0 : $uid);
    $data = (is_array($data) ? implode("", $data) : $data);
    return insert_and_id("INSERT INTO logs_vps\n\t\t\t\t\t\tSET uid = :uid,\n\t\t\t\t\t\tvpsid = :vpsid,\n\t\t\t\t\t\taction = :action,\n\t\t\t\t\t\t`data` = :data,\n\t\t\t\t\t\t`time` = :time,\n\t\t\t\t\t\t`status` = :status,\n\t\t\t\t\t\tip = :ip", array( ":uid" => $uid, ":vpsid" => $vpsid, ":action" => $action, ":data" => $data, ":time" => time(), ":status" => $status, ":ip" => $_SERVER["REMOTE_ADDR"] ));
}
function get_task_progress($actid) 
{
    $res = makequery("SELECT * FROM `tasks`\n\t\t\t\t\t  WHERE actid = " . $actid);
    if( 0 < vsql_num_rows($res) ) 
    {
        for( $i = 0; $i < vsql_num_rows($res);
        $i++ ) 
        {
            $row = vsql_fetch_assoc($res);
            $tasks[$row["actid"]] = $row;
        }
    }
    if( !empty($tasks) ) 
    {
        foreach( $tasks as $k => $v ) 
        {
            $progress[] = $v["status"];
            $data = unserialize($v["data"]);
            $progress[] = $data[0];
            $progress[] = $v["vpsid"];
        }
    }
    return $progress;
}
function migration_task_status($actid) 
{
    $res = makequery("SELECT * FROM `tasks`\n\t\t\t\t\t  WHERE actid = '" . $actid . "'");
    if( vsql_num_rows($res) < 1 ) 
    {
        return false;
    }
    $task = vsql_fetch_assoc($res);
    $data = _unserialize($task["data"]);
    $progress["status"] = $task["status"];
    $progress["status_txt"] = $task["status_txt"];
    $progress["vpsid"] = $task["vpsid"];
    $progress["completed"] = 0;
    $progress["updated"] = $task["updated"];
    $progress["percent"] = $data["percent"];
    $progress["speed"] = $data["speed"];
    if( $task["status"] == -1 || $task["progress"] == 100 ) 
    {
        $progress["completed"] = 1;
    }
    return $progress;
}
function task_start($actid) 
{
    $GLOBALS["current_taskid"] = $actid;
    $res = update_query("UPDATE tasks \n\t\t\t\t\tSET started = '" . time() . "'\n\t\t\t\t\tWHERE actid = " . $actid);
    if( is_slave() ) 
    {
        to_master("tasks", "started", $actid, "actid", time());
        if( defined("INITIATE_REVERSE_SYNC") ) 
        {
            initiate_reverse_sync();
        }
    }
}
function task_update($actid, $status_txt = "", $status = 0, $data = "") 
{
    $actid = (int) $actid;
    $vpsid = $GLOBALS["cache_actid_vpsid"][$actid]["vpsid"];
    $action = $GLOBALS["cache_actid_vpsid"][$actid]["action"];
    if( empty($vpsid) || empty($action) ) 
    {
        $res = makequery("SELECT * FROM tasks WHERE actid = '" . $actid . "'");
        $row = vsql_fetch_assoc($res);
        $vpsid = $row["vpsid"];
        $action = $row["action"];
        $GLOBALS["cache_actid_vpsid"][$actid]["vpsid"] = $row["vpsid"];
        $GLOBALS["cache_actid_vpsid"][$actid]["action"] = $row["action"];
    }
    $token_vals = array( ":updated" => time(), ":status" => ($status == -1 ? -1 : 1), ":actid" => $actid );
    if( $status == 100 || $status == -1 ) 
    {
        $token_vals[":ended"] = time();
        unset($GLOBALS["current_taskid"]);
    }
    if( !empty($status_txt) ) 
    {
        $token_vals[":status_txt"] = $status_txt;
    }
    if( !empty($data) ) 
    {
        $data = (is_array($data) ? serialize($data) : $data);
        $token_vals[":data"] = $data;
    }
    if( 0 <= $status ) 
    {
        $token_vals[":progress"] = $status;
    }
    $res = update_query("UPDATE tasks\n\t\t\t\t\tSET updated = :updated,\n\t\t\t\t\t" . (($status == 100 || $status == -1 ? "ended = :ended," : "")) . "\n\t\t\t\t\t" . ((!empty($status_txt) ? "status_txt = :status_txt," : "")) . "\n\t\t\t\t\tstatus = :status\n\t\t\t\t\t" . ((!empty($data) ? ",data = :data" : "")) . "\n\t\t\t\t\t" . ((0 <= $status ? ",progress = :progress" : "")) . "\n\t\t\t\t\tWHERE actid = :actid", $token_vals);
    if( is_slave() ) 
    {
        $value["updated"] = time();
        $value["status"] = ($status == -1 ? -1 : 1);
        if( !empty($status_txt) ) 
        {
            $value["status_txt"] = $status_txt;
        }
        if( 0 <= $status ) 
        {
            $value["progress"] = $status;
        }
        if( $status == 100 || $status == -1 ) 
        {
            $value["ended"] = time();
        }
        if( !empty($data) ) 
        {
            $value["data"] = $data;
        }
        if( !empty($vpsid) ) 
        {
            $value["vpsid"] = $vpsid;
        }
        if( !empty($action) ) 
        {
            $value["action"] = $action;
        }
        $res = makequery("SELECT value FROM to_master \n\t\t\t\t\t\t\tWHERE tables = 'tasks'\n\t\t\t\t\t\t\tAND columns = 'array'\n\t\t\t\t\t\t\tAND id = :actid", array( ":actid" => $actid ));
        if( 0 < vsql_num_rows($res) ) 
        {
            $row = vsql_fetch_assoc($res);
            $prev_value = $row["value"];
            $prev_value = unserialize($prev_value);
            $value = array_replace($prev_value, $value);
        }
        to_master("tasks", "array", $actid, "actid", $value);
        if( defined("INITIATE_REVERSE_SYNC") ) 
        {
            initiate_reverse_sync();
        }
    }
}
function task_update_echo($actid, $status_txt = "", $status = 0, $data = "") 
{
    echo "Progress: " . $status . ": " . $status_txt . "\n";
    return task_update($actid, $status_txt, $status, $data);
}
function tasks_admin_process($action, $data, $status = 1, $vpsid = 0, $uid = 0, $replace = 0, $actid = 0) 
{
    global $user;
    global $globals;
    global $l;
    global $error;
    $uid = (empty($uid) ? 0 : $uid);
    $data = (is_array($data) ? serialize($data) : $data);
    if( !empty($replace) ) 
    {
        $token_vals = array( ":data" => $data, ":status" => ($status == -1 ? -1 : 1), ":vpsid" => $vpsid, ":updated" => time(), ":actid" => $actid );
        if( $status == 100 || $status == -1 ) 
        {
            $token_vals["ended"] = time();
        }
        if( 0 <= $status ) 
        {
            $token_vals[":progress"] = $status;
        }
        $res = update_query("UPDATE tasks \n\t\t\t\t\t\tSET data = :data,\n\t\t\t\t\t\tstatus = :status,\n\t\t\t\t\t\t" . ((0 <= $status ? "progress = :progress," : "")) . "\n\t\t\t\t\t\tvpsid = :vpsid,\n\t\t\t\t\t\t" . (($status == 100 || $status == -1 ? "ended = :ended," : "")) . "\n\t\t\t\t\t\tupdated = :updated\n\t\t\t\t\t\tWHERE actid = :actid", $token_vals);
    }
    else 
    {
        $token_vals = array( ":uid" => $uid, ":vpsid" => $vpsid, ":action" => $action, ":data" => $data, ":time" => time(), ":status" => ($status == -1 ? -1 : 1), ":ip" => $_SERVER["REMOTE_ADDR"] );
        if( 0 <= $status ) 
        {
            $token_vals[":progress"] = $status;
        }
        $actid = insert_and_id("INSERT INTO tasks\n\t\t\t\t\t\t\tSET `uid` = :uid,\n\t\t\t\t\t\t\t`vpsid` = :vpsid,\n\t\t\t\t\t\t\t`action` = :action,\n\t\t\t\t\t\t\t`data` = :data,\n\t\t\t\t\t\t\t`time` = :time,\n\t\t\t\t\t\t\t`status` = :status,\n\t\t\t\t\t\t\t" . ((0 <= $status ? "progress = :progress," : "")) . "\n\t\t\t\t\t\t\t`ip` = :ip", $token_vals);
    }
    if( is_slave() ) 
    {
        if( !empty($replace) ) 
        {
            $value["updated"] = time();
        }
        else 
        {
            $value["uid"] = $uid;
            $value["action"] = $action;
        }
        $value["actid"] = $actid;
        $value["vpsid"] = $vpsid;
        $value["data"] = $data;
        $value["status"] = ($status == -1 ? -1 : 1);
        $value["status_txt"] = $status_txt;
        if( 0 <= $status ) 
        {
            $value["progress"] = $status;
        }
        if( $status == 100 || $status == -1 ) 
        {
            $value["ended"] = time();
        }
        to_master("tasks", "array", $actid, "actid", $value);
        if( defined("INITIATE_REVERSE_SYNC") ) 
        {
            initiate_reverse_sync();
        }
    }
    $GLOBALS["cache_actid_vpsid"][$actid]["vpsid"] = $vpsid;
    $GLOBALS["cache_actid_vpsid"][$actid]["action"] = $action;
    return $actid;
}
function tasks_running($action, $vpsid = 0, $uid = 0) 
{
    $where = array( );
    $where["action"] = "action = '" . $action . "'";
    $where["started"] = "started > '0'";
    $where["ended"] = "ended = '0'";
    if( !empty($vpsid) ) 
    {
        $where["vpsid"] = "vpsid = '" . $vpsid . "'";
    }
    if( !empty($uid) ) 
    {
        $where["uid"] = "uid = '" . $uid . "'";
    }
    $res = makequery("SELECT * FROM `tasks` WHERE " . implode(" AND ", $where));
    $tasks = array( );
    for( $i = 0; $i < vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $data = unserialize($row["data"]);
        if( !empty($data["pid"]) ) 
        {
            vexec("/bin/ps " . $data["pid"], $output);
            if( 1 < count($output) ) 
            {
                $tasks[] = $row;
            }
        }
    }
    return $tasks;
}
function logs_admin($action, $data, $status = 1, $id = 0, $uid = 0) 
{
    global $user;
    global $globals;
    global $l;
    global $error;
    $uid = (empty($uid) ? 0 : $uid);
    return insert_and_id("INSERT INTO logs_admin\n\t\t\t\t\t\tSET uid = :uid,\n\t\t\t\t\t\tid = :id,\n\t\t\t\t\t\taction = :action,\n\t\t\t\t\t\t`data` = :data,\n\t\t\t\t\t\t`time` = :time,\n\t\t\t\t\t\t`status` = :status,\n\t\t\t\t\t\tip = :ip", array( ":uid" => $uid, ":id" => $id, ":action" => $action, ":data" => $data, ":time" => time(), ":status" => $status, ":ip" => $_SERVER["REMOTE_ADDR"] ));
}
function ip_logs($vpsid) 
{
    global $user;
    global $globals;
    global $l;
    global $error;
    $ipes = array( );
    $res = makequery("SELECT * from `ips`\n\t\t\tWHERE vpsid = '" . $vpsid . "'");
    while( $row = vsql_fetch_assoc($res) ) 
    {
        $ipes[$row["ipid"]] = $row["ip"];
    }
    $res = makequery("SELECT * from `vps`\n\t\t\tWHERE vpsid= '" . $vpsid . "'");
    if( 0 < vsql_num_rows($res) ) 
    {
        $row = vsql_fetch_assoc($res);
        $userid = $row["uid"];
        $res = makequery("SELECT * from `users`\n\t\t\t\tWHERE uid= '" . $userid . "'");
        if( 0 < vsql_num_rows($res) ) 
        {
            $row = vsql_fetch_assoc($res);
            $useremail = $row["email"];
        }
        if( !empty($row["pid"]) ) 
        {
            $res = makequery("SELECT * from `users`\n\t\t\t\t\tWHERE uid= '" . $row["pid"] . "'");
            if( 0 < vsql_num_rows($res) ) 
            {
                $row = vsql_fetch_assoc($res);
                $cid = $row["uid"];
                $cemail = $row["email"];
            }
        }
    }
    foreach( $ipes as $k => $v ) 
    {
        insert_and_id("INSERT INTO ip_logs\n\t\t\t\tSET ipid = :ipid,\n\t\t\t\tip = :ip,\n\t\t\t\tvpsid = :vpsid,\n\t\t\t\tuid = :uid,\n\t\t\t\t`email` = :email,\n\t\t\t\tcloud_uid = :cloud_uid,\n\t\t\t\t`cloud_email` = :cloud_email,\n\t\t\t\t`time` = :time,\n\t\t\t\t`date` = :date", array( ":ipid" => $k, ":ip" => $v, ":vpsid" => $vpsid, ":uid" => $userid, ":email" => $useremail, ":cloud_uid" => (empty($cid) ? 0 : $cid), ":cloud_email" => (empty($cemail) ? 0 : $cemail), ":time" => time(), ":date" => time() ));
    }
}
function logs_login($username, $vpsid = 0, $status = 1) 
{
    global $user;
    global $globals;
    global $l;
    global $error;
    return insert_and_id("INSERT INTO logs_login\n\t\t\t\t\t\tSET username = :username,\n\t\t\t\t\t\tvpsid = :vpsid,\n\t\t\t\t\t\t`time` = :time,\n\t\t\t\t\t\t`status` = :status,\n\t\t\t\t\t\tip = :ip", array( ":username" => $username, ":vpsid" => $vpsid, ":time" => time(), ":status" => $status, ":ip" => $_SERVER["REMOTE_ADDR"] ));
}
function vps_task($action, $data, $status = 1, $vpsid = 0, $uid = 0, $replace = 0, $status_txt = "") 
{
    global $user;
    global $globals;
    global $l;
    global $error;
    $uid = (empty($uid) ? 0 : $uid);
    if( !empty($replace) ) 
    {
        $replace_actid = 0;
        $res = makequery("SELECT * FROM `tasks`\n\t\t\t\t\t\tWHERE vpsid = '" . $vpsid . "'\n\t\t\t\t\t\tAND `action` = '" . $action . "'\n\t\t\t\t\t\tAND started = 0 \n\t\t\t\t\t\tAND updated = 0 \n\t\t\t\t\t\tAND ended = 0\n\t\t\t\t\t\tORDER BY actid ASC");
        if( 0 < vsql_num_rows($res) ) 
        {
            for( $i = 0; $i < vsql_num_rows($res);
            $i++ ) 
            {
                $row = vsql_fetch_assoc($res);
                $tasks[$row["actid"]] = $row;
                $replace_actid = $row["actid"];
            }
        }
        $keys = @implode(", ", @array_keys($tasks));
        $keys = (empty($keys) ? 0 : $keys);
        $res = makequery("DELETE FROM `tasks`\n\t\t\t\t\tWHERE vpsid = '" . $vpsid . "'\n\t\t\t\t\tAND actid IN (" . $keys . ")");
    }
    $token_vals = array( ":uid" => $uid, ":vpsid" => $vpsid, ":action" => $action, ":data" => $data, ":time" => time(), ":status_txt" => $status_txt, ":status" => ($status == -1 ? -1 : 1), ":ip" => $_SERVER["REMOTE_ADDR"] );
    if( 0 <= $status ) 
    {
        $token_vals[":progress"] = $status;
    }
    if( !empty($replace_actid) ) 
    {
        $token_vals[":actid"] = $replace_actid;
    }
    $actid = insert_and_id("INSERT INTO tasks\n\t\t\t\t\t\tSET uid = :uid,\n\t\t\t\t\t\t" . ((!empty($replace_actid) ? "actid = :actid," : "")) . "\n\t\t\t\t\t\tvpsid = :vpsid,\n\t\t\t\t\t\taction = :action,\n\t\t\t\t\t\t`data` = :data,\n\t\t\t\t\t\t`time` = :time,\n\t\t\t\t\t\t`status` = :status,\n\t\t\t\t\t\t" . ((0 <= $status ? "progress = :progress," : "")) . "\n\t\t\t\t\t\t`status_txt` = :status_txt,\n\t\t\t\t\t\tip = :ip", $token_vals);
    if( is_slave() ) 
    {
        $value["actid"] = $actid;
        $value["uid"] = $uid;
        $value["vpsid"] = $vpsid;
        $value["action"] = $action;
        $value["data"] = $data;
        $value["time"] = time();
        $value["status"] = ($status == -1 ? -1 : 1);
        $value["status_txt"] = $status_txt;
        $value["ip"] = $_SERVER["REMOTE_ADDR"];
        if( 0 <= $status ) 
        {
            $value["progress"] = $status;
        }
        to_master("tasks", "array", $actid, "actid", $value);
    }
    return $actid;
}
function action_text($action, $data, $admin = 1) 
{
    global $l;
    load_lang("log_action");
    $a = (!empty($admin) ? "a" : "");
    $txt = (empty($l[$a . "log_act_" . $action]) ? ucfirst($action) : $l[$a . "log_act_" . $action]);
    if( !empty($data) ) 
    {
        $txt .= " - " . $data;
    }
    return $txt;
}
function new_mac() 
{
    $c = "abcdef0123456789";
    $r = array( );
    for( $i = 1; $i <= 6; $i++ ) 
    {
        $r[] = $c[rand(0, 15)] . $c[rand(0, 15)];
    }
    return implode(":", $r);
}
function valid_mac($mac_addr) 
{
    $validval = (preg_match("/^[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}\$/i", $mac_addr) ? 1 : 0);
    if( !empty($validval) ) 
    {
        return true;
    }
    return false;
}
function fstypes() 
{
    $fstypes["0"] = "Empty";
    $fstypes["1"] = "FAT12";
    $fstypes["2"] = "XENIX root";
    $fstypes["3"] = "XENIX usr";
    $fstypes["4"] = "FAT16 <32M";
    $fstypes["5"] = "Extended";
    $fstypes["6"] = "FAT16";
    $fstypes["7"] = "HPFS/NTFS";
    $fstypes["8"] = "AIX";
    $fstypes["9"] = "AIX bootable";
    $fstypes["a"] = "OS/2 Boot Manag";
    $fstypes["b"] = "W95 FAT32";
    $fstypes["c"] = "W95 FAT32 (LBA)";
    $fstypes["e"] = "W95 FAT16 (LBA)";
    $fstypes["f"] = "W95 Ext'd (LBA)";
    $fstypes["10"] = "OPUS";
    $fstypes["11"] = "Hidden FAT12";
    $fstypes["12"] = "Compaq diagnost";
    $fstypes["14"] = "Hidden FAT16 <3";
    $fstypes["16"] = "Hidden FAT16";
    $fstypes["17"] = "Hidden HPFS/NTF";
    $fstypes["18"] = "AST SmartSleep";
    $fstypes["1b"] = "Hidden W95 FAT3";
    $fstypes["1c"] = "Hidden W95 FAT3";
    $fstypes["1e"] = "Hidden W95 FAT1";
    $fstypes["24"] = "NEC DOS";
    $fstypes["39"] = "Plan 9";
    $fstypes["3c"] = "PartitionMagic";
    $fstypes["40"] = "Venix 80286";
    $fstypes["41"] = "PPC PReP Boot";
    $fstypes["42"] = "SFS";
    $fstypes["4d"] = "QNX4.x";
    $fstypes["4e"] = "QNX4.x 2nd part";
    $fstypes["4f"] = "QNX4.x 3rd part";
    $fstypes["50"] = "OnTrack DM";
    $fstypes["51"] = "OnTrack DM6 Aux";
    $fstypes["52"] = "CP/M";
    $fstypes["53"] = "OnTrack DM6 Aux";
    $fstypes["54"] = "OnTrackDM6";
    $fstypes["55"] = "EZ-Drive";
    $fstypes["56"] = "Golden Bow";
    $fstypes["5c"] = "Priam Edisk";
    $fstypes["61"] = "SpeedStor";
    $fstypes["63"] = "GNU HURD or Sys";
    $fstypes["64"] = "Novell Netware";
    $fstypes["65"] = "Novell Netware";
    $fstypes["70"] = "DiskSecure Mult";
    $fstypes["75"] = "PC/IX";
    $fstypes["80"] = "Old Minix";
    $fstypes["81"] = "Minix / old Lin";
    $fstypes["82"] = "Linux swap";
    $fstypes["83"] = "Linux";
    $fstypes["84"] = "OS/2 hidden C:";
    $fstypes["85"] = "Linux extended";
    $fstypes["86"] = "NTFS volume set";
    $fstypes["87"] = "NTFS volume set";
    $fstypes["88"] = "Linux plaintext";
    $fstypes["8e"] = "Linux LVM";
    $fstypes["93"] = "Amoeba";
    $fstypes["94"] = "Amoeba BBT";
    $fstypes["9f"] = "BSD/OS";
    $fstypes["a0"] = "IBM Thinkpad hi";
    $fstypes["a5"] = "FreeBSD";
    $fstypes["a6"] = "OpenBSD";
    $fstypes["a7"] = "NeXTSTEP";
    $fstypes["a8"] = "Darwin UFS";
    $fstypes["a9"] = "NetBSD";
    $fstypes["ab"] = "Darwin boot";
    $fstypes["af"] = "HFS / HFS+";
    $fstypes["b7"] = "BSDI fs";
    $fstypes["b8"] = "BSDI swap";
    $fstypes["bb"] = "Boot Wizard hid";
    $fstypes["be"] = "Solaris boot";
    $fstypes["c1"] = "DRDOS/sec (FAT-";
    $fstypes["bf"] = "Solaris";
    $fstypes["c4"] = "DRDOS/sec (FAT-";
    $fstypes["c6"] = "DRDOS/sec (FAT-";
    $fstypes["c7"] = "Syrinx";
    $fstypes["da"] = "Non-FS data";
    $fstypes["db"] = "CP/M / CTOS / .";
    $fstypes["de"] = "Dell Utility";
    $fstypes["df"] = "BootIt";
    $fstypes["e1"] = "DOS access";
    $fstypes["e3"] = "DOS R/O";
    $fstypes["e4"] = "SpeedStor";
    $fstypes["eb"] = "BeOS fs";
    $fstypes["ee"] = "GPT";
    $fstypes["ef"] = "EFI (FAT-12/16/";
    $fstypes["f0"] = "Linux/PA-RISC b";
    $fstypes["f1"] = "SpeedStor";
    $fstypes["f4"] = "SpeedStor";
    $fstypes["f2"] = "DOS secondary";
    $fstypes["fb"] = "VMware VMFS";
    $fstypes["fc"] = "VMware VMKCORE";
    $fstypes["fd"] = "Linux raid auto";
    $fstypes["fe"] = "LANstep";
    $fstypes["ff"] = "BBT";
    return $fstypes;
}
function diskinfo($dev) 
{
    $ret = array( );
    $ret["num"]["linux"] = 0;
    $ret["num"]["windows"] = 0;
    $ret["parts"] = array( );
    $ret["rawparts"] = array( );
    $ret["numparts"] = 0;
    vexec("/sbin/kpartx " . $dev, $parts);
    $ret["numparts"] = count($parts);
    if( $ret["numparts"] < 1 ) 
    {
        return $ret;
    }
    unset($parts);
    vexec("/sbin/sfdisk -luS -q " . $dev, $ret["rawparts"]);
    $ret["rawparts"] = array_slice($ret["rawparts"], 0 - max($ret["numparts"], 4));
    foreach( $ret["rawparts"] as $k => $v ) 
    {
        $tmp = preg_split("/[\\s]+/is", trim($ret["rawparts"][$k]));
        $part_type = strtolower($tmp[count($tmp) - 1]);
        $ret["parts"][$k]["start"] = trim($tmp[count($tmp) - 5]);
        $ret["parts"][$k]["hextype"] = trim($tmp[count($tmp) - 2]);
        $ret["parts"][$k]["boot"] = ($tmp[1] == "*" ? "*" : "-");
        if( $part_type == "linux" ) 
        {
            $ret["parts"][$k]["islinux"] = 1;
            $ret["num"]["linux"]++;
        }
        else 
        {
            if( preg_match("/linux swap/is", $ret["rawparts"][$k]) ) 
            {
                $ret["parts"][$k]["isswap"] = 1;
                $ret["num"]["linux"]++;
            }
            else 
            {
                if( preg_match("/ntfs/is", $part_type) ) 
                {
                    $ret["parts"][$k]["iswindows"] = 1;
                    $ret["num"]["windows"]++;
                }
            }
        }
    }
    return $ret;
}
function file_diskinfo($dev) 
{
    global $globals;
    $ret = array( );
    $ret["num"]["linux"] = 0;
    $ret["num"]["windows"] = 0;
    $ret["parts"] = array( );
    $ret["rawparts"] = array( );
    $ret["numparts"] = 0;
    vexec("guestfish -a " . $dev . " 2>/dev/null << EOF \nrun\n-list-devices\necho \"VIRTUALIZOR\"\n-blockdev-getsz /dev/sda\necho \"VIRTUALIZOR\"\n-part-list /dev/sda\necho \"VIRTUALIZOR\"\n-part-get-mbr-id /dev/sda 1\n-part-get-mbr-id /dev/sda 2\n-part-get-mbr-id /dev/sda 3\n-part-get-mbr-id /dev/sda 4\necho \"VIRTUALIZOR\"\n-part-get-bootable /dev/sda 1\n-part-get-bootable /dev/sda 2\n-part-get-bootable /dev/sda 3\n-part-get-bootable /dev/sda 4\nEOF", $parts);
    $details = implode("\n", $parts);
    $details = explode("VIRTUALIZOR", $details);
    foreach( $details as $k => $v ) 
    {
        $details[$k] = trim($v);
    }
    $details[3] = explode("\n", $details[3]);
    $details[4] = explode("\n", $details[4]);
    $partitions = array( );
    if( preg_match("/\\}/", $details[2]) ) 
    {
        $tmp = preg_replace("/\\[.\\](\\s*)\\=(\\s*)/is", "", $details[2]);
        $tmp = preg_split("/\\}(\\s*)\\{/is", $tmp);
        foreach( $tmp as $tk => $tv ) 
        {
            $tmp[$tk] = $tv = trim(str_replace(array( "{", "}" ), array( "", "" ), $tv));
            $tv = explode("\n", $tv);
            foreach( $tv as $k => $v ) 
            {
                $v = explode(":", $v);
                $partitions[$tk][trim($v[0])] = trim($v[1]);
            }
        }
        preg_match("/(\\s*?)part_start:(\\s*?)(\\d+)/", $details[2], $matches);
        $ret["start_offset"] = (int) $matches[3];
    }
    $ret["numparts"] = count($partitions);
    $ret["disk_max_sectors"] = $details[1];
    if( $ret["numparts"] < 1 ) 
    {
        return $ret;
    }
    $fstypes = fstypes();
    foreach( $partitions as $k => $v ) 
    {
        $ret["parts"][$k]["start"] = $v["part_start"] / 512;
        $ret["parts"][$k]["hextype"] = str_replace("0x", "", $details[3][$k]);
        $ret["parts"][$k]["boot"] = (!empty($details[4][$k]) && $details[4][$k] == "true" ? true : false);
        $part_type = strtolower($fstypes[$ret["parts"][$k]["hextype"]]);
        $partitions[$k]["part_type"] = $part_type;
        if( $part_type == "linux" ) 
        {
            $ret["parts"][$k]["islinux"] = 1;
            $ret["num"]["linux"]++;
        }
        else 
        {
            if( preg_match("/linux swap/is", $part_type) ) 
            {
                $ret["parts"][$k]["isswap"] = 1;
                $ret["num"]["linux"]++;
            }
            else 
            {
                if( preg_match("/ntfs/is", $part_type) ) 
                {
                    $ret["parts"][$k]["iswindows"] = 1;
                    $ret["num"]["windows"]++;
                }
            }
        }
    }
    $ret["rawparts"] = $partitions;
    return $ret;
}
function is_safe_file($path) 
{
    if( file_exists($path) && realpath($path) != $path ) 
    {
        return false;
    }
    if( is_link($path) ) 
    {
        return false;
    }
    $stat = @stat($path);
    if( !is_dir($path) && 1 < $stat["nlink"] ) 
    {
        return false;
    }
    return true;
}
function sshkey_clean($path) 
{
    if( empty($path) || realpath($path . "/etc") == "/etc" || realpath($path) != $path ) 
    {
        return false;
    }
    if( !is_safe_file($path . "/etc/ssh/ssh_host_rsa_key") || !is_safe_file($path . "/etc/ssh/ssh_host_dsa_key") ) 
    {
        return false;
    }
    vexec("/bin/rm -rf " . $path . "/etc/ssh/ssh_host*");
    if( is_file($path . "/etc/network/interfaces") ) 
    {
        vexec("/usr/bin/ssh-keygen -t rsa -N \"\" -f " . $path . "/etc/ssh/ssh_host_rsa_key");
        vexec("/usr/bin/ssh-keygen -t dsa -N \"\" -f " . $path . "/etc/ssh/ssh_host_dsa_key");
    }
}
function dns_configure($path, $vps) 
{
    global $globals;
    if( empty($path) || realpath($path . "/etc") == "/etc" || realpath($path) != $path ) 
    {
        return false;
    }
    if( !is_safe_file($path . "/etc/resolv.conf.org") || !is_safe_file($path . "/etc/resolv.conf") ) 
    {
        return false;
    }
    if( is_dir($path . "/etc") ) 
    {
        $dns = unserialize($vps["dns_nameserver"]);
        if( !empty($dns) ) 
        {
            $ret1 = vexec("/bin/mv " . $path . "/etc/resolv.conf " . $path . "/etc/resolv.conf.org", $o1);
            $returnval = 0;
            foreach( $dns as $f => $d ) 
            {
                $ret = vexec("/bin/echo \"nameserver " . $d . "\"  >> " . $path . "/etc/resolv.conf", $o);
                $returnval += $ret;
            }
            if( empty($returnval) ) 
            {
                vexec("rm -f" . $path . "/etc/resolv.conf.org");
                return NULL;
            }
            vexec("mv " . $path . "/etc/resolv.conf.org " . $path . "/etc/resolv.conf");
        }
    }
}
function network_configure($path, $ips, $dns, $add_route) 
{
    global $globals;
    if( empty($path) || realpath($path . "/etc") == "/etc" || realpath($path) != $path ) 
    {
        return false;
    }
    $_ips = $ips;
    $ips = array( );
    $ips6 = array( );
    $ips_int = array( );
    $add_ipv6_route = 0;
    $has_v6 = false;
    $has_v6s = false;
    foreach( $_ips as $k => $v ) 
    {
        if( !empty($v["internal"]) ) 
        {
            $ips_int[] = $v;
        }
        else 
        {
            if( !empty($v["ipv6"]) ) 
            {
                if( !empty($v["ipr_netmask"]) && !empty($v["ipr_ips"]) ) 
                {
                    $ipr_ips = _unserialize($v["ipr_ips"]);
                    if( !empty($ipr_ips) && is_array($ipr_ips) ) 
                    {
                        $v["ipr_ips"] = $ipr_ips;
                    }
                    $has_v6s = true;
                }
                if( !$has_v6s ) 
                {
                    $has_v6 = true;
                }
                $ips6[$v["ipid"]] = $v;
                if( !empty($v["routing"]) ) 
                {
                    $add_ipv6_route = 1;
                }
            }
            else 
            {
                $ips[] = $v;
            }
        }
    }
    if( is_dir($path . "/etc/sysconfig/network-scripts") ) 
    {
        foreach( glob($path . "/etc/sysconfig/network-scripts/ifcfg-eth0*") as $filename ) 
        {
            if( !is_safe_file($filename) ) 
            {
                return false;
            }
        }
        foreach( glob($path . "/etc/sysconfig/network-scripts/route-eth0*") as $filename ) 
        {
            if( !is_safe_file($filename) ) 
            {
                return false;
            }
        }
        if( !is_safe_file($path . "/etc/sysconfig/network") ) 
        {
            return false;
        }
        vexec("rm -rf " . $path . "/etc/sysconfig/network-scripts/ifcfg-eth0:*");
        if( $add_route ) 
        {
            vexec("rm -rf " . $path . "/etc/sysconfig/network-scripts/route-eth0:*");
        }
        foreach( $ips as $k => $v ) 
        {
            $v["dev"] = "eth0" . (($k == 0 ? "" : ":" . ($k - 1)));
            $v["netmask"] = (empty($v["netmask"]) ? (empty($ips[0]["netmask"]) ? "255.255.255.0" : $ips[0]["netmask"]) : $v["netmask"]);
            $v["gateway"] = (empty($v["gateway"]) ? (empty($ips[0]["gateway"]) ? "" : $ips[0]["gateway"]) : $v["gateway"]);
            $eth = "DEVICE=" . $v["dev"] . "\nBOOTPROTO=static\nONBOOT=yes\nIPADDR=" . $v["ip"] . "\nNETMASK=" . $v["netmask"] . "\n" . ((empty($v["gateway"]) || $k != 0 ? "" : "GATEWAY=" . $v["gateway"])) . "\n" . ((empty($v["mtu"]) ? "" : "\n" . "MTU=" . $v["mtu"])) . "\n";
            writefile($path . "/etc/sysconfig/network-scripts/ifcfg-" . $v["dev"], $eth, 1);
            if( $add_route ) 
            {
                $route = ((empty($v["gateway"]) ? "" : $v["gateway"])) . " dev " . $v["dev"] . "\ndefault via " . ((empty($v["gateway"]) ? "" : $v["gateway"])) . " dev " . $v["dev"] . "\n";
                writefile($path . "/etc/sysconfig/network-scripts/route-" . $v["dev"], $route, 1);
            }
        }
        if( 0 < count($ips6) ) 
        {
            $network = file($path . "/etc/sysconfig/network");
            foreach( $network as $nk => $nv ) 
            {
                if( preg_match("/NETWORKING_IPV6/is", $nv) ) 
                {
                    $network[$nk] = "NETWORKING_IPV6=yes\n";
                }
            }
            writefile($path . "/etc/sysconfig/network", implode("", $network), 1);
            $eth0 = implode("", file($path . "/etc/sysconfig/network-scripts/ifcfg-eth0"));
            if( empty($ips) ) 
            {
                $eth0 = "DEVICE=eth0\nBOOTPROTO=static\nONBOOT=yes";
            }
            $current = current($ips6);
            unset($ips6[$current["ipid"]]);
            $eth0 .= "\nIPV6INIT=yes\nIPV6ADDR=" . $current["ip"] . ((empty($current["ipr_netmask"]) ? (empty($current["netmask"]) ? "" : "/" . $current["netmask"]) : "/" . $current["ipr_netmask"])) . "\n" . ((empty($current["mtu"]) ? "" : "IPV6_MTU=" . $current["mtu"])) . "\nIPV6_DEFAULTGW=" . $current["gateway"];
            if( !empty($current["ipr_ips"]) && is_array($current["ipr_ips"]) ) 
            {
                foreach( $current["ipr_ips"] as $ipr_ip ) 
                {
                    $_ips6[] = $ipr_ip . ((empty($current["ipr_netmask"]) ? (empty($current["netmask"]) ? "" : "/" . $current["netmask"]) : "/" . $current["ipr_netmask"]));
                }
            }
            foreach( $ips6 as $k => $v ) 
            {
                $_ips6[] = $v["ip"] . ((empty($v["ipr_netmask"]) ? (empty($v["netmask"]) ? "" : "/" . $v["netmask"]) : "/" . $v["ipr_netmask"]));
                if( !empty($v["ipr_ips"]) && is_array($v["ipr_ips"]) ) 
                {
                    foreach( $v["ipr_ips"] as $ipr_ip ) 
                    {
                        $_ips6[] = $ipr_ip . ((empty($v["ipr_netmask"]) ? (empty($v["netmask"]) ? "" : "/" . $v["netmask"]) : "/" . $v["ipr_netmask"]));
                    }
                }
            }
            if( 0 < count($_ips6) ) 
            {
                $eth0 .= "\n" . "IPV6ADDR_SECONDARIES=\"" . implode(" \\ \n", $_ips6) . "\"";
            }
            $eth0 .= "\n";
            writefile($path . "/etc/sysconfig/network-scripts/ifcfg-eth0", $eth0, 1);
            if( $has_v6 && $add_ipv6_route || !$has_v6 && $has_v6s ) 
            {
                vexec("rm -rf " . $path . "/etc/sysconfig/network-scripts/route6-eth0");
                $route6 = ((empty($current["gateway"]) ? "" : $current["gateway"])) . " dev eth0\ndefault via " . ((empty($current["gateway"]) ? "" : $current["gateway"])) . " dev eth0\n";
                writefile($path . "/etc/sysconfig/network-scripts/route6-eth0", $route6, 1, 420);
            }
        }
        if( !empty($ips_int) ) 
        {
            foreach( glob($path . "/etc/sysconfig/network-scripts/ifcfg-eth1*") as $filename ) 
            {
                if( !is_safe_file($filename) ) 
                {
                    return false;
                }
            }
            vexec("rm -rf " . $path . "/etc/sysconfig/network-scripts/ifcfg-eth1:*");
            foreach( $ips_int as $k => $v ) 
            {
                $v["dev"] = "eth1" . (($k == 0 ? "" : ":" . ($k - 1)));
                $v["netmask"] = (empty($v["netmask"]) ? (empty($ips_int[0]["netmask"]) ? "255.255.255.0" : $ips_int[0]["netmask"]) : $v["netmask"]);
                $v["gateway"] = (empty($v["gateway"]) ? (empty($ips_int[0]["gateway"]) ? "" : $ips_int[0]["gateway"]) : $v["gateway"]);
                $eth = "DEVICE=" . $v["dev"] . "\nBOOTPROTO=static\nONBOOT=yes\nIPADDR=" . $v["ip"] . "\nNETMASK=" . $v["netmask"] . "\n" . ((empty($v["mtu"]) ? "" : "MTU=" . $v["mtu"])) . "\n";
                writefile($path . "/etc/sysconfig/network-scripts/ifcfg-" . $v["dev"], $eth, 1);
            }
        }
    }
    if( is_file($path . "/etc/network/interfaces") ) 
    {
        if( !is_safe_file($path . "/etc/network/interfaces") ) 
        {
            return false;
        }
        $eth = "# The loopback network interface\nauto lo\niface lo inet loopback\n\n# The primary network interface\n";
        foreach( $ips as $k => $v ) 
        {
            $v["dev"] = "eth0" . (($k == 0 ? "" : ":" . ($k - 1)));
            $v["netmask"] = (empty($v["netmask"]) ? (empty($ips[0]["netmask"]) ? "255.255.255.0" : $ips[0]["netmask"]) : $v["netmask"]);
            $v["gateway"] = (empty($v["gateway"]) ? (empty($ips[0]["gateway"]) ? "" : $ips[0]["gateway"]) : $v["gateway"]);
            $eth .= "auto " . $v["dev"] . "\niface " . $v["dev"] . " inet static\naddress " . $v["ip"] . "\nnetmask " . $v["netmask"] . "\n" . ((empty($v["mtu"]) ? "" : "mtu " . $v["mtu"]));
            if( empty($add_route) ) 
            {
                $eth .= (empty($v["gateway"]) ? "" : " \ngateway " . $v["gateway"] . "\n");
            }
            else 
            {
                $eth .= " \nbroadcast " . $v["ip"] . "\n" . ((empty($v["gateway"]) ? "" : "post-up route add " . $v["gateway"] . " dev " . $v["dev"])) . "\n" . ((empty($v["gateway"]) ? "" : "post-up route add default gw " . $v["gateway"] . " dev " . $v["dev"])) . "\n";
            }
        }
        if( 0 < count($ips6) ) 
        {
            $current = current($ips6);
            unset($ips6[$current["ipid"]]);
            $current["dev"] = "eth0";
            if( empty($ips) ) 
            {
                $eth .= "auto " . $current["dev"] . "\n";
            }
            $eth .= "iface " . $current["dev"] . " inet6 static\n\taddress " . $current["ip"] . "\n\tnetmask " . ((empty($current["ipr_netmask"]) ? (empty($current["netmask"]) ? "" : $current["netmask"]) : $current["ipr_netmask"])) . "\n" . ((empty($current["mtu"]) ? "" : "\tmtu " . $current["mtu"])) . "\n" . ((empty($current["gateway"]) || !empty($add_ipv6_route) ? "" : "\tgateway " . $current["gateway"]));
            if( !empty($current["ipr_ips"]) && is_array($current["ipr_ips"]) ) 
            {
                foreach( $current["ipr_ips"] as $ipr_ip ) 
                {
                    $eth .= "\n" . "\tup /sbin/ifconfig " . $current["dev"] . " inet6 add " . $ipr_ip . ((empty($current["ipr_netmask"]) ? (empty($current["netmask"]) ? "" : "/" . $current["netmask"]) : "/" . $current["ipr_netmask"]));
                }
            }
            foreach( $ips6 as $k => $v ) 
            {
                $eth .= "\n" . "\tup /sbin/ifconfig " . $current["dev"] . " inet6 add " . $v["ip"] . ((empty($v["ipr_netmask"]) ? (empty($v["netmask"]) ? "" : "/" . $v["netmask"]) : "/" . $v["ipr_netmask"]));
                if( !empty($v["ipr_ips"]) && is_array($v["ipr_ips"]) ) 
                {
                    foreach( $v["ipr_ips"] as $ipr_ip ) 
                    {
                        $eth .= "\n" . "\tup /sbin/ifconfig " . $current["dev"] . " inet6 add " . $ipr_ip . ((empty($v["ipr_netmask"]) ? (empty($v["netmask"]) ? "" : "/" . $v["netmask"]) : "/" . $v["ipr_netmask"]));
                    }
                }
            }
            if( ($has_v6 && $add_ipv6_route || !$has_v6 && $has_v6s) && !empty($current["gateway"]) ) 
            {
                $eth .= "\n" . "post-up /sbin/ip -r route add " . $current["gateway"] . " dev eth0\npost-up /sbin/ip -r route add default via " . $current["gateway"] . "\n";
            }
            $eth .= "\n\n";
        }
        if( !empty($ips_int) ) 
        {
            foreach( $ips_int as $k => $v ) 
            {
                $v["dev"] = "eth1" . (($k == 0 ? "" : ":" . ($k - 1)));
                $v["netmask"] = (empty($v["netmask"]) ? (empty($ips_int[0]["netmask"]) ? "255.255.255.0" : $ips_int[0]["netmask"]) : $v["netmask"]);
                $v["gateway"] = (empty($v["gateway"]) ? (empty($ips_int[0]["gateway"]) ? "" : $ips_int[0]["gateway"]) : $v["gateway"]);
                $eth .= "\nauto " . $v["dev"] . "\niface " . $v["dev"] . " inet static\naddress " . $v["ip"] . "\n" . ((empty($v["mtu"]) ? "" : "mtu " . $v["mtu"])) . "\nnetmask " . $v["netmask"];
            }
        }
        writefile($path . "/etc/network/interfaces", $eth, 1);
    }
    if( is_dir($path . "/etc/sysconfig/network") ) 
    {
        if( !is_safe_file($path . "/etc/sysconfig/network") || !is_safe_file($path . "/etc/sysconfig/network/ifcfg-eth0") || !is_safe_file($path . "/etc/init.d/after.local") || !is_safe_file($path . "/etc/sysconfig/network/routes") ) 
        {
            return false;
        }
        $eth = "DEVICE='eth0'\nBOOTPROTO='static'\nSTARTMODE='auto'\n";
        foreach( $ips as $k => $v ) 
        {
            $v["netmask"] = (empty($v["netmask"]) ? (empty($ips[0]["netmask"]) ? "255.255.255.0" : $ips[0]["netmask"]) : $v["netmask"]);
            if( $k == 0 ) 
            {
                $eth .= "IPADDR='" . $v["ip"] . "'\nNETMASK='" . $v["netmask"] . "'\n";
                $eth .= (empty($v["mtu"]) ? "" : "MTU='" . $v["mtu"] . "'\n");
            }
            else 
            {
                $eth .= "IPADDR_" . ($k - 1) . "='" . $v["ip"] . "'\nNETMASK_" . ($k - 1) . "='" . $v["netmask"] . "'\nLABEL_" . ($k - 1) . "='" . ($k - 1) . "'\n";
                $eth .= (empty($v["mtu"]) ? "" : "MTU_" . ($k - 1) . "='" . $v["mtu"] . "'\n");
            }
        }
        if( 0 < count($ips6) ) 
        {
            $i = $k;
            foreach( $ips6 as $ik => $iv ) 
            {
                if( empty($current) ) 
                {
                    $current = $iv;
                }
                $eth .= "IPADDR_" . $i . "='" . $iv["ip"] . "'\nPREFIXLEN_" . $i . "='" . ((empty($iv["ipr_netmask"]) ? (empty($iv["netmask"]) ? "" : $iv["netmask"]) : $iv["ipr_netmask"])) . "'\nLABEL_" . $i . "='" . $i . "'\n";
                $eth .= (empty($iv["mtu"]) ? "" : "MTU_" . $i . "='" . $iv["mtu"] . "'\n");
                $i++;
                if( !empty($iv["ipr_ips"]) && is_array($iv["ipr_ips"]) ) 
                {
                    foreach( $iv["ipr_ips"] as $ipr_ip ) 
                    {
                        $eth .= "IPADDR_" . $i . "='" . $ipr_ip . "'\nPREFIXLEN_" . $i . "='" . ((empty($iv["ipr_netmask"]) ? (empty($iv["netmask"]) ? "" : $iv["netmask"]) : $iv["ipr_netmask"])) . "'\nLABEL_" . $i . "='" . $i . "'\n";
                        $eth .= (empty($iv["mtu"]) ? "" : "MTU_" . $i . "='" . $iv["mtu"] . "'\n");
                        $i++;
                    }
                }
            }
        }
        writefile($path . "/etc/sysconfig/network/ifcfg-eth0", $eth, 1);
        $gw = "";
        if( !empty($ips[0]["gateway"]) ) 
        {
            $gw .= "default " . $ips[0]["gateway"] . " - -" . "\n";
        }
        if( !empty($current["gateway"]) ) 
        {
            $gw .= "default " . $current["gateway"] . " - -" . "\n";
        }
        writefile($path . "/etc/sysconfig/network/routes", $gw, 1);
        if( !empty($add_route) || $has_v6 && $add_ipv6_route || !$has_v6 && $has_v6s ) 
        {
            $route_gw = "#!/bin/sh" . "\n";
            if( !empty($add_route) && !empty($ips[0]["gateway"]) ) 
            {
                $route_gw .= "ip route add " . $ips[0]["gateway"] . " dev eth0" . "\n";
                $route_gw .= "route add -net default gw " . $ips[0]["gateway"] . "\n";
                $suse_route_write = 1;
            }
            if( ($has_v6 && $add_ipv6_route || !$has_v6 && $has_v6s) && !empty($current["gateway"]) ) 
            {
                $route_gw .= "ip -r route add " . $current["gateway"] . " dev eth0" . "\n";
                $route_gw .= "ip -r route add default via " . $current["gateway"] . "\n";
                $suse_route_write = 1;
            }
            if( !empty($suse_route_write) ) 
            {
                writefile($path . "/etc/init.d/after.local", $route_gw, 1);
                @chmod($path . "/etc/init.d/after.local", 493);
            }
        }
        if( !empty($ips_int) && is_safe_file($path . "/etc/sysconfig/network/ifcfg-eth1") ) 
        {
            $eth = "DEVICE='eth1'\nBOOTPROTO='static'\nSTARTMODE='auto'\n";
            foreach( $ips_int as $k => $v ) 
            {
                $v["netmask"] = (empty($v["netmask"]) ? (empty($ips_int[0]["netmask"]) ? "255.255.255.0" : $ips_int[0]["netmask"]) : $v["netmask"]);
                if( $k == 0 ) 
                {
                    $eth .= "IPADDR='" . $v["ip"] . "'\nNETMASK='" . $v["netmask"] . "'\n";
                    $eth .= (empty($v["mtu"]) ? "" : "MTU='" . $v["mtu"] . "'\n");
                }
                else 
                {
                    $eth .= "IPADDR_" . ($k - 1) . "='" . $v["ip"] . "'\nNETMASK_" . ($k - 1) . "='" . $v["netmask"] . "'\nLABEL_" . ($k - 1) . "='" . ($k - 1) . "'\n";
                    $eth .= (empty($v["mtu"]) ? "" : "MTU_" . ($k - 1) . "='" . $v["mtu"] . "'");
                }
            }
            writefile($path . "/etc/sysconfig/network/ifcfg-eth1", $eth, 1);
        }
    }
    if( is_dir($path . "/etc") ) 
    {
        if( !is_safe_file($path . "/etc/resolv.conf") ) 
        {
            return false;
        }
        if( !empty($dns["dns"]) ) 
        {
            $ns = "";
            foreach( $dns["dns"] as $key => $value ) 
            {
                $ns .= "nameserver " . $value . "\n";
            }
        }
        else 
        {
            $ips[0]["ns1"] = (empty($ips[0]["ns1"]) ? "4.2.2.1" : $ips[0]["ns1"]);
            $ips[0]["ns2"] = (empty($ips[0]["ns2"]) ? "4.2.2.2" : $ips[0]["ns2"]);
            $ns = "nameserver " . $ips[0]["ns1"] . "\nnameserver " . $ips[0]["ns2"] . "\n";
            if( 0 < count($ips6) || !empty($current) ) 
            {
                $ns .= "nameserver " . $current["ns1"] . "\nnameserver " . $current["ns2"] . "\n";
            }
        }
        writefile($path . "/etc/resolv.conf", $ns, 1);
    }
    if( !is_safe_file($path . "/etc/udev/rules.d/70-persistent-net.rules") ) 
    {
        return false;
    }
    if( file_exists($path . "/etc/udev/rules.d/70-persistent-net.rules") ) 
    {
        unlink($path . "/etc/udev/rules.d/70-persistent-net.rules");
    }
}
function hostname_configure($path, $host) 
{
    global $globals;
    if( empty($path) || realpath($path . "/etc") == "/etc" || realpath($path) != $path ) 
    {
        return false;
    }
    if( is_file($path . "/etc/hostname") ) 
    {
        if( !is_safe_file($path . "/etc/hostname") ) 
        {
            return false;
        }
        writefile($path . "/etc/hostname", $host . "\n", 1);
        return true;
    }
    if( is_file($path . "/etc/sysconfig/network") ) 
    {
        if( !is_safe_file($path . "/etc/sysconfig/network") ) 
        {
            return false;
        }
        $file = file($path . "/etc/sysconfig/network");
        foreach( $file as $k => $v ) 
        {
            if( preg_match("/hostname(\\s*?)=(\\s*?)(.*?)/is", $v) ) 
            {
                $found = 1;
                $file[$k] = "HOSTNAME=\"" . $host . "\"" . "\n";
            }
        }
        if( empty($found) ) 
        {
            $file[] = "HOSTNAME=\"" . $host . "\"" . "\n";
        }
        writefile($path . "/etc/sysconfig/network", implode("", $file), 1);
        return true;
    }
    else 
    {
        if( is_file($path . "/etc/HOSTNAME") ) 
        {
            if( !is_safe_file($path . "/etc/HOSTNAME") ) 
            {
                return false;
            }
            writefile($path . "/etc/HOSTNAME", $host . "\n", 1);
            return true;
        }
        return false;
    }
}
function valid_ipv6($ip) 
{
    $pattern = "/^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b)\\.){3}(\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b)\\.){3}(\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b)\\.){3}(\\b((25[0-5])|(1\\d{2})|(2[0-4]\\d)|(\\d{1,2}))\\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))\$/";
    if( !preg_match($pattern, $ip) ) 
    {
        return false;
    }
    return true;
}
function ip6range($start, $num = 1, $till = 7, $input_mask = 0) 
{
    $range = array( );
    $chars = "abcdef0123456789";
    $there = explode(":", $start);
    for( $i = 1; $i <= $num; $i++ ) 
    {
        $tmp = $there;
        if( !empty($input_mask) ) 
        {
            $last_key = count($tmp) - 1;
            $rem = $input_mask % 16;
            if( $rem != 0 ) 
            {
                $rem = $rem / 4;
                for( $j = 4; $rem < $j; $j-- ) 
                {
                    $tmp[$last_key] .= $chars[rand(0, 15)];
                }
            }
        }
        for( $t = count($tmp);
        $t <= $till;
        $t++ ) 
        {
            $tmp[] = $chars[rand(0, 15)] . $chars[rand(0, 15)] . $chars[rand(0, 15)] . $chars[rand(0, 15)];
        }
        $range[] = implode(":", $tmp);
    }
    if( $num == 1 ) 
    {
        return current($range);
    }
    return $range;
}
function ipv6_expand($addr) 
{
    if( strpos($addr, "::") !== false ) 
    {
        $part = explode("::", $addr);
        $part[0] = explode(":", $part[0]);
        $part[1] = explode(":", $part[1]);
        $missing = array( );
        for( $i = 0; $i < 8 - (count($part[0]) + count($part[1]));
        $i++ ) 
        {
            array_push($missing, "0000");
        }
        $missing = array_merge($part[0], $missing);
        $part = array_merge($missing, $part[1]);
    }
    else 
    {
        $part = explode(":", $addr);
    }
    foreach( $part as &$p ) 
    {
        while( strlen($p) < 4 ) 
        {
            $p = "0" . $p;
        }
    }
    unset($p);
    $result = implode(":", $part);
    if( strlen($result) == 39 ) 
    {
        return $result;
    }
    return false;
}
function sync($serid, $tables = array( )) 
{
    global $globals;
    global $servers;
    global $servergroups;
    global $SETTINGS;
    $data = array( );
    $allowed = array( "vps" => array( ), "ips" => array( ), "ippool" => array( ), "users" => array( ), "os" => array( ), "iso" => array( ), "enduser_iso" => array( ), "console_sessions" => array( ), "ippool_servers" => array( ), "backup_servers" => array( ), "os_distros" => array( ), "haproxy" => array( ), "backup_plans" => array( ), "plans" => array( ) );
    $info = $allowed;
    $info["vps"]["id"] = "vpsid";
    $info["ips"]["id"] = "ipid";
    $info["ippool"]["id"] = "ippid";
    $info["os"]["id"] = "osid";
    $info["iso"]["id"] = "uuid";
    $info["console_sessions"]["id"] = "vpsid";
    $info["os_distros"]["id"] = "distro";
    $info["haproxy"]["id"] = "id";
    $info["enduser_iso"]["id"] = "isoid";
    $info["backup_plans"]["id"] = "bpid";
    $info["backup_servers"]["id"] = "bid";
    $info["plans"]["id"] = "plid";
    $info["vps"]["serid"] = "serid";
    $info["ips"]["serid"] = "ip_serid";
    $info["ippool"]["serid"] = "ipp_serid";
    $info["console_sessions"]["serid"] = "serid";
    $info["haproxy"]["serid"] = "serid";
    $info["ips"]["ippid"] = "ippid";
    $info["ippool"]["ippid"] = "ippid";
    $resid = makequery("SELECT * FROM ippool_servers\n\t\t\t\t\t\tWHERE sgid = '" . $servers[$serid]["sgid"] . "'\n\t\t\t\t\t\tOR serid IN ('-1', '" . $serid . "')");
    $ipsid = array( );
    if( 1 <= vsql_num_rows($resid) ) 
    {
        for( $i = 0; $i < vsql_num_rows($resid);
        $i++ ) 
        {
            $row = vsql_fetch_assoc($resid);
            $ipsid[] = $row["ippid"];
            $row["sgid"] = -2;
            $row["serid"] = 0;
            $data["ippool_servers"][] = $row;
        }
    }
    $depends["vps"][] = array( "id" => "uuid", "did" => "vps_uuid", "key" => "did", "table" => "disks" );
    $depends["vps"][] = array( "id" => "uid", "did" => "uid", "key" => "uid", "table" => "users" );
    $tables = (empty($tables) ? $allowed : $tables);
    foreach( $tables as $k => $v ) 
    {
        if( $k == "ippool_servers" ) 
        {
            continue;
        }
        $where = array( );
        if( !empty($v) ) 
        {
            $where[] = "`" . $info[$k]["id"] . "` IN (" . implode(", ", $v) . ")";
        }
        if( !empty($info[$k]["serid"]) ) 
        {
            if( $k == "ippool" || $k == "ips" ) 
            {
                if( !empty($ipsid) ) 
                {
                    $where[] = "(`" . $info[$k]["ippid"] . "` IN (" . implode(",", $ipsid) . ") " . (($k == "ips" ? " OR `" . $info[$k]["serid"] . "` = '" . $serid . "'" : "")) . ")";
                }
            }
            else 
            {
                $where[] = "(`" . $info[$k]["serid"] . "` = '" . $serid . "' " . ((empty($info[$k]["serid_additional"]) ? "" : " OR `" . $info[$k]["serid"] . "` = '" . $info[$k]["serid_additional"] . "'")) . ")";
            }
        }
        $res = makequery("SELECT * FROM `" . $k . "`\n\t\t\t\t\t\t" . ((!empty($where) ? "WHERE " . implode(" AND ", $where) : "")));
        $data[$k] = array( );
        for( $i = 1; $i <= vsql_num_rows($res);
        $i++ ) 
        {
            $row = vsql_fetch_assoc($res);
            if( !empty($info[$k]["serid"]) ) 
            {
                $row[$info[$k]["serid"]] = 0;
            }
            $data[$k][$row[$info[$k]["id"]]] = $row;
        }
    }
    foreach( $depends as $dk => $dtables ) 
    {
        foreach( $dtables as $k => $v ) 
        {
            $where = array( );
            if( !empty($v["id"]) ) 
            {
                foreach( $data[$dk] as $x => $y ) 
                {
                    $dids[] = $y[$v["id"]];
                }
                if( !empty($dids) ) 
                {
                    $where[] = "`" . $v["did"] . "` IN ('" . implode("', '", $dids) . "')";
                }
            }
            $res = makequery("SELECT * FROM `" . $v["table"] . "`\n\t\t\t\t\t\t\t" . ((!empty($where) ? "WHERE " . implode(" AND ", $where) : "")));
            for( $i = 1; $i <= vsql_num_rows($res);
            $i++ ) 
            {
                $row = vsql_fetch_assoc($res);
                if( !empty($v["did"]) ) 
                {
                    $data[$v["table"]][$row[$v["key"]]] = $row;
                }
                else 
                {
                    $data[$v["table"]][$row[$v["did"]]] = $row;
                }
            }
        }
    }
    if( $serid != 0 ) 
    {
        $master_settings = load_master_settings();
        $slave_data = array( );
        foreach( $SETTINGS as $sk => $sv ) 
        {
            if( preg_match("/m/", $sv) && array_key_exists($sk, $master_settings) ) 
            {
                $slave_data[$sk] = $master_settings[$sk];
            }
        }
        $res = makequery("SELECT vnc_ip, internal_ip, settings FROM `servers` WHERE serid = '" . $serid . "'");
        $tmp_data = vsql_fetch_assoc($res);
        $data["servers"][0]["serid"] = 0;
        $data["servers"][0]["vnc_ip"] = $tmp_data["vnc_ip"];
        $data["servers"][0]["internal_ip"] = $tmp_data["internal_ip"];
        $tmp_data = unserialize($tmp_data["settings"]);
        if( !empty($tmp_data) ) 
        {
            foreach( $SETTINGS as $sk => $sv ) 
            {
                if( preg_match("/s/", $sv) && array_key_exists($sk, $tmp_data) ) 
                {
                    $slave_data[$sk] = $tmp_data[$sk];
                }
            }
        }
        $data["servers"][0]["settings"] = serialize($slave_data);
        $resid = makequery("SELECT * FROM storage_servers\n\t\t\t\t\t\t\tWHERE sgid = '" . $servers[$serid]["sgid"] . "'\n\t\t\t\t\t\t\tOR serid IN ('-1', '" . $serid . "')");
        $stids = array( );
        $data["storage"] = array( );
        $data["storage_servers"] = array( );
        if( 1 <= vsql_num_rows($resid) ) 
        {
            for( $i = 0; $i < vsql_num_rows($resid);
            $i++ ) 
            {
                $row = vsql_fetch_assoc($resid);
                $stids[$row["stid"]] = $row["stid"];
                $row["sgid"] = -2;
                $row["serid"] = 0;
                $data["storage_servers"][] = $row;
            }
            $res = makequery("SELECT * FROM storage\n\t\t\t\t\t\t\t\tWHERE stid IN (" . implode(",", $stids) . ")");
            for( $i = 1; $i <= vsql_num_rows($res);
            $i++ ) 
            {
                $row = vsql_fetch_assoc($res);
                $data["storage"][$row["stid"]] = $row;
            }
        }
    }
    $ret = base64_encode(gzcompress(serialize($data)));
    return $ret;
}
function storedata($data) 
{
    $r = _unserialize(gzuncompress(base64_decode($data)));
    if( !is_array($r) || empty($r) ) 
    {
        return false;
    }
    foreach( $r as $table => $values ) 
    {
        if( $table == "ippool_servers" ) 
        {
            $res = makequery("TRUNCATE TABLE `" . $table . "`");
            foreach( $values as $k => $v ) 
            {
                $res = makequery("INSERT INTO `" . $table . "`\n\t\t\t\t\t\t\t\t\tSET `ippid` = :ippid,\n\t\t\t\t\t\t\t\t\t`serid` = :serid,\n\t\t\t\t\t\t\t\t\t`sgid` = :sgid", array( ":ippid" => $v["ippid"], ":serid" => $v["serid"], ":sgid" => $v["sgid"] ));
            }
            continue;
        }
        else 
        {
            if( $table == "storage" ) 
            {
                $res = makequery("TRUNCATE TABLE `" . $table . "`");
            }
            if( $table == "iso" || $table == "enduser_iso" ) 
            {
                $res = makequery("TRUNCATE TABLE `" . $table . "`");
            }
            if( $table == "storage_servers" ) 
            {
                $res = makequery("TRUNCATE TABLE `" . $table . "`");
                foreach( $values as $k => $v ) 
                {
                    $res = makequery("INSERT INTO `" . $table . "`\n\t\t\t\t\t\t\t\t\tSET `stid` = " . $v["stid"] . ",\n\t\t\t\t\t\t\t\t\t`serid` = " . $v["serid"] . ",\n\t\t\t\t\t\t\t\t\t`sgid` = " . $v["sgid"] . "");
                }
                continue;
            }
            else 
            {
                $res = makequery("SHOW COLUMNS FROM `" . $table . "`", array( ), true);
                $temp = vsql_fetch_assoc($res);
                $key = $temp["Field"];
                if( empty($key) ) 
                {
                    continue;
                }
                foreach( $values as $k => $v ) 
                {
                    $str = array( );
                    foreach( $v as $col => $val ) 
                    {
                        $str[] = "`" . $col . "` = '" . addslashes($val) . "'";
                    }
                    if( $table == "servers" ) 
                    {
                        $res = makequery("SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\"");
                    }
                    $res = makequery("INSERT INTO `" . $table . "`\n\t\t\t\t\t\t\t\tSET " . implode(", ", $str) . "\n\t\t\t\t\t\t\t\tON DUPLICATE KEY UPDATE " . implode(", ", $str), array( ), true);
                }
                $keys = (empty($values) ? 0 : implode("', '", array_keys($values)));
                $res = makequery("DELETE FROM `" . $table . "`\n\t\t\t\t\t\tWHERE `" . $key . "` NOT IN ('" . $keys . "')", array( ), true);
            }
        }
    }
    return true;
}
function getos($name, $virt, $ip = "", $key = "") 
{
    global $globals;
    $ip = (empty($ip) ? $globals["masterip"] : $ip);
    $key = (empty($key) ? $globals["key"] : $key);
    if( empty($ip) ) 
    {
        return true;
    }
    if( 0 < @vfilesize($globals[$virt] . "/" . $name) ) 
    {
        return true;
    }
    $url = "https://" . $ip . ":4085/index.php?giveos=1&slavekey=" . rawurlencode($key) . "&os=" . rawurlencode($name) . "&osvirt=" . rawurlencode($virt);
    mkosdir();
    if( file_exists("/usr/bin/wget") ) 
    {
        $ret = vexec("/usr/bin/wget -O \"" . $globals[$virt] . "/" . $name . "\" \"" . $url . "\" --no-check-certificate", $o);
        $ret = (int) $ret;
        return empty($ret);
    }
    return save_web_file($url, $globals[$virt] . "/" . $name);
}
function vps_status($array, $live = 1) 
{
    global $user;
    global $servers;
    global $globals;
    global $kernel;
    if( empty($servers) ) 
    {
        if( !class_exists("cluster") ) 
        {
            include_once($globals["adminfiles"] . "/cluster.php");
        }
        $cluster = new cluster();
        list_servers();
    }
    else 
    {
        global $cluster;
    }
    return $cluster->vps_status($array, $live);
}
function sysctl_configure($property, $value) 
{
    $sysctl = file("/etc/sysctl.conf");
    foreach( $sysctl as $k => $v ) 
    {
        $v = trim($v);
        if( empty($v[0]) || $v[0] == "#" ) 
        {
            continue;
        }
        if( preg_match("/^" . preg_quote($property, "/") . "/is", $v) ) 
        {
            $sysctlline = $k;
        }
    }
    if( empty($sysctlline) ) 
    {
        $sysctl[] = (string) $property . " = " . $value . " \n";
    }
    else 
    {
        $sysctl[$sysctlline] = (string) $property . " = " . $value . " \n";
    }
    writefile("/etc/sysctl.conf", implode("", $sysctl), 1);
    return true;
}
function mkosdir() 
{
    global $globals;
    include_once($globals["mainfiles"] . "/functions/file_functions.php");
    if( !is_dir($globals["isos"]) ) 
    {
        @mkdir_recursive($globals["isos"], 493);
    }
    if( !is_dir($globals["euisos"]) ) 
    {
        @mkdir_recursive($globals["euisos"], 493);
    }
    if( !is_dir($globals["openvzos"]) ) 
    {
        @mkdir_recursive($globals["openvzos"], 493);
    }
    if( !is_dir($globals["xenos"]) ) 
    {
        @mkdir_recursive($globals["xenos"], 493);
    }
    if( !is_dir($globals["kvmos"]) ) 
    {
        @mkdir_recursive($globals["kvmos"], 493);
    }
    if( !is_dir($globals["xcpos"]) ) 
    {
        @mkdir_recursive($globals["xcpos"], 493);
    }
    if( !is_dir($globals["lxcos"]) ) 
    {
        @mkdir_recursive($globals["lxcos"], 493);
    }
    if( !is_dir($globals["proxkos"]) ) 
    {
        @mkdir_recursive($globals["proxkos"], 493);
    }
    if( !is_dir($globals["proxoos"]) ) 
    {
        @mkdir_recursive($globals["proxoos"], 493);
    }
    if( !is_dir($globals["proxlos"]) ) 
    {
        @mkdir_recursive($globals["proxlos"], 493);
    }
    if( !is_dir($globals["vzoos"]) ) 
    {
        @mkdir_recursive($globals["vzoos"], 493);
    }
    if( !is_dir($globals["vzkos"]) ) 
    {
        @mkdir_recursive($globals["vzkos"], 493);
    }
    if( !is_dir($globals["webuzo_scripts"]) ) 
    {
        @mkdir_recursive($globals["webuzo_scripts"], 493);
    }
}
function random_unqnum($start, $end, $col_name, $table_name) 
{
    $r = rand($start, $end);
    $res = makequery("SELECT COUNT(" . $col_name . ") AS count FROM " . $table_name . " where " . $col_name . "='" . $r . "'");
    $row = vsql_fetch_assoc($res);
    if( !empty($row["count"]) ) 
    {
        random_unqnum($start, $end, $col_name, $table_name);
    }
    return $r;
}
function ftp_upload($backup) 
{
    $connection = ftp_connect($backup["ftp_backupserver"]);
    $login = ftp_login($connection, $backup["ftp_username"], $backup["ftp_passwd"]);
    if( !$connection || !$login ) 
    {
        return false;
    }
    $upload = ftp_put($connection, $backup["remote_filename"], $backup["filename"], FTP_BINARY);
    if( !$upload ) 
    {
        return false;
    }
    ftp_close($connection);
}
function check_disk_space($vpsid, $space) 
{
    global $globals;
    if( !empty($vpsid) && !empty($space) ) 
    {
        $server_free_space = "";
        $req_space = (int) $space * 2;
        $spaceret = vexec($globals["com"]["vgdisplay"] . " vg", $spaceout);
        if( !empty($spaceout) && empty($spaceret) ) 
        {
            foreach( $spaceout as $s => $p ) 
            {
                if( preg_match("/Free  PE/i", $p) ) 
                {
                    $sp = explode("/", $p);
                    $server_free_space = (int) $sp[2];
                }
            }
        }
        if( $req_space < $server_free_space ) 
        {
            return true;
        }
        return false;
    }
}
function vexec($command, &$o = "", &$r = NULL) 
{
    exec($command, $output, $retval);
    if( defined("DEBUG") ) 
    {
        $log = "[COMMAND]: " . $command . " , [OUTPUT]: " . print_r($output, true) . ", [RETVAL]: " . $retval . "\n";
        $handle = fopen(logdir() . "virtualizor.log", "a");
        fwrite($handle, $log);
        fclose($handle);
    }
    $GLOBALS["logr"][] = array( "command" => $command, "output" => $output, "return" => $retval );
    if( 2 <= func_num_args() ) 
    {
        $o = $output;
    }
    $r = $retval;
    return $retval;
}
function oexec($command, &$o = "", &$r = NULL) 
{
    $ret = vexec($command, $o, $r);
    $o = implode("\n", $o);
    return $ret;
}
function array_end(&$array) 
{
    return end($array);
}
function server_load() 
{
    oexec("uptime", $uptime);
    $tmp = explode("average:", $uptime);
    $load = explode(",", $tmp[1]);
    foreach( $load as $k => $v ) 
    {
        $load[$k] = (double) trim($v);
    }
    return $load;
}
function calc_load($uptime) 
{
    if( !preg_match("/average/is", $uptime) ) 
    {
        return array( );
    }
    $tmp = explode("average:", $uptime);
    $load = explode(",", $tmp[1]);
    foreach( $load as $k => $v ) 
    {
        $load[$k] = (double) trim($v);
    }
    return $load;
}
function lvsize($lv, $units = "G") 
{
    $lvsize = 0;
    $units = (empty($units) ? "G" : $units);
    vexec("lvdisplay -C --nosuffix --units " . strtolower($units) . " " . $lv, $o, $ret);
    if( $ret != 0 ) 
    {
        return 0;
    }
    if( !empty($o) ) 
    {
        $lvtmp = preg_split("/[\\s]+/is", trim($o[1]));
        $lvsize = (int) trim($lvtmp[3]);
    }
    return $lvsize;
}
function qemu_size($lv, $units = "G") 
{
    $lvsize = 0;
    $units = (empty($units) ? "G" : $units);
    vexec("qemu-img info " . $lv, $o, $ret);
    if( $ret != 0 ) 
    {
        return 0;
    }
    if( !empty($o) ) 
    {
        foreach( $o as $k => $v ) 
        {
            $matches = array( );
            if( preg_match("/virtual(\\s*)size(\\s*)\\:(\\s*)(\\d{1,5})G(\\s*)/is", $v, $matches) ) 
            {
                $lvsize = (int) $matches[4];
            }
            if( preg_match("/virtual(\\s*)size(\\s*)\\:(\\s*)(\\d{1,5}\\.\\d{1,5})G(\\s*)/is", $v, $matches) ) 
            {
                $lvsize = (int) $matches[4];
            }
            if( preg_match("/virtual(\\s*)size(\\s*)\\:(\\s*)(\\d{1,5})T(\\s*)/is", $v, $matches) ) 
            {
                $lvsize = (int) $matches[4];
                if( $units == "G" ) 
                {
                    $lvsize = $lvsize * 1024;
                }
            }
            if( preg_match("/virtual(\\s*)size(\\s*)\\:(\\s*)(\\d{1,5}\\.\\d{1,5})T(\\s*)/is", $v, $matches) ) 
            {
                $lvsize = (int) $matches[4];
                if( $units == "G" ) 
                {
                    $lvsize = $lvsize * 1024;
                }
            }
        }
    }
    return $lvsize;
}
function qemu_size_real($lv, $units = "B") 
{
    $disk_size = 0;
    $disk_size = (int) @vfilesize($lv);
    if( $units == "K" ) 
    {
        $disk_size = $disk_size / 1024;
    }
    if( $units == "M" ) 
    {
        $disk_size = $disk_size / 1024 / 1024;
    }
    if( $units == "G" ) 
    {
        $disk_size = $disk_size / 1024 / 1024 / 1024;
    }
    return $disk_size;
}
function listmgs() 
{
    $res = makequery("SELECT * FROM media_groups\n\t\t\t\t\tORDER BY `mgid` ASC");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $mgs[$row["mgid"]] = $row;
    }
    return $mgs;
}
function server_groups() 
{
    global $globals;
    $servergroups[0]["sgid"] = 0;
    $servergroups[0]["sg_name"] = (!empty($globals["default_sg_name"]) ? $globals["default_sg_name"] : "Default");
    $servergroups[0]["sg_reseller_name"] = (!empty($globals["default_sg_reseller_name"]) ? $globals["default_sg_reseller_name"] : "Default");
    $servergroups[0]["sg_desc"] = (!empty($globals["default_sg_desc"]) ? $globals["default_sg_desc"] : "Default Group");
    $servergroups[0]["sg_select"] = 0;
    $res = makequery("SELECT * FROM server_groups");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        if( 0 < vsql_num_rows($res) ) 
        {
            $row = vsql_fetch_assoc($res);
            $row["sg_reseller_name"] = (empty($row["sg_reseller_name"]) ? $row["sg_name"] : $row["sg_reseller_name"]);
            $servergroups[$row["sgid"]] = $row;
        }
    }
    return $servergroups;
}
function updatescripts($force = 0) 
{
    global $globals;
    global $scripts;
    $modified = @filemtime($globals["path"] . "/scripts.json");
    if( !empty($force) || 86400 < time() - $modified ) 
    {
        save_web_file("http://api.softaculous.com/_scripts.php?in=json", $globals["path"] . "/scripts.json");
    }
    return true;
}
function load_scripts() 
{
    global $globals;
    global $scripts;
    global $iscripts;
    if( $globals["disable_webuzo"] ) 
    {
        return false;
    }
    $scripts = json_decode(file_get_contents($globals["path"] . "/scripts.json"), 1);
    $iscripts = array( );
    $_scripts = $scripts;
    $scripts = array( );
    foreach( $_scripts as $k => $v ) 
    {
        $scripts[$k]["sid"] = $k;
        $scripts[$k]["parent"] = $v["parent"];
        $scripts[$k]["name"] = $v["name"];
        $scripts[$k]["softname"] = $v["softname"];
        $scripts[$k]["type"] = $v["type"];
        $scripts[$k]["category"] = $v["category"];
        if( $v["type"] != "php" || (empty($globals["noc_apikey"]) || empty($globals["noc_apipass"])) && empty($v["ins"]) ) 
        {
            continue;
        }
        $iscripts[$k] = $k;
    }
}
function update_webuzoapps($force = 0) 
{
    global $globals;
    $modified = @filemtime($globals["path"] . "/apps.json");
    if( !empty($force) || 86400 < time() - $modified ) 
    {
        save_web_file("http://api.webuzo.com/apps.php?in=json", $globals["path"] . "/apps.json");
    }
    $modified = @filemtime($globals["path"] . "/conf/default_web_apps.json");
    if( !empty($force) || 86400 < time() - $modified ) 
    {
        save_web_file("http://api.webuzo.com/apps.php?in=json&default=1", $globals["path"] . "/conf/default_web_apps.json");
    }
    return true;
}
function load_webuzoapps() 
{
    global $globals;
    global $apps;
    if( !empty($globals["disable_webuzo"]) ) 
    {
        return false;
    }
    if( !file_exists($globals["path"] . "/apps.json") ) 
    {
        update_webuzoapps();
    }
    $apps = json_decode(file_get_contents($globals["path"] . "/apps.json"), 1);
    $webuzo_apps = array( );
    $restricted_apps = array( 1, 2 );
    foreach( $apps as $k => $v ) 
    {
        if( !preg_match("/apache|php|mysql/is", $v["softname"]) ) 
        {
            continue;
        }
        if( empty($globals["noc_apikey"]) && empty($globals["noc_apipass"]) ) 
        {
            continue;
        }
        if( !empty($v["deprecated"]) ) 
        {
            continue;
        }
        if( in_array($k, $restricted_apps) ) 
        {
            continue;
        }
        $webuzo_apps[$v["group_type"]][$k]["fullname"] = $apps[$k]["fullname"];
        $webuzo_apps[$v["group_type"]][$k]["softname"] = $apps[$k]["softname"];
        $webuzo_apps[$v["group_type"]][$k]["version"] = $apps[$k]["version"];
    }
    return $webuzo_apps;
}
function load_free_webapps() 
{
    global $globals;
    $webuzo_apps = load_webuzoapps();
    $stack = json_decode(read_file($globals["path"] . "/conf/default_web_apps.json"), 1);
    foreach( $stack as $sk => $sv ) 
    {
        $free_apps[$sv][$sk] = $webuzo_apps[$sv][$sk];
    }
    return $free_apps;
}
function prepare_webuzo($options) 
{
    global $globals;
    global $scripts;
    global $iscripts;
    if( empty($options["webuzo"]) || empty($options["license"]) || empty($options["ip"]) ) 
    {
        return false;
    }
    return get_web_file("http://" . $options["ip"] . ":2004/install.php?prepareinstall=" . $options["webuzo"] . "&license=" . $options["license"]);
}
function prepare_webuzoapps($options) 
{
    global $globals;
    global $error;
    $apps = array( );
    if( empty($options) || empty($options["primary_ip"]) || empty($options["data"]) ) 
    {
        return false;
    }
    if( !empty($options["isfree"]) ) 
    {
        $stack = load_free_webapps();
        foreach( $stack as $sk => $sv ) 
        {
            $apps[] = $stack[$sk][$sv]["softname"];
        }
    }
    else 
    {
        if( empty($options["applist"]["webserver"]) || empty($options["applist"]["mysql"]) || empty($options["applist"]["php"]) ) 
        {
            $error[] = "No Application List found";
            return false;
        }
        $apps[] = implode(",", $options["applist"]);
        $apps[] = implode(",", array( "exim", "bind" ));
    }
    $params = implode(",", $apps);
    $ret = get_web_file("http://" . $options["primary_ip"] . ":2004/install.php?prepareapps=" . $params . "&license=" . $options["lic"]);
    if( !$ret ) 
    {
        return false;
    }
    if( !empty($options["script"]) ) 
    {
        $url = "http://" . $options["primary_ip"] . ":2004/install.php?prepareinstall=" . $options["script"];
        $ret = get_web_file($url . "&license=" . $options["lic"]);
        if( !$ret ) 
        {
            return false;
        }
    }
    $params = "";
    foreach( $options["data"] as $k => $v ) 
    {
        if( !empty($v) ) 
        {
            $params[] = $k . "=" . $v;
        }
    }
    $params = implode("&", $params);
    $ret = vexec("curl --data \"" . $params . "&submit=1&api=serialize\" http://" . $options["primary_ip"] . ":2004/install.php", $output, $ret);
    $output = unserialize($output[0]);
    if( $ret != 0 ) 
    {
        return false;
    }
    if( !empty($output["error"]) ) 
    {
        $error[] = $output["error"][0];
        return false;
    }
    return true;
}
function is_internalip($ip) 
{
    return (preg_match("/^10\\.(.*?)|^192\\.168\\.(.*?)/s", $ip) ? true : false);
}
function save_web_scripts($data) 
{
    global $globals;
    if( !writefile($globals["path"] . "/conf/web_scripts.json", json_encode($data), 1) ) 
    {
        return false;
    }
    return true;
}
function get_web_scripts() 
{
    global $globals;
    return (array) json_decode(read_file($globals["path"] . "/conf/web_scripts.json"));
}
function is_validNOC($noc_apikey, $noc_apipass) 
{
    global $globals;
    if( empty($noc_apikey) || empty($noc_apipass) ) 
    {
        return false;
    }
    if( !class_exists("SOFT_NOC") ) 
    {
        include_once($globals["path"] . "/sdk/" . "noc_api.inc");
    }
    $obj = new SOFT_NOC($noc_apikey, $noc_apipass, "", 1);
    $response = $obj->licenses("", "", "", 0, 1, "");
    if( empty($response) ) 
    {
        return false;
    }
    return true;
}
function get_webuzo_license($ip = 0, $email = 0, &$isfree, $buy = 0) 
{
    global $globals;
    global $error;
    $lic = "WEBUZO-42117-76793-20955-49158";
    if( empty($ip) || empty($email) ) 
    {
        return false;
    }
    $isvalid = is_validnoc($globals["noc_apikey"], $globals["noc_apipass"]);
    if( empty($isvalid) ) 
    {
        $isfree = 1;
        return $lic;
    }
    $isinternal = is_internalip($ip);
    if( !empty($isinternal) ) 
    {
        return $lic;
    }
    if( empty($buy) ) 
    {
        return NULL;
    }
    if( !class_exists("SOFT_NOC") ) 
    {
        include_once($globals["path"] . "/sdk/noc_api.inc");
    }
    $noc = new SOFT_NOC($globals["noc_apikey"], $globals["noc_apipass"], "", 1);
    $licenses = (array) $noc->webuzo_licenses("", $ip);
    $ret = current($licenses["licenses"]);
    $lic = $ret["license"];
    if( empty($lic) ) 
    {
        $ret = $noc->webuzo_buy($ip, "1M", 2, $email, 1);
        if( empty($ret) || !empty($noc->error) ) 
        {
            $error[] = $noc->error;
            return NULL;
        }
        $lic = $ret["license"];
    }
    return $lic;
}
function webuzo_os($virt, $hvm = "") 
{
    global $globals;
    global $ostemplates;
    if( empty($virt) ) 
    {
        return false;
    }
    if( empty($ostemplates) ) 
    {
        oslist();
    }
    $webuzo_os = array( );
    foreach( $ostemplates as $k => $v ) 
    {
        if( $v["distro"] != "webuzo" ) 
        {
            continue;
        }
        if( !preg_match("/" . $virt . "/is", $v["Nvirt"]) ) 
        {
            continue;
        }
        $webuzo_os[$k] = $v;
    }
    return $webuzo_os;
}
function ping_webuzo_vps($ip) 
{
    $active = false;
    oexec("curl \"http://" . $ip . ":2004/install.php\"", $output, $ret);
    if( $ret != 0 ) 
    {
        return $active;
    }
    if( preg_match("/\\<\\!DOCTYPE/", $output) ) 
    {
        $active = true;
    }
    return $active;
}
function get_script_req($sid) 
{
    global $globals;
    global $tmp_req;
    if( empty($sid) ) 
    {
        return false;
    }
    if( !is_dir($globals["webuzo_scripts"]) ) 
    {
        mkdir_recursive($globals["webuzo_scripts"], 493);
    }
    if( !is_dir($globals["webuzo_scripts"] . "/" . $sid) ) 
    {
        mkdir_recursive($globals["webuzo_scripts"] . "/" . $sid, 493);
    }
    if( !file_exists($globals["webuzo_scripts"] . "/" . $sid . "/info.xml") ) 
    {
        $zip_path = $globals["webuzo_scripts"] . "/" . $sid . "/" . $sid . ".zip";
        $res = save_web_file("http://api.softaculous.com/givesoft.php?softid=" . $sid . "&sp=1&license=WEBUZO-42067-82998-91612-49497&panel=webuzo", $zip_path);
        if( !$res ) 
        {
            return false;
        }
        rmdir_recursive($globals["webuzo_scripts"] . "/" . $sid . "/tmp/");
        if( !unzip($zip_path, $globals["webuzo_scripts"] . "/" . $sid . "/tmp/", 1, array( ), array( ), 1) ) 
        {
            return false;
        }
        if( !copy($globals["webuzo_scripts"] . "/" . $sid . "/tmp/info.xml", $globals["webuzo_scripts"] . "/" . $sid . "/info.xml") ) 
        {
            return false;
        }
        if( is_safe_file($zip_path) ) 
        {
            @unlink($zip_path);
        }
        rmdir_recursive($globals["webuzo_scripts"] . "/" . $sid . "/tmp/");
    }
    $tmp_req = array( );
    $tmp_info = @implode("", @file($globals["webuzo_scripts"] . "/" . $sid . "/info.xml"));
    $tmp_info = preg_replace_callback("/<requirement(.*?)>(.*?)<\\/requirement>/is", "replace_callback", $tmp_info);
    $tmp_info = preg_replace_callback("/<requirement(.*?)\\/>/is", "replace_callback", $tmp_info);
    $requirements = $tmp_req;
    $req = array( );
    foreach( $requirements as $k => $v ) 
    {
        soft_preg_replace("/check=(\"|')(.*?)(\"|')(\\s*?)/is", $v, $req[$k]["check"], 2);
        soft_preg_replace("/type=(\"|')(.*?)(\"|')(\\s*?)/is", $v, $req[$k]["type"], 2);
        soft_preg_replace("/operator=(\"|')(.*?)(\"|')(\\s*?)/is", $v, $req[$k]["operator"], 2);
        soft_preg_replace("/<\\!\\[CDATA\\[(\\s*?)(.*?)(\\s*?)\\]\\]>/is", $v, $req[$k]["grep"], 2);
        soft_preg_replace("/name=(\"|')(.*?)(\"|')(\\s*?)/is", $v, $req[$k]["name"], 2);
        soft_preg_replace("/value=(\"|')(.*?)(\"|')(\\s*?)/is", $v, $req[$k]["value"], 2);
        soft_preg_replace("/version=(\"|')(.*?)(\"|')(\\s*?)/is", $v, $req[$k]["version"], 2);
        soft_preg_replace("/err=(\"|')(.*?)(\"|')(\\s*?)/is", $v, $req[$k]["err"], 2);
        soft_preg_replace("/function=(\"|')(.*?)(\"|')(\\s*?)/is", $v, $req[$k]["function"], 2);
        if( !empty($req[$k]["value"]) && empty($req[$k]["version"]) ) 
        {
            $req[$k]["version"] = $req[$k]["value"];
        }
    }
    return $req;
}
function soft_preg_replace($pattern, $file, &$var, $valuenum, $stripslashes = "") 
{
    preg_match($pattern, $file, $matches);
    if( empty($stripslashes) ) 
    {
        $var = @trim($matches[$valuenum]);
    }
    else 
    {
        $var = @stripslashes(@trim($matches[$valuenum]));
    }
}
function replace_callback($matches) 
{
    global $tmp_req;
    $tmp_req[] = $matches[0];
    return true;
}
function list_all_storages() 
{
    global $globals;
    global $servers;
    global $storages;
    $res = makequery("SELECT * FROM `storage`");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $storages[$row["stid"]] = $row;
    }
    if( count($storages) < 1 ) 
    {
        return false;
    }
    $res = makequery("SELECT * FROM `storage_servers`");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        if( -1 < $row["sgid"] ) 
        {
            $storages[$row["stid"]]["server_groups"][$row["sgid"]] = $row["sgid"];
        }
        if( -2 < $row["serid"] ) 
        {
            $storages[$row["stid"]]["servers"][$row["serid"]] = $row["serid"];
        }
    }
}
function list_storages() 
{
    global $globals;
    global $servers;
    global $storages;
    global $cluster;
    $storages = array( );
    $res = makequery("SELECT * FROM `storage_servers`\n\t\t\t\t\tWHERE sgid = '" . $servers[$globals["server"]]["sgid"] . "'\n\t\t\t\t\tOR serid IN ('-1', '" . $globals["server"] . "')");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $storages[$row["stid"]] = $row;
    }
    if( count($storages) < 1 ) 
    {
        $storages[0]["stid"] = 0;
        $storages[0]["name"] = "Default Storage" . ((!empty($globals["slave"]) ? " " . $globals["slave"] : ""));
        $storages[0]["path"] = (!empty($globals["disk_path"]) ? $globals["disk_path"] : (!empty($globals["thin_lv"]) ? "/dev/" . $globals["lv"] . "/" . $globals["thin_lv"] : "/dev/" . $globals["lv"]));
        $storages[0]["type"] = (!empty($globals["disk_path"]) ? "file" : (!empty($globals["thin_lv"]) ? "thin block" : "block"));
        $storages[0]["format"] = "";
        $storages[0]["primary_storage"] = 1;
        if( $cluster->virt(0, 0, 0, 0, 0, 0, 0, 1) ) 
        {
            $storages[0]["name"] = "local";
            $storages[0]["path"] = "/var/lib/vz";
            $storages[0]["type"] = "file";
            $storages[0]["format"] = "raw";
        }
        else 
        {
            if( $cluster->virt(1) ) 
            {
                $storages[0]["path"] = "/vz";
                $storages[0]["type"] = "openvz";
            }
            else 
            {
                if( empty($globals["disk_path"]) && empty($globals["lv"]) && empty($globals["thin_lv"]) ) 
                {
                    unset($storages[0]);
                }
            }
        }
        return true;
    }
    $res = makequery("SELECT * FROM `storage`\n\t\t\t\t\tWHERE stid IN (" . implode(", ", array_keys($storages)) . ")\n\t\t\t\t\tORDER BY primary_storage DESC");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $storages[$row["stid"]] = $row;
    }
    foreach( $storages as $k => $v ) 
    {
        if( preg_match("/block/is", $v["type"]) && empty($v["format"]) ) 
        {
            $storages[$k]["format"] = "raw";
        }
        if( preg_match("/file/is", $v["type"]) && empty($v["format"]) ) 
        {
            $storages[$k]["format"] = "qcow2";
        }
    }
}
function list_servers() 
{
    global $globals;
    global $servers;
    global $servers_keypass;
    global $A;
    global $storages;
    $serids = array( );
    $serids[0] = array( );
    $res = makequery("SELECT * FROM `servers` \n\t\t\t\t\t" . ((empty($globals["slave"]) ? "" : "WHERE serid = 0")) . "\n\t\t\t\t\tORDER BY serid ASC");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $serids[$row["serid"]] = $row;
        if( empty($row["serid"]) ) 
        {
            $localhost = 1;
        }
    }
    $serids[0]["serid"] = 0;
    $serids[0]["server_name"] = (empty($globals["master_name"]) ? "localhost" : $globals["master_name"]);
    $serids[0]["virt"] = $globals["kernel"];
    $serids[0]["ip"] = "127.0.0.1";
    $serids[0]["key"] = $globals["key"];
    $serids[0]["pass"] = $globals["pass"];
    $serids[0]["lv"] = $globals["lv"];
    $serids[0]["overcommit"] = $globals["overcommit"];
    if( empty($localhost) ) 
    {
        if( preg_match("/xen/is", $globals["kernel"]) ) 
        {
            vexec("/usr/sbin/xm info | grep hvm", $ishvm);
        }
        else 
        {
            if( preg_match("/xcp/is", $globals["kernel"]) ) 
            {
                vexec("/usr/sbin/xl info | grep hvm", $ishvm);
            }
        }
        if( !empty($ishvm) && 0 < count($ishvm) ) 
        {
            $serids[0]["hvm"] = 1;
        }
        $res = makequery("SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\"");
        $res = makequery("INSERT INTO servers\n\t\t\t\t\tSET serid = 0,\n\t\t\t\t\tserver_name = :server_name,\n\t\t\t\t\tvirt = :virt,\n\t\t\t\t\tip = :ip,\n\t\t\t\t\tlv = :lv,\n\t\t\t\t\thvm = :hvm\n\t\t\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\t\t\tserid = 0,\n\t\t\t\t\t\tserver_name = :server_name,\n\t\t\t\t\t\tvirt = :virt,\n\t\t\t\t\t\tip = :ip,\n\t\t\t\t\t\tlv = :lv,\n\t\t\t\t\t\thvm = :hvm", array( ":server_name" => $serids[0]["server_name"], ":virt" => $serids[0]["virt"], ":ip" => $serids[0]["ip"], ":lv" => $serids[0]["lv"], ":hvm" => (empty($serids[0]["hvm"]) ? 0 : 1) ));
    }
    $res = makequery("SELECT serid, COUNT(vpsid) AS numvps, SUM(ram) AS alloc_ram, SUM(space) AS alloc_space, \n\t\t\t\t\tSUM(cpu) AS alloc_cpu, SUM(cpu_percent) AS alloc_cpu_percent, SUM(bandwidth) AS alloc_bandwidth\n\t\t\t\t\tFROM `vps`\n\t\t\t\t\tGROUP BY serid");
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $serids[$row["serid"]]["numvps"] = $row["numvps"];
        $serids[$row["serid"]]["alloc_ram"] = $row["alloc_ram"];
        $serids[$row["serid"]]["alloc_space"] = $row["alloc_space"];
        $serids[$row["serid"]]["alloc_cpu"] = $row["alloc_cpu"];
        $serids[$row["serid"]]["alloc_cpu_percent"] = $row["alloc_cpu_percent"];
        $serids[$row["serid"]]["alloc_bandwidth"] = $row["alloc_bandwidth"];
    }
    foreach( $serids as $k => $v ) 
    {
        $servers_keypass[$k]["key"] = $v["key"];
        $servers_keypass[$k]["pass"] = $v["pass"];
        $serids[$k]["virts"] = explode(" ", $v["virt"]);
        unset($serids[$k]["key"]);
        unset($serids[$k]["pass"]);
    }
    $servers = $serids;
    if( empty($storages) ) 
    {
        list_storages();
    }
}
function set_active_server($serid) 
{
    global $globals;
    global $servers;
    global $servers_keypass;
    global $A;
    global $storages;
    $globals["server"] = $serid;
    list_storages();
}
function server_virt($serid, $virt) 
{
    global $globals;
    global $servers;
    $server_virt = $globals["kernel"];
    if( 0 < $serid ) 
    {
        $server_virt = $servers[$serid]["virt"];
    }
    if( preg_match("/" . $virt . "/is", $server_virt) ) 
    {
        return $virt;
    }
    return false;
}
function server_os_arch($serid) 
{
    global $globals;
    global $servers;
    $server_arch = $servers[$serid]["os_arch"];
    return (preg_match("/amd64|x86\\_64/is", $server_arch) ? 64 : 32);
}
function server_hostname($serid) 
{
    global $globals;
    global $servers;
    $hostname = $servers[$serid]["server_name"];
    if( $serid == 0 ) 
    {
        $tmp = $_SERVER["HTTP_HOST"];
        if( 0 < substr_count($tmp, ":") ) 
        {
            $tmp = explode(":", $tmp);
            $hostname = $tmp[0];
        }
        else 
        {
            $hostname = $tmp;
        }
    }
    return $hostname;
}
function server_publicip($serid) 
{
    global $globals;
    global $servers;
    $ip = $servers[$serid]["ip"];
    if( $serid == 0 ) 
    {
        $ip = $globals["primary_ip"];
    }
    return $ip;
}
function server_vncip($serid) 
{
    global $globals;
    global $servers;
    $ip = $servers[$serid]["vnc_ip"];
    if( empty($ip) ) 
    {
        $ip = server_publicip($serid);
    }
    return $ip;
}
function server_primary_virt($serid) 
{
    global $globals;
    global $servers;
    $server_virt = $globals["kernel"];
    if( 0 < $serid ) 
    {
        $server_virt = $servers[$serid]["virt"];
    }
    $virts = explode(" ", $server_virt);
    if( preg_match("/proxk/is", $server_virt) ) 
    {
        return "proxk";
    }
    if( preg_match("/vzk/is", $server_virt) ) 
    {
        return "vzk";
    }
    if( preg_match("/kvm/is", $server_virt) ) 
    {
        return "kvm";
    }
    return $virts[0];
}
function server_update_location($serid) 
{
    global $globals;
    global $servers;
    $server = $servers[$serid];
    $ser_addr = $server["ip"];
    if( empty($server["serid"]) ) 
    {
        $ser_addr = $globals["primary_ip"];
    }
    $location_data = get_map_data($ser_addr);
    if( !json_decode($location_data) ) 
    {
        return false;
    }
    if( !empty($location_data) ) 
    {
        $res = makequery("UPDATE servers \n\t\t\t\t\t\tSET location = '" . $location_data . "'\n\t\t\t\t\t\tWHERE serid = '" . $serid . "'");
    }
    return $location_data;
}
function numvs($serid) 
{
    global $servers;
    if( empty($servers[$serid]["licnumvs"]) ) 
    {
        return true;
    }
    $qres = makequery("SELECT *\tFROM `vps`\n\t\t\t\t\t\tWHERE serid = " . $serid);
    if( $servers[$serid]["licnumvs"] <= vsql_num_rows($qres) ) 
    {
        return false;
    }
    return true;
}
function load_cluster() 
{
    global $globals;
    global $servers;
    global $cluster;
    if( !class_exists("cluster") ) 
    {
        include_once($globals["adminfiles"] . "/cluster.php");
    }
    $cluster = new cluster();
}
function get_next_serial($curr_serial, $today = "") 
{
    if( $today == "" ) 
    {
        $today = date("Ymd");
    }
    $revision = (int) substr($curr_serial, -2);
    $ser_date = substr($curr_serial, 0, 8);
    if( $curr_serial == "0" ) 
    {
        $serial = $curr_serial;
    }
    else 
    {
        if( $curr_serial == $today . "99" ) 
        {
            $serial = get_next_date($today) . "00";
        }
        else 
        {
            if( strcmp($today, $ser_date) === 0 ) 
            {
                $revision = $revision + 1;
            }
            else 
            {
                if( strncmp($today, $curr_serial, 8) === -1 ) 
                {
                    $today = substr($curr_serial, 0, 8);
                    if( $revision == 99 ) 
                    {
                        $today = get_next_date($today);
                        $revision = "00";
                    }
                    else 
                    {
                        $revision = $revision + 1;
                    }
                }
                else 
                {
                    $revision = "00";
                }
            }
            $serial = $today . str_pad($revision, 2, "0", STR_PAD_LEFT);
        }
    }
    return $serial;
}
function set_soa_serial($soa_rec, $serial) 
{
    $soa = explode(" ", $soa_rec);
    if( 5 < count($soa) ) 
    {
        $soa[2] = $serial;
    }
    else 
    {
        $soa[0] = $serial;
    }
    $soa_rec = join(" ", $soa);
    chop($soa_rec);
    return $soa_rec;
}
function update_soa_serial($domain_id, $con) 
{
    $res = mysql_query("SELECT content FROM records WHERE type = 'SOA' AND domain_id = " . $domain_id, $con);
    if( mysql_num_rows($res) < 1 ) 
    {
        return false;
    }
    $soa_rec = mysql_fetch_assoc($res);
    $temp_curr_serial = explode(" ", $soa_rec["content"]);
    if( 5 < count($temp_curr_serial) ) 
    {
        $curr_serial = $temp_curr_serial[2];
    }
    else 
    {
        $curr_serial = $temp_curr_serial[0];
    }
    $new_serial = get_next_serial($curr_serial);
    if( $curr_serial != $new_serial ) 
    {
        $soa_record = set_soa_serial($soa_rec["content"], $new_serial);
        return mysql_query("UPDATE records SET content='" . $soa_record . "' WHERE domain_id = " . $domain_id . " AND type = 'SOA'", $con);
    }
    return true;
}
function get_next_date($curr_date) 
{
    $next_date = date("Ymd", strtotime("+1 day", strtotime($curr_date)));
    return $next_date;
}
function is_valid_domain_name($domain_name) 
{
    $pieces = explode(".", $domain_name);
    foreach( $pieces as $piece ) 
    {
        if( !preg_match("/^[a-z\\d-_][a-z\\d-_]{0,62}\$/i", $piece) || preg_match("/-\$/", $piece) ) 
        {
            return false;
        }
    }
    return true;
}
function connect_to_remote_mysql($hostname, $username, $password, $dbname, $ssl = 0) 
{
    if( !empty($ssl) ) 
    {
        $con = mysql_connect($hostname, $username, $password, MYSQL_CLIENT_SSL);
    }
    else 
    {
        $con = mysql_connect($hostname, $username, $password);
    }
    if( !mysql_select_db($dbname, $con) ) 
    {
        return false;
    }
    return $con;
}
function get_dns_server($pdnsid) 
{
    if( empty($pdnsid) ) 
    {
        return false;
    }
    $res = makequery("SELECT * FROM pdns WHERE id = " . $pdnsid);
    $pdns = vsql_fetch_assoc($res);
    if( !empty($pdns["encrypt_sql_pass"]) ) 
    {
        $pdns["sql_password"] = pass_decrypt($pdns["sql_password"], $pdns["salt"]);
    }
    return $pdns;
}
function rdns_ip($ip, &$zone) 
{
    if( !valid_ip($ip) && !valid_ipv6($ip) ) 
    {
        return false;
    }
    if( valid_ipv6($ip) ) 
    {
        $ip = ipv6_expand($ip);
        $rzone = $r_zone = explode(":", $ip);
        $r_zone = implode("", $r_zone);
        $r_zone = strrev($r_zone);
        $r_zone = str_split($r_zone);
        $domainIP = implode(".", $r_zone);
        unset($rzone[6]);
        unset($rzone[7]);
        $rzone = implode("", $rzone);
        $rzone = strrev($rzone);
        $rzone = str_split($rzone);
        $rzone_ip = implode(".", $rzone);
        $zone_extension = ".ip6.arpa";
        $rnds_entry = $domainIP . $zone_extension;
    }
    if( valid_ip($ip) ) 
    {
        $rzone = explode(".", $ip);
        $rdomain = $rzone = array_reverse($rzone);
        $popped = array_shift($rzone);
        $rzone_ip = implode(".", $rzone);
        $zone_extension = ".in-addr.arpa";
        $rnds_entry = implode(".", $rdomain) . $zone_extension;
    }
    $zone = $rzone_ip . $zone_extension;
    return $rnds_entry;
}
function rdns_name($name) 
{
    $name = explode(".", $name);
    $len = count($name);
    if( $name[$len - 2] == "in-addr" ) 
    {
        unset($name[$len - 2]);
        unset($name[$len - 1]);
        $rnds_ip = implode(".", array_reverse($name));
    }
    else 
    {
        if( $name[$len - 2] == "ip6" ) 
        {
            unset($name[$len - 2]);
            unset($name[$len - 1]);
            $name = implode("", $name);
            $name = strrev($name);
            $ipes = str_split($name, 4);
            $rnds_ip = implode(":", $ipes);
            if( strlen($rnds_ip) != 39 ) 
            {
                return false;
            }
        }
    }
    return $rnds_ip;
}
function connect_ftp($hostname, $username, $password, $port) 
{
    $ftp_con = ftp_connect($hostname, $port, 24 * 60 * 60);
    $login_res = ftp_login($ftp_con, $username, $password);
    if( !$ftp_con || !$login_res ) 
    {
        return false;
    }
    ftp_pasv($ftp_con, true);
    return $ftp_con;
}
function get_ssh_backup_list($connection, $dir, $selected_date = 0) 
{
    $sftp = ssh2_sftp($connection);
    $directory = scandir("ssh2.sftp://" . intval($sftp) . $dir . "/", 1);
    foreach( $directory as $k => $folder ) 
    {
        if( $folder != ".." && $folder != "." && strlen($folder) == 8 && strtotime($folder) <= time() && 0 < strtotime($folder) ) 
        {
            $temp_date = (int) substr($folder, 6, 2);
            $temp_mon = (int) substr($folder, 4, 2);
            $temp_yr = (int) substr($folder, 0, 4);
            if( 0 < $temp_date && $temp_date < 32 && 0 < $temp_mon && $temp_mon < 13 && 2010 <= $temp_yr ) 
            {
                $back_folder_list[$folder] = array( );
            }
        }
    }
    if( empty($selected_date) || !isset($back_folder_list[$selected_date]) ) 
    {
        $dates = array_keys($back_folder_list);
        $selected_date = max($dates);
        if( empty($selected_date) ) 
        {
            return array( );
        }
    }
    $folder_to_fetch = $dir . "/" . $selected_date;
    $temp_backups = scandir("ssh2.sftp://" . intval($sftp) . $folder_to_fetch . "", 1);
    $backups = array( );
    foreach( $temp_backups as $k => $file ) 
    {
        $back_file_list[$file] = array( );
        $temp_file = explode("/", $file);
        $name = $temp_file[count($temp_file) - 1];
        if( preg_match("/(.*?)\\.((img\\.gz)|(tar\\.gz)|(vma\\.gz)|(img)|(vma)|(tar))\$/is", $name) ) 
        {
            $statinfo = ssh2_sftp_stat($sftp, $folder_to_fetch . "/" . $name);
            $size = $statinfo["size"];
            $backups[] = array( "abs_path" => $folder_to_fetch . "/" . $file, "size" => $size );
        }
    }
    $back_folder_list[$selected_date] = $backups;
    return $back_folder_list;
}
function get_backups_list($ftp_con, $dir, $selected_date = 0) 
{
    if( !empty($ftp_con) ) 
    {
        $folderlist = _ftp_nlist($ftp_con, $dir);
        $folder_to_fetch = "";
        foreach( $folderlist as $k => $folder ) 
        {
            $temp = explode("/", $folder);
            $folder_name = $temp[count($temp) - 1];
            if( strlen($folder_name) == 8 && strtotime($folder_name) <= time() && 0 < strtotime($folder_name) ) 
            {
                $temp_date = (int) substr($folder_name, 6, 2);
                $temp_mon = (int) substr($folder_name, 4, 2);
                $temp_yr = (int) substr($folder_name, 0, 4);
                if( 0 < $temp_date && $temp_date < 32 && 0 < $temp_mon && $temp_mon < 13 && 2010 <= $temp_yr ) 
                {
                    $backup_folders_list[$folder_name] = array( );
                }
            }
        }
        if( empty($selected_date) || !isset($backup_folders_list[$selected_date]) ) 
        {
            $dates = array_keys($backup_folders_list);
            $selected_date = max($dates);
            if( empty($selected_date) ) 
            {
                return array( );
            }
        }
        $folder_to_fetch = $dir . "/" . $selected_date;
        $backups = array( );
        $temp_backups = _ftp_nlist($ftp_con, $folder_to_fetch);
        foreach( $temp_backups as $k => $file ) 
        {
            $temp_file = explode("/", $file);
            $name = $temp_file[count($temp_file) - 1];
            if( !preg_match("/(\\w+.inf)/", $name, $matches) ) 
            {
                ftp_size($ftp_con, $file);
                $resp = ftp_raw($ftp_con, "size " . $file);
                $size = implode("", $resp);
                $size = explode(" ", $size);
                $size = $size[count($size) - 1];
                $backups[] = array( "abs_path" => $file, "size" => $size );
            }
        }
        $backup_folders_list[$selected_date] = $backups;
    }
    else 
    {
        $folderlist = filelist($dir, 0);
        $folder_to_fetch = "";
        foreach( $folderlist as $folder => $folderinfo ) 
        {
            if( strlen($folderinfo["name"]) == 8 && strtotime($folderinfo["name"]) <= time() && 0 < strtotime($folderinfo["name"]) ) 
            {
                $temp_date = (int) substr($folderinfo["name"], 6, 2);
                $temp_mon = (int) substr($folderinfo["name"], 4, 2);
                $temp_yr = (int) substr($folderinfo["name"], 0, 4);
                if( 0 < $temp_date && $temp_date < 32 && 0 < $temp_mon && $temp_mon < 13 && 2010 <= $temp_yr ) 
                {
                    $backup_folders_list[$folderinfo["name"]] = array( );
                }
            }
        }
        if( empty($selected_date) || !isset($backup_folders_list[$selected_date]) ) 
        {
            $dates = array_keys($backup_folders_list);
            $selected_date = max($dates);
            if( empty($selected_date) ) 
            {
                return array( );
            }
        }
        $folder_to_fetch = $dir . "/" . $selected_date;
        $backups = array( );
        $t_backups = filelist($folder_to_fetch, 0);
        foreach( $t_backups as $backup => $backupinfo ) 
        {
            $file_parts = pathinfo($backup);
            if( $file_parts["extension"] != "inf" && $file_parts["extension"] != "log" ) 
            {
                $size = vfilesize($backup);
                $backups[] = array( "abs_path" => $backup, "size" => $size );
            }
        }
        $backup_folders_list[$selected_date] = $backups;
    }
    return $backup_folders_list;
}
function create_backup_folders($ftp_con, $start_dir, $rotation) 
{
    global $error;
    global $l;
    $date = @datify(@time(), 0, 1, "Ymd");
    $result = @ftp_chdir($ftp_con, $start_dir);
    if( !$result && !ftp_mkdir($ftp_con, $start_dir) ) 
    {
        $error[] = $l["err_create_backup_folder"];
        return false;
    }
    $folderlist = _ftp_nlist($ftp_con, $start_dir);
    $folders = array( );
    foreach( $folderlist as $k => $folderinfo ) 
    {
        if( $folderinfo == $start_dir . "/" . $date ) 
        {
            continue;
        }
        $bfolder = substr($folderinfo, -8, 8);
        if( strtotime($bfolder) <= time() && 0 < strtotime($bfolder) ) 
        {
            $temp_date = (int) substr($bfolder, 6, 2);
            $temp_mon = (int) substr($bfolder, 4, 2);
            $temp_yr = (int) substr($bfolder, 0, 4);
            if( 0 < $temp_date && $temp_date < 32 && 0 < $temp_mon && $temp_mon < 13 && 2010 <= $temp_yr ) 
            {
                $folders[] = $bfolder;
            }
        }
    }
    log_output("FTP Folders : ");
    log_output($folders);
    $num_backups = count($folders);
    $folders_to_delete = array( );
    if( $num_backups == $rotation ) 
    {
        $folders_to_delete = array( min($folders) );
    }
    else 
    {
        if( $rotation < $num_backups ) 
        {
            $folder_delete_count = $num_backups - $rotation;
            $folder_delete_count++;
            $folders_to_delete = array( );
            for( $i = 0; $i < $folder_delete_count; $i++ ) 
            {
                $folders_to_delete[] = min($folders);
                $folders = array_diff($folders, $folders_to_delete);
            }
        }
    }
    log_output("Folders to Delete : ");
    log_output($folders_to_delete);
    if( !empty($folders_to_delete) ) 
    {
        foreach( $folders_to_delete as $k => $v ) 
        {
            $files = _ftp_nlist($ftp_con, $v);
            foreach( $files as $file ) 
            {
                ftp_delete($ftp_con, $file);
            }
            if( !ftp_rmdir($ftp_con, $v) ) 
            {
                return false;
            }
        }
    }
    $result = @ftp_chdir($ftp_con, $start_dir . "/" . $date);
    if( !$result && !ftp_mkdir($ftp_con, $start_dir . "/" . $date) ) 
    {
        $error[] = $l["err_create_backup_date_folder_folder"];
        return false;
    }
    return $start_dir . "/" . $date;
}
function create_backup_folders2($ftp_con, $start_dir, $vpsid, $rotation = 0, $date = "") 
{
    global $error;
    global $l;
    if( empty($date) ) 
    {
        $date = @datify(@time(), 0, 1, "Ymd");
    }
    $result = _ftp_nlist($ftp_con, $start_dir);
    if( $result === false && !ftp_mkdir($ftp_con, $start_dir) ) 
    {
        $error[] = $l["err_create_backup_folder"];
        return false;
    }
    if( $rotation != 0 ) 
    {
        echo lang_vars_name($l["log_deleting_backups"], array( "rotation" => $rotation )) . "\n";
        $folders = _ftp_nlist($ftp_con, $start_dir);
        rsort($folders);
        $vps = getvps($vpsid);
        $extensions = get_backup_extensions($vps["virt"]);
        foreach( $folders as $folder ) 
        {
            $folder = basename($folder);
            if( $folder == $date ) 
            {
                continue;
            }
            if( !is_valid_backup_folder($folder) ) 
            {
                continue;
            }
            $files = _ftp_nlist($ftp_con, $start_dir . "/" . $folder);
            if( empty($files) ) 
            {
                if( ftp_rmdir($ftp_con, $start_dir . "/" . $folder) ) 
                {
                    echo lang_vars_name($l["log_deleted_folder"], array( "folder" => $start_dir . "/" . $folder )) . "\n";
                }
                continue;
            }
            foreach( $files as $file ) 
            {
                $filename = basename($file);
                $parts = explode(".", $filename, 2);
                if( preg_match("/^" . $vpsid . "(_\\d+)?\$/is", $parts[0]) && in_array($parts[1], $extensions) ) 
                {
                    if( 1 < $rotation ) 
                    {
                        $rotation--;
                        continue 2;
                    }
                    if( ftp_delete($ftp_con, $file) ) 
                    {
                        echo lang_vars_name($l["log_deleted_file"], array( "file" => $file )) . "\n";
                    }
                }
            }
            if( ftp_delete($ftp_con, $start_dir . "/" . $folder . "/" . $vpsid . ".inf") ) 
            {
                echo lang_vars_name($l["log_deleted_file"], array( "file" => $start_dir . "/" . $folder . "/" . $vpsid . ".inf" )) . "\n";
            }
            $files = _ftp_nlist($ftp_con, $start_dir . "/" . $folder);
            if( empty($files) && ftp_rmdir($ftp_con, $start_dir . "/" . $folder) ) 
            {
                echo lang_vars_name($l["log_deleted_folder"], array( "folder" => $start_dir . "/" . $folder )) . "\n";
            }
        }
        echo $l["log_finished_deleting_backups"] . "\n";
    }
    $result = _ftp_nlist($ftp_con, $start_dir . "/" . $date);
    if( $result === false && !ftp_mkdir($ftp_con, $start_dir . "/" . $date) ) 
    {
        $error[] = $l["err_create_backup_date_folder"];
        return false;
    }
    return $start_dir . "/" . $date;
}
function create_ssh_backup_folders2($connection, $start_dir, $vpsid, $rotation = 0, $date = "") 
{
    global $error;
    global $l;
    if( substr($start_dir, 0, 1) != "/" ) 
    {
        $error[] = $l["err_backup_dir_not_absolute"];
        return false;
    }
    $sftp = ssh2_sftp($connection);
    if( empty($date) ) 
    {
        $date = @datify(@time(), 0, 1, "Ymd");
    }
    $result = file_exists("ssh2.sftp://" . intval($sftp) . "/" . $start_dir);
    if( !$result && !ssh2_sftp_mkdir($sftp, $start_dir) ) 
    {
        $error[] = $l["err_create_backup_folder"];
        return false;
    }
    if( $rotation != 0 ) 
    {
        echo lang_vars_name($l["log_deleting_backups"], array( "rotation" => $rotation )) . "\n";
        $folders = scandir("ssh2.sftp://" . intval($sftp) . $start_dir);
        rsort($folders);
        $vps = getvps($vpsid);
        $extensions = get_backup_extensions($vps["virt"]);
        foreach( $folders as $folder ) 
        {
            if( $folder == $date ) 
            {
                continue;
            }
            if( !is_valid_backup_folder($folder) ) 
            {
                continue;
            }
            $files = scandir("ssh2.sftp://" . intval($sftp) . $start_dir . "/" . $folder);
            if( count($files) <= 2 ) 
            {
                if( ssh2_sftp_rmdir($sftp, $start_dir . "/" . $folder) ) 
                {
                    echo lang_vars_name($l["log_deleted_folder"], array( "folder" => $start_dir . "/" . $folder )) . "\n";
                }
                continue;
            }
            foreach( $files as $file ) 
            {
                $parts = explode(".", $file, 2);
                if( preg_match("/^" . $vpsid . "(_\\d+)?\$/is", $parts[0]) && in_array($parts[1], $extensions) ) 
                {
                    if( 1 < $rotation ) 
                    {
                        $rotation--;
                        continue 2;
                    }
                    if( ssh2_sftp_unlink($sftp, $start_dir . "/" . $folder . "/" . $file) ) 
                    {
                        echo lang_vars_name($l["log_deleted_file"], array( "file" => $file )) . "\n";
                    }
                }
            }
            if( ssh2_sftp_unlink($sftp, $start_dir . "/" . $folder . "/" . $vpsid . ".inf") ) 
            {
                echo lang_vars_name($l["log_deleted_file"], array( "file" => $file . ".inf" )) . "\n";
            }
            $files = scandir("ssh2.sftp://" . intval($sftp) . $start_dir . "/" . $folder);
            if( count($files) <= 2 && ssh2_sftp_rmdir($sftp, $start_dir . "/" . $folder) ) 
            {
                echo lang_vars_name($l["log_deleted_folder"], array( "folder" => $start_dir . "/" . $folder )) . "\n";
            }
        }
        echo $l["log_finished_deleting_backups"] . "\n";
    }
    $result = file_exists("ssh2.sftp://" . intval($sftp) . (string) $start_dir . "/" . $date);
    if( !$result && !ssh2_sftp_mkdir($sftp, $start_dir . "/" . $date) ) 
    {
        $error[] = $l["err_create_backup_date_folder"];
        return false;
    }
    return $start_dir . "/" . $date;
}
function create_local_backup_folders($start_dir, $rotation = 0) 
{
    global $error;
    global $l;
    $date = @datify(@time(), 0, 1, "Ymd");
    $result = @chdir($start_dir);
    if( !$result && !mkdir($start_dir) ) 
    {
        $error[] = $l["err_create_backup_folder"];
        return false;
    }
    $folderlist = scandir($start_dir);
    $folderlist = array_diff($folderlist, array( ".", ".." ));
    $folders = array( );
    foreach( $folderlist as $k => $folderinfo ) 
    {
        if( $folderinfo == $date ) 
        {
            continue;
        }
        if( strlen($folderinfo) == 8 && strtotime($folderinfo) <= time() && 0 < strtotime($folderinfo) ) 
        {
            $temp_date = (int) substr($folderinfo, 6, 2);
            $temp_mon = (int) substr($folderinfo, 4, 2);
            $temp_yr = (int) substr($folderinfo, 0, 4);
            if( 0 < $temp_date && $temp_date < 32 && 0 < $temp_mon && $temp_mon < 13 && 2010 <= $temp_yr ) 
            {
                $folders[] = $folderinfo;
            }
        }
    }
    log_output("Local Backup Folders : ");
    log_output($folders);
    $num_backups = count($folders);
    $folders_to_delete = array( );
    if( $num_backups == $rotation ) 
    {
        $folders_to_delete = array( min($folders) );
    }
    else 
    {
        if( $rotation < $num_backups ) 
        {
            $folder_delete_count = $num_backups - $rotation;
            $folder_delete_count++;
            $folders_to_delete = array( );
            for( $i = 0; $i < $folder_delete_count; $i++ ) 
            {
                $folders_to_delete[] = min($folders);
                $folders = array_diff($folders, $folders_to_delete);
            }
        }
    }
    log_output("Folders to Delete : ");
    log_output($folders_to_delete);
    if( !empty($folders_to_delete) ) 
    {
        foreach( $folders_to_delete as $k => $v ) 
        {
            $files = scandir($start_dir . "/" . $v);
            $files = array_diff($files, array( ".", ".." ));
            foreach( $files as $file ) 
            {
                @unlink($start_dir . "/" . $v . "/" . $file);
            }
            if( !rmdir($start_dir . "/" . $v) ) 
            {
                return false;
            }
        }
    }
    $result = @chdir($start_dir . "/" . $date);
    if( !$result && !mkdir($start_dir . "/" . $date) ) 
    {
        $error[] = $l["err_create_backup_date_folder_folder"];
        return false;
    }
    return $start_dir . "/" . $date;
}
function create_local_backup_folders2($start_dir, $vpsid, $rotation = 0, $date = "") 
{
    global $error;
    global $l;
    if( substr($start_dir, 0, 1) != "/" ) 
    {
        $error[] = $l["err_backup_dir_not_absolute"];
        return false;
    }
    if( empty($date) ) 
    {
        $date = @datify(@time(), 0, 1, "Ymd");
    }
    $result = is_dir($start_dir);
    if( !$result && !mkdir($start_dir) ) 
    {
        $error[] = $l["err_create_backup_folder"];
        return false;
    }
    if( $rotation != 0 ) 
    {
        echo lang_vars_name($l["log_deleting_backups"], array( "rotation" => $rotation )) . "\n";
        $folders = scandir($start_dir);
        rsort($folders);
        $vps = getvps($vpsid);
        $extensions = get_backup_extensions($vps["virt"]);
        foreach( $folders as $folder ) 
        {
            if( $folder == $date ) 
            {
                continue;
            }
            if( !is_valid_backup_folder($folder) ) 
            {
                continue;
            }
            $files = scandir($start_dir . "/" . $folder);
            if( count($files) <= 2 ) 
            {
                if( @rmdir($start_dir . "/" . $folder) ) 
                {
                    echo lang_vars_name($l["log_deleted_folder"], array( "folder" => $start_dir . "/" . $folder )) . "\n";
                }
                continue;
            }
            foreach( $files as $file ) 
            {
                $parts = explode(".", $file, 2);
                if( preg_match("/^" . $vpsid . "(_\\d+)?\$/is", $parts[0]) && in_array($parts[1], $extensions) ) 
                {
                    if( 1 < $rotation ) 
                    {
                        $rotation--;
                        continue 2;
                    }
                    if( @unlink($start_dir . "/" . $folder . "/" . $file) ) 
                    {
                        echo lang_vars_name($l["log_deleted_file"], array( "file" => $file )) . "\n";
                    }
                }
            }
            if( @unlink($start_dir . "/" . $folder . "/" . $vpsid . ".inf") ) 
            {
                echo lang_vars_name($l["log_deleted_file"], array( "file" => $start_dir . "/" . $folder . "/" . $vpsid . ".inf" )) . "\n";
            }
            $files = scandir($start_dir . "/" . $folder);
            if( count($files) <= 2 && rmdir($start_dir . "/" . $folder) ) 
            {
                echo lang_vars_name($l["log_deleted_folder"], array( "folder" => $start_dir . "/" . $folder )) . "\n";
            }
        }
        echo $l["log_finished_deleting_backups"] . "\n";
    }
    $result = is_dir($start_dir . "/" . $date);
    if( !$result && !mkdir($start_dir . "/" . $date) ) 
    {
        $error[] = $l["err_create_backup_date_folder"];
        return false;
    }
    return $start_dir . "/" . $date;
}
function _ftp_nlist($ftp_con, $dir) 
{
    $pwd = ftp_pwd($ftp_con);
    if( !@ftp_chdir($ftp_con, $dir) ) 
    {
        return false;
    }
    $_list = ftp_nlist($ftp_con, ".");
    if( empty($_list) ) 
    {
        $_list = ftp_nlist($ftp_con, "");
    }
    if( !@ftp_chdir($ftp_con, $pwd) ) 
    {
        return false;
    }
    $list = array( );
    foreach( $_list as $k => $v ) 
    {
        if( $v == "." || $v == ".." ) 
        {
            continue;
        }
        $v = ltrim($v, "./");
        $list[] = $dir . "/" . $v;
    }
    return $list;
}
function snapsize($size) 
{
    return (25 < $size ? 25 : $size);
}
function log_output($msg) 
{
    $handle = fopen(logdir() . "virtualizor-backups.log", "a");
    if( is_array($msg) ) 
    {
        foreach( $msg as $k => $m ) 
        {
            $log = "[" . datify(time(), 0, 1, "D M d H:i:s Y") . "] " . $m . "\n";
            fwrite($handle, $log);
        }
    }
    else 
    {
        $log = "[" . datify(time(), 0, 1, "D M d H:i:s Y") . "] " . $msg . "\n";
        fwrite($handle, $log);
    }
    fclose($handle);
}
function xmlstring2array($string) 
{
    $xml = simplexml_load_string($string, "SimpleXMLElement", LIBXML_NOCDATA);
    $array = json_decode(json_encode($xml), true);
    return $array;
}
function array2json($arr) 
{
    if( function_exists("json_encode") ) 
    {
        return json_encode($arr);
    }
    $parts = array( );
    $is_list = false;
    $keys = array_keys($arr);
    $max_length = count($arr) - 1;
    if( $keys[0] == 0 && $keys[$max_length] == $max_length ) 
    {
        $is_list = true;
        for( $i = 0; $i < count($keys);
        $i++ ) 
        {
            if( $i != $keys[$i] ) 
            {
                $is_list = false;
                break;
            }
        }
    }
    foreach( $arr as $key => $value ) 
    {
        if( is_array($value) ) 
        {
            if( $is_list ) 
            {
                $parts[] = array2json($value);
            }
            else 
            {
                $parts[] = "\"" . $key . "\":" . array2json($value);
            }
        }
        else 
        {
            $str = "";
            if( !$is_list ) 
            {
                $str = "\"" . $key . "\":";
            }
            if( is_numeric($value) ) 
            {
                $str .= $value;
            }
            else 
            {
                if( $value === false ) 
                {
                    $str .= "false";
                }
                else 
                {
                    if( $value === true ) 
                    {
                        $str .= "true";
                    }
                    else 
                    {
                        $str .= "\"" . addslashes($value) . "\"";
                    }
                }
            }
            $parts[] = $str;
        }
    }
    $json = implode(",", $parts);
    if( $is_list ) 
    {
        return "[" . $json . "]";
    }
    return "{" . $json . "}";
}
function vlog() 
{
    if( empty($GLOBALS["vlogfile"]) ) 
    {
        return false;
    }
    $handle = fopen($GLOBALS["vlogfile"], "a");
    $args = func_get_args();
    foreach( $args as $k => $v ) 
    {
        $log = "";
        if( is_array($v) ) 
        {
            $log = "[" . strftime("%a %b %e %H:%M:%S %Y") . "] Array : \n";
            $log .= var_export($v, 1);
            $log .= "\n";
            fwrite($handle, $log);
        }
        else 
        {
            $log = "[" . strftime("%a %b %e %H:%M:%S %Y") . "] " . $v . " \n";
            fwrite($handle, $log);
        }
        echo $log;
    }
    fclose($handle);
}
function create_temp_storage($stid, $lv, $type, $vpsid, $disable_compression) 
{
    global $globals;
    global $error;
    global $l;
    global $storages;
    $storage = $storages[$stid];
    if( empty($storage) ) 
    {
        $error[] = "create_temp_storage() : Storage not found";
        return false;
    }
    if( empty($vpsid) ) 
    {
        $error[] = "create_temp_storage() : No VPS IDs";
        return false;
    }
    $tmp_lv = trim(cleanpath($lv));
    if( empty($lv) || $tmp_lv == "/" || empty($tmp_lv) ) 
    {
        $error[] = "create_temp_storage() : LV empty";
        return false;
    }
    $disks = get_vps_DISKS($vpsid);
    $max_space = 0;
    $vps = getvps($vpsid);
    foreach( $disks as $disk ) 
    {
        if( preg_match("/" . $vps["vps_name"] . "swap/is", $disk["path"]) || !empty($disk["size_unit"]) && $disk["size_unit"] != "G" ) 
        {
            continue;
        }
        $size = $disk["size"];
        if( $max_space < $size ) 
        {
            $max_space = $size;
        }
    }
    $temp_storage_dir = "";
    $lv_size = (empty($disable_compression) ? $max_space * 1024 + 512 : ceil($max_space * 1024 * 1.1));
    if( preg_match("/block/is", $storage["type"]) ) 
    {
        if( preg_match("/zfs/is", $storage["type"]) ) 
        {
            $lvm_path = $storage["path"];
            $ret_lv = vexec("zfs create -V " . $lv_size . "M " . basename($lvm_path) . "/" . $lv);
            sleep(3);
        }
        else 
        {
            if( preg_match("/thin/is", $storage["type"]) ) 
            {
                $lvm_path = $storage["path"];
                $ret_lv = vexec($globals["com"]["lvcreate"] . " -V" . $lv_size . "M -n " . $lv . " -T " . $lvm_path);
                $lvm_path = dirname($lvm_path);
            }
            else 
            {
                $lvm_path = $storage["path"];
                $ret_lv = vexec($globals["com"]["lvcreate"] . " -L " . $lv_size . "M -n " . $lv . " " . $lvm_path);
            }
        }
        if( $ret_lv != 0 ) 
        {
            $error[] = $l["backups_err_lvm"];
            return false;
        }
        $ret_mkfs = vexec("/sbin/mkfs -t ext3 " . $lvm_path . "/" . $lv);
        if( $ret_mkfs != 0 ) 
        {
            $error[] = $l["backup_err_mkfs"];
            return false;
        }
        $ret_fsck = vexec("/sbin/e2fsck -f -y " . $lvm_path . "/" . $lv);
        $temp_storage_dir = "/var/virtualizor/" . $lv;
        if( !file_exists($temp_storage_dir) ) 
        {
            $ret_mkdir = vexec("/bin/mkdir " . $temp_storage_dir);
        }
        $ret_mount = vexec("/bin/mount " . $lvm_path . "/" . $lv . " " . $temp_storage_dir);
        if( $ret_mount != 0 ) 
        {
            $error[] = $l["backup_err_mount"];
            return false;
        }
    }
    if( preg_match("/file/is", $storage["type"]) ) 
    {
        $temp_storage_dir = $storage["path"] . "/" . $lv;
        @mkdir($temp_storage_dir, 493);
    }
    return $temp_storage_dir;
}
function cleanup_temp_storage($stid, $lv, $type, $virt, $vpsid) 
{
    global $globals;
    global $error;
    global $storages;
    if( in_array($virt, array( "openvz", "vzo", "vzk" )) ) 
    {
        vexec("/bin/rm -rf /vz/dump/" . $vpsid . ".*");
        return true;
    }
    $storage = $storages[$stid];
    if( empty($storage) ) 
    {
        $error[] = "cleanup_temp_storage() : Storage not found";
        return false;
    }
    $tmp_lv = trim(cleanpath($lv));
    if( empty($lv) || $tmp_lv == "/" || empty($tmp_lv) ) 
    {
        $error[] = "cleanup_temp_storage() : LV empty";
        return false;
    }
    if( preg_match("/block/is", $storage["type"]) ) 
    {
        $temp_dir = "/var/virtualizor/" . $lv;
        vexec("/bin/umount " . $temp_dir);
        if( preg_match("/zfs/is", $storage["type"]) ) 
        {
            vexec("zfs destroy -R " . basename($storage["path"]) . "/" . $lv);
            sleep(3);
        }
        else 
        {
            if( preg_match("/thin/is", $storage["type"]) ) 
            {
                vexec($globals["com"]["lvremove"] . " -f " . dirname($storage["path"]) . "/" . $lv);
            }
            else 
            {
                vexec($globals["com"]["lvremove"] . " -f " . $storage["path"] . "/" . $lv);
            }
        }
    }
    if( preg_match("/file/is", $storage["type"]) ) 
    {
        $temp_dir = $storage["path"] . "/" . $lv;
        if( cleanpath($storage["path"]) == cleanpath($temp_dir) ) 
        {
            $error[] = "cleanup_temp_storage() : Storage Path equal to TEMPORARY PATH to delete !";
            return false;
        }
    }
    vexec("/bin/rm -rf " . $temp_dir);
    return true;
}
function is_allowed($act) 
{
    global $user;
    $action = "act_" . $act;
    if( $user["uid"] == 0 ) 
    {
        return true;
    }
    if( empty($user[$action]) && !empty($user["aclid"]) ) 
    {
        return false;
    }
    return true;
}
function hooks($hook) 
{
    global $globals;
    $hookpath = $globals["path"] . "/hooks/" . $hook . ".php";
    if( file_exists($hookpath) ) 
    {
        include_once($hookpath);
        $args = func_get_args();
        unset($args[0]);
        $final_args = array( );
        foreach( $args as $k => $v ) 
        {
            $final_args[] = $v;
        }
        return call_user_func_array("__" . $hook, $final_args);
    }
    else 
    {
        return false;
    }
}
function distro_check($centos5 = 0, $centos6 = 0, $ubuntu = 0, $xcp = 0, $centos7 = 0) 
{
    if( file_exists("/etc/redhat-release") ) 
    {
        $release = file_get_contents("/etc/redhat-release");
        if( preg_match("/xenserver/is", $release) ) 
        {
            if( !empty($centos5) && preg_match("/release 5/is", $release) ) 
            {
                return $centos5;
            }
            if( !empty($centos6) && preg_match("/release 6/is", $release) ) 
            {
                return $centos6;
            }
            if( !empty($centos7) && preg_match("/release 7/is", $release) ) 
            {
                return $centos7;
            }
            return $xcp;
        }
        if( preg_match("/release 5/is", $release) ) 
        {
            return $centos5;
        }
        if( preg_match("/release 6/is", $release) ) 
        {
            return $centos6;
        }
        if( preg_match("/release 7/is", $release) ) 
        {
            return $centos7;
        }
    }
    else 
    {
        if( file_exists("/etc/debian_version") ) 
        {
            return $ubuntu;
        }
    }
}
function distro_name() 
{
    if( file_exists("/etc/redhat-release") ) 
    {
        return trim(file_get_contents("/etc/redhat-release"));
    }
    if( file_exists("/etc/debian_version") ) 
    {
        oexec("lsb_release -d | cut -f2", $o, $ret);
        if( $ret == 0 ) 
        {
            return trim($o);
        }
        return "Ubuntu";
    }
    return "otheros";
}
function vfilesize($file) 
{
    if( empty($file) ) 
    {
        return false;
    }
    if( PHP_INT_SIZE >= 8 ) 
    {
        return filesize($file);
    }
    vexec("stat -c%s \"" . $file . "\"", $output);
    return trim($output[0]);
}
function vm_disk_path($vps) 
{
    global $globals;
    if( !empty($vps["disks"][0]) ) 
    {
        return $vps["disks"][0]["path"];
    }
    return "/dev/" . $globals["lv"] . "/vs" . $vps["vps_name"];
}
function vps_disk_struct() 
{
    $ret["primary"] = 0;
    $ret["path"] = "";
    $ret["st_uuid"] = "";
    $ret["type"] = "block";
    $ret["size"] = 0;
    $ret["size_unit"] = "";
    $ret["vpsid"] = 0;
    $ret["rescue"] = 0;
    $ret["target_name"] = "";
    $ret["format"] = "";
    $ret["disk_uuid"] = "";
    return $ret;
}
function vpsdisk_db_struct() 
{
    $r["did"] = "";
    $r["disk_uuid"] = "";
    $r["st_uuid"] = "";
    $r["vps_uuid"] = "";
    $r["path"] = "";
    $r["primary"] = "";
    $r["size"] = "";
    $r["size_unit"] = "";
    $r["type"] = "";
    $r["format"] = "";
    $r["num"] = "";
    $r["rescue"] = "";
    $r["extra"] = "";
    return $r;
}
function get_vps_DISKS($vpsid) 
{
    global $globals;
    global $servers;
    global $kernel;
    $vps = getvps($vpsid);
    if( empty($vps) ) 
    {
        return "";
    }
    if( empty($servers) ) 
    {
        list_servers();
    }
    $vps["virt"] = (empty($vps["virt"]) ? $servers[$vps["serid"]]["virt"] : $vps["virt"]);
    $disks = $vps["disks"];
    if( empty($vps["disks"]) ) 
    {
        $disks[0]["primary"] = 1;
        $disks[0]["path"] = "/dev/" . $globals["lv"] . "/vs" . $vps["vps_name"];
        $disks[0]["st_uuid"] = "";
        $disks[0]["type"] = ((!empty($globals["thin_lv"]) ? "thin " : "")) . "block";
        $disks[0]["size"] = $vps["space"];
        $disks[0]["vpsid"] = $vpsid;
        if( $vps["virt"] == "xen" && empty($vps["hvm"]) && 0 < $vps["swap"] ) 
        {
            $disks[1]["primary"] = 0;
            $disks[1]["path"] = "/dev/" . $globals["lv"] . "/vs" . $vps["vps_name"] . "swap";
            $disks[1]["st_uuid"] = "";
            $disks[1]["type"] = ((!empty($globals["thin_lv"]) ? "thin " : "")) . "block";
            $disks[1]["size"] = $vps["swap"];
            $disks[1]["size_unit"] = "M";
            $disks[1]["vpsid"] = $vpsid;
        }
    }
    if( !empty($vps["rescue"]) ) 
    {
        $disks[-1]["primary"] = 1;
        $disks[-1]["rescue"] = 1;
        $disks[-1]["path"] = $disks[0]["path"] . "-rescue";
        $disks[-1]["st_uuid"] = $disks[0]["st_uuid"];
        $disks[-1]["type"] = $disks[0]["type"];
        $disks[-1]["format"] = $disks[0]["format"];
        $disks[-1]["size"] = 1;
        $disks[-1]["vpsid"] = $vpsid;
        $disks[0]["primary"] = 0;
        if( $kernel->conf($vpsid, "get_vps_rescue_DISKS") ) 
        {
            $disks = $kernel->get_vps_rescue_DISKS($vpsid, $disks);
        }
    }
    foreach( $disks as $k => $v ) 
    {
        $disks[$k]["vpsid"] = $vpsid;
        if( preg_match("/file/is", $v["type"]) ) 
        {
            $disks[$k]["format"] = (empty($v["format"]) ? "qcow2" : $v["format"]);
        }
        $disks[$k]["key"] = $k;
    }
    if( $kernel->conf($vpsid, "get_vps_DISKS") ) 
    {
        $disks = $kernel->get_vps_DISKS($vpsid, $disks);
    }
    return $disks;
}
function get_vps_disk($vpsid, $storage = "", $disk_num = 0) 
{
    $vps = getvps($vpsid);
    if( empty($vps) ) 
    {
        return "";
    }
    $disks = get_vps_disks($vpsid);
    if( empty($storage) ) 
    {
        if( !empty($disk_num) ) 
        {
            $DISK = $disks[$disk_num];
            $KEY = $disk_num;
        }
        else 
        {
            foreach( $disks as $k => $v ) 
            {
                if( !empty($v["primary"]) ) 
                {
                    $DISK = $v;
                    $KEY = $k;
                }
            }
        }
    }
    else 
    {
        foreach( $disks as $k => $v ) 
        {
            if( !empty($v["path"]) && $v["path"] == $storage ) 
            {
                $DISK = $v;
                $KEY = $k;
            }
        }
    }
    if( empty($DISK) ) 
    {
        return "";
    }
    $DISK["mount_point"] = "/home/" . $vps["vps_name"] . "/" . $KEY;
    $DISK["key"] = $KEY;
    return $DISK;
}
function update_vps_disks($serid, $stid, $resources, $vpsIDs = array( )) 
{
    return false;
}
function vpsdisk_info($vpsid, $storage = "") 
{
    $DISK = get_vps_disk($vpsid, $storage);
    if( empty($DISK) ) 
    {
        return "";
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        return diskinfo($DISK["path"]);
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        return file_diskinfo($DISK["path"]);
    }
}
function get_diskinfo($DISK) 
{
    if( empty($DISK) ) 
    {
        return "";
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        return diskinfo($DISK["path"]);
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        return file_diskinfo($DISK["path"]);
    }
}
function vpsdisk_size($DISK) 
{
    if( empty($DISK) ) 
    {
        return -1;
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        if( preg_match("/zfs/is", $DISK["type"]) ) 
        {
            $disk_path = basename(dirname($DISK["path"])) . "/" . basename($DISK["path"]);
            vexec("zfs get -p referenced " . $disk_path . " -o value", $o, $ret);
            $disk_size = (int) $o[1];
            if( empty($DISK["size_unit"]) || $DISK["size_unit"] == "G" ) 
            {
                $init = $disk_size / 1024 / 1024 / 1024;
            }
            else 
            {
                if( $DISK["size_unit"] == "M" ) 
                {
                    $init = $disk_size / 1024 / 1024;
                }
                else 
                {
                    if( $DISK["size_unit"] == "K" ) 
                    {
                        $init = $disk_size / 1024;
                    }
                    else 
                    {
                        $init = $disk_size;
                    }
                }
            }
            return $init;
        }
        if( preg_match("/ceph/is", $DISK["type"]) ) 
        {
            $disk_path = basename(dirname($DISK["path"])) . "/" . basename($DISK["path"]);
            vexec("/usr/bin/rbd info " . $disk_path, $o, $ret);
            $disk_size_temp = explode(" ", $o[1]);
            $disk_size = (int) trim($disk_size_temp[1]);
            if( empty($DISK["size_unit"]) || $DISK["size_unit"] == "G" ) 
            {
                $init = $disk_size / 1024;
            }
            else 
            {
                if( $DISK["size_unit"] == "M" ) 
                {
                    $init = $disk_size;
                }
                else 
                {
                    if( $DISK["size_unit"] == "K" ) 
                    {
                        $init = $disk_size * 1024;
                    }
                    else 
                    {
                        $init = $disk_size;
                    }
                }
            }
            return $init;
        }
        return lvsize($DISK["path"], $DISK["size_unit"]);
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        return qemu_size($DISK["path"], $DISK["size_unit"]);
    }
    return 0;
}
function vpsdisk_real_size($DISK) 
{
    if( empty($DISK) ) 
    {
        return -1;
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        if( preg_match("/zfs/is", $DISK["type"]) ) 
        {
            $disk_path = basename(dirname($DISK["path"])) . "/" . basename($DISK["path"]);
            vexec("zfs get -p volsize " . $disk_path . " -o value", $o, $ret);
            $disk_size = (int) $o[1];
            if( $DISK["size_unit"] == "G" ) 
            {
                $init = $disk_size / 1024 / 1024 / 1024;
            }
            else 
            {
                if( $DISK["size_unit"] == "M" ) 
                {
                    $init = $disk_size / 1024 / 1024;
                }
                else 
                {
                    if( $DISK["size_unit"] == "K" ) 
                    {
                        $init = $disk_size / 1024;
                    }
                    else 
                    {
                        $init = $disk_size;
                    }
                }
            }
            return $init;
        }
        return lvsize($DISK["path"], "B");
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        return qemu_size_real($DISK["path"]);
    }
    return 0;
}
function vpsdisk_path_build($suffix = "", $storage, $vps) 
{
    global $globals;
    global $kernel;
    if( $kernel->conf($vps["vpsid"], "vpsdisk_path_build") ) 
    {
        return $kernel->vpsdisk_path_build($vps["vpsid"], $suffix, $storage, $vps);
    }
    if( preg_match("/ceph/is", $storage["type"]) ) 
    {
        $disk_name = "vs" . $vps["vps_name"] . $suffix . "-" . $vps["uuid"];
        return $storage["path"] . "/" . $disk_name;
    }
    if( preg_match("/block/is", $storage["type"]) ) 
    {
        $disk_name = "vs" . $vps["vps_name"] . $suffix . "-" . $vps["uuid"];
    }
    else 
    {
        $disk_name = $vps["vps_name"] . $suffix . "-" . $vps["uuid"] . "." . ((empty($storage["format"]) ? "qcow2" : $storage["format"]));
    }
    $storage_path = (preg_match("/thin/is", $storage["type"]) && !preg_match("/zfs/is", $storage["type"]) ? dirname($storage["path"]) : $storage["path"]);
    return $storage_path . "/" . $disk_name;
}
function vpsdisk_add($vps_uuid, $DISK) 
{
    global $globals;
    global $kernel;
    $return = array( );
    $struct = vpsdisk_db_struct();
    $vals["vps_uuid"] = $vps_uuid;
    $vals["disk_uuid"] = (preg_match("/^d(\\w{15})/is", $DISK["disk_uuid"]) ? $DISK["disk_uuid"] : "d" . generaterandstr(15));
    foreach( $DISK as $k => $v ) 
    {
        if( !array_key_exists($k, $vals) && array_key_exists($k, $struct) ) 
        {
            $vals[$k] = $DISK[$k];
        }
    }
    if( !empty($vals["extra"]) && is_array($vals["extra"]) ) 
    {
        $vals["extra"] = serialize($vals["extra"]);
    }
    foreach( $vals as $k => $v ) 
    {
        $tokens[$k] = "`" . $k . "` = :" . $k;
    }
    $did = insert_and_id("INSERT INTO disks\n\t\t\t\t\t\tSET " . implode(", ", $tokens), $vals);
    if( empty($did) ) 
    {
        return false;
    }
    return $vals["disk_uuid"];
}
function vpsdisk_update($vps_uuid, $DISK) 
{
    global $globals;
    global $kernel;
    $return = array( );
    if( empty($DISK["disk_uuid"]) ) 
    {
        $return["no_disk_uuid"] = "There is no Disk UUID given !";
        return $return;
    }
    $struct = vpsdisk_db_struct();
    $vals["vps_uuid"] = $vps_uuid;
    $vals["disk_uuid"] = $DISK["disk_uuid"];
    foreach( $DISK as $k => $v ) 
    {
        if( !array_key_exists($k, $vals) && array_key_exists($k, $struct) ) 
        {
            $vals[$k] = $DISK[$k];
        }
    }
    if( !empty($vals["extra"]) && is_array($vals["extra"]) ) 
    {
        $vals["extra"] = serialize($vals["extra"]);
    }
    foreach( $vals as $k => $v ) 
    {
        $tokens[$k] = "`" . $k . "` = :" . $k;
    }
    makequery("UPDATE disks\n\t\t\t\t\t\tSET " . implode(", ", $tokens) . "\n\t\t\t\t\t\tWHERE disk_uuid = '" . $DISK["disk_uuid"] . "'", $vals);
    return $return;
}
function vpsdisk_create($DISK, $os_template = "") 
{
    global $globals;
    global $kernel;
    $return = array( );
    if( empty($DISK) ) 
    {
        $return[] = "No disk info";
        return $return;
    }
    if( $kernel->conf($DISK["vpsid"], "vpsdisk_create") ) 
    {
        return $kernel->vpsdisk_create($DISK["vpsid"], $DISK, $os_template);
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        if( preg_match("/zfs/is", $DISK["type"]) ) 
        {
            $disk_path = str_replace("/dev/zvol/", "", $DISK["path"]);
            if( preg_match("/thin/is", $DISK["type"]) ) 
            {
                vexec("zfs create -s -V " . $DISK["size"] . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G")) . " " . $disk_path, $o, $ret);
                if( $ret != "0" ) 
                {
                    $return[] = $GLOBALS["l"]["kvm_err_lvm"] . " " . $disk_path;
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
                if( preg_match("/compressed/is", $DISK["type"]) ) 
                {
                    vexec("zfs set compression=on " . $disk_path, $o, $ret);
                }
            }
            else 
            {
                if( preg_match("/block/is", $DISK["type"]) ) 
                {
                    vexec("zfs create -V " . $DISK["size"] . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G")) . " " . $disk_path, $o, $ret);
                    if( $ret != "0" ) 
                    {
                        $return[] = $GLOBALS["l"]["kvm_err_lvm"] . " " . $disk_path;
                        $return["derr"] = array_end($GLOBALS["logr"]);
                        return $return;
                    }
                    if( preg_match("/compressed/is", $DISK["type"]) ) 
                    {
                        vexec("zfs set compression=on " . $disk_path, $o, $ret);
                    }
                }
            }
            sleep(3);
            if( $ret != "0" ) 
            {
                $return[] = $GLOBALS["l"]["kvm_err_lvm"] . " " . $disk_path;
                $return["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
        }
        else 
        {
            if( preg_match("/ceph/is", $DISK["type"]) ) 
            {
                $disk_name = explode("/", $DISK["path"]);
                $pool_disk = $disk_name[3] . "/" . $disk_name[4];
                vexec("/usr/bin/rbd create --size " . round($DISK["size"]) . "" . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G")) . " " . $pool_disk . " --image-feature layering", $o, $ret);
                sleep(1);
                if( $ret != 0 ) 
                {
                    $return[] = $GLOBALS["l"]["kvm_err_ceph_block"] . " " . $pool_disk;
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
                vexec("/usr/bin/rbd map " . $pool_disk, $o, $ret);
                if( $ret != 0 ) 
                {
                    $return[] = $GLOBALS["l"]["kvm_err_ceph_block_map"] . " " . $pool_disk;
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
            }
            else 
            {
                if( preg_match("/thin/is", $DISK["type"]) ) 
                {
                    vexec($globals["com"]["lvcreate"] . " -V" . $DISK["size"] . "" . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G")) . " -n " . basename($DISK["path"]) . " -T " . storage_thin_path($DISK));
                }
                else 
                {
                    vexec($globals["com"]["lvcreate"] . " -L " . $DISK["size"] . "" . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G")) . " -n " . basename($DISK["path"]) . " " . storage_path($DISK));
                }
                vexec($globals["com"]["lvdisplay"] . " \"" . $DISK["path"] . "\"", $o, $ret);
                if( $ret != "0" ) 
                {
                    $return[] = $GLOBALS["l"]["kvm_err_lvm"];
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
            }
        }
        if( !empty($os_template) ) 
        {
            vexec("/bin/dd if=\"" . $os_template . "\" of=" . $DISK["path"] . " bs=24M 2>&1", $o, $ret);
            if( $ret != "0" ) 
            {
                $return[] = $GLOBALS["l"]["kvm_err_dd"];
                $return["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
        }
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        $format = $DISK["format"];
        $size = $DISK["size"] . "" . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G"));
        if( !empty($os_template) ) 
        {
            vexec("qemu-img convert -f raw -O " . $format . " " . $os_template . " " . $DISK["path"], $o, $ret);
            if( $ret != "0" ) 
            {
                $return[] = "QEMU : File Convert Error";
                $return["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
            vexec("qemu-img resize " . $DISK["path"] . " " . $size, $o, $ret);
            if( $ret != "0" ) 
            {
                $return[] = "QEMU : Resize Error";
                $return["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
        }
        else 
        {
            vexec("qemu-img create -f " . $format . " " . $DISK["path"] . " " . $size, $o, $ret);
            if( $ret != "0" ) 
            {
                $return[] = "QEMU : Create Error";
                $return["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
        }
    }
    return $return;
}
function vpsdisk_destroy($vid, $storage = "") 
{
    global $globals;
    global $kernel;
    if( is_array($vid) ) 
    {
        $DISK = $vid;
        $vid = $DISK["vpsid"];
    }
    else 
    {
        $DISK = get_vps_disk($vid, $storage);
        if( empty($DISK) ) 
        {
            $return[] = "Disk not found";
            return $return;
        }
    }
    $return = array( );
    if( $kernel->conf($vid, "vpsdisk_destroy") ) 
    {
        return $kernel->vpsdisk_destroy($vid, $DISK);
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        if( preg_match("/zfs/is", $DISK["type"]) ) 
        {
            $disk_path = basename(dirname($DISK["path"])) . "/" . basename($DISK["path"]);
            vexec("zfs destroy -R " . $disk_path);
        }
        else 
        {
            if( preg_match("/ceph/is", $DISK["type"]) ) 
            {
                $disk_path = basename(dirname($DISK["path"])) . "/" . basename($DISK["path"]);
                vexec("/usr/bin/rbd unmap " . $disk_path, $o, $ret);
                if( $ret != 0 ) 
                {
                    $return[] = $GLOBALS["l"]["kvm_err_ceph_block_unmap"] . " " . $disk_path;
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
                vexec("/usr/bin/rbd rm " . $disk_path, $o, $ret);
                if( $ret != 0 ) 
                {
                    $return[] = $GLOBALS["l"]["kvm_err_ceph_block_rm"] . " " . $disk_path;
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
            }
            else 
            {
                vexec($globals["com"]["lvremove"] . " -f " . $DISK["path"]);
            }
        }
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        vexec("rm -rf " . $DISK["path"]);
    }
}
function vpsdisk_mkfs_direct($DISK, $fstype) 
{
    global $globals;
    global $l;
    $return = array( );
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        if( $fstype != "swap" ) 
        {
            $ret = vexec("/sbin/mkfs -t " . $fstype . " " . $DISK["path"]);
        }
        else 
        {
            $ret = vexec("/sbin/mkswap -f " . $DISK["path"]);
        }
        if( $ret != "0" ) 
        {
            $return[] = $l["xen_err_mkfs"] . " - " . $fstype;
            $error["derr"] = array_end($GLOBALS["logr"]);
            return false;
        }
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        $com = "guestfish -a " . $DISK["path"] . " 2>/dev/null << EOF \nrun\n";
        if( $fstype != "swap" ) 
        {
            $com .= "mkfs " . $fstype . " /dev/sda\nEOF";
        }
        else 
        {
            $com .= "mkswap /dev/sda\nEOF";
        }
        $ret = vexec($com);
        if( $ret != "0" ) 
        {
            $return[] = "File : " . $l["xen_err_mkfs"] . " - " . $fstype;
            $error["derr"] = array_end($GLOBALS["logr"]);
            return false;
        }
    }
}
function mount($vpsid, $storage = "", $win = 0) 
{
    global $globals;
    global $kernel;
    $DISK = get_vps_disk($vpsid, $storage);
    if( empty($DISK) ) 
    {
        return "";
    }
    if( !is_dir($DISK["mount_point"]) ) 
    {
        mkdir_recursive($DISK["mount_point"], 493);
    }
    if( $kernel->conf($vpsid, "vbd_plug") && $DISK["format"] == "vhd" ) 
    {
        $orig_type = $DISK["type"];
        $DISK = $kernel->vbd_plug($vpsid, $DISK);
        $DISK["type"] = "block";
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        $diskinfo = diskinfo($DISK["path"]);
        if( empty($diskinfo["parts"][0]["islinux"]) && empty($win) ) 
        {
            return -1;
        }
        vexec("/sbin/kpartx -l " . $DISK["path"], $kpart, $kparted);
        $is_centos5 = os_check("centos", "<", 6);
        $kpartx_s = (!empty($is_centos5) ? "" : "s");
        vexec("/sbin/kpartx -av" . $kpartx_s . " " . $DISK["path"], $_kpart, $kparted);
        if( $kparted != 0 ) 
        {
            vexec("/sbin/kpartx -d " . $DISK["path"]);
            return "";
        }
        $tmp = explode(" ", $kpart[0]);
        $mapper = $tmp[0];
        vexec("/bin/mount /dev/mapper/" . $mapper . " " . $DISK["mount_point"], $mout, $mounted);
        if( $mounted != 0 && $diskinfo["parts"][0]["iswindows"] == 1 ) 
        {
            vexec("/bin/ntfsfix /dev/mapper/" . $mapper);
            vexec("/bin/mount /dev/mapper/" . $mapper . " " . $DISK["mount_point"], $mout, $mounted);
        }
        if( $mounted != "0" ) 
        {
            vexec("/bin/umount " . $DISK["mount_point"]);
            vexec("/sbin/kpartx -d " . $DISK["path"]);
            return "";
        }
        $DISK["kpart"] = $kpart;
        $DISK["diskinfo"] = $diskinfo;
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        $no_guestmount_support = os_check("centos", ">=", 7.3);
        $dret = file_diskinfo($DISK["path"]);
        if( $no_guestmount_support && $DISK["format"] == "raw" && !empty($dret["parts"][0]["iswindows"]) ) 
        {
            if( empty($dret["start_offset"]) ) 
            {
                return "";
            }
            vexec("mount -o loop,rw,offset=" . xss($dret["start_offset"]) . " " . xss($DISK["path"]) . " " . xss($DISK["mount_point"]), $mout, $mounted);
        }
        else 
        {
            vexec("guestmount -a " . $DISK["path"] . " -i --rw " . $DISK["mount_point"], $mout, $mounted);
        }
        if( $mounted != 0 && $dret["parts"][0]["iswindows"] == 1 ) 
        {
            $cmd = "guestfish -a " . $DISK["path"] . " 2>/dev/null << EOF \nrun\nntfsfix /dev/sda1\nEOF";
            vexec($cmd);
            vexec("guestmount -a " . $DISK["path"] . " -i --rw " . $DISK["mount_point"], $mout, $mounted);
        }
        if( $mounted != "0" ) 
        {
            vexec("/bin/umount " . $DISK["mount_point"]);
            return "";
        }
    }
    if( !empty($orig_type) ) 
    {
        $DISK["type"] = $orig_type;
    }
    return $DISK;
}
function mount_direct($vpsid, $storage = "") 
{
    global $globals;
    $DISK = get_vps_disk($vpsid, $storage);
    if( empty($DISK) ) 
    {
        return "";
    }
    if( !is_dir($DISK["mount_point"]) ) 
    {
        mkdir_recursive($DISK["mount_point"], 493);
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        $diskinfo = diskinfo($DISK["path"]);
        $DISK["diskinfo"] = $diskinfo;
        vexec("/bin/mount " . $DISK["path"] . " " . $DISK["mount_point"], $mout, $mounted);
        if( $mounted != "0" ) 
        {
            vexec("/bin/umount " . $DISK["mount_point"]);
            return "";
        }
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        vexec("guestmount -a " . $DISK["path"] . " -m /dev/sda --rw " . $DISK["mount_point"], $mout, $mounted);
        if( $mounted != "0" ) 
        {
            vexec("/bin/umount " . $DISK["mount_point"]);
            return "";
        }
    }
    return $DISK;
}
function mount_snapshot($DISK) 
{
    global $globals;
    if( empty($DISK) ) 
    {
        return "";
    }
    $DISK["mount_point"] = rtrim($DISK["mount_point"], "/") . "_snap";
    if( !is_dir($DISK["mount_point"]) ) 
    {
        mkdir_recursive($DISK["mount_point"], 493);
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        vexec("/bin/mount " . $DISK["snapshot_path"] . " " . $DISK["mount_point"], $mout, $mounted);
        if( $mounted != "0" ) 
        {
            vexec("/bin/umount " . $DISK["mount_point"]);
            return "";
        }
    }
    return $DISK;
}
function umount($DISK) 
{
    global $kernel;
    $return = array( );
    if( empty($DISK["mount_point"]) ) 
    {
        $return[] = "No mount point found";
        return $return;
    }
    vexec("/bin/umount " . $DISK["mount_point"], $o, $ret);
    if( $ret != "0" ) 
    {
        $return[] = "Error unmounting";
        $return["derr"] = array_end($GLOBALS["logr"]);
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        vexec("/sbin/kpartx -d " . $DISK["path"]);
    }
    if( $kernel->conf($DISK["vpsid"], "vbd_unplug") && $DISK["format"] == "vhd" ) 
    {
        $DISK = $kernel->vbd_unplug($DISK["vpsid"], $DISK);
    }
    return $return;
}
function vpsdisk_resize($vpsid, $storage = "") 
{
    global $kernel;
    $return = array( );
    $vps = getvps($vpsid);
    if( empty($vps) ) 
    {
        $return["error"][] = "VPS not found";
        return $return;
    }
    $DISK = get_vps_disk($vpsid, $storage);
    if( empty($DISK) ) 
    {
        $return["error"][] = "DISK not found";
        return $return;
    }
    if( $kernel->conf($vpsid, "vpsdisk_resize") ) 
    {
        $kernel_return = $kernel->vpsdisk_resize($vpsid, $DISK);
    }
    if( $kernel->conf($vpsid, "vbd_plug") && $DISK["format"] == "vhd" ) 
    {
        $DISK = $kernel->vbd_plug($vpsid, $DISK);
        $DISK["type"] = "block";
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        if( $DISK["format"] != "vhd" ) 
        {
            if( preg_match("/zfs/is", $DISK["type"]) ) 
            {
                $disk_path = str_replace("/dev/zvol/", "", $DISK["path"]);
                vexec("zfs set volsize=" . $DISK["size"] . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G")) . " " . $disk_path, $o, $ret);
            }
            else 
            {
                if( preg_match("/ceph/is", $DISK["type"]) ) 
                {
                    $disk_path = str_replace("/dev/rbd/", "", $DISK["path"]);
                    vexec("/usr/bin/rbd resize --size " . round($DISK["size"]) . "" . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G")) . " " . $disk_path);
                }
                else 
                {
                    vexec("lvresize -L " . $DISK["size"] . "" . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G")) . " " . $DISK["path"], $o, $ret);
                }
            }
        }
        $return["resized"] = true;
        $diskinfo = diskinfo($DISK["path"]);
        $DISK["diskinfo"] = $diskinfo;
        $return["diskinfo"] = $diskinfo;
        if( !empty($diskinfo["parts"][0]["islinux"]) && $diskinfo["numparts"] == 1 || !empty($diskinfo["parts"][0]["islinux"]) && !empty($diskinfo["parts"][1]["isswap"]) && $diskinfo["numparts"] == 2 ) 
        {
            $return["altered_partitions"] = true;
            if( 0 < $vps["swap"] && !empty($DISK["primary"]) ) 
            {
                $space_less_swap = (1024 * $DISK["size"] - $vps["swap"]) * 1024 * 2;
                $swap_start = $space_less_swap + $diskinfo["parts"][0]["start"];
                vexec("/sbin/sfdisk " . $DISK["path"] . " -uS --force << EOF\n" . $diskinfo["parts"][0]["start"] . "," . $space_less_swap . "," . $diskinfo["parts"][0]["hextype"] . "," . $diskinfo["parts"][0]["boot"] . "\n" . $swap_start . ",,82\n0,0\n0,0\nEOF", $o, $ret);
                if( $ret != "0" ) 
                {
                    $return["error"][] = "Error sfdisk";
                    $return["error"]["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
                vexec("/sbin/kpartx -l " . $DISK["path"], $kpart, $kparted);
                $is_centos5 = os_check("centos", "<", 6);
                $kpartx_s = (!empty($is_centos5) ? "" : "s");
                vexec("/sbin/kpartx -av" . $kpartx_s . " " . $DISK["path"], $_kpart, $kparted);
                if( $kparted == 0 ) 
                {
                    $stmp = explode(" ", $kpart[1]);
                    $smapper = $stmp[0];
                    vexec("/sbin/mkswap /dev/mapper/" . $smapper, $swaping, $swapret);
                }
                vexec("/sbin/kpartx -d " . $DISK["path"]);
            }
            else 
            {
                vexec("/sbin/sfdisk " . $DISK["path"] . " -uS --force << EOF\n" . $diskinfo["parts"][0]["start"] . ",," . $diskinfo["parts"][0]["hextype"] . "," . $diskinfo["parts"][0]["boot"] . "\n0,0\n0,0\n0,0\nEOF", $o, $ret);
                if( $ret != "0" ) 
                {
                    $return["error"][] = "Error sfdisk without swap";
                    $return["error"]["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
            }
        }
        else 
        {
            if( !empty($diskinfo["parts"][0]["iswindows"]) && $diskinfo["numparts"] == 1 ) 
            {
                $return["altered_partitions"] = true;
                vexec("/sbin/sfdisk " . $DISK["path"] . " -uS --force << EOF\n" . $diskinfo["parts"][0]["start"] . ",," . $diskinfo["parts"][0]["hextype"] . "," . $diskinfo["parts"][0]["boot"] . "\n0,0\n0,0\n0,0\nEOF", $o, $ret);
                if( $ret != "0" ) 
                {
                    $return["error"][] = "Windows : Error sfdisk";
                    $return["error"]["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
            }
        }
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        $size = $DISK["size"] . "" . ((!empty($DISK["size_unit"]) ? $DISK["size_unit"] : "G"));
        vexec("qemu-img resize " . $DISK["path"] . " " . $size, $o, $ret);
        if( $ret != "0" ) 
        {
            $return["error"][] = $GLOBALS["l"]["qemu_resize_err"];
            $return["error"]["derr"] = array_end($GLOBALS["logr"]);
            return $return;
        }
        $return["resized"] = true;
        $diskinfo = file_diskinfo($DISK["path"]);
        $DISK["diskinfo"] = $diskinfo;
        $return["diskinfo"] = $diskinfo;
        $com = "";
        if( !empty($diskinfo["parts"][0]["islinux"]) && $diskinfo["numparts"] == 1 || !empty($diskinfo["parts"][0]["islinux"]) && !empty($diskinfo["parts"][1]["isswap"]) && $diskinfo["numparts"] == 2 ) 
        {
            $return["altered_partitions"] = true;
            if( 0 < $vps["swap"] ) 
            {
                $space_less_swap = (1024 * $DISK["size"] - $vps["swap"]) * 1024 * 2;
                $com = "guestfish -a " . $DISK["path"] . " << EOF\nrun";
                foreach( $diskinfo["parts"] as $k => $v ) 
                {
                    $com .= "\npart-del /dev/sda " . ($k + 1);
                }
                $v = $diskinfo["parts"][0];
                $k = 0;
                $com .= "\npart-add /dev/sda p " . $v["start"] . " " . $space_less_swap . "\npart-set-mbr-id /dev/sda 1 0x" . $v["hextype"] . "\npart-set-bootable /dev/sda 1 " . (($v["boot"] ? "true" : "false"));
                $swap_start = $space_less_swap + 1;
                $com .= "\npart-add /dev/sda p " . $swap_start . " " . ($diskinfo["disk_max_sectors"] - 1) . "\npart-set-mbr-id /dev/sda 2 0x82\nmkswap /dev/sda2";
                $com .= "\nEOF";
            }
            else 
            {
                $make_single = 1;
            }
        }
        else 
        {
            if( !empty($diskinfo["parts"][0]["iswindows"]) && $diskinfo["numparts"] == 1 ) 
            {
                $return["altered_partitions"] = true;
                $make_single = 1;
            }
        }
        if( !empty($make_single) ) 
        {
            $com = "guestfish -a " . $DISK["path"] . " << EOF\nrun";
            foreach( $diskinfo["parts"] as $k => $v ) 
            {
                $com .= "\npart-del /dev/sda " . ($k + 1);
            }
            $v = $diskinfo["parts"][0];
            $com .= "\npart-add /dev/sda p " . $v["start"] . " " . ($diskinfo["disk_max_sectors"] - 1) . "\npart-set-mbr-id /dev/sda 1 0x" . $v["hextype"] . "\npart-set-bootable /dev/sda 1 " . (($v["boot"] ? "true" : "false"));
            $com .= "\nEOF";
        }
        if( !empty($com) ) 
        {
            vexec($com, $o, $ret);
            if( $ret != "0" ) 
            {
                $return["error"][] = "Qemu : Resize Partitions Error";
                $return["error"]["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
        }
    }
    return $return;
}
function vpsdisk_resize_filesystem($DISK) 
{
    global $globals;
    global $l;
    global $kernel;
    $return = array( );
    $vps = getvps($DISK["vpsid"]);
    if( empty($vps) ) 
    {
        $return["error"][] = "VPS not found";
        return $return;
    }
    if( $kernel->conf($vps["vpsid"], "vbd_plug") && $DISK["format"] == "vhd" ) 
    {
        $DISK = $kernel->vbd_plug($DISK["vpsid"], $DISK);
    }
    if( empty($DISK["diskinfo"]) ) 
    {
        $DISK["diskinfo"] = get_diskinfo($DISK);
    }
    if( $DISK["format"] == "vhd" ) 
    {
        $DISK["type"] = "block";
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        $kpartx = kpartx($DISK);
        if( empty($kpartx) ) 
        {
            $return[] = $l["kvm_err_kpart"];
            $return["derr"] = array_end($GLOBALS["logr"]);
            return $return;
        }
        $disk = $DISK["diskinfo"];
        if( !empty($disk["parts"][0]["islinux"]) ) 
        {
            vexec("/sbin/fsck -f -y " . $kpartx["maps"][0], $e2fsck, $e2ret);
            vexec($globals["com"]["resizefs"] . " " . $kpartx["maps"][0], $resize2fs, $reret);
            if( $reret != "0" ) 
            {
                $return["error"] = $l["kvm_err_resizefs"];
                $return["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
        }
        else 
        {
            if( !empty($disk["parts"][0]["iswindows"]) ) 
            {
                vexec("ntfsresize -P --force " . $kpartx["maps"][0] . " 2>&1", $resize2fs, $reret);
                if( $reret != "0" ) 
                {
                    $return["error"] = $l["kvm_err_resizefs"];
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
                vexec("ntfsfix -b " . $kpartx["maps"][0] . " 2>&1", $resize2fs, $reret);
                if( $reret != "0" ) 
                {
                    $return["error"] = $l["kvm_err_resizefs"];
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
            }
        }
        kpartx_delete($DISK);
    }
    if( preg_match("/file/is", $DISK["type"]) ) 
    {
        $disk = $DISK["diskinfo"];
        if( !empty($disk["parts"][0]["islinux"]) ) 
        {
            $com = "guestfish -a " . $DISK["path"] . " 2>/dev/null << EOF \nrun\ne2fsck /dev/sda1 correct:true\nresize2fs /dev/sda1\nEOF";
        }
        else 
        {
            if( !empty($disk["parts"][0]["iswindows"]) ) 
            {
                $com = "guestfish -a " . $DISK["path"] . " 2>/dev/null << EOF \nrun\nntfsfix /dev/sda1\nntfsresize-opts /dev/sda1 force:true\nEOF";
            }
        }
        if( !empty($com) ) 
        {
            vexec($com, $o, $ret);
            if( $ret != "0" ) 
            {
                if( !empty($disk["parts"][0]["islinux"]) ) 
                {
                    vexec($com, $o, $ret);
                }
                if( $ret != "0" ) 
                {
                    $return["error"] = "QEMU : Resize FS error";
                    $return["derr"] = array_end($GLOBALS["logr"]);
                    return $return;
                }
            }
        }
    }
    return $return;
}
function vpsdisk_snapshot_create($vid, $prefix = "snapshot", $disk_num = 0) 
{
    global $globals;
    if( is_array($vid) ) 
    {
        $DISK = $vid;
        $vid = $DISK["vpsid"];
    }
    else 
    {
        $DISK = get_vps_disk($vid, $storage, $disk_num);
        if( empty($DISK) ) 
        {
            return "";
        }
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        $tmp = $prefix . "-" . $disk_num . "-" . generaterandstr(5);
        if( preg_match("/zfs/is", $DISK["type"]) ) 
        {
            $disk_path = str_replace("/dev/zvol/", "", $DISK["path"]);
            $ret = vexec("zfs snapshot " . $disk_path . "@" . $tmp . "-SNAP");
            if( $ret != "0" ) 
            {
                return "";
            }
            $ret = vexec("zfs clone " . $disk_path . "@" . $tmp . "-SNAP " . basename(dirname($DISK["path"])) . "/" . $tmp);
            sleep(1);
        }
        else 
        {
            if( preg_match("/thin/is", $DISK["type"]) ) 
            {
                $ret = vexec($globals["com"]["lvcreate"] . " -kn -s -n " . $tmp . " " . $DISK["path"]);
            }
            else 
            {
                $ret = vexec($globals["com"]["lvcreate"] . " -s -L " . snapsize($DISK["size"]) . "G -n " . $tmp . " " . $DISK["path"]);
            }
        }
        if( $ret != "0" ) 
        {
            return "";
        }
        $DISK["snapshot_path"] = storage_path($DISK) . "/" . $tmp;
    }
    return $DISK;
}
function vpsdisk_snapshot_delete($DISK) 
{
    global $globals;
    $return = array( );
    if( empty($DISK["snapshot_path"]) ) 
    {
        $return[] = "No snapshot found";
        return $return;
    }
    if( preg_match("/block/is", $DISK["type"]) ) 
    {
        if( preg_match("/zfs/is", $DISK["type"]) ) 
        {
            $disk_path = str_replace("/dev/zvol/", "", $DISK["path"]);
            $tmp = basename($DISK["snapshot_path"]);
            $ret = vexec("zfs destroy " . basename(dirname($DISK["path"])) . "/" . $tmp . " 2>&1");
            sleep(2);
            if( $ret != "0" ) 
            {
                $return[] = "Error deleteing Clone";
                $return["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
            $ret = vexec("zfs destroy -R " . $disk_path . "@" . $tmp . "-SNAP", $o, $ret);
            sleep(3);
            if( $ret != "0" ) 
            {
                $return[] = "Error deleteing snapshot";
                $return["derr"] = array_end($GLOBALS["logr"]);
                return $return;
            }
        }
        else 
        {
            $ret = vexec($globals["com"]["lvremove"] . " -f " . $DISK["snapshot_path"], $o, $ret);
        }
        if( $ret != "0" ) 
        {
            $return[] = "Error deleteing snapshot";
            $return["derr"] = array_end($GLOBALS["logr"]);
            return $return;
        }
    }
    return $return;
}
function storage_type_text($type) 
{
    $type_text = array( );
    $type_text["block"] = "LVM";
    $type_text["thin block"] = "Thin LVM";
    $type_text["openvz"] = "OpenVZ";
    $type_text["file"] = "File";
    $type_text["zfs block"] = "ZFS";
    $type_text["zfs thin block"] = "ZFS Thin";
    $type_text["zfs block compressed"] = "ZFS Compressed";
    $type_text["zfs thin block compressed"] = "ZFS Thin Compressed";
    $type_text["ceph block"] = "Ceph Block Device";
    if( array_key_exists($type, $type_text) ) 
    {
        return $type_text[$type];
    }
}
function storage_path($DISK) 
{
    global $storages;
    $type = $DISK["type"];
    $vpsdisk_path = $DISK["path"];
    if( preg_match("/block/is", $type) ) 
    {
        return dirname($vpsdisk_path);
    }
    return dirname($vpsdisk_path);
}
function storage_thin_path($DISK) 
{
    global $storages;
    $st_uuid = $DISK["st_uuid"];
    $type = $DISK["type"];
    if( preg_match("/block/is", $type) && preg_match("/thin/is", $type) ) 
    {
        foreach( $storages as $sk => $sv ) 
        {
            if( $sv["st_uuid"] == $st_uuid ) 
            {
                return $sv["path"];
            }
        }
    }
    return "";
}
function storage_get_primary($virt = "") 
{
    global $storages;
    if( $virt == "vzo" ) 
    {
        $virt = "openvz";
    }
    foreach( $storages as $k => $v ) 
    {
        if( !empty($virt) && ($virt == "openvz" && $virt != $v["type"] || $virt != "openvz" && $v["type"] == "openvz") ) 
        {
            continue;
        }
        if( $virt == "proxo" && $v["type"] != "file" ) 
        {
            continue;
        }
        if( !empty($v["primary_storage"]) ) 
        {
            return $k;
        }
    }
    foreach( $storages as $k => $v ) 
    {
        if( !empty($virt) && ($virt == "openvz" && $virt != $v["type"] || $virt != "openvz" && $v["type"] == "openvz") ) 
        {
            continue;
        }
        if( $virt == "proxo" && $v["type"] == "file" ) 
        {
            continue;
        }
        return $k;
    }
}
function storage_size($path, $type) 
{
    if( preg_match("/file|openvz/is", $type) ) 
    {
        vexec("df -P " . $path, $disk);
        if( !empty($disk[1]) ) 
        {
            $tmp = preg_split("/[\\s]+/", trim($disk[1]));
            $free_Kblocks = (double) trim($tmp[3]);
            $one_Kblocks = (double) trim($tmp[1]);
            $ret["size"] = @round($one_Kblocks / 1024 / 1024, 2);
            $ret["free"] = @round($free_Kblocks / 1024 / 1024, 2);
        }
    }
    else 
    {
        if( preg_match("/zfs/is", $type) ) 
        {
            $pool_name = basename($path);
            vexec("zfs get -p available " . $pool_name . " -o value", $o);
            $available = @round($o[1] / 1024 / 1024 / 1024, 2);
            vexec("zpool list " . $pool_name . " -o size", $k);
            if( strpos($k[1], "M") !== false ) 
            {
                $tmp = (double) str_replace("M", "", $k[1]);
                $size = @round($tmp / 1024, 2);
            }
            else 
            {
                if( strpos($k[1], "T") !== false ) 
                {
                    $tmp = (double) str_replace("T", "", $k[1]);
                    $size = round($tmp * 1024, 2);
                }
                else 
                {
                    $tmp = (double) substr($k[1], 0, -1);
                    $size = round($tmp, 2);
                }
            }
            $ret["size"] = $size;
            $ret["free"] = $available;
        }
        else 
        {
            if( preg_match("/ceph/is", $type) ) 
            {
                $pool_name = basename($path);
                vexec("rados df -p \"" . $pool_name . "\"", $disk);
                if( !empty($disk[3]) ) 
                {
                    $tmp = explode(" ", $disk[3]);
                    $ret["free"] = @round((double) @trim($tmp[@count($tmp) - 1]) / 1024 / 1024, 2);
                }
                if( !empty($disk[4]) ) 
                {
                    $tmp = explode(" ", $disk[4]);
                    $ret["size"] = @round((double) @trim($tmp[@count($tmp) - 1]) / 1024 / 1024, 2);
                }
            }
            else 
            {
                if( preg_match("/thin/is", $type) && preg_match("/block/is", $type) ) 
                {
                    vexec("lvdisplay -C --nosuffix --units k \"" . $path . "\"", $disk);
                    if( !empty($disk[1]) ) 
                    {
                        $tmp = preg_split("/[\\s]+/", trim($disk[1]));
                        $used_percentage = (double) trim($tmp[4]);
                        $free_percentage = 100 - $used_percentage;
                        $total_space_kb = (double) trim($tmp[3]);
                        $ret["size"] = @round($total_space_kb / 1024 / 1024, 2);
                        $ret["free"] = @round(($total_space_kb * $free_percentage) / 100 / 1024 / 1024, 2);
                    }
                }
                else 
                {
                    vexec("vgdisplay -C --nosuffix --units k \"" . $path . "\"", $disk);
                    if( !empty($disk[1]) ) 
                    {
                        $tmp = preg_split("/[\\s]+/", trim($disk[1]));
                        $ret["size"] = @round((double) @trim($tmp[@count($tmp) - 2]) / 1024 / 1024, 2);
                        $ret["free"] = @round((double) @trim($tmp[@count($tmp) - 1]) / 1024 / 1024, 2);
                    }
                }
            }
        }
    }
    return $ret;
}
function storage_allocated_space($stid) 
{
    global $globals;
    global $servers;
    $resid = makequery("SELECT * FROM storage\n\t\t\t\t\t\tWHERE stid = '" . $stid . "'");
    if( vsql_num_rows($resid) < 1 ) 
    {
        return 0;
    }
    $storage = vsql_fetch_assoc($resid);
    $resid = makequery("SELECT * FROM storage_servers\n\t\t\t\t\t\tWHERE stid = '" . $stid . "'");
    if( 1 <= vsql_num_rows($resid) ) 
    {
        for( $i = 0; $i < vsql_num_rows($resid);
        $i++ ) 
        {
            $prow = vsql_fetch_assoc($resid);
            $storage_servers[$prow["stid"] . "|" . $prow["serid"] . "|" . $prow["sgid"]] = $prow;
            $_servers[$prow["serid"]] = $prow["serid"];
            $_server_groups[$prow["sgid"]] = $prow["sgid"];
        }
    }
    $final_servers = array( );
    foreach( $servers as $k => $v ) 
    {
        if( isset($_servers[$k]) || !empty($_servers[-1]) || isset($_server_groups[$v["sgid"]]) ) 
        {
            $final_servers[$k] = $k;
        }
    }
    if( empty($final_servers) ) 
    {
        return 0;
    }
    if( $storage["type"] == "openvz" ) 
    {
        $res = makequery("SELECT SUM(space) AS alloc_space FROM vps\n\t\t\t\t\t\t\tWHERE serid IN (" . implode(", ", $final_servers) . ")\n\t\t\t\t\t\t\tAND virt = 'openvz'");
        $row = vsql_fetch_assoc($res);
        return (double) $row["alloc_space"];
    }
    $res = makequery("SELECT SUM(size) AS total_size, size_unit FROM disks\n\t\t\tWHERE st_uuid = '" . $storage["st_uuid"] . "'");
    $space_alloc = 0;
    for( $i = 0; $i < vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        if( $row["size_unit"] == "M" ) 
        {
            $row["total_size"] = (double) ($row["total_size"] / 1024);
        }
        $space_alloc += (double) $row["total_size"];
    }
    return (double) $space_alloc;
}
function kpartx($vid, $storage = "") 
{
    if( is_array($vid) ) 
    {
        $DISK = $vid;
        $vid = $DISK["vpsid"];
    }
    else 
    {
        $DISK = get_vps_disk($vid, $storage);
        if( empty($DISK) ) 
        {
            return "";
        }
    }
    vexec("/sbin/kpartx -l " . $DISK["path"], $kpart, $kparted);
    $is_centos5 = os_check("centos", "<", 6);
    $kpartx_s = (!empty($is_centos5) ? "" : "s");
    vexec("/sbin/kpartx -av" . $kpartx_s . " " . $DISK["path"], $_kpart, $kparted);
    if( $kparted != 0 ) 
    {
        return "";
    }
    $maps = array( );
    foreach( $kpart as $k => $v ) 
    {
        $tmp = explode(" ", $kpart[$k]);
        $maps[$k] = "/dev/mapper/" . $tmp[0];
    }
    $KPARTX["maps"] = $maps;
    $KPARTX["raw_list"] = $kpart;
    return $KPARTX;
}
function kpartx_delete($vid, $storage = "") 
{
    if( is_array($vid) ) 
    {
        $DISK = $vid;
        $vid = $DISK["vpsid"];
    }
    else 
    {
        $DISK = get_vps_disk($vid, $storage);
        if( empty($DISK) ) 
        {
            $return[] = "Disk not found";
            return $return;
        }
    }
    vexec("/sbin/kpartx -d " . $DISK["path"], $kpart, $kparted);
    return "";
}
function package_install($package, $log) 
{
    global $globals;
    $package = (is_array($package) ? $package : array( $package ));
    $package_list = implode(" ", $package);
    if( distro_check(0, 0, 1) ) 
    {
        foreach( $package as $k => $v ) 
        {
            shell_exec("apt-get -y install " . $v . " >> " . $log . " 2>&1");
        }
        return NULL;
    }
    else 
    {
        shell_exec("yum -y install " . $package_list . " >> " . $log . " 2>&1");
    }
}
function chkconfig($service, $priority = "") 
{
    global $globals;
    if( distro_check(0, 0, 1) ) 
    {
        shell_exec("update-rc.d " . $service . " defaults " . $priority . "");
    }
    else 
    {
        shell_exec("/sbin/chkconfig " . $service . " on");
    }
}
function get_cores() 
{
    global $globals;
    @exec("cat /proc/cpuinfo", $core_output, $ret);
    $c_tmp = implode("\n", $core_output);
    preg_replace("/(.*?)processor(\\s*?):(\\s*?)(.*?)\\n/ies", "\$cores[] = trim('\$4');", $c_tmp);
    if( $ret != 0 || count($cores) < 1 ) 
    {
        return false;
    }
    return $no_of_cores = max(array_values($cores)) + 1;
}
function database_dump($dbuser, $dbpass, $db, $filename) 
{
    vexec("/usr/local/emps/bin/mysqldump --user=" . $dbuser . " --password=" . $dbpass . " " . $db . " | gzip -9 > " . $filename, $out, $ret);
    return $ret;
}
function pass_encrypt($txt, $salt) 
{
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($salt), $txt, MCRYPT_MODE_CBC, md5(md5($salt))));
}
function pass_decrypt($crypttxt, $salt) 
{
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($salt), base64_decode($crypttxt), MCRYPT_MODE_CBC, md5(md5($salt))), "");
}
function ebtables_save() 
{
    if( distro_check(0, 0, 0, 0, 1) ) 
    {
        vexec("/usr/libexec/ebtables save");
    }
    else 
    {
        vexec("service ebtables save");
    }
}
function vncPort($vps) 
{
    $vncport = 0;
    if( !empty($vps["vncport"]) ) 
    {
        $vncport = $vps["vncport"];
    }
    if( empty($vncport) ) 
    {
        $vps_name = (int) str_replace("v", "", $vps["vps_name"]);
        $vncport = 5900 - 1000 + $vps_name;
    }
    return $vncport;
}
function merge_error($error1, $error2) 
{
    if( empty($error2) ) 
    {
        return $error1;
    }
    if( !is_array($error2) ) 
    {
        $error2 = array( $error2 );
    }
    if( !is_array($error1) ) 
    {
        $error1 = (empty($error1) ? array( ) : array( $error1 ));
    }
    return array_merge($error1, $error2);
}
function yum_exclude($excludes = "") 
{
    $conf = "/etc/yum.conf";
    if( !file_exists($conf) ) 
    {
        return true;
    }
    $excludes = (is_array($excludes) ? $excludes : array( $excludes ));
    if( empty($excludes) ) 
    {
        $excludes = array( "kernel" );
    }
    $excludes = array_unique($excludes);
    $yum = file($conf);
    $exclude_line = -1;
    foreach( $yum as $k => $line ) 
    {
        if( preg_match("/^exclude/is", $line) ) 
        {
            $exclude_line = $k;
            foreach( $excludes as $xk => $xv ) 
            {
                if( !is_string($xv) ) 
                {
                    return false;
                }
                if( preg_match("/" . trim($xv) . "/is", $line) ) 
                {
                    unset($excludes[$xk]);
                }
            }
        }
    }
    if( count($excludes) == 0 ) 
    {
        return true;
    }
    $excludes = implode(" ", $excludes);
    if( $exclude_line != -1 ) 
    {
        $yum[$exclude_line] = trim($yum[$exclude_line]) . " " . $excludes . "\n";
        writefile($conf, implode("", $yum), 1);
    }
    else 
    {
        exec("echo " . xss("exclude=" . $excludes) . " >> " . $conf);
    }
    return true;
}
function load_master_settings() 
{
    include(dirname(dirname(__FILE__)) . "/universal.php");
    return $globals;
}
function get_slave_settings($serid = 0, $setting_name = "") 
{
    global $globals;
    global $servers;
    global $servergroups;
    global $SETTINGS;
    $SLAVE_SETTINGS = @unserialize($servers[$serid]["settings"]) or $ret = array( );
    foreach( $SETTINGS as $sk => $sv ) 
    {
        if( preg_match("/m/", $SETTINGS[$sk]) && array_key_exists($sk, $globals) ) 
        {
            $ret[$sk] = $globals[$sk];
        }
        if( preg_match("/s/", $SETTINGS[$sk]) && array_key_exists($sk, $SLAVE_SETTINGS) ) 
        {
            $ret[$sk] = $SLAVE_SETTINGS[$sk];
        }
    }
    if( !empty($setting_name) ) 
    {
        return $ret[$setting_name];
    }
    return $ret;
}
function os_arch() 
{
    oexec("uname -a", $o, $r);
    return (preg_match("/amd64|x86\\_64/is", $o) ? 64 : 32);
}
function cleanpath($path) 
{
    $path = str_replace("\\\\", "/", $path);
    $path = str_replace("\\", "/", $path);
    return rtrim($path, "/");
}
function pass_strength($passowrd) 
{
    global $globals;
    global $error;
    $score = 0;
    if( strlen($passowrd) < 4 ) 
    {
        $pass_strength = (int) (1.5 / 5 * 100);
        return $pass_strength;
    }
    if( 7 < strlen($passowrd) ) 
    {
        $score += 1.5;
    }
    if( preg_match("/([a-z].*[A-Z])|([A-Z].*[a-z])/", $passowrd) ) 
    {
        $score += 1.5;
    }
    if( preg_match("/([a-zA-Z])/", $passowrd) && preg_match("/([0-9])/", $passowrd) ) 
    {
        $score += 1.5;
    }
    if( preg_match("/([!%&@#\$^*?_])/", $passowrd) && preg_match("/([a-zA-Z])/", $passowrd) ) 
    {
        $score += 1.5;
    }
    if( preg_match("/(.*[!%&@#\$^*?_].*[!%&@#\$^*?_])/", $passowrd) && preg_match("/([a-zA-Z])/", $passowrd) ) 
    {
        $score += 1.5;
    }
    if( $score < 2 ) 
    {
        $pass_strength = (int) ($score / 5 * 100);
    }
    if( $score == 2 ) 
    {
        $pass_strength = (int) ($score / 5 * 100);
    }
    else 
    {
        $pass_strength = (int) ($score / 5 * 100);
    }
    if( 100 < $pass_strength ) 
    {
        return 100;
    }
    return $pass_strength;
}
function win_pass_score($passowrd) 
{
    global $globals;
    global $error;
    $score = 0;
    if( preg_match("/[0-9]/", $passowrd) ) 
    {
        $score += 1;
    }
    if( preg_match("/[a-z]/", $passowrd) ) 
    {
        $score += 1;
    }
    if( preg_match("/[A-Z]/", $passowrd) ) 
    {
        $score += 1;
    }
    if( preg_match("/[^a-zA-Z0-9]/", $passowrd) ) 
    {
        $score += 1;
    }
    return $score;
}
function generateRandPwd($length) 
{
    $string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%&*";
    return substr(str_shuffle($string), 0, $length);
}
function get_meminfo($path = "/proc/meminfo", $data = "") 
{
    if( empty($data) ) 
    {
        $data = explode("\n", file_get_contents($path));
    }
    $meminfo = array( );
    foreach( $data as $line ) 
    {
        list($key, $val) = explode(":", $line);
        $tmp_val = explode(" ", trim($val));
        $meminfo[$key] = (int) ($tmp_val[0] / 1024);
    }
    return $meminfo;
}
function new_vps_name($virt) 
{
    global $globals;
    global $error;
    if( !empty($globals["disable_master_vpsname"]) ) 
    {
        return "";
    }
    $res = makequery("DELETE FROM `vps_name`\n\t\t\tWHERE time <= (" . (time() - 1800) . ")");
    if( $virt == "openvz" || $virt == "vzo" ) 
    {
        $ret = 101;
        $q = "SELECT vps_name FROM `vps` \n\t\t\tWHERE (vps_name * 1) rlike '^[0-9]*\$'\n\t\t\tAND virt = 'openvz' OR virt = 'vzo'\n\t\t\tORDER BY (vps_name * 1) DESC\n\t\t\tLIMIT 0, 1";
    }
    else 
    {
        $ret = 1001;
        $q = "SELECT vps_name FROM `vps` \n\t\t\tWHERE vps_name rlike '^[0-9]*\$'\n\t\t\tAND virt != 'openvz'\n\t\t\tORDER BY vps_name DESC\n\t\t\tLIMIT 0, 1";
        $res = makequery($q);
        if( 0 < vsql_num_rows($res) ) 
        {
            $row = vsql_fetch_assoc($res);
            $row["vps_name"] = (int) str_replace("v", "", $row["vps_name"]);
            if( $ret <= $row["vps_name"] ) 
            {
                $ret = $row["vps_name"] + 1;
            }
        }
        $q = "SELECT vps_name FROM `vps` \n\t\t\tWHERE vps_name rlike '^v[0-9]*\$'\n\t\t\tAND virt != 'openvz'\n\t\t\tORDER BY substring(vps_name, 2)*1 DESC\n\t\t\tLIMIT 0, 1";
    }
    $res = makequery($q);
    if( 0 < vsql_num_rows($res) ) 
    {
        $row = vsql_fetch_assoc($res);
        $row["vps_name"] = (int) str_replace("v", "", $row["vps_name"]);
        if( $ret <= $row["vps_name"] ) 
        {
            $ret = $row["vps_name"] + 1;
        }
    }
    if( $virt == "openvz" || $virt == "vzo" ) 
    {
        $res = makequery("SELECT vpsname FROM vps_name \n\t\t\t\tWHERE virt = 'openvz' OR virt = 'vzo'\n\t\t\t\tORDER BY (vpsname * 1) DESC\n\t\t\t\tLIMIT 0, 1");
    }
    else 
    {
        $res = makequery("SELECT vpsname FROM vps_name \n\t\t\t\tWHERE virt != 'openvz' && virt != 'vzo'\n\t\t\t\tORDER BY (vpsname * 1) DESC\n\t\t\t\tLIMIT 0, 1");
    }
    if( 0 < vsql_num_rows($res) ) 
    {
        $row = vsql_fetch_assoc($res);
        if( $ret <= $row["vpsname"] ) 
        {
            $ret = $row["vpsname"] + 1;
        }
    }
    $res = makequery("INSERT INTO vps_name \n\t\t\t\tSET vpsname = '" . $ret . "',\n\t\t\t\tvirt = '" . $virt . "',\n\t\t\t\tserid='" . $globals["server"] . "',\n\t\t\t\ttime = '" . time() . "'");
    if( $virt == "openvz" || $virt == "proxo" || $virt == "proxl" || $virt == "proxk" || $virt == "vzo" ) 
    {
        return $ret;
    }
    return "v" . $ret;
}
function mask2cidr($mask) 
{
    if( $mask == "0.0.0.0" ) 
    {
        return 0;
    }
    $long = ip2long($mask);
    $base = ip2long("255.255.255.255");
    return 32 - log(($long ^ $base) + 1, 2);
}
function to_master($table, $column, $id, $unique_column, $value) 
{
    if( $column == "array" && is_array($value) ) 
    {
        $value = serialize($value);
    }
    $res = makequery("INSERT INTO to_master SET\n\t\t\t\t\t`tables` = :tables,\n\t\t\t\t\t`columns` = :columns,\n\t\t\t\t\t`id` = :id,\n\t\t\t\t\t`unique_column` = :unique_column,\n\t\t\t\t\t`value` = :value\n\t\t\t\t\tON DUPLICATE KEY UPDATE \n\t\t\t\t\t\t`tables` = :tables,\n\t\t\t\t\t\t`columns` = :columns,\n\t\t\t\t\t\t`id` = :id,\n\t\t\t\t\t\t`unique_column` = :unique_column,\n\t\t\t\t\t\t`value` = :value", array( ":tables" => $table, ":columns" => $column, ":id" => $id, ":unique_column" => $unique_column, ":value" => $value ));
    if( vsql_num_rows($res) < 1 ) 
    {
        return false;
    }
    return true;
}
function give_to_master_data() 
{
    global $globals;
    if( is_slave() && !is_api_call(1) ) 
    {
        return false;
    }
    $res = makequery("SELECT * FROM to_master");
    $to_master = array( );
    for( $i = 1; $i <= vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $to_master[$row["tables"]][$row["id"]][$row["columns"]] = $row;
    }
    $res = makequery("TRUNCATE to_master");
    return $to_master;
}
function save_to_master_data($data, $serid) 
{
    if( empty($data) ) 
    {
        return false;
    }
    foreach( $data as $tables => $tabledata ) 
    {
        if( $tables == "tasks" ) 
        {
            if( !is_master() ) 
            {
                continue;
            }
            $keys = implode(",", array_keys($tabledata));
            $res = makequery("SELECT actid, slaveactid FROM `tasks` \n\t\t\t\t\t\t\tWHERE slaveactid IN (" . ((empty($keys) ? "-1000" : $keys)) . ")\n\t\t\t\t\t\t\tAND serid = '" . $serid . "'");
            for( $i = 0; $i < vsql_num_rows($res);
            $i++ ) 
            {
                $row = vsql_fetch_assoc($res);
                $found[$row["slaveactid"]] = $row["actid"];
            }
            foreach( $tabledata as $id => $columndata ) 
            {
                $qval = array( );
                $token_vals = array( );
                foreach( $columndata as $cols => $values ) 
                {
                    if( $cols == "array" ) 
                    {
                        $tmp = unserialize($values["value"]);
                        foreach( $tmp as $tk => $tv ) 
                        {
                            $token_vals[":" . $tk] = $tv;
                        }
                        continue;
                    }
                    else 
                    {
                        $token_vals[":" . $cols] = $values["value"];
                    }
                }
                if( empty($found[$id]) ) 
                {
                    $query_table = "INSERT INTO tasks SET ";
                    $token_vals[":slaveactid"] = $id;
                    $token_vals[":serid"] = $serid;
                    $where = "";
                }
                else 
                {
                    $query_table = "UPDATE tasks SET ";
                    $where = "`slaveactid` = '" . $id . "' AND serid = '" . $serid . "'";
                }
                unset($token_vals[":actid"]);
                foreach( $token_vals as $ck => $cv ) 
                {
                    $qval[$ck] = "`" . substr($ck, 1) . "` = " . $ck;
                }
                $query = $query_table . implode(",", $qval) . ((empty($where) ? "" : " WHERE " . $where));
                $_res = makequery($query, $token_vals);
            }
            continue;
        }
        else 
        {
            $query_table = "UPDATE " . $tables . " SET ";
            foreach( $tabledata as $id => $columndata ) 
            {
                $qval = array( );
                $token_vals = array( );
                foreach( $columndata as $cols => $values ) 
                {
                    $qval[$cols] = "`" . $cols . "` = :" . $cols;
                    $token_vals[":" . $cols] = $values["value"];
                    $token_vals[":where"] = $id;
                    $where = "`" . $values["unique_column"] . "` = :where";
                }
                $query = $query_table . implode(",", $qval) . " WHERE " . $where;
                $_res = makequery($query, $token_vals);
            }
        }
    }
}
function get_recipe($rid = "") 
{
    global $globals;
    $recipes = array( );
    if( empty($rid) ) 
    {
        return false;
    }
    $where = " WHERE rid = '" . $rid . "'";
    $res = makequery("SELECT * FROM recipes " . $where);
    if( vsql_num_rows($res) < 0 ) 
    {
        return $recipes;
    }
    return vsql_fetch_assoc($res);
}
function getall_bw_info($start, $end) 
{
    $vpses = array( );
    $res = makequery("SELECT v.vpsid,v.time as creation_date,v.uid,b.*\n\t\t\t\t\tFROM vps v \n\t\t\t\t\tLEFT JOIN bandwidth b ON v.vpsid = b.vpsid\n\t\t\t\t\tWHERE b.date >= '" . $start . "' AND b.date <= '" . $end . "' AND b.time = 0 AND v.serid=0");
    for( $i = 0; $i < vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $vpses[$row["vpsid"]]["bandwidth"][$row["date"]]["in"] = $row["in"];
        $vpses[$row["vpsid"]]["bandwidth"][$row["date"]]["out"] = $row["out"];
        $vpses[$row["vpsid"]]["user"] = $row["uid"];
        $vpses[$row["vpsid"]]["creation_date"] = $row["creation_date"];
    }
    return $vpses;
}
function get_map_data($ip_address) 
{
    $address = array( );
    if( empty($ip_address) ) 
    {
        return false;
    }
    $address = get_softaculous_file("http://s2.softaculous.com/a/virtualizor/ip_location.php?ip=" . $ip_address);
    return $address;
}
function valid_date($date) 
{
    if( strlen($date) != 10 ) 
    {
        return false;
    }
    $day = (int) substr($date, 0, 2);
    $month = (int) substr($date, 3, 2);
    $year = (int) substr($date, 6, 4);
    if( $year < 0 ) 
    {
        return false;
    }
    if( $month < 0 || 12 < $month ) 
    {
        return false;
    }
    if( $day < 0 || 31 < $day ) 
    {
        return false;
    }
    if( mktime(0, 0, 0, $month, $day, $year) < 0 ) 
    {
        return false;
    }
    return substr($date, 6, 4) . substr($date, 3, 2) . substr($date, 0, 2);
}
function valid_time($time, $date = "") 
{
    if( strlen($time) != 8 ) 
    {
        return false;
    }
    $hour = (int) substr($time, 0, 2);
    $minute = (int) substr($time, 3, 2);
    $second = (int) substr($time, 6, 2);
    if( $hour < 0 || 23 < $hour ) 
    {
        return false;
    }
    if( $minute < 0 || 59 < $minute ) 
    {
        return false;
    }
    if( $second < 0 || 59 < $second ) 
    {
        return false;
    }
    if( !empty($date) ) 
    {
        if( !valid_date($date) ) 
        {
            return false;
        }
        $day = (int) substr($date, 0, 2);
        $month = (int) substr($date, 3, 2);
        $year = (int) substr($date, 6, 4);
        $unixtime = mktime($hour, $minute, $second, $month, $day, $year);
        if( $unixtime < 0 ) 
        {
            return false;
        }
        return $unixtime;
    }
    return true;
}
function valid_datetime($datetime) 
{
    if( strlen($datetime) != 12 ) 
    {
        return false;
    }
    $year = (int) substr($datetime, 0, 4);
    $month = (int) substr($datetime, 4, 2);
    $day = (int) substr($datetime, 6, 2);
    $hour = (int) substr($datetime, 8, 2);
    $minute = (int) substr($datetime, 10, 2);
    if( $year < 0 ) 
    {
        return false;
    }
    if( $month < 0 || 12 < $month ) 
    {
        return false;
    }
    if( $day < 0 || 31 < $day ) 
    {
        return false;
    }
    if( $hour < 0 || 23 < $hour ) 
    {
        return false;
    }
    if( $minute < 0 || 59 < $minute ) 
    {
        return false;
    }
    if( mktime($hour, $minute, 0, $month, $day, $year) < 0 ) 
    {
        return false;
    }
    return true;
}
function datetime_to_time($datetime) 
{
    if( strlen($datetime) != 12 ) 
    {
        return false;
    }
    $year = (int) substr($datetime, 0, 4);
    $month = (int) substr($datetime, 4, 2);
    $day = (int) substr($datetime, 6, 2);
    $hour = (int) substr($datetime, 8, 2);
    $minute = (int) substr($datetime, 10, 2);
    return mktime($hour, $minute, 0, $month, $day, $year);
}
function proxmox_api_call() 
{
    global $globals;
    global $error;
    global $pve2;
    if( is_object($pve2) ) 
    {
        return $pve2;
    }
    require_once($globals["mainfiles"] . "/classes/pve2_api.class.php");
    if( !empty($globals["proxmox_server_pass"]) ) 
    {
        $proxmox_server_pass = (!empty($globals["proxmox_server_pass_salt"]) ? pass_decrypt($globals["proxmox_server_pass"], $globals["proxmox_server_pass_salt"]) : $globals["proxmox_server_pass"]);
        $pve2 = new PVE2_API("127.0.0.1", "root", "pam", $proxmox_server_pass);
        if( $pve2->login() ) 
        {
            return $pve2;
        }
        $error[] = "Api call failed";
        return false;
    }
    $error[] = "Server Password validation failed";
    return false;
}
function proxmox_post_call($action, $path, $post = array( )) 
{
    global $globals;
    global $error;
    global $pve2;
    proxmox_api_call();
    $first_node = get_proxmox_node($globals["proxmox_server_name"]);
    return $pve2->post("/" . $action . "/" . $first_node . $path, $post);
}
function proxmox_put_call($action, $path, $put = array( )) 
{
    global $globals;
    global $error;
    global $pve2;
    proxmox_api_call();
    $first_node = get_proxmox_node($globals["proxmox_server_name"]);
    return $pve2->put("/" . $action . "/" . $first_node . $path, $put);
}
function proxmox_del_call($action, $path, $post = array( )) 
{
    global $globals;
    global $error;
    global $pve2;
    proxmox_api_call();
    $first_node = get_proxmox_node($globals["proxmox_server_name"]);
    return $pve2->delete("/" . $action . "/" . $first_node . $path);
}
function proxmox_get_call($action, $path) 
{
    global $globals;
    global $error;
    global $pve2;
    proxmox_api_call();
    $first_node = get_proxmox_node($globals["proxmox_server_name"]);
    return $pve2->get("/" . $action . "/" . $first_node . $path);
}
function get_proxmox_node($proxserver_name) 
{
    global $globals;
    global $error;
    global $pve2;
    global $first_node;
    if( !is_object($pve2) ) 
    {
        proxmox_api_call();
    }
    if( !empty($first_node) ) 
    {
        return $first_node;
    }
    if( !empty($error) ) 
    {
        return false;
    }
    $node_info = $pve2->get("/nodes");
    if( is_array($node_info) ) 
    {
        foreach( $node_info as $k => $v ) 
        {
            $server_name = $node_info[$k]["node"];
            $server_info[$server_name] = $v;
            $server_info_key[$server_name] = $v["node"];
        }
    }
    if( array_key_exists($proxserver_name, $server_info) ) 
    {
        $first_node = array_search($proxserver_name, $server_info_key);
        return $first_node;
    }
}
function get_proxmox_storage() 
{
    global $globals;
    global $error;
    global $pve2;
    global $first_node;
    if( !is_object($pve2) ) 
    {
        proxmox_api_call();
    }
    if( !empty($error) ) 
    {
        return false;
    }
    $storage_info = $pve2->get("/storage");
    if( is_array($storage_info) ) 
    {
        foreach( $storage_info as $k => $v ) 
        {
            $storage_name = $storage_info[$k]["storage"];
            $storage_details[$storage_name] = $v;
        }
    }
    return $storage_details;
}
function put_proxmox_storage($storage_data) 
{
    global $globals;
    global $error;
    global $pve2;
    global $first_node;
    if( !is_object($pve2) ) 
    {
        proxmox_api_call();
    }
    if( !empty($storage_data) ) 
    {
        if( $storage_data["type"] == "file" ) 
        {
            $pve2->post("/storage", array( "storage" => $storage_data["name"], "type" => "dir", "path" => $storage_data["path"], "content" => "images,rootdir" ));
            sleep(2);
            return NULL;
        }
        if( $storage_data["type"] == "block" ) 
        {
            $vg_name = explode("/", $storage_data["path"]);
            $pve2->post("/storage", array( "storage" => $storage_data["name"], "type" => "lvm", "vgname" => $vg_name[2], "content" => "images,rootdir" ));
            sleep(2);
            return NULL;
        }
        if( preg_match("/zfs/is", $storage_data["type"]) ) 
        {
            $zfspool = $disk_path = str_replace("/dev/zvol/", "", $storage_data["path"]);
            $pve2->post("/storage", array( "storage" => $storage_data["name"], "type" => "zfspool", "pool" => $zfspool, "content" => "images,rootdir" ));
            sleep(2);
            return NULL;
        }
        if( preg_match("/thin/is", $storage_data["type"]) ) 
        {
            $thin_pool = explode("/", $storage_data["path"]);
            $pve2->post("/storage", array( "storage" => $storage_data["name"], "type" => "lvmthin", "thinpool" => $thin_pool[3], "vgname" => $thin_pool[2], "content" => "images,rootdir" ));
            sleep(2);
        }
    }
}
function del_proxmox_storage($storage_name) 
{
    global $globals;
    global $error;
    global $pve2;
    global $first_node;
    if( !is_object($pve2) ) 
    {
        proxmox_api_call();
    }
    if( !empty($storage_name) ) 
    {
        $pve2->delete("/storage/" . $storage_name);
        sleep(2);
    }
}
function callback_api_call($vpsid, $act, $data = array( )) 
{
    global $globals;
    if( empty($act) || empty($globals["cb_hash"]) || empty($globals["cb_url"]) ) 
    {
        return false;
    }
    $post["hash"] = $globals["cb_hash"];
    $post["act"] = $act;
    $post["vpsid"] = (int) $vpsid;
    $url = ((empty($globals["cb_use_https"]) ? "http://" : "https://")) . $globals["cb_url"];
    if( !empty($data) ) 
    {
        $post["data"] = base64_encode(serialize($data));
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (!empty($GLOBALS["globals"]["curl_timeout"]) ? $GLOBALS["globals"]["curl_timeout"] : 3));
    curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, "Softaculous");
    if( !empty($post) ) 
    {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $resp = curl_exec($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);
    if( empty($resp) ) 
    {
        return false;
    }
    return trim($resp);
}
function emaillog($msg, $debug_level) 
{
    global $globals;
    if( !empty($globals["mail_debug"]) ) 
    {
        file_put_contents(logdir("email") . "email.log", "[" . datify(time(), 0, 1, "Y-m-d H:i:s") . "] " . $msg . "\n");
    }
}
function generate_email_otp($user) 
{
    global $globals;
    global $l;
    global $error;
    $otp = rand(100000, 999999);
    $user["uid"] = (empty($user["uid"]) ? "0" : $user["uid"]);
    $res = makequery("INSERT INTO user_meta\tSET \n\t\t\t\t\tuid = :uid,\n\t\t\t\t\tmeta_value = :meta_value,\n\t\t\t\t\tmeta_key = :meta_key\n\t\t\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\t\t\tuid = :uid,\n\t\t\t\t\t\tmeta_value = :meta_value,\n\t\t\t\t\t\tmeta_key = :meta_key", array( ":uid" => $user["uid"], ":meta_value" => $otp, ":meta_key" => "valid_otp" ));
    $res = makequery("INSERT INTO user_meta\tSET \n\t\t\t\t\tuid = :uid,\n\t\t\t\t\tmeta_value = :meta_value,\n\t\t\t\t\tmeta_key = :meta_key\n\t\t\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\t\t\tuid = :uid,\n\t\t\t\t\t\tmeta_value = :meta_value,\n\t\t\t\t\t\tmeta_key = :meta_key", array( ":uid" => $user["uid"], ":meta_value" => time() + 900, ":meta_key" => "email_otp_expiry" ));
    if( empty($error) ) 
    {
        return $otp;
    }
    return false;
}
function os_check($distro = "", $operator = "", $version = "", $value = true) 
{
    global $error;
    global $globals;
    global $kernel;
    global $servers;
    global $cluster;
    $os_name = $servers[0]["os"];
    $distro = strtolower($distro);
    if( $distro == "centos" || $distro == "sl" ) 
    {
        $distro = "rhel";
    }
    if( $distro == "debian" ) 
    {
        $distro = "ubuntu";
    }
    $matched = os_distro_check($distro);
    if( !$matched ) 
    {
        return false;
    }
    if( empty($operator) ) 
    {
        return $value;
    }
    if( $distro == "rhel" || $distro == "xcp" ) 
    {
        $tmp = preg_split("/release/is", $os_name);
        $os_version = trim(substr(trim($tmp[1]), 0, 5));
        if( version_compare($os_version, $version, $operator) ) 
        {
            return $value;
        }
        return false;
    }
    if( $distro == "ubuntu" ) 
    {
        $tmp = explode(" ", $os_name);
        $os_version = trim($tmp[1]);
        if( version_compare($os_version, $version, $operator) ) 
        {
            return $value;
        }
        return false;
    }
    return false;
}
function os_distro_check($distro = "", $value = true) 
{
    global $error;
    global $globals;
    global $kernel;
    global $servers;
    $os_name = $servers[0]["os"];
    $distro = strtolower($distro);
    if( $distro == "centos" || $distro == "sl" ) 
    {
        $distro = "rhel";
    }
    if( $distro == "debian" ) 
    {
        $distro = "ubuntu";
    }
    if( $distro == "rhel" ) 
    {
        if( preg_match("/centos|Red Hat|Scientific/is", $os_name) ) 
        {
            return $value;
        }
        return false;
    }
    if( $distro == "xcp" ) 
    {
        if( preg_match("/xenserver/is", $os_name) ) 
        {
            return $value;
        }
        return false;
    }
    if( $distro == "ubuntu" ) 
    {
        if( preg_match("/ubuntu|debian/is", $os_name) ) 
        {
            return $value;
        }
        return false;
    }
    return false;
}
function lockvps($vpsid, $reason = "") 
{
    $res = makequery("UPDATE `vps`\n\t\t\t\t\tSET locked = :locked\n\t\t\t\t\tWHERE vpsid = :vpsid", array( ":locked" => serialize(array( "time" => time(), "reason" => $reason )), ":vpsid" => $vpsid ));
    if( !$res ) 
    {
        return false;
    }
    return true;
}
function unlockvps($vpsid) 
{
    $res = makequery("UPDATE `vps`\n\t\t\t\t\tSET locked = ''\n\t\t\t\t\tWHERE vpsid = :vpsid", array( ":vpsid" => $vpsid ));
    if( !$res ) 
    {
        return false;
    }
    return true;
}
function validate_speed_cap($speed_cap_down, $speed_cap_up, $network_speed, $upload_speed) 
{
    global $l;
    global $error;
    if( $speed_cap_down < 0 || !empty($network_speed) && $network_speed < $speed_cap_down ) 
    {
        $error["speed_cap_down"] = $l["speed_cap_down_inv"] . ": " . $speed_cap_down;
    }
    if( $speed_cap_up < 0 || $upload_speed < 0 && 0 < $network_speed && $network_speed < $speed_cap_up || 0 < $upload_speed && $upload_speed < $speed_cap_up ) 
    {
        $error["speed_cap_up"] = $l["speed_cap_up_inv"] . ": " . $speed_cap_up;
    }
    return $error;
}
function validate_ports_list($ports_list, $all_ports = "", $not_in = 0) 
{
    global $error;
    unset($error["validate_ports_list"]);
    if( empty($ports_list) ) 
    {
        return $ports_list;
    }
    $err_ports = array( );
    $in_all_ports = array( );
    $not_in_all_ports = array( );
    $tmp = preg_split("/\\s*\\,\\s*/", trim($ports_list));
    $found = false;
    if( !empty($all_ports) ) 
    {
        $all_ports = preg_split("/\\s*\\,\\s*/", trim($all_ports));
    }
    $returnportlist = "";
    foreach( $tmp as $k => $v ) 
    {
        $tmp_v = array( );
        if( preg_match("/\\s*\\-\\s*/", $v) ) 
        {
            $vtmp = preg_split("/\\s*\\-\\s*/", $v);
            if( $vtmp[1] < $vtmp[0] ) 
            {
                $err_ports[] = $vtmp[0] . "-" . $vtmp[1];
                continue;
            }
            $tmp_v[] = trim($vtmp[0]);
            $tmp_v[] = trim($vtmp[1]);
        }
        else 
        {
            $tmp_v[] = $v;
        }
        $returnportlist .= $v . ",";
        foreach( $tmp_v as $m => $n ) 
        {
            if( !preg_match("/^\\d{1,5}\$/", $n) || $n <= 0 || pow(2, 16) <= $n ) 
            {
                $err_ports[] = $n;
            }
            if( is_array($all_ports) ) 
            {
                foreach( $all_ports as $x => $y ) 
                {
                    $found = false;
                    if( preg_match("/\\s*\\-\\s*/", $y) ) 
                    {
                        $ytmp = preg_split("/\\s*\\-\\s*/", $y);
                        if( $ytmp[1] < $ytmp[0] ) 
                        {
                            $err_ports[] = $ytmp[0] . "-" . $ytmp[1];
                            continue;
                        }
                        if( $ytmp[0] <= $n && $n <= $ytmp[1] ) 
                        {
                            $found = true;
                        }
                    }
                    else 
                    {
                        if( $n == $y ) 
                        {
                            $found = true;
                        }
                    }
                    if( $found ) 
                    {
                        break;
                    }
                }
            }
            if( $found == true ) 
            {
                $in_all_ports[] = $n;
            }
            else 
            {
                $not_in_all_ports[] = $n;
            }
        }
    }
    if( !empty($all_ports) ) 
    {
        if( !empty($in_all_ports) && empty($not_in) ) 
        {
            $error["validate_ports_list"] = $in_all_ports;
            return false;
        }
        if( !empty($not_in_all_ports) && !empty($not_in) ) 
        {
            $error["validate_ports_list"] = $not_in_all_ports;
            return false;
        }
    }
    else 
    {
        if( !empty($err_ports) ) 
        {
            $error["validate_ports_list"] = $err_ports;
            return false;
        }
    }
    return trim($returnportlist, ",");
}
function vdf_no_duplicates($new, $serid) 
{
    $res = makequery("SELECT *\n\t\t\t\t\tFROM haproxy\n\t\t\t\t\tWHERE serid=:serid AND src_hostname=:src_hostname AND src_port=:src_port", array( ":serid" => $serid, ":src_hostname" => $new["src_hostname"], "src_port" => $new["src_port"] ));
    if( 0 < vsql_num_rows($res) ) 
    {
        return false;
    }
    return true;
}
function log_message($path, $msg, $echo = 0) 
{
    global $globals;
    $msg = "[" . gmdate("D M d, Y H:i:s T", time()) . "] " . $msg . "\n";
    if( $echo == 1 ) 
    {
        echo $msg;
    }
    file_put_contents($path, $msg, FILE_APPEND);
}
function save_haproxy() 
{
    global $globals;
    $empty_config = 0;
    $haconftemplate = "/usr/local/virtualizor/conf/haproxy_template.dat";
    $haproxybin = "/usr/sbin/haproxy";
    $haproxycfg = "/etc/haproxy/haproxy.cfg";
    $iptablescfg = (os_distro_check("debian", 1) ? "/etc/iptables/rules.v4" : "/etc/sysconfig/iptables");
    $virt_halog_path = logdir("haproxy") . "/haproxy.log";
    if( !empty($globals["haproxy_enable"]) ) 
    {
        $actid = tasks_admin_process("haproxy_cron", array( ));
        task_start($actid);
        task_update($actid, "Checking if HAProxy binary installed or not", 5);
        if( !file_exists($haproxybin) ) 
        {
            $msg = "Installing HAProxy, as HAProxy binary not found";
            task_update($actid, $msg, 10);
            log_message($virt_halog_path, $msg);
            log_message(logdir("haproxy") . "haproxyinstall.log", $msg);
            $install_bin = (distro_check(0, 0, 1) ? "apt-get" : "yum");
            vexec($install_bin . " -y install haproxy 2>&1 >> " . logdir("haproxy") . "haproxyinstall.log", $o, $r);
            if( $r != 0 ) 
            {
                $msg = "Failed to install haproxy\nError: " . print_r($o, 1);
                task_update($actid, $msg, -1);
                log_message($virt_halog_path, $msg);
                log_message(logdir("haproxy") . "haproxyinstall.log", $msg);
                return false;
            }
            $msg = "HAProxy binary installed";
            log_message($virt_halog_path, $msg);
            log_message(logdir("haproxy") . "haproxyinstall.log", $msg);
            task_update($actid, $msg, 45);
            $msg = "Enabling TPROXY kernel module";
            log_message($virt_halog_path, $msg);
            vexec("modprobe xt_TPROXY 2>&1 >> " . logdir("haproxy") . "haproxyinstall.log", $o, $r);
            if( $r != 0 ) 
            {
                $msg = "Failed to enable TPROXY kernel module\nError: " . print_r($o, 1);
                task_update($actid, $msg, -1);
                log_message($virt_halog_path, $msg);
                return false;
            }
            $msg = "TPROXY kernel module enabled";
            log_message($virt_halog_path, $msg);
            $msg = "Adding IPtables Mangle Rules";
            log_message($virt_halog_path, $msg);
            $mangle_rules_reload = "ip route del local 0.0.0.0/0 dev lo table 100;\nip rule del fwmark 111 lookup 100;\niptables -t mangle -D DIVERT -j ACCEPT;\niptables -t mangle -D DIVERT -j MARK --set-mark 111;\niptables -t mangle -D PREROUTING -p tcp -m socket -j DIVERT;\niptables -t mangle -X DIVERT;\n\niptables -t mangle -N DIVERT;\niptables -t mangle -A PREROUTING -p tcp -m socket -j DIVERT;\niptables -t mangle -A DIVERT -j MARK --set-mark 111;\niptables -t mangle -A DIVERT -j ACCEPT;\nip rule add fwmark 111 lookup 100;\nip route add local 0.0.0.0/0 dev lo table 100;";
            vexec($mangle_rules_reload, $o, $r);
            if( $r != 0 ) 
            {
                $msg = "Failed to add mangle rules for transparent proxy\nError:\n" . print_r($o, 1);
                task_update($actid, $msg, -1);
                log_message($virt_halog_path, $msg);
                return false;
            }
            $msg = "Added mangle rules and route entry";
            log_message($virt_halog_path, $msg);
            $msg = "Adding MASQUERADE rules for transparent proxy";
            log_message($virt_halog_path, $msg);
            $interface = (!empty($globals["interface"]) ? $globals["interface"] : "eth0");
            if( server_virt(0, "xen") == "xen" || server_virt(0, "kvm") == "kvm" ) 
            {
                $interface = "viifbr0";
            }
            if( server_virt(0, "xcp") == "xcp" ) 
            {
                $interface = "xenbr0";
            }
            $masquerade_reload = "iptables -t nat -D POSTROUTING -o " . $interface . " -j MASQUERADE; iptables -t nat -A POSTROUTING -o " . $interface . " -j MASQUERADE";
            vexec($masquerade_reload, $o, $r);
            if( $r ) 
            {
                $msg = "Failed to add MASQUERADE rules for transparent proxy\nError:\n" . print_r($o, 1);
                task_update($actid, $msg, -1);
                log_message($virt_halog_path, $msg);
                return false;
            }
            vexec("iptables-save > " . $iptablescfg, $o, $r);
            if( $r ) 
            {
                $msg = "Failed to save iptables rules\nErrors:\n" . print_r($o, 1);
                log_message($virt_halog_path, $msg);
            }
            else 
            {
                $msg = "Saved iptables rules";
                log_message($virt_halog_path, $msg);
            }
            $msg = "Added MASQUERADE rules";
            log_message($virt_halog_path, $msg);
            chkconfig("haproxy", 99);
            $msg = "Enabling HAProxy logging in rsyslod";
            log_message($virt_halog_path, $msg);
            $logconf = "/etc/rsyslog.d/haproxylogs.conf";
            $content = "\$ModLoad imudp\n\$UDPServerRun 514\nlocal2.*" . "\t" . "/var/log/haproxy.log";
            if( !file_put_contents($logconf, $content) ) 
            {
                $msg = "Failed to write log configuration to file " . $logconf . "\n";
                task_update($actid, $msg, -1);
                log_message($virt_halog_path, $msg);
                return false;
            }
            $msg = "Wrote the log configuration, restarting rsyslog service" . $logconf;
            log_message($virt_halog_path, $msg);
            vexec("service rsyslog restart", $o, $r);
            if( $r != 0 ) 
            {
                $msg = "Failed to restart rsyslog service\nErrors:\n" . print_r($o, 1);
                task_update($actid, $msg, 46);
                log_message($virt_halog_path, $msg);
            }
            $msg = "Restarted rsyslog service";
            log_message($virt_halog_path, $msg);
            $msg = "HAProxy installation completed";
            log_message($virt_halog_path, $msg);
        }
        else 
        {
            $msg = "HAProxy already installed";
            task_update($actid, $msg, 46);
            log_message($virt_halog_path, $msg);
        }
        $msg = "Rebuilding HAProxy configuration";
        task_update($actid, $msg, 50);
        log_message($virt_halog_path, $msg);
        $res = makequery("select * from haproxy where serid = 0");
        $vdfdata = array( );
        $srcports = array( );
        if( 0 < vsql_num_rows($res) ) 
        {
            for( $i = 1; $i <= vsql_num_rows($res);
            $i++ ) 
            {
                $row = vsql_fetch_assoc($res);
                $distinct_src_ports[$row["src_port"]] = $row["src_port"];
                $vdfdata[$row["id"]] = $row;
            }
            $frontend_str = "frontend mainfrontend\nmode tcp\noption tcplog" . "\n";
            $backend_common_str = "mode tcp\noption tcplog\nsource 0.0.0.0 usesrc clientip\nserver server_";
            $backends_str = "";
            $bind_ports = array( );
            $front_use_backendlist = array( );
            $backends = array( );
            $tc_req_acpt = array( );
            $acl_host = array( );
            $acl_port = array( );
            $skipped_rec = array( );
            $remove_skipped_rec_entry = array( );
            $server_config = get_slave_settings(0);
            $server_public_ip = server_publicip(0);
            $server_src_ips = (empty($globals["haproxy_src_ips"]) ? array( $server_public_ip ) : preg_split("/\\s*\\,\\s*/", trim($globals["haproxy_src_ips"])));
            if( !empty($globals["le_primary_domain"]) && !empty($globals["le_verify"]) ) 
            {
                $vdfdata["local80"] = array( "id" => "local80", "vpsuuid" => -1, "serid" => 0, "protocol" => "HTTP", "src_hostname" => $globals["le_primary_domain"], "src_port" => 80, "dest_ip" => "127.0.0.1", "dest_port" => 4082 );
            }
            foreach( $vdfdata as $k => $v ) 
            {
                $skipped_rec[$k] = array( );
                if( $v["protocol"] == "TCP" ) 
                {
                    if( !in_array($v["src_hostname"], $server_src_ips) ) 
                    {
                        $skipped_rec[$k]["haproxy_src_ips"] = 1;
                    }
                    if( !validate_ports_list($v["src_port"], $server_config["haproxy_reservedports_http"]) ) 
                    {
                        $skipped_rec[$k]["haproxy_reservedports_http"] = 1;
                    }
                }
                if( !validate_ports_list($v["src_port"], $server_config["haproxy_allowedports"], 1) ) 
                {
                    $skipped_rec[$k]["haproxy_allowedports"] = 1;
                }
                if( !validate_ports_list($v["src_port"], $server_config["haproxy_reservedports"]) ) 
                {
                    $skipped_rec[$k]["haproxy_reservedports"] = 1;
                }
                if( !empty($skipped_rec[$k]) ) 
                {
                    continue;
                }
                $name = $v["dest_ip"] . "_" . $v["dest_port"];
                $backend_server = $v["dest_ip"] . ":" . $v["dest_port"];
                $acl_port["acl_p_" . $v["src_port"]] = "dst_port " . $v["src_port"];
                $use_backend_priority = ($v["src_port"] != $v["dest_port"] ? ($v["protocol"] != "TCP" ? 0 : 1) : ($v["protocol"] != "TCP" ? 2 : 3));
                $backend_name = "backend_" . $name;
                if( $v["protocol"] == "HTTP" || $v["protocol"] == "HTTPS" ) 
                {
                    foreach( $server_src_ips as $kk => $vv ) 
                    {
                        $bind_ports[$vv][$v["src_port"]] = "bind " . $vv . ":" . $v["src_port"];
                    }
                    $act_http_check = "hdr(Host)";
                    $acl_host["acl_h_" . $v["src_hostname"]] = $act_http_check . " -i -m reg ^" . $v["src_hostname"];
                    $tc_req_acpt["acl_h_" . $v["src_hostname"]] = "tcp-request content accept if acl_h_" . $v["src_hostname"];
                    $front_use_backendlist[$use_backend_priority][$v["src_hostname"] . "_" . $v["src_port"]] = "use_backend " . $backend_name . " if acl_h_" . $v["src_hostname"] . " acl_p_" . $v["src_port"];
                    if( $v["protocol"] == "HTTPS" ) 
                    {
                        $act_http_check = "req_ssl_sni";
                        $acl_host["acl_hs_" . $v["src_hostname"]] = $act_http_check . " -i -m reg ^" . $v["src_hostname"] . "(:\\d+)*";
                        $tc_req_acpt["acl_hs_" . $v["src_hostname"]] = "tcp-request content accept if { req_ssl_hello_type 1 } acl_hs_" . $v["src_hostname"];
                        $front_use_backendlist[$use_backend_priority][$v["src_hostname"] . "_" . $v["src_port"]] .= "\n\t" . "use_backend " . $backend_name . " if acl_hs_" . $v["src_hostname"] . " acl_p_" . $v["src_port"];
                    }
                }
                else 
                {
                    if( $v["protocol"] == "TCP" ) 
                    {
                        $bind_ports[$v["src_hostname"]][$v["src_port"]] = "bind " . $v["src_hostname"] . ":" . $v["src_port"];
                        $front_use_backendlist[$use_backend_priority][$v["src_hostname"] . "_" . $v["src_port"]] = "use_backend " . $backend_name . " if { dst " . $v["src_hostname"] . " } acl_p_" . $v["src_port"];
                    }
                }
                $backends[$backend_name] = "backend " . $backend_name . "\n" . $backend_common_str . $name . " " . $backend_server . "\n";
                if( $v["vpsuuid"] == -1 ) 
                {
                    $backends[$backend_name] = preg_replace("/(\\nsource.+clientip)/", "", $backends[$backend_name]);
                }
            }
            if( !empty($skipped_rec) ) 
            {
                $query = "";
                foreach( $skipped_rec as $k => $v ) 
                {
                    $query .= "UPDATE haproxy SET skipped='" . ((!empty($v) ? serialize($v) : "")) . "' WHERE id='" . $k . "';";
                }
                makequery($query);
            }
            foreach( $bind_ports as $k => $v ) 
            {
                foreach( $v as $kk => $vv ) 
                {
                    $frontend_str .= "\t" . $vv . "\n";
                }
            }
            $frontend_str .= "\n";
            foreach( $acl_host as $k => $v ) 
            {
                $frontend_str .= "\t" . "acl " . $k . " " . $v . "\n";
            }
            $frontend_str .= "\n";
            foreach( $acl_port as $k => $v ) 
            {
                $frontend_str .= "\t" . "acl " . $k . " " . $v . "\n";
            }
            $frontend_str .= "\n\ttcp-request inspect-delay\t100ms" . "\n";
            foreach( $tc_req_acpt as $k => $v ) 
            {
                $frontend_str .= "\t" . $v . "\n";
            }
            $frontend_str .= "\n";
            for( $i = 0; $i < 4; $i++ ) 
            {
                if( !empty($front_use_backendlist[$i]) ) 
                {
                    foreach( $front_use_backendlist[$i] as $k => $v ) 
                    {
                        $frontend_str .= "\t" . $v . "\n";
                    }
                }
            }
            $frontend_str .= "\n";
            foreach( $backends as $k => $v ) 
            {
                $backends_str .= $v . "\n";
            }
            $maincfg = file_get_contents($haconftemplate);
            if( empty($maincfg) ) 
            {
                $msg = "Initial HAProxy configuration template empty, exiting";
                task_update($actid, $msg, -1);
                log_message($virt_halog_path, $msg);
                return false;
            }
            $maincfg .= "\n" . $frontend_str . $backends_str;
            writefile($haproxycfg, $maincfg, 1, 384);
            $msg = "Configuration saved";
            log_message($virt_halog_path, $msg);
            vexec("service haproxy status 2>&1", $o, $r);
            if( $r != 0 ) 
            {
                $msg = "HAProxy service not running, starting HAProxy service";
                log_message($virt_halog_path, $msg);
                vexec("service haproxy start 2>&1 && service haproxy status", $o, $r);
                if( $r != 0 ) 
                {
                    $msg = "Failed to start HAProxy service";
                    task_update($actid, $msg, -1);
                    log_message($virt_halog_path, $msg . "\n" . print_r($o, 1));
                    return false;
                }
                $msg = "Started HAProxy service successfuly";
                log_message($virt_halog_path, $msg);
            }
            else 
            {
                $msg = "Reloading HAProxy service";
                log_message($virt_halog_path, $msg);
                vexec("service haproxy reload 2>&1 && service haproxy status", $o, $r);
                if( $r != 0 ) 
                {
                    $msg = "Failed to reload HAProxy service";
                    task_update($actid, $msg, -1);
                    log_message($virt_halog_path, $msg . "\n" . print_r($o, 1));
                    return false;
                }
                $msg = "Reloaded HAProxy service successfuly";
                log_message($virt_halog_path, $msg);
            }
            if( !empty($globals["le_primary_domain"]) ) 
            {
                $globals["le_haproxy"] = 1;
            }
        }
        else 
        {
            $empty_config = 1;
            $msg = "No HAProxy rules found to build";
            task_update($actid, $msg, 80);
            log_message($virt_halog_path, $msg);
        }
    }
    else 
    {
        $msg = "HAProxy not enabled";
        log_message($virt_halog_path, $msg);
        $globals["le_haproxy"] = 0;
    }
    if( empty($globals["haproxy_enable"]) || $empty_config == 1 ) 
    {
        if( file_exists($haproxybin) ) 
        {
            log_message($virt_halog_path, "Stopping");
            vexec("service haproxy status", $o, $r);
            if( $r == 0 ) 
            {
                $msg = "Stopping HAProxy service";
                log_message($virt_halog_path, $msg);
                vexec("service haproxy stop", $o, $r);
                if( $r != 0 ) 
                {
                    $msg = "Failed to stop HAProxy service";
                    log_message($virt_halog_path, $msg);
                    return false;
                }
                $msg = "Stopped HAProxy service successfuly";
                log_message($virt_halog_path, $msg);
                task_update($actid, $msg, 90);
            }
            else 
            {
                $msg = "HAProxy service already stopped";
                log_message($virt_halog_path, $msg);
            }
        }
        $globals["le_haproxy"] = 0;
    }
    if( !empty($actid) ) 
    {
        task_update($actid, $msg, 100);
    }
    return true;
}
function reinit_haproxy() 
{
    global $globals;
    $mangle_rules_reload = "ip route del local 0.0.0.0/0 dev lo table 100;\nip rule del fwmark 111 lookup 100;";
    if( !empty($globals["haproxy_enable"]) ) 
    {
        $mangle_rules_reload .= "\nip rule add fwmark 111 lookup 100;\nip route add local 0.0.0.0/0 dev lo table 100";
    }
    vexec($mangle_rules_reload, $o, $r);
}
function is_valid_backup_folder($folder) 
{
    if( strlen($folder) == 8 && strtotime($folder) <= time() && 0 < strtotime($folder) ) 
    {
        $temp_date = (int) substr($folder, 6, 2);
        $temp_mon = (int) substr($folder, 4, 2);
        $temp_yr = (int) substr($folder, 0, 4);
        if( 0 < $temp_date && $temp_date < 32 && 0 < $temp_mon && $temp_mon < 13 && 2010 <= $temp_yr ) 
        {
            return true;
        }
    }
    return false;
}
function get_backup_plan($vpsid) 
{
    $res = makequery("SELECT bp.* FROM vps v\n\t\t\t\t\t\tLEFT JOIN plans p ON p.plid = v.plid\n\t\t\t\t\t\tINNER JOIN backup_plans bp ON (bp.bpid = v.bpid OR (v.bpid = -1 AND bp.bpid = p.bpid))\n\t\t\t\t\t\tWHERE v.vpsid = :vpsid", array( ":vpsid" => $vpsid ));
    if( vsql_num_rows($res) == 0 ) 
    {
        return false;
    }
    $row = vsql_fetch_assoc($res);
    return $row;
}
function get_backup_extensions($virt = "") 
{
    $extensions = array( "kvm" => array( "img", "img.gz" ), "xen" => array( "img", "img.gz", "tar.gz" ), "xcp" => array( "img", "img.gz" ), "openvz" => array( "tar.gz", "tar" ), "lxc" => array( "tar.gz" ), "proxk" => array( "vma.gz", "vma.lzo", "vma" ), "proxl" => array( "tar.gz", "tar.lzo", "tar" ), "proxo" => array( "tar.gz", "tar.lzo", "tar" ), "vzk" => array( "tar.gz", "tar" ), "vzo" => array( "tar.gz", "tar" ) );
    if( !empty($virt) ) 
    {
        return $extensions[$virt];
    }
    return $extensions;
}
function iso_path($uid, $uuid, &$type = "isos") 
{
    global $globals;
    global $isos;
    $isopath = "";
    if( empty($isos) ) 
    {
        useriso($uid);
    }
    foreach( $isos as $isok => $iso ) 
    {
        if( $isok == $uuid ) 
        {
            $filename = $isos[$isok]["filename"];
            if( $isos[$isok]["isuseriso"] ) 
            {
                $isopath = $uid . "/" . $uuid . ".iso";
                $type = "euisos";
                $path_info = pathinfo($isopath);
                if( !is_dir($globals[$type] . "/" . $path_info["dirname"]) ) 
                {
                    @mkdir($globals[$type] . "/" . $path_info["dirname"]);
                }
            }
            else 
            {
                $isopath = $filename;
                $type = "isos";
            }
            break;
        }
    }
    return $isopath;
}
function addsshkeys($mount_point, $ssh_keys) 
{
    $auth_file = $mount_point . "/root/.ssh/authorized_keys";
    if( !is_safe_file($auth_file) ) 
    {
        return false;
    }
    if( empty($ssh_keys) || !is_array($ssh_keys) ) 
    {
        return false;
    }
    $keys_to_add = "\n" . implode("\n", $ssh_keys);
    if( !is_dir(dirname($auth_file)) && !mkdir(dirname($auth_file)) ) 
    {
        return false;
    }
    $result = file_put_contents($auth_file, $keys_to_add, FILE_APPEND);
    return $result !== false;
}
function get_vps_disk_usage($virt) 
{
    $disk_usage = array( );
    if( !file_exists("/var/virtualizor/dumpe2fs") ) 
    {
        mkdir("/var/virtualizor/dumpe2fs");
    }
    $res = makequery("SELECT vpsid FROM vps\n\t\t\t\t\t\tWHERE serid = :serid\n\t\t\t\t\t\tAND virt = :virt", array( ":serid" => 0, ":virt" => $virt ));
    for( $i = 0; $i < vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $vpsid = $row["vpsid"];
        $disks = get_vps_disks($vpsid);
        $disk_used = 0;
        $disk_free = 0;
        $inode_count = 0;
        $inode_used = 0;
        $inode_free = 0;
        $num_linux_parts = 0;
        foreach( $disks as $disk ) 
        {
            if( preg_match("/block/is", $disk["type"]) ) 
            {
                $diskinfo = diskinfo($disk["path"]);
            }
            if( preg_match("/file/is", $disk["type"]) ) 
            {
                $diskinfo = file_diskinfo($disk["path"]);
            }
            if( empty($diskinfo) || empty($diskinfo["num"]["linux"]) ) 
            {
                continue;
            }
            $num_linux_parts = $diskinfo["num"]["linux"];
            $sector_size = 512;
            foreach( $diskinfo["parts"] as $part ) 
            {
                vexec("dd if=" . xss($disk["path"]) . " of=/var/virtualizor/dumpe2fs/superblock ibs=" . $sector_size . " obs=" . $sector_size . " bs=" . $sector_size . " skip=" . $part["start"] . " count=24 status=none", $out, $ret);
                if( $ret != 0 ) 
                {
                    continue;
                }
                vexec("dumpe2fs -h /var/virtualizor/dumpe2fs/superblock 2> /dev/null", $out, $ret);
                unlink("/var/virtualizor/dumpe2fs/superblock");
                $part_block_size = 0;
                $part_block_count = 0;
                $part_block_free = 0;
                $part_inode_count = 0;
                $part_inode_free = 0;
                foreach( $out as $line ) 
                {
                    $parts = explode(":", $line);
                    $key = trim($parts[0]);
                    $value = trim($parts[1]);
                    if( preg_match("/^Block\\s+size/is", $key) ) 
                    {
                        $part_block_size = (int) $value;
                    }
                    else 
                    {
                        if( preg_match("/^Block\\s+count/is", $key) ) 
                        {
                            $part_block_count = (int) $value;
                        }
                        else 
                        {
                            if( preg_match("/^Free\\s+blocks/is", $key) ) 
                            {
                                $part_block_free = (int) $value;
                            }
                            else 
                            {
                                if( preg_match("/^Inode\\s+count/is", $key) ) 
                                {
                                    $part_inode_count = (int) $value;
                                }
                                else 
                                {
                                    if( preg_match("/^Free\\s+inodes/is", $key) ) 
                                    {
                                        $part_inode_free = (int) $value;
                                    }
                                }
                            }
                        }
                    }
                }
                if( !empty($part_block_size) && !empty($part_block_count) ) 
                {
                    $part_size = $part_block_count * $part_block_size;
                    $part_free = $part_block_free * $part_block_size;
                    $disk_used += $part_size - $part_free;
                    $disk_free += $part_free;
                }
                if( !empty($part_inode_count) ) 
                {
                    $inode_count += $part_inode_count;
                    $inode_free += $part_inode_free;
                    $inode_used += $part_inode_count - $part_inode_free;
                }
            }
        }
        if( empty($num_linux_parts) ) 
        {
            continue;
        }
        $disk_size = $disk_used + $disk_free;
        $disk_usage[$vpsid] = array( "disk" => array( "Used" => $disk_used / 1024, "Available" => $disk_free / 1024, "Use%" => (empty($disk_size) ? 0 : round($disk_used / $disk_size * 100, 2)) ), "inode" => array( "Inodes" => $inode_count, "IUsed" => $inode_used, "IFree" => $inode_free, "Use%" => (empty($inode_count) ? 0 : round($inode_used / $inode_count * 100, 2)) ) );
    }
    return $disk_usage;
}
function vs_ebtables_remove($vps_name, $vif_name) 
{
    vexec("ebtables -L --Lx | grep " . xss($vps_name), $o, $r);
    $regexp1 = "/\\s-A\\s/";
    foreach( $o as $k => $v ) 
    {
        if( preg_match($regexp1, $v) ) 
        {
            $v = preg_replace($regexp1, " -D ", $v);
            vexec($v);
        }
    }
    $regexp1 = "/\\s-N\\s/";
    foreach( $o as $k => $v ) 
    {
        if( preg_match($regexp1, $v) ) 
        {
            $v = preg_replace($regexp1, " -X ", $v);
            vexec($v);
        }
    }
    return true;
}
function vs_ebtables_add($vid, $vif_name, $mac_addr) 
{
    global $globals;
    global $error;
    $vps = getvps($vid);
    $vps_name = $vps["vps_name"];
    $res = makequery("SELECT i.*, ip.* FROM `ips` i\n\t\t\t\tLEFT JOIN ippool ip ON (ip.ippid = i.ippid) \n\t\t\t\tWHERE i.vpsid = '" . $vps["vpsid"] . "'\n\t\t\t\tORDER BY `primary` DESC");
    for( $i = 0; $i < vsql_num_rows($res);
    $i++ ) 
    {
        $ips[$i] = vsql_fetch_assoc($res);
    }
    vs_ebtables_remove($vps_name, $vif_name);
    $no_ebtables_on_plans_arr = array( );
    if( !empty($globals["no_ebtables_on_plans"]) ) 
    {
        $no_ebtables_on_plans_arr = cexplode(",", $globals["no_ebtables_on_plans"]);
    }
    if( !in_array($vps["plid"], $no_ebtables_on_plans_arr) && empty($vps["disable_ebtables"]) ) 
    {
        if( !empty($ips[0]) ) 
        {
            vexec("ebtables -N " . xss("vm" . $vps_name), $output, $return);
            vexec("ebtables -P " . xss("vm" . $vps_name) . " DROP", $output, $return);
            vexec("ebtables -N " . xss("vm" . $vps_name) . "ARPIN", $output, $return);
            vexec("ebtables -A FORWARD -p IPv4 -i " . xss($vif_name) . " -j " . xss("vm" . $vps_name), $output, $return);
            vexec("ebtables -A INPUT -p ARP -i " . xss($vif_name) . " -j " . xss("vm" . $vps_name) . "ARPIN", $output, $return);
            vexec("ebtables -A FORWARD -p ARP -i " . xss($vif_name) . " -j " . xss("vm" . $vps_name) . "ARPIN", $output, $return);
            foreach( $ips as $k => $v ) 
            {
                if( !empty($v["ipv6"]) ) 
                {
                    continue;
                }
                vexec("ebtables -A " . xss("vm" . $vps_name) . " -p " . ((empty($v["ipv6"]) ? "IPv4" : "IPv6")) . " --ip" . ((empty($v["ipv6"]) ? "" : "6")) . "-src " . xss($v["ip"] . ((empty($v["ipr_netmask"]) ? "" : "/" . $v["ipr_netmask"]))) . " -s " . xss($mac_addr) . " -j ACCEPT", $output, $return);
                vexec("ebtables -A " . xss("vm" . $vps_name) . "ARPIN -p ARP --arp-ip-src " . xss($v["ip"] . ((empty($v["ipr_netmask"]) ? "" : "/" . $v["ipr_netmask"]))) . " --arp-mac-src " . xss($mac_addr) . " -j ACCEPT", $output, $return);
            }
            vexec("ebtables -A " . xss("vm" . $vps_name) . "ARPIN -p ARP -j DROP", $output, $return);
        }
        ebtables_save();
    }
}
function vs_get_net_speed($vid, $force_limit = 0) 
{
    global $globals;
    global $error;
    $vps = getvps($vid, 0);
    if( !is_array($vps) ) 
    {
        $error = "empty_vid";
        return false;
    }
    $download_limit = (int) (($vps["network_speed"] * 8) / 1024);
    $upload_limit = (int) (((($vps["upload_speed"] == -1 ? $vps["network_speed"] : $vps["upload_speed"])) * 8) / 1024);
    if( !empty($vps["speed_cap"]) && $vps["bandwidth"] < $vps["speed_cap"]["bw"] && (0 < $vps["speed_cap"]["down"] || 0 < $vps["speed_cap"]["up"]) && empty($globals["speed_cap_disable"]) ) 
    {
        $download_limit = (int) (($vps["speed_cap"]["down"] * 8) / 1024);
        $upload_limit = (int) (((($vps["upload_speed"] == -1 ? $vps["speed_cap"]["down"] : $vps["speed_cap"]["up"])) * 8) / 1024);
    }
    if( !empty($force_limit) && empty($download_limit) ) 
    {
        $download_limit = 10000;
    }
    if( !empty($force_limit) && empty($upload_limit) ) 
    {
        $upload_limit = 10000;
    }
    return array( "down" => $download_limit, "up" => $upload_limit );
}
function vs_tc_create($vid, $interface, $force_limit = 0) 
{
    global $globals;
    global $error;
    vexec("ip a | grep " . xss(": " . $interface), $o, $r);
    if( empty($interface) || !empty($r) ) 
    {
        return false;
    }
    unset($o);
    unset($r);
    $ret = vs_get_net_speed($vid, $force_limit);
    $download_limit = $ret["down"];
    $upload_limit = $ret["up"];
    $interface_speed = "100mbit";
    if( 1000 < $download_limit || 1000 < $upload_limit ) 
    {
        $interface_speed = "10000mbit";
    }
    else 
    {
        if( 100 < $download_limit || 100 < $upload_limit ) 
        {
            $interface_speed = "1000mbit";
        }
    }
    vs_tc_destroy($interface);
    usleep(500000);
    if( !empty($download_limit) ) 
    {
        vexec("tc qdisc add dev " . xss($interface) . " root handle 1: htb default 10 2>&1");
        vexec("tc class add dev " . xss($interface) . " parent 1: classid 1:1 htb rate " . xss($interface_speed) . " burst 15k 2>&1");
        vexec("tc class add dev " . xss($interface) . " parent 1:1 classid 1:10 htb rate " . xss($download_limit) . "mbit burst 15k 2>&1");
        vexec("tc qdisc add dev " . xss($interface) . " parent 1:10 handle 2: sfq perturb 10 2>&1");
    }
    if( !empty($upload_limit) ) 
    {
        vexec("tc qdisc add dev " . xss($interface) . " ingress 2>&1");
        vexec("tc filter add dev " . xss($interface) . " parent ffff: protocol ip u32 match ip src 0.0.0.0/0 police rate " . xss($upload_limit) . "mbit burst 1000k mtu 64kb drop 2>&1");
        vexec("tc filter add dev " . xss($interface) . " parent ffff: protocol ipv6 u32 match ip6 src 0:0:0:0:0:0:0:0/0 police rate " . xss($upload_limit) . "mbit burst 1000k mtu 64kb drop 2>&1");
    }
    return true;
}
function vs_tc_create_vz($vid, $force_limit = 0) 
{
    global $globals;
    global $error;
    if( file_exists($globals["var"] . "/tc_ovz_old") ) 
    {
        $ret = vs_get_net_speed($vid, $force_limit);
        $download_limit = $ret["down"];
        $upload_limit = $ret["up"];
        if( empty($download_limit) && empty($upload_limit) ) 
        {
            vs_tc_destroy_vz($vid);
            return true;
        }
        $interface = (empty($GLOBALS["globals"]["interface"]) ? "eth0" : $GLOBALS["globals"]["interface"]);
        $ips = array( );
        $classids = array( );
        $res = makequery("SELECT * FROM `ips`\n\t\t\t\t\t\tWHERE vpsid = '" . $vid . "'\t\t\t\t\t\n\t\t\t\t\t\tORDER BY `primary` DESC");
        for( $i = 0; $i < vsql_num_rows($res);
        $i++ ) 
        {
            $row = vsql_fetch_assoc($res);
            $ips[$row["ipid"]] = $row["ip"];
        }
        vexec("tc qdisc add dev venet0 root handle 1: cbq avpkt 1000 bandwidth 1000Mbit");
        vexec("tc qdisc add dev " . xss($interface) . " root handle 1: cbq avpkt 1000 bandwidth 1000Mbit");
        $classids = get_all_classids();
        $vps_class_ids = array( );
        foreach( $ips as $k => $v ) 
        {
            for( $i = 1; $i < 10000; $i++ ) 
            {
                if( !in_array($i, $classids) ) 
                {
                    $classids[$i] = $i;
                    $classid = $classids[$i];
                    break;
                }
            }
            $vps_class_ids[$v] = $classid;
            if( !empty($download_limit) ) 
            {
                vexec("tc class add dev venet0 parent 1: classid 1:" . xss($classid) . " cbq rate " . xss($download_limit) . "mbit allot 1500 prio 5 bounded isolated");
                vexec("tc filter add dev venet0 parent 1: protocol ip prio 16 u32 match ip dst " . xss($v) . " flowid 1:" . xss($classid));
                vexec("tc qdisc add dev venet0 parent 1:" . xss($classid) . " sfq perturb 10");
            }
            if( !empty($upload_limit) ) 
            {
                vexec("tc class add dev " . xss($interface) . " parent 1: classid 1:" . xss($classid) . " cbq rate " . xss($upload_limit) . "mbit allot 1500 prio 5 bounded isolated");
                vexec("tc filter add dev " . xss($interface) . " parent 1: protocol ip prio 16 u32 match ip src " . xss($v) . " flowid 1:" . xss($classid));
                vexec("tc qdisc add dev " . xss($interface) . " parent 1:" . xss($classid) . " sfq perturb 10");
            }
        }
        writefile($GLOBALS["globals"]["var"] . "/classids/" . $vid . ".cid", serialize($vps_class_ids), 1);
    }
    else 
    {
        $ret = vs_get_net_speed($vid, $force_limit);
        $download_limit = $ret["down"];
        $upload_limit = $ret["up"];
        if( empty($download_limit) && empty($upload_limit) ) 
        {
            vs_tc_destroy_vz($vid);
            return true;
        }
        $interface = (empty($GLOBALS["globals"]["interface"]) ? "eth0" : $GLOBALS["globals"]["interface"]);
        $ips = array( );
        $classids = array( );
        $ipv6prefixes = array( );
        $res = makequery("SELECT * FROM `ips`\n\t\t\t\t\t\tWHERE vpsid = '" . $vid . "'\n\t\t\t\t\t\tORDER BY `primary` DESC");
        for( $i = 0; $i < vsql_num_rows($res);
        $i++ ) 
        {
            $row = vsql_fetch_assoc($res);
            if( !empty($row["ipv6"]) ) 
            {
                $row["ip"] = ipv6_expand($row["ip"]);
                $ipv6prefixes[$row["ip"]] = (!empty($row["ipr_netmask"]) ? $row["ipr_netmask"] : 128);
            }
            $ips[$row["ipid"]] = $row["ip"];
        }
        $if_speed["venet0"] = $download_limit;
        $if_speed[$interface] = $upload_limit;
        $classids = get_all_classids();
        $vps_class_id = array( );
        for( $i = 1; $i < 65535; $i++ ) 
        {
            $tmp_i = dechex($i);
            if( !in_array($tmp_i, $classids) ) 
            {
                $classids[$i] = $tmp_i;
                $classid = $classids[$i];
                break;
            }
        }
        $vps_class_id[$vid] = $classid;
        foreach( $if_speed as $k => $v ) 
        {
            $k = xss($k);
            vexec("tc qdisc show dev " . $k . " | grep \"qdisc htb 1: root \"", $o, $r);
            if( $r ) 
            {
                vexec("tc qdisc add dev " . $k . " root handle 1: htb default ffff 2>&1");
            }
            unset($r);
            vexec("tc class show dev " . $k . " | grep \"class htb 1:ffff root \"", $o, $r);
            if( $r ) 
            {
                vexec("tc class add dev " . $k . " parent 1: classid 1:ffff htb rate 10000mbit burst 24k 2>&1");
            }
            unset($r);
            vexec("tc qdisc show dev " . $k . " | grep \"qdisc sfq 2: parent 1:ffff \"", $o, $r);
            if( $r ) 
            {
                vexec("tc qdisc add dev " . $k . " parent 1:ffff handle 2: sfq perturb 10 2>&1");
            }
            unset($r);
            vexec("tc class add dev " . $k . " parent 1: classid 1:" . xss($classid) . " htb rate " . xss($v) . "mbit burst 15k 2>&1");
            vexec("tc qdisc add dev " . $k . " parent 1:" . $classid . " handle " . xss(dechex(hexdec($classid) + 2)) . ": sfq perturb 10 2>&1");
        }
        foreach( $ips as $k => $v ) 
        {
            foreach( $if_speed as $if => $sp ) 
            {
                if( !empty($sp) ) 
                {
                    vexec("tc filter add dev " . xss($if) . " parent 1: protocol ip" . ((!empty($ipv6prefixes[$v]) ? "v6 prio 17" : " prio 16")) . " u32 match ip" . ((!empty($ipv6prefixes[$v]) ? "6" : "")) . " " . (($if == "venet0" ? "dst" : "src")) . " " . xss($v . ((!empty($ipv6prefixes[$v]) ? "/" . $ipv6prefixes[$v] : ""))) . " flowid 1:" . xss($classid) . " 2>&1");
                }
            }
        }
        writefile($GLOBALS["globals"]["var"] . "/classids/" . $vid . ".cid", serialize($vps_class_id), 1);
    }
    return true;
}
function vs_tc_destroy($interface) 
{
    if( empty($interface) ) 
    {
        return false;
    }
    vexec("tc qdisc del dev " . $interface . " root");
    vexec("tc qdisc del dev " . $interface . " ingress");
    return true;
}
function vs_tc_destroy_vz($vid) 
{
    global $globals;
    global $error;
    $interface = (empty($GLOBALS["globals"]["interface"]) ? "eth0" : $GLOBALS["globals"]["interface"]);
    $vps_classid = "";
    if( file_exists($GLOBALS["globals"]["var"] . "/classids/" . $vid . ".cid") && is_safe_file($GLOBALS["globals"]["var"] . "/classids/" . $vid . ".cid") ) 
    {
        $classids = file_get_contents($GLOBALS["globals"]["var"] . "/classids/" . $vid . ".cid");
        $tmp_vps_classid = _unserialize($classids);
        $vps_classids = $tmp_vps_classid;
    }
    $fhs = array( );
    $fhs["up"] = $interface;
    $fhs["down"] = "venet0";
    foreach( $fhs as $k => $v ) 
    {
        vexec("tc filter show dev " . xss($v), $o, $ret);
        if( !empty($o) ) 
        {
            foreach( $o as $j => $m ) 
            {
                if( preg_match("/pref (\\w+).+\\s(\\w+::\\w+)\\s.+1:(" . implode("|", $vps_classids) . ")/", $m, $matches) ) 
                {
                    vexec("tc filter del dev " . xss($v) . " prio " . trim($matches[1]) . " handle " . xss(trim($matches[2])) . " u32");
                    unset($matches);
                }
            }
        }
        unset($o);
        unset($ret);
    }
    foreach( $vps_classids as $vk => $vv ) 
    {
        vexec("tc class del dev venet0 parent 1: classid 1:" . xss($vv));
        vexec("tc class del dev " . xss($interface) . " parent 1: classid 1:" . xss($vv));
    }
    return true;
}
function get_all_classids() 
{
    $classids = array( );
    oexec("tc qdisc show", $out, $ret);
    $out = explode("\n", $out);
    foreach( $out as $k => $v ) 
    {
        preg_match("/(.*?)parent(\\s*?)1:(\\w+)(.*?)/is", $v, $classid);
        if( empty($classid[3]) ) 
        {
            continue;
        }
        $classids[$classid[3]] = $classid[3];
    }
    return $classids;
}
function get_running_tasks($actid = 0, $actions = array( ), $vpsid = 0, $failed_func = "") 
{
    $query = "SELECT * FROM `tasks`";
    $where = array( "ended" => "ended = 0", "serid" => "serid = 0" );
    $tokenvals = array( );
    if( !empty($actid) ) 
    {
        $where["actid"] = "actid < :actid";
        $tokenvals[":actid"] = $actid;
    }
    if( !empty($actions) ) 
    {
        $where["action"] = "action IN ('-1', '" . implode("', '", $actions) . "')";
    }
    if( !empty($vpsid) ) 
    {
        $where["vpsid"] = "vpsid = :vpsid";
        $tokenvals[":vpsid"] = $vpsid;
    }
    $query .= " WHERE " . implode(" AND ", $where);
    $res = makequery($query, $tokenvals);
    $running = 0;
    for( $i = 0; $i < vsql_num_rows($res);
    $i++ ) 
    {
        $row = vsql_fetch_assoc($res);
        $data = unserialize($row["data"]);
        if( !empty($data["pid"]) ) 
        {
            vexec("/bin/ps " . $data["pid"], $output);
            $virt = $data["virt"];
            if( 1 < count($output) ) 
            {
                $running++;
            }
            else 
            {
                task_update($row["actid"], "", -1);
                if( !empty($failed_func) && function_exists($failed_func) ) 
                {
                    call_user_func($failed_func, $row);
                }
            }
        }
    }
    return $running;
}
function initiate_reverse_sync() 
{
    global $globals;
    if( !is_slave() ) 
    {
        return false;
    }
    $timestamp = time();
    $res = makequery("UPDATE servers\n\t\t\t\t\t\tSET last_reverse_sync = :timestamp\n\t\t\t\t\t\tWHERE serid = 0", array( ":timestamp" => $timestamp ));
    if( 0 < vsql_affected_rows($res) ) 
    {
        vexec("/bin/ps aux | grep " . xss($globals["path"] . "/scripts/reverse_sync.ph[p]"), $out);
        if( 0 < count($out) ) 
        {
            return NULL;
        }
        vexec($globals["com"]["php"] . " " . $globals["path"] . "/scripts/reverse_sync.php > " . logdir() . "reverse_sync.log 2>&1 &");
    }
}
function billing_symbol() 
{
    global $globals;
    $GLOBALS["_api"]["billing_symbol"] = $globals["billing_symbol"];
}
function bill_status($invoice) 
{
    return (!empty($invoice["cancelled"]) ? "cancelled" : (empty($invoice["paydate"]) ? "unpaid" : "paid"));
}
function full_cp_url() 
{
    global $globals;
    global $SESS;
    return $globals["cp_url"] . ((empty($SESS["token_key"]) ? "" : "/" . $SESS["token_key"])) . "/index.php?";
}
function billing_balance($uid) 
{
    global $globals;
    global $user;
    if( $uid <= 0 ) 
    {
        return 0;
    }
    $res = makequery("SELECT SUM(amt) AS bal FROM transactions\n\t\t\t\t\tWHERE uid = '" . $uid . "'\n\t\t\t\t\tAND used = 0");
    if( 0 < vsql_num_rows($res) ) 
    {
        $tmp = vsql_fetch_assoc($res);
        return (double) $tmp["bal"];
    }
    return 0;
}
function billing_charges_month($uid) 
{
    global $globals;
    global $user;
    if( $uid <= 0 ) 
    {
        return 0;
    }
    $res = makequery("SELECT SUM(net) AS charges FROM invoices\n\t\t\t\t\tWHERE uid = '" . $uid . "'\n\t\t\t\t\tAND invodate >= '" . datify(time(), 0, 1, "Ym") . "01'\n\t\t\t\t\tAND invodate <= '" . datify(time(), 0, 1, "Ymt") . "'");
    if( 0 < vsql_num_rows($res) ) 
    {
        $tmp = vsql_fetch_assoc($res);
        return (double) $tmp["charges"];
    }
    return 0;
}
function billing_unpaid($uid, &$value = 0) 
{
    global $globals;
    global $user;
    $ret = array( );
    if( $uid <= 0 ) 
    {
        return $ret;
    }
    $res = makequery("SELECT * FROM invoices\n\t\t\t\t\tWHERE uid = '" . $uid . "'\n\t\t\t\t\tAND cancelled = 0\n\t\t\t\t\tAND paydate = 0\n\t\t\t\t\tORDER BY `net` ASC");
    if( 0 < vsql_num_rows($res) ) 
    {
        for( $i = 0; $i < vsql_num_rows($res);
        $i++ ) 
        {
            $row = vsql_fetch_assoc($res);
            $ret[$row["invoid"]] = $row;
            $value += $row["net"];
        }
    }
    return $ret;
}
function billing_funds_added($uid) 
{
    $balance = billing_balance($uid);
    if( 0 < $balance ) 
    {
        $unpaid = billing_unpaid($uid);
        if( 0 < count($unpaid) ) 
        {
            foreach( $unpaid as $uk => $uv ) 
            {
                $balance = billing_balance($uid);
                if( $balance < $uv["net"] ) 
                {
                    break;
                }
                $invoice_trid = insert_and_id("INSERT INTO transactions\n\t\t\t\t\t\tSET uid = :uid,\n\t\t\t\t\t\tdate = '" . datify(time(), 0, 1, "Ymd") . "',\n\t\t\t\t\t\tunixtime = '" . time() . "',\n\t\t\t\t\t\tinvoid = :invoid,\n\t\t\t\t\t\tamt = :amt,\n\t\t\t\t\t\tfees = :fees,\n\t\t\t\t\t\tnet = amt - fees,\n\t\t\t\t\t\tbal = :bal", array( "uid" => $uid, "invoid" => $uk, "amt" => 0 - $uv["net"], "fees" => 0, "bal" => $balance - $uv["net"] ));
                $res = makequery("UPDATE invoices\n\t\t\t\t\tSET paydate = '" . datify(time(), 0, 1, "Ymd") . "',\n\t\t\t\t\tpaytime = '" . time() . "',\n\t\t\t\t\ttoken = '" . $invoice_trid . "'\n\t\t\t\t\tWHERE invoid = :invoid\n\t\t\t\t\tAND uid = :uid", array( ":invoid" => $uk, ":uid" => $uid ));
            }
        }
    }
    billing_try_unsuspend($uid);
}
function billing_try_unsuspend($uid) 
{
    global $globals;
    global $ckernel;
    $res = makequery("UPDATE users u\n\t\t\t\t\tSET u.cur_bal = (SELECT SUM(amt)\n\t\t\t\t\t\t\t\tFROM transactions t\n\t\t\t\t\t\t\t\tWHERE t.`used` = 0\n\t\t\t\t\t\t\t\tAND t.uid = '" . $uid . "'),\n\t\t\t\t\tu.cur_invoices = (SELECT SUM(net)\n\t\t\t\t\t\t\t\tFROM invoices i\n\t\t\t\t\t\t\t\tWHERE i.paydate = 0\n\t\t\t\t\t\t\t\tAND i.cancelled = 0\n\t\t\t\t\t\t\t\tAND i.uid = '" . $uid . "'),\n\t\t\t\t\tu.cur_usage = (SELECT SUM(h_used)\n\t\t\t\t\t\t\t\tFROM `usage` us\n\t\t\t\t\t\t\t\tWHERE us.invoid = 0\n\t\t\t\t\t\t\t\tAND us.uid = '" . $uid . "')\n\t\t\t\t\tWHERE u.uid = '" . $uid . "'");
    $res = makequery("SELECT uid, email, cur_bal, cur_usage, cur_invoices, (cur_usage + cur_invoices) AS total_usage,\n\t\t\t\t\t((cur_usage + cur_invoices) / cur_bal * 100) AS used_percent, billing_warn, suspended\n\t\t\t\t\tFROM `users`\n\t\t\t\t\tWHERE uid = '" . $uid . "'");
    $row = vsql_fetch_assoc($res);
    if( $row["cur_bal"] < $row["total_usage"] ) 
    {
        return false;
    }
    if( defined("VIRTUALIZOR_ENDUSER") ) 
    {
        return $ckernel->billing_unsuspend($uid);
    }
    return billing_unsuspend($uid);
}
function billing_unsuspend($uid) 
{
    global $globals;
    global $ckernel;
    vexec($globals["com"]["php"] . " " . $globals["path"] . "/scripts/billing_unsuspend.php " . $uid . " > " . logdir("billing_unsuspend") . $uid . ".log 2>&1 &");
    return true;
}
function billing_update_all() 
{
    $res = makequery("UPDATE users u\n\t\t\t\t\tINNER JOIN (\n\t\t\t\t\t\tSELECT uid, SUM(amt) 'cur_bal'\n\t\t\t\t\t\tFROM transactions\n\t\t\t\t\t\tWHERE `used` = 0\n\t\t\t\t\t\tGROUP BY uid\n\t\t\t\t\t) t\n\t\t\t\t\tSET u.cur_bal = t.cur_bal\n\t\t\t\t\tWHERE u.inhouse_billing > 0\n\t\t\t\t\tAND u.uid = t.uid");
    $res = makequery("UPDATE users u\n\t\t\t\t\tINNER JOIN (\n\t\t\t\t\t\tSELECT uid, SUM(net) 'cur_invoices'\n\t\t\t\t\t\tFROM invoices\n\t\t\t\t\t\tWHERE `paydate` = 0\n\t\t\t\t\t\tAND cancelled = 0\n\t\t\t\t\t\tGROUP BY uid\n\t\t\t\t\t) t\n\t\t\t\t\tSET u.cur_invoices = t.cur_invoices\n\t\t\t\t\tWHERE u.inhouse_billing > 0\n\t\t\t\t\tAND u.uid = t.uid");
    $res = makequery("UPDATE users u\n\t\t\t\t\tINNER JOIN (\n\t\t\t\t\t\tSELECT uid, SUM(h_used) 'cur_usage'\n\t\t\t\t\t\tFROM `usage`\n\t\t\t\t\t\tWHERE invoid = 0\n\t\t\t\t\t\tGROUP BY uid\n\t\t\t\t\t) t\n\t\t\t\t\tSET u.cur_usage = t.cur_usage\n\t\t\t\t\tWHERE u.inhouse_billing > 0\n\t\t\t\t\tAND u.uid = t.uid");
}
function get_vps_service_period($vpsid) 
{
    global $globals;
    $vps = getvps($vpsid);
    $start = array( "day" => 1, "month" => (int) datify(time(), 0, 0, "n"), "year" => (int) datify(time(), 0, 0, "Y") );
    if( !empty($globals["band_calc_creation"]) ) 
    {
        $curr_day = datify(time(), 0, 1, "j");
        $start["day"] = datify($vps["time"], 0, 1, "j");
        if( $curr_day < $start["day"] ) 
        {
            $start["month"]--;
        }
    }
    $timestamps = array( );
    $timestamps["start"] = mktime(0, 0, 0, $start["month"], $start["day"], $start["year"]);
    $timestamps["end"] = strtotime("+1 month", $timestamps["start"]);
    return $timestamps;
}
function is_billing_api() 
{
    $is_billing = optreq("billing_panel");
    if( !empty($is_billing) ) 
    {
        return $is_billing;
    }
    return false;
}
function resource_rates() 
{
    global $globals;
    $json = @file_get_contents($globals["path"] . "/resource_pricing.json");
    return @json_decode($json, 1);
}
function timezones() 
{
    $regions = array( "Africa" => DateTimeZone::AFRICA, "America" => DateTimeZone::AMERICA, "Antarctica" => DateTimeZone::ANTARCTICA, "Asia" => DateTimeZone::ASIA, "Atlantic" => DateTimeZone::ATLANTIC, "Europe" => DateTimeZone::EUROPE, "Indian" => DateTimeZone::INDIAN, "Pacific" => DateTimeZone::PACIFIC );
    $timezones = array( );
    foreach( $regions as $name => $mask ) 
    {
        $zones = DateTimeZone::listIdentifiers($mask);
        foreach( $zones as $timezone ) 
        {
            $time = new DateTime(NULL, new DateTimeZone($timezone));
            $ampm = $time->format("g:i A");
            $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . " - " . $ampm;
        }
    }
    return $timezones;
}
function perform_vps_operation($vid, $actid = 0, $action, $data = array( )) 
{
    global $globals;
    global $user;
    global $ostemplates;
    global $l;
    global $oslist;
    global $kernel;
    if( is_array($actid) ) 
    {
        $actid = $GLOBALS["current_taskid"];
    }
    $vps = getvps($vid);
    if( empty($oslist) ) 
    {
        oslist();
    }
    task_start($actid);
    task_update($actid, $l["started"], 10, "XXXXXXXX");
    if( $vps["virt"] == "lxc" || $vps["virt"] == "xen" && empty($vps["hvm"]) ) 
    {
        $mount = mount_direct($vid);
    }
    else 
    {
        $mount = mount($vid, "", 1);
    }
    if( !is_array($mount) ) 
    {
        if( $mount == -1 ) 
        {
            task_update($actid, $l["mount_undetermined"], -1);
            return true;
        }
        task_update($actid, $l["err_mount"], -1);
        return false;
    }
    if( $action == "change_password" && is_safe_file($mount["mount_point"] . "/etc/shadow") && file_exists($mount["mount_point"] . "/etc/shadow") ) 
    {
        $shadow = file($mount["mount_point"] . "/etc/shadow");
        $tmp = explode(":", $shadow[0]);
        $tmp[1] = crypt($data[0]);
        $shadow[0] = implode(":", $tmp);
        writefile($mount["mount_point"] . "/etc/shadow", implode("", $shadow), 1);
    }
    if( file_exists($mount["mount_point"] . "/Windows/System32/config/SAM") || file_exists($mount["mount_point"] . "/WINDOWS/system32/config/SAM") ) 
    {
        $sam_location = $mount["mount_point"] . "/Windows/System32/config/SAM";
        if( !file_exists($sam_location) ) 
        {
            $sam_location = $mount["mount_point"] . "/WINDOWS/system32/config/SAM";
        }
        if( !empty($ostemplates[$vps["osid"]]["template_admin_name"]) ) 
        {
            $windows_admin_name = $ostemplates[$vps["osid"]]["template_admin_name"];
        }
        $location = $mount["mount_point"] . "/Users/" . ((empty($windows_admin_name) ? "Administrator" : $windows_admin_name)) . "/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup";
        if( !file_exists($location) ) 
        {
            $location = $mount["mount_point"] . "/Documents and Settings/All Users/Start Menu/Programs/Startup";
        }
        if( is_safe_file($sam_location) && is_safe_file($location) && is_safe_file($location . "/virtualizor.bat") ) 
        {
            $contents = file_get_contents($location . "/virtualizor.bat");
            if( !preg_match("/REM @remote_desktop_start.*REM @remote_desktop_end/is", $contents) || !preg_match("/REM @password_start.*REM @password_end/is", $contents) ) 
            {
                $contents = "@echo off\n\nREM @remote_desktop_start\nREM @remote_desktop_end\n\nREM @password_start\nREM @password_end\n\ntimeout /t 5 /nobreak >nul 2>nul\nREM @shutdown\nDEL \"%~f0\"";
            }
            if( $action == "change_password" ) 
            {
                vexec("chntpw ", $o, $r);
                $v1 = explode(" ", $o[0]);
                $v1 = explode(".", $v1[2]);
                $v1 = (0 < $v1[0] ? "q" : "");
                @exec("chntpw -u " . ((empty($windows_admin_name) ? "Administrator" : $windows_admin_name)) . " \"" . $sam_location . "\" << EOF\n1" . ((empty($v1) ? "" : "\nq")) . "\ny\nEOF", $output, $ret);
                $contents = preg_replace("/REM @password_start.*REM @password_end/is", "REM @password_start\nnet user " . ((empty($windows_admin_name) ? "Administrator" : $windows_admin_name)) . " \"" . str_replace("\"", "\\\"", $data[0]) . "\" >nul 2>nul\nREM @password_end", $contents);
                $contents = preg_replace("/REM @shutdown/is", "Shutdown -l", $contents);
            }
            if( $action == "remote_desktop" ) 
            {
                if( !empty($data[0]) ) 
                {
                    $contents = preg_replace("/REM @remote_desktop_start.*REM @remote_desktop_end/is", "REM @remote_desktop_start\nreg add \"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\" /v fDenyTSConnections /t REG_DWORD /d 0 /f >nul 2>nul\nnetsh firewall set service type = remotedesktop mode = enable >nul 2>nul\nREM @remote_desktop_end", $contents);
                }
                else 
                {
                    $contents = preg_replace("/REM @remote_desktop_start.*REM @remote_desktop_end/is", "REM @remote_desktop_start\nreg add \"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\" /v fDenyTSConnections /t REG_DWORD /d 1 /f >nul 2>nul\nnetsh firewall set service type = remotedesktop mode = disable >nul 2>nul\nREM @remote_desktop_end", $contents);
                }
            }
            writefile($location . "/virtualizor.bat", $contents, 1);
        }
    }
    $umount = umount($mount);
    if( !empty($umount) ) 
    {
        $error[] = $l["err_unmount"];
        task_update($actid, $l["err_unmount"], -1);
        return false;
    }
    task_update($actid, $l["completed"], 100);
    return true;
}

生成license的脚本

function sm_reverse_bits($orig) 
{
    $v = decbin(ord($orig));
    $pad = str_pad($v, 8, "0", STR_PAD_LEFT);
    $rev = strrev($pad);
    $bin = bindec($rev);
    $chr = chr($bin);
    return $chr;
}

function sm_encode($txt) 
{
    $from = array( "!", "@", "#", "\$", "%", "^", "&", "*", "(", ")" );
    $to = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" );
    $txt = base64_encode($txt);
    
    $txt = str_replace($to, $from, $txt);

    
    $txt = gzcompress($txt);

    for( $i = 0; $i < strlen($txt);$i++ ) 
    {
        $txt[$i] = sm_reverse_bits($txt[$i]);
    }
    $txt = base64_encode($txt);
    return $txt;
}

$ip=str_replace(PHP_EOL, '',file_get_contents("http://www.cpanel.net/showip.cgi"));
$ipx=str_replace(".","",$ip);
echo sm_encode('{
    "license": "VRTDVLPL-FULLANDFULL-TUHANTS75-INEEDMONEY-FORANEWSERVER-'.$ipx.'END",
    "lictype": "1",
    "lictype_txt": "Unlimited",
    "active": 1,
    "active_txt": "<font color=\"green\">Active<\/font>",
    "licnumvs": "0",
    "primary_ip": "'.$ip.'",
    "licexpires": "29991231",
    "licexpires_txt": "31\/12\/2999 GMT",
    "last_edit": "0",
    "fast_mirrors": ["https:\/\/s1.softaculous.com\/a\/virtualizor", "https:\/\/s2.softaculous.com\/a\/virtualizor", "https:\/\/s3.softaculous.com\/a\/virtualizor", "https:\/\/s4.softaculous.com\/a\/virtualizor", "https:\/\/s7.softaculous.com\/a\/virtualizor"]
}');
?>

解密license的脚本

<?php
function sm_decode($txt) 
{
    $from = array( "!", "@", "#", "\$", "%", "^", "&", "*", "(", ")" );
    $to = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" );
    $txt = base64_decode($txt);
    
    
    for( $i = 0; $i < strlen($txt);$i++ ) 
    {
        $txt[$i] = sm_reverse_bits($txt[$i]);
    }
    $txt = gzuncompress($txt);

    $txt = str_replace($from, $to, $txt);

    $txt = base64_decode($txt);
    return $txt;
}
function sm_reverse_bits($orig) 
{
    $v = decbin(ord($orig));
    $pad = str_pad($v, 8, "0", STR_PAD_LEFT);
    $rev = strrev($pad);
    $bin = bindec($rev);
    $chr = chr($bin);
    return $chr;
}

echo sm_decode("license2.php 里面的字符串");
?>

一键自动破解脚本

首先创建脚本

vi /opt/license.sh

然后写入下面的内容

#/bin/bash
# 
# 设置license
# 
chattr -i /usr/local/virtualizor/license2.php
rm -rf /usr/local/virtualizor/license2.php
IP=`curl http://members.3322.org/dyndns/getip`
LIC_URL='http://www.03sec.com/make_license.php?str='$IP
license_text=`curl $LIC_URL`
echo $license_text >> /usr/local/virtualizor/license2.php
chattr +i /usr/local/virtualizor/license2.php

最后增加执行权限以及运行脚本

chmod +x /opt/license.sh && /opt/license.sh

测试中发现,virtualizor会自己更改license2.php,即使使用了chattr也没用。建议将上面的脚本设置为定时任务,每小时运行一次

0 * * * * /opt/license.sh

make_license.php

function sm_reverse_bits($orig)
{
        $v = decbin(ord($orig));
        $pad = str_pad($v, 8, "0", STR_PAD_LEFT);
        $rev = strrev($pad);
        $bin = bindec($rev);
        $chr = chr($bin);
        return $chr;
}
function sm_encode($txt)
{
        $from = array( "!", "@", "#", "\$", "%", "^", "&", "*", "(", ")" );
        $to = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" );
        $txt = base64_encode($txt);
        $txt = str_replace($to, $from, $txt);
        $txt = gzcompress($txt);
        for( $i = 0; $i < strlen($txt);$i++ )
        {
                $txt[$i] = sm_reverse_bits($txt[$i]);
        }
        $txt = base64_encode($txt);
        return $txt;
}
$str=$_REQUEST['str'];
                if(filter_var($str, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                        $ipx=str_replace(".","",$str);
                        echo sm_encode('{
                                "license": "VRTDVLPL-03SEC-CRACK-FORANEWSERVER-'.$ipx.'END",
                                "lictype": "1",
                                "lictype_txt": "Unlimited",
                                "active": 1,
                                "active_txt": "<font color=\"green\">Active<\/font>",
                                "licnumvs": "0",
                                "primary_ip": "'.$str.'",
                                "licexpires": "29991231",
                                "licexpires_txt": "31\/12\/2999 GMT",
                                "last_edit": "0",
                                "fast_mirrors": ["https:\/\/s1.softaculous.com\/a\/virtualizor", "https:\/\/s2.softaculous.com\/a\/virtualizor", "https:\/\/s3.softaculous.com\/a\/virtualizor", "https:\/\/s4.softaculous.com\/a\/virtualizor", "https:\/\/s7.softaculous.com\/a\/virtualizor"]
                        }');
                        }else{
                                echo "sb.....";
                                exit();
                        }
        
?>
最后修改:2021 年 11 月 23 日
如果觉得我的文章对你有用,请随意赞赏