<?php
require_once(dirname(__FILE__) . '/../dashlet-helper.inc.php');

dashlets_data_check();

route_request();

function route_request() {

    $load_perfgraph_url = grab_request_var('load');

    if ($load_perfgraph_url)
        load_perfgraph_url();

    perfgraph_dashlet();
}

function perfgraph_dashlet() {

    $id = 'perfgraph_' . random_string(6);
    $id_container = "{$id}_container";

    $server = urlencode(grab_request_var('server'));
    $host = grab_request_var('host', 'localhost');
    $service = urlencode(grab_request_var('service', '_HOST_'));
    $width = intval(grab_request_var('width', 400));
    $height = intval(grab_request_var('height', 200));

    $host = urlencode(remove_params_mask($host, $server));

    $output = "

        <div class=\"perfgraph\">
            <div class=\"fusioncore_perfgraphs\" id=\"{$id}\"></div>
            <div class=\"graphcontainer\" id=\"{$id_container}\"></div>
        </div>
    
        <script type=\"text/javascript\">
            $(function() {

                get_{$id}_content();
                var hc = $('#{$id_container}').find('.highcharts-container');
                                
                $('#{$id}').closest('.ui-resizable').on('resizestop', function() {
                    get_{$id}_content();
                });

                function get_{$id}_content() {

                    var dash = $('#{$id}').parents('.dashlet');

                    var height = dash.height();
                    if (dash.find('.title').is(':visible')) {
                        height -= dash.find('.title').height(); 
                    }

                    var ptop = parseInt(dash.find('.content-overflow').css('padding-top').replace('px', ''));
                    var pbottom = parseInt(dash.find('.content-overflow').css('padding-bottom').replace('px', ''));
                    var padding = (ptop + pbottom);
                    height -= padding;

                    var url = '/nagiosfusion/includes/dashlets/perfgraph/perfgraph.php?load=1';
                    url += '&server=' + " . json_encode($server) . ";
                    url += '&host=' + " . json_encode($host) . ";
                    url += '&service=' + " . json_encode($service) . ";
                    url += '&width=' + (dash.width()-padding);
                    url += '&height=' + height;
                    url += '&div=' + " . json_encode($id_container) . ";

                    $('#{$id}').load(url);

                    // Stop clicking in graph from moving dashlet
                    $('#{$id}').closest('.ui-draggable').draggable('option', 'cancel', '#{$id_container}');
                }
            });
        </script>";

    echo $output;
}

function load_perfgraph_url() {

    // TODO: this function uses the server's default username/password to auth. should not do that

    $server = urlencode(grab_request_var('server'));
    $host = urlencode(grab_request_var('host', 'localhost'));
    $service = urlencode(grab_request_var('service', '_HOST_'));
    $width = intval(grab_request_var('width', 400));
    $height = intval(grab_request_var('height', 200));
    $div = urlencode(grab_request_var('div'));

    $type = 'perfdata';

    if (empty($host))
        exit();

    $server = get_server($server);
    if ($server === false)
        exit();

    $url = get_server_base_url($server);
    $url .= 'includes/components/graphexplorer/visApi.php';

    // Try the server's username and password and if it doesn't work, let's look and see
    // if the user has auto-login credentials for this server
    if (!empty($server['username'])) {
        $username = $server['username'];
        $password = _decrypt($server['password']);
    } else {
        $al = get_auto_logins(0, false, $server['server_id']);
        if (!empty($al)) {
            $al = $al[0];
            $username = $al['username'];
            $password = _decrypt($al['password']);
        }
    }

    // Check server version if it needs to do XI 5.5 auth ticket login
    if (isset($server['version']) && version_compare($server['version'], '5.5.0') >= 0) {

        // Generate a login auth token
        $auth_token_url = get_server_base_url($server);
        $auth_token_url .= "api/v1/authenticate";
        $post_data = array("username" => $username,
                           "password" => $password);

        // Load auth token generation data
        $auth_data = load_url($auth_token_url, array('method' => 'post', 'post_data' => $post_data));
        $obj = json_decode($auth_data);
        if ($obj->auth_token) {
            $url .= '?token='.$obj->auth_token;
        }

    } else {
        $url .= "?username={$username}&password=".md5($password);
    }

    // Clear password from memory
    unset($password);

    $url .= "&div={$div}";
    $url .= "&type={$type}";
    $url .= "&host={$host}";

    if (!empty($service))
        $url .= "&service={$service}";

    if (!empty($width))
        $url .= "&width={$width}";

    if (!empty($height))
        $url .= "&height={$height}";

    if (!empty($start))
        $url .= "&start={$start}";

    $data = load_url($url);

    // Failure to authenticate
    if (strpos($data, "<script type='text/javascript'>") === false) {
        $data = '<div style="text-align: center;">
<h5>'._('Could not authenticate.').'</h5>
<p>'._("This dashlet uses your user account XI server authentication settings.").'<br>'._("You must have valid credentials for XI in your account even if auto login is disabled.").'</p>
<p><a href="'.get_base_url().'/account/" target="_top">'._('Update your credentials').'</a></p>
</div>';
    }

    // we need to set exporting: to disabled so the buttons don't show up here
    $data = preg_replace("/exporting:\s*{/", "exporting: {\nenabled: false,", $data);

    echo $data;
    exit();
}
