<?php
require("config.php");
require("includes/debug.php");
require("includes/functions.php");
require("includes/logincheck.php");
require("includes/settings.php");
//require("includes/admincheck.php");

$tool = "";
$toolselect = "";

$admId = $_SESSION["adminid"];
$level = $_SESSION["adminlevel"];

if (isset($_POST["subimportxml"]) and $_POST["subimportxml"] == "Importar") {
    //$toolselect = "Importar Usuarios (CSP XML)";


    $cspxmlusers = $_POST["cspxmlusers"];
    $cspxmlusers = str_replace("<auth-config>", "", $cspxmlusers);
    $cspxmlusers = str_replace("</auth-config>", "", $cspxmlusers);
    $cspxmlusers = str_replace("</user-manager>", "", $cspxmlusers);
    $cspxmlusers = str_replace("<user-manager class=\"com.bowman.cardserv.SimpleUserManager\" allow-on-failure=\"true\" log-failures=\"true\">", "", $cspxmlusers);
    $cspxmlusers = str_replace("<user-manager class=\"com.bowman.cardserv.SimpleUserManager\" allow-on-failure=\"false\" log-failures=\"false\">", "", $cspxmlusers);
    $cspxmlusers = str_replace("<user-manager class=\"com.bowman.cardserv.SimpleUserManager\" allow-on-failure=\"true\" log-failures=\"false\">", "", $cspxmlusers);
    $cspxmlusers = str_replace("<user-manager class=\"com.bowman.cardserv.SimpleUserManager\" allow-on-failure=\"false\" log-failures=\"true\">", "", $cspxmlusers);
    $cspxmlusers = str_replace("<user-manager class=\"com.bowman.cardserv.SimpleUserManager\">", "", $cspxmlusers);
    $cspxmlusers = str_replace("display-name", "displayname", $cspxmlusers);
    $cspxmlusers = str_replace("ip-mask", "ipmask", $cspxmlusers);
    $cspxmlusers = str_replace("max-connections", "maxconnections", $cspxmlusers);
    $cspxmlusers = str_replace("map-exclude", "mapexclude", $cspxmlusers);
    $cspxmlusers = str_replace("email-address", "emailaddress", $cspxmlusers);
    $cspxmlusers = str_replace("ecm-rate", "ecmrate", $cspxmlusers);
    $cspxmlusers = str_replace("start-date", "startdate", $cspxmlusers);
    $cspxmlusers = str_replace("expire-date", "expiredate", $cspxmlusers);

    $cspuserlines = explode("\n", $cspxmlusers);

    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);

    $i = 0;
    $x = 0; // logins importados com sucesso
    $y = 0; // erros logins
    $e = 0; // se já tem login cadastrado

    $userimportlist = "";
    $userexistlist = "";
    $importresult = "";
    $impdonecolor = "#347C2C";

    $c_saldo = 0;

    foreach ($cspuserlines as $i => $value) {

        libxml_use_internal_errors(true);

        $cspusersxml = simplexml_load_string(stripslashes($cspuserlines[$i]));

        if (!$cspusersxml) {

            $y++;

            // verifica se o login importado tem senha, profiles
        } elseif ($cspusersxml->attributes()->name == "" or $cspusersxml->attributes()->password == "") {

            $y++;
            
        } else {

            $username = $cspusersxml->attributes()->name;
            $uesql = mysql_query("SELECT * FROM cmum_udb WHERE name='" . $username . "'");
            $foundusers = mysql_num_rows($uesql);

            if ($foundusers == 0) {

                $password = $cspusersxml->attributes()->password;
                $displayname = $cspusersxml->attributes()->displayname;
                $ipmask = $cspusersxml->attributes()->ipmask;
                $profiles = $cspusersxml->attributes()->profiles;
                $maxconnections = intval($cspusersxml->attributes()->maxconnections);
                $admin = $cspusersxml->attributes()->admin;
                $enabled = $cspusersxml->attributes()->enabled;
                $mapexclude = $cspusersxml->attributes()->mapexclude;
                $debug = $cspusersxml->attributes()->debug;
                $email = $cspusersxml->attributes()->emailaddress;
                $ecmrate = $cspusersxml->attributes()->ecmrate;
                $startdate = (isset($cspusersxml->attributes()->startdate) && $cspusersxml->attributes()->startdate != "") ? $cspusersxml->attributes()->startdate : date('Y-m-d');
                $expiredate = date('Y-m-d H:i:s', strtotime(str_replace("/", "-", $cspusersxml->attributes()->expiredate)));
                $added = date('Y-m-d H:i:s', strtotime(str_replace("/", "-", $startdate)));

                $comment = "";
                $usrgroup = "";
                $improf = explode(" ", $profiles);
                $convporf = profiles_por_csp_value($improf);
                
                $id_rev = isset($_GET['id']) ? $_GET['id'] : $_SESSION["adminid"];

                $SQL = "SELECT level,rev_pre FROM cmum_admins WHERE id='{$id_rev}'";

                $rs = mysql_query($SQL);
                $level_rev = false;

                while ($row = mysql_fetch_assoc($rs)) {

                    $level_rev = $row['level'];
                    $rev_pre = $row['rev_pre'];
                }

                //verifica o saldo pre pago e pos pago

                if ($rev_pre == '1') {

                    $_saldo_revenda_pre = saldo_revenda_pre($id_rev);
                    $saldo_revenda_pre = $_saldo_revenda_pre[$id_rev];

                    $valor_base_pre = valor_base_pre($expiredate);

                    if ($saldo_revenda_pre['saldo_real'] < ($valor_base_pre * $maxconnections)) {
                        
                        $c_saldo++;
                        continue;
                        
                    }
                } else {

                    $saldo_rev_pos = saldo_revenda2($id_rev);

                    if ($saldo_rev_pos <= 0) {

                        $c_saldo++;
                        continue;
                    }
                }


                $convporf = serialize($convporf);
                
                //var_dump($username .": ",$convporf);exit();

                mysql_query("INSERT INTO cmum_udb (name,password,displayname,ipmask,profiles,maxconnections,admin,enabled,mapexclude,debug,comment,email,usrgroup,ecmrate,startdate,expiredate,added,addedby,changed,changedby) VALUES ('" . $username . "','" . $password . "','" . $displayname . "','" . $ipmask . "','" . $convporf . "','" . $maxconnections . "','" . strtolower($admin) . "','" . strtolower($enabled) . "','" . strtolower($mapexclude) . "','" . strtolower($debug) . "','" . $comment . "','" . $email . "','" . $usrgroup . "','" . $ecmrate . "','" . $startdate . "','" . $expiredate . "','" . $added . "','" . $id_rev . "','','{$_SESSION["adminid"]}')");

                if($rev_pre == '1'){
                    
                    atualiza_cota_pre($id_rev, 0, ($valor_base_pre * $maxconnections));
                    
                }
                
                $x++;

                unset($convporf);

                $sql = "";
                $uesql = "";
                $foundusers = "";
                $userimportlist = $userimportlist . $username . "<br>";
            } else {

                $e++;
                $userexistlist = $userexistlist . $username . "<br>";
            }
        }
    }

    mysql_close($conn);
    
    
    

    if ($x <> 0 and $e <> 0) {

        $importresult = "<br/><br/>Listando os Usuarios Importados:<br/>" . $userimportlist . "<br/>Lista de usuários não forma importados, pois já existem:<br>" . $userexistlist;
        $impdonecolor = "#FF6600";
    }
    if ($x <> 0 and $e == 0) {

        $importresult = "<br/><br/>Listando os Usuarios Importados:<br>" . $userimportlist;
    }
    if ($x == 0 and $e <> 0) {

        $importresult = "<br><br>Lista de usuários importado, pois já existem:<br>" . $userexistlist;
        $impdonecolor = "#FF0000";
    }
    if ($y <> 0) {

        if ($x == 0) {

            $toolstatus = "<font color=\"#FF0000\">" . $x . " Usuários importados ao banco de dados. Ocorreu " . $y . " Erros.  Valores vazios em usuários ou senha." . $importresult . "</font>";
        } else {

            $toolstatus = "<font color=\"#FF6600\">" . $x . " Usuários importados com êxito. Mas houve" . $y . " Erros. Valores vazios em usuários ou senha" . $importresult . "</font>";
        }
    } else {

        $toolstatus = "<font color=\"" . $impdonecolor . "\">" . $x . " Usuários importados com êxito" . $importresult . "</font>";
    }
    if ($c_saldo > 0) {

        $toolstatus.= '<p style="color: red">' . $c_saldo . ' logins não foram importados por que utltrapassou o saldo disponivel</p>';
    }

    $tool = "tools/imusrxmldone.php";
    $toolselect = "Importar Usuarios (CSP XML)";
}

