<?php

//echo '<pre>';
//var_dump($_POST);
//echo '</pre>';


$_REQUEST = _antiSqlInjection($_REQUEST);
$_POST = _antiSqlInjection($_POST);
$_GET = _antiSqlInjection($_GET);
$_COOKIE = _antiSqlInjection($_COOKIE);

function _antiSqlInjection($Target, $campos_excluidos = array()) {
    $sanitizeRules = array(' OR ', ' OR', 'FROM', 'SELECT', 'INSERT', 'DELETE', 'WHERE', 'DROP TABLE', 'SHOW TABLES', ' *', '--', '<SCRIPT>', '<script>', '</SCRIPT>', '</script>');
    //$campos_permitidos = array('recaptcha_challenge_field');
    foreach ($Target as $key => $value):
        if (is_array($value)): $arraSanitized[$key] = _antiSqlInjection($value, $campos_excluidos);
        else:
            $arraSanitized[$key] = (!get_magic_quotes_gpc()) ? addslashes(str_ireplace($sanitizeRules, "", $value)) : str_ireplace($sanitizeRules, "", $value);
        endif;


    endforeach;
    if (isset($arraSanitized)) {
        return $arraSanitized;
    }
}

function kickuser($username) {
    $url = $_SESSION["cspsrv_protocol"] . "://" . $_SESSION["cspsrv_user"] . ":" . $_SESSION["cspsrv_pass"] . "@" . $_SESSION["cspsrv_ip"] . ":" . $_SESSION["cspsrv_port"] . "/xmlHandler?command=kick-user&name=" . $username;
    file($url);
    return($username . " sucesso chutou!");
}

function removeuser($uid, $username) {
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    mysql_query("DELETE FROM cmum_udb WHERE id='" . $uid . "'") or sqlerror();
    mysql_close($conn);
    return("Usuário [" . $username . "] Removido Com Sucesso");
}

function randomstring() {
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $sql = mysql_query("SELECT * FROM cmum_settings WHERE id='1'");
    $line = mysql_fetch_array($sql);
    mysql_close($conn);
    $chars = $line["rndpasschr"];
    srand((double) microtime() * 1000000);
    $i = 0;
    $pass = "";
    while ($i <= $line["rndpasschrlength"] - 1) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return($pass);
}

function sendosdmessage($username, $text) {
    $text = str_replace(" ", "+", $text);
    $url = $_SESSION["cspsrv_protocol"] . "://" . $_SESSION["cspsrv_user"] . ":" . $_SESSION["cspsrv_pass"] . "@" . $_SESSION["cspsrv_ip"] . ":" . $_SESSION["cspsrv_port"] . "/xmlHandler?command=osd-message&name=" . $username . "&text=" . $text;
    $retvalue = file($url);
    if (substr($retvalue[2], 0, 12) == "Message sent") {
        $status = str_replace(".", "", $retvalue[2]);
    }
    if (substr($retvalue[2], 0, 9) == "No active") {
        $status = "<font color=\"#FF0000\">" . $retvalue[2] . "</font>";
    }
    return($status);
}

function updatecspudb() {
    $url = $_SESSION["cspsrv_protocol"] . "://" . $_SESSION["cspsrv_user"] . ":" . $_SESSION["cspsrv_pass"] . "@" . $_SESSION["cspsrv_ip"] . ":" . $_SESSION["cspsrv_port"] . "/xmlHandler?command=update-users";
    $retvalue = file($url);
    if (substr($retvalue[2], 0, 17) == "Updated performed") {
        $status = "<font color=\"#347C2C\">" . trim(str_replace(".", "", $retvalue[2])) . "!</font>";
    } else {
        $status = "<font color=\"#FF0000\">" . trim(str_replace(".", "", $retvalue[2])) . "!</font>";
    }
    return($status);
}

function replacechars($string) {
    $string = str_replace("'", "&#39;", $string);
    $string = str_replace("\"", "&quot;", $string);
    $string = str_replace("&", "&amp;", $string);
    $string = str_replace("¢", "&cent;", $string);
    $string = str_replace("©", "&copy;", $string);
    $string = str_replace("÷", "&divide;", $string);
    $string = str_replace(">", "&gt;", $string);
    $string = str_replace("<", "&lt;", $string);
    $string = str_replace("µ", "&micro;", $string);
    $string = str_replace("·", "&middot;", $string);
    $string = str_replace("¶", "&para;", $string);
    $string = str_replace("±", "&plusmn;", $string);
    $string = str_replace("€", "&euro;", $string);
    $string = str_replace("£", "&pound;", $string);
    $string = str_replace("®", "&reg;", $string);
    $string = str_replace("§", "&sect;", $string);
    $string = str_replace("™", "&trade;", $string);
    $string = str_replace("¥", "&yen;", $string);
    $string = str_replace("–", "&ndash;", $string);
    $string = str_replace("—", "&mdash;", $string);
    $string = str_replace("¡", "&iexcl;", $string);
    $string = str_replace("¿", "&iquest;", $string);
    $string = str_replace("\"", "&quot;", $string);
    $string = str_replace("“", "&ldquo;", $string);
    $string = str_replace("”", "&rdquo;", $string);
    $string = str_replace("‘", "&lsquo;", $string);
    $string = str_replace("’", "&rsquo;", $string);
    $string = str_replace("«", "&laquo;", $string);
    $string = str_replace("»", "&raquo;", $string);
    return($string);
}

function reversechars($string) {
    $string = str_replace("&#39;", "'", $string);
    $string = str_replace("&quot;", "\"", $string);
    $string = str_replace("&amp;", "&", $string);
    $string = str_replace("&cent;", "¢", $string);
    $string = str_replace("&copy;", "©", $string);
    $string = str_replace("&divide;", "÷", $string);
    $string = str_replace("&gt;", ">", $string);
    $string = str_replace("&lt;", "<", $string);
    $string = str_replace("&micro;", "µ", $string);
    $string = str_replace("&middot;", "·", $string);
    $string = str_replace("&para;", "¶", $string);
    $string = str_replace("&plusmn;", "±", $string);
    $string = str_replace("&euro;", "€", $string);
    $string = str_replace("&pound;", "£", $string);
    $string = str_replace("&reg;", "®", $string);
    $string = str_replace("&sect;", "§", $string);
    $string = str_replace("&trade;", "™", $string);
    $string = str_replace("&yen;", "¥", $string);
    $string = str_replace("&ndash;", "–", $string);
    $string = str_replace("&mdash;", "—", $string);
    $string = str_replace("&iexcl;", "¡", $string);
    $string = str_replace("&iquest;", "¿", $string);
    $string = str_replace("&quot;", "\"", $string);
    $string = str_replace("&ldquo;", "“", $string);
    $string = str_replace("&rdquo;", "”", $string);
    $string = str_replace("&lsquo;", "‘", $string);
    $string = str_replace("&rsquo;", "’", $string);
    $string = str_replace("&laquo;", "«", $string);
    $string = str_replace("&raquo;", "»", $string);
    $string = str_replace(array('á', 'à', 'ã'), 'a', $string);
    $string = str_replace(array('é', 'è'), 'e', $string);
    $string = str_replace(array('í', 'ì'), 'i', $string);
    $string = str_replace(array('ó', 'ò', 'õ'), 'o', $string);
    $string = str_replace(array('ú', 'ù'), 'u', $string);
    $string = str_replace(array('Á', 'À', 'Ã'), 'A', $string);
    $string = str_replace(array('É', 'È'), 'E', $string);
    $string = str_replace(array('Í', 'Ì'), 'I', $string);
    $string = str_replace(array('Ó', 'Ò', 'Õ'), 'O', $string);
    $string = str_replace(array('Ú', 'Ù'), 'U', $string);
    $string = str_replace("ç", "c", $string);
    $string = str_replace("Ç", "C", $string);

    return($string);
}

