<?php $tempo_inicio = microtime(true); ?>
<?php
/* ini_set('display_errors','On');
  ini_set('allow_url_fopen', '1');
  ini_set('allow_url_include', 'On'); */
ini_set('display_errors', true);
ini_set('safe_mode', false);
ini_set('allow_url_fopen', true);
ini_set('allow_url_include', true);
require("config.php");
$debug = 0;
require("includes/debug.php");
require("includes/functions.php");
require("includes/logincheck.php");
require("includes/settings.php");
require("classes/cache.php");
//-- ConexÃ£o com o BD

// Xml do CSP
$pf_pm = unserialize($_SESSION["_profiles_pm"]);
if (is_null($pf_pm)) {
    $pf_pm = array();
}

$id = $_SESSION["adminid"];
if (isset($_GET["id"]) and is_numeric($_GET["id"])) {
    $id = $_GET["id"];
}

if (isset($_GET["p"])) {

    $param = json_decode(base64_decode($_GET["p"]), true);
    if (key_exists("id", $param)) {
        $id = $param["id"];
    }
}
if (isset($_GET['p']) || isset($_GET['perfil']) || isset($_POST['bcLogin'])) {
    $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
    mysql_select_db($dbname);
    $sql = "SELECT * FROM cmum_csp_config WHERE ip_serv <> '' AND porta_serv <> ''";
    $result = mysql_query($sql);
    $csps = array();

    $cache = new Cache();
    $cache->setFolder('cache');
    $i = 0;

    while ($lineCSP = mysql_fetch_assoc($result)) {
        //$csps[] = "{$lineCSP["protocol_serv"]}://{$lineCSP["user_serv"]}:{$lineCSP["senha_serv"]}@{$lineCSP["ip_serv"]}:{$lineCSP["porta_serv"]}/xmlHandler?command=proxy-users";
        $csps["{$lineCSP['id']}"] = $cache->read("csp{$lineCSP['id']}");

        if (is_null($csp["{$lineCSP['desc_serv']}"]) || $csp["{$lineCSP['desc_serv']}"] == "") {
            $url = $lineCSP["protocol_serv"] . "://" . $lineCSP["ip_serv"] . ":" . $lineCSP["porta_serv"] . "/xmlHandler?command=proxy-users&hide-inactive=false";
            if (isset($_GET['perfil'])) {
                $url .= "&profile={$_GET['perfil']}";
            }
            //var_dump($url);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_USERPWD, $lineCSP["user_serv"] . ":" . $lineCSP["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, 30); // TIME OUT is 5 seconds
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//var_dump($httpCode);
            curl_close($ch);
            $csps["{$lineCSP['id']}"] = $response;
            $cache->save("csp{$lineCSP['id']}", $response, '90 seconds');
        }
        $i++;
    }
    $xmls = array();
    foreach ($csps as $_nome_csp => $csp) {
        if ($csp != "") {
            $xmls["{$_nome_csp}"] = simplexml_load_string($csp);
        }
    }
}