// Ferramentas para limpeza do banco de dados.
if (isset($_POST["subemptyudb"]) and $_POST["subemptyudb"] == "Yes") {
    $adminpassword = sha1($_POST["adminpassword"]);
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $sql = mysql_query("SELECT * FROM cmum_admins WHERE username='" . $_SESSION["loginuser"] . "'");
    while ($line = mysql_fetch_array($sql)) {
        if ($adminpassword == $line["password"]) {
            $esql = mysql_query("TRUNCATE TABLE cmum_udb");
            $emptyudbstatus = "<font color=\"#347C2C\">User database successfully erased!</font>";
            $tool = "tools/emptyudbdone.php";
            $toolselect = "Empty user database";
            mysql_close($conn);
        } else {
            $emptyudbstatus = "<font color=\"#FF0000\">Password didn't match!</font>";
            $tool = "tools/emptyudb.php";
            $toolselect = "Empty user database";
            mysql_close($conn);
        }
    }
}

if (isset($_POST["subendiudb"]) and $_POST["subendiudb"] == "Enable all") {
    $adminpassword = sha1($_POST["adminpassword"]);
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $sql = mysql_query("SELECT * FROM cmum_admins WHERE username='" . $_SESSION["loginuser"] . "'");
    while ($line = mysql_fetch_array($sql)) {
        if ($adminpassword == $line["password"]) {
            $ensql = mysql_query("SELECT * FROM cmum_udb");
            while ($line = mysql_fetch_array($ensql)) {
                mysql_query("UPDATE cmum_udb SET enabled='true' WHERE id='" . $line["id"] . "'");
            }
            $endiudbstatus = "<font color=\"#347C2C\">All users have been enabled!</font>";
            $tool = "tools/endiudbdone.php";
            $toolselect = "Enable/disable all users";
            mysql_close($conn);
        } else {
            $endiudbstatus = "<font color=\"#FF0000\">Password didn't match!</font>";
            $tool = "tools/endiudb.php";
            $toolselect = "Enable/disable all users";
            mysql_close($conn);
        }
    }
}