function dpt($d, $s) {
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $s, base64_decode($d), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}

function adduser($username, $password, $displayname, $ipmask, $profiles, $maxconnections, $admin, $enabled, $mapexclude, $debug, $email, $dd, $telefone, $dd_cel, $celular, $comment, $usrgroup, $customvalues, $ecmrate, $startdate, $expiredate, $obs_user, $valor_cob) {
    // Return codes
    // 0 = user added
    // 1 = no username or password
    // 2 = username allready exists
    // 10 = internal: create random password
    // 11 = internal: load defaults/auto load defaults
    // 12 = internal: user added and defaults loaded
    require("config.php");

    $expiredate = date("Y-m-d H:i:s", strtotime(str_replace("/", "-", trim($expiredate))));

    if ($username == "" or $password == "" || $displayname == "") {
        $status = "1";
    } elseif (strtotime($expiredate) < time()) {
        $status = "6";
    } else {
        $conn = @mysql_connect($dbhost, $dbuser, $dbpass);
        mysql_select_db($dbname, $conn);
        $sql = mysql_query("SELECT * FROM cmum_udb WHERE name='" . $username . "'");
        $rowcheck = mysql_num_rows($sql);
        if ($rowcheck == 1) {
            $status = "2";
            mysql_close($conn);
        } elseif ($profiles == "") {
            $status = "3";
        } elseif (strlen($username) < 3 or strlen($username) > 20) {
            $status = "4";
        } elseif (strlen($password) < 2 or strlen($password) > 15) {
            $status = "5";
        } elseif ($expiredate == "") {
            $status = "6";
        } elseif (($telefone != "" && $dd == "") || ($celular != "" && $dd_cel == "")) {//$dd_cel,$celular
            $status = "7";
        } else {
            if (!isset($profiles)) {
                $count_maxconnections = 1;
                $profiles = "N;";
            } else {
                $count_maxconnections = count($profiles);
                $profiles = serialize($profiles);
            }
            $username = trim(addslashes(replacechars($username)));
            $password = trim(addslashes(replacechars($password)));
            $displayname = trim(replacechars($displayname));
            $ipmask = trim($ipmask);
            $maxconnections = (is_numeric($maxconnections)) ? trim(addslashes(replacechars($maxconnections))) : 1;
            $admin = strtolower($admin);
            $enabled = strtolower($enabled);
            $mapexclude = strtolower($mapexclude);
            $debug = strtolower($debug);
            $email = trim(addslashes(replacechars($email)));
            $dd = trim(addslashes(replacechars($dd)));
            $telefone = trim(addslashes(replacechars($telefone)));
            $dd_cel = trim(addslashes(replacechars($dd_cel)));
            $celular = trim(addslashes(replacechars($celular)));
            $comment = replacechars($comment);
            $usrgroup = trim(replacechars($usrgroup));
            $customvalues = trim(replacechars($customvalues));
            $ecmrate = trim($ecmrate);
            $startdate = trim($startdate);
            $obs_user = trim(addslashes(replacechars($obs_user)));
            $valor_cob = trim(addslashes(replacechars($valor_cob)));
            $ip_cad = $_SERVER['REMOTE_ADDR'];
            mysql_query("INSERT INTO cmum_udb (name,password,displayname,ipmask,profiles,maxconnections,admin,enabled,mapexclude,debug,comment,email,dd,telefone,dd_cel,celular,usrgroup,customvalues,ecmrate,startdate,expiredate,added,addedby,addedbyname,changed,changedby,obs_user,valor_cob,ip_cad) VALUES "
                    . "('" . $username . "','" . $password . "','" . $displayname . "','" . $ipmask . "','" . $profiles . "','" . $maxconnections . "','" . $admin . "','" . $enabled . "','" . $mapexclude . "','" . $debug . "','" . $comment . "','" . $email . "','" . $dd . "','" . $telefone . "','" . $dd_cel . "','" . $celular . "','" . $usrgroup . "','" . $customvalues . "','" . $ecmrate . "','" . $startdate . "','" . $expiredate . "','" . date("Y-m-d H:i") . "','" . $_SESSION["adminid"] . "','" . $_SESSION["loginuser"] . "','','','{$obs_user}','{$valor_cob}','{$ip_cad}')");
            $_id_inserido = mysql_insert_id($conn);
            mysql_close($conn);
            $status = "0";
        }
    }
    return array($status, $_id_inserido);
}

function ept($e, $s) {
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $s, $e, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}