?>
<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 type="text/javascript" src="js/jquery.js"></script>-->
            <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    </head>
    <body>                      
        <?php require_once 'topo.php'; ?>
        <table width="980" border="0" align="center" valign="middle" cellpadding="2" cellspacing="1" style="font-size: 8pt;">
            <?php
            $conn = @mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
            mysql_select_db($dbname, $conn);
            $sSQL = "SELECT id,addedby,username,level,realname FROM cmum_admins WHERE id = $id";
            $result = mysql_query($sSQL);

            $revs = array();
            while ($linha = mysql_fetch_array($result)) {
                $revs[$linha['id']] = array('id' => $linha['id'], 'parent' => $linha['addedby'], 'title' => $linha['username']);
                $revID = $linha['addedby'];
                $level = $linha['level'];
                while ($level > 0) {
                    $sSQL = "SELECT id,addedby,username,level,realname FROM cmum_admins WHERE id=$revID";
                    $result = mysql_query($sSQL);
                    $linha = mysql_fetch_array($result);
                    $revs[$linha['id']] = array('id' => $linha['id'], 'parent' => $linha['addedby'], 'title' => $linha['username']);
                    $revID = $linha['addedby'];
                    $level = $linha['level'];
                }
            }

            //var_dump($revs);
            function breadcrumbs($id) {
                //global $revs;                               
                //$p = base64_encode("{\"id\":{$GLOBALS['revs'][$id]['id']}}");
                $json["id"] = "{$GLOBALS['revs'][$id]['id']}";
                $p = base64_encode(json_encode($json));
                if ($id >= $_SESSION['adminid']) {
                    if ($GLOBALS['revs'][$id]['parent'] > 0) {
                        return breadcrumbs($GLOBALS['revs'][$id]['parent']) . "<li><a href='?p=$p'>" . $GLOBALS['revs'][$id]['title'] . "</a></li>";
                        //return breadcrumbs($GLOBALS['revs'][$id]['parent']) . " -> " . $GLOBALS['revs'][$id]['title'];
                    } else {
                        return "<li><a href='?p=$p'>" . $GLOBALS['revs'][$id]['title'] . '</a></li>';
                        //return $GLOBALS['revs'][$id]['title'];
                    }
                }
            }
            ?>
            <tr>
                <td colspan="3" style="border: solid 0px red; height: 25px; font-size: 12pt">
                    <div>Você está em:</div><ul class="breadcrumb" style="height: 50px; line-height: 30px; padding-left:5px;"><?php echo breadcrumbs($id) ?></ul>
                </td>
            </tr>
            <tr>
                <td width="33%">
                    <fieldset>
                        <h5>Filtro Por Revendas</h5>
                        <form name="formFiltro" id="formFiltro" method="" action="?filtro=revenda">
                            <table>
                                <tr>
                                    <td >&nbsp;</td><td>
                                        <select name='p' class='form-control' id="p" onchange="this.form.submit()">
                                            <?php
                                            $json["id"] = "{$_SESSION['adminid']}";
                                            $p = base64_encode(json_encode($json));
                                            ?>
                                            <option value="<?php echo $p ?>"><?php echo $_SESSION['loginuser'] ?></option>
                                            <?php
                                            $arvore = arvoreRevendas2();
                                            $arvore_lista = arvoreRevendasLista();
                                            listaOptionsRenvendas($arvore[$_SESSION['adminid']], $arvore_lista, isset($_GET['p']) ? $_GET['p'] : "", $_SESSION['_hierarquia']);
                                            ?>
                                        </select>
                                    </td><td><input type="submit" value="Filtrar" name="" <?php if ($numReg == 0) { ?>disabled="true"<?php } ?> class="btn btn-default"/></td>
                                </tr>
                            </table>
                        </form>
                    </fieldset>
                </td>
                <td width="33%">
                    <fieldset>                        
                        <h5>Filtro Por Perfil</h5>
                        <form>
                            <?php if (isset($_GET['p'])): ?>
                                <input type="hidden" name="p" value="<?php echo $_GET['p']; ?>"/>
                            <?php endif; ?>
                            <table>
                                <tr>
                                    <td>Perfil:</td>
                                    <td>
                                        <?php
                                        $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
                                        $SQL = "SELECT * FROM cmum_profiles ORDER BY value ASC";
                                        $rs = $conn->query($SQL);
                                        $ls_pfs = array();
                                        while ($reg_pf = $rs->fetch_assoc()) {
                                            $ls_pfs[$reg_pf['value']] = $reg_pf;
                                        }
                                        ?>
                                        <select class="form-control" name="perfil" onchange="this.form.submit();">
                                            <?php if ($rs !== false): ?>
                                                <?php foreach ($ls_pfs as $ls_pf): ?>
                                                    <?php if ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && array_search($ls_pf['id'], $pf_pm) !== false)): ?>
                                                        <option value="<?php echo $ls_pf['value'] ?>" <?php
                                                        if (isset($_GET['perfil']) && $ls_pf['value'] == $_GET['perfil']) {
                                                            echo "selected";
                                                        }
                                                        ?>><?php echo $ls_pf['name'] ?></option>
                                                            <?php endif; ?>
                                                        <?php endforeach; ?>
                                                    <?php else: ?>
                                                <option>Não Ha Perfis</option>
                                            <?php endif; ?>
                                        </select>
                                    </td>
                                    <td><input type="submit" class="btn btn-default"/></td>
                                </tr>
                            </table>
                        </form>
                    </fieldset>
                </td>
                <td align="right" width="33%">
                    <fieldset>
                        <h5>Buscar por login ou nome:</h5>
                        <form method="post">
                            <table>
                                <tr>
                                    <td></td><td><input type="text" name="bcLogin" class="form-control" id="bcLogin" value="<?php echo isset($_POST["bcLogin"]) ? $_POST["bcLogin"] : ""; ?>"/></td>
                                    <td><input type="submit" name="" id="btBcLogin" value="Buscar" class="btn btn-default"/></td>
                                </tr>
                            </table>
                        </form>
                    </fieldset>
                </td>

            </tr>
        </table>
        <?php if (isset($_GET['p']) || isset($_GET['perfil']) || isset($_POST['bcLogin'])) { ?>
            <div style="width: 980px; border: solid 0px red; margin: auto; font-size: 8pt">
                <table width="980px" border="0" align="center" valign="top" cellpadding="2" cellspacing="1" class="table table-striped table-bordered table-condensed table-hover" style="font-size: 8pt">
                    <thead>
                        <tr>
                            <th >&nbsp;</th>
                            <th ><a href="?<?php echo url_query(array("orderby"), array("login")) ?>">Login</a></th>
                            <th ><a href="?<?php echo url_query(array("orderby"), array("nome")) ?>">Nome</a></th>
                            <th ><a href="?<?php echo url_query(array("orderby"), array("perfil")) ?>">Perfil</a></th>
                            <th >Canal</th>
                            <th >Tempo Conectado</th>
                            <th >Ip da Conexao</th>
                            <th ><a href="?<?php echo url_query(array("orderby"), array("revenda")) ?>">Revenda</a></th>
                            <th>&nbsp;</th>
                        </tr>
                    </thead>

                    <?php
                    $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
                    $strSql = "SELECT id,name,displayname,(SELECT username FROM cmum_admins WHERE cmum_admins.id = cmum_udb.addedby) AS admin,DATEDIFF(expiredate,added) as teste_ver FROM cmum_udb WHERE enabled = 'true' AND addedby = '{$id}'";
//Mostrando Todos Para os Admins
                    if (isset($_GET["id"])) {
                        $strSql = "SELECT id,name,displayname,(SELECT username FROM cmum_admins WHERE cmum_admins.id = cmum_udb.addedby) AS admin,DATEDIFF(expiredate,added) as teste_ver FROM cmum_udb WHERE enabled = 'true' AND addedby = '{$_GET["id"]}'";
                    }
                    if (($_SESSION["adminlevel"] == 0) AND !isset($_GET["id"]) AND !isset($_GET["p"])) {
                        $strSql = "SELECT id,name,displayname,(SELECT username FROM cmum_admins WHERE cmum_admins.id = cmum_udb.addedby) AS admin,DATEDIFF(expiredate,added) as teste_ver FROM cmum_udb WHERE enabled = 'true'";
                    }
                    if (isset($_POST["bcLogin"]) && $_POST["bcLogin"] != "") {
                        if ($_SESSION["adminlevel"] == "0") {
                            $strSql = "SELECT id,name,displayname,(SELECT username FROM cmum_admins WHERE cmum_admins.id = cmum_udb.addedby) AS admin,DATEDIFF(expiredate,added) as teste_ver FROM cmum_udb WHERE name LIKE '%{$_POST["bcLogin"]}%' OR displayname LIKE '%{$_POST["bcLogin"]}%'";
                        } else {
                            $strSql = "SELECT id,name,displayname,(SELECT username FROM cmum_admins WHERE cmum_admins.id = cmum_udb.addedby) AS admin,DATEDIFF(expiredate,added) as teste_ver FROM cmum_udb WHERE addedby = {$id} AND (name LIKE '%{$_POST["bcLogin"]}%' OR displayname LIKE '%{$_POST["bcLogin"]}%')";
                        }
                    }
                    //Ordenaçãoes
                    if (isset($_GET['orderby']) && $_GET['orderby'] != "perfil") {
                        if ($_GET['orderby'] == "revenda") {
                            $strSql .= " ORDER BY admin";
                        }
                        if ($_GET['orderby'] == "nome") {
                            $strSql .= " ORDER BY displayname";
                        }
                        if ($_GET['orderby'] == "login") {
                            $strSql .= " ORDER BY name";
                        }

                        $c = "ASC";
                        if (isset($_SESSION['order_by_online'])) {
                            $ordem = explode(".", $_SESSION['order_by_online']);
                            if ($ordem[0] == $_GET['orderby']) {
                                if ($ordem[1] == $c) {
                                    $c = "DESC";
                                }
                            }
                        }
                        $strSql .= " {$c}";

                        $_SESSION['order_by_online'] = "{$_GET['orderby']}.$c";
                    } else {
                        $strSql .= " ORDER BY id ASC";
                    }


                    $result_us = $conn->prepare($strSql);
                    $result_us->execute();
                    $result_us->bind_result($id, $name, $displayname, $admin, $teste_ver);
                    $logins = array();
                    while ($result_us->fetch()) {
                        $logins[$name] = array('id' => $id, 'login' => $name, 'nome' => $displayname, 'revendedor' => $admin);
                    }

                    $c = 0;
                    if (!isset($_GET['orderby']) || $_GET['orderby'] != "perfil") {
                        //echo "<pre>";
                        //var_dump($ls_pfs);
                        //echo "</pre>";
                        foreach ($logins as $login) {

                            //exit('Executou');
                            foreach ($xmls as $id_csp => $xml) {
                                $user = $xml->xpath("//proxy-users/user[@name='{$login['login']}']");

                                if (!empty($user)) {
                                    $num_session = count($user[0]->session);

                                    for ($i = 0; $i < $num_session; $i++) {

                                        //if ($user[0]->session[$i]->attributes()->active == "true" && ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && array_search($ls_pfs["{$user[0]->session[$i]->attributes()->profile}"]['id'], $pf_pm) !== false))) {
                                        if (($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && array_search($ls_pfs["{$user[0]->session[$i]->attributes()->profile}"]['id'], $pf_pm) !== false))) {
                                            $c++;

                                            $duration = $user[0]->session[$i]->attributes()->duration;
                                            $perfil = $user[0]->session[$i]->attributes()->profile;
                                            $ip = $user[0]->session[$i]->attributes()->host;
                                            $canal = "";
                                            if (@isset($user[0]->session[$i]->service->attributes()->name)) {
                                                @$canal = $user[0]->session[$i]->service->attributes()->name;
                                            }
                                            $status = '<span class="label label-warning" style="font-size: 7pt">Ocioso</span>';
                                            if ($user[0]->session[$i]->attributes()->active == "true") {
                                                $status = '<span class="label label-success" style="font-size: 7pt">Online</span>';
                                            }
                                            // <td ><img src='images/online.png' width='20px'/></td>
                                            //$cdata = $user[0]->session->service->attributes()->cdata;
                                            //$logoff = '<a href="kickuser.php?login=' . $login["login"] . '&id=' . $id_csp . '" title="Kick User" class="kick-user"><img src="images/logoff.png"/></a>';
                                            $logoff = '<a href="kickuser_desativar.php?login=' . $login["login"] . '&id=' . $id_csp . '&opc_kick=1" title="Kick User" class="kick-user">Desconectar</a>&nbsp;|&nbsp;<a href="kickuser_desativar.php?login=' . $login["login"] . '&id=' . $id_csp . '&opc_kick=2" title="Kick User" class="kick-user">Desativar</a>';
                                            echo "<tr>
                      <td>{$status}</td>
                      <td>{$login['login']}</td><td >{$login['nome']}</td><td >{$perfil}</td>                                              
                      <td>{$canal}</td><td >{$duration}</td>
                      <td>{$ip}</td>
                      <td>{$login['revendedor']}</td>
                      <td style='text-align:center'>{$logoff}</td>
                      </tr>
                      ";
                                        }//end if session active
                                    }//end for

                                    unset($user);
                                }
                            }// end foreach xml
                        }
                    }
                    if (isset($_GET['orderby']) && $_GET['orderby'] == 'perfil') {

                        $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
                        $SQL = "SELECT id,value FROM cmum_profiles ORDER BY value ";
                        $c_p = "ASC";
                        if (isset($_SESSION['order_by_online_pf'])) {
                            if ($_SESSION['order_by_online_pf'] == $c_p) {
                                $c_p = "DESC";
                            }
                        }
                        $SQL .= "{$c_p}";
                        $_SESSION['order_by_online_pf'] = $c_p;
                        $rs_pf = $conn->query($SQL);
                        $users = array();
                        if ($rs_pf !== false) {
                            while ($reg = $rs_pf->fetch_assoc()) {
                                if ($_SESSION['adminlevel'] == "0" || ($_SESSION['adminlevel'] != "0" && array_search($reg['id'], $pf_pm) !== false)) {
                                    foreach ($xmls as $id_csp => $xml) {
                                        $n = $xml->{'proxy-users'}->attributes()->count;
                                        for ($j = 0; $j < $n; $j++) {
                                            //if ((isset($xml->{'proxy-users'}->user[$j]) && isset($xml->{'proxy-users'}->user[$j]->session) && $xml->{'proxy-users'}->user[$j]->session->attributes()->active == "true") && $xml->{'proxy-users'}->user[$j]->session->attributes()->profile == $reg['value']) {
                                            if ((isset($xml->{'proxy-users'}->user[$j]) && isset($xml->{'proxy-users'}->user[$j]->session)) && $xml->{'proxy-users'}->user[$j]->session->attributes()->profile == $reg['value']) {
                                                $users[] = $xml->{'proxy-users'}->user[$j];
                                            }
                                        }
                                    }// end for
                                }//end if
                            }//end while
                        }

                        $c = 0;
                        foreach ($users as $user) {

                            if (isset($logins["{$user->attributes()->name}"])) {
                                $login = $logins["{$user->attributes()->name}"];
                                $status = '<span class="label label-warning" style="font-size: 7pt">Ocioso</span>';
                                if ($user->session[0]->attributes()->active == "true") {
                                    $status = '<span class="label label-success" style="font-size: 7pt">Online</span>';
                                }
                                $logoff = '<a href="kickuser.php?login=' . $login["login"] . '&id=' . $id_csp . '" title="Kick User" class="kick-user"><img src="images/logoff.png"/></a>';
                                echo "<tr>
                      <td>{$status}</td>
                      <td>{$login["login"]}</td>
                      <td>{$login["nome"]}</td>
                      <td>{$user->session->attributes()->profile}</td>                                              
                      <td>{$user->session->service->attributes()->name}</td>
                      <td>{$user->session->attributes()->duration}</td>
                      <td>{$user->session->attributes()->host}</td>
                      <td>{$login["revendedor"]}</td>
                      <td>{$logoff}</td>
                      </tr>
                      ";
                                $c++;
                            }
                        }
                    }
                    ?>
                    <?php if ($c == 0): ?>
                        <tr  style="text-align: center; font-size: 14pt;">
                            <td colspan="9">Login offline ou desativado.</td>
                        </tr>
                    <?php endif; ?>
                    <tr style="text-align: right">
                        <td colspan="9">Total:&nbsp;<?php echo $c; ?></td>
                    </tr>
                </table>
            </div>
        <?php }else { ?>
            <div style="width: 980px; border: solid 0px red; margin: auto">
                Escolha a opção de listagem.
            </div>
        <?php } ?>
        <?php
        require("includes/footer.php");
        ?>
        <?php
        $tempo_final = microtime(true);
        $tempo_total = $tempo_final - $tempo_inicio;
        ?>
        <script>
            $('.kick-user').on('click', this, function(e) {
                e.preventDefault();
                var url = $(this).attr('href');
                var w = 400;
                var h = 200;
                var left = (screen.width / 2) - (w / 2);
                var top = (screen.height / 2) - (h / 2);
                var janela = window.open(url, "", "width=" + w + ", height=" + h + ", left=" + left + ", top=" + top);
                var id_int = setInterval(function() {
                    if (janela.closed == true) {
                        window.self.location.reload();
                        clearInterval(id_int);
                    }
                }, 1000);
            });
        </script>       

        <div style="width: 980px; border: solid 0px red; margin: auto; font-size: 8pt">
            <p>Tempo de execução: <?php echo number_format($tempo_total, 4) ?> segundos</p>
        </div>

    </body>
</html>