if (isset($_POST["subendiudb"]) and $_POST["subendiudb"] == "Disable all") {
    $adminpassword = sha1($_POST["adminpassword"]);
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $sql = mysql_query("SELECT * FROM cmum_admins WHERE username='" . $_SESSION["loginuser"] . "'");
    while ($line = mysql_fetch_array($sql)) {
        if ($adminpassword == $line["password"]) {
            $disql = mysql_query("SELECT * FROM cmum_udb");
            while ($line = mysql_fetch_array($disql)) {
                mysql_query("UPDATE cmum_udb SET enabled='false' WHERE id='" . $line["id"] . "'");
            }
            $endiudbstatus = "<font color=\"#347C2C\">All users have been disabled!</font>";
            $tool = "tools/endiudbdone.php";
            $toolselect = "Enable/disable all users";
            mysql_close($conn);
        } else {
            $endiudbstatus = "<font color=\"#FF0000\">Password didn't match!</font>";
            $tool = "tools/endiudb.php";
            $toolselect = "Enable/disable all users";
            mysql_close($conn);
        }
    }
}

if (isset($_POST["subdeldisusr"]) and $_POST["subdeldisusr"] == "Yes") {
    $adminpassword = sha1($_POST["adminpassword"]);
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);
    $sql = mysql_query("SELECT * FROM cmum_admins WHERE username='" . $_SESSION["loginuser"] . "'");
    while ($line = mysql_fetch_array($sql)) {
        if ($adminpassword == $line["password"]) {
            $deldisql = mysql_query("SELECT * FROM cmum_udb WHERE enabled='false'");
            while ($line = mysql_fetch_array($deldisql)) {
                mysql_query("DELETE FROM cmum_udb WHERE id='" . $line["id"] . "'");
            }
            $deldisusrstatus = "<font color=\"#347C2C\">All disabled users have been removed!</font>";
            $tool = "tools/deldisusrdone.php";
            $toolselect = "Delete disabled users";
            mysql_close($conn);
        } else {
            $deldisusrstatus = "<font color=\"#FF0000\">Password didn't match!</font>";
            $tool = "tools/deldisusr.php";
            $toolselect = "Delete disabled users";
            mysql_close($conn);
        }
    }
}