function edituser($uid, $username, $password, $displayname, $ipmask, $profiles, $maxconnections, $admin, $enabled, $mapexclude, $debug, $email, $dd, $telefone, $dd_cel, $celular, $comment, $usrgroup, $customvalues, $ecmrate, $startdate, $expiredate, $obs_user, $valor_cob) {
    require("config.php");
    if (!isset($profiles)) {
        $count_maxconnections = 1;
        $profiles = "N;";
    } else {
        $count_maxconnections = count($profiles);
        $profiles = serialize($profiles);
    }
    $username = trim(addslashes(replacechars($username)));
    $password = trim(addslashes(replacechars($password)));
    $displayname = trim(replacechars($displayname));
    $ipmask = trim($ipmask);
    $maxconnections = (is_numeric($maxconnections)) ? trim(addslashes(replacechars($maxconnections))) : 1;
    $admin = strtolower($admin);
    $enabled = strtolower($enabled);
    $mapexclude = strtolower($mapexclude);
    $debug = strtolower($debug);
    $email = trim(addslashes(replacechars($email)));
    $dd = trim(addslashes(replacechars($dd)));
    $telefone = trim(addslashes(replacechars($telefone)));
    $dd_cel = trim(addslashes(replacechars($dd_cel)));
    $celular = trim(addslashes(replacechars($celular)));
    $comment = replacechars($comment);
    $usrgroup = trim(replacechars($usrgroup));
    $customvalues = trim(replacechars($customvalues));
    $ecmrate = trim($ecmrate);
    $startdate = trim($startdate);
    $expiredate = trim($expiredate);
    $obs_user = trim(addslashes(replacechars($obs_user)));
    $valor_cob = trim(addslashes(replacechars($valor_cob)));
    $ip_atualizacao = $_SERVER['REMOTE_ADDR'];
    $id_rev_mudou_status = "0";
    if ($enabled == "false") {
        $id_rev_mudou_status = $_SESSION['adminid'];
    }


    /* $status = 0;
      if (strlen($username) < 3 or strlen($username) > 15) {
      $status = 4; // Limites tamanhos logins
      } elseif (strlen($password) < 2 or strlen($password) > 15) {
      $status = 5;// Limites tamanhos Senhas
      } elseif ($expiredate == "") {
      $status = 6;// Vencimento Vazio
      }
      if($status > 0){
      //header($_SERVER['HTTP_REFERRER']."&status={$status}");
      //exit();
      return $status;
      } */




    $conn = @mysql_connect($dbhost, $dbuser, $dbpass);
    mysql_select_db($dbname, $conn);
    /*
      1	Pode alterar login
      2	Pode alterar senha
      3	Pode alterar email
      4	Pode alterar vencimento
      5	Pode alterar status
      6	Pode exlcuir logins
      7	Pode alterar nome
      8	Pode alterar o numero de conexoees
     *      */
    $opc_log = unserialize($_SESSION["_opcoes_log"]);
    if (is_null($opc_log)) {
        $opc_log = array();
    }
    $SQL = "";
    if ($_SESSION['adminlevel'] != "0") {

        $SQL = "UPDATE cmum_udb SET ";
        if (!empty($opc_log) && array_search('1', $opc_log) !== false) {
            $SQL .= "name='{$username}',";
        }
        if (!empty($opc_log) && array_search('2', $opc_log) !== false) {
            $SQL .= "password='{$password}',";
        }
        if (!empty($opc_log) && array_search('7', $opc_log) !== false) {
            $SQL .= "displayname='{$displayname}',";
        }
        if (!empty($opc_log) && array_search('3', $opc_log) !== false) {
            $SQL .= "email='{$email}',";
        }
        if (!empty($opc_log) && array_search('4', $opc_log) !== false) {
            $SQL .= "expiredate='{$expiredate}',";
        }
        if (!empty($opc_log) && array_search('5', $opc_log) !== false) {
            $SQL .= "enabled='{$enabled}',"
                    . "id_rev_mudou_status='{$id_rev_mudou_status}',";
        }
        if (!empty($opc_log) && array_search('8', $opc_log) !== false) {
            $SQL .= "maxconnections = '{$maxconnections}', ";
        }
        /* if (!empty($opc_log) && array_search('9', $opc_log) !== false) {
          $SQL .= "dd = '{$dd}', "
          . "telefone = '{$telefone}', ";
          } */
        $SQL .= "dd = '{$dd}', ";
        $SQL .= "telefone = '{$telefone}', ";
        $SQL .= "dd_cel = '{$dd_cel}', ";
        $SQL .= "celular = '{$celular}', ";
        $SQL .= "profiles = '{$profiles}', ";
        $SQL .= "changed = '" . date('Y-m-d H:i:s') . "', ";
        $SQL .= "changedby = '{$_SESSION["adminid"]}', ";
        $SQL .= "obs_user = '{$obs_user}', ";
        $SQL .= "valor_cob = '{$valor_cob}'";
        $SQL .= " WHERE id = '{$uid}'";
        //exit($SQL);
    } else {
        $SQL = "UPDATE cmum_udb SET name = '" . $username . "', "
                . "password = '" . $password . "', "
                . " displayname = '" . $displayname . "', "
                . " ipmask = '" . $ipmask . "', "
                . " profiles = '" . $profiles . "', "
                . " maxconnections = '" . $maxconnections . "', "
                . " admin = '" . $admin . "', "
                . " enabled = '" . $enabled . "', "
                . " mapexclude = '" . $mapexclude . "', "
                . " debug = '" . $debug . "', "
                . " comment = '" . $comment . "', "
                . " email = '" . $email . "', "
                . " dd = '" . $dd . "', "
                . " telefone = '" . $telefone . "', "
                . " dd_cel = '" . $dd_cel . "', "
                . " celular = '" . $celular . "', "
                . " usrgroup = '" . $usrgroup . "', "
                . " customvalues = '" . $customvalues . "', "
                . " ecmrate = '" . $ecmrate . "', "
                . " startdate = '" . $startdate . "', "
                . " expiredate = '" . $expiredate . "', "
                . " changed = '" . date('Y-m-d H:i:s') . "', "
                . " changedby = '" . $_SESSION["adminid"] . "', "
                . " obs_user = '{$obs_user}', "
                . " valor_cob = '{$valor_cob}', "
                . " id_rev_mudou_status = '{$id_rev_mudou_status}',"
                . " ip_atualizacao = '{$ip_atualizacao}'"
                . " WHERE id = '" . $uid . "'";
    }
    $status = mysql_query($SQL) or die(mysql_error());
    /* mysql_query("UPDATE cmum_udb SET name = '" . $username . "', "
      . "password = '" . $password . "', "
      . " displayname = '" . $displayname . "', "
      . " ipmask = '" . $ipmask . "', "
      . " profiles = '" . $profiles . "', "
      . " maxconnections = '" . $maxconnections . "', "
      . " admin = '" . $admin . "', "
      . " enabled = '" . $enabled . "', "
      . " mapexclude = '" . $mapexclude . "', "
      . " debug = '" . $debug . "', "
      . " comment = '" . $comment . "', "
      . " email = '" . $email . "', "
      . " usrgroup = '" . $usrgroup . "', "
      . " customvalues = '" . $customvalues . "', "
      . " ecmrate = '" . $ecmrate . "', "
      . " startdate = '" . $startdate . "', "
      . " expiredate = '" . $expiredate . "', "
      . " changed = '" . date('Y-m-d H:i') . "', "
      . " changedby = '" . $_SESSION["adminid"] . "', "
      . " obs_user = '{$obs_user}'"
      . " WHERE id = '" . $uid . "'"); */
    mysql_close($conn);
    //$status = "Usuário [" . $username . "] atualizado com sucesso.";
    return $status;
}

function checkcspconn() {
    if ($_SESSION["cspconnchk"] == "1") {
        if (@simplexml_load_file($_SESSION["cspsrv_protocol"] . "://" . $_SESSION["cspsrv_user"] . ":" . $_SESSION["cspsrv_pass"] . "@" . $_SESSION["cspsrv_ip"] . ":" . $_SESSION["cspsrv_port"] . "/xmlHandler?command=proxy-status")) {
            $status = "1";
        } else {
            $status = "0";
        }
    }
    if ($_SESSION["cspconnchk"] == "0") {
        $status = "1";
    }
    return($status);
}

/* function valVers() {
  require 'config.php';
  require 'includes/debug.php';
  //echo $dbhost;
  //exit();
  $v = ept($h, $s);
  $v2 = ept(dirname(realpath(__DIR__ . '/../index.php')), $s);
  $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(sqlerror());
  mysql_select_db($dbname, $conn);
  //8c298a406786fa34b06cbee8b81a670ecba1e6b4
  $rs = mysql_query("SELECT rndpasschr FROM cmum_settings WHERE rndpasschr = '{$v}' AND rndpasschrlength = '{$v2}' AND id = 1");
  //exit(var_dump("SELECT rndpasschr FROM cmum_settings WHERE rndpasschr = '{$v}' AND rndpasschrlength = '{$v2}'"));
  if (mysql_num_rows($rs) == 0) { //?
  //echo "SELECT rndpasschr FROM cmum_settings WHERE rndpasschr = '{$v}'";
  return true;
  } else {
  mysql_close();
  header("Location: reg.php");
  exit();
  }
  } */

function sqlerror() {
    require("config.php");
    require("includes/settings.php");
    print("<html><head>");
    print("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">");
    print("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" . $charset . "\">");
    print("<title>" . $longtitle . "</title>");
    print("<link href=\"css/main.css\" rel=\"stylesheet\" type=\"text/css\"></head><body>");
    print("<center><br><img src=\"images/warning.png\"><br><br>");
    print("<h1>There was a error connecting to the MySQL server!</h1>");
    print("<strong>MySQL Server Error:<br>" . mysql_error() . "</strong><br><br><br>");
    print("<a href=\"index.php\">Back to main page</a></center>");
    print("</center></body></html>");
    exit;
}

function optimizedb() {
    require("config.php");
    $connopt = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $connopt);
    mysql_query("OPTIMIZE TABLE cmum_admins");
    mysql_query("OPTIMIZE TABLE cmum_failedlogins");
    mysql_query("OPTIMIZE TABLE cmum_profiles");
    mysql_query("OPTIMIZE TABLE cmum_settings");
    mysql_query("OPTIMIZE TABLE cmum_udb");
    mysql_close($connopt);
}

function checkdbver() {
    require("config.php");
    require("includes/settings.php");
    $conndbchk = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conndbchk);
    $sql = mysql_query("SELECT * FROM cmum_settings WHERE id='1'");
    $line = mysql_fetch_array($sql);
    $chkdbver = $line["dbversion"];
    mysql_close($conndbchk);
    if ($chkdbver <> $version) {
        print("<html><head>");
        print("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">");
        print("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" . $charset . "\">");
        print("<title>" . $longtitle . "</title>");
        print("<link href=\"css/main.css\" rel=\"stylesheet\" type=\"text/css\"></head><body>");
        print("<center><br><img src=\"images/warning.png\"><br><br>");
        print("<h1>Incorrect database version for this installation!</h1>");
        print("<strong>Your installed version: " . $version . " - Your database version: " . $chkdbver . "<br>Please run the upgrade tool to upgrade your database!</strong><br><br>");
        print("<a href=\"upgrade.php\">Click here to run the upgrade tool now</a><br><br><br>");
        print("<a href=\"index.php\">Back to main page</a>");
        print("</center></body></html>");
        exit;
    }
}

function getadminname($adminid, $dosql) {
    // 0 = no sql connect
    // 1 = do sql connect
    require("config.php");
    if ($dosql == 1) {
        $connadminchk = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
        mysql_select_db($dbname, $connadminchk);
    }
    $sqladminchk = mysql_query("SELECT * FROM cmum_admins WHERE id='" . $adminid . "'");
    $lineadminchk = mysql_fetch_array($sqladminchk);
    if ($lineadminchk["username"] <> "") {
        $name = $lineadminchk["username"];
    } else {
        $name = "<i>Excluidos administrador!</i>";
    }
    if ($dosql == 1) {
        mysql_close($connadminchk);
    }
    return($name);
}

function getadminid($admname, $dosql) {
    // 0 = no sql connect
    // 1 = do sql connect
    require("config.php");
    if ($dosql == 1) {
        $connadminchk = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
        mysql_select_db($dbname, $connadminchk);
    }
    $sqladminchk = mysql_query("SELECT * FROM cmum_admins WHERE username='" . $admname . "'");
    $lineadminchk = mysql_fetch_array($sqladminchk);
    if ($lineadminchk["id"] <> "") {
        $admid = $lineadminchk["id"];
    } else {
        $admid = "";
    }
    if ($dosql == 1) {
        mysql_close($connadminchk);
    }
    return($admid);
}