if (isset($_POST["subupdatecspudb"]) and $_POST["subupdatecspudb"] == "Yes") {
    $updatecspudbstatus = updatecspudb();
    $tool = "tools/updatecspudbdone.php";
    $toolselect = "Update CSP users";
}

if (isset($_POST["bimcspprof"]) and $_POST["bimcspprof"] == "Import") {
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or sqlerror();
    mysql_select_db($dbname, $conn);

    $i = 0;
    $e = 0;
    $pfexists = "";
    $pfimported = "";

    $cspvalue = $_POST["cspvalue"];
    $profilename = $_POST["profilename"];
    $cvnum = count($cspvalue);

    foreach ($cspvalue as $x => $value) {
        $cpsql = mysql_query("SELECT * FROM cmum_profiles WHERE value='" . $cspvalue[$x] . "' AND bloqueado='0'");
        $foundcspprof = mysql_num_rows($cpsql);
        if ($foundcspprof == 0 and $cspvalue[$x] <> "") {
            $pnsql = mysql_query("SELECT * FROM cmum_profiles WHERE name='" . $profilename[$x] . "' AND bloqueado='0'");
            $foundprofname = mysql_num_rows($pnsql);
            if ($foundprofname == 0 and $profilename[$x] <> "") {
                mysql_query("INSERT INTO cmum_profiles (name,value) VALUES ('" . $profilename[$x] . "','" . $cspvalue[$x] . "')");
                $i++;
                $pfimported = $pfimported . $profilename[$x] . " (" . $cspvalue[$x] . ")<br>";
            } else {
                $e++;
                $pfexists = $pfexists . $profilename[$x] . " (" . $cspvalue[$x] . ")<br>";
            }
        } else {
            $e++;
            $pfexists = $pfexists . $profilename[$x] . " (" . $cspvalue[$x] . ")<br>";
        }
    }

    if ($i <> 0 and $e <> 0) {
        $importresult = "<br><br>The following profiles where imported:<br>" . $pfimported . "<br>The following profiles where not imported due to duplicates:<br>" . $pfexists;
        $impdonecolor = "#FF6600";
    }
    if ($i <> 0 and $e == 0) {
        $importresult = "<br><br>The following profiles where imported:<br>" . $pfimported;
        $impdonecolor = "#347C2C";
    }
    if ($i == 0 and $e <> 0) {
        $importresult = "<br><br>The following profiles where not imported due to duplicates:<br>" . $pfexists;
        $impdonecolor = "#FF0000";
    }
    if ($e <> 0) {
        if ($i == 0) {
            $toolstatus = "<font color=\"#FF0000\">" . $i . " profiles imported into database! There were " . $e . " duplicates!" . $importresult . "</font>";
        } else {
            $toolstatus = "<font color=\"#FF6600\">" . $i . " profiles successfully imported into database! But there were " . $e . " duplicates!" . $importresult . "</font>";
        }
    } else {
        $toolstatus = "<font color=\"" . $impdonecolor . "\">" . $i . " profiles successfully imported into database!" . $importresult . "</font>";
    }
    mysql_close($conn);
    $tool = "tools/imcspprofilesdone.php";
    $toolselect = "Import profiles from CSP";
}