function smtpmailer($para, $de, $de_nome, $senha, $assunto, $corpo, $serv) {
    require_once("includes/PHPMailer/class.phpmailer.php");
    global $contato;
    //global $error;
    //global $sucesso;
    //
    //Gambiarra Email ------------//
    /* $serv = 'local';
      if ($serv == "local") {
      $mail = new PHPMailer();
      $mail->CharSet = "UTF-8";
      $mail->IsSMTP();  // Ativar SMTP
      $mail->IsHTML();
      $mail->SMTPDebug = 0;  // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
      $mail->SMTPAuth = true; // Autenticação ativada
      $mail->SMTPSecure = 'ssl'; // SSL REQUERIDO pelo GMail
      $mail->Host = 'mail.cspadmin.com'; // SMTP utilizado
      $mail->Port = 465;    // A porta 465 deverá estar aberta em seu servidor
      //$mail->Username = GUSER;
      //$mail->Username = $de;
      //$mail->Password = $senha;
      $mail->Username = 'painel@cspadmin.com';
      $mail->Password = '@MAX??//';
      $mail->SetFrom($de, $de_nome);
      $mail->Subject = $assunto;
      $mail->Body = $corpo;
      $mail->AddAddress($para);
      $mail->AddBCC($contato);
      if (!$mail->Send()) {
      $msgError = 'Mail error: ' . $mail->ErrorInfo;
      return $msgError;
      //$error = "&erro=1";
      //return false;
      } else {
      //$sucesso = '&sucesso=1';
      return true;
      }
      } */
    ///------------ Fim da Gambiarra --------->
    if ($serv == "gmail") {
        $mail = new PHPMailer();
        $mail->CharSet = "UTF-8";
        $mail->IsSMTP();  // Ativar SMTP
        $mail->IsHTML();
        $mail->SMTPDebug = 0;  // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
        $mail->SMTPAuth = true; // Autenticação ativada
        $mail->SMTPSecure = 'ssl'; // SSL REQUERIDO pelo GMail
        $mail->Host = 'smtp.gmail.com'; // SMTP utilizado
        $mail->Port = 465;    // A porta 465 deverá estar aberta em seu servidor
        //$mail->Username = GUSER;
        $mail->Username = $de;
        $mail->Password = $senha;
        $mail->SetFrom($de, $de_nome);
        $mail->Subject = $assunto;
        $mail->Body = $corpo;
        $mail->AddAddress($para);
        $mail->AddBCC($contato);
        if (!$mail->Send()) {
            $msgError = 'Mail error: ' . $mail->ErrorInfo;
            return $msgError;
            //$error = "&erro=1";
            //return false;
        } else {
            //$sucesso = '&sucesso=1';
            return true;
        }
    }
    if ($serv == "hotmail") {
        $mail = new PHPMailer();
        $mail->CharSet = "UTF-8";
        $mail->IsSMTP();  // Ativar SMTP
        $mail->IsHTML();
        $mail->SMTPDebug = 0;  // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
        $mail->SMTPAuth = true; // Autenticação ativada
        $mail->SMTPSecure = 'tls'; // SSL REQUERIDO pelo GMail
        //$mail->Mailer = "smtp";
        $mail->Host = 'smtp.live.com'; // SMTP utilizado
        $mail->Port = 25;    // A porta 465 deverá estar aberta em seu servidor
        //$mail->Username = GUSER;
        $mail->Username = $de;
        $mail->Password = $senha;
        $mail->SetFrom($de, $de_nome);
        $mail->Subject = $assunto;
        $mail->Body = $corpo;
        $mail->AddAddress($para);
        $mail->AddBCC($contato);
        if (!$mail->Send()) {
            $msgError = 'Mail error: ' . $mail->ErrorInfo;
            return $msgError;
            //$error = "&erro=1";
            //return false;
        } else {
            //$sucesso = '&sucesso=1';
            return true;
        }
    }
    if ($serv == "yahoo") {
        //exit("Yahoo");
        $mail = new PHPMailer();
        $mail->CharSet = "UTF-8";
        $mail->IsSMTP();  // Ativar SMTP
        //$mail->IsMail();
        $mail->IsHTML();
        $mail->SMTPDebug = 1;  // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
        $mail->SMTPAuth = true; // Autenticação ativado
        $mail->SMTPSecure = 'tsl'; // SSL REQUERIDO pelo GMail
        //$mail->Mailer = "smtp";
        $mail->Host = 'smtp.mail.yahoo.com.br'; // SMTP utilizado
        $mail->Port = 587;    // A porta 465 deverá estar aberta em seu servidor
        //$mail->Username = GUSER;
        $mail->Username = $de;
        $mail->Password = $senha;
        $mail->SetFrom($de, $de_nome);
        $mail->Subject = $assunto;
        $mail->Body = $corpo;
        $mail->AddAddress($para);
        $mail->AddBCC($contato);
        if (!$mail->Send()) {
            $msgError = 'Mail error: ' . $mail->ErrorInfo;
            return $msgError;
            //$error = "&erro=1";
            //return false;
        } else {
            //$sucesso = '&sucesso=1';
            return true;
        }
    }
}

function smtpmailer2($para, $de, $de_nome, $senha, $assunto, $corpo, $serv) {
    require_once("includes/PHPMailer/class.phpmailer.php");
    global $contato;
    if ($serv == "gmail") {
        $mail = new PHPMailer();
        $mail->CharSet = "UTF-8";
        $mail->IsSMTP();  // Ativar SMTP
        $mail->IsHTML();
        $mail->SMTPDebug = 1;  // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
        $mail->SMTPAuth = true; // Autenticação ativada
        $mail->SMTPSecure = 'ssl'; // SSL REQUERIDO pelo GMail
        $mail->Host = 'smtp.gmail.com'; // SMTP utilizado
        $mail->Port = 465;    // A porta 465 deverá estar aberta em seu servidor
        //$mail->Username = GUSER;
        $mail->Username = $de;
        $mail->Password = $senha;
        $mail->SetFrom($de, $de_nome);
        $mail->Subject = $assunto;
        $mail->Body = $corpo;
        $mail->AddAddress($para);
        $mail->AddBCC($contato);
        $ret = array();
        /* try {
          $mail->PreSend();
          if ($mail->Send() == true) {
          return true;
          }
          } catch (phpmailerAppException $e) {
          return 'Erro: ' . $e->errorMessage();
          } */

        /* if (!$mail->Send()) {
          //$msgError = 'Mail error: ' . $mail->ErrorInfo;
          //return $msgError;
          $ret['erro'] = $mail->ErrorInfo;
          } else {
          $ret['sucesso'] =        } */
    }
    if ($serv == "hotmail") {
        $mail = new PHPMailer();
        $mail->CharSet = "UTF-8";
        $mail->IsSMTP();  // Ativar SMTP
        $mail->IsHTML();
        $mail->SMTPDebug = 1;  // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
        $mail->SMTPAuth = true; // Autenticação ativada
        $mail->SMTPSecure = 'tls'; // SSL REQUERIDO pelo GMail
        //$mail->Mailer = "smtp";
        $mail->Host = 'smtp.live.com'; // SMTP utilizado
        $mail->Port = 25;    // A porta 465 deverá estar aberta em seu servidor
        //$mail->Username = GUSER;
        $mail->Username = $de;
        $mail->Password = $senha;
        $mail->SetFrom($de, $de_nome);
        $mail->Subject = $assunto;
        $mail->Body = $corpo;
        $mail->AddAddress($para);
        $mail->AddBCC($contato);
        /* if (!$mail->Send()) {
          $msgError = 'Mail error: ' . $mail->ErrorInfo;
          return $msgError;
          } else {
          return true;
          } */
    }
    if ($serv == "yahoo") {
        //exit("Yahoo");
        $mail = new PHPMailer();
        $mail->CharSet = "UTF-8";
        $mail->IsSMTP();  // Ativar SMTP
        //$mail->IsMail();
        $mail->IsHTML();
        $mail->SMTPDebug = 1;  // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
        $mail->SMTPAuth = true; // Autenticação ativado
        $mail->SMTPSecure = 'tsl'; // SSL REQUERIDO pelo GMail
        //$mail->Mailer = "smtp";
        $mail->Host = 'smtp.mail.yahoo.com.br'; // SMTP utilizado
        $mail->Port = 587;    // A porta 465 deverá estar aberta em seu servidor
        //$mail->Username = GUSER;
        $mail->Username = $de;
        $mail->Password = $senha;
        $mail->SetFrom($de, $de_nome);
        $mail->Subject = $assunto;
        $mail->Body = $corpo;
        $mail->AddAddress($para);
        $mail->AddBCC($contato);
        /* (if (!$mail->Send()) {
          $msgError = 'Mail error: ' . $mail->ErrorInfo;
          return $msgError;
          } else {
          return true;
          } */
    }

    try {
        $mail->PreSend();
        if ($mail->Send() == true) {
            return true;
        }
    } catch (phpmailerException $e) {
        return 'Erro: ' . $e->errorMessage();
    }
}

// Query String da Ordenação
function url_query2($chave = array(), $valor = array()) {
    $var_query = array();
    if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != "") {
        parse_str($_SERVER['QUERY_STRING'], $var_query);
        //$var_query[$chave] = $valor;
        for ($i = 0; $i < count($chave); $i++) {
            $var_query[$chave[$i]] = $valor[$i];
        }
    } else {
        for ($i = 0; $i < count($chave); $i++) {
            $var_query[$chave[$i]] = $valor[$i];
        }
        //$var_query[$chave] = $valor;
    }



    return http_build_query($var_query);
}

// Query String da Ordenação
function url_query($chave = array(), $valor = array()) {
    $var_query = array();
    if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != "") {
        parse_str($_SERVER['QUERY_STRING'], $var_query);
    }
    for ($i = 0; $i < count($chave); $i++) {
        $var_query[$chave[$i]] = $valor[$i];
    }



    return http_build_query($var_query);
}

//Arvore Revendas
function arvoreRevendas() {
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    $SQL = "SELECT vw1.*,vw2.total_ativos,IFNULL(vw2.total_por_con,0) AS total_por_con FROM cmum_admins_pais_filhos AS vw1 LEFT JOIN"
            . " cmum_total_logins_ativos AS vw2 ON vw1.id = vw2.id";
    $rs = mysql_query($SQL);

    $_arvore = array();

    while ($reg = mysql_fetch_assoc($rs)) {
        $_arvore[] = (object) $reg;
    }
    $_filhos = array();
    foreach ($_arvore as $_a) {
        $_filhos[$_a->id_pai][] = $_a;
    }
    /* foreach ($_arvore as $_a) {
      if (isset($_filhos[$_a->id])) {
      $_a->_filhos = $_filhos[$_a->id];
      //unset($_a);
      }
      } */
    return $_filhos;
}

//Arvore Revendas Sem Totais
function arvoreRevendasSemTotais() {
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    $SQL = "SELECT * FROM cmum_admins_pais_filhos";
    $rs = mysql_query($SQL);

    $_arvore = array();

    while ($reg = mysql_fetch_assoc($rs)) {
        $_arvore[] = (object) $reg;
    }
    $_filhos = array();
    foreach ($_arvore as $_a) {
        $_filhos[$_a->id_pai][] = $_a;
    }
    /* foreach ($_arvore as $_a) {
      if (isset($_filhos[$_a->id])) {
      $_a->_filhos = $_filhos[$_a->id];
      //unset($_a);
      }
      } */
    return $_filhos;
}

// Arvore limpa
function arvoreRevendas2() {
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    $SQL = "SELECT * FROM cmum_admins_pais_filhos";
    $rs = mysql_query($SQL);

    $_arvore = array();

    while ($reg = mysql_fetch_assoc($rs)) {
        $_arvore[] = (object) $reg;
    }
    $_filhos = array();

    foreach ($_arvore as $_a) {
        $_filhos[$_a->id_pai][] = $_a;
    }

    foreach ($_arvore as $_a) {
        if (isset($_filhos[$_a->id])) {
            $_a->filhos = $_filhos[$_a->id];
        }
    }
    return $_filhos;
}

function arvoreRevendasLista() {
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    $SQL = "SELECT * FROM cmum_admins_pais_filhos";
    $rs = mysql_query($SQL);

    $_arvore = array();

    while ($reg = mysql_fetch_assoc($rs)) {
        $_arvore[$reg['id']] = $reg;
    }

    return $_arvore;
}

//Lista options para select revendas
function listaOptionsRenvendas($arvore, $arvore_lista, $rev_sel = "", $hierarquia) {
    foreach ($arvore as $folha) {
        /* $pref = "";
          $cor = "black";
          if ($folha->hierarquia > 0) {
          $pref = str_repeat("-", $folha->hierarquia * 2) . $folha->pai_login . "->";
          if ($folha->hierarquia == 0) {
          $cor = "black";
          }
          if ($folha->hierarquia == 1) {
          $cor = "red";
          }
          if ($folha->hierarquia == 2) {
          $cor = "green";
          }
          if ($folha->hierarquia == 3) {
          $cor = "blue";
          }
          } */
        $json["id"] = "{$folha->id}";
        $p = base64_encode(json_encode($json));
        //echo $rev_sel . "<br/>" . $p;
        if ($rev_sel == $p) {
            echo '<option value="' . $p . '" selected="true" >' . prefixoRevenda($folha->id, $arvore_lista, $hierarquia) . '</option>';
        } else {
            echo '<option value="' . $p . '">' . prefixoRevenda($folha->id, $arvore_lista, $hierarquia) . '</option>';
        }

        if (isset($folha->filhos)) {
            listaOptionsRenvendas($folha->filhos, $arvore_lista, $rev_sel, $hierarquia);
        }
    }
}

//Prefixo revendas
function prefixoRevenda($revenda = 0, $arvore = array(), $hierarquia) {//rev1
    $rev_atual = $arvore[$revenda];
    $prefixo = $rev_atual['username'];
    if ($rev_atual['hierarquia'] > $hierarquia) {
        return prefixoRevenda($rev_atual['id_pai'], $arvore, $hierarquia) . '->' . $prefixo;
    }
    return $prefixo;
}

// Total Login Ativos e Por Maximo de Conexões
function totalPorRevendasSub($rev, $_filhos = array(), $t = 0, $perfil = NULL) { // ID Revenda, $arvoreRevendas,$t=0 Logins Ativos, $t=1 Logins Por Conexao
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    $s = 0;
    //sleep(1);
    foreach ($_filhos as $pai => $_filho) {
        if ($pai == $rev) {
            foreach ($_filho as $_f) {
                $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_ativos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_ativos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$_f->id}'";
                if (is_numeric($perfil)) {
                    $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_ativos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_ativos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$_f->id}'";
                }
                $rs = mysql_query($SQL);
                $sub_rev = mysql_fetch_assoc($rs);
                if ($t == 0) {
                    $s += $sub_rev['total_ativos']; // Pode ter erros                   
                } else {
                    //$s+= $_f->total_por_con;
                    $s += $sub_rev['total_por_con'];
                }

                if (isset($_filhos[$_f->id])) {
                    $s += totalPorRevendasSub($_f->id, $_filhos, $t, $perfil);
                }
            }
        }
    }
    return $s;
}