if (isset($_POST["suboptdb"]) and $_POST["suboptdb"] == "Yes") {
    $updatecspudbstatus = optimizedb();
    $tool = "tools/optimizedbdone.php";
    $toolselect = "Optimize database";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Choose a tool...") {
    $tool = "";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Enable/disable all users") {
    $tool = "tools/endiudb.php";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Delete disabled users") {
    $tool = "tools/deldisusr.php";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Empty user database") {
    $tool = "tools/emptyudb.php";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Update CSP users") {
    $tool = "tools/updatecspudb.php";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Import profiles from CSP") {
    $tool = "tools/imcspprofiles.php";
}

if ((isset($_POST["choosetool"]) and $_POST["choosetool"] == "Importar Usuarios (CSP XML)")) {
    $tool = "tools/imusrxml.php";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Importar Usuarios (CSV)") {
    $tool = "tools/imusrcsv.php";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Exportar Usuarios (CSP XML)") {
    $tool = "tools/expusrxml.php";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Export users (CSV)") {
    $tool = "tools/expusrcsv.php";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Optimize database") {
    $tool = "tools/optimizedb.php";
}
//Codigo para lixeira
if (isset($_POST["Limpar"])) {

    //var_dump($_POST);
    $param = json_decode(base64_decode($_POST['p']), true);
    array_walk($param, function(&$param) {
        htmlentities($param);
    });
    //strtoupper($pfimported);
    //var_dump($param);
    //exit();
    $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    //var_dump($conn);
    //exit("Lixeira");
    $n_dias = $_POST["adias"];
    $diasAntes = date("Y-m-d H:i:s", strtotime("-{$n_dias} day"));
    $strDel = 'DELETE FROM cmum_udb';
    if (isset($_POST["opc_logins"])) {
        if ($_POST["opc_logins"] == "1") {
            $strDel .= " WHERE enabled='false'";
        }
        if ($_POST["opc_logins"] == "2") {
            $strDel .= " WHERE expiredate < '{$diasAntes}'";
        }
    }
    if ($param["id"] != "0") {
        //$strDel = "DELETE FROM cmum_udb WHERE expiredate < '{$diasAntes}'"; 
        $strDel .= " AND addedby='{$param["id"]}'";
    }

    $status = "Dados";
    if ($conn->query($strDel)) {
        $n_linhas = $conn->affected_rows;
        $status = "Total de ({$n_linhas}) Logins, de ({$n_dias}) dias atrás, limpos com sucesso.";
    }
    $tool = "tools/lixeira.php";
}
if (isset($_POST['servidor'])) {
    //var_dump($_POST);
    $id_serv = trim($_POST['servidor']);

    $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    if ($id_serv == "0") {
        $SQL = "SELECT * FROM cmum_csp_config";
    } else {
        $SQL = "SELECT * FROM cmum_csp_config WHERE id='{$id_serv}'";
    }

    $rs = $conn->query($SQL);
    $reshares = array();
    $csps = array();
    if ($rs->num_rows > 0) {
        //$csp = $rs->fetch_assoc();
        while ($row = $rs->fetch_assoc()) {
            $csps[] = $row;
        }
    }
    //var_dump($csps);
    /*
      id	int(11)	Não
      ip_serv	varchar(50)	Não
      porta_serv	varchar(50)	Não
      user_serv	varchar(50)	Não
      senha_serv	varchar(50)	Não
      protocol_serv	varchar(50)	Não
      desc_serv
     */
    //var_dump($csp);
    //Conectando ao servidor
    foreach ($csps as $csp) {
        $url = $csp["protocol_serv"] . "://" . $csp["ip_serv"] . ":" . $csp["porta_serv"] . "/xmlHandler?command=proxy-users";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERPWD, $csp["user_serv"] . ":" . $csp["senha_serv"]);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5); // TIME OUT is 5 seconds
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        $dados_csp = $response;
        //header("Content-type: text/xml; charset=utf-8");
        $xml = simplexml_load_string($dados_csp);
        $total_logins = (int) $xml->{"proxy-users"}->attributes()->count;

        for ($i = 0; $i <= $total_logins; $i++) {
            if ((isset($_POST['busca_ip']) && $_POST['busca_ip'] != "") && isset($xml->{"proxy-users"}->user[$i]->session) && \preg_match('/^(' . $_POST['busca_ip'] . ')/', $xml->{"proxy-users"}->user[$i]->session->attributes()->host)) {
                $xml->{"proxy-users"}->user[$i]->id_servidor = $csp['id'];
                $xml->{"proxy-users"}->user[$i]->servidor = $csp['desc_serv'];
                $reshares[] = $xml->{"proxy-users"}->user[$i];
            } else {
                if ((!isset($_POST['busca_ip']) || $_POST['busca_ip'] == "") && (isset($xml->{"proxy-users"}->user[$i]->session) && $xml->{"proxy-users"}->user[$i]->session->attributes()->active != "false") && preg_match('/[Z]/', $xml->{"proxy-users"}->user[$i]->session->attributes()->flags)) {
                    $xml->{"proxy-users"}->user[$i]->id_servidor = $csp['id'];
                    $xml->{"proxy-users"}->user[$i]->servidor = $csp['desc_serv'];
                    $reshares[] = $xml->{"proxy-users"}->user[$i];
                }
            }
        }
    }

    $tool = "tools/resharehunt.php";
    $toolselect = "Pegar Reshare";
}