//Totais sub revendas
function totalPorRevendasSubTestes($rev, $_filhos = array(), $t = 0, $perfil = NULL) { // ID Revenda, $arvoreRevendas,$t=0 Logins Ativos, $t=1 Logins Por Conexao
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    $s = 0;
    //sleep(1);
    foreach ($_filhos as $pai => $_filho) {
        if ($pai == $rev) {
            foreach ($_filho as $_f) {
                $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_testes_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_testes_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$_f->id}'";
                if (is_numeric($perfil)) {
                    $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_testes_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_testes_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$_f->id}'";
                }
                $rs = mysql_query($SQL);
                $sub_rev = mysql_fetch_assoc($rs);
                if ($t == 0) {
                    $s += $sub_rev['total_ativos']; // Pode ter erros                   
                } else {
                    //$s+= $_f->total_por_con;
                    $s += $sub_rev['total_por_con'];
                }

                if (isset($_filhos[$_f->id])) {
                    $s += totalPorRevendasSubTestes($_f->id, $_filhos, $t, $perfil);
                }
            }
        }
    }
    return $s;
}

//Totais sub revendas desativados
function totalPorRevendasSubDesat($rev, $_filhos = array(), $t = 0, $perfil = NULL) { // ID Revenda, $arvoreRevendas,$t=0 Logins Ativos, $t=1 Logins Por Conexao
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    $s = 0;
    //sleep(1);
    foreach ($_filhos as $pai => $_filho) {
        if ($pai == $rev) {
            foreach ($_filho as $_f) {
                $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_desativados_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_desativados_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$_f->id}'";
                if (is_numeric($perfil)) {
                    $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_desativados_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_desativados_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$_f->id}'";
                }
                $rs = mysql_query($SQL);
                $sub_rev = mysql_fetch_assoc($rs);
                if ($t == 0) {
                    $s += $sub_rev['total_ativos']; // Pode ter erros                   
                } else {
                    //$s+= $_f->total_por_con;
                    $s += $sub_rev['total_por_con'];
                }

                if (isset($_filhos[$_f->id])) {
                    $s += totalPorRevendasSubDesat($_f->id, $_filhos, $t, $perfil);
                }
            }
        }
    }
    return $s;
}

//totais logins sub revendas vencidos
function totalPorRevendasSubVenc($rev, $_filhos = array(), $t = 0, $perfil = NULL) { // ID Revenda, $arvoreRevendas,$t=0 Logins Ativos, $t=1 Logins Por Conexao
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    $s = 0;
    //sleep(1);
    foreach ($_filhos as $pai => $_filho) {
        if ($pai == $rev) {
            foreach ($_filho as $_f) {
                $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_vencidos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_vencidos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id`)),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$_f->id}'";
                if (is_numeric($perfil)) {
                    $SQL = "select `a`.`id` AS `id`,`a`.`username` AS `username`,(select count(`vw1`.`name`) from `cmum_logins_vencidos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')) AS `total_ativos`,ifnull((select sum(`vw1`.`maxconnections`) from `cmum_logins_vencidos_por_rev` `vw1` where (`vw1`.`id_rev` = `a`.`id` AND vw1.id_profile = '{$_GET['perfil']}')),0) AS `total_por_con` from `cmum_admins` `a` where a.id = '{$_f->id}'";
                }
                $rs = mysql_query($SQL);
                $sub_rev = mysql_fetch_assoc($rs);
                if ($t == 0) {
                    $s += $sub_rev['total_ativos']; // Pode ter erros                   
                } else {
                    //$s+= $_f->total_por_con;
                    $s += $sub_rev['total_por_con'];
                }

                if (isset($_filhos[$_f->id])) {
                    $s += totalPorRevendasSubVenc($_f->id, $_filhos, $t, $perfil);
                }
            }
        }
    }
    return $s;
}

// Total Login Ativos e Por Maximo de Conexões 2
function totalPorRevendasSub2($rev, $_filhos = array(), $t = 0) { // ID Revenda, $arvoreRevendas,$t=0 Logins Ativos, $t=1 Logins Por Conexao
    $s = 0;
    foreach ($_filhos as $pai => $_filho) {
        if ($pai == $rev) {
            foreach ($_filho as $_f) {
                if ($t == 0) {
                    $s+= $_f->total_ativos;
                } else {
                    $s+= $_f->total_por_con;
                }

                if (isset($_filhos[$_f->id])) {
                    $s += totalPorRevendasSub($_f->id, $_filhos, $t);
                }
            }
        }
    }
    return $s;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '_-,', '+/='));
}

function base64_url_encode($input) {
    return strtr(base64_encode($input), '+/=', '_-,');
}

// saldo logins
function saldo_revenda() {
    $arg = func_get_args();

    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    //Pegando a quantidade definida pra revenda
    $SQL = "SELECT quantidade FROM "
            . "cmum_limite_logins_profiles WHERE "
            . "id_revenda='{$arg[0]}' AND id_profiles='{$arg[1]}'";
    $rs = mysql_query($SQL);
    $limite_rev = 0;
    if ($rs !== false && mysql_num_rows($rs) > 0) {
        while ($row = mysql_fetch_assoc($rs)) {
            $limite_rev = $row['quantidade'];
        }
    }
    //pega os logins cadastrados
    $SQL = "SELECT COUNT(*) AS total_cad FROM "
            . "cmum_logins_com_perfis_limpos WHERE "
            . "addedby='{$arg[0]}' AND perfil_lp='{$arg[1]}' AND enabled='true'";
    $rs = mysql_query($SQL);
    $total_cad = 0;
    if ($rs !== false && mysql_num_rows($rs) > 0) {
        while ($row = mysql_fetch_assoc($rs)) {
            $total_cad = $row['total_cad'];
        }
    }
    //pega as subrevendas
    $SQL = "SELECT id FROM "
            . "cmum_admins WHERE "
            . "addedby='{$arg[0]}' AND enabled='true'";
    $rs = mysql_query($SQL);
    $revs = '';
    if ($rs !== false && mysql_num_rows($rs) > 0) {
        while ($row = mysql_fetch_assoc($rs)) {
            $revs .= $row["id"] . ',';
        }
    }
    $revs = substr($revs, 0, -1);
    //soma a quantidade de todas as subs
    $SQL = "SELECT SUM(quantidade) as total_sub FROM "
            . "cmum_limite_logins_profiles WHERE "
            . "id_revenda IN ({$revs}) AND id_profiles='{$arg[1]}'";
    $rs = mysql_query($SQL);
    $total_sub = 0;
    if ($rs !== false && mysql_num_rows($rs) > 0) {
        if (mysql_num_rows($rs) > 0) {
            while ($row = mysql_fetch_assoc($rs)) {
                $total_sub = $row['total_sub'];
            }
        }
    }
    return $limite_rev - ($total_cad + $total_sub);
}