if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Lixeira") {
    $tool = "tools/lixeira.php";
}
if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Pegar Reshare") {
    $tool = "tools/resharehunt.php";
    $toolselect = "Pegar Reshare";
}
if (isset($_GET['impuser']) && !isset($_POST["cspxmlusers"])) {
    $tool = "tools/imusrxml.php";

    if ($_SESSION["adminlevel"] != "0") {
        $id = $_GET['id'];
        $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
        $SQL = "SELECT id,addedby FROM cmum_admins WHERE id='{$id}'";
        $rs = $conn->query($SQL);
        $adm = $rs->fetch_assoc();
        //var_dump($adm);
        if ($adm['id'] != $_SESSION['adminid'] && $_SESSION['adminid'] != $adm['addedby']) {
            exit('Chamada Invalida' . $adm['id']);
        }
    }
}
if (isset($_GET['expuser'])) {
    $tool = "tools/expusrxml.php";
    $toolselect = "Exportar Usuarios (CSP XML)";
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title><?php print($longtitle); ?></title>
        <link rel="shortcut icon" href="favicon.ico"/>
        <link rel="apple-touch-icon" href="favicon.png"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
            <link href="css/main.css" rel="stylesheet" type="text/css"/>
            <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
            <script>
                function abrirJanela(j) {
                    var janela = window.open(j, "", "width=350, height=500");
                }
            </script>

    </head>

    <body style="font-size: 8pt; font-family: sans-serif">

<?php require_once 'topo.php'; ?>
        <table width="980" height="20" border="0" align="center" valign="top" cellpadding="0" cellspacing="0" style="border-left: 0px solid #DDDDDD; border-right: 0px solid #DDDDDD; text-align: left;">
            <tr >
                <td width="195" height="20">
                    <form name="tool" action="tools.php" method="post">
                        <fieldset>
                            <legend>Ferramentas</legend>
                            <select name="choosetool" class="form-control" onChange="this.form.submit();" tabindex="1">
                                <option <?php
if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Escolha a Ferramenta..." or $toolselect == "Escolha a Ferramenta...") {
    print("selected=\"selected\"");
}
?>>Escolha a Ferramenta...</option>
                                <!--<option <?php
if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Enable/disable all users" or $toolselect == "Enable/disable all users") {
    print("selected=\"selected\"");
}
?>>Enable/disable all users</option>
                                <option <?php
if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Delete disabled users" or $toolselect == "Delete disabled users") {
    print("selected=\"selected\"");
}
?>>Delete disabled users</option>
                                <option <?php
                                if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Empty user database" or $toolselect == "Empty user database") {
                                    print("selected=\"selected\"");
                                }
                                ?>>Empty user database</option>-->
                                <?php
                                $selectedupd = "";
                                $selectedimp = "";
                                /* if ($_SESSION["fetchfromcsp"] == "1" and checkcspconn() == "1") {
                                  if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Update CSP users" or $toolselect == "Update CSP users") { $selectedupd = "selected"; }
                                  print("<option ".$selectedupd.">Update CSP users</option>");
                                  if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Import profiles from CSP" or $toolselect == "Import profiles from CSP") { $selectedimp = "selected"; }
                                  print("<option ".$selectedimp.">Import profiles from CSP</option>");

                                  } */
                                ?>
                                <option <?php
                                if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Importar Usuarios (CSP XML)" or $toolselect == "Importar Usuarios (CSP XML)" || isset($_GET['impuser'])) {
                                    print("selected=\"selected\"");
                                }
                                ?>>Importar Usuarios (CSP XML)</option>
                                <!--<option <?php
                                if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Importar Usuarios (CSV)" or $toolselect == "Importar Usuarios (CSV)") {
                                    print("selected=\"selected\"");
                                }
                                ?>>Importar Usuarios (CSV)</option>
                                -->
                                <?php if ($level == 0): ?>
                                    <option <?php
                                    if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Exportar Usuarios (CSP XML)" or $toolselect == "Exportar Usuarios (CSP XML)") {
                                        print("selected=\"selected\"");
                                    }
                                    ?>>Exportar Usuarios (CSP XML)</option>
                                    <option <?php
                                    if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Lixeira" or $toolselect == "Lixeira") {
                                        print("selected=\"selected\"");
                                    }
                                    ?>>Lixeira</option>
                                    <option <?php
                                    if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Pegar Reshare" or $toolselect == "Pegar Reshare") {
                                        print("selected=\"selected\"");
                                    }
                                    ?>>Pegar Reshare</option>
                                <?php endif; ?>

                                <!--<option <?php
                                if (isset($_POST["choosetool"]) and $_POST["choosetool"] == "Optimize database" or $toolselect == "Optimize database") {
                                    print("selected=\"selected\"");
                                }
                                ?>>Optimize database</option>-->
                            </select> 
                        </fieldset>
                    </form>
                </td>
                <td width="555" height="20">&nbsp;</td>
                <td width="15" height="20">&nbsp;</td>
            </tr>
        </table>
                                    <?php
                                    if ($tool <> "") {
                                        include $tool;
                                    }
                                    ?>
        <table width="980" height="20" border="0" align="center" valign="top" cellpadding="0" cellspacing="0" style="border-left: 0px solid #DDDDDD; border-right: 0px solid #DDDDDD; border-bottom: 0px solid #DDDDDD; text-align: left;">
            <tr >
                <td height="20" width="980">&nbsp;</td>
            </tr>
        </table>
<?php
require("includes/footer.php");
?>
    </body>
</html>