// saldo revenda 2 
// 
function saldo_revenda2($id_rev_atual = null, $id_rev_exc = null) { //args: lista ids revendas
    require("config.php");
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die("ERROR! Não Conectado ao Banco de Dados..");
    mysql_select_db($dbname, $conn);
    // pegando os ativos da revenda atual
    /*
      id	int(11)	Não 	0
      username	tinytext	Não
      total_ativos	bigint(21)	Sim 	NULL
      total_por_con	double	Não
     */
    $SQL = "SELECT total_ativos FROM cmum_total_logins_ativos WHERE id='{$id_rev_atual}'";
    $rs = mysql_query($SQL);
    // qtd logins ativos
    $qtd_logins_ativos = 0;
    if (mysql_num_rows($rs) > 0) {
        while ($row = mysql_fetch_assoc($rs)) {
            $qtd_logins_ativos = $row['total_ativos'];
        }
    }
    // qtd liberado pra revenda atual
    $SQL = "SELECT qtd_logins FROM cmum_admins WHERE id='{$id_rev_atual}'";

    $rs = mysql_query($SQL);
    $qtd_logins_rev_atual = 0;

    if (mysql_num_rows($rs) > 0) {
        while ($row = mysql_fetch_assoc($rs)) {
            $qtd_logins_rev_atual = $row['qtd_logins'];
        }
    }

    //qtd liberado para as revendas
    $SQL = "SELECT SUM(qtd_logins) AS total_lib_rev FROM cmum_admins WHERE addedby='{$id_rev_atual}' AND enabled='true'";
    if (is_numeric($id_rev_exc)) {
        $SQL = "SELECT SUM(qtd_logins) AS total_lib_rev FROM cmum_admins WHERE addedby='{$id_rev_atual}' AND enabled='true' AND id <> '$id_rev_exc'";
    }
    $rs = mysql_query($SQL);
    $total_lib_rev = 0;

    if (mysql_num_rows($rs) > 0) {
        while ($row = mysql_fetch_assoc($rs)) {
            $total_lib_rev = $row['total_lib_rev'];
        }
    }
    return ($qtd_logins_rev_atual - $qtd_logins_ativos - $total_lib_rev);
}

function listaIdsRenvendasSub($_arv, &$a) { // arvoreRevendas2() e array referencia
    foreach ($_arv as $folha) {
        $a[] = $folha->id;
        if (isset($folha->filhos)) {
            listaIdsRenvendasSub($folha->filhos, $a);
        }
    }
}

function arrayListaRevenda($revenda = 0, $arvore = array(), $hierarquia, &$a = array()) {//rev1
    $rev_atual = $arvore[$revenda];
    $a[] = $rev_atual['id'];
    if ($rev_atual['hierarquia'] > $hierarquia) {
        return arrayListaRevenda($rev_atual['id_pai'], $arvore, $hierarquia, $a);
    }
}

eval(base64_decode("ZnVuY3Rpb24gaXNfcGFpbmVsKCkgew0KICAgICRpc19wYWluZWwgPSBfX0RJUl9fIC4gRElSRUNUT1JZX1NFUEFSQVRPUiAuICIuLiIgLiBESVJFQ1RPUllfU0VQQVJBVE9SIC4gImlzX3BhaW5lbC5waHAiOw0KICAgIGlmICghZmlsZV9leGlzdHMoJGlzX3BhaW5lbCkpIHsNCiAgICAgICAgcmV0dXJuIGZhbHNlOw0KICAgIH0NCiAgICByZXR1cm4gc3RyX3JlcGxhY2UoIlxcIiwgIi8iLCBkaXJuYW1lKHJlYWxwYXRoKCRpc19wYWluZWwpKSk7DQp9"));

function v() {
    eval(base64_decode("aWYoIWZ1bmN0aW9uX2V4aXN0cygiaXNfcGFpbmVsIikpew0KICAgICAgICBleGl0KCJFcnJvIEludGVybm8iKTsgICAgICAgIA0KICAgIH0="));
    eval(base64_decode("cmVxdWlyZSgiY29uZmlnLnBocCIpOw0KICAgICRkYiA9IG5ldyBteXNxbGkoJGRiaG9zdCwgJGRidXNlciwgJGRicGFzcywgJGRibmFtZSk7DQogICAgJFNRTCA9ICJTRUxFQ1QgKiBGUk9NIGNtdW1fcGFpbmVsX2F0aXZhY2FvIFdIRVJFIDE9MSBPUkRFUiBCWSBJRCBERVNDIExJTUlUIDEiOw0KICAgICRycyA9ICRkYi0+cXVlcnkoJFNRTCk7DQogICAgJGF0aXZhY2FvID0gJHJzLT5mZXRjaF9hc3NvYygpOw=="));   
    eval(base64_decode("bGlzdCgkdmVuY2ltZW50bywgJGRpcl9pbnN0YWwpID0gZXhwbG9kZSgiLiIsIGRwdCgkYXRpdmFjYW9bImNoYXZlMSJdLCAic2RlYnVnIikpOw0KICAgIGxpc3QoJHZlbmNpbWVudG8sICRpcF9pbnN0YWwpID0gZXhwbG9kZSgiLiIsIGRwdCgkYXRpdmFjYW9bImNoYXZlMiJdLCAic2RlYnVnIikpOyAgICANCiAgICAkaXNfcGFpbmVsID0gaXNfcGFpbmVsKCk7"));
    eval(base64_decode("aWYgKCRkaXJfaW5zdGFsICE9PSAkaXNfcGFpbmVsKSBleGl0KGhlYWRlcigiTG9jYXRpb246IGluZGV4LnBocD9lcnJvcj05IikpOyAgICANCiAgICAkaXBfbG9jYWwgPSAkX1NFUlZFUlsiUkVNT1RFX0FERFIiXTsNCiAgICBpZiAoJGlwX2luc3RhbCAhPT0gJGlwX2xvY2FsKSBleGl0KGhlYWRlcigiTG9jYXRpb246IGluZGV4LnBocD9lcnJvcj05IikpOyAgICANCiAgICAkaG9qZSA9IHRpbWUoKTsNCiAgICBpZiAoc3RydG90aW1lKCR2ZW5jaW1lbnRvKSA8ICRob2plKSBleGl0KGhlYWRlcigiTG9jYXRpb246IGluZGV4LnBocD9lcnJvcj05IikpOw=="));
}
eval(base64_decode("digpOw=="));
//var_dump(is_painel());
